python 开线程池去 请求一个api接口 无限循环
时间: 2023-05-24 09:03:19 浏览: 52
A:可以使用Python的concurrent.futures模块中的ThreadPoolExecutor来创建一个线程池,并使用requests模块向API接口发出请求。同时,可以使用while True语句来实现无限循环。以下是一个示例代码:
```python
import concurrent.futures
import requests
# 定义要请求的API接口地址
api_url = 'http://example.com/api'
# 定义向API接口发出请求的函数
def make_request():
response = requests.get(api_url)
print(response.text)
# 创建一个包含5个线程的线程池
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
while True:
# 向线程池提交make_request函数,等待执行
executor.submit(make_request)
```
这段代码中,先定义了要请求的API接口地址,并编写了一个名为make_request的函数来向API接口发出请求并打印响应数据。接着,使用with语句创建了一个包含5个线程的线程池,并不断地向线程池提交make_request函数以实现无限循环。每个线程将执行make_request函数,向API接口发出请求并打印响应数据。由于使用了线程池,可以在程序中同时执行多个请求,以提高效率。