我正在尝试调整另一个 StackOverflow 答案,有条件地应用装饰器,只需要登录特定环境(最终是一个staging
环境,但development
直到我得到这个工作)。为此,我从以下内容开始
auth = HTTPDigestAuth()
def login_required(dec, condition):
def decorator(func):
if not condition:
return func
return dec(func)
return decorator
@bp.route('/auth')
@login_required(auth.login_required, current_app.config['ENV'] != 'development')
def auth_route():
return current_app.config['ENV']
当我启动服务器时,我得到一个RuntimeError: Working outside of application context
错误。在尝试了这个问题的早期版本的一些建议之后,我得到了RuntimeError
消失,但是当我想要的时候,装饰器仍然没有被正确应用。这是当前版本:
def login_required(dec):
def decorator(func):
if not os.environ.get('ENV') != 'development':
return func
return dec(func)
return decorator
@bp.route('/auth')
@login_required(auth.login_required)
def auth_route():
return current_app.config['ENV']
这永远不会返回auth.login_reqired
函数。它总是让浏览器在没有身份验证的情况下进入。
所以,我尝试将条件更改为
if not os.environ.get('ENV') is not None:
然后出现身份验证。
是的,我export ENV=development
在 shell 中做了一个并用env
命令确认它。但即便如此,它也没有像我预期的那样读取环境变量。
也许这只是错误的做法?我的最终目标是要求在一个特定环境中进行身份验证。这可能与我正在走的路吗?有可能吗?