accessing app state on startup/shutdown handlers
See original GitHub issuei have a starlette app that uses @app.[route|on_event]
decorators for routing but would like to switch to the recommended Starlette(routes=..., on_startup=...)
.
one thing i’m confusing about: how can i access app state via startup/shutdown handlers? currently i have the following:
from my_middleware import GetDatabaseConnectionMiddleware
app = Starlette()
# some middleware that gets a connection from app.state.connection_pool
# and adds it to the request's scope
app.add_middleware(GetDatabaseConnectionMiddleware)
@app.on_event("startup")
async def startup():
app.state.connection_pool = await asyncpg.create_pool(
dsn=DATABASE_URL, min_size=2, max_size=2
)
i think this is a bit messy but seemed like the most obvious way to set app state in the startup handler. i’m not sure how i’d do the same when app is created after the functions are defined, though. any ideas on how to do this?
Issue Analytics
- State:
- Created 4 years ago
- Reactions:2
- Comments:5 (2 by maintainers)
Top Results From Across the Web
Events: startup - shutdown - FastAPI
Here, the shutdown event handler function will write a text line "Application shutdown" to a file log.txt . Info. In the open() function,...
Read more >How to: Log Messages When the Application Starts or Shuts ...
On the Declarations menu, choose Shutdown. The application raises the Shutdown event after the main application runs, but before it shuts down.
Read more >Managing your app's life cycle - Apple Developer
The current state of your app determines what it can and can't do at any time. For example, a foreground app has the...
Read more >tiangolo/fastapi - Gitter
Event() def shutdown(self): self.cancellation_event.set() async def ... service_task = asyncio.create_task(service.startup()) app.state.service = service ...
Read more >Understanding Server Life Cycle - Oracle Help Center
Perform day-to-day operations tasks, including startup and shutdown procedures; Diagnose problems with application services; Plan corrective actions, such as ...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
You can define the startup function before the application instantation. That’s fine, since it won’t run until the
app
is in scope.@laurentS Yup I think that’s reasonable. I’ve got an outstanding PR for a context-managed.
lifespan
alternative to startup/shudown, and yes, that happens to include the app instance… https://github.com/encode/starlette/pull/799