Previously with Flask I wanted to remove database upon shutdown :
database.py
db_session = scoped_session(sessionmaker(.....)
app.py
from database import db_session
@app.teardown_appcontext
def shutdown_session(exception=None):
db_session.remove()
But with FastAPI:
AttributeError: 'FastAPI' object has no attribute 'teardown_appcontext'
What to do please?
Hi @dmontagu how would one write a unit test for example:
@app.on_event("shutdown")
def shutdown_session():
db_session.remove()
If you use a starlette TestClient via a context manager:
with TestClient(app) as client:
client.get(...)
it will run the startup and shutdown events when entering/exiting the context. So that should help you run the events as part of your test suite.
Yeah, all what @dmontagu said. :point_up:
If that solves your problem @scheung38 , you can close the issue.
Assuming the original issue was solved, it will be automatically closed now. But feel free to add more comments or create new issues.
https://fastapi.tiangolo.com/tutorial/events/#shutdown-event
Above link is expired, here is the updated link https://fastapi.tiangolo.com/advanced/events/#events-startup-shutdown .
Most helpful comment
https://fastapi.tiangolo.com/tutorial/events/#shutdown-event