简体   繁体   English

了解Flask-HTTPAuth上的装饰器

[英]Understand decorators on Flask-HTTPAuth

I want to understand how and when @auth.verify_password decorator is used on this program. 我想了解在此程序中如何以及何时使用@ auth.verify_password装饰器。 If i navigate to route http://127.0.0.1:5000 , I understand that I need to passed in a username and a password and @auth.login_required will verify it, but where does @auth.verify_password comes in? 如果我导航到路线http://127.0.0.1:5000 ,我理解我需要输入用户名和密码,然后@ auth.login_required将对其进行验证,但是@ auth.verify_password出现在哪里?

Does @auth.login_required calls it? @ 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()

From the documentation : 文档中

verify_password(verify_password_callback) 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. 回调函数接受两个参数,即用户名和密码,并且必须返回True或False。

So you basically provide the function so your program is able to verify the credentials supplied by the user. 因此,您基本上可以提供该功能,以便您的程序能够验证用户提供的凭据。

The login_required decorator protects the route by reading the authentication credentials provided by the user and passing them to your verify_password function to be verified. login_required装饰器通过读取用户提供的身份验证凭据并将其传递给您要验证的verify_password函数来保护路由。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM