Skip to content

Flask teardown request equivalent in Fastapi #6012

Discussion options

You must be logged in to vote

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:

INFO:     Started server process [14025]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Pr…

Replies: 1 comment 5 replies

Comment options

You must be logged in to vote
5 replies
@maxwelldorliea
Comment options

@williamjamir
Comment options

@maxwelldorliea
Comment options

@crazydevlegend
Comment options

@ondiekisteven
Comment options

Answer selected by maxwelldorliea
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Question or problem
4 participants