Django中如何调用异步函数?

nag*_*las 12 python django django-rest-framework python-3.6 django-3.0

以下不执行foo并给出 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({})
Run Code Online (Sandbox Code Playgroud)

小智 15

Django 是一种同步语言,但它支持异步行为。分享可能有帮助的代码片段。

    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()
Run Code Online (Sandbox Code Playgroud)

这样我就在同步函数中调用了异步函数。

数据库同步到异步装饰器的参考


nag*_*las 8

找到了一种方法来做到这一点。

bar.py在与 相同的目录中创建另一个文件urls.py

# bar.py

def foo(data):
    // process data
Run Code Online (Sandbox Code Playgroud)
# 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({})
Run Code Online (Sandbox Code Playgroud)