Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

_request_methods.py 7.6KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. from __future__ import annotations
  2. import json as _json
  3. import typing
  4. from urllib.parse import urlencode
  5. from ._base_connection import _TYPE_BODY
  6. from ._collections import HTTPHeaderDict
  7. from .filepost import _TYPE_FIELDS, encode_multipart_formdata
  8. from .response import BaseHTTPResponse
  9. __all__ = ["RequestMethods"]
  10. _TYPE_ENCODE_URL_FIELDS = typing.Union[
  11. typing.Sequence[typing.Tuple[str, typing.Union[str, bytes]]],
  12. typing.Mapping[str, typing.Union[str, bytes]],
  13. ]
  14. class RequestMethods:
  15. """
  16. Convenience mixin for classes who implement a :meth:`urlopen` method, such
  17. as :class:`urllib3.HTTPConnectionPool` and
  18. :class:`urllib3.PoolManager`.
  19. Provides behavior for making common types of HTTP request methods and
  20. decides which type of request field encoding to use.
  21. Specifically,
  22. :meth:`.request_encode_url` is for sending requests whose fields are
  23. encoded in the URL (such as GET, HEAD, DELETE).
  24. :meth:`.request_encode_body` is for sending requests whose fields are
  25. encoded in the *body* of the request using multipart or www-form-urlencoded
  26. (such as for POST, PUT, PATCH).
  27. :meth:`.request` is for making any kind of request, it will look up the
  28. appropriate encoding format and use one of the above two methods to make
  29. the request.
  30. Initializer parameters:
  31. :param headers:
  32. Headers to include with all requests, unless other headers are given
  33. explicitly.
  34. """
  35. _encode_url_methods = {"DELETE", "GET", "HEAD", "OPTIONS"}
  36. def __init__(self, headers: typing.Mapping[str, str] | None = None) -> None:
  37. self.headers = headers or {}
  38. def urlopen(
  39. self,
  40. method: str,
  41. url: str,
  42. body: _TYPE_BODY | None = None,
  43. headers: typing.Mapping[str, str] | None = None,
  44. encode_multipart: bool = True,
  45. multipart_boundary: str | None = None,
  46. **kw: typing.Any,
  47. ) -> BaseHTTPResponse: # Abstract
  48. raise NotImplementedError(
  49. "Classes extending RequestMethods must implement "
  50. "their own ``urlopen`` method."
  51. )
  52. def request(
  53. self,
  54. method: str,
  55. url: str,
  56. body: _TYPE_BODY | None = None,
  57. fields: _TYPE_FIELDS | None = None,
  58. headers: typing.Mapping[str, str] | None = None,
  59. json: typing.Any | None = None,
  60. **urlopen_kw: typing.Any,
  61. ) -> BaseHTTPResponse:
  62. """
  63. Make a request using :meth:`urlopen` with the appropriate encoding of
  64. ``fields`` based on the ``method`` used.
  65. This is a convenience method that requires the least amount of manual
  66. effort. It can be used in most situations, while still having the
  67. option to drop down to more specific methods when necessary, such as
  68. :meth:`request_encode_url`, :meth:`request_encode_body`,
  69. or even the lowest level :meth:`urlopen`.
  70. """
  71. method = method.upper()
  72. if json is not None and body is not None:
  73. raise TypeError(
  74. "request got values for both 'body' and 'json' parameters which are mutually exclusive"
  75. )
  76. if json is not None:
  77. if headers is None:
  78. headers = self.headers.copy() # type: ignore
  79. if not ("content-type" in map(str.lower, headers.keys())):
  80. headers["Content-Type"] = "application/json" # type: ignore
  81. body = _json.dumps(json, separators=(",", ":"), ensure_ascii=False).encode(
  82. "utf-8"
  83. )
  84. if body is not None:
  85. urlopen_kw["body"] = body
  86. if method in self._encode_url_methods:
  87. return self.request_encode_url(
  88. method,
  89. url,
  90. fields=fields, # type: ignore[arg-type]
  91. headers=headers,
  92. **urlopen_kw,
  93. )
  94. else:
  95. return self.request_encode_body(
  96. method, url, fields=fields, headers=headers, **urlopen_kw
  97. )
  98. def request_encode_url(
  99. self,
  100. method: str,
  101. url: str,
  102. fields: _TYPE_ENCODE_URL_FIELDS | None = None,
  103. headers: typing.Mapping[str, str] | None = None,
  104. **urlopen_kw: str,
  105. ) -> BaseHTTPResponse:
  106. """
  107. Make a request using :meth:`urlopen` with the ``fields`` encoded in
  108. the url. This is useful for request methods like GET, HEAD, DELETE, etc.
  109. """
  110. if headers is None:
  111. headers = self.headers
  112. extra_kw: dict[str, typing.Any] = {"headers": headers}
  113. extra_kw.update(urlopen_kw)
  114. if fields:
  115. url += "?" + urlencode(fields)
  116. return self.urlopen(method, url, **extra_kw)
  117. def request_encode_body(
  118. self,
  119. method: str,
  120. url: str,
  121. fields: _TYPE_FIELDS | None = None,
  122. headers: typing.Mapping[str, str] | None = None,
  123. encode_multipart: bool = True,
  124. multipart_boundary: str | None = None,
  125. **urlopen_kw: str,
  126. ) -> BaseHTTPResponse:
  127. """
  128. Make a request using :meth:`urlopen` with the ``fields`` encoded in
  129. the body. This is useful for request methods like POST, PUT, PATCH, etc.
  130. When ``encode_multipart=True`` (default), then
  131. :func:`urllib3.encode_multipart_formdata` is used to encode
  132. the payload with the appropriate content type. Otherwise
  133. :func:`urllib.parse.urlencode` is used with the
  134. 'application/x-www-form-urlencoded' content type.
  135. Multipart encoding must be used when posting files, and it's reasonably
  136. safe to use it in other times too. However, it may break request
  137. signing, such as with OAuth.
  138. Supports an optional ``fields`` parameter of key/value strings AND
  139. key/filetuple. A filetuple is a (filename, data, MIME type) tuple where
  140. the MIME type is optional. For example::
  141. fields = {
  142. 'foo': 'bar',
  143. 'fakefile': ('foofile.txt', 'contents of foofile'),
  144. 'realfile': ('barfile.txt', open('realfile').read()),
  145. 'typedfile': ('bazfile.bin', open('bazfile').read(),
  146. 'image/jpeg'),
  147. 'nonamefile': 'contents of nonamefile field',
  148. }
  149. When uploading a file, providing a filename (the first parameter of the
  150. tuple) is optional but recommended to best mimic behavior of browsers.
  151. Note that if ``headers`` are supplied, the 'Content-Type' header will
  152. be overwritten because it depends on the dynamic random boundary string
  153. which is used to compose the body of the request. The random boundary
  154. string can be explicitly set with the ``multipart_boundary`` parameter.
  155. """
  156. if headers is None:
  157. headers = self.headers
  158. extra_kw: dict[str, typing.Any] = {"headers": HTTPHeaderDict(headers)}
  159. body: bytes | str
  160. if fields:
  161. if "body" in urlopen_kw:
  162. raise TypeError(
  163. "request got values for both 'fields' and 'body', can only specify one."
  164. )
  165. if encode_multipart:
  166. body, content_type = encode_multipart_formdata(
  167. fields, boundary=multipart_boundary
  168. )
  169. else:
  170. body, content_type = (
  171. urlencode(fields), # type: ignore[arg-type]
  172. "application/x-www-form-urlencoded",
  173. )
  174. extra_kw["body"] = body
  175. extra_kw["headers"].setdefault("Content-Type", content_type)
  176. extra_kw.update(urlopen_kw)
  177. return self.urlopen(method, url, **extra_kw)