You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask POST请求报错致服务器崩溃:/Summarize路由KeyError问题修复

问题修复与部署方案

一、KeyError:0 错误修复

这个错误是因为你直接假设Hugging Face API返回的是列表并取索引[0],但实际API可能返回错误字典(比如密钥无效、模型加载超时、输入格式问题),或者返回结构不符合预期。按以下步骤修复:

  1. 验证API密钥
    确保你把代码中的<API-KEY>替换成了自己的Hugging Face Access Token(在Hugging Face账号设置里生成)。

  2. 修改返回结果处理逻辑
    不要直接取索引[0],先判断返回内容的结构,添加错误处理:
    修改Summarize函数中的代码:

    output = query({
        "inputs":data,
        "parameters":{"min_length":minL,"max_length":maxL},
    })
    # 先检查是否有错误
    if "error" in output:
        return render_template("index.html", result=f"API错误: {output['error']}")
    # 处理正确返回的情况
    if isinstance(output, list):
        summary = output[0]["summary_text"]
    else:
        summary = output.get("summary_text", "无法生成摘要")
    return render_template("index.html", result=summary)
    
  3. 添加请求超时与异常捕获
    防止API请求超时导致的崩溃,修改query函数:

    def query(payload):
        try:
            response = requests.post(API_URL, headers=headers, json=payload, timeout=30)
            response.raise_for_status() # 捕获HTTP状态码错误
            return response.json()
        except requests.exceptions.RequestException as e:
            return {"error": str(e)}
    

二、可反复重启的个人部署方案

方案1:使用systemd管理Gunicorn服务(Linux环境)

适合个人VPS或本地Linux机器,能自动重启服务:

  1. 安装依赖

    pip install gunicorn flask requests
    
  2. 编写Gunicorn启动命令
    假设你的app.py在/home/yourname/data-summarize目录下,启动命令:

    gunicorn -w 4 -b 0.0.0.0:5000 app:app
    
    • -w 4:4个工作进程,根据CPU核心数调整
    • -b 0.0.0.0:5000:绑定所有网卡的5000端口
  3. 创建systemd服务文件
    新建/etc/systemd/system/summarize.service,内容:

    [Unit]
    Description=Data Summarization Flask App
    After=network.target
    
    [Service]
    User=yourname
    WorkingDirectory=/home/yourname/data-summarize
    ExecStart=/usr/local/bin/gunicorn -w 4 -b 0.0.0.0:5000 app:app
    Restart=always
    RestartSec=5
    
    [Install]
    WantedBy=multi-user.target
    

    替换yourname和路径为实际信息。

  4. 启动并设置开机自启

    sudo systemctl daemon-reload
    sudo systemctl start summarize
    sudo systemctl enable summarize
    

    以后服务会自动重启,查看状态用sudo systemctl status summarize。

方案2:使用Docker容器(跨平台)

适合任何支持Docker的环境,容器停止后可一键重启:

  1. 编写Dockerfile
    在项目根目录新建Dockerfile:

    FROM python:3.11-slim
    
    WORKDIR /app
    
    COPY requirements.txt .
    RUN pip install --no-cache-dir -r requirements.txt
    
    COPY . .
    
    EXPOSE 5000
    
    CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:5000", "app:app"]
    
  2. 编写requirements.txt

    flask
    requests
    gunicorn
    
  3. 构建并运行容器

    # 构建镜像
    docker build -t data-summarize .
    # 运行容器,设置自动重启
    docker run -d --restart always -p 5000:5000 data-summarize
    

    容器会在开机或意外停止后自动重启,查看容器状态用docker ps。

内容的提问来源于stack exchange,提问作者hipprofessional

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 01:42:48