stream.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. # -*- coding: utf-8 -*-
  2. """Utilities for dealing with streamed requests."""
  3. import os.path
  4. import re
  5. from .. import exceptions as exc
  6. # Regular expressions stolen from werkzeug/http.py
  7. # cd2c97bb0a076da2322f11adce0b2731f9193396 L62-L64
  8. _QUOTED_STRING_RE = r'"[^"\\]*(?:\\.[^"\\]*)*"'
  9. _OPTION_HEADER_PIECE_RE = re.compile(
  10. r';\s*(%s|[^\s;=]+)\s*(?:=\s*(%s|[^;]+))?\s*' % (_QUOTED_STRING_RE,
  11. _QUOTED_STRING_RE)
  12. )
  13. _DEFAULT_CHUNKSIZE = 512
  14. def _get_filename(content_disposition):
  15. for match in _OPTION_HEADER_PIECE_RE.finditer(content_disposition):
  16. k, v = match.groups()
  17. if k == 'filename':
  18. # ignore any directory paths in the filename
  19. return os.path.split(v)[1]
  20. return None
  21. def get_download_file_path(response, path):
  22. """
  23. Given a response and a path, return a file path for a download.
  24. If a ``path`` parameter is a directory, this function will parse the
  25. ``Content-Disposition`` header on the response to determine the name of the
  26. file as reported by the server, and return a file path in the specified
  27. directory.
  28. If ``path`` is empty or None, this function will return a path relative
  29. to the process' current working directory.
  30. If path is a full file path, return it.
  31. :param response: A Response object from requests
  32. :type response: requests.models.Response
  33. :param str path: Directory or file path.
  34. :returns: full file path to download as
  35. :rtype: str
  36. :raises: :class:`requests_toolbelt.exceptions.StreamingError`
  37. """
  38. path_is_dir = path and os.path.isdir(path)
  39. if path and not path_is_dir:
  40. # fully qualified file path
  41. filepath = path
  42. else:
  43. response_filename = _get_filename(
  44. response.headers.get('content-disposition', '')
  45. )
  46. if not response_filename:
  47. raise exc.StreamingError('No filename given to stream response to')
  48. if path_is_dir:
  49. # directory to download to
  50. filepath = os.path.join(path, response_filename)
  51. else:
  52. # fallback to downloading to current working directory
  53. filepath = response_filename
  54. return filepath
  55. def stream_response_to_file(response, path=None, chunksize=_DEFAULT_CHUNKSIZE):
  56. """Stream a response body to the specified file.
  57. Either use the ``path`` provided or use the name provided in the
  58. ``Content-Disposition`` header.
  59. .. warning::
  60. If you pass this function an open file-like object as the ``path``
  61. parameter, the function will not close that file for you.
  62. .. warning::
  63. This function will not automatically close the response object
  64. passed in as the ``response`` parameter.
  65. If a ``path`` parameter is a directory, this function will parse the
  66. ``Content-Disposition`` header on the response to determine the name of the
  67. file as reported by the server, and return a file path in the specified
  68. directory. If no ``path`` parameter is supplied, this function will default
  69. to the process' current working directory.
  70. .. code-block:: python
  71. import requests
  72. from requests_toolbelt import exceptions
  73. from requests_toolbelt.downloadutils import stream
  74. r = requests.get(url, stream=True)
  75. try:
  76. filename = stream.stream_response_to_file(r)
  77. except exceptions.StreamingError as e:
  78. # The toolbelt could not find the filename in the
  79. # Content-Disposition
  80. print(e.message)
  81. You can also specify the filename as a string. This will be passed to
  82. the built-in :func:`open` and we will read the content into the file.
  83. .. code-block:: python
  84. import requests
  85. from requests_toolbelt.downloadutils import stream
  86. r = requests.get(url, stream=True)
  87. filename = stream.stream_response_to_file(r, path='myfile')
  88. If the calculated download file path already exists, this function will
  89. raise a StreamingError.
  90. Instead, if you want to manage the file object yourself, you need to
  91. provide either a :class:`io.BytesIO` object or a file opened with the
  92. `'b'` flag. See the two examples below for more details.
  93. .. code-block:: python
  94. import requests
  95. from requests_toolbelt.downloadutils import stream
  96. with open('myfile', 'wb') as fd:
  97. r = requests.get(url, stream=True)
  98. filename = stream.stream_response_to_file(r, path=fd)
  99. print('{} saved to {}'.format(url, filename))
  100. .. code-block:: python
  101. import io
  102. import requests
  103. from requests_toolbelt.downloadutils import stream
  104. b = io.BytesIO()
  105. r = requests.get(url, stream=True)
  106. filename = stream.stream_response_to_file(r, path=b)
  107. assert filename is None
  108. :param response: A Response object from requests
  109. :type response: requests.models.Response
  110. :param path: *(optional)*, Either a string with the path to the location
  111. to save the response content, or a file-like object expecting bytes.
  112. :type path: :class:`str`, or object with a :meth:`write`
  113. :param int chunksize: (optional), Size of chunk to attempt to stream
  114. (default 512B).
  115. :returns: The name of the file, if one can be determined, else None
  116. :rtype: str
  117. :raises: :class:`requests_toolbelt.exceptions.StreamingError`
  118. """
  119. pre_opened = False
  120. fd = None
  121. filename = None
  122. if path and callable(getattr(path, 'write', None)):
  123. pre_opened = True
  124. fd = path
  125. filename = getattr(fd, 'name', None)
  126. else:
  127. filename = get_download_file_path(response, path)
  128. if os.path.exists(filename):
  129. raise exc.StreamingError("File already exists: %s" % filename)
  130. fd = open(filename, 'wb')
  131. for chunk in response.iter_content(chunk_size=chunksize):
  132. fd.write(chunk)
  133. if not pre_opened:
  134. fd.close()
  135. return filename