About Function Calls With Timeouts

Use the func-timeout module to raise a timeout error for a function when it takes longer than expected to execute:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
from func_timeout import func_set_timeout, FunctionTimedOut
from django.shortcuts import render
from django.conf import settings

# raise timeout error in 1.5 seconds if unfinished
@func_set_timeout(1.5)
def _get_realtime_pricing_information(request):
    # fetch the real-time prices here...
    return prices

def pricing(request):
    try:
        prices = _get_realtime_pricing_information(request)
        real_time = True
    except FunctionTimedOut:
        prices = settings.PRICES
        real_time = False
    return render(request, "pricing/pricing.html", {
        "prices": prices,
        "real_time": real_time,
    })

Tips and Tricks Programming Development Django 4.2 Django 3.2 Django 2.2 Python 3