Flask teardown request equivalent in Fastapi #6012
-
First Check
Commit to Help
Example Code# Flask Implementation
from models import storage
.....
.....
@app.teardown_request
def close_session(exception=None):
storage.close_session() DescriptionI am building a rest api with fastapi. I implemented the data layer separately from the fastapi application meaning I do not have direct access to the database session in my fastapi application. I have access to the storage object which have method like Is there a equivalent of flask I have looked at fastapi Operating SystemLinux Operating System DetailsNo response FastAPI Version0.92.0 Python Version3.8.10 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
It is possible to have a teardown request in FastAPI by using a Dependency. Here is an example: from fastapi import FastAPI, Depends
app = FastAPI()
async def some_func():
print('Up')
try:
yield
finally:
print('Teardown')
@app.get('/')
async def some_router_func(foo=Depends(some_func)):
print('Some code')
if __name__ == '__main__':
import uvicorn
uvicorn.run('x:app') When you run this code and make a GET request to '/', you will see the following output in your console:
As you can see, the After the request has been finished (everything from the function was executed), the code after the I hope this helps! |
Beta Was this translation helpful? Give feedback.
It is possible to have a teardown request in FastAPI by using a Dependency. Here is an example:
When you run this code and make a GET request to '/', you will see the following output in your console: