[英]Python, run a background task while not blocking the api thread, using Quart
我正在尝试创建一个适用于输入数据并根据提供的输入运行不同脚本的 python api。 我早些时候和 8 名工人一起使用烧瓶 + gunicorn。 我了解了 asyncio 库,并使用以下 [指南][1] 从烧瓶切换到夸脱,从 gunicorn 切换到 hypercorn。
我的功能看起来像:
@app.route("/pyscript", methods=["POST"])
#@cross_origin(supports_credentials=True)
async def pyscript():
#check for pre defined token
try:
if(token == consts.authToken):
print("TOKEN VALIDATED")
else:
return jsonify({'message': 'token is invalid'})
except:
return jsonify({'message': 'token is invalid'})
json_all_data = await request.get_json(force=True)
print(json_all_data)
json_data = json_all_data['data']
json_data = json.dumps(json_data)
if json_data is None:
return "Bad request, invalid JSON Format inserted", 401
json_LOC = (json_all_data['LOC'])
json_LOI = (json_all_data['LOB'])
try:
if(json_LOC in keys and json_LOI in keys[json_LOC]):
chosen_operation_function = carriers.get(json_LOC).get(json_LOI)
return_UUID = uuid.uuid4()
app.add_background_task(run_task(json_data, json_LOC, json_LOI, chosen_operation_function, return_UUID))
out_int = {
"job_id" : return_UUID,
"status" : "Running",
"input" : json.loads(json_data)
}
return out_int, 202
else:
return jsonify({'message': 'LOC/LOB is invalid'})
except Exception as e:
print(e)
return e
run_task 是其他文件中的一个函数,它是一个异步定义的函数。
预期输出:我想在后台处理 run_task,同时返回 202 响应和与之关联的 json 数据。
发生了什么:邮递员请求中返回了该值,但服务器显示以下错误:
Traceback (most recent call last):
File "/home/user/.local/lib/python3.8/site-packages/quart/app.py", line 1396, in _wrapper
await copy_current_app_context(func)(*args, **kwargs)
File "/home/user/.local/lib/python3.8/site-packages/quart/ctx.py", line 333, in wrapper
return await app_context.app.ensure_async(func)(*args, **kwargs)
File "/home/user/.local/lib/python3.8/site-packages/quart/utils.py", line 55, in _wrapper
None, copy_context().run, partial(func, *args, **kwargs)
TypeError: the first argument must be callable
我无法识别错误,我们将不胜感激。
谢谢 [1]: https ://pgjones.gitlab.io/quart/how_to_guides/flask_migration.html
我认为您调用 add_background_task 不正确,而不是,
app.add_background_task(run_task(json_data, json_LOC, json_LOI, chosen_operation_function, return_UUID))
它应该被称为,
app.add_background_task(run_task, json_data, json_LOC, json_LOI, chosen_operation_function, return_UUID)
请注意,在您的代码的第二个示例中未调用run_task
,而是将它和调用它的参数传递给add_background_task
函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.