【发布时间】:2019-08-10 00:56:38
【问题描述】:
首先我的项目是这样的:
├───api
│ ├───config
│ │ └───config.json
│ ├───namespace
│ │ └───routes.py
│ └───auth.py (where the decorator is)
│ │
│ └───__init__.py (where the config is injected with flask injector)
├───core
└───example_service.py
我一直在尝试重构烧瓶应用程序上的一些现有代码,以避免在代码中硬写验证 url。这个想法是创建一个装饰器 @authorize 在应用程序的每个路由处理程序上使用,以检查请求标头 Authorization 是否已设置并正常工作。
现在装饰器看起来像这样:
def authorize(func):
def decorator(*args, **kwargs):
get_token_info()
return func(*args, **kwargs)
return decorator
验证函数如下所示:
def get_token_info():
session = requests.Session()
res = session.get('my_auth_url', headers={'Authorization' : request.headers['Authorization']}
if r.status_code != requests.codes.ok:
abort(401)
现在,我的应用程序有一个 init 文件,我在其中使用烧瓶注入器将应用程序的配置注入不同的服务类中。问题是,我还想注入 'my_auth_url' 而不是直接将其写入代码中。但似乎烧瓶注入器只能注入到类中。
我尝试使用烧瓶全局上下文使 url 在应用程序中的任何地方都可以访问,但我发现这不是它的目的,我真的不知道该怎么做。 (实际上我是 python 新手)
非常感谢您的帮助,不清楚的地方见谅,项目很大,很难同时清晰简洁。
【问题讨论】:
标签: python flask python-requests decorator