[Solved]-How to call asynchronous function in Django?


Found a way to do it.

Create another file bar.py in the same directory as urls.py.

# bar.py

def foo(data):
    // process data
# urls.py

from multiprocessing import Process
from .bar import foo

def endpoint(request):
    data = request.data.get('data')

    p = Process(target=foo, args=(data,))

    return Response({})


Django is an synchronous language but it supports Async behavior.
Sharing the code snippet which may help.

    import asyncio
    from channels.db import database_sync_to_async

    def get_details(tag):
        response = another_sync_function()

        # Creating another thread to execute function
        loop = asyncio.new_event_loop()
        async_result = loop.run_until_complete(remove_tags(response, tag))

    # Async function 
    async def remove_tags(response, tag_id):
        // do something here

        # calling another function only for executing database queries
        await tag_query(response, tag_id)

   def tag_query(response, tag_id):

This way i called async function in synchronous function.

Reference for database sync to async decorator


You can’t await foo in this context. Seeing that Django is mainly a synchronous library, it doesn’t interact well with asynchronous code. The best advice I can give it to try avoid using an asynchronous function here, or perhaps use another method of concurrency (ie threading or multiprocessing).

Note: there is a great answer given about Django’s synchronous nature that can be found here: Django is synchronous or asynchronous?.

Leave a comment