Skip to content
Discussion options

You must be logged in to vote

I think this use case could be easily handled without a middleware, using normal dependencies, here's an example:

from fastapi import FastAPI, Depends


class Action:
    def __init__(self, action: str):
        self.action = action

    def __call__(self):
        # action parameter available here, do anything you want with audit here
        # before the response
        print(self.action)
        yield
        # or after the response
        print(self.action)


app = FastAPI()


@app.get("/", dependencies=[Depends(Action("search"))])
def home():
    return {"Hello": "World"}

It would probably not be a good idea to do that in a middleware as it doesn't have access to any info you put …

Replies: 10 comments

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
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
Answer selected by Kludex
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 #1879 on February 28, 2023 00:50.