0

I have tried every way I can think of to make this work, and each method fails for a different reason.

I am using Flask-Login to manage users. I want to make a custom decorator that allows me to check user roles. I've looked at Implementing Flask-Login with multiple User Classes, I cannot make it work. I've also looked at Decorators with parameters? and a plethora of other links, and no matter what I do, I can't match the behavior I'm finding in tutorials and stack overflow answers.

So here's one attempt:

def check_role(f):
@wraps(f)
def decorated_view(*args, **kwargs):
    print(f)
    return f(*args, **kwargs)
return decorated_view

This works and prints the name of the function I decorated, but it isn't accepting a "role" parameter for me to check against. If I add that:

def check_role(f, a="test"):
    @wraps(f)
    def decorated_view(*args, **kwargs):
        print(f)
        return f(*args, **kwargs)
    return decorated_view

and then use it with:

@bp.route('/topicManagement', methods=('GET', 'POST'))
@login_required
@check_role(a="foo")

I get "TypeError: check_role() missing 1 required positional argument: 'f'". I have tried every combination I can think of with positional, optional arguments and I can't get past this. The function doesn't need me to pass "f" manually in code until I add a parameter the same way every tutorial tells you to, and then it breaks because it wants the functional parameter supplied, but it errors when I try to provide anything as that now-suddenly-mandatory parameter.

So then from the Decorators with parameters?, I tried doing:

def check_role(a):
def bar(function):
    def foo(*args, **kwargs):
        print(a)
        return function(*args, **kwargs)
    return foo
return bar

No matter what I do here, regardless of names or how many view functions I've decorated, I always get the same:

Could not build url for endpoint ''. Did you mean '' instead?

Thank you Stack Overflow, you're my only hope.

sprmap
  • 71
  • 1
  • 6
  • Is your indentation correct? I don't think your first attempt is valid python yet. – byxor Oct 01 '19 at 14:59
  • It is a bit hard to follow your question here... is the first part still relevant? Do you understand why your first attempt to add the `a` parameter didn't work? – tomjn Oct 01 '19 at 15:10
  • I'm not sure if i'm just having a bad brain day or what, but I found another link (https://stackoverflow.com/questions/13896650/how-to-make-a-python-decorator-function-in-flask-with-arguments-for-authorizati) and a copy-paste worked for me. I don't seem to understand anything going on with the arguments and why they impact the routing and any answer with some additional info would be great. – sprmap Oct 01 '19 at 15:20

0 Answers0