api.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. """
  2. requests.api
  3. ~~~~~~~~~~~~
  4. This module implements the Requests API.
  5. :copyright: (c) 2012 by Kenneth Reitz.
  6. :license: Apache2, see LICENSE for more details.
  7. """
  8. from __future__ import annotations
  9. from typing import TYPE_CHECKING
  10. from . import sessions
  11. from .models import Response
  12. if TYPE_CHECKING:
  13. from typing_extensions import Unpack
  14. from . import _types as _t
  15. def request(
  16. method: str, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]
  17. ) -> Response:
  18. """Constructs and sends a :class:`Request <Request>`.
  19. :param method: method for the new :class:`Request` object: ``GET``, ``OPTIONS``, ``HEAD``, ``POST``, ``PUT``, ``PATCH``, or ``DELETE``.
  20. :param url: URL for the new :class:`Request` object.
  21. :param params: (optional) Dictionary, list of tuples or bytes to send
  22. in the query string for the :class:`Request`.
  23. :param data: (optional) Dictionary, list of tuples, bytes, or file-like
  24. object to send in the body of the :class:`Request`.
  25. :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
  26. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
  27. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
  28. :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.
  29. ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``
  30. or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content_type'`` is a string
  31. defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers
  32. to add for the file.
  33. :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
  34. :param timeout: (optional) How many seconds to wait for the server to send data
  35. before giving up, as a float, or a :ref:`(connect timeout, read
  36. timeout) <timeouts>` tuple.
  37. :type timeout: float or tuple
  38. :param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``.
  39. :type allow_redirects: bool
  40. :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
  41. :param verify: (optional) Either a boolean, in which case it controls whether we verify
  42. the server's TLS certificate, or a string, in which case it must be a path
  43. to a CA bundle to use. Defaults to ``True``.
  44. :param stream: (optional) if ``False``, the response content will be immediately downloaded.
  45. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
  46. :return: :class:`Response <Response>` object
  47. :rtype: requests.Response
  48. Usage::
  49. >>> import requests
  50. >>> req = requests.request('GET', 'https://httpbin.org/get')
  51. >>> req
  52. <Response [200]>
  53. """
  54. # By using the 'with' statement we are sure the session is closed, thus we
  55. # avoid leaving sockets open which can trigger a ResourceWarning in some
  56. # cases, and look like a memory leak in others.
  57. with sessions.Session() as session:
  58. return session.request(method=method, url=url, **kwargs)
  59. def get(
  60. url: _t.UriType, params: _t.ParamsType = None, **kwargs: Unpack[_t.GetKwargs]
  61. ) -> Response:
  62. r"""Sends a GET request.
  63. :param url: URL for the new :class:`Request` object.
  64. :param params: (optional) Dictionary, list of tuples or bytes to send
  65. in the query string for the :class:`Request`.
  66. :param \*\*kwargs: Optional arguments that ``request`` takes.
  67. :return: :class:`Response <Response>` object
  68. :rtype: requests.Response
  69. """
  70. return request("get", url, params=params, **kwargs)
  71. def options(url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:
  72. r"""Sends an OPTIONS request.
  73. :param url: URL for the new :class:`Request` object.
  74. :param \*\*kwargs: Optional arguments that ``request`` takes.
  75. :return: :class:`Response <Response>` object
  76. :rtype: requests.Response
  77. """
  78. return request("options", url, **kwargs)
  79. def head(url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:
  80. r"""Sends a HEAD request.
  81. :param url: URL for the new :class:`Request` object.
  82. :param \*\*kwargs: Optional arguments that ``request`` takes. If
  83. `allow_redirects` is not provided, it will be set to `False` (as
  84. opposed to the default :meth:`request` behavior).
  85. :return: :class:`Response <Response>` object
  86. :rtype: requests.Response
  87. """
  88. kwargs.setdefault("allow_redirects", False)
  89. return request("head", url, **kwargs)
  90. def post(
  91. url: _t.UriType,
  92. data: _t.DataType = None,
  93. json: _t.JsonType = None,
  94. **kwargs: Unpack[_t.PostKwargs],
  95. ) -> Response:
  96. r"""Sends a POST request.
  97. :param url: URL for the new :class:`Request` object.
  98. :param data: (optional) Dictionary, list of tuples, bytes, or file-like
  99. object to send in the body of the :class:`Request`.
  100. :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
  101. :param \*\*kwargs: Optional arguments that ``request`` takes.
  102. :return: :class:`Response <Response>` object
  103. :rtype: requests.Response
  104. """
  105. return request("post", url, data=data, json=json, **kwargs)
  106. def put(
  107. url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]
  108. ) -> Response:
  109. r"""Sends a PUT request.
  110. :param url: URL for the new :class:`Request` object.
  111. :param data: (optional) Dictionary, list of tuples, bytes, or file-like
  112. object to send in the body of the :class:`Request`.
  113. :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
  114. :param \*\*kwargs: Optional arguments that ``request`` takes.
  115. :return: :class:`Response <Response>` object
  116. :rtype: requests.Response
  117. """
  118. return request("put", url, data=data, **kwargs)
  119. def patch(
  120. url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs]
  121. ) -> Response:
  122. r"""Sends a PATCH request.
  123. :param url: URL for the new :class:`Request` object.
  124. :param data: (optional) Dictionary, list of tuples, bytes, or file-like
  125. object to send in the body of the :class:`Request`.
  126. :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
  127. :param \*\*kwargs: Optional arguments that ``request`` takes.
  128. :return: :class:`Response <Response>` object
  129. :rtype: requests.Response
  130. """
  131. return request("patch", url, data=data, **kwargs)
  132. def delete(url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response:
  133. r"""Sends a DELETE request.
  134. :param url: URL for the new :class:`Request` object.
  135. :param \*\*kwargs: Optional arguments that ``request`` takes.
  136. :return: :class:`Response <Response>` object
  137. :rtype: requests.Response
  138. """
  139. return request("delete", url, **kwargs)