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

2 投票
1 回答
2170 浏览
提问于 2025-04-18 07:25

我正在用 Flask-Restless 创建一个需要 API 密钥的接口,这个密钥会放在 Authorization 的 HTTP 头里。

在 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]))

我该如何在 check_auth 函数中获取 Authorization 头的信息呢?

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

1 个回答

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)

应该是可以正常工作的。

撰写回答