【FaskAPI】python web框架详细使用

FastAPI 的详细用法介绍,涵盖其核心功能、常用技巧和最佳实践。FastAPI 是一个现代、高性能的 Python Web 框架,基于 StarlettePydantic,支持异步编程,适合构建 API 和 Web 应用。


一、安装 FastAPI

1. 安装依赖

pip install fastapi uvicorn[standard]
  • fastapi: 核心框架。
  • uvicorn: ASGI 服务器,用于运行 FastAPI 应用。
  • [standard]: 安装额外依赖(如异步支持、文档工具等)。

二、创建第一个 FastAPI 应用

1. 示例代码

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"message": "Hello, FastAPI!"}

@app.get("/items/{item_id}")
def read_item(item_id: int):
    return {"item_id": item_id, "name": "Sample Item"}

2. 启动应用

uvicorn main:app --reload
  • main: 文件名(如 main.py)。
  • app: FastAPI 实例的名称。
  • --reload: 开发模式下自动重新加载服务器。

3. 访问 API 文档

  • 自动文档:http://localhost:8000/docs(Swagger UI)。
  • ReDoc 文档:http://localhost:8000/redoc

三、核心功能详解

1. 路由定义与请求处理

HTTP 方法映射
HTTP 方法 装饰器 示例
GET @app.get() 获取资源
POST @app.post() 创建资源
PUT @app.put() 更新资源
DELETE @app.delete() 删除资源
路径参数
@app.get("/items/{item_id}")
def read_item(item_id: int):
    return {"item_id": item_id}
查询参数
@app.get("/items/")
def read_items(skip: int = 0, limit: int = 10):
    return {"skip": skip, "limit": limit}

2. 数据验证与 Pydantic 模型

定义请求体模型
from pydantic import BaseModel
from typing import Optional

class Item(BaseModel):
    name: str
    price: float
    description: Optional[str] = None
    tax: Optional[float] = None
使用模型处理 POST 请求
@app.post("/items/")
def create_item(item: Item):
    return item
示例请求
{
  "name": "Foo",
  "price": 45.2,
  "description": "A very nice item",
  "tax": 3.2
}

3. 异步编程支持

异步函数示例
import asyncio

@app.get("/async")
async def async_example():
    await asyncio.sleep(1)  # 模拟 I/O 操作
    return {"message": "Async response"}
异步数据库操作
@app.get("/db")
async def fetch_data():
    data = await async_db_query()  # 假设的异步数据库查询
    return data

4. 中间件(Middleware)

自定义中间件示例
@app.middleware("http")
async def log_request_time(request, call_next):
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    print(f"请求路径: {request.url.path}, 处理时间: {process_time:.4f} 秒")
    return response
内置中间件
  • SessionMiddleware: 管理会话(需 itsdangerous)。
  • CORS: 跨域资源共享支持(通过 CORSMiddleware)。

5. 依赖注入(Dependency Injection)

创建依赖项
from fastapi import Depends

def get_db():
    db = "Database Connection"
    try:
        yield db
    finally:
        db.close()
在路由中使用依赖
@app.get("/users/")
def read_users(db: str = Depends(get_db)):
    return {"db": db}

6. 文件上传与表单数据

处理文件上传
from fastapi import File, UploadFile

@app.post("/uploadfile/")
def upload_file(file: UploadFile = File(...)):
    return {"filename": file.filename}
处理表单数据
from fastapi import Form

@app.post("/login")
def login(username: str = Form(...), password: str = Form(...)):
    return {"username": username}

7. 错误处理与异常响应

自定义异常
from fastapi import HTTPException

@app.get("/items/{item_id}")
def read_item(item_id: int):
    if item_id < 0:
        raise HTTPException(status_code=404, detail="Item not found")
    return {"item_id": item_id}
全局异常处理
from fastapi import FastAPI, HTTPException
from starlette.exceptions import HTTPException as StarletteHTTPException

@app.exception_handler(StarletteHTTPException)
def custom_http_exception_handler(request, exc):
    return JSONResponse({"error": exc.detail}, status_code=exc.status_code)

四、高级功能

1. OAuth2 与 JWT 认证

使用 OAuth2 密码流程
from fastapi.security import OAuth2PasswordBearer
from fastapi import Depends

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

@app.get("/users/me")
def read_users_me(token: str = Depends(oauth2_scheme)):
    return {"token": token}

2. 背景任务(Background Tasks)

执行后台任务
from fastapi import BackgroundTasks

def write_log(message: str):
    with open("log.txt", "a") as f:
        f.write(message + "\n")

@app.post("/send-notification/")
def send_notification(background_tasks: BackgroundTasks):
    background_tasks.add_task(write_log, "Notification sent")
    return {"message": "Notification sent in background"}

3. WebSocket 支持

实现 WebSocket 路由
from fastapi import WebSocket

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        data = await websocket.receive_text()
        await websocket.send_text(f"Message text was: {data}")

五、部署与优化

1. 生产环境部署

  • 使用 Uvicorn 或 Gunicorn 部署:
    uvicorn main:app --host 0.0.0.0 --port 8000
  • 使用 Nginx 作为反向代理,负载均衡。

2. 性能优化

  • 异步处理: 尽量使用 async def 和 await
  • 缓存: 使用 Redis 或 FastAPI 的 Cache-Control
  • 数据库优化: 使用连接池、索引等。

六、最佳实践

  1. 遵循 RESTful 风格:

    • 使用名词表示资源(如 /users)。
    • 使用 HTTP 方法表示操作(GET/POST/PUT/DELETE)。
  2. 自动生成文档:

    • 利用 Swagger UI 和 ReDoc 自动生成 API 文档。
  3. 类型提示:

    • 使用 Python 3.8+ 的类型提示,提高代码可读性和安全性。
  4. 模块化设计:

    • 将路由拆分为多个模块,使用 APIRouter 组织代码。

七、参考资料

  • 官方文档: https://fastapi.tiangolo.com
  • GitHub 仓库: GitHub - fastapi/fastapi: FastAPI framework, high performance, easy to learn, fast to code, ready for production
  • Pydantic 文档: https://pydantic-docs.helpmanual.io

你可能感兴趣的:(python,fastapi,后端)