了解 Flask-HTTPAuth 上的装饰器

Understand decorators on Flask-HTTPAuth

我想了解@auth.verify_password装饰器是如何以及何时在这个程序上使用的。 如果我导航到路由 http://127.0.0.1:5000,我知道我需要输入用户名和密码,@auth.login_required 会验证它,但是 @auth.verify_password 是从哪里来的呢?

@auth.login_required调用它吗?

#!/usr/bin/env python
from flask import Flask
from flask_httpauth import HTTPBasicAuth
from werkzeug.security import generate_password_hash, check_password_hash

app = Flask(__name__)
auth = HTTPBasicAuth()

users = {
    "john": generate_password_hash("hello"),
    "susan": generate_password_hash("bye")
}


@auth.verify_password
def verify_password(username, password):
    if username in users:
        return check_password_hash(users.get(username), password)
    return False


@app.route('/')
@auth.login_required
def index():
    return "Hello, %s!" % auth.username()


if __name__ == '__main__':
    app.run()

来自the documentation

verify_password(verify_password_callback)

If defined, this callback function will be called by the framework to verify that the username and password combination provided by the client are valid. The callback function takes two arguments, the username and the password and must return True or False.

所以您基本上提供了该功能,以便您的程序能够验证用户提供的凭据。

login_required 装饰器通过读取用户提供的身份验证凭据并将其传递给您的 verify_password 函数进行验证来保护路由。