request.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. from __future__ import absolute_import
  2. from base64 import b64encode
  3. from ..exceptions import UnrewindableBodyError
  4. from ..packages.six import b, integer_types
  5. # Pass as a value within ``headers`` to skip
  6. # emitting some HTTP headers that are added automatically.
  7. # The only headers that are supported are ``Accept-Encoding``,
  8. # ``Host``, and ``User-Agent``.
  9. SKIP_HEADER = "@@@SKIP_HEADER@@@"
  10. SKIPPABLE_HEADERS = frozenset(["accept-encoding", "host", "user-agent"])
  11. ACCEPT_ENCODING = "gzip,deflate"
  12. try:
  13. import brotli as _unused_module_brotli # noqa: F401
  14. except ImportError:
  15. pass
  16. else:
  17. ACCEPT_ENCODING += ",br"
  18. _FAILEDTELL = object()
  19. def make_headers(
  20. keep_alive=None,
  21. accept_encoding=None,
  22. user_agent=None,
  23. basic_auth=None,
  24. proxy_basic_auth=None,
  25. disable_cache=None,
  26. ):
  27. """
  28. Shortcuts for generating request headers.
  29. :param keep_alive:
  30. If ``True``, adds 'connection: keep-alive' header.
  31. :param accept_encoding:
  32. Can be a boolean, list, or string.
  33. ``True`` translates to 'gzip,deflate'.
  34. List will get joined by comma.
  35. String will be used as provided.
  36. :param user_agent:
  37. String representing the user-agent you want, such as
  38. "python-urllib3/0.6"
  39. :param basic_auth:
  40. Colon-separated username:password string for 'authorization: basic ...'
  41. auth header.
  42. :param proxy_basic_auth:
  43. Colon-separated username:password string for 'proxy-authorization: basic ...'
  44. auth header.
  45. :param disable_cache:
  46. If ``True``, adds 'cache-control: no-cache' header.
  47. Example::
  48. >>> make_headers(keep_alive=True, user_agent="Batman/1.0")
  49. {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'}
  50. >>> make_headers(accept_encoding=True)
  51. {'accept-encoding': 'gzip,deflate'}
  52. """
  53. headers = {}
  54. if accept_encoding:
  55. if isinstance(accept_encoding, str):
  56. pass
  57. elif isinstance(accept_encoding, list):
  58. accept_encoding = ",".join(accept_encoding)
  59. else:
  60. accept_encoding = ACCEPT_ENCODING
  61. headers["accept-encoding"] = accept_encoding
  62. if user_agent:
  63. headers["user-agent"] = user_agent
  64. if keep_alive:
  65. headers["connection"] = "keep-alive"
  66. if basic_auth:
  67. headers["authorization"] = "Basic " + b64encode(b(basic_auth)).decode("utf-8")
  68. if proxy_basic_auth:
  69. headers["proxy-authorization"] = "Basic " + b64encode(
  70. b(proxy_basic_auth)
  71. ).decode("utf-8")
  72. if disable_cache:
  73. headers["cache-control"] = "no-cache"
  74. return headers
  75. def set_file_position(body, pos):
  76. """
  77. If a position is provided, move file to that point.
  78. Otherwise, we'll attempt to record a position for future use.
  79. """
  80. if pos is not None:
  81. rewind_body(body, pos)
  82. elif getattr(body, "tell", None) is not None:
  83. try:
  84. pos = body.tell()
  85. except (IOError, OSError):
  86. # This differentiates from None, allowing us to catch
  87. # a failed `tell()` later when trying to rewind the body.
  88. pos = _FAILEDTELL
  89. return pos
  90. def rewind_body(body, body_pos):
  91. """
  92. Attempt to rewind body to a certain position.
  93. Primarily used for request redirects and retries.
  94. :param body:
  95. File-like object that supports seek.
  96. :param int pos:
  97. Position to seek to in file.
  98. """
  99. body_seek = getattr(body, "seek", None)
  100. if body_seek is not None and isinstance(body_pos, integer_types):
  101. try:
  102. body_seek(body_pos)
  103. except (IOError, OSError):
  104. raise UnrewindableBodyError(
  105. "An error occurred when rewinding request body for redirect/retry."
  106. )
  107. elif body_pos is _FAILEDTELL:
  108. raise UnrewindableBodyError(
  109. "Unable to record file position for rewinding "
  110. "request body during a redirect/retry."
  111. )
  112. else:
  113. raise ValueError(
  114. "body_pos must be of type integer, instead it was %s." % type(body_pos)
  115. )