request.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. from __future__ import annotations
  2. import io
  3. import sys
  4. import typing
  5. from base64 import b64encode
  6. from enum import Enum
  7. from ..exceptions import UnrewindableBodyError
  8. from .util import to_bytes
  9. if typing.TYPE_CHECKING:
  10. from typing import Final
  11. # Pass as a value within ``headers`` to skip
  12. # emitting some HTTP headers that are added automatically.
  13. # The only headers that are supported are ``Accept-Encoding``,
  14. # ``Host``, and ``User-Agent``.
  15. SKIP_HEADER = "@@@SKIP_HEADER@@@"
  16. SKIPPABLE_HEADERS = frozenset(["accept-encoding", "host", "user-agent"])
  17. ACCEPT_ENCODING = "gzip,deflate"
  18. try:
  19. try:
  20. import brotlicffi as _unused_module_brotli # type: ignore[import-not-found] # noqa: F401
  21. except ImportError:
  22. import brotli as _unused_module_brotli # type: ignore[import-not-found] # noqa: F401
  23. except ImportError:
  24. pass
  25. else:
  26. ACCEPT_ENCODING += ",br"
  27. try:
  28. if sys.version_info >= (3, 14):
  29. from compression import zstd as _unused_module_zstd # noqa: F401
  30. else:
  31. from backports import zstd as _unused_module_zstd # noqa: F401
  32. except ImportError:
  33. pass
  34. else:
  35. ACCEPT_ENCODING += ",zstd"
  36. class _TYPE_FAILEDTELL(Enum):
  37. token = 0
  38. _FAILEDTELL: Final[_TYPE_FAILEDTELL] = _TYPE_FAILEDTELL.token
  39. _TYPE_BODY_POSITION = typing.Union[int, _TYPE_FAILEDTELL]
  40. # When sending a request with these methods we aren't expecting
  41. # a body so don't need to set an explicit 'Content-Length: 0'
  42. # The reason we do this in the negative instead of tracking methods
  43. # which 'should' have a body is because unknown methods should be
  44. # treated as if they were 'POST' which *does* expect a body.
  45. _METHODS_NOT_EXPECTING_BODY = {"GET", "HEAD", "DELETE", "TRACE", "OPTIONS", "CONNECT"}
  46. def make_headers(
  47. keep_alive: bool | None = None,
  48. accept_encoding: bool | list[str] | str | None = None,
  49. user_agent: str | None = None,
  50. basic_auth: str | None = None,
  51. proxy_basic_auth: str | None = None,
  52. disable_cache: bool | None = None,
  53. *,
  54. basic_auth_encoding: str = "latin-1",
  55. proxy_basic_auth_encoding: str = "latin-1",
  56. ) -> dict[str, str]:
  57. """
  58. Shortcuts for generating request headers.
  59. :param keep_alive:
  60. If ``True``, adds 'connection: keep-alive' header.
  61. :param accept_encoding:
  62. Can be a boolean, list, or string.
  63. ``True`` translates to 'gzip,deflate'. If the dependencies for
  64. Brotli (either the ``brotli`` or ``brotlicffi`` package) and/or
  65. Zstandard (the ``backports.zstd`` package for Python before 3.14)
  66. algorithms are installed, then their encodings are
  67. included in the string ('br' and 'zstd', respectively).
  68. List will get joined by comma.
  69. String will be used as provided.
  70. :param user_agent:
  71. String representing the user-agent you want, such as
  72. "python-urllib3/0.6"
  73. :param basic_auth:
  74. Colon-separated username:password string for 'authorization: basic ...'
  75. auth header. Basic authentication transmits Base64-encoded bytes, not
  76. Unicode text, so the string is encoded with ``basic_auth_encoding``
  77. before Base64 encoding.
  78. Must contain decoded credentials (not percent-encoded).
  79. For URLs parsed with :func:`parse_url`, use :attr:`Url.auth_decoded_joined`
  80. to get the properly formatted string.
  81. :param basic_auth_encoding:
  82. Text encoding used to encode ``basic_auth`` before Base64 encoding.
  83. Defaults to "latin-1" for backward compatibility. Use "utf-8" only
  84. when the peer expects UTF-8 Basic authentication credentials.
  85. Must contain decoded credentials (not percent-encoded).
  86. For URLs parsed with :func:`parse_url`, use :attr:`Url.auth_decoded_joined`
  87. to get the properly formatted string.
  88. :param proxy_basic_auth:
  89. Colon-separated username:password string for 'proxy-authorization: basic ...'
  90. auth header. Basic authentication transmits Base64-encoded bytes, not
  91. Unicode text, so the string is encoded with ``proxy_basic_auth_encoding``
  92. before Base64 encoding.
  93. Must contain decoded credentials (not percent-encoded).
  94. For URLs parsed with :func:`parse_url`, use :attr:`Url.auth_decoded_joined`
  95. to get the properly formatted string.
  96. :param proxy_basic_auth_encoding:
  97. Text encoding used to encode ``proxy_basic_auth`` before Base64
  98. encoding. Defaults to "latin-1" for backward compatibility. Use
  99. "utf-8" only when the proxy expects UTF-8 Basic authentication
  100. credentials.
  101. Must contain decoded credentials (not percent-encoded).
  102. For URLs parsed with :func:`parse_url`, use :attr:`Url.auth_decoded_joined`
  103. to get the properly formatted string.
  104. :param disable_cache:
  105. If ``True``, adds 'cache-control: no-cache' header.
  106. Example:
  107. .. code-block:: python
  108. import urllib3
  109. print(urllib3.util.make_headers(keep_alive=True, user_agent="Batman/1.0"))
  110. # {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'}
  111. print(urllib3.util.make_headers(accept_encoding=True))
  112. # {'accept-encoding': 'gzip,deflate'}
  113. """
  114. headers: dict[str, str] = {}
  115. if accept_encoding:
  116. if isinstance(accept_encoding, str):
  117. pass
  118. elif isinstance(accept_encoding, list):
  119. accept_encoding = ",".join(accept_encoding)
  120. else:
  121. accept_encoding = ACCEPT_ENCODING
  122. headers["accept-encoding"] = accept_encoding
  123. if user_agent:
  124. headers["user-agent"] = user_agent
  125. if keep_alive:
  126. headers["connection"] = "keep-alive"
  127. if basic_auth:
  128. headers["authorization"] = (
  129. f"Basic {b64encode(basic_auth.encode(basic_auth_encoding)).decode()}"
  130. )
  131. if proxy_basic_auth:
  132. headers["proxy-authorization"] = (
  133. f"Basic {b64encode(proxy_basic_auth.encode(proxy_basic_auth_encoding)).decode()}"
  134. )
  135. if disable_cache:
  136. headers["cache-control"] = "no-cache"
  137. return headers
  138. def set_file_position(
  139. body: typing.Any, pos: _TYPE_BODY_POSITION | None
  140. ) -> _TYPE_BODY_POSITION | None:
  141. """
  142. If a position is provided, move file to that point.
  143. Otherwise, we'll attempt to record a position for future use.
  144. """
  145. if pos is not None:
  146. rewind_body(body, pos)
  147. elif getattr(body, "tell", None) is not None:
  148. try:
  149. pos = body.tell()
  150. except OSError:
  151. # This differentiates from None, allowing us to catch
  152. # a failed `tell()` later when trying to rewind the body.
  153. pos = _FAILEDTELL
  154. return pos
  155. def rewind_body(body: typing.IO[typing.AnyStr], body_pos: _TYPE_BODY_POSITION) -> None:
  156. """
  157. Attempt to rewind body to a certain position.
  158. Primarily used for request redirects and retries.
  159. :param body:
  160. File-like object that supports seek.
  161. :param int pos:
  162. Position to seek to in file.
  163. """
  164. body_seek = getattr(body, "seek", None)
  165. if body_seek is not None and isinstance(body_pos, int):
  166. try:
  167. body_seek(body_pos)
  168. except OSError as e:
  169. raise UnrewindableBodyError(
  170. "An error occurred when rewinding request body for redirect/retry."
  171. ) from e
  172. elif body_pos is _FAILEDTELL:
  173. raise UnrewindableBodyError(
  174. "Unable to record file position for rewinding "
  175. "request body during a redirect/retry."
  176. )
  177. elif body_seek is None:
  178. raise UnrewindableBodyError("body does not implement seek.")
  179. else:
  180. raise ValueError(
  181. f"body_pos must be of type integer, instead it was {type(body_pos)}."
  182. )
  183. class ChunksAndContentLength(typing.NamedTuple):
  184. chunks: typing.Iterable[bytes] | None
  185. content_length: int | None
  186. def body_to_chunks(
  187. body: typing.Any | None, method: str, blocksize: int
  188. ) -> ChunksAndContentLength:
  189. """Takes the HTTP request method, body, and blocksize and
  190. transforms them into an iterable of chunks to pass to
  191. socket.sendall() and an optional 'Content-Length' header.
  192. A 'Content-Length' of 'None' indicates the length of the body
  193. can't be determined so should use 'Transfer-Encoding: chunked'
  194. for framing instead.
  195. """
  196. chunks: typing.Iterable[bytes] | None
  197. content_length: int | None
  198. # No body, we need to make a recommendation on 'Content-Length'
  199. # based on whether that request method is expected to have
  200. # a body or not.
  201. if body is None:
  202. chunks = None
  203. if method.upper() not in _METHODS_NOT_EXPECTING_BODY:
  204. content_length = 0
  205. else:
  206. content_length = None
  207. # Bytes or strings become bytes
  208. elif isinstance(body, (str, bytes)):
  209. chunks = (to_bytes(body),)
  210. content_length = len(chunks[0])
  211. # File-like object, TODO: use seek() and tell() for length?
  212. elif hasattr(body, "read"):
  213. def chunk_readable() -> typing.Iterable[bytes]:
  214. encode = isinstance(body, io.TextIOBase)
  215. while True:
  216. datablock = body.read(blocksize)
  217. if not datablock:
  218. break
  219. if encode:
  220. datablock = datablock.encode("utf-8")
  221. yield datablock
  222. chunks = chunk_readable()
  223. content_length = None
  224. # Otherwise we need to start checking via duck-typing.
  225. else:
  226. try:
  227. # Check if the body implements the buffer API.
  228. mv = memoryview(body)
  229. except TypeError:
  230. try:
  231. # Check if the body is an iterable
  232. chunks = iter(body)
  233. content_length = None
  234. except TypeError:
  235. raise TypeError(
  236. f"'body' must be a bytes-like object, file-like "
  237. f"object, or iterable. Instead was {body!r}"
  238. ) from None
  239. else:
  240. # Since it implements the buffer API can be passed directly to socket.sendall()
  241. chunks = (body,)
  242. content_length = mv.nbytes
  243. return ChunksAndContentLength(chunks=chunks, content_length=content_length)