FastAPI 服务器部署
搭建一个 FastAPI 服务器:监听本地 8888 端口;通过 GET 访问 /file01,返回 D:\cursor\ex.txt 的文件内容。
环境
| 项目 | 版本 / 说明 |
|---|---|
| Python | 3.13.4 |
| 系统 | Windows 11 |
| 依赖 | fastapi、uvicorn |
1. 安装依赖
pip install fastapi uvicorn
可选:写入 requirements.txt 便于复现:
fastapi
uvicorn
再执行:pip install -r requirements.txt
2. 创建 main.py
from fastapi import FastAPI
from fastapi.responses import PlainTextResponse
app = FastAPI()
# Windows 下正斜杠路径同样可用;也可写成 r"D:\cursor\ex.txt"
FILE_PATH = "D:/cursor/ex.txt"
@app.get("/file01")
async def read_file():
try:
with open(FILE_PATH, "r", encoding="utf-8") as file:
content = file.read()
return PlainTextResponse(content)
except FileNotFoundError:
return PlainTextResponse("文件未找到", status_code=404)
except Exception as e:
return PlainTextResponse(f"发生错误: {str(e)}", status_code=500)
if __name__ == "__main__":
import uvicorn
# 0.0.0.0:本机各网卡均可访问;仅本机可用 127.0.0.1
uvicorn.run(app, host="0.0.0.0", port=8888)
说明:
- 接口:
GET /file01→ 以纯文本返回文件内容。 - 文件不存在时返回 404;其他异常返回 500。
- 请先确保
D:\cursor\ex.txt存在且为 UTF-8 文本(或其他与encoding一致的编码)。
3. 启动服务器
在 main.py 所在目录执行:
python main.py
也可直接用 uvicorn(便于开发时自动重载):
uvicorn main:app --host 0.0.0.0 --port 8888 --reload
启动成功后,访问地址示例:
- http://127.0.0.1:8888/file01
- http://localhost:8888/file01
FastAPI 自带文档(可选):
- Swagger UI:http://127.0.0.1:8888/docs
- ReDoc:http://127.0.0.1:8888/redoc
4. Windows 后台运行(批处理)
先创建 start_server.bat(与 main.py 同目录):
@echo off
cd /d "%~dp0"
start "fastapi-8888" /B python main.py
echo 服务器已在后台启动,监听端口 8888
echo 访问: http://127.0.0.1:8888/file01
然后双击运行该批处理即可。
补充:
-
cd /d "%~dp0":保证工作目录为脚本所在目录,避免相对路径错乱。 -
若希望单独弹出最小化窗口便于查看日志,可用:
start "fastapi-8888" /MIN python main.py -
结束进程:在任务管理器中结束对应
python.exe,或在 PowerShell 中按端口查找后结束:netstat -ano | findstr :8888 taskkill /PID <上述PID> /F
5. 在 Cursor 中查看效果
- 确认
D:\cursor\ex.txt有可读内容。 - 启动服务(前台
python main.py或双击批处理)。 - 在 Cursor 中任选一种方式验证:
-
简易浏览器 / 打开链接:访问 http://127.0.0.1:8888/file01
-
终端:
curl http://127.0.0.1:8888/file01 -
文档页:打开 http://127.0.0.1:8888/docs ,对
/file01点 Try it out → Execute
-
预期:响应体为 ex.txt 的文本内容;文件缺失时应看到「文件未找到」且状态码为 404。
快速自检清单
| 步骤 | 检查项 |
|---|---|
| 1 | 已安装 fastapi、uvicorn |
| 2 | D:\cursor\ex.txt 存在且可读 |
| 3 | 8888 端口未被占用 |
| 4 | GET /file01 能返回文件内容 |