Search code examples
pythondecoratorflaskwerkzeug

Create a Flask public url decorator


I'd like to create a decorator for Flask routes to flag certain routes as public, so I can do things like this:

@public
@app.route('/welcome')
def welcome():
    return render_template('/welcome.html')

Elsewhere, here's what I was thinking the decorator and check would look like:

_public_urls = set()

def public(route_function):
    # add route_function's url to _public_urls
    # _public_urls.add(route_function ...?.url_rule)
    def decorator(f):
        return f

def requested_url_is_public():
    from flask import request
    return request.url_rule in _public_urls

Then when a request is made, I have a context function that checks requested_url_is_public.

I'm a bit stumped because I don't know how to get the url rule for a given function in the public decorator.

Perhaps this isn't the best design choice for Flask, but I'd expect there's another simple & elegant way to achieve this.

I've seen this patterns like this before, and would like to mimic it. For example, this is something of a counterpart to Django's login_required decorator.

I'd enjoy reading thoughts on this.


Solution

  • Flask already has a login_required decorator (see view decorators). If you are using public_urls to decide which urls to require authentication for, you are most likely better off using that.