4
我有一個非常大的問題,試圖在Django REST Framework應用程序中用文件發佈數據。我通過djangorestframework網站上的示例創建了一個簡單的應用程序。所以我有網址的文件:Django REST Framework帶有文件錯誤的POST數據(使用ModelResource)
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錯誤和服務器(蟒蛇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代碼。我找不到更多的例子。
服務器看起來不錯,我可以在瀏覽器中發佈數據。非常感謝你。
我不知道什麼是你的代碼錯誤... 你應該嘗試使用[要求](http://docs.python-requests.org/en/latest/ index.html)而不是urllib。這將有助於避免urllib頭痛。 – yprez 2012-08-11 08:00:21
是否有可能在您的計算機上安裝某種防火牆? re:「建立的連接被主機中的軟件中止」 – 2013-01-23 03:00:13