Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 以编程方式启用或禁用@auth_basic()_Python_Bottle - Fatal编程技术网

Python 以编程方式启用或禁用@auth_basic()

Python 以编程方式启用或禁用@auth_basic(),python,bottle,Python,Bottle,我试图在我的程序中使用瓶子框架@auth\u basic(check\u credentials)装饰器,但我希望能够根据用户在程序设置中的选择启用或禁用它 我曾尝试在检查凭证中执行if操作,如果设置为False,则返回True,但我仍然得到登录弹出窗口,该弹出窗口始终返回True。我根本不想看到弹出窗口 你知道我怎样才能做到吗 def check_credentials(user, pw): if auth_enabled == True: username = "te

我试图在我的程序中使用瓶子框架
@auth\u basic(check\u credentials)
装饰器,但我希望能够根据用户在程序设置中的选择启用或禁用它

我曾尝试在
检查凭证
中执行
if
操作,如果设置为
False
,则返回
True
,但我仍然得到登录弹出窗口,该弹出窗口始终返回
True
。我根本不想看到弹出窗口

你知道我怎样才能做到吗

def check_credentials(user, pw):
    if auth_enabled == True:
        username = "test"
        password = "test"
        if pw == password and user == username:
            return True
        return False
    else:
        return True

@route('/')
@auth_basic(check_credentials)
def root():
    # ---page content---

HTTP Auth弹出是因为您正在使用瓶子框架中的装饰器,这是一种默认行为

您的设置实际上总是允许所有人进入,而不是禁用HTTP弹出窗口。您需要做的是实现另一个检查密码的“中间件”

from bottle import route, Response, run, HTTPError, request

auth_enabled = True


def custom_auth_basic(check, realm="private", text="Access denied"):
    ''' Callback decorator to require HTTP auth (basic).
        TODO: Add route(check_auth=...) parameter. '''
    def decorator(func):
        def wrapper(*a, **ka):
            if auth_enabled:
                user, password = request.auth or (None, None)
                if user is None or not check(user, password):
                    err = HTTPError(401, text)
                    err.add_header('WWW-Authenticate', 'Basic realm="%s"' % realm)
                    return err
                return func(*a, **ka)
            else:
                return func(*a, **ka)

        return wrapper
    return decorator


def check_credentials(user, pw):
    if auth_enabled:
        username = "test"
        password = "test"
        if pw == password and user == username:
            return True
        return False
    else:
        return True


@route('/')
@custom_auth_basic(check_credentials)
def root():
    return Response("Test")


run(host='localhost', port=8080)

您能解释一下您使用的框架或显示一些代码吗?对不起,我只添加了瓶子标签,没有在文本中提到它。您是否尝试在检查函数中记录
auth\u enabled
的值?是的,auth\u enabled值可以。装饰器添加到路由后,将立即显示基本身份验证弹出窗口。我需要在它显示之前截取它。@morpheus65535我用自定义auth_basic更新了答案