python - 如何使用 django Rest 框架解析多部分表单数据中的多个文件?

标签 python django django-rest-framework multipartform-data

我收到一个包含几个文件的数组。我的 request.data 如下所示:

<QueryDict: {'image': [<TemporaryUploadedFile: image_1.png (image/png)>, <TemporaryUploadedFile: image_2.png (image/png)>]

但是,如果我尝试像这样解析图像:

request.data['image']

我只能看到最后一个图像,django Rest框架将其识别为文件对象,而不是列表。 如果我尝试迭代它,我只能看到字节。

我正在使用 ModelViewset 并添加了这个解析器

    parser_classes = (MultiPartParser, FormParser)

最佳答案

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.)

关于python - 如何使用 django Rest 框架解析多部分表单数据中的多个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50505440/

相关文章:

python - 无法在 MacOS : 'zsh: command not found: nvm' 上使用 nvm install

python - PyUSB 错误 "USBError: [Errno 2] Entity not found"使用 libusb0 驱动程序 (Windows 10)

python - Djoser 用户激活电子邮件 POST 示例

python - Pyqt GroupBox 育儿

python - 使用 gspread 访问谷歌文档

python - Django 应用程序 : unit tests fails because of django. db.utils.IntegrityError

python - 一次将多个应用程序添加到 INSTALLED_APPS

django - 将 PostgreSQL 重写为 Django ORM

django - 缺少 1 个必需的位置参数 : 'pk'

python - 使用 django rest 框架自定义 lookup_field,无法解析细节