12

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({})
Anupam
  • 14,950
  • 19
  • 67
  • 94
naglas
  • 462
  • 1
  • 6
  • 16

3 Answers3

11

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

Karamdeep Singh
  • 254
  • 2
  • 5
7

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
  • 462
  • 1
  • 6
  • 16
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?.

hipeople321
  • 122
  • 1
  • 9