可以使用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时可能会遇到并发访问的问题,需要根据具体情况采取相应的措施,如使用锁、限制并发数等。

python 多线程批量请求api

原文地址: http://www.cveoy.top/t/topic/bL1u 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录