• Requests接口测试库-官网快速上手


    Requests

    一个发送HTTP请求的库基于urllib3,相比自带的库,提供了更高效简洁的可用方法,测试从业者用来做接口测试的一个好工具

    文章内容均来自官网:https://requests.readthedocs.io/zh_CN/latest/

    安装

    • pip install requests

    发送请求

    • requests.request()与requests.get 不同的地方是 requests.request(),需要指定参数内指定method=请求方式(get/post/put/delete...)

    • get请求- 不带查询参数

      import requests
      
      # 使用request发送get请求
      res = requests.request(method="get", url='https://api.github.com/')
      print(res.text)
      
      
      # 使用get发送get请求
      res = requests.get(url='https://api.github.com/')
      print(res.text)
      
    • post请求

      import requests
      
      # 使用post发送请求,post需要传递一个请求参数,使用 data, 或者json
      res = requests.request(method="post", url='http://httpbin.org/post', data={'key': 'value'})
      print(res.text)
      
      res = requests.post(url='http://httpbin.org/post', json={'key1': 'value1'})
      print(res.text)
      
    • 其他请求实例

      import requests
      
      # 其他请求, put 请求也可以传递data  或者json
      res = requests.put(url='http://httpbin.org/put', data={'key': 'value'})
      res = requests.delete(url='http://httpbin.org/delete')
      res = requests.head(url='http://httpbin.org/get')
      res = requests.options(url='http://httpbin.org/get')
      

    传递URL参数

    带参数的get请求,其中使用params(推荐)关键字传递参数,data关键字有时候不行,我也不知道为什么,如果你知道,也可以告诉我,谢谢

    带查询参数的URL:http://httpbin.org/get?key=val其中之后是查询参数,key=val是一个键值对如果有多个中间需要使用&进行连接例如:http://httpbin.org/get?key=val&name=jobi

    import requests
    
    # 带参数的get请求 , 最终请求的地址大概如下,http://httpbin.org/get?key1=value1&key2=value2&key2=value3
    res = requests.request(method='get', url='http://httpbin.org/get', params={'key1': 'value1', 'key2': ['value2', 'value3']})
    print(res.text)
    

    响应内容

    当requests发送了get、post...请求之后 会得到一个响应的实例(<class 'requests.models.Response'>),下方的response只是一个响应实例的变量名称,请知悉

    • response.text:以字符串形式返回响应的body内容
    • response.json(): 以json形式返回响应的body内容
    • response.content: 以字节的形式访问请求响应内容(下载文件使用)
    • response.status_code: 返回响应的HTTP状态码
    • response.encoding: 返回响应使用的字符编码
    • response.url: 返回请求使用的完整url地址
    • response.headers: 返回响应头header信息
    • response.is_redirect: 检查是否重定向(重定向的状态码是302)
    • response.raise_for_status():发送错误请求,使用这个方法抛出异常
    • response.cookies: 返回一个cookie字典
    • response.history: 追踪重定向
    import requests
    
    # 带参数的get请求 , 最终请求的地址大概如下,http://httpbin.org/get?key1=value1&key2=value2&key2=value3
    res = requests.request(method='get', url='http://httpbin.org/get', params={'key1': 'value1', 'key2': ['value2', 'value3']})
    
    print(res.text)
    print(res.json())
    print(res.url)
    

    定制请求头

    部分网站,通过请求头来判断是否是合法用户,这时候就需要用到关键字参数 headers

    注意: 定制 header 的优先级低于某些特定的信息源,例如:

    • 如果在 .netrc 中设置了用户认证信息,使用 headers= 设置的授权就不会生效。而如果设置了 auth= 参数,.netrc 的设置就无效了。
    • 如果被重定向到别的主机,授权 header 就会被删除。
    • 代理授权 header 会被 URL 中提供的代理身份覆盖掉。
    • 在我们能判断内容长度的情况下,header 的 Content-Length 会被改写。
    import requests
    
    # 定制请求头
    headers = {'user-agent': 'my-app/0.0.1'}
    res = requests.get(url='https://api.github.com/some/endpoint', headers=headers)
    print(res.text)
    

    POST上传文件

    如果你发送一个非常大的文件作为 multipart/form-data 请求,你可能希望将请求做成数据流。默认下 requests 不支持, 但有个第三方包 requests-toolbelt 是支持的。你可以阅读 toolbelt 文档 来了解使用方法。

    在一个请求中发送多文件参考 高级用法 一节。

    import requests
    
    # POST上传文件
    url = 'http://httpbin.org/post'
    files = {'file': open('no_lock.py', 'rb')}
    
    res = requests.post(url=url, files=files)
    print(res.text)
    
    # 设置文件名,文件类型和请求头
    files = {'file': ('示例文件.xlsx', open('demo.xlsx', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
    res = requests.post(url=url, files=files)
    print(res.text)
    

    Cookie

    保持登录权限访问的方式之一,登录后获取到cookie,其他请求携带cookie就会被认为是有效用户,否则将无法访问,发送请求时需要使用到关键字参数 cookies

    # cookie
    url = 'http://httpbin.org/cookies'
    cookies = dict(cookies_are='working')
    res = requests.get(url, cookies=cookies)
    print(res.text)
    
    # RequestsCookieJar
    
    jar = requests.cookies.RequestsCookieJar()
    # 访问 http://httpbin.org/cookies时的cookie是 tasty_cookie = yum
    jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')
    # 访问 http://httpbin.org/elsewhere 时的cookie是 gross_cookie = blech
    jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')
    
    res = requests.get(url='http://httpbin.org/cookies', cookies=jar)
    print(res.text)
    

    重定向与请求历史

    默认情况下,除了 HEAD, Requests 会自动处理所有重定向。

    可以使用响应对象的 history 方法来追踪重定向。

    Response.history 是一个 Response 对象的列表,为了完成请求而创建了这些对象。这个对象列表按照从最老到最近的请求进行排序。

    使用的是GET、OPTIONS、POST、PUT、PATCH 或者 DELETE,那么你可以通过 allow_redirects 参数禁用重定向处理:

    import requests
    
    res = requests.get(url='http://github.com', allow_redirects=False)
    print(res.history)
    
    res = requests.head(url='http://github.com', allow_redirects=True)
    print(res.history)
    

    超时

    通过设置timeout关键字参数,控制在设定的秒数后停止等待响应,官方建议所有生产代码都应该使用这个参数,避免程序永远失去响应

    timeout 仅对连接过程有效,与响应体的下载无关。 timeout 并不是整个下载响应的时间限制,而是如果服务器在 timeout 秒内没有应答,将会引发一个异常(更精确地说,是在 timeout 秒内没有从基础套接字上接收到任何字节的数据时)If no timeout is specified explicitly, requests do not time out.

    import requests
    res = requests.get('http://github.com', timeout=0.001)
    
    作者:zy7y
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    3月2日 学习记录
    2月10日 体温APP开发总结
    2月8日 体温APP开发记录
    2月5日 体温APP开发记录
    2月4日 体温APP开发记录
    2月3日 体温APP开发记录
    2月2日 体温APP开发记录
    2月1日 体温APP开发记录
    Java并发编程之synchronized详解(锁优化、锁升级)
    mysql 中关于获取行号@rownum:=@rownum+1 需要进一步了解
  • 原文地址:https://www.cnblogs.com/zy7y/p/13356204.html
Copyright © 2020-2023  润新知