上一小节中,我么已经掌握了requests发送post请求的方法,本小节我们讲解一下requests的put请求的使用方法。
首先我们需要了解一下requests.put方法的源码,代码如下:
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)
上图所示put方法有3个入参,1个return函数,返回一个request方法的调用。
url:代表接口请求的url
data: 一般代表表单数据即字典格式,也可以是json/xmL等文本格式
**kwargs:代表接口请求可选参数,是一种key-value键值对参数,比如在接口请求中添加请求头信息headers="xxxx"
put请求通常用于更新已有资源。在接口自动化测试中,我们可以使用 put请求来修改已有资源,下面是一个使用 requests 发送 put 请求的例子。
import requests
data = {'title': 'foo', 'body': 'bar', 'userId': 1}
response = requests.put('https://jsonplaceholder.typicode.com/posts/1', data=data)
print(response.status_code)
print(response.json())
注:这段代码向 https://jsonplaceholder.typicode.com/posts/1 发送了一个 put 请求,并提交一个json数据。与 post请求相似,put() 方法也可以使用 data 参数来指定请求体的内容。
最后感谢每一个认真阅读我文章的人,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走,希望可以帮助到大家!