I'm building an API with Flask-Restless that requires an API key, that will be in the Authorization
HTTP header.
我正在使用Flask-Restless构建一个API,它需要一个API密钥,它将位于Authorization HTTP标头中。
In the Flask-Restless example here for a preprocessor:
在Flask-Restless示例中,这里有一个预处理器:
def check_auth(instance_id=None, **kw):
# Here, get the current user from the session.
current_user = ...
# Next, check if the user is authorized to modify the specified
# instance of the model.
if not is_authorized_to_modify(current_user, instance_id):
raise ProcessingException(message='Not Authorized',
status_code=401)
manager.create_api(Person, preprocessors=dict(GET_SINGLE=[check_auth]))
How do I retrieve the Authorization
header in the check_auth
function?
如何在check_auth函数中检索Authorization标头?
I have tried accessing the Flask response
object, but it is None
during the scope of this function. The kw
parameter is also an empty dict.
我试过访问Flask响应对象,但在此函数的范围内它是None。 kw参数也是一个空字典。
1 个解决方案
#1
7
In a normal Flask request-response cycle, the request
context is active when the Flask-Restful preprocessors and postprocessors are being run.
在正常的Flask请求 - 响应周期中,当运行Flask-Restful预处理器和后处理器时,请求上下文处于活动状态。
As such, using:
因此,使用:
from flask import request, abort
def check_auth(instance_id=None, **kw):
current_user = None
auth = request.headers.get('Authorization', '').lower()
try:
type_, apikey = auth.split(None, 1)
if type_ != 'your_api_scheme':
# invalid Authorization scheme
ProcessingException(message='Not Authorized',
status_code=401)
current_user = user_for_apikey[apikey]
except (ValueError, KeyError):
# split failures or API key not valid
ProcessingException(message='Not Authorized',
status_code=401)
should Just Work.
应该工作。
#1
7
In a normal Flask request-response cycle, the request
context is active when the Flask-Restful preprocessors and postprocessors are being run.
在正常的Flask请求 - 响应周期中,当运行Flask-Restful预处理器和后处理器时,请求上下文处于活动状态。
As such, using:
因此,使用:
from flask import request, abort
def check_auth(instance_id=None, **kw):
current_user = None
auth = request.headers.get('Authorization', '').lower()
try:
type_, apikey = auth.split(None, 1)
if type_ != 'your_api_scheme':
# invalid Authorization scheme
ProcessingException(message='Not Authorized',
status_code=401)
current_user = user_for_apikey[apikey]
except (ValueError, KeyError):
# split failures or API key not valid
ProcessingException(message='Not Authorized',
status_code=401)
should Just Work.
应该工作。