gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:11:21 26 4
gpt4 key购买 nike

我正在尝试在程序中使用 Bottle 框架 @auth_basic(check_credentials) 装饰器,但我希望能够根据用户在程序设置。

我尝试在 check_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 弹出是因为您正在使用 Bottle 框架中的装饰器,这是默认行为 link .

您的设置实际上所做的是始终让所有人进入,而不是禁用 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)

关于python - 以编程方式启用或禁用@auth_basic(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51630946/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com