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:

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