虽然说它主要是给前端做练习的hh,不过AI时代总是要用别人的api哈哈,练一练也好
import requests # 导入requests模块,用于进行HTTP请求
"""
此代码演示如何使用reqres.in API进行各种RESTful操作。
"""
class AdvancedReqResAPI:
# 定义API的基础URL,这样我们可以在整个类中重复使用它
BASE_URL = "https://reqres.in/api"
def __init__(self):
"""构造函数,当我们创建类的实例时会自动调用"""
# 初始化一个Session对象,这个Session可以在多个请求之间保持状态(如登录状态、cookies等)
# 这与浏览器的工作方式类似,浏览器会在多个请求中保存你的登录状态
self.session = requests.Session()
def login(self, email, password):
"""使用邮箱和密码进行登录,并从API响应中获取token"""
# 定义登录的完整URL
url = f"{self.BASE_URL}/login"
# 定义登录请求所需的数据
payload = {
"email": email,
"password": password
}
# 使用session发送POST请求进行登录
response = self.session.post(url, json=payload)
# 检查响应状态码和响应内容中是否包含token
if response.status_code == 200 and "token" in response.json():
# 从响应中提取token
token = response.json()["token"]
# 将token设置为session的headers中,这样后续的请求都会自动带上这个token进行认证
self.session.headers.update({"Authorization": f"Bearer {token}"})
return token
# 如果登录失败,则返回None
return None
def all_users(self):
"""获取所有用户信息的生成器"""
page = 1
while True:
users = self.fetch_users(page)
if not users:
break
for user in users:
# yield关键字用于定义生成器函数,每次调用next()时会返回一个值
yield user
page += 1
def fetch_users(self, page=1):
"""根据指定的页面号获取用户列表"""
url = f"{self.BASE_URL}/users?page={page}"
try:
# 使用session发送GET请求获取用户信息
response = self.session.get(url)
if response.status_code == 200:
# 如果请求成功,返回用户数据
return response.json()['data']
return []
except requests.RequestException as e:
# 如果发生任何请求错误,打印错误并返回空列表
print(f"Error fetching users: {e}")
return []
def create_users(self, name, job):
"""创建新用户"""
url = f"{self.BASE_URL}/users"
payload = {
"name": name,
"job": job
}
try:
response = self.session.post(url, json=payload)
if response.status_code == 201:
return response.json()
return None
except requests.RequestException as e:
print(f"Error creating user: {e}")
return None
def update_users(self, user_id, name, job):
"""更新特定ID的用户信息"""
url = f"{self.BASE_URL}/users/{user_id}"
payload = {
"name": name,
"job": job
}
try:
response = self.session.put(url, json=payload)
if response.status_code == 200:
return response.json()
return None
except requests.RequestException as e:
print(f"Error updating user with ID {user_id}: {e}")
return None
def delete_users(self, user_id):
"""删除特定ID的用户"""
url = f"{self.BASE_URL}/users/{user_id}"
try:
response = self.session.delete(url)
return response.status_code == 204
except requests.RequestException as e:
print(f"Error deleting user with ID {user_id}: {e}")
return False
# 使用示例
import json
from pprint import pprint
api = AdvancedReqResAPI()
token = api.login("[email protected]", "cityslicka")
if token:
print("登陆成功!")
for user in api.all_users():
pprint(user)
else:
print("登陆失败。")
# C - Create a new user
new_user = api.create_users("Tom", "Developer")
print("Created user:")
pprint(new_user)
# R - Read users
users = api.fetch_users()
print("User List:")
pprint(users)
# R - Read a specific user
user = api.fetch_users(2)
print("Fetched user with ID 2:")
pprint(user)
# U - Update a user
updated_user = api.update_users(2, "Tom Updated", "Senior Developer")
print("Updated user:")
pprint(updated_user)
# D - Delete a user
deleted = api.delete_users(2)
if deleted:
print("User deleted successfully.")
else:
print("Failed to delete user.")
登陆成功!
{'avatar': 'https://reqres.in/img/faces/1-image.jpg',
'email': '[email protected]',
'first_name': 'George',
'id': 1,
'last_name': 'Bluth'}
{'avatar': 'https://reqres.in/img/faces/2-image.jpg',
'email': '[email protected]',
'first_name': 'Janet',
'id': 2,
'last_name': 'Weaver'}
{'avatar': 'https://reqres.in/img/faces/3-image.jpg',
'email': '[email protected]',
'first_name': 'Emma',
'id': 3,
'last_name': 'Wong'}
{'avatar': 'https://reqres.in/img/faces/4-image.jpg',
'email': '[email protected]',
'first_name': 'Eve',
'id': 4,
'last_name': 'Holt'}
{'avatar': 'https://reqres.in/img/faces/5-image.jpg',
'email': '[email protected]',
'first_name': 'Charles',
'id': 5,
'last_name': 'Morris'}
{'avatar': 'https://reqres.in/img/faces/6-image.jpg',
'email': '[email protected]',
'first_name': 'Tracey',
'id': 6,
'last_name': 'Ramos'}
{'avatar': 'https://reqres.in/img/faces/7-image.jpg',
'email': '[email protected]',
'first_name': 'Michael',
'id': 7,
'last_name': 'Lawson'}
{'avatar': 'https://reqres.in/img/faces/8-image.jpg',
'email': '[email protected]',
'first_name': 'Lindsay',
'id': 8,
'last_name': 'Ferguson'}
{'avatar': 'https://reqres.in/img/faces/9-image.jpg',
'email': '[email protected]',
'first_name': 'Tobias',
'id': 9,
'last_name': 'Funke'}
{'avatar': 'https://reqres.in/img/faces/10-image.jpg',
'email': '[email protected]',
'first_name': 'Byron',
'id': 10,
'last_name': 'Fields'}
{'avatar': 'https://reqres.in/img/faces/11-image.jpg',
'email': '[email protected]',
'first_name': 'George',
'id': 11,
'last_name': 'Edwards'}
{'avatar': 'https://reqres.in/img/faces/12-image.jpg',
'email': '[email protected]',
'first_name': 'Rachel',
'id': 12,
'last_name': 'Howell'}
Created user:
{'createdAt': '2023-10-15T17:04:35.496Z',
'id': '700',
'job': 'Developer',
'name': 'Tom'}
User List:
[{'avatar': 'https://reqres.in/img/faces/1-image.jpg',
'email': '[email protected]',
'first_name': 'George',
'id': 1,
'last_name': 'Bluth'},
{'avatar': 'https://reqres.in/img/faces/2-image.jpg',
'email': '[email protected]',
'first_name': 'Janet',
'id': 2,
'last_name': 'Weaver'},
{'avatar': 'https://reqres.in/img/faces/3-image.jpg',
'email': '[email protected]',
'first_name': 'Emma',
'id': 3,
'last_name': 'Wong'},
{'avatar': 'https://reqres.in/img/faces/4-image.jpg',
'email': '[email protected]',
'first_name': 'Eve',
'id': 4,
'last_name': 'Holt'},
{'avatar': 'https://reqres.in/img/faces/5-image.jpg',
'email': '[email protected]',
'first_name': 'Charles',
'id': 5,
'last_name': 'Morris'},
{'avatar': 'https://reqres.in/img/faces/6-image.jpg',
'email': '[email protected]',
'first_name': 'Tracey',
'id': 6,
'last_name': 'Ramos'}]
Fetched user with ID 2:
[{'avatar': 'https://reqres.in/img/faces/7-image.jpg',
'email': '[email protected]',
'first_name': 'Michael',
'id': 7,
'last_name': 'Lawson'},
{'avatar': 'https://reqres.in/img/faces/8-image.jpg',
'email': '[email protected]',
'first_name': 'Lindsay',
'id': 8,
'last_name': 'Ferguson'},
{'avatar': 'https://reqres.in/img/faces/9-image.jpg',
'email': '[email protected]',
'first_name': 'Tobias',
'id': 9,
'last_name': 'Funke'},
{'avatar': 'https://reqres.in/img/faces/10-image.jpg',
'email': '[email protected]',
'first_name': 'Byron',
'id': 10,
'last_name': 'Fields'},
{'avatar': 'https://reqres.in/img/faces/11-image.jpg',
'email': '[email protected]',
'last_name': 'Edwards'},
{'avatar': 'https://reqres.in/img/faces/12-image.jpg',
'email': '[email protected]',
'first_name': 'Rachel',
'id': 12,
'last_name': 'Howell'}]
Updated user:
{'job': 'Senior Developer',
'name': 'Tom Updated',
'updatedAt': '2023-10-15T17:04:36.199Z'}
import requests
import json
class CampusManagementSystem:
# 基础URL,用于API请求的基础部分
BASE_URL = "https://reqres.in/api/"
@staticmethod # 使用staticmethod装饰器定义静态方法,这样方法可以不通过类实例直接调用
def get_students_list(page=1):
"""
从服务器获取学生列表。
:param page: 要获取的学生列表的页码,默认为1。
:return: 学生列表,如果请求失败则返回空列表。
"""
# 构造完整的API请求URL
endpoint = f"users?page={page}"
url = CampusManagementSystem.BASE_URL + endpoint
# 发起GET请求
response = requests.get(url)
# 检查响应状态码,200表示请求成功
if response.status_code == 200:
# 解析响应内容为JSON格式并获取"data"键的值,如果不存在则返回空列表
students = response.json().get("data", [])
return students
else:
print("获取学生数据失败。")
return []
@staticmethod
def add_student(name, course):
"""
向服务器添加新学生。
:param name: 学生姓名。
:param course: 学生所学课程。
:return: 如果添加成功则返回学生数据,否则返回None。
"""
endpoint = "users" # endpoint是API的路径部分
url = CampusManagementSystem.BASE_URL + endpoint
# 定义请求头,指明内容类型为JSON
headers = {
"Content-Type": "application/json"
}
# 构建请求的数据体
data = {
"name": name,
"course": course
}
# 使用json.dumps()方法将Python字典转换为JSON字符串
response = requests.post(url, headers=headers, data=json.dumps(data))
# 检查响应状态码,201表示创建成功
if response.status_code == 201:
student = response.json()
return student
else:
print("添加学生失败。")
return None
if __name__ == "__main__":
# 获取学生列表并打印
students = CampusManagementSystem.get_students_list()
for student in students:
print(f"ID: {student['id']}, 姓名: {student['first_name']} {student['last_name']}")
# 添加新学生并打印其信息
new_student = CampusManagementSystem.add_student(name="John Doe", course="Computer Science")
if new_student:
print(f"已添加新学生,ID: {new_student['id']}, 姓名: {new_student['name']}, 课程: {new_student['course']}")