Python教程(十四):Requests模块详解

专栏列表


在这里插入图片描述

正文开始如果觉得文章对您有帮助,请帮我三连+订阅,谢谢💖💖💖


前言:

Requests 是一个Python第三方库,用于发送HTTP请求。它以简单易用而著称,隐藏了HTTP协议的复杂性,让开发者能够用很少的代码完成HTTP请求的发送和处理:

安装 Requests

首先,你需要安装Requests库(如果你还没有安装的话)。可以通过自带的 pip 命令来安装:

pip install requests

在这里插入图片描述

查看包安装情况:

  • 可以使用已下命令:
pip show requests
# or
pip list 

在这里插入图片描述

RESTful 介绍

RESTful API设计原则

  • 使用HTTP方法GET用于获取资源,POST用于创建资源,PUT用于更新资源,DELETE用于删除资源。
  • 使用URI:资源的标识符,例如/users/{userId}
  • 使用状态码:例如200表示成功,404表示未找到,500表示服务器错误等。
  • 使用JSON或XML:作为数据交换格式。
  • 避免使用动词:所有的操作都应该通过HTTP方法和URI来表达,而不是通过URI中的动词。
  • 使用集合和文档:集合是资源的集合,文档是单个资源的表示。

示例

假设有一个用户资源,RESTful API可能如下:

  • 获取用户列表:GET /users
  • 获取单个用户信息:GET /users/{userId}
  • 创建新用户:POST /users
  • 更新用户信息:PUT /users/{userId}
  • 删除用户:DELETE /users/{userId}

基本用法

安装完成后,你可以开始使用Requests发送HTTP请求了。接下来我们将使用一个在线的RestfulAPI 进行实例使用,完成对用户信息的增删查改:

jsonplaceholder.typicode.com 是一个免费的在线REST API,用于测试和原型设计。它提供了一组JSON资源,包括用户、帖子、评论等,允许你执行CRUD(创建、读取、更新、删除)操作。

1. 查询ID为1的用户(GET)

查询用户的示例:

import requests
import json

# API URL
url = 'https://jsonplaceholder.typicode.com/users/1'

# 发送GET请求
response = requests.get(url)

# 检查请求是否成功
if response.status_code == 200:
	# 打印响应内容
    #print(response.text)
    # 将响应内容解析为JSON
    user = response.json()
    print("查询到的用户信息:")
    print(json.dumps(user, indent=4)) # 格式化json数据
else:
    print("请求失败,状态码:", response.status_code)

在这里插入图片描述

2. 创建新用户(POST)

创建新用户的示例:

import requests
import json

# 用户数据
new_user = {
    "name": "张三",
    "username": "zhangsan",
    "email": "zhangsan@example.com"
}

# 发送POST请求
response = requests.post('https://jsonplaceholder.typicode.com/users', json=new_user)

# 检查请求是否成功
if response.status_code == 201:
    created_user = response.json()  # 获取创建后的用户信息
    print("创建的用户信息:")
    print(json.dumps(created_user, indent=4))
else:
    print("创建失败,状态码:", response.status_code)

在这里插入图片描述

3. 更新ID 为 1 的用户(PUT)

更新用户的示例:

import requests
import json

# 更新的用户数据
updated_user = {
    "name": "张三",
    "username": "zhangsan_updated",
    "email": "zhangsan_updated@example.com"
}

# 发送PUT请求
response = requests.put('https://jsonplaceholder.typicode.com/users/1', json=updated_user)

# 检查请求是否成功
if response.status_code == 200:
    updated_user_info = response.json()  # 获取更新后的用户信息
    print("更新后的用户信息:")
    print(json.dumps(updated_user_info, indent=4))
else:
    print("更新失败,状态码:", response.status_code)

在这里插入图片描述

4. 删除ID 为 1 的用户(DELETE)

删除用户的示例:

# 发送DELETE请求
response = requests.delete('https://jsonplaceholder.typicode.com/users/1')

# 检查请求是否成功
if response.status_code == 200:
    print("用户删除成功")
else:
    print("删除失败,状态码:", response.status_code)

在这里插入图片描述

  • jsonplaceholder.typicode.com API是只读的,意味着实际上你不能通过POST、PUT或DELETE请求来创建、更新或删除数据。这些请求会返回错误或不执行任何操作。
  • 上述示例中的POST、PUT和DELETE操作仅用于演示requests模块如何使用,实际上不会对jsonplaceholder的数据产生影响。
  • 通过这些示例,你可以了解如何使用Python的requests模块来发送HTTP请求,并处理响应。

响应对象

Requests返回的Response对象包含了服务器响应的所有信息,包括:

  • status_code: 响应的状态码。
  • text: 响应的文本内容。
  • json(): 解析JSON响应的方法。
  • headers: 响应的HTTP头部。
  • url: 请求的URL。

会话(Session)

Requests还支持会话(Session),它允许你共享某些行为和参数跨多个请求。这包括cookies、headers等。


import requests

# 创建一个Session对象
session = requests.Session()

# 假设我们首先访问一个页面,该页面设置了一个cookie
# httpbin.org/cookies 会返回一个设置了cookie的响应
set_cookie_url = 'https://httpbin.org/cookies/set?sessioncookie=test'

# 发送GET请求,服务器将设置cookie
response = session.get(set_cookie_url)

# 打印Session中的所有cookie
print("Session中的Cookie:")
for cookie in session.cookies:
    print(cookie.name, cookie.value)

# 现在访问另一个页面,Session会自动携带cookie
headers_url = 'https://httpbin.org/headers'

# 发送GET请求,查看请求头中的cookie
response = session.get(headers_url)
print("\n受保护页面的响应中的Cookie:")
print(f'返回的header {response.text}') 
print(f'cookie:{response.json()['headers']['Cookie']}')  # 打印服务器接收到的Cookie

在这里插入图片描述

异常处理

Requests使用异常来指示请求出现问题的地方,我们以获取用户信息为例

import requests
import json

# API URL
url = 'https://jsonplaceholder.typicode.com/users/1'

try:
    # 发送GET请求
    response = requests.get(url)
    # 检查请求是否成功
    if response.status_code == 200:
        user = response.json()  # 将响应内容解析为JSON
        print("查询到的用户信息:")
        print(json.dumps(user, indent=4))
    else:
        print("请求失败,状态码:", response.status_code)
except requests.exceptions.Timeout:
    print("请求超时")
except requests.exceptions.HTTPError as err:
    print(f"HTTP错误: {err}")
except requests.exceptions.RequestException as err:
    print(f"请求出错: {err}")

高级用法

Requests还支持一些高级用法,如:

  • 流式上传和下载。
  • 处理重定向。
  • 使用代理。
  • 请求超时设置。

流式上传

with open('file.txt', 'rb') as f:
    response = requests.post('https://httpbin.org/post', data=f)

处理重定向

response = requests.get('http://github.com', allow_redirects=True)
print(response.status_code)  # 应该不再是302

使用代理

proxies = {
    'http': 'http://10.10.1.10:3128',
    'https': 'http://10.10.1.10:1080',
}

response = requests.get('http://example.com', proxies=proxies)

请求超时

  • 通过设置 timeout 参数限制,单位为秒
response = requests.get('https://api.github.com', timeout=0.01)

总结:

Requests库的易用性和强大功能使其成为Python开发者进行HTTP请求的首选库之一。通过上述示例,你可以看到Requests的灵活性和表达能力。

评论 108
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

子羽bro

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值