簡體   English   中英

DeliciousPie:是否可以在批量請求中發布多個文件

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

我想發表大量帖子。 問題在於每個項目都需要一張圖像(甚至可能只有幾張)。 是否可以通過批量請求執行此操作?

該模型:

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

和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"

我可以使用批量請求發布多張圖片,還是應該回復到單個帖子?

當然可以! 根據圖像的大小,您必須決定上載它們是否花費太長時間,但是有可能。 根據好吃的文檔,可以通過Patch選項進行批量創建和更新。

文件在這里

並在這里詳細

我走了自定義序列化器之路:

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

並且是需要發布多個文件的所有資源的基類:

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

當然,序列化程序需要一些其他處理(例如,UTF8字段),我從答案中省略了這些處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM