如何使用python多线程调用接口获得结果

文章介绍了如何在Python中使用threading模块实现多线程,通过requests库发送POST请求获取数据。主要内容包括创建线程、执行普通消息测试和读取文件中的问题进行并发处理。
摘要由CSDN通过智能技术生成
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()


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值