Python Flask-Asyncio异步问题

我有一个Web端点供用户上传文件。 端点收到请求后,我想运行一个后台作业来处理文件。

由于作业需要花费一些时间,因此我希望在后台中运行作业时,将job_id返回给用户以跟踪请求的状态。

我想知道在这种情况下asyncio是否会有所帮助。

import asyncio

@asyncio.coroutine
def process_file(job_id,file_obj):
     <process the file and dump results in db>

@app.route('/file-upload',methods=['POST'])
def upload_file():
    job_id = uuid()
    process_file(job_id,requests.files['file']) . # I want this call to be asyc without any await
    return jsonify('message' : 'Request received. Track the status using: " + `job_id`)

使用上面的代码,永远不会调用process_file方法。无法理解原因。

我不确定这是否是正确的方法,如果我缺少某些东西,请提供帮助。

wuzesc 回答:Python Flask-Asyncio异步问题

Flask还不支持异步调用。

要在后台创建和执行繁重的任务,可以使用https://flask.palletsprojects.com/en/1.1.x/patterns/celery/ Celery库。

您可以将其用作参考: Making an asynchronous task in Flask

官方文档: http://docs.celeryproject.org/en/latest/getting-started/first-steps-with-celery.html#installing-celery

即使您在函数周围编写了@asyncio.coroutine(),也从未awaited告诉函数返回结果。

Asyncio不适用于此类任务,因为它们阻止了I / O。通常用于进行函数调用并快速返回结果。

,

@py_dude mentioned一样,Flask不支持异步调用。如果您要寻找一个功能类似于Flask但异步的库,建议您检出Sanic。这是一些示例代码:

from sanic import Sanic
from sanic.response import json

app = Sanic()

@app.route("/")
async def test(request):
    return json({"hello": "world"})

if __name__ == "__main__":
    app.run(host="0.0.0.0",port=8000)

异步更新数据库应该不是问题。请参考here来找到异步支持的数据库驱动程序。要处理文件,请签出aiohttp。如果异步进行,则可以在单个线程上极快地运行服务器,而无需任何启动。

本文链接:https://www.f2er.com/3050066.html

大家都在问