Add support for app.on_event("startup")
and app.on_event("cleanup")
.
#98
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Closes #64.
Example:
Requires the latest version of uvicorn (0.3.11), which adds ASGI lifespan support.
Docs:
Starlette applications can register multiple event handlers for dealing with
code than needs to run before the application starts up, or when the application
is shutting down.
Registering events
These event handlers can either be
async
coroutines, or regular syncronousfunctions.
The event handlers are registered with a decorator syntax, like so:
Starlette will not start serving any incoming requests until all of the
registered startup handlers have completed.
The cleanup handlers will run once all connections have been closed, and
any in-process background tasks have completed.
Note: The ASGI lifespan protocol has only recently been added to the spec,
and is only currently supported by the
uvicorn
server. Make sure to use thelatest
uvicorn
release if you need startup/cleanup support.Running event handers in tests
You might want to explicitly call into your event handlers in any test setup
or test teardown code.
Alternatively, Starlette provides a context manager that ensures the
lifespan events are called.