views:

234

answers:

3

Hi,

I'm building a download manager in python for fun, and sometimes the connection to the server is still on but the server doesn't send me data, so read method (of HTTPResponse) block me forever. This happens, for example, when I download from a server, which located outside of my country, that limit the bandwidth to other countries.

How can I set a timeout for the read method (2 minutes for example)?

Thanks, Nir.

+1  A: 

You have to set it during HTTPConnection initialization.

Note: in case you are using an older version of Python, then you can install httplib2; by many, it is considered a superior alternative to httplib, and it does supports timeout.
I've never used it, though, and I'm just reporting what documentation and blogs are saying.

Roberto Liffredo
+1, but note the timeout parameter to the constructor is available only in python 2.6+.
Jarret Hardie
Right - I've added some notes about httplib2
Roberto Liffredo
I will try it, but I'm a little bit skeptic because the code of HTTPResponse class use the 'makefile' method, which cannot get a timeout by the documentation: "The socket must be in blocking mode (it can not have a timeout)".
Thanks, it works :)
+1  A: 

If you're stuck on some Python version < 2.6, one (imperfect but usable) approach is to do

import socket
socket.setdefaulttimeout(10.0)  # or whatever

before you start using httplib. The docs are here, and clearly state that setdefaulttimeout is available since Python 2.3 -- every socket made from the time you do this call, to the time you call the same function again, will use that timeout of 10 seconds. You can use getdefaulttimeout before setting a new timeout, if you want to save the previous timeout (including none) so that you can restore it later (with another setdefaulttimeout).

These functions and idioms are quite useful whenever you need to use some older higher-level library which uses Python sockets but doesn't give you a good way to set timeouts (of course it's better to use updated higher-level libraries, e.g. the httplib version that comes with 2.6 or the third-party httplib2 in this case, but that's not always feasible, and playing with the default timeout setting can be a good workaround).

Alex Martelli
A: 

Setting the default timeout might abort a download early if it's large, as opposed to only aborting if it stops receiving data for the timeout value. HTTPlib2 is probably the way to go.

Anonymous