[Flask] combing decorators

Cameron Simpson cs at cskk.id.au
Tue Jun 4 17:31:36 EDT 2019


On 04Jun2019 15:38, Corey Boyle <coreybrett at gmail.com> wrote:
>I need to create a new decorator for my views to handle different users
>having different roles/access levels.
>
>Something like this...
>@role_required('SALES')

I'm doing roughly this, though at present there's just one logged in 
role for my app.

>So my views would end up something like this...
>@blueprint.route('/post')
>@login_required
>@role_required(['SALES'])
>def post():
>    pass
>
>Is there any way for me to combine those decorators?
>Maybe something like...
>@view('/post', ['SALES'])

Sure. You just need to ensure that app.route is the outermost decorator 
so that it attaches your other-decorated handler to the route.

I've a @post_route decorator in my current app which intercepts 
particular form fields, looks them up, and presents the lookups as 
parameters, and this is common enough to do exactly what you're 
describing: wrap app.route and other things into a single decorator.  
Works a treat.

Start with this:

  def view(route, roles, **kw):
    def decorate(handler):
      return blueprint.route(route,**kw)(
               login_required(
                 role_required(roles)(
                   handler)))
    return decorate

That's untested, but you see the structure I presume.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Flask mailing list