1 from twisted.web.client import HTTPDownloader
3 class HTTPProgressDownloader(HTTPDownloader):
4 """Download to a file and keep track of progress."""
6 def __init__(self, url, fileOrName, writeProgress = None, *args, **kwargs):
7 HTTPDownloader.__init__(self, url, fileOrName, *args, **kwargs)
9 # Save callback(s) locally
10 if writeProgress and type(writeProgress) is not list:
11 writeProgress = [ writeProgress ]
12 self.writeProgress = writeProgress
15 self.currentlength = 0
16 self.totallength = None
18 def gotHeaders(self, headers):
19 # If we have a callback and 'OK' from Server try to get length
20 if self.writeProgress and self.status == '200':
21 if headers.has_key('content-length'):
22 self.totallength = int(headers['content-length'][0])
23 for cb in self.writeProgress:
24 cb(0, self.totallength)
26 return HTTPDownloader.gotHeaders(self, headers)
28 def pagePart(self, data):
29 # If we have a callback and 'OK' from server increment pos
30 if self.writeProgress and self.status == '200':
31 self.currentlength += len(data)
32 for cb in self.writeProgress:
33 cb(self.currentlength, self.totallength)
35 return HTTPDownloader.pagePart(self, data)