request.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. # SPDX-License-Identifier: MIT
  2. from __future__ import absolute_import
  3. from .filepost import encode_multipart_formdata
  4. from .packages.six.moves.urllib.parse import urlencode
  5. __all__ = ['RequestMethods']
  6. class RequestMethods(object):
  7. """
  8. Convenience mixin for classes who implement a :meth:`urlopen` method, such
  9. as :class:`~urllib3.connectionpool.HTTPConnectionPool` and
  10. :class:`~urllib3.poolmanager.PoolManager`.
  11. Provides behavior for making common types of HTTP request methods and
  12. decides which type of request field encoding to use.
  13. Specifically,
  14. :meth:`.request_encode_url` is for sending requests whose fields are
  15. encoded in the URL (such as GET, HEAD, DELETE).
  16. :meth:`.request_encode_body` is for sending requests whose fields are
  17. encoded in the *body* of the request using multipart or www-form-urlencoded
  18. (such as for POST, PUT, PATCH).
  19. :meth:`.request` is for making any kind of request, it will look up the
  20. appropriate encoding format and use one of the above two methods to make
  21. the request.
  22. Initializer parameters:
  23. :param headers:
  24. Headers to include with all requests, unless other headers are given
  25. explicitly.
  26. """
  27. _encode_url_methods = set(['DELETE', 'GET', 'HEAD', 'OPTIONS'])
  28. def __init__(self, headers=None):
  29. self.headers = headers or {}
  30. def urlopen(self, method, url, body=None, headers=None,
  31. encode_multipart=True, multipart_boundary=None,
  32. **kw): # Abstract
  33. raise NotImplemented("Classes extending RequestMethods must implement "
  34. "their own ``urlopen`` method.")
  35. def request(self, method, url, fields=None, headers=None, **urlopen_kw):
  36. """
  37. Make a request using :meth:`urlopen` with the appropriate encoding of
  38. ``fields`` based on the ``method`` used.
  39. This is a convenience method that requires the least amount of manual
  40. effort. It can be used in most situations, while still having the
  41. option to drop down to more specific methods when necessary, such as
  42. :meth:`request_encode_url`, :meth:`request_encode_body`,
  43. or even the lowest level :meth:`urlopen`.
  44. """
  45. method = method.upper()
  46. if method in self._encode_url_methods:
  47. return self.request_encode_url(method, url, fields=fields,
  48. headers=headers,
  49. **urlopen_kw)
  50. else:
  51. return self.request_encode_body(method, url, fields=fields,
  52. headers=headers,
  53. **urlopen_kw)
  54. def request_encode_url(self, method, url, fields=None, headers=None,
  55. **urlopen_kw):
  56. """
  57. Make a request using :meth:`urlopen` with the ``fields`` encoded in
  58. the url. This is useful for request methods like GET, HEAD, DELETE, etc.
  59. """
  60. if headers is None:
  61. headers = self.headers
  62. extra_kw = {'headers': headers}
  63. extra_kw.update(urlopen_kw)
  64. if fields:
  65. url += '?' + urlencode(fields)
  66. return self.urlopen(method, url, **extra_kw)
  67. def request_encode_body(self, method, url, fields=None, headers=None,
  68. encode_multipart=True, multipart_boundary=None,
  69. **urlopen_kw):
  70. """
  71. Make a request using :meth:`urlopen` with the ``fields`` encoded in
  72. the body. This is useful for request methods like POST, PUT, PATCH, etc.
  73. When ``encode_multipart=True`` (default), then
  74. :meth:`urllib3.filepost.encode_multipart_formdata` is used to encode
  75. the payload with the appropriate content type. Otherwise
  76. :meth:`urllib.urlencode` is used with the
  77. 'application/x-www-form-urlencoded' content type.
  78. Multipart encoding must be used when posting files, and it's reasonably
  79. safe to use it in other times too. However, it may break request
  80. signing, such as with OAuth.
  81. Supports an optional ``fields`` parameter of key/value strings AND
  82. key/filetuple. A filetuple is a (filename, data, MIME type) tuple where
  83. the MIME type is optional. For example::
  84. fields = {
  85. 'foo': 'bar',
  86. 'fakefile': ('foofile.txt', 'contents of foofile'),
  87. 'realfile': ('barfile.txt', open('realfile').read()),
  88. 'typedfile': ('bazfile.bin', open('bazfile').read(),
  89. 'image/jpeg'),
  90. 'nonamefile': 'contents of nonamefile field',
  91. }
  92. When uploading a file, providing a filename (the first parameter of the
  93. tuple) is optional but recommended to best mimick behavior of browsers.
  94. Note that if ``headers`` are supplied, the 'Content-Type' header will
  95. be overwritten because it depends on the dynamic random boundary string
  96. which is used to compose the body of the request. The random boundary
  97. string can be explicitly set with the ``multipart_boundary`` parameter.
  98. """
  99. if headers is None:
  100. headers = self.headers
  101. extra_kw = {'headers': {}}
  102. if fields:
  103. if 'body' in urlopen_kw:
  104. raise TypeError(
  105. "request got values for both 'fields' and 'body', can only specify one.")
  106. if encode_multipart:
  107. body, content_type = encode_multipart_formdata(fields, boundary=multipart_boundary)
  108. else:
  109. body, content_type = urlencode(fields), 'application/x-www-form-urlencoded'
  110. extra_kw['body'] = body
  111. extra_kw['headers'] = {'Content-Type': content_type}
  112. extra_kw['headers'].update(headers)
  113. extra_kw.update(urlopen_kw)
  114. return self.urlopen(method, url, **extra_kw)