tee.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. """Tee function implementations."""
  2. import io
  3. _DEFAULT_CHUNKSIZE = 65536
  4. __all__ = ['tee', 'tee_to_file', 'tee_to_bytearray']
  5. def _tee(response, callback, chunksize, decode_content):
  6. for chunk in response.raw.stream(amt=chunksize,
  7. decode_content=decode_content):
  8. callback(chunk)
  9. yield chunk
  10. def tee(response, fileobject, chunksize=_DEFAULT_CHUNKSIZE,
  11. decode_content=None):
  12. """Stream the response both to the generator and a file.
  13. This will stream the response body while writing the bytes to
  14. ``fileobject``.
  15. Example usage:
  16. .. code-block:: python
  17. resp = requests.get(url, stream=True)
  18. with open('save_file', 'wb') as save_file:
  19. for chunk in tee(resp, save_file):
  20. # do stuff with chunk
  21. .. code-block:: python
  22. import io
  23. resp = requests.get(url, stream=True)
  24. fileobject = io.BytesIO()
  25. for chunk in tee(resp, fileobject):
  26. # do stuff with chunk
  27. :param response: Response from requests.
  28. :type response: requests.Response
  29. :param fileobject: Writable file-like object.
  30. :type fileobject: file, io.BytesIO
  31. :param int chunksize: (optional), Size of chunk to attempt to stream.
  32. :param bool decode_content: (optional), If True, this will decode the
  33. compressed content of the response.
  34. :raises: TypeError if the fileobject wasn't opened with the right mode
  35. or isn't a BytesIO object.
  36. """
  37. # We will be streaming the raw bytes from over the wire, so we need to
  38. # ensure that writing to the fileobject will preserve those bytes. On
  39. # Python3, if the user passes an io.StringIO, this will fail, so we need
  40. # to check for BytesIO instead.
  41. if not ('b' in getattr(fileobject, 'mode', '') or
  42. isinstance(fileobject, io.BytesIO)):
  43. raise TypeError('tee() will write bytes directly to this fileobject'
  44. ', it must be opened with the "b" flag if it is a file'
  45. ' or inherit from io.BytesIO.')
  46. return _tee(response, fileobject.write, chunksize, decode_content)
  47. def tee_to_file(response, filename, chunksize=_DEFAULT_CHUNKSIZE,
  48. decode_content=None):
  49. """Stream the response both to the generator and a file.
  50. This will open a file named ``filename`` and stream the response body
  51. while writing the bytes to the opened file object.
  52. Example usage:
  53. .. code-block:: python
  54. resp = requests.get(url, stream=True)
  55. for chunk in tee_to_file(resp, 'save_file'):
  56. # do stuff with chunk
  57. :param response: Response from requests.
  58. :type response: requests.Response
  59. :param str filename: Name of file in which we write the response content.
  60. :param int chunksize: (optional), Size of chunk to attempt to stream.
  61. :param bool decode_content: (optional), If True, this will decode the
  62. compressed content of the response.
  63. """
  64. with open(filename, 'wb') as fd:
  65. for chunk in tee(response, fd, chunksize, decode_content):
  66. yield chunk
  67. def tee_to_bytearray(response, bytearr, chunksize=_DEFAULT_CHUNKSIZE,
  68. decode_content=None):
  69. """Stream the response both to the generator and a bytearray.
  70. This will stream the response provided to the function, add them to the
  71. provided :class:`bytearray` and yield them to the user.
  72. .. note::
  73. This uses the :meth:`bytearray.extend` by default instead of passing
  74. the bytearray into the ``readinto`` method.
  75. Example usage:
  76. .. code-block:: python
  77. b = bytearray()
  78. resp = requests.get(url, stream=True)
  79. for chunk in tee_to_bytearray(resp, b):
  80. # do stuff with chunk
  81. :param response: Response from requests.
  82. :type response: requests.Response
  83. :param bytearray bytearr: Array to add the streamed bytes to.
  84. :param int chunksize: (optional), Size of chunk to attempt to stream.
  85. :param bool decode_content: (optional), If True, this will decode the
  86. compressed content of the response.
  87. """
  88. if not isinstance(bytearr, bytearray):
  89. raise TypeError('tee_to_bytearray() expects bytearr to be a '
  90. 'bytearray')
  91. return _tee(response, bytearr.extend, chunksize, decode_content)