我们希望您开发一个小型Python应用程序,该应用程序可以同时从多个API端点请求数据,并将从每个端点接收到的数据保存在一个单独的CSV文件中。用于此目的的API位于:https://fakestoreapi.com请求#1将从相关API端点(GET /products)获取所有产品。请求#2将从相关API端点(GET /users)获取所有用户。接收到的数据将分别保存在products.csv和users.csv文件中。
我的密码正确吗?
import requests
import csv
# API endpoint URLs
products_url = "https://fakestoreapi.com/products"
users_url = "https://fakestoreapi.com/users"
# Send requests to API endpoints
products_response = requests.get(products_url)
users_response = requests.get(users_url)
# Check if requests are successful
if products_response.status_code != 200:
print("Products request failed with status code:", products_response.status_code)
exit()
if users_response.status_code != 200:
print("Users request failed with status code:", users_response.status_code)
exit()
# Save products data to CSV file
products_data = products_response.json()
with open("products.csv", "w", newline="") as csvfile:
writer = csv.writer(csvfile)
writer.writerow(products_data[0].keys())
for product in products_data:
writer.writerow(product.values())
# Save users data to CSV file
users_data = users_response.json()
with open("users.csv", "w", newline="") as csvfile:
writer = csv.writer(csvfile)
writer.writerow(users_data[0].keys())
for user in users_data:
writer.writerow(user.values())
2条答案
按热度按时间qoefvg9y1#
我不确定你会如何并发地做这些,但是我认为你可以使用多处理,即使它对于这个简单的任务来说是极端的矫枉过正。
下面是我的解决方案:
neekobn82#
否,您的代码不符合所列出的要求。在您的代码中,您运行了以下函数:
但是,
requests.get
的第一次调用将停止第二次调用的执行,直到它完成。这意味着您的代码是 synchronous。您需要的是同时运行两个GET请求的 asynchronous(或多线程)代码。您可以使用threading
库通过以下代码完成此操作,该库可以集成到当前代码中: