本实例教程深入浅出地介绍了如何在Python中实现和使用多线程技术,包含创建、启动及控制线程的基本方法与应用案例。
为了满足某内控公司的并发测试需求,并编写一个多线程访问接口并生成Excel报告的脚本,请参考以下步骤:
1. 打开网页以获取后端提供的cookie。
2. 使用该cookie登录用户,保持会话链接。
3. 进行业务操作,通过调用相应的业务接口完成任务。
4. 将上述三步添加到多线程任务中,并集中执行这些任务。同时记录下所有相关的数据信息。
5. 最后将收集的数据整理成表格形式并保存为Excel文件。
以下是实现这一目标的Python代码示例:
```python
import xlwt
import json
import random
import threading
import time
import requests
def get_cookie():
# 打开网页,获取cookie逻辑在此处编写。
pass
def login_with_cookie(cookie):
# 使用获得的cookie登录用户,保持链接状态。这里需要实现具体的登录请求代码。
pass
def perform_business_operation(session, user_id):
# 业务操作的具体步骤,在此调用相应的接口并返回结果
response = session.get(fhttp://example.com/api/user/{user_id})
return json.loads(response.text)
class ConcurrentTask(threading.Thread):
def __init__(self, thread_id, cookie):
threading.Thread.__init__(self)
self.thread_id = thread_id
self.cookie = cookie
def run(self):
# 获取会话对象,这里使用requests.Session()来保持cookie和链接状态。
session = requests.Session()
try:
login_with_cookie(session) # 使用获取到的cookie登录用户
user_id = random.randint(1, 50)
result = perform_business_operation(session, user_id)
print(fThread {self.thread_id} - User ID: {user_id}, Result: {result})
except Exception as e:
print(fError occurred in thread {self.thread_id}: {e})
def generate_excel_report(data):
# 创建一个Excel工作簿
workbook = xlwt.Workbook(encoding=utf-8)
# 添加一个工作表到workbook中
sheet1 = workbook.add_sheet(Sheet 1)
# 设置列标题
sheet1.write(0, 0, Thread ID)
sheet1.write(0, 1, User ID)
sheet1.write(0, 2, Result)
row_index = 1
for item in data:
thread_id = item[thread_id]
user_id = item[user_id]
result = str(item[result])
# 将数据写入到Excel表格中
sheet1.write(row_index, 0, thread_id)
sheet1.write(row_index, 1, user_id)
sheet1.write(row_index, 2, result)
row_index += 1
workbook.save(output.xls)
def main():
# 假设这里已经有了一个cookie列表
cookies = [get_cookie() for _ in range(50)]
threads_data = []
# 启动多线程任务
for i, cookie in enumerate(cookies):
thread = ConcurrentTask(i+1, cookie)
thread.start()
# 等待所有子线程完成后再继续执行主程序中的其他代码。
thread.join()
threads_data.append({thread_id: i + 1})
generate_excel_report(threads_data)
if __name__ == __main__:
main()
```
以上脚本实现了从获取cookie到生成Excel报告的整个流程,可以根据实际需求进行调整。