Looking into the documentation about middleware i didn't found anything about adding a middleware to a single route, in my case i would like to validate the request payload on each route because each route has a diferente body request, is that possible?
The whole point if middleware is to work on multiple routes.
If you want to run logic on just endpoint view, you should add the logic to the view.
However, if you really want to do this, you can do something like
@middlware
async def my_middleware(request, handler):
if request.path == '/foobar/'
.... # my custom logic
else:
return await handler(request)
You can even look at route names, via
if isinstance(request.match_info, MatchInfoError):
return
if request.match_info.route.name in {'foo', 'bar', ...}:
...
Ye, i get it, i was imagining something like laravel and spring does.
The whole point if middleware is to work on multiple routes.
not on every case, let suppose that i have a service where i charge my clients per feature, before the client enter the section of that feature i need to know if he paid for it, but this verification don't need to be on every route of my project.
here is a example on laravel.
https://laravel.com/docs/5.7/middleware#registering-middleware
Thank you anyway!
It would be helpful if route middleware is available in the core of aiohttp . Also it would make up for a great feature !
A wrapper/decorator for your web-handler can do this work pretty well; the decorator works with any aiohttp version pretty well.
Can you kindly give me an example?
import functools
def deco(func):
@functools.wraps(func)
async def wrapper(request):
await prepare(request)
try:
return await func(request)
finally:
await finalize(request)
return wrapper
@deco
async def handler(request):
return web.Response(text='OK')
app.router.add_get('/', handler)
Thank you so much for the prompt reply! That's exactly what I was looking for :)
Welcome!
Most helpful comment