从Python发送文件到Django时出现500错误
我找到一个不错的Python模块,可以通过HTTP POST向远程服务器发送数据,叫做 poster。于是我在我的Django应用中写了一个简单的视图,用来接收和存储数据,然后尝试发送一些文件。不幸的是,尽管我按照说明设置了一切,但我还是遇到了 Internal Server Error
(内部服务器错误)。有没有人能帮我看看我哪里做错了?
这是我的视图函数:
def upload(request):
for key, file in request.FILES.items():
path = '/site_media/remote/'+ file.name
dest = open(path.encode('utf-8'), 'wb+')
if file.multiple_chunks:
for c in file.chunks():
dest.write(c)
else:
dest.write(file.read())
dest.close()
这是模块的说明:http://atlee.ca/software/poster/,还有一些我参考的说明 http://www.laurentluce.com/?p=20
这是错误追踪信息:
In [15]: print urllib2.urlopen(request).read()
-------> print(urllib2.urlopen(request).read())
---------------------------------------------------------------------------
HTTPError Traceback (most recent call last)
/home/rails/ntt/<ipython console> in <module>()
/bin/python-2.6.2/lib/python2.6/urllib2.pyc in urlopen(url, data, timeout)
122 if _opener is None:
123 _opener = build_opener()
--> 124 return _opener.open(url, data, timeout)
125
126 def install_opener(opener):
/bin/python-2.6.2/lib/python2.6/urllib2.pyc in open(self, fullurl, data, timeout)
387 for processor in self.process_response.get(protocol, []):
388 meth = getattr(processor, meth_name)
--> 389 response = meth(req, response)
390
391 return response
/bin/python-2.6.2/lib/python2.6/urllib2.pyc in http_response(self, request, response)
500 if not (200 <= code < 300):
501 response = self.parent.error(
--> 502 'http', request, response, code, msg, hdrs)
503
504 return response
/bin/python-2.6.2/lib/python2.6/urllib2.pyc in error(self, proto, *args)
425 if http_err:
426 args = (dict, 'default', 'http_error_default') + orig_args
--> 427 return self._call_chain(*args)
428
429 # XXX probably also want an abstract factory that knows when it makes
/bin/python-2.6.2/lib/python2.6/urllib2.pyc in _call_chain(self, chain, kind, meth_name, *args)
359 func = getattr(handler, meth_name)
360
--> 361 result = func(*args)
362 if result is not None:
363 return result
/bin/python-2.6.2/lib/python2.6/urllib2.pyc in http_error_default(self, req, fp, code, msg, hdrs)
508 class HTTPDefaultErrorHandler(BaseHandler):
509 def http_error_default(self, req, fp, code, msg, hdrs):
--> 510 raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
511
512 class HTTPRedirectHandler(BaseHandler):
HTTPError: HTTP Error 500: Internal Server Error
当我尝试将文件发送到一个PHP函数时(来自 www.w3schools.com/php/php_file_upload.asp
我用wireshark检查过,我的POST请求发送得没有问题,但之后发生了一些错误,我得到了这个500错误。是不是服务器有什么限制?在上面运行的应用程序上传文件是很顺利的。
把这个视图函数和URL放到不同的服务器上,然后运行:
import httplib
conn = httplib.HTTPConnection("address")
f = open("file, "rb")
conn.request("POST","/upload", f, headers)
response = conn.getresponse()
抛出了:BadStatusLine
异常。
1 个回答
3
这是一个基础的Python问题。在使用某个模块之前,你需要先把它导入。所以只需要在脚本的最上面加上 import urllib
这一行,就可以正常使用了。