作为一名长期奋战在一线的全栈开发者,我亲历了Python Web框架从Django、Flask到FastAPI的迭代过程。FastAPI凭借其卓越的性能、直观的类型提示和自动化的API文档生成,已经成为现代Python后端开发的首选方案。这个教程将带你从零开始,用最精简的路径掌握FastAPI的核心用法,最终部署一个符合生产标准的API服务。
推荐使用Python 3.8+版本,这是FastAPI官方建议的最低版本要求。创建一个干净的虚拟环境是良好实践的开始:
bash复制python -m venv fastapi-env
source fastapi-env/bin/activate # Linux/Mac
fastapi-env\Scripts\activate # Windows
安装核心依赖包时,建议固定版本以避免兼容性问题:
bash复制pip install fastapi==0.95.2 uvicorn==0.22.0
注意:生产环境务必使用固定版本号,避免自动升级导致意外问题。我曾遇到过因uvicorn自动升级导致的websocket连接异常,排查了整整一天。
创建一个main.py文件,写入以下代码:
python复制from fastapi import FastAPI
app = FastAPI(
title="光子AI服务",
description="极简FastAPI教程示例",
version="0.1.0"
)
@app.get("/")
async def root():
return {"message": "Hello FastAPI"}
启动开发服务器:
bash复制uvicorn main:app --reload
访问http://127.0.0.1:8000即可看到返回的JSON响应,访问http://127.0.0.1:8000/docs可以看到自动生成的Swagger文档。
FastAPI的路由系统非常直观,支持所有HTTP方法:
python复制from fastapi import Path, Query
@app.get("/items/{item_id}")
async def read_item(
item_id: int = Path(..., title="商品ID", gt=0),
q: str = Query(None, min_length=3, max_length=50)
):
return {"item_id": item_id, "q": q}
路径参数和查询参数都支持丰富的验证规则:
Path(..., gt=0) 表示必传且必须大于0的整数Query(None,...) 表示可选参数,带长度限制定义数据模型是FastAPI的强项:
python复制from pydantic import BaseModel, EmailStr
class UserCreate(BaseModel):
username: str
email: EmailStr
password: str
@app.post("/users/")
async def create_user(user: UserCreate):
# 密码应该哈希处理
return {"username": user.username, "email": user.email}
模型会自动验证输入数据,并生成详细的错误信息。EmailStr会自动验证邮箱格式,这在注册场景非常实用。
推荐使用SQLAlchemy 1.4+的异步API:
python复制from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
DATABASE_URL = "postgresql+asyncpg://user:pass@localhost/dbname"
engine = create_async_engine(DATABASE_URL)
AsyncSessionLocal = sessionmaker(engine, class_=AsyncSession)
@app.get("/users/{user_id}")
async def get_user(user_id: int):
async with AsyncSessionLocal() as session:
user = await session.get(User, user_id)
return user
经验分享:异步数据库操作需要特别注意连接管理。我曾因忘记关闭session导致连接池耗尽,建议使用
async with上下文管理器。
调整uvicorn启动参数:
bash复制uvicorn main:app \
--host 0.0.0.0 \
--port 8000 \
--workers 4 \
--limit-concurrency 100 \
--timeout-keep-alive 30
关键参数说明:
workers:建议设置为CPU核心数的1-2倍limit-concurrency:防止突发流量导致系统过载timeout-keep-alive:优化长连接资源占用必须添加的安全中间件:
python复制from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
app.add_middleware(HTTPSRedirectMiddleware)
app.add_middleware(TrustedHostMiddleware, allowed_hosts=["example.com"])
其他安全建议:
推荐使用Prometheus监控:
python复制from prometheus_fastapi_instrumentator import Instrumentator
Instrumentator().instrument(app).expose(app)
日志配置示例:
python复制import logging
from fastapi.logger import logger
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
当QPS上不去时,按以下顺序检查:
正确的CORS配置:
python复制from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["https://yourdomain.com"],
allow_methods=["*"],
allow_headers=["*"],
)
常见错误:
allow_credentials=True导致cookie无法传递*时浏览器可能拒绝某些请求使用pipdeptree分析依赖关系:
bash复制pip install pipdeptree
pipdeptree --warn silence | grep -E 'fastapi|uvicorn|pydantic'
我曾遇到pydantic版本冲突导致文档不生成的问题,最终通过创建隔离环境解决。
对于大型项目,推荐如下结构:
code复制.
├── app
│ ├── __init__.py
│ ├── main.py # 入口文件
│ ├── api # 路由
│ │ ├── v1 # API版本
│ │ │ ├── users.py
│ │ │ └── items.py
│ ├── core # 核心配置
│ │ ├── config.py
│ │ └── security.py
│ ├── db # 数据库
│ │ ├── models.py
│ │ └── session.py
│ └── schemas # Pydantic模型
│ └── users.py
├── tests
│ ├── test_api
│ └── conftest.py
└── requirements
├── base.txt
└── prod.txt
关键设计原则:
在项目规模扩大后,可以考虑引入:
通过这个结构,我们的光子AI后端服务成功支撑了日均百万级的API调用,同时保持了良好的可维护性。记住,好的架构不是一次性设计出来的,而是在不断迭代中演化而成的。