使用Python Multiprocessing模拟Flask服务器多请求遇问题求助
问题分析与解决方案
原代码核心问题
- 你的
ENDPOINT列表仅包含1个元素,因此pool.map只会执行1次请求,自然仅返回1个结果。 - 重复创建
Pool对象(先with Pool()再pool = mp.Pool(mp.cpu_count())),逻辑冗余且浪费资源。 - 缺少结果写入CSV的处理逻辑。
修改后的完整代码
import multiprocessing as mp import requests import csv from datetime import datetime HOST = 'http://127.0.0.1:5000' API_PATH = '/' REQUEST_COUNT = 100 # 模拟100次请求 MAX_PROCESSES = 10 # 最大并行进程数 def send_api_request(endpoint): process_name = mp.current_process().name start_time = datetime.now() try: r = requests.get(endpoint) status_code = r.status_code elapsed_time = r.elapsed.total_seconds() # 转换为秒数,便于CSV存储 return (process_name, start_time.strftime("%Y-%m-%d %H:%M:%S.%f"), status_code, elapsed_time) except Exception as e: # 捕获请求异常,避免单个请求失败导致程序中断 return (process_name, start_time.strftime("%Y-%m-%d %H:%M:%S.%f"), "ERROR", str(e)) def main(): # 构造100次请求的任务列表 tasks = [HOST + API_PATH] * REQUEST_COUNT # 创建指定数量的进程池,并行执行所有任务 with mp.Pool(processes=MAX_PROCESSES) as pool: results = pool.map(send_api_request, tasks) # 将所有请求结果写入CSV文件 with open('request_response_times.csv', 'w', newline='', encoding='utf-8') as csvfile: fieldnames = ['进程名称', '请求时间', '状态码', '响应时间(秒)'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for res in results: writer.writerow({ '进程名称': res[0], '请求时间': res[1], '状态码': res[2], '响应时间(秒)': res[3] }) print(f"所有请求完成,结果已写入request_response_times.csv") if __name__ == '__main__': main()
关键修改说明
任务列表构造
用[HOST + API_PATH] * REQUEST_COUNT生成100个重复的请求地址,确保pool.map触发100次并行请求。进程池优化
直接在with语句中指定processes=MAX_PROCESSES,明确控制并行进程数,避免重复创建池的冗余操作。请求函数增强
- 记录进程名称,可直观确认多进程运行状态
- 记录请求开始时间,便于分析请求时间分布
- 将响应时间转换为秒数,比原生
timedelta更适合CSV存储 - 增加异常捕获,防止单个请求失败导致整个程序崩溃
CSV结果存储
使用csv.DictWriter格式化写入结果,表头清晰,后续可直接用表格工具(如Excel)分析数据。
验证多进程运行
运行代码后,打开生成的request_response_times.csv,查看“进程名称”列,会看到不同的SpawnPoolWorker编号(如SpawnPoolWorker-1、SpawnPoolWorker-2等),这即可证明多个进程在并行处理请求。
内容的提问来源于stack exchange,提问作者YannickMetz
相关产品推荐
相关产品推荐

