Django REST框架POST文件错误(使用ModelResource)

时间:2012-08-10 14:04:56

标签: django file post urllib2 django-rest-framework

尝试在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:\Python27\lib\SocketServer.py", line 284, in _handle_request_noblock
    self.process_request(request, client_address)
  File "C:\Python27\lib\SocketServer.py", line 310, in process_request
    self.finish_request(request, client_address)
  File "C:\Python27\lib\SocketServer.py", line 323, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "C:\Python27\lib\site-packages\django\core\servers\basehttp.py", line 570
, in __init__
    BaseHTTPRequestHandler.__init__(self, *args, **kwargs)
  File "C:\Python27\lib\SocketServer.py", line 641, in __init__
    self.finish()
  File "C:\Python27\lib\SocketServer.py", line 694, in finish
    self.wfile.flush()
  File "C:\Python27\lib\socket.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代码有什么问题。我找不到更多的例子。

服务器看起来不错,我可以在浏览器中发布数据。非常感谢你。

1 个答案:

答案 0 :(得分:1)

它看起来好像你正在读取文件,而是传递文件指针?

尝试:

initial_data = (    
    {'name', 'Imagine de test REST'},
    {'description', 'Dude, this is awesome'},
    {'image', poza.read()},
)