response.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. from ..utils import cached_property
  2. from .auth import WWWAuthenticateMixin
  3. from .base_response import BaseResponse
  4. from .common_descriptors import CommonResponseDescriptorsMixin
  5. from .etag import ETagResponseMixin
  6. class ResponseStream(object):
  7. """A file descriptor like object used by the :class:`ResponseStreamMixin` to
  8. represent the body of the stream. It directly pushes into the response
  9. iterable of the response object.
  10. """
  11. mode = "wb+"
  12. def __init__(self, response):
  13. self.response = response
  14. self.closed = False
  15. def write(self, value):
  16. if self.closed:
  17. raise ValueError("I/O operation on closed file")
  18. self.response._ensure_sequence(mutable=True)
  19. self.response.response.append(value)
  20. self.response.headers.pop("Content-Length", None)
  21. return len(value)
  22. def writelines(self, seq):
  23. for item in seq:
  24. self.write(item)
  25. def close(self):
  26. self.closed = True
  27. def flush(self):
  28. if self.closed:
  29. raise ValueError("I/O operation on closed file")
  30. def isatty(self):
  31. if self.closed:
  32. raise ValueError("I/O operation on closed file")
  33. return False
  34. def tell(self):
  35. self.response._ensure_sequence()
  36. return sum(map(len, self.response.response))
  37. @property
  38. def encoding(self):
  39. return self.response.charset
  40. class ResponseStreamMixin(object):
  41. """Mixin for :class:`BaseRequest` subclasses. Classes that inherit from
  42. this mixin will automatically get a :attr:`stream` property that provides
  43. a write-only interface to the response iterable.
  44. """
  45. @cached_property
  46. def stream(self):
  47. """The response iterable as write-only stream."""
  48. return ResponseStream(self)
  49. class Response(
  50. BaseResponse,
  51. ETagResponseMixin,
  52. ResponseStreamMixin,
  53. CommonResponseDescriptorsMixin,
  54. WWWAuthenticateMixin,
  55. ):
  56. """Full featured response object implementing the following mixins:
  57. - :class:`ETagResponseMixin` for etag and cache control handling
  58. - :class:`ResponseStreamMixin` to add support for the `stream` property
  59. - :class:`CommonResponseDescriptorsMixin` for various HTTP descriptors
  60. - :class:`WWWAuthenticateMixin` for HTTP authentication support
  61. """