如何在 Python 中启用基本身份验证调用函数

How to call funcions with basic authentication enabled in Python

我在 Flask 应用程序中使用装饰器进行基本身份验证。 代码如下所示:

from flask import Flask, Response, request
from functools import wraps

app = Flask(__name__)
app.config.from_object('settings')

def valid_credentials(username, password):
    return username == app.config['USER'] and password == app.config['PASS']

def authenticate(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        auth = request.authorization
        if not auth.username or not auth.password or not valid_credentials(auth.username, auth.password):
            return Response('Login!', 401, {'WWW-Authenticate': 'Basic realm="Login!"'})
        return f(*args, **kwargs)
    return wrapper

@app.route('/')
def index():
    return 'Hello, world!'

@app.route('/secure')
@authenticate
def secure():
    return 'Secure!'

@app.route('/check')
@authenticate
def check():
    secure()
    return 'checked'

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

但是由于身份验证,我无法从检查功能调用安全功能。现在可以调用当前场景下的函数吗?

通常的方法是将辅助方法与视图分开。例如:

def _secure():
    return 'Secure!'

@app.route('/secure')
@authenticate
def secure():
    return _secure()

然后您可以从其他地方重用辅助方法 (_secure())。由于它没有关联的路由,因此访问者无法在没有身份验证的情况下访问 运行 它。

将这些辅助方法放在单独的模块中也是一个好主意(例如 helpers.pyutils.py)。