Run middleware after web application check if the path exists #7326
-
Hello, I'm looking for a way to run my middleware after the application check if the path that the client requested exists or not. I don't want my middleware to run if the path does not exist and I have to return a This is a server example: from aiohttp import web
@web.middleware
async def log_middleware(request, handler):
print('Incoming request')
response = await handler(request)
print('Request handled')
return response
async def hello_world(request):
return web.Response(text="Hello World")
app = web.Application(middlewares=[log_middleware])
app.router.add_get("/valid", hello_world)
web.run_app(app) So if the user request ======== Running on http://0.0.0.0:8080 ========
(Press CTRL+C to quit)
Incoming request Note that the server does not log the message The client gets the following response: > curl http://localhost:8080/invalid
404: Not Found My python version is Do you have an idea about how we can imlpement this scenario? Thanks in advance. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
The handler is raising the 404 as an exception, that's why your second print doesn't happen. You can catch and reraise the exception, if you want to run something in that situation. This is demonstrated in the tutorial which customises the default error responses: |
Beta Was this translation helpful? Give feedback.
Looking at the code, try this:
if isinstance(request.match_info.http_exception, web.HTTPNotFound):