在Flask2.0中介绍了异步/等待的用法。(https://flask.palletsprojects.com/en/2.0.x/async-await/)
我使用的是async- RestX,所以在RestX请求处理程序中可以使用RestX/await吗?
类似于:
@api.route('/try-async')
class MyResource(Resource):
@api.expect(some_schema)
async def get(self):
result = await async_function()
return result不起作用,当我试图到达这个端点时,我得到了错误:
TypeError: Object of type coroutine is not JSON serializable
有这方面的信息吗?
包版本:
flask==2.0.1
flask-restx==0.4.0我还安装了flask[async],正如文档所显示的那样。
发布于 2021-12-11 14:12:10
我通过使用内部重定向来解决这个问题
@api.route('/try-async')
class MyResource(Resource):
@api.expect(some_schema)
def get(self):
return redirect(url_for('.hidden_async'), code=307)
@api.route('/hidden-async', methods=['GET'])
async def hidden_async():
result = await async_function()
return result使用code=307重定向将确保任何方法和主体在重定向(链接)后保持不变。因此,将数据传递给异步函数也是可能的。
@api.route('/try-async')
class MyResource(Resource):
@api.expect(some_schema)
def post(self):
return redirect(url_for('.hidden_async'), code=307)
@api.route('/hidden-async', methods=['POST'])
async def hidden_async():
data = request.get_json()
tasks = [async_function(d) for d in data]
result = await asyncio.gather(tasks)
return resulthttps://stackoverflow.com/questions/68115481
复制相似问题