任何人都可以爲我提供一步一步/鏈接資源,瞭解如何使用REST API將文件從移動/桌面應用程序上載到基於Django的服務器?嘗試使用REST框架或Tastypie將圖像上傳到FileField模型
服務器有一個名爲「縮略圖」的FileField模型。我能夠上傳其他數據,但文件似乎是一個巨大的問題。
請注意,我不是通過一個HTTP請求談論使用的瀏覽器/ Django的形式上傳,但是從一個應用程序
API:
from models import Article
class ArticleResource(ModelResource):
class Meta:
queryset = Article.objects.all()
resource_name = 'article'
filtering = {'title': ALL}
authorization=Authorization()
我使用做出獨立python腳本的Http請求(模擬移動應用)
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請求的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
當你運行腳本時會發生什麼?或者更好的是,當你使用'curl'時會發生什麼,其餘的數據是否保存,而不是文件?還是這一切錯誤? – 2015-02-06 00:52:51
@LegoStormtroopr每當我運行這樣的腳本時:'headers = {'content-type':'application/json'} print requests.post(url,data = json.dumps(data),headers = headers).text ' – aggolb 2015-02-06 08:25:16
@LegoStormtroopr每當我運行這樣的腳本:'headers = {'content-type':'application/json'} print requests.post(url,data = json.dumps(data),headers = headers) .text'它運行良好,但是當我編輯它來添加文件時,它給出了一個500錯誤:「error_message」:「指定'multipart/form-data'的格式沒有可用的反序列化方法。請檢查你的''formats' ''和''content_types''在你的串行器上。「 – aggolb 2015-02-06 08:41:23