1

I defined a check user method:

from functools import wraps

def check_user(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        if session['logged_in']:
            return func(*args, **kwargs)
        else:
            return '<a href="/#/login">Log in</a>'
    return wrapper

@app.route('/test')
@check_user
def test():
    return "Hello"

It does not work. how can I correct it?

Alex.sun
  • 61
  • 1
  • 7

1 Answers1

4

It seems you don't know how to create decorators in python. There are many helpful answers on this question: How can I make a chain of function decorators in Python?

Below is how you can create a decorator that checks if a user is logged in.

from functools import wraps

def checkuser(func):
    """Checks whether user is logged in or raises error 401."""
    @wraps(func)
    def wrapper(*args, **kwargs):
        if not g.user:
            abort(401)
        return func(*args, **kwargs)
    return wrapper

The decorator above will raise a 401 error if a user is not logged in. It will return the view function otherwise.

Community
  • 1
  • 1
xyres
  • 18,466
  • 3
  • 49
  • 80