Skip to content

Equivalent of flask's Flask.before_request and Flask.after_request? #8200

Answered by dmontagu
cetanu asked this question in Questions
Discussion options

You must be logged in to vote

I haven't used flask much, but looking through the flask docs a little, this seems to be the same concept as middleware.

Here are the middleware docs for FastAPI, and for starlette.

For example, looking at an example from the SQL Databases page from the FastAPI docs (linked from the middleware link above), here's a way to use this to handle a database session at the start and end of each request:

@app.middleware("http")
async def db_session_middleware(request: Request, call_next):
    response = Response("Internal server error", status_code=500)
    try:
        request.state.db = SessionLocal()
        response = await call_next(request)
    finally:
        request.state.db.close()
    r…

Replies: 6 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by cetanu
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
4 participants
Converted from issue

This discussion was converted from issue #409 on February 28, 2023 12:26.