【问题标题】:Flask-HTTPAuth: how to pass an extra argument to a function decorated with @auth.verify_password?Flask-HTTPAuth:如何将额外参数传递给用@auth.verify_password 装饰的函数?
【发布时间】:2022-12-05 22:17:25
【问题描述】:

这是一个通过Flask-HTTPAuth 验证的小型 Flask 应用程序。

如何将下面的authorized_users_dict传递给用@auth.verify_password装饰的authenticate函数(不引发错误)?

理由:我想通过将带有用户凭据的字典更明确地传递给修饰的自动函数来提高代码的可读性和可测试性(例如,使用函数调用,而不是通过全局变量隐式调用)。

当前代码:


auth = HTTPBasicAuth()

authorized_users_dict = [..]

# [..]

@auth.verify_password
def authenticate(username, password):    

    #######################################################
    # caution: authorized_users_dict passed via global env.
    #######################################################
    if username in authorized_users_dict:
        
        if check_password_hash(pwhash=authorized_users_dict[username], password=password):
            return True

    # [..]

# [..]

@auth.login_required()

# [..]

【问题讨论】:

    标签: python authentication flask basic-authentication


    【解决方案1】:

    我不认为将这本字典作为参数传递是最佳选择。我假设这本字典是固定的,所以实际上没有技术原因每次有传入请求时都将它作为参数传递。

    但是,如果您对此有强烈的感觉,一种方法是使用 Python 标准库中的 partial 函数。像这样:

    from functools import partial
    
    authorized_users_dict = [..]
    
    def authenticate(users_dict, username, password):    
        if username in users_dict:
            # ...
    
    auth.login_required(partial(authenticate, users_dict))
    

    【讨论】:

      猜你喜欢
      • 2012-04-27
      • 2021-08-06
      • 2016-02-14
      • 2021-11-21
      • 1970-01-01
      • 2017-12-13
      • 1970-01-01
      相关资源
      最近更新 更多