Requests教程-2-源码解析

发布时间:2024年01月08日

上一小节中,我们完成了requests库的环境搭建,并且了解了如何使用requests发送接口请求,本节中我们对requests发送请求的源码进行分析。

首先明确一点,requests发送请求,其实是内部调用了requests.request方法,如下图,按住ctrl键盘点击request方法即可进入该方法的源码。

源码如下:

def request(method, url, **kwargs):
    """Constructs and sends a :class:`Request <Request>`.

    :param method: method for the new :class:`Request` object: ``GET``, ``OPTIONS``, ``HEAD``, ``POST``, ``PUT``, ``PATCH``, or ``DELETE``.
    :param url: URL for the new :class:`Request` object.
    :param params: (optional) Dictionary, list of tuples or bytes to send
        in the query string for the :class:`Request`.
    :param data: (optional) Dictionary, list of tuples, bytes, or file-like
        object to send in the body of the :class:`Request`.
    :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
    :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
    :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
    :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.
        ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``
        or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string
        defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers
        to add for the file.
    :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
    :param timeout: (optional) How many seconds to wait for the server to send data
        before giving up, as a float, or a :ref:`(connect timeout, read
        timeout) <timeouts>` tuple.
    :type timeout: float or tuple
    :param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``.
    :type allow_redirects: bool
    :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
    :param verify: (optional) Either a boolean, in which case it controls whether we verify
            the server's TLS certificate, or a string, in which case it must be a path
            to a CA bundle to use. Defaults to ``True``.
    :param stream: (optional) if ``False``, the response content will be immediately downloaded.
    :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response

    Usage::

      >>> import requests
      >>> req = requests.request('GET', 'https://httpbin.org/get')
      >>> req
      <Response [200]>
    """

    # By using the 'with' statement we are sure the session is closed, thus we
    # avoid leaving sockets open which can trigger a ResourceWarning in some
    # cases, and look like a memory leak in others.
    with sessions.Session() as session:
        return session.request(method=method, url=url, **kwargs)

上面的源码注释部分,param表示该方法的入参种类,接下来我们具体分析一下, request方法这15个入参分别代表什么含义,后续编写接口请求时,做到心中有数。

  • method: 表示接口请求方式 ,常见的有get/post/put/delete 等
  • url :表示接口请求的 url 地址
  • params:表示接口请求数据,常用于get请求中,数据放在url中
  • data :表示接口请求数据,数据格式为表单,常用于post请求
  • json:表示接口请求数据,数据格式为json,常用于post请求
  • headers: 表示接口请求头信息,http请求中,比如说编码方式等内容添加
  • cookie :表示保存的用户个人信息,如登录信息
  • file: 表示上传文件接口中需要传该参数信息
  • auth :表示鉴权的意思,接口设置操作权限
  • timeout :表示超时处理 ,可设置超时时间
  • proxys:表示设置代理
  • allow_redirects :表示重定向,请求不成功,再次请求
  • verify :证书验证 1、要么请求忽略证书,2、要么加载证书地址
  • stream :表示下载文件接口中需要传该参数信息
  • cert :表示CA证书参数
文章来源:https://blog.csdn.net/qq_22357323/article/details/135337369
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。