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

如何将FastAPI与ngrok连接?微调BERT部署遇错误求助

问题解决:FastAPI与ngrok连接及部署错误修复

一、错误原因分析与修复方案

错误1:端口占用([Errno 98] address already in use)

  • 原因:8080端口被其他进程占用,导致uvicorn无法绑定该端口。
  • 修复步骤:
    1. 查找占用8080端口的进程:
      • Linux/macOS:执行 lsof -i :8080 或 netstat -tulpn | grep 8080
      • Windows:执行 netstat -ano | findstr :8080
    2. 杀死占用进程:
      • Linux/macOS:执行 kill -9 <进程PID>
      • Windows:执行 taskkill /F /PID <进程PID>
    3. 或直接更换端口,比如将uvicorn启动端口改为8000:uvicorn.run(app, port=8000),同时ngrok连接对应改为ngrok.connect(8000)

错误2:TypeError: object of type 'NoneType' has no len()

  • 原因:代码存在多重逻辑问题触发该错误:
    1. 错误混用FastAPI与Streamlit:初始化FastAPI后未使用,反而动态生成Streamlit脚本,两个框架属于不同web体系,不能这样混合编写。
    2. trainer变量未定义:Streamlit代码块中直接使用trainer作为模型参数,但当前脚本中未定义该变量,导致模型加载失败,引发后续递归错误。
    3. 执行顺序混乱:Streamlit逻辑应单独编写脚本运行,而非动态写入文件后在FastAPI脚本中调用。
  • 修复步骤:
    1. 拆分框架代码:选择FastAPI或Streamlit其中一个框架实现功能,如需前后端分离,单独编写各自脚本。
    2. 正确加载微调后的BERT模型:提前定义好模型路径或对象,例如使用Hugging Face API加载训练好的模型:
      from transformers import AutoModelForSequenceClassification
      model = AutoModelForSequenceClassification.from_pretrained("./你的训练模型目录")
      
    3. 删除动态写入app.py的代码块,改为单独编写对应框架的完整脚本。

二、正确的FastAPI与ngrok连接方法

步骤1:编写FastAPI后端代码

创建main.py文件,内容如下:

from fastapi import FastAPI
from transformers import pipeline, AutoModelForSequenceClassification, AutoTokenizer

app = FastAPI()

# 加载微调后的BERT模型与tokenizer
model = AutoModelForSequenceClassification.from_pretrained("./你的训练模型路径")
tokenizer = AutoTokenizer.from_pretrained("./你的训练模型路径")
classifier = pipeline("text-classification", model=model, tokenizer=tokenizer, device=0, return_all_scores=False)

@app.post("/classify")
async def text_classify(text: str):
    result = classifier(text)
    return {"classification_result": result}

步骤2:启动FastAPI服务

在终端执行:

uvicorn main:app --host 0.0.0.0 --port 8000

步骤3:用ngrok暴露公网访问

在另一个终端执行(需先安装ngrok并配置认证token):

ngrok http 8000

执行后会生成公网URL,例如https://xxxx-xx-xx-xx-xx.ngrok.io,可通过该URL发送POST请求到/classify接口,传入文本参数获取分类结果。

注意事项

  • 确保ngrok已完成认证,执行ngrok config add-authtoken 你的认证token完成配置
  • 若在Jupyter环境运行,需先安装nest_asyncio并调用nest_asyncio.apply(),避免异步运行冲突

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 17:34:59