小编Kvo*_*the的帖子

当我在主循环中处理请求时,如何从 django 视图运行异步函数以在后台运行?

正如我在标题中所说,我希望在处理来自前端的请求时在后台运行一个任务来处理大型数据库查询。我什至可以使用 async/asyncio 来做到这一点吗?有人告诉我这是可能的...

出于上下文的目的,我想做如下的事情。另请注意,我实际上并不需要该函数告诉我何时完成(尽管我肯定想知道是否可能),因为我只是检查 .json 文件是否最终写入。


def post_data_view(request):
    if request.method == 'POST':
        ...
        do_long_query_in_the_background(some_data)
        return HttpResponse('Received. Ask me in a while if I finished.')

def is_it_done_view(request):
    if request.method == 'GET':
        data = find_json()
        if data:
            return JsonResponse(data)
        else:
            return HttpResponse('Not yet dude...')

async def do_long_query_in_the_background(data):
    # do some long processing...
    # dump the result to a result.json
    return
Run Code Online (Sandbox Code Playgroud)

有人告诉我这可以通过异步实现,但我真的很难理解。对于上下文,我试图简化这一点,即使如此,我发现我不太明白发生了什么:


async def f():
    while True:
        print(0)
        await asyncio.sleep(2)

asyncio.create_task(f())
Run Code Online (Sandbox Code Playgroud)

即使我尝试的这段代码也失败了sys:1: RuntimeWarning: coroutine 'f' was never awaited,但它确实可以在控制台上运行,我不明白为什么会这样。

我还想知道这对于线程来说是否可能并且安全?

我对此感到非常沮丧,因为其他线程中建议的一般解决方案似乎只是使用芹菜,但对于一个不那么复杂的问题来说,它确实感觉有点矫枉过正。

python django multithreading asynchronous

5
推荐指数
1
解决办法
4652
查看次数

标签 统计

asynchronous ×1

django ×1

multithreading ×1

python ×1