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

8👍

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

@api_view(['POST'])
def endpoint(request):
    data = request.data.get('data')

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

    return Response({})
👤naglas

15👍

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()
        asyncio.set_event_loop(loop)
        async_result = loop.run_until_complete(remove_tags(response, tag))
        loop.close()

    # 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)

   @database_sync_to_async
   def tag_query(response, tag_id):
        Mymodel.objects.get(all_tag_id=tag_id).delete()

This way i called async function in synchronous function.

Reference for database sync to async decorator

0👍

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