这是重现该问题的最小蓝图:
@my_blueprint.route('/my_route', methods=['POST'])
async def my_route() -> Response:
await asyncio.sleep(5)
return format_json_response(
{
'success': True,
},
)
当一个接一个地拨打电话时,通话之间有一些延迟,它工作得非常好。但是,如果进行并发调用或只是进行串行调用太快,则会产生以下错误:
Traceback (most recent call last):
File "[myvenv]lib/python3.8/site-packages/gunicorn/workers/base_async.py", line 55, in handle
self.handle_request(listener_name, req, client, addr)
File "[myvenv]lib/python3.8/site-packages/gunicorn/workers/ggevent.py", line 127, in handle_request
super().handle_request(listener_name, req, sock, addr)
File "[myvenv]lib/python3.8/site-packages/gunicorn/workers/base_async.py", line 108, in handle_request
respiter = self.wsgi(environ, resp.start_response)
File "[myvenv]lib/python3.8/site-packages/flask/app.py", line 2213, in __call__
return self.wsgi_app(environ, start_response)
File "[myvenv]lib/python3.8/site-packages/flask/app.py", line 2193, in wsgi_app
response = self.handle_exception(e)
File "[myvenv]lib/python3.8/site-packages/flask_cors/extension.py", line 165, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "[myvenv]lib/python3.8/site-packages/flask/app.py", line 2190, in wsgi_app
response = self.full_dispatch_request()
File "[myvenv]lib/python3.8/site-packages/flask/app.py", line 1486, in full_dispatch_request
rv = self.handle_user_exception(e)
File "[myvenv]lib/python3.8/site-packages/flask_cors/extension.py", line 165, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "[myvenv]lib/python3.8/site-packages/flask/app.py", line 1484, in full_dispatch_request
rv = self.dispatch_request()
File "[myvenv]lib/python3.8/site-packages/flask_protobuf/api.py", line 91, in dispatch_request
rv = original_dispatch_request(self)
File "[myvenv]lib/python3.8/site-packages/flask/app.py", line 1469, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
File "[myvenv]lib/python3.8/site-packages/asgiref/sync.py", line 209, in __call__
raise RuntimeError(
RuntimeError: You cannot use AsyncToSync in the same thread as an async event loop - just await the async function directly.
以下是一些额外的环境信息:
gevent==23.7.0
flask[async]==2.3.3
gunicorn[gevent]==20.1.0
gunicorn wsgi:app --workers=2 -k gevent
实际端点执行一些复杂的异步/等待并行处理,但其行为与这个最小示例完全相同。
我希望端点能够正常工作而不会出现任何错误消息。
我认为这个问题来自
async def my_route
。它将使用 AsyncToSync 类,因此它无法处理到 gevent 运行的主线程。
所以,将模式gunicorn更改为
gthread
来修复它。
gunicorn wsgi:app --workers=2 -k gthread