我尝试在 python 3.6.10 上以异步方式运行 Flask,但不断收到:
RuntimeError: Async cannot be used with this combination of Python and Greenlet versions.
我编写了以下简单脚本来测试 Flask 异步功能:
from flask import Flask
import asyncio
app = Flask(__name__)
async def load_user_from_database():
"""Mimics a long-running operation to load a user from an external database."""
app.logger.info('Loading user from database...')
await asyncio.sleep(1)
@app.before_request
async def add_drink():
await load_user_from_database()
升级到 python 3.9.2 似乎可以解决该问题,但对于我的应用程序,我被迫使用 python 3.6.10,因此欢迎任何建议让它在后一个 python 版本上工作。
P.S 以下是简单应用程序的requirements.txt:
aiohttp==3.7.4.post0
asgiref==3.3.4
async-timeout==3.0.1
attrs==20.3.0
certifi==2020.12.5
chardet==4.0.0
click==8.0.0rc1
Flask==2.0.0
idna==2.10
iniconfig==1.1.1
itsdangerous==2.0.0
Jinja2==3.0.0
MarkupSafe==2.0.0rc2
multidict==5.1.0
packaging==20.9
pluggy==0.13.1
py==1.10.0
pyparsing==2.4.7
pytest==6.2.4
pytest-asyncio==0.15.1
requests==2.25.1
toml==0.10.2
typing-extensions==3.10.0.0
urllib3==1.26.4
Werkzeug==2.0.0
yarl==1.6.3
最佳答案
Flask 2.0 中的
Flask.async_to_sync()
需要 ContextVar
。如果您不使用 Greenlet,Flask 中对 async
支持的最低 Python 要求是 3.7(当引入 contextvars
时)。如果您使用 Greenlet,它还取决于 Greenlet 版本。
关于python - 在 Python 3.6.10 上运行异步 Flask 2.0.0 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67698544/