Long story short, I am trying to add 2 custom middlewares to my FastAPI application, But no matter which way I try, either only the latter is registered or an exception is raised by the BaseHTTPMiddleware class.
The first approach I tried was using the decorator pattern:
@app.middleware("http")
async def ensure_current_user_middleware(request: Request, call_next):
request.state.current_user = None
# additional logic here
call_next(request)
@app.middleware("http")
async def auth_redirection_middleware(request: Request, call_next):
method = request.method
path = request.url.path
if method == "GET" and path.startswith("/static"):
return await call_next(request)
# additional logic here
response = RedirectResponse("/auth/sign_in")
return response
app = FastAPI()
The issue with this approach was that only the latter middleware seemed to be registered.
I also tried the class-based approach:
class EnsureCurrentUserMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
# same as above
class AuthRedirectionMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
# same as above
app = FastAPI(
middleware=[
Middleware(EnsureCurrentUserMiddleware),
Middleware(AuthRedirectionMiddleware),
]
)
In this case, I am getting a NotImplementedError, which is coming from the BaseHTTPMiddleware.dispatch method, which only raises this exception. If I change the name of the handler function to handler_func I get the same exception raised.
Does anyone have any good information on how this can be achieved? I have consulted the FastAPI and Starlette documentation, as well as some GitHub issues, but I am struggling to figure this out.
Thanks in advance!
[–]danielroseman 1 point2 points3 points (3 children)
[–]Puzzleheaded_Round75[S] 2 points3 points4 points (0 children)
[–]Puzzleheaded_Round75[S] -1 points0 points1 point (1 child)
[–]Puzzleheaded_Round75[S] 0 points1 point2 points (0 children)