【问题标题】:Django Rest Framework does not decode JSON fields in Multipart requests like it does with standard POST requestsDjango Rest Framework 不像标准 POST 请求那样解码 Multipart 请求中的 JSON 字段
【发布时间】:2016-12-12 09:38:08
【问题描述】:

当我使用 Content-Typeapplication/json 提交 POST 请求时,我在服务器上的数据将按应有的方式解码为本机 Python - JSON 对象显示为 dicts,数组显示为数组等。这很棒。
但是,当我对我的 API 进行 MultiPart 发布请求时,当然也包含一个文件,任何包含 JSON/对象的字段都不会在服务器上解码,我留下了我需要自己解码的字符串。我的应用程序的性质意味着我不能总是知道我将要获得哪些领域。

我的问题是 - 我如何提交包含文件的多部分请求,同时保留 DRF 在某些字段中解码 JSON 数据的能力? 我试过一起使用所有 3 个主要的解析器,但是没有用(通过将 API 视图的 parser_classes 设置为它们: parser_classes = (MultiPartParser, JSONParser, FormParser)

以下是发送的一些示例请求(通过 Chrome 的开发工具):

标准邮递(非多部分,无文件): {"first_name":"Test","last_name":"Shmest","email":[{"channel_type":"Email","value":"test@example.com","name":null,"default":false}],"company":{"position":"Manager","id":"735d2b5f-e032-4ca8-93e4-c7773872d0cc","name":"The Compapa"},"access":{"private":true,"users":[10,1]},"description":"Nice guy!!","address":{"city":"San Fanfanfo","zip":"39292","country":"United States of America","state":"CA","map_url":null,"country_code":"US","address":"123 This street"},"phone":[{"default":false,"type":"Phone","id":"70e2b437-6841-4536-9acf-f6a55cc372f6","value":"+141512312345","name":null}],"position":"","department":"","supervisor":"","assistant":"","referred_by":"","status":"","source":"","category":"Lead","do_not_call":false,"do_not_text":false,"do_not_email":false,"birthday":null,"identifier":""} DRF 可以很好地读取此有效负载,并且所有值都设置为其本机等效值。

包含文件的多部分,其中一个字段是 JSON 编码对象:

------WebKitFormBoundaryPfKUrmBd9vRwp5Rb
Content-Disposition: form-data; name="file"; filename="image.png"
Content-Type: image/png


------WebKitFormBoundaryPfKUrmBd9vRwp5Rb
Content-Disposition: form-data; name="first_name"

Test
------WebKitFormBoundaryPfKUrmBd9vRwp5Rb
Content-Disposition: form-data; name="last_name"

Shmest
------WebKitFormBoundaryPfKUrmBd9vRwp5Rb
Content-Disposition: form-data; name="email"

[{"channel_type":"Email","value":"test@example.com","name":null,"default":false}]
------WebKitFormBoundaryPfKUrmBd9vRwp5Rb
Content-Disposition: form-data; name="company"

{"position":"Manager","id":"735d2b5f-e032-4ca8-93e4-c7773872d0cc","name":"The Compapa"}
------WebKitFormBoundaryPfKUrmBd9vRwp5Rb
Content-Disposition: form-data; name="access"

{"private":true,"users":[10,1]}
------WebKitFormBoundaryPfKUrmBd9vRwp5Rb
Content-Disposition: form-data; name="description"

Nice guy!!
------WebKitFormBoundaryPfKUrmBd9vRwp5Rb
Content-Disposition: form-data; name="address"

我正在寻找的是在我深入手动解码所有字段以检查它们是否为 JSON 之前,看看是否有某种方法可以像在常规 POST 中那样在多部分请求中自动进行 JSON 解码.在发出请求之前,我将获得的大多数字段对我来说都是未知的,因为每个用户可能有不同的字段组合。

【问题讨论】:

  • 您对已发送的客户端数据有任何控制权吗?您怎么不知道正在发送哪些字段(这意味着即使使用 json 解析器也不起作用..)?
  • 是的,我愿意。这是一个反应应用程序,使用超级代理进行 api 调用。在多部分请求中(不多,只有 2 个),我必须自己对数据进行字符串化,但它仍然是有效的 json。
  • 在这种情况下我需要编写自己的解析器吗?
  • 如果你知道数据总是json数据+文件格式,那么你可以简单地在序列化器或视图中解码json。除非您在其他视图中使用此流程,否则无需编写自定义解析器,因为 json 解析器的功能完全相同 - 它只是解码 json..
  • 问题是传入的字段不一致。整个系统是动态的,任何东西都可以进入(类型明智:一些字符串,一些数字,一些复杂的 json)。系统基本上已经准备好了,直到现在我在发送带有文件的多部分请求时才注意到这个问题。我想过将上传中断到单独的端点并自己解码一个我无法解决的情况,但我仍然宁愿将其作为一个整体解决并正确处理,因此无论是多部分还是常规帖子都没有关系。

标签: python json django django-rest-framework


【解决方案1】:

我创建了一个新的 Parser 对象来处理这种包含 JSON 字段的 MultiPart 文件上传场景。如果有人需要,代码如下。

import json
from rest_framework.parsers import BaseParser, DataAndFiles
from django.conf import settings
from django.http.multipartparser import MultiPartParser as DjangoMultiPartParser, MultiPartParserError
from django.utils import six
from rest_framework.exceptions import ParseError


class MultiPartJSONParser(BaseParser):
    """
    Parser for multipart form data which might contain JSON values
    in some fields as well as file data.
    This is a variation of MultiPartJSONParser, which goes through submitted fields
    and attempts to decode them as JSON where a value exists. It is not to be used as a replacement
    for MultiPartParser, only in cases where MultiPart AND JSON data are expected.
    """
    media_type = 'multipart/form-data'

    def parse(self, stream, media_type=None, parser_context=None):
        """
        Parses the incoming bytestream as a multipart encoded form,
        and returns a DataAndFiles object.
        `.data` will be a `QueryDict` containing all the form parameters, and JSON decoded where available.
        `.files` will be a `QueryDict` containing all the form files.
        """
        parser_context = parser_context or {}
        request = parser_context['request']
        encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)
        meta = request.META.copy()
        meta['CONTENT_TYPE'] = media_type
        upload_handlers = request.upload_handlers

        try:
            parser = DjangoMultiPartParser(meta, stream, upload_handlers, encoding)
            data, files = parser.parse()
            for key in data:
                if data[key]:
                    try:
                        data[key] = json.loads(data[key])
                    except ValueError:
                        pass
            return DataAndFiles(data, files)
        except MultiPartParserError as exc:
            raise ParseError('Multipart form parse error - %s' % six.text_type(exc))

解析器可以像任何其他一样在 API 视图中使用:

parser_classes = (MultiPartJSONParser, JSONParser , FormParser)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-09
    • 2019-11-20
    • 2023-01-08
    • 2021-07-09
    • 2019-05-04
    • 1970-01-01
    • 2021-01-19
    • 2018-09-22
    相关资源
    最近更新 更多