我的代码如下所示,但是当它运行时会抛出错误。
search_request = urllib2.Request(url,data=tmp_file_name,headers={'X-Requested-With':'WoMenShi888XMLHttpRequestWin'})
#print search_request.get_method()
search_response = urllib2.urlopen(search_request)
html_data = search_response.read()
错误是:
Traceback (most recent call last):
File "xx_tmp.py", line 83, in <module>
print hello_lfi()
File "xx_tmp.py", line 69, in hello_lfi
search_response = urllib2.urlopen(search_request)
File "D:\Python27\lib\urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "D:\Python27\lib\urllib2.py", line 406, in open
response = meth(req, response)
File "D:\Python27\lib\urllib2.py", line 519, in http_response
'http', request, response, code, msg, hdrs)
File "D:\Python27\lib\urllib2.py", line 444, in error
return self._call_chain(*args)
File "D:\Python27\lib\urllib2.py", line 378, in _call_chain
result = func(*args)
File "D:\Python27\lib\urllib2.py", line 527, in http_error_defau
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 500: Internal Server Error
我不知道如何修复它?我的意思是,当发生错误时,我的代码如何继续工作?
当我尝试使用
时 try:
search_response = urllib2.urlopen(search_request)
except urllib2.HTTPError:
pass
新错误
UnboundLocalError: local variable 'search_response' referenced before assignment
我用
global search_response
并有错误
NameError: global name 'search_response' is not defined
答案 0 :(得分:1)
您可以捕获异常,这将阻止您的程序“突然”停止:
try:
search_response = urllib2.urlopen(search_request)
except urllib2.HTTPError:
print 'There was an error with the request'
如果您想继续,可以简单地说:
try:
search_response = urllib2.urlopen(search_request)
except urllib2.HTTPError:
pass
这将允许您的程序继续;但是你的另一个陈述html_data = search_response.read()
不会给你预期的结果。要永久地解决此问题,您需要调试您的请求以查看其失败的原因;这不是Python特有的东西。
答案 1 :(得分:0)
当我尝试向我的GAE Python服务器发送大量的帖子请求时,我遇到了同样的错误。事实证明服务器抛出了错误,因为我试图将收到的POST字符串写入db.StringProperty()。我将其更改为db.TextProperty()并且它不再抛出错误。
来源:Overcome appengine 500 byte string limit in python? consider text