robert
robert

Reputation: 25

Traceback when I use urllib2, get a HTTP 500 error

My code is like follows, but when it runs it throws an error.

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()

the error is:

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

I don't know how to fix it? I mean, when an error happened, how can my code continue to work?

when i try use

       try:
                search_response = urllib2.urlopen(search_request)
            except urllib2.HTTPError:
                pass

new error

UnboundLocalError: local variable 'search_response' referenced before assignment

i use

global search_response

and have error

NameError: global name 'search_response' is not defined

Upvotes: 1

Views: 14704

Answers (2)

enkash
enkash

Reputation: 151

I had the same error when I was trying to send a large post request to my GAE Python server. It turns out the server threw the error because I was trying to write the received POST string into a db.StringProperty(). I changed that to db.TextProperty() and it didn't throw the error anymore.

Source: Overcome appengine 500 byte string limit in python? consider text

Upvotes: 0

Burhan Khalid
Burhan Khalid

Reputation: 174698

You can catch the exception, this will prevent your program from stopping so 'abruptly':

try:
  search_response = urllib2.urlopen(search_request)
except urllib2.HTTPError:
  print 'There was an error with the request'

If you want to continue, you can simply:

try:
  search_response = urllib2.urlopen(search_request)
except urllib2.HTTPError:
  pass

This will allow your program to continue; but your other statement html_data = search_response.read() won't give you the expected result. To fix this problem permanently, you need to debug your request to see why its failing; this isn't something specific to Python.

Upvotes: 1

Related Questions