如何使用 django rest 框架解析多部分表单数据中的多个文件?
How to parse multiple files in multipart form-data with django rest framework?
我收到一个包含几个文件的数组。我的 request.data 看起来像这样:
<QueryDict: {'image': [<TemporaryUploadedFile: image_1.png (image/png)>, <TemporaryUploadedFile: image_2.png (image/png)>]
但是,如果我尝试像这样解析图像:
request.data['image']
我只能看到最后一张图片,django rest framework 将其识别为文件对象,而不是列表。
如果我尝试遍历它,我只能看到字节。
我正在使用 ModelViewset 并添加了这个解析器
parser_classes = (MultiPartParser, FormParser)
A QueryDict
有一个特殊的函数来获取 所有 与特定键关联的值:getlist(key)
[doc]。所以你可以这样写:
request.data<b>.getlist('image')</b> # list of images
然后您可以分别处理每个图像(例如在 for
循环中)。
或者像在documentation中指定的那样:
<b>QueryDict.getlist(key, default=None)</b>
Returns a list of the data with the requested key. Returns an empty list if the key doesn't exist and a default value wasn’t provided. It's guaranteed to return a list unless the default
value provided is' a list.
如果您执行索引(如 request.data[key]
),那么 Python 将在幕后调用 __getitem__
,这将导致:
<b>QueryDict.__getitem__(key)</b>
Returns the value for the given key. If the key has more than one value, it returns the last value. Raises django.utils.datastructures.MultiValueDictKeyError
if the key does not exist. (This is a subclass of Python's standard KeyError
, so you can stick to catching KeyError
.)
我收到一个包含几个文件的数组。我的 request.data 看起来像这样:
<QueryDict: {'image': [<TemporaryUploadedFile: image_1.png (image/png)>, <TemporaryUploadedFile: image_2.png (image/png)>]
但是,如果我尝试像这样解析图像:
request.data['image']
我只能看到最后一张图片,django rest framework 将其识别为文件对象,而不是列表。 如果我尝试遍历它,我只能看到字节。
我正在使用 ModelViewset 并添加了这个解析器
parser_classes = (MultiPartParser, FormParser)
A QueryDict
有一个特殊的函数来获取 所有 与特定键关联的值:getlist(key)
[doc]。所以你可以这样写:
request.data<b>.getlist('image')</b> # list of images
然后您可以分别处理每个图像(例如在 for
循环中)。
或者像在documentation中指定的那样:
Returns a list of the data with the requested key. Returns an empty list if the key doesn't exist and a default value wasn’t provided. It's guaranteed to return a list unless the<b>QueryDict.getlist(key, default=None)</b>
default
value provided is' a list.
如果您执行索引(如 request.data[key]
),那么 Python 将在幕后调用 __getitem__
,这将导致:
Returns the value for the given key. If the key has more than one value, it returns the last value. Raises<b>QueryDict.__getitem__(key)</b>
django.utils.datastructures.MultiValueDictKeyError
if the key does not exist. (This is a subclass of Python's standardKeyError
, so you can stick to catchingKeyError
.)