Python 多线程批量请求 API 提高效率
可以使用 Python 的多线程模块 'threading' 和 HTTP 请求库 'requests' 来实现多线程批量请求 API。
以下是一段示例代码:
import threading
import requests
# 定义要请求的 API 地址列表
api_list = [
'https://api.example.com/user/1',
'https://api.example.com/user/2',
'https://api.example.com/user/3',
# ...
]
# 定义请求函数
def request_api(api):
response = requests.get(api)
print(response.json())
# 创建线程池
threads = []
# 遍历 API 地址列表,为每个 API 地址创建一个线程
for api in api_list:
thread = threading.Thread(target=request_api, args=(api,))
threads.append(thread)
# 启动所有线程
for thread in threads:
thread.start()
# 等待所有线程完成
for thread in threads:
thread.join()
在示例代码中,首先定义了要请求的 API 地址列表 'api_list',然后定义了一个 'request_api()' 函数用于发送 HTTP 请求并输出响应结果。接着,创建一个线程池 'threads',遍历 API 地址列表,为每个 API 地址创建一个线程,并将线程对象添加到线程池中。最后,启动所有线程,等待所有线程完成。
需要注意的是,多线程请求 API 时可能会遇到并发访问的问题,需要根据具体情况采取相应的措施,如使用锁、限制并发数等。
原文地址: https://www.cveoy.top/t/topic/ndR1 著作权归作者所有。请勿转载和采集!