Django Tastypie反序列化多部分/表单数据上传文件

时间:2013-04-18 16:24:37

标签: django tastypie

我正在尝试通过Multipart / Form-Data表单和Tastypie API上传文件,并遇到了一些问题:

我的模特:

class Client(models.Model):
    account = models.ForeignKey(Account)
    client_image = models.FileField(upload_to=client_image_path, default="/assets/img/default-user-image.png", blank=True, null=True)
    client_image_thumb = models.FileField(upload_to=client_image_thumb_path, default="/assets/img/default-user-image.png", blank=True, null=True)

我正在使用Tastypie问题#42中概述的自定义反序列化方法:

class MultipartResource(object):
    def deserialize(self, request, data, format=None):
        if not format:
            format = request.META.get('CONTENT_TYPE', 'application/json')

        if format == 'application/x-www-form-urlencoded':
            return request.POST

        if format.startswith('multipart'):
            data = request.POST.copy()
            data.update(request.FILES)
            return data

        return super(MultipartResource, self).deserialize(request, data, format)

    def put_detail(self, request, **kwargs):
        if request.META.get('CONTENT_TYPE').startswith('multipart') and \
                not hasattr(request, '_body'):
            request._body = ''

        return super(MultipartResource, self).put_detail(request, **kwargs)

这是我对应的ModelResource:

class ClientResource(MultipartResource, ModelResource):
    account = fields.ForeignKey(AccountResource, 'account')

    class Meta():
        queryset = Client.objects.all()
        always_return_data = True
        resource_name = 'account/clients/client-info'
        authorization = AccountLevelAuthorization()
        list_allowed_methods = ['get','post','put','delete','patch']
        detail_allowed_methods = ['get', 'post', 'put', 'delete','patch']
        authentication = ApiKeyAuthentication()
        filtering = {
            'username': ALL,
        }

如果我使用内容类型application / JSON进行POST并且不包含client_image字段,它将成功创建一个新的客户端对象。这表明模型/资源正在按预期工作。

但是,当我尝试使用Multipart / Form-Data内容类型时,我可以看到它通过此有效负载正确地通过我的反序列化器:

------WebKitFormBoundaryp0Q7Q9djlsvVGwbb
Content-Disposition: form-data; name="{%0D%0A%22account%22"

"/api/v1/account/account-info/21/",

------WebKitFormBoundaryp0Q7Q9djlsvVGwbb
Content-Disposition: form-data; name="client_image"; filename="donavan.jpg"
Content-Type: image/jpeg

------WebKitFormBoundaryp0Q7Q9djlsvVGwbb--

我在调试时也看到了这个QueryDict,它正确地显示了InMemoryUploadedFile:

<QueryDict: {u'client_image': [<InMemoryUploadedFile: donavan.jpg (image/jpeg)>], u'{%0D%0A%22account%22': [u'"/api/v1/account/account-info/21/"']}>

但我一直收到这个错误:

  

{error_message:“”traceback:“Traceback(最近一次调用最后一次):   文件   “/Users/stevewirig/Documents/www/vu/venv/lib/python2.7/site-packages/tastypie/resources.py”   第202行,在包装器响应中=回调(request,* args,** kwargs)   文件   “/Users/stevewirig/Documents/www/vu/venv/lib/python2.7/site-packages/tastypie/resources.py”   第440行,在dispatch_list中返回self.dispatch('list',request,   ** kwargs)文件“/Users/stevewirig/Documents/www/vu/venv/lib/python2.7/site-packages/tastypie/resources.py”,   第472行,在调度响应=方法(请求,** kwargs)文件   “/Users/stevewirig/Documents/www/vu/venv/lib/python2.7/site-packages/tastypie/resources.py”   第1328行,在post_list updated_bundle = self.obj_create(bundle,   ** self.remove_api_resource_names(kwargs))文件“/Users/stevewirig/Documents/www/vu/venv/lib/python2.7/site-packages/tastypie/resources.py”,   第2104行,在obj_create bundle = self.full_hydrate(bundle)文件中   “/Users/stevewirig/Documents/www/vu/venv/lib/python2.7/site-packages/tastypie/resources.py”   第890行,在full_hydrate值= field_object.hydrate(包)文件中   “/Users/stevewirig/Documents/www/vu/venv/lib/python2.7/site-packages/tastypie/fields.py”   732行,水合物值= super(ToOneField,self)。水合物(束)   文件   “/Users/stevewirig/Documents/www/vu/venv/lib/python2.7/site-packages/tastypie/fields.py”   第165行,在hydrate elif self.attribute和getattr(bundle.obj,   self.attribute,无):文件   “/Users/stevewirig/Documents/www/vu/venv/lib/python2.7/site-packages/django/db/models/fields/related.py”   第343行,在获取提升self.field.rel.to.DoesNotExist DoesNotExist   “}

有什么想法可以打破吗?提前致谢!

2 个答案:

答案 0 :(得分:0)

当我在没有提供必要字段的情况下发布数据时发生这种情况。发布时必须提供那些不能为null的字段。

答案 1 :(得分:0)

按以下方式初始化序列化器:

serializer = Serializer(formats=['json'])