import requests
import threading
# 测试案例json报文
d_data = {
}
# 调用接口的url
s_url = 'http://(ip或域名)/v1/rule_threshold'
# 调用接口的函数
def response_function(i, s_url, d_data):
p_response = requests.post(s_url, json=d_data)
# d_result = p_response.json()
return p_response
# 重构多线程
class mythread(threading.Thread):
def __init__(self, func, args=()):
super(mythread, self).__init__()
self.func = func
self.args = args
def run(self):
self.result = self.func(*self.args)
def get_result(self):
try:
return self.result
except Exception:
return None
# 利用多线程方式调用接口
# 创建线程列表
threads = []
# 创建并启动线程
for i in range(20):
thread = mythread(response_function, args=(i, s_url, d_data))
thread.start()
threads.append(thread)
# 等待所有线程执行完毕,拿到执行结果
for thread in threads:
thread.join()
print(thread.get_result().json())
使用 threading.Thread()多线程调用url接口服务,并通过封装 threading.Thread(),重写 run 方法获取调取后的结果
最新推荐文章于 2025-05-19 21:19:18 发布
本文介绍了如何使用Python的requests库结合threading模块实现对HTTP接口的批量并发调用,并通过mythread类进行多线程处理,最后获取并解析返回的JSON数据。
442

被折叠的 条评论
为什么被折叠?



