blob: 1352622e31960163921cb7d19fc98a842861ae99 [file] [log] [blame]
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001"""Response classes used by urllib.
2
3The base class, addbase, defines a minimal file-like interface,
4including read() and readline(). The typical response object is an
5addinfourl instance, which defines an info() method that returns
6headers and a geturl() method that returns the url.
7"""
8
9class addbase(object):
10 """Base class for addinfo and addclosehook."""
11
12 # XXX Add a method to expose the timeout on the underlying socket?
13
14 def __init__(self, fp):
15 # TODO(jhylton): Is there a better way to delegate using io?
16 self.fp = fp
17 self.read = self.fp.read
18 self.readline = self.fp.readline
19 # TODO(jhylton): Make sure an object with readlines() is also iterable
20 if hasattr(self.fp, "readlines"): self.readlines = self.fp.readlines
21 if hasattr(self.fp, "fileno"):
22 self.fileno = self.fp.fileno
23 else:
24 self.fileno = lambda: None
25 if hasattr(self.fp, "__iter__"):
26 self.__iter__ = self.fp.__iter__
27 if hasattr(self.fp, "__next__"):
28 self.__next__ = self.fp.__next__
29
30 def __repr__(self):
31 return '<%s at %r whose fp = %r>' % (self.__class__.__name__,
32 id(self), self.fp)
33
34 def close(self):
35 self.read = None
36 self.readline = None
37 self.readlines = None
38 self.fileno = None
39 if self.fp: self.fp.close()
40 self.fp = None
41
42class addclosehook(addbase):
43 """Class to add a close hook to an open file."""
44
45 def __init__(self, fp, closehook, *hookargs):
46 addbase.__init__(self, fp)
47 self.closehook = closehook
48 self.hookargs = hookargs
49
50 def close(self):
51 addbase.close(self)
52 if self.closehook:
53 self.closehook(*self.hookargs)
54 self.closehook = None
55 self.hookargs = None
56
57class addinfo(addbase):
58 """class to add an info() method to an open file."""
59
60 def __init__(self, fp, headers):
61 addbase.__init__(self, fp)
62 self.headers = headers
63
64 def info(self):
65 return self.headers
66
67class addinfourl(addbase):
68 """class to add info() and geturl() methods to an open file."""
69
70 def __init__(self, fp, headers, url, code=None):
71 addbase.__init__(self, fp)
72 self.headers = headers
73 self.url = url
74 self.code = code
75
76 def info(self):
77 return self.headers
78
79 def getcode(self):
80 return self.code
81
82 def geturl(self):
83 return self.url