response.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. """Response classes used by urllib.
  2. The base class, addbase, defines a minimal file-like interface,
  3. including read() and readline(). The typical response object is an
  4. addinfourl instance, which defines an info() method that returns
  5. headers and a geturl() method that returns the url.
  6. """
  7. import tempfile
  8. __all__ = ['addbase', 'addclosehook', 'addinfo', 'addinfourl']
  9. class addbase(tempfile._TemporaryFileWrapper):
  10. """Base class for addinfo and addclosehook. Is a good idea for garbage collection."""
  11. # XXX Add a method to expose the timeout on the underlying socket?
  12. def __init__(self, fp):
  13. super(addbase, self).__init__(fp, '<urllib response>', delete=False)
  14. # Keep reference around as this was part of the original API.
  15. self.fp = fp
  16. def __repr__(self):
  17. return '<%s at %r whose fp = %r>' % (self.__class__.__name__,
  18. id(self), self.file)
  19. def __enter__(self):
  20. if self.fp.closed:
  21. raise ValueError("I/O operation on closed file")
  22. return self
  23. def __exit__(self, type, value, traceback):
  24. self.close()
  25. class addclosehook(addbase):
  26. """Class to add a close hook to an open file."""
  27. def __init__(self, fp, closehook, *hookargs):
  28. super(addclosehook, self).__init__(fp)
  29. self.closehook = closehook
  30. self.hookargs = hookargs
  31. def close(self):
  32. try:
  33. closehook = self.closehook
  34. hookargs = self.hookargs
  35. if closehook:
  36. self.closehook = None
  37. self.hookargs = None
  38. closehook(*hookargs)
  39. finally:
  40. super(addclosehook, self).close()
  41. class addinfo(addbase):
  42. """class to add an info() method to an open file."""
  43. def __init__(self, fp, headers):
  44. super(addinfo, self).__init__(fp)
  45. self.headers = headers
  46. def info(self):
  47. return self.headers
  48. class addinfourl(addinfo):
  49. """class to add info() and geturl() methods to an open file."""
  50. def __init__(self, fp, headers, url, code=None):
  51. super(addinfourl, self).__init__(fp, headers)
  52. self.url = url
  53. self.code = code
  54. @property
  55. def status(self):
  56. return self.code
  57. def getcode(self):
  58. return self.code
  59. def geturl(self):
  60. return self.url