网页 综合 更新时间 2026-11-14 16:46:32

Lifespan - Uvicorn

自动蜘蛛 uvicorn.dev 正文约 1608 字
Since Uvicorn is an ASGI server, it supports the ASGI lifespan protocol. This allows you to run startup and shutdown events for your application.
The lifespan protocol is useful for initializing resources that need to be available throughout the lifetime of the application, such as database connections, caches, or other services.
Keep in mind that the lifespan is executed only once per application instance. If you have multiple workers, each worker will execute the lifespan independently.
The lifespan protocol runs as a sibling task alongside your main application, allowing both to execute concurrently.
Let's see how Uvicorn handles the lifespan and main application tasks:
Having the lifespan task run as a sibling task is a deliberate design choice. It could have been implemented as a parent task that spawns the application task. This decision has the implication that if you create a ContextVar in the lifespan task, it will not be available in the application task.
Let's see an example of a minimal (but complete) ASGI application that implements the lifespan protocol:
You can run the above application with uvicorn main:app. Then you'll see the print statements when the application starts. You can also try to send some HTTP requests to it, and it will respond with "Hello, World!". And if you stop the server (CTRL + C), it will print "Application is shutting down...".
If you want to disable the lifespan protocol, you can do so by setting the lifespan option to off when running Uvicorn:
By default, Uvicorn will automatically enable the lifespan protocol if the application supports it.
访问原文 返回搜索 https://uvicorn.dev/concepts/asgi/../lifespan/
本页为82搜索生成的网页快照,内容来自站内索引;演示数据的原文链接仅作示例。