1

我的代码如下所示,但是运行时会引发错误。

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
4

2 回答 2

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 特有的。

于 2012-12-24T11:38:31.603 回答
0

当我试图向我的 GAE Python 服务器发送一个大的 post 请求时,我遇到了同样的错误。事实证明服务器抛出错误是因为我试图将接收到的 POST 字符串写入 db.StringProperty()。我将其更改为 db.TextProperty() 并且它不再抛出错误。

资料来源:克服 python 中的 appengine 500 字节字符串限制?考虑文本

于 2013-11-27T02:17:56.423 回答