尝试使用REST框架或Tastypie将图像上载到FileField模型

时间:2015-02-06 00:39:46

标签: python django rest tastypie

有人可以给我一步一步/链接资源,了解如何使用REST API将文件从移动/桌面应用程序上传到基于Django的服务器吗?

服务器有一个名为“thumbnail”的FileField模型。我能够上传其他数据,但文件似乎是个大问题。

请注意,我不是在谈论使用浏览器/ Django表单上传,而是通过Http请求从应用程序上传

API:

from models import Article

class ArticleResource(ModelResource):

    class Meta:
        queryset = Article.objects.all()
        resource_name = 'article'
        filtering = {'title': ALL}
        authorization=Authorization()

独立的python脚本我正在使用Http Requests(模拟移动应用程序)

url="http://127.0.0.1:8000/articles/api/article/"

data={
    'title':'Tastypie',
    'body':'First Restful client',
    'pub_date':'05/02/2015',
    }
files=  {'thumbnail': open('django.png', 'rb')}
headers =  {'content-type': 'image/png'}
print requests.post(url, files=files)

模型:

class Article(models.Model):
    title = models.CharField(max_length=200)
    body = models.TextField()
    pub_date = models.DateTimeField('date published')
    likes = models.IntegerField(default=0)
    thumbnail = models.FileField(blank=True,null=True,upload_to=get_upload_file_name)
    def __unicode__(self):
        return str(self.title)

修改

这有效:

API:

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()
                photo = Article()
                photo.thumbnail = request.FILES['thumbnail']
                photo.title = request.POST.get('title')
                photo.body=request.POST.get('body')
                photo.pub_date = request.POST.get('pub_date')
                photo.save()
                # ... etc
                return data
            return super(ArticleResource, self).deserialize(request, data, format)

        # overriding the save method to prevent the object getting saved twice 
        def obj_create(self, bundle, request=None, **kwargs):
             pass


class ArticleResource(MultipartResource,ModelResource):

    class Meta:
        queryset = Article.objects.all()
        resource_name = 'article'
        filtering = {'title': ALL}
        authorization=Authorization()

Http Request Python脚本:

url="http://127.0.0.1:8000/articles/api/article/"

data={
    'title':'Tastypie',
    'body':'First Restful client',
    'pub_date':'2015-02-05',
    }
files=  {'thumbnail': open('django.png', 'rb')}

print requests.post(url, data=data, files=files).text

1 个答案:

答案 0 :(得分:1)

Tastypie没有任何保存二进制文件的好方法。我会尝试这样的事情:

class ArticleResource(ModelResource):

    class Meta:
        queryset = Article.objects.all()
        resource_name = 'article'
        filtering = {'title': ALL}
        authorization=Authorization()    

    # save the photo
        def deserialize(self, request, data, format=None):
            if not format:
                format = request.META.get('CONTENT_TYPE', 'application/json')

            if format.startswith('multipart'):
                data = request.POST.copy()
                photo = Article()
                photo.thumbnail = request.FILES['thumbnail']
                photo.title = request.POST.get('title')
                # ... etc
                return data
            return super(ArticleResource, self).deserialize(request, data, format)

        # overriding the save method to prevent the object getting saved twice 
        def obj_create(self, bundle, request=None, **kwargs):
            pass