简体   繁体   English

DeliciousPie:是否可以在批量请求中发布多个文件

[英]TastyPie: is it possible to post multiple files in a bulk request

I would like to make a bulk post. 我想发表大量帖子。 The problem is that each item requires an image (or, maybe even a few). 问题在于每个项目都需要一张图像(甚至可能只有几张)。 Is it possible to do this via bulk request? 是否可以通过批量请求执行此操作?

The model: 该模型:

class CollageItem(models.Model):
  url = models.URLField(null = True)
  image = models.FileField(upload_to = 'i')
  thumbnail = models.FileField(upload_to = 't')

And the TastyPie object: 和TastyPie对象:

class CollageItemResource(ModelResource):
  image = fields.FileField(attribute = 'image', null = True, blank = true)
  thumbnail = fields.FileField(attribute = 'thumbnail', null = True, blank = true)
  class Meta:
    queryset = CollageItem.objects.all(
    resource_name = "collage_item"

Can I post multiple images using bulk request or should I revert to individual posts? 我可以使用批量请求发布多张图片,还是应该回复到单个帖子?

Ofcourse you can! 当然可以! Depending on the image size, you'll have to decide whether it takes too long to upload them or not, but it is possible. 根据图像的大小,您必须决定上载它们是否花费太长时间,但是有可能。 According to tastypie docs, bulk creation and updation are possible via the Patch option. 根据好吃的文档,可以通过Patch选项进行批量创建和更新。

Docs here 文件在这里

and in detail here 并在这里详细

I went with custom serializer road: 我走了自定义序列化器之路:

class FormPostSerializer(Serializer):
    formats = ['form']
    content_types = {
        'form': 'multipart/form-data',
    }

    def from_form(self, content):
        try:
            dict = cgi.parse_multipart(StringIO(content), self.form_boundary)
        except Exception, e:
            raise e
        for key, value in dict.iteritems():
            dict[key] = value[0] if len(value) > 0 else None
        return dict

And base class for all the resources that require posting multiple files: 并且是需要发布多个文件的所有资源的基类:

class FormResource(ModelResource):
    class Meta:
        serializer = FormPostSerializer()

    def dispatch(self, request_type, request, **kwargs):
        cth = request.META.get('CONTENT_TYPE') or \
            request.META.get('Content-type') or \
            self._meta.serializer.content_types['json']
        self.Meta.serializer.form_boundary = self.parse_content_type_header(cth)
        return super(FormResource, self).dispatch(request_type, request, **kwargs)

    def parse_content_type_header(self, content_type_header):
        parts = cgi.parse_header(content_type_header)
        rv = {}
        for p in parts:
            if isinstance(p, dict):
                rv = dict(rv.items() + p.items())
        return rv

Of course, the serializer requires some additional processing (UTF8 fields, for example) I omitted those from the answer. 当然,序列化程序需要一些其他处理(例如,UTF8字段),我从答案中省略了这些处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM