Flask Web应用运行报错 请求排查与代码修正
代码问题排查与修正
原代码中的核心问题
- 未处理空单元格(NaN):Excel中
Comments列为空时,会返回NaN,调用split(';')直接抛出AttributeError。 - 正则匹配鲁棒性差:原正则要求末尾必须带
-,格式稍有偏差就匹配失败;同时未处理分割后为空的评论项。 - 请求头判断有风险:直接访问
request.headers['Content-Type']会在请求无该头时抛出KeyError。 - Excel读取无异常处理:文件损坏、权限不足等情况会导致程序崩溃,无错误捕获。
- 参数校验缺失:请求中缺少
Job Req ID时,未返回明确错误提示;且未处理Excel中Job ID为数值类型的匹配问题。 - 冗余代码未清理:
allowed_file函数定义后未使用,属于无效代码。
修正后的完整代码
from flask import Flask, request, jsonify import pandas as pd import re import os app = Flask(__name__) def load_excel_file(): file_path = "abc.xlsx" if not os.path.isfile(file_path): return None try: return pd.read_excel(file_path) except Exception as e: print(f"读取Excel失败: {str(e)}") return None def process_comments(comments): result = {"count": 0, "ec": 0, "ic": 0, "names": []} # 处理空值或非字符串情况 if not isinstance(comments, str) or not comments.strip(): return result ec_count = 0 ic_count = 0 names = [] # 优化正则:兼容末尾无'-'、任意空格的格式 pattern = r'\[(.*?)\]\s+(.*?)\s+\((.*?)\)(?:\s*-)?' for comment in comments.split(';'): comment_clean = comment.strip() if not comment_clean: continue match = re.search(pattern, comment_clean) if match: _, name, role = match.groups() role = role.strip() if role == "EC": ec_count += 1 elif role == "IC": ic_count += 1 # 提取姓名首部分,避免空字符串 name_parts = name.strip().split() if name_parts: names.append(name_parts[0]) result["count"] = ec_count + ic_count result["ec"] = ec_count result["ic"] = ic_count result["names"] = names return result @app.route("/", methods=['POST']) def process_comments_route(): excel_data = load_excel_file() # 安全判断JSON请求 if not request.is_json: return jsonify({"error": "仅支持JSON格式请求"}), 415 data = request.get_json() job_id = data.get("Job Req ID") # 校验必填参数 if not job_id: return jsonify({"error": "缺少必填参数: Job Req ID"}), 400 if excel_data is None: return jsonify({"error": "Excel文件未找到或无法读取"}), 404 # 处理Excel中Job ID为数值类型的匹配问题 job_id_col = excel_data['Job Req ID'] if job_id_col.dtype in ['int64', 'float64']: try: job_id = float(job_id) if '.' in str(job_id) else int(job_id) except ValueError: return jsonify({"error": "Job Req ID类型与Excel数据不匹配"}), 400 row = excel_data[excel_data['Job Req ID'] == job_id] if row.empty: return jsonify({"error": "未找到对应Job ID的数据"}), 404 comments = row['Comments'].iloc[0] result = process_comments(comments) response = {str(job_id): result} return jsonify(response) if __name__ == '__main__': app.run(debug=True)
关键修正说明
- 空值处理:在
process_comments开头判断输入是否为有效字符串,避免NaN导致的报错。 - 正则优化:调整规则兼容不同格式的评论,跳过空评论项。
- 请求安全校验:用Flask内置的
request.is_json替代直接读取请求头,避免异常。 - 异常捕获:给Excel读取添加try-except,捕获文件损坏、权限等问题。
- 类型兼容:处理Excel中Job ID为数值的情况,确保匹配准确。
内容的提问来源于stack exchange,提问作者Glane Gonsalves
相关产品推荐
相关产品推荐

