作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
给定 main.py
:
import asyncio
async def new_app():
# Await some things.
async def app(scope, receive, send):
...
return app
app = asyncio.run(new_app())
其次是:
uvicorn main.app
给出:
RuntimeError: asyncio.run() cannot be called from a running event loop
这是因为
uvicorn
在导入我的应用程序之前已经启动了一个事件循环。如何在
uvicorn
下异步构建应用程序?
最佳答案
Yoe 不需要使用 asyncio.run
.你的类或函数应该只实现 ASGI
界面。像这样,最简单的可行:
# main.py
def app(scope):
async def asgi(receive, send):
await send(
{
"type": "http.response.start",
"status": 200,
"headers": [[b"content-type", b"text/plain"]],
}
)
await send({"type": "http.response.body", "body": b"Hello, world!"})
return asgi
你可以在 uvicorn 下启动它:
uvicorn main:app
.
main:app
将由
uvicorn
解析导入和
executed在其事件循环中以这种方式:
app = self.config.loaded_app
scope: LifespanScope = {
"type": "lifespan",
"asgi": {"version": self.config.asgi_version, "spec_version": "2.0"},
}
await app(scope, self.receive, self.send)
如果你想制作一个可执行模块,你可以这样做:
import uvicorn
# app definition
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
关于python - 如何让 uvicorn 运行异步构建的应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65837966/
我是一名优秀的程序员,十分优秀!