setting the timeout on a urllib2.request() call

eran picture eran · May 20, 2013 · Viewed 32k times · Source

I need to set the timeout on urllib2.request().

I do not use urllib2.urlopen() since i am using the data parameter of request. How can I set this?

Answer

Jared picture Jared · May 20, 2013

Although urlopen does accept data param for POST, you can call urlopen on a Request object like this,

import urllib2
request = urllib2.Request('http://www.example.com', data)
response = urllib2.urlopen(request, timeout=4)
content = response.read()