本文将详细介绍如何在 Vercel 平台上部署 Python FastAPI 项目,包括项目结构、代码实现、部署流程以及常见问题的解决方案。这是一个前置的测试项目,验证在vercel部署python项目的可行性,后续会部署更加复杂的服务,并且与coze结合
大模型落地开发实战指南!请关注微信公众号:「AGI启程号」 深入浅出,助你轻松入门!
数据分析、深度学习、大模型与算法的综合进阶,尽在CSDN博客主页
本项目源代码github链接,可自行克隆到自己的代码仓库完成vercel部署
velcel项目部署测试/
├── api/
│ ├── hello.py # 基础 Python API 函数
│ └── app.py # FastAPI 应用(主应用)
├── Pipfile # Python 环境配置
├── requirements.txt # Python 依赖
├── vercel.json # Vercel 路由配置
├── .gitignore # Git 忽略文件
└── README.md # 项目说明
api/app.py
)from fastapi import FastAPI
from datetime import datetime
# 创建 FastAPI 应用实例
app = FastAPI(title="Vercel FastAPI 测试", version="1.0.0")
@app.get("/")
def read_root():
return {
"message": "Hello from FastAPI on Vercel!",
"timestamp": datetime.now().isoformat(),
"status": "running"
}
@app.get("/info")
def get_info():
return {
"app": "FastAPI on Vercel",
"version": "1.0.0",
"python_version": "3.10",
"timestamp": datetime.now().isoformat()
}
@app.get("/health")
def health_check():
return {"status": "healthy", "timestamp": datetime.now().isoformat()}
@app.post("/echo")
def echo_data(data: dict):
return {
"message": "Data received successfully",
"received_data": data,
"timestamp": datetime.now().isoformat()
}
代码关键点:
app
变量,无需额外的 handler 函数api/hello.py
)from http.server import BaseHTTPRequestHandler
class handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write("Hello from Python on Vercel!".encode('utf-8'))
return
代码关键点:
requirements.txt
)fastapi==0.104.1
说明:
Pipfile
)[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"
[requires]
python_version = "3.10"
[packages]
fastapi = "*"
uvicorn = "*"
[dev-packages]
说明:
vercel.json
){
"routes": [
{ "src": "/(.*)", "dest": "api/app.py" }
]
}
说明:
# 初始化 Git 仓库
git init
# 添加文件
git add .
# 提交代码
git commit -m "Initial commit: Vercel FastAPI project"
# 关联远程仓库
git remote add origin https://github.com/your-username/your-repo.git
# 推送代码
git push -u origin main
.gitignore
文件排除不必要的文件# 全局安装 Vercel CLI
npm install -g vercel
# 登录 Vercel 账户
vercel login
# 在项目根目录执行
vercel
# 或直接部署到生产环境
vercel --prod
在部署过程中,Vercel 会询问:
部署完成后会得到访问 URL,测试以下端点:
https://your-project.vercel.app/
- FastAPI 主页https://your-project.vercel.app/health
- 健康检查https://your-project.vercel.app/info
- 应用信息https://your-project.vercel.app/api/hello
- 基础函数# 启动本地开发服务器
vercel dev
# 访问本地地址
http://localhost:3000
错误信息:
File "/var/task/api/app.py", line 1, in
from fastapi import FastAPI
ModuleNotFoundError: No module named 'fastapi'
解决方案:
requirements.txt
包含正确的依赖fastapi==0.104.1
requirements.txt
错误信息:
TypeError: issubclass() arg 1 must be a class
Python process exited with exit status: 1
原因:
使用了 handler = Mangum(app)
导致 Vercel 检查 handler 时出错
解决方案:
# ❌ 错误方式
from mangum import Mangum
handler = Mangum(app)
# ✅ 正确方式
app = FastAPI()
# 直接导出 app,无需额外 handler
错误信息:
ImportError: cannot import name 'Adapter' from 'mangum'
原因:
Mangum 库版本更新,API 发生变化
解决方案:
完全移除 Mangum 依赖,让 Vercel 自动处理 ASGI:
# 删除这些导入和代码
from mangum import Adapter # 删除
handler = Adapter(app) # 删除
警告信息:
WARN! Due to `builds` existing in your configuration file,
the Build and Development Settings defined in your Project Settings will not apply.
解决方案:
简化 vercel.json
配置:
// ❌ 导致警告的配置
{
"version": 2,
"builds": [
{
"src": "api/*.py",
"use": "@vercel/python"
}
],
"routes": [...]
}
// ✅ 简化后的配置
{
"routes": [
{ "src": "/(.*)", "dest": "api/app.py" }
]
}
requirements.txt
指定明确的版本号vercel.json
配置# 查看部署日志
vercel logs
# 查看项目列表
vercel ls
# 查看项目详情
vercel inspect [deployment-url]
# 强制重新部署
vercel --force
冷启动优化
响应时间优化
监控和日志
通过本文的详细介绍,我们成功实现了:
这个项目展示了如何在 Vercel 上正确部署 Python FastAPI 应用,避免了传统部署中的复杂配置,充分利用了 Vercel 的自动检测和 Serverless 特性。
关键成功要素:
该方案特别适合:
希望本文能帮助您顺利完成 Vercel Python 项目的部署!