About Turning Any Function into Async Function

ASGI configurations support both types of views: synchronous (normal) and asynchronous (similar to threads, allowing long execution time).

To convert any function to asynchronous, use this technique:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from asgiref.sync import sync_to_async
from django.shortcuts import render
from .helpers import helper_function

async timely_view(request, param1, param2):
    result = None
    if request.method == "POST":
        result = await sync_to_async(
            helper_function, thread_sensitive=True
        )(param1=param1, param2=param2)
    return render(request, "myapp/timely_view.html", {"result": result})

Tips and Tricks Programming Django 5.x Django 4.2 Django 3.2 ASGI