尝试在 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)),
图像模型很简单:
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 代码有什么问题。我找不到更多的例子。
服务器看起来不错,我可以在浏览器中发布数据。非常感谢。