Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call asynchronous function in Django?

The following doesn't execute foo and gives RuntimeWarning: coroutine 'foo' was never awaited

# urls.py

async def foo(data):
    # process data ...

@api_view(['POST'])
def endpoint(request):
    data = request.data.get('data')
    
    # How to call foo here?
    foo(data)

    return Response({})
like image 793
naglas Avatar asked Mar 08 '26 07:03

naglas


1 Answers

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

like image 124
Karamdeep Singh Avatar answered Mar 09 '26 20:03

Karamdeep Singh