I have a simple website I’m testing. It’s running on localhost and I can access it in my web browser. The index page is simply the word ‘running’. urllib.urlopen will successfully read the page but urllib2.urlopen will not. Here’s a script which demonstrates the problem (this is the actual script and not a simplification of a different test script):
import urllib, urllib2 print urllib.urlopen('http://127.0.0.1').read() # prints 'running' print urllib2.urlopen('http://127.0.0.1').read() # throws an exception
Here’s the stack trace:
Traceback (most recent call last): File 'urltest.py', line 5, in <module> print urllib2.urlopen('http://127.0.0.1').read() File 'C:\Python25\lib\urllib2.py', line 121, in urlopen return _opener.open(url, data) File 'C:\Python25\lib\urllib2.py', line 380, in open response = meth(req, response) File 'C:\Python25\lib\urllib2.py', line 491, in http_response 'http', request, response, code, msg, hdrs) File 'C:\Python25\lib\urllib2.py', line 412, in error result = self._call_chain(*args) File 'C:\Python25\lib\urllib2.py', line 353, in _call_chain result = func(*args) File 'C:\Python25\lib\urllib2.py', line 575, in http_error_302 return self.parent.open(new) File 'C:\Python25\lib\urllib2.py', line 380, in open response = meth(req, response) File 'C:\Python25\lib\urllib2.py', line 491, in http_response 'http', request, response, code, msg, hdrs) File 'C:\Python25\lib\urllib2.py', line 418, in error return self._call_chain(*args) File 'C:\Python25\lib\urllib2.py', line 353, in _call_chain result = func(*args) File 'C:\Python25\lib\urllib2.py', line 499, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 504: Gateway Timeout
Any ideas? I might end up needing some of the more advanced features of urllib2, so I don’t want to just resort to using urllib, plus I want to understand this problem.
Sounds like you have proxy settings defined that urllib2 is picking up on. When it tries to proxy ‘127.0.0.01/’, the proxy gives up and returns a 504 error.
From Obscure python urllib2 proxy gotcha: