在flask-restless预处理器中访问请求标头

Cas*_*sey 2 python flask flask-restless

我正在使用Flask-Restless构建一个API,它需要一个API密钥,它将位于AuthorizationHTTP标头中.

在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]))
Run Code Online (Sandbox Code Playgroud)

如何检索函数中的Authorization标题check_auth

我试过访问Flask response对象,但它是None在这个函数的范围内.该kw参数也是一个空字典.

Mar*_*ers 7

在正常的Flask请求 - 响应周期中,当运行Flask-Restful预处理器和后处理器时,request上下文处于活动状态.

因此,使用:

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)
Run Code Online (Sandbox Code Playgroud)

应该工作.