Flask-基本身份验证的装饰器

时间:2019-03-26 19:54:01

标签: python python-3.x authentication flask

我正在尝试创建装饰器,如果未登录,它将重定向到指定路径。

装饰器:

def secured(path):
    @wraps(path)
    def wrapper(f, *args, **kwargs):
        if 'loggedin' in session:
            if session.get('loggedin'):
                return f(*args, **kwargs)
            else:
                redirect(path)
        else:
            session['loggedin'] = False
            redirect(path)
    return wrapper

登录功能:

def val_cred(username, password):
    return username == 'login' and password == 'password'
@app.route('/login', methods=['POST'])
def login():
    auth = request.authorization
    if not auth.username or not auth.password or not val_cred(auth.username, auth.password):
        return 'bad credentials', 401
    session['loggedin'] = True
    return redirect("/hello")

安全路径示例:

@app.route('/hello')
@secured('/')
def hello():
    return 'you are logged in'

在我创建带有静态路径的装饰器之前,该装饰器不带任何参数,并且效果很好,所以我认为这是语法问题,但是Flask指出了其他问题

Traceback (most recent call last):
  File "C:/daftcode-flask/app.py", line 31, in <module>
    @secured('/')
  File "C:/daftcode-flask/app.py", line 14, in wrapper
    if 'loggedin' in session:
  ...

    RuntimeError: Working outside of request context.

This typically means that you attempted to use functionality that needed
an active HTTP request.  Consult the documentation on testing for
information about how to avoid this problem.

如何使其正常工作?

1 个答案:

答案 0 :(得分:1)

您在secured装饰器中输入了错误。您忘记在其中添加一个功能(请参见:def _secured(f)):

def secured(path):
    def _secured(f):
        @wraps(path)
        def __secured(*args, **kwargs):
            # Note! I didn't check your functionality
            if 'loggedin' in session:
                if session.get('loggedin'):
                    return f(*args, **kwargs)
                else:
                    redirect(path)
            else:
                session['loggedin'] = False
                redirect(path)
        return __secured
    return _secured

希望这会有所帮助。