Apply middleware to single routes

Okay, I think I know the answer after digging most of the afternoon, but we don’t have a way to apply middleware to a single route using a decorator currently, right?

Correct. Middleware is global scope only currently. There is PR #1399 that would add it to Blueprints.

Bah. I’m just working around it then. I haven’t had a use for middleware until now!

at the point your doing this for a single route doesn’t it make more sense to use a decorator instead of a middleware?

I wish. A decorator doesn’t have access to the response object, so it can’t push response headers or cookies. If I had access to the response object, I’d simply wrap the route.

I might be misunderstanding your question but I’m fairly sure you can do whatever you want to the response using a decorator

def decorator(func):
    """ adds foo header to response """
    async def wrapper(request, *args):
        response = func(request, *args)
        if isawaitable(response):
            response = await response
        response.headers['foo'] = 'bar'
        return response
    return wrapper

@app.route("/")
@decorator
async def test(request):
    return response.json({"test": True})

That’s pretty much what I want to do; I’m a bit confused as to what’s happening here though as where you have func as a parameter, I was certain it was a request object. Mental blind spot, I guess.

Thanks, this exactly solves my use case!