yuv*_*yun 8 python python-asyncio python-aiofiles fastapi
我有一个在 fastapi 和 aiofiles 上运行的异步代码,我正在尝试从 .json 文件加载和保存我的信息,但是每次我关闭程序时,它只保存字典的键并显示“ASGI 'lifespan'协议似乎不受支持”按摩
这是我的开启/关闭部分:
@app.on_event("startup")
async def startup_event():
global beers
try:
async with aiofiles.open("data.json", mode='r+', json=True) as file:
beers = await file.read()
except:
beers = {}
@app.on_event("shutdown")
async def on_exit_app():
async with aiofiles.open("data.json", "w+") as outfile:
await outfile.write(beers)
Run Code Online (Sandbox Code Playgroud)
任何想法问题出在哪里?
M. *_*olf 15
这 99% 意味着on_event("shutdown")
函数中的某些内容引发了服务器(FastAPI/Starlette)未捕获的错误,并且应用程序崩溃,而不是正确结束。这导致 uvicorn 相信服务器不支持 ASGI 协议的 livespan 部分。
如果您uvicorn
使用附加选项运行,--lifespan on
则会显示错误,您可以对其进行调试。
请参阅Starlette 错误报告。
我在 Django 应用程序中遇到了同样的错误。当服务器启动时,它似乎运行良好,但[INFO] ASGI 'lifespan' protocol appears unsupported
会出现该消息。
(authentication-py3.11) ml@192 authentication % python -m gunicorn "authentication.asgi:application"
[2023-04-12 10:07:28 -0300] [2900] [INFO] Starting gunicorn 20.1.0
[2023-04-12 10:07:28 -0300] [2900] [INFO] Listening at: http://0.0.0.0:8000 (2900)
[2023-04-12 10:07:28 -0300] [2900] [INFO] Using worker: uvicorn.workers.UvicornWorker
[2023-04-12 10:07:28 -0300] [2902] [INFO] Booting worker with pid: 2902
[2023-04-12 13:07:29 +0000] [2902] [INFO] Started server process [2902]
[2023-04-12 13:07:29 +0000] [2902] [INFO] Waiting for application startup.
[2023-04-12 13:07:29 +0000] [2902] [INFO] ASGI 'lifespan' protocol appears unsupported.
[2023-04-12 13:07:29 +0000] [2902] [INFO] Application startup complete.
Run Code Online (Sandbox Code Playgroud)
按照本期的解决方案,我创建了一个自定义 uvicorn 工作线程来禁用生命周期协议。
工人.py
from typing import Any, Dict
from uvicorn.workers import UvicornWorker as BaseUvicornWorker
class UvicornWorker(BaseUvicornWorker):
CONFIG_KWARGS: Dict[str, Any] = {"loop": "auto", "http": "auto", "lifespan": "off"}
Run Code Online (Sandbox Code Playgroud)
Gunicorn.conf.py
from myapp import settings
port = int(settings.APPLICATION_PORT)
bind = f"0.0.0.0:{port}"
workers = int(settings.GUNICORN_WORKERS)
worker_class = "myapp.workers.UvicornWorker"
accesslog = "-"
Run Code Online (Sandbox Code Playgroud)
这只是一个断言,你可以忽略这一点,据我所知,你正在使用 Uvicorn 作为 HTTP 服务器,因为 FastAPI 是构建在 ASGI 框架之上的,而 Uvicorn 是一个 ASGI HTTP 服务器,所以它上面有一些协议。ASGI协议支持http、websocket。
Uvicorn 将寿命的值设置为auto
,并且断言就来自那里。
if self.config.lifespan == "auto":
msg = "ASGI 'lifespan' protocol appears unsupported."
Run Code Online (Sandbox Code Playgroud)
但你可以用--lifespan on
它来解决这个问题。
归档时间: |
|
查看次数: |
3870 次 |
最近记录: |