import threading
import requests
# 普通消息测试
def successfully_requested_validation_stream(s_thread_id, s_question):
# s_question代表当前的问题 - 传到data里面
# 请求头需要哪些参数
d_headers = {}
# 有哪些参数
d_data = {}
# 接口地址
s_url = ''
p_response = requests.post(s_url, headers=d_headers, json=d_data)
d_result = p_response.json()
# d_result是响应json信息可以根据自己的接口结果进行解析得到结果s_result
s_result = d_result['data']['cont']
return s_thread_id, s_question, s_result
# 多线程执行
def run_thread(thread_id, s_question):
s_thread_id, s_questions, s_result = successfully_requested_validation_stream(str(thread_id), s_question)
print(f's_questions={s_questions},s_result={s_result}')
# 读取存储内容
def read_file_cont(s_file_path):
with open(s_file_path, 'r', encoding='utf-8') as files:
l_all_questions = files.readlines()
l_all_question_new = []
for s_cont in l_all_questions:
s_cont_now = s_cont.replace('\n', '')
if s_cont_now:
l_all_question_new.append(s_cont_now)
return l_all_question_new
if __name__ == '__main__':
# 读取文本的路径
s_read_file_path = r"C:\Users\Administrator\Desktop\新建文件夹\laji.txt"
# 读取文件内容
l_all_question = read_file_cont(s_read_file_path)
print(l_all_question)
# 创建线程列表
threads = []
# 创建并启动线程
for i in range(len(l_all_question)):
thread = threading.Thread(target=run_thread, args=(i, l_all_question[i]))
thread.start()
threads.append(thread)
# 等待所有线程执行完毕
for thread in threads:
thread.join()
如何使用python多线程调用接口获得结果
于 2023-08-01 10:07:19 首次发布
文章介绍了如何在Python中使用threading模块实现多线程,通过requests库发送POST请求获取数据。主要内容包括创建线程、执行普通消息测试和读取文件中的问题进行并发处理。
摘要由CSDN通过智能技术生成