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:
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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.