在 Python 3.6.10 上出现错误 运行 Async Flask 2.0.0

Error Running Async Flask 2.0.0 on Python 3.6.10

我正尝试在 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.async_to_sync() 在 Flask 2.0 中需要 ContextVar。如果您不使用 Greenlet,Flask 中 async 支持的最低 Python 要求是 3.7(当引入 contextvars 时)。如果您使用的是 Greenlet,它还取决于 Greenlet 版本。