接口自动化之request模块

1、安装

  • 方式一、命令行直接 pip install requests
  • 方式二、PyCharm中,File >> Settings >> Project:Practice >> Python Interpreter,点击+号,搜索requests,点击Install Package。

2、常用的方法

请求方式

  • requests.get() # 发送GET请求
  • requests.post() # 发送POST请求
  • requests.delete() # 发送DELETE请求
  • requests.put() # 发送PUT请求
  • requests.request() # 核心方法

返回类型

  • res = requests.request()
  • res.text # 返回字符串数据
  • res.content # 返回字节格式数据
  • res.json() # 返回字典格式数据
  • res.status_code # 返回状态码
  • res.cookies # 返回Cookie信息
  • res.reason # 返回状态信息
  • res.encoding # 返回编码格式
  • res.headers # 返回响应头信息

核心方法-request()

通过查看python的源码,可以看到Get请求和Post请求,实际上都是去调用request()发送请求。

# Get请求
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请求
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) json data 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)

3、接口实战

本文中的接口示例全部来自微信公众开发平台,详细的请直接参考官网
https://developers.weixin.qq.com/doc/offiaccount/Getting_Started/Overview.html

发送GET请求

import requests

# 发送GET请求
url = "https://api.weixin.qq.com/cgi-bin/token"
data = {
    "grant_type": "client_credential",
    "appid": "wx1369184acdfe****",
    "secret": "34b1eb5f6ed2aa8a2ef3333bac63****"
}

res = requests.get(url=url, params=data)
print(res.json())

发送GET请求

import requests

# 发送GET请求
url = "https://api.weixin.qq.com/cgi-bin/token"
data = {
    "grant_type": "client_credential",
    "appid": "wx1369184acdfe****",
    "secret": "34b1eb5f6ed2aa8a2ef3333bac63****"
}
res = requests.get(url=url, params=data)
print(res.json())
access_token = res.json()["access_token"]
print(access_token)
# post请求
url = "https://api.weixin.qq.com/cgi-bin/clear_quota?access_token=" + access_token + ""

data = {
    "appid": "wx1369184acdfe****"
}
res = requests.post(url=url, json=data)
print(res.json())

posted @ 2022-12-31 15:17  cavan丶keke  阅读(133)  评论(0编辑  收藏  举报