trd*_*trd 5 django post file urllib2 django-rest-framework
我在尝试在Django REST Framework应用程序中使用文件发布数据时遇到了一个很大的问题。我已经在djangorestframework网站上通过示例创建了一个简单的应用程序。所以我有urls文件:
class MyImageResource(ModelResource):
model = Image
Run Code Online (Sandbox Code Playgroud)
并在urlpatters中:
url(r'^image/$', ListOrCreateModelView.as_view(resource=MyImageResource)),
url(r'^image/(?P<pk>[^/]+)/$', InstanceModelView.as_view(resource=MyImageResource)),
Run Code Online (Sandbox Code Playgroud)
图像模型很简单:
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)
Run Code Online (Sandbox Code Playgroud)
在浏览器中测试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()
Run Code Online (Sandbox Code Playgroud)
我也尝试了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)
Run Code Online (Sandbox Code Playgroud)
但相同: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
Run Code Online (Sandbox Code Playgroud)
如果有人,请给我一个示例,用文件发布数据,或者告诉我发布python代码有什么问题。我找不到更多示例。
服务器看起来不错,我可以在浏览器中发布数据。非常感谢你。
看起来您不是在读取文件,而是传递文件指针?
尝试:
initial_data = (
{'name', 'Imagine de test REST'},
{'description', 'Dude, this is awesome'},
{'image', poza.read()},
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1530 次 |
| 最近记录: |