requests模块

非常优秀的第三方请求模块,支持多种HTTP请求方式,在开发中经常用来做单元测试,在数据获取中经常用来做爬虫。

  • 安装 sudo pip3 install requests
# 常用方法
# url : 请求URL地址
# json = {} :请求体数据
# headers = {} :请求头 {"authorization": "xxxxxxx"}

requests.get(url="http://www.baidu.com/", headers={})
requests.post(url="URL地址", json={} , headers={})
requests.put(url="URL地址", json={}, headers={})
requests.delete(url="URL地址", json={}, headers={})
  • POST测试登录功能
"""
    测试达达商城登录功能
    请求地址:http://127.0.0.1:8000/v1/tokens
    请求方式:POST
    请求体: {"username":xxx, "password":xxx, "carts":xx}
"""

import requests

url = "http://127.0.0.1:8000/v1/tokens"
data = {
    "username": "zhaoliying",
    "password": "123456",
    "carts": 0
}

resp = requests.post(url=url, json=data)

print(resp.json())
  • GET测试地址查询功能
import requests


url = "http://127.0.0.1:8000/v1/users/zhaoliying/address"
headers = {
    "authorization": "自己的token",
}

html = requests.get(url=url, headers=headers).json()
print(html)
  • DELETE请求测试地址删除功能
import requests


url = "http://127.0.0.1:8000/v1/users/zhaoliying/address/3"
data = {"id": "3"}
headers = {
    "authorization": "自己的token",
}

html = requests.delete(url=url, json=data, headers=headers).json()
print(html)