Django Rest Framework批量请求

时间:2018-05-17 16:45:04

标签: django django-rest-framework

我试图在Google的batch requests精神中,在Django Rest Framework中创建一个批处理端点。为此,端点使用TokenAuthentication并在必要时请求带有路径,方法和数据的json编码的字典列表,如下所示:

[
    {
        "path": "/endpoint1",
        "method": "GET"
    },
    {
        "path": "/endpoint2",
        "method": "GET"
    },
    {
        "path": "/endpoint3",
        "method": "POST",
        "data": {
            "file": "<base64>"
        }
    }
]

视图迭代列表,复制请求(使用令牌),根据每个项目设置路径和方法,并通过解析路径获得响应。这是代码:

from copy import copy

@api_view(["POST"])
@authentication_classes((SessionAuthentication, TokenAuthentication))
@permission_classes((IsAuthenticated,))
def batch(request):
    operations = request.data
    responses = []
    for operation in operations:
        op_request = copy(request._request)
        op_request.path = operation["path"]
        op_request.method = operation["method"]
        view, args, kwargs = resolve(operation["path"])
        response = view(op_request, *args, **kwargs)
        operation["response"] = {
            "status": response.status_code,
            "data": response.data
        }
    return Response(operations)

所有非批处理端点都使用相同的autentication_classespermission_classes。我遇到的问题是,身份验证标头与调度视图不同。也就是说,/endpoint3在发送文件(带有用户令牌)时的常规响应是成功的响应:

{
    "id": "asdf",
    "name": "asdf.txt",
}

但是当批量运行时它会像这样结束:

[
    ...<other operations>...,
    {
        "response": {
            "status": 403,
            "data": {
                "detail": "CSRF Failed: CSRF cookie not set."
            }
        },
        "path": "/endpoint3",
        "method": "POST",
        "data": {
            "file": "<Base64>"
        }
    }
]

我是否正确地将标题传递给我要发送的新请求?

0 个答案:

没有答案