首页 > 其他分享 >requests库的常用方法

requests库的常用方法

时间:2023-10-27 14:12:48浏览次数:25  
标签:常用 url object request param kwargs requests 方法 class

requests是python的第三方库

pip3 install requests

 常用的6种方法:

post delete put get 增加、删除、修改、查询 .基于Restful API架构

request session

 

发送get请求

get(url, params=None, **kwargs)

def get(url, params=None, **kwargs):
    r"""Sends a GET request.

    :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 \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response
    """

    return request("get", url, params=params, **kwargs)

 

发送post请求

post(url, data=None, json=None, **kwargs)

def post(url, data=None, json=None, **kwargs):
    r"""Sends a POST request.

    :param url: URL for the new :class:`Request` object.
    :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 \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response
    """

    return request("post", url, data=data, json=json, **kwargs)

发送put请求

put(url, data=None, **kwarge)

def put(url, data=None, **kwargs):
    r"""Sends a PUT request.

    :param url: URL for the new :class:`Request` object.
    :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 \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response
    """

    return request("put", url, data=data, **kwargs)

 

delete(url, **kwargs)

def delete(url, **kwargs):
    r"""Sends a DELETE request.

    :param url: URL for the new :class:`Request` object.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response
    """

    return request("delete", url, **kwargs)

 

---------------------前面四种方法都调用下面request方法-------------------

根据method传参的请求方式发送请求

request(method,url, **kwargs)

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)

 

-------------------------上面request调用的是下面session方法---------------------------------

session

标签:常用,url,object,request,param,kwargs,requests,方法,class
From: https://www.cnblogs.com/may18/p/17792154.html

相关文章

  • 常用hook记录
    1headershook当header中包含Authorization时,则插入断点varcode=function(){varorg=window.XMLHttpRequest.prototype.setRequestHeader;window.XMLHttpRequest.prototype.setRequestHeader=function(key,value){if(key=='Authorization'){debugg......
  • C#入门:如何合理制定方法参数
    1、利用面向对象的原则,将我们面对的功能拆分出相关类2、相同功能只应出现在一个类中。3、相似功能尽量提取其公共部分总的目标可以简化为精减代码量。我们以一个动态条件查询界面来说明一下上面几点 这是一个病案查询功能,左则的列表是所有可供选择的字段,中间是用户要求查询......
  • DSPLearning_dayONE___________matlab实现DTFT里面的一些常用函数以及基本运算
    DSPmatlab实现\(\delta(n)\)的实现%matlab中坐标轴的横坐标和纵坐标是分开表示的n=-10:20;%横坐标的显示范围这个是确定了x轴的坐标范围delta=[zeros(1,10)1zeros(1,20)];%zeros(m,n)产生一个mxn的全零矩阵这个是每个x轴对应的y轴的值stem(n,delta);gridon......
  • stm32cubeide+bootloader跳转的方法和坑点
    网上介绍方法很多,跳转原理可以看这一篇  基于STM32的简易Bootloader实现-JiuLiBlog-博客园(cnblogs.com)大概步骤为:先判断栈顶地址是否合法,再关闭总中断和systick中断,再设置跳转地址、再加载栈顶地址,然后就可以跳转了,跳转后的应用程序需要先设置栈顶地址、再开启之前关闭......
  • 通过requests库使用HTTP编写的爬虫程序
    使用Python的requests库可以方便地编写HTTP爬虫程序。以下是一个使用requests库的示例:importrequests#发送HTTPGET请求response=requests.get("http://example.com")#检查响应状态码ifresponse.status_code==200:#获取响应内容html=response.text......
  • SQL Server常用命令
     --重建索引dbccdbreindex('表名','',90) --清除数据库日志use[数据库]selectFILE_ID,name,size,*fromsys.database_files--查询数据库及日志名称alterdatabase[数据库名称]setrecoverysimplewithno_waitalterdatabase[数据库名称]setrecoverysimple--简......
  • 最近学习到的一些linux的常用命令
    1、ls命令可以列出当前目录下的内容清单。它与windows下的dir命令很像 2、cd命令这个命令可以改变目录cd~  //更改到本用户的主目录cddesktop //更改目录到desktop cd.. //更改目录到上一级 3、管道输出可以把shell命令输出到文件里面ls>somefile.tx......
  • 微信小程序获取用户名和头像方式以及使文本可复制方法
    1.微信小程序获取微信昵称和头像在微信小程序之前的版本可以通过wx.getUserInfo和wx.getUserProfile来获取微信头像和昵称。2022年11月8日24时之后上述两个接口均被微信小程序进行回收。本来以为通过一些其他方式也可以获取到微信头像和昵称,比如设置button组件的open-type为getU......
  • 基于测试数据、测试方法和测试执行的测试用例设计
    测试用例的重要性不言而喻,如何让测试用例设计的更好、更有效是所有测试团队需要深入研究的问题。一般来说,测试用例的设计可以分为三个方向,测试数据的用例设计、测试方法的用例设计和测试执行的用例设计。接下来我们将从这三个方面一一讲解。基于测试数据的测试用例设计边界值分......
  • 振弦式轴力计的埋设安装方法
    GEOAF型振弦式轴力计,又称反力计,是一种振弦式载重传感器,具有分辨力高、抗干扰性能强,对集中载荷反应灵敏、测值可靠和稳定性好等优点,能长期测量基础对上部结构的反力,对钢支撑轴力及静压桩试验时的载荷,并可同步测量埋设点的温度。轴力计的使用场合较多,仪器的工作及施工条件也不完全一......