You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

186 lines
6.8 KiB

4 years ago
  1. import base64
  2. import io
  3. import json
  4. import zlib
  5. import msgpack
  6. from requests.structures import CaseInsensitiveDict
  7. from .compat import HTTPResponse, pickle, text_type
  8. def _b64_decode_bytes(b):
  9. return base64.b64decode(b.encode("ascii"))
  10. def _b64_decode_str(s):
  11. return _b64_decode_bytes(s).decode("utf8")
  12. class Serializer(object):
  13. def dumps(self, request, response, body=None):
  14. response_headers = CaseInsensitiveDict(response.headers)
  15. if body is None:
  16. body = response.read(decode_content=False)
  17. # NOTE: 99% sure this is dead code. I'm only leaving it
  18. # here b/c I don't have a test yet to prove
  19. # it. Basically, before using
  20. # `cachecontrol.filewrapper.CallbackFileWrapper`,
  21. # this made an effort to reset the file handle. The
  22. # `CallbackFileWrapper` short circuits this code by
  23. # setting the body as the content is consumed, the
  24. # result being a `body` argument is *always* passed
  25. # into cache_response, and in turn,
  26. # `Serializer.dump`.
  27. response._fp = io.BytesIO(body)
  28. # NOTE: This is all a bit weird, but it's really important that on
  29. # Python 2.x these objects are unicode and not str, even when
  30. # they contain only ascii. The problem here is that msgpack
  31. # understands the difference between unicode and bytes and we
  32. # have it set to differentiate between them, however Python 2
  33. # doesn't know the difference. Forcing these to unicode will be
  34. # enough to have msgpack know the difference.
  35. data = {
  36. u"response": {
  37. u"body": body,
  38. u"headers": dict(
  39. (text_type(k), text_type(v)) for k, v in response.headers.items()
  40. ),
  41. u"status": response.status,
  42. u"version": response.version,
  43. u"reason": text_type(response.reason),
  44. u"strict": response.strict,
  45. u"decode_content": response.decode_content,
  46. }
  47. }
  48. # Construct our vary headers
  49. data[u"vary"] = {}
  50. if u"vary" in response_headers:
  51. varied_headers = response_headers[u"vary"].split(",")
  52. for header in varied_headers:
  53. header = text_type(header).strip()
  54. header_value = request.headers.get(header, None)
  55. if header_value is not None:
  56. header_value = text_type(header_value)
  57. data[u"vary"][header] = header_value
  58. return b",".join([b"cc=4", msgpack.dumps(data, use_bin_type=True)])
  59. def loads(self, request, data):
  60. # Short circuit if we've been given an empty set of data
  61. if not data:
  62. return
  63. # Determine what version of the serializer the data was serialized
  64. # with
  65. try:
  66. ver, data = data.split(b",", 1)
  67. except ValueError:
  68. ver = b"cc=0"
  69. # Make sure that our "ver" is actually a version and isn't a false
  70. # positive from a , being in the data stream.
  71. if ver[:3] != b"cc=":
  72. data = ver + data
  73. ver = b"cc=0"
  74. # Get the version number out of the cc=N
  75. ver = ver.split(b"=", 1)[-1].decode("ascii")
  76. # Dispatch to the actual load method for the given version
  77. try:
  78. return getattr(self, "_loads_v{}".format(ver))(request, data)
  79. except AttributeError:
  80. # This is a version we don't have a loads function for, so we'll
  81. # just treat it as a miss and return None
  82. return
  83. def prepare_response(self, request, cached):
  84. """Verify our vary headers match and construct a real urllib3
  85. HTTPResponse object.
  86. """
  87. # Special case the '*' Vary value as it means we cannot actually
  88. # determine if the cached response is suitable for this request.
  89. if "*" in cached.get("vary", {}):
  90. return
  91. # Ensure that the Vary headers for the cached response match our
  92. # request
  93. for header, value in cached.get("vary", {}).items():
  94. if request.headers.get(header, None) != value:
  95. return
  96. body_raw = cached["response"].pop("body")
  97. headers = CaseInsensitiveDict(data=cached["response"]["headers"])
  98. if headers.get("transfer-encoding", "") == "chunked":
  99. headers.pop("transfer-encoding")
  100. cached["response"]["headers"] = headers
  101. try:
  102. body = io.BytesIO(body_raw)
  103. except TypeError:
  104. # This can happen if cachecontrol serialized to v1 format (pickle)
  105. # using Python 2. A Python 2 str(byte string) will be unpickled as
  106. # a Python 3 str (unicode string), which will cause the above to
  107. # fail with:
  108. #
  109. # TypeError: 'str' does not support the buffer interface
  110. body = io.BytesIO(body_raw.encode("utf8"))
  111. return HTTPResponse(body=body, preload_content=False, **cached["response"])
  112. def _loads_v0(self, request, data):
  113. # The original legacy cache data. This doesn't contain enough
  114. # information to construct everything we need, so we'll treat this as
  115. # a miss.
  116. return
  117. def _loads_v1(self, request, data):
  118. try:
  119. cached = pickle.loads(data)
  120. except ValueError:
  121. return
  122. return self.prepare_response(request, cached)
  123. def _loads_v2(self, request, data):
  124. try:
  125. cached = json.loads(zlib.decompress(data).decode("utf8"))
  126. except (ValueError, zlib.error):
  127. return
  128. # We need to decode the items that we've base64 encoded
  129. cached["response"]["body"] = _b64_decode_bytes(cached["response"]["body"])
  130. cached["response"]["headers"] = dict(
  131. (_b64_decode_str(k), _b64_decode_str(v))
  132. for k, v in cached["response"]["headers"].items()
  133. )
  134. cached["response"]["reason"] = _b64_decode_str(cached["response"]["reason"])
  135. cached["vary"] = dict(
  136. (_b64_decode_str(k), _b64_decode_str(v) if v is not None else v)
  137. for k, v in cached["vary"].items()
  138. )
  139. return self.prepare_response(request, cached)
  140. def _loads_v3(self, request, data):
  141. # Due to Python 2 encoding issues, it's impossible to know for sure
  142. # exactly how to load v3 entries, thus we'll treat these as a miss so
  143. # that they get rewritten out as v4 entries.
  144. return
  145. def _loads_v4(self, request, data):
  146. try:
  147. cached = msgpack.loads(data, encoding="utf-8")
  148. except ValueError:
  149. return
  150. return self.prepare_response(request, cached)