pythondjangodjango-rest-frameworkpython-3.6django-3.0

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({})

Solution

  • 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({})