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)

Requests接口测试库-官网快速上手的更多相关文章

  1. Python第三方库官网

    Python第三方库官网 https://pypi.python.org/pypi 包下载后的处理: 下载后放到Python的scripts文件夹中(D:\Python3.5\Scripts),用cm ...

  2. 几个比較好的IT站和开发库官网

    几个比較好的IT站和开发库官网 1.IT技术.项目类站点 (1)首推CodeProject,一个国外的IT站点,官网地址为:http://www.codeproject.com,这个站点为程序开发人员 ...

  3. 几个比较好的IT站和开发库官网

    1.IT技术.项目类网站 (1)首推CodeProject,一个国外的IT网站,官网地址为:http://www.codeproject.com,这个网站为程序开发者提供了很好的代码示例以及讲解,不过 ...

  4. 【转】Requests 官方中文文档 - 快速上手

    迫不及待了吗?本页内容为如何入门 Requests 提供了很好的指引.其假设你已经安装了 Requests.如果还没有,去安装一节看看吧. 首先,确认一下: Requests 已安装 Requests ...

  5. 微信小程序UI组件库 iView Weapp快速上手

    概述 今天在网上突然看到iView新出了一个微信小程序的组件库iView Weapp,自己就上手试了一下,发现用起来还是不错的,把自己使用的过程与大家分享下. 一 预览iView组件 1.可以在手机上 ...

  6. 【Python】【有趣的模块】【requests】【二】快速上手

    [一]参数及结果 [二]响应内容 >>> r = requests.get('https://github.com/timeline.json') >>> prin ...

  7. Quartz.NET快速上手第一课(官网文档翻译)

    Quartz.NET快速上手第一课(官网文档翻译) 原文链接 在你使用调度者(scheduler)之前,你需要对它进行实例化(谁能猜到这呢?).在实例化scheduler时候,你需要使用ISchedu ...

  8. requests库的文档--快速上手

    快速上手 迫不及待了吗?本页内容为如何入门 Requests 提供了很好的指引.其假设你已经安装了 Requests.如果还没有,去安装一节看看吧. 首先,确认一下: Requests 已安装 Req ...

  9. Requests快速上手

    发送请求 使用 Requests 发送网络请求非常简单. 一开始要导入 Requests 模块: >>> import requests 然后,尝试获取某个网页.本例子中,我们来获取 ...

随机推荐

  1. MobileNetV1/V2/V3简述 | 轻量级网络

    MobileNet系列很重要的轻量级网络家族,出自谷歌,MobileNetV1使用深度可分离卷积来构建轻量级网络,MobileNetV2提出创新的inverted residual with line ...

  2. 谈谈你对 TCP 三次握手和四次挥手的理解

    TCP三次握手: 1.客户端发送syn包到服务器,等待服务器确认接收. 2.服务器确认接收syn包并确认客户的syn,并发送回来一个syn+ack的包给客户端. 3.客户端确认接收服务器的syn+ac ...

  3. 使用命名管道承载gRPC

    最近GRPC很火,感觉整RPC不用GRPC都快跟不上时髦了. gRPC设计 刚好需要使用一个的RPC应用系统,自然而然就盯上了它,但是它真能够解决所有问题吗?不见得,先看看他的优点: gRPC是一种与 ...

  4. python 输出日志到文件和控制台

    import logging # 第一步,创建一个logger logger = logging.getLogger() logger.setLevel(logging.INFO) # Log等级总开 ...

  5. Configurate vim tool

    vim tool is a commom editor, for the sake of improving effeicient, it is necessary to configurate vi ...

  6. Ethical Hacking - Web Penetration Testing(12)

    XSS VULNS XSS - CROSS SITE SCRIPTING VULNS Allow an attacker to inject javascript code into the page ...

  7. Oracle DataGuard主库丢失归档日志后备库的RMAN增量恢复一例

    第一部分  问题描述和环境状态确认 ----1. 问题场景 Oracle DataGuard主库丢失archivelog,如何不重建备库完成同步? 在Oracle DataGuard主从同步过程中可能 ...

  8. P2070 刷墙 (洛谷)

    题目描述 Farmer John已经设计了一种方法来装饰谷仓旁边的长栅栏(把栅栏认为是一根一维的线).他把一只画刷绑在他最喜爱的奶牛Bessie身上,之后就去喝一杯冰水,而Bessie隔着栅栏来回走, ...

  9. 一个牛逼的FTP——Wring Ftp

    背景:总公司内网有一部分文档需要共享,想要一个能便捷管理的文档系统 需求:分帐号授权,有的帐号只能看,有的帐号只能新增,有的帐号可以增删改查,另外可以便捷的对帐号进行管理 方法: 一.Wing Ftp ...

  10. ajax异步上传图片&SpringMVC后台代码

    function uploadPic(){ var options = { url : "/upload/updatePic.action", type : "post& ...