Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting the timeout on a urllib2.request() call

Tags:

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?

like image 921
eran Avatar asked May 20 '13 09:05

eran


People also ask

What value should be returned by the call to the URL request Getcode () method to confirm that the specified URL has successfully returned data?

The getcode() method (Added in python2. 6) returns the HTTP status code that was sent with the response, or None if the URL is no HTTP URL.

What is Urllib request request?

The urllib. request module defines functions and classes which help in opening URLs (mostly HTTP) in a complex world — basic and digest authentication, redirections, cookies and more. See also. The Requests package is recommended for a higher-level HTTP client interface.

What does urllib2 do in Python?

Urllib package is the URL handling module for python. It is used to fetch URLs (Uniform Resource Locators). It uses the urlopen function and is able to fetch URLs using a variety of different protocols.

What is the difference between Urllib and urllib2?

1) urllib2 can accept a Request object to set the headers for a URL request, urllib accepts only a URL. 2) urllib provides the urlencode method which is used for the generation of GET query strings, urllib2 doesn't have such a function. This is one of the reasons why urllib is often used along with urllib2.


2 Answers

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() 
like image 121
Jared Avatar answered Oct 22 '22 15:10

Jared


still, you can avoid using urlopen and proceed like this:

request = urllib2.Request('http://example.com') response = opener.open(request,timeout=4) response_result = response.read() 

this works too :)

like image 24
OrangeG Avatar answered Oct 22 '22 16:10

OrangeG