Django REST框架POST文件错误(使用ModelResource)
发布时间:2020-12-20 13:29:29 所属栏目:Python 来源:网络整理
导读:尝试在Django REST Framework应用程序中使用文件发布数据时,我遇到了一个非常大的问题.我在 djangorestframework网站上通过示例创建了一个简单的应用程序.所以我有urls文件: class MyImageResource(ModelResource): model = Image 在urlpatters中: url(r'^
尝试在Django REST Framework应用程序中使用文件发布数据时,我遇到了一个非常大的问题.我在
djangorestframework网站上通过示例创建了一个简单的应用程序.所以我有urls文件:
class MyImageResource(ModelResource): model = Image 在urlpatters中: url(r'^image/$',ListOrCreateModelView.as_view(resource=MyImageResource)),url(r'^image/(?P<pk>[^/]+)/$',InstanceModelView.as_view(resource=MyImageResource)), Image模型很简单: class Image(models.Model): image = models.ImageField(upload_to=get_file_path) name = models.CharField(max_length=256,blank=True) description = models.TextField(blank=True) 在浏览器中测试REST页面,效果很好.甚至用文件发布数据. 我的问题是我想创建一个简单的python应用程序来发布数据.我使用了简单的urllib2,但是我得到500内部错误或400错误请求: poza = open('poza.jpg','rb') initial_data = ( {'name','Imagine de test REST'},{'description','Dude,this is awesome'},{'image',poza},) d = urllib.urlencode(initial_data) r = urllib2.Request('http://localhost:8000/api/image/',data=d,headers={'Content-Type':'multipart/form-data'}) resp = urllib2.urlopen(r) code = resp.getcode() data = resp.read() 我也尝试过使用MultipartPostHandler: import MultipartPostHandler,urllib2,cookielib cookies = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies),MultipartPostHandler.MultipartPostHandler) params = { "name":"bob","description":"riviera","content" : open("poza.jpg","rb") } opener.open("http://localhost:8000/api/image/",params) 但相同:500或400错误和服务器(python manage.py runserver)停止,并出现以下错误: Exception happened during processing of request from ('127.0.0.1',64879) Traceback (most recent call last): File "C:Python27libSocketServer.py",line 284,in _handle_request_noblock self.process_request(request,client_address) File "C:Python27libSocketServer.py",line 310,in process_request self.finish_request(request,line 323,in finish_request self.RequestHandlerClass(request,client_address,self) File "C:Python27libsite-packagesdjangocoreserversbasehttp.py",line 570,in __init__ BaseHTTPRequestHandler.__init__(self,*args,**kwargs) File "C:Python27libSocketServer.py",line 641,in __init__ self.finish() File "C:Python27libSocketServer.py",line 694,in finish self.wfile.flush() File "C:Python27libsocket.py",line 303,in flush self._sock.sendall(view[write_offset:write_offset+buffer_size]) error: [Errno 10053] An established connection was aborted by the software in yo ur host machine 如果有人有,请给我一个用文件发布数据的例子或告诉我发布python代码有什么问题.我找不到更多的例子了. 服务器看起来不错,我可以在浏览器中发布数据.非常感谢你. 解决方法
它看起来不像是在读取文件,而是传递文件指针?
尝试: initial_data = ( {'name',poza.read()},) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |