别院牧志知识库 别院牧志知识库
首页
  • 基础

    • 全栈之路
    • 😎Awesome资源
  • 进阶

    • Python 工匠系列
    • 高阶知识点
  • 指南教程

    • Socket 编程
    • 异步编程
    • PEP 系列
  • Python 面试题
  • 2025 面试记录
  • 2022 面试记录
  • 2021 面试记录
  • 2020 面试记录
  • 2019 面试记录
  • 数据库索引原理
  • 基金

    • 基金知识
    • 基金经理
  • 细读经典

    • 德隆-三个知道
    • 孔曼子-摊大饼理论
    • 配置者说-躺赢之路
    • 资水-建立自己的投资体系
    • 反脆弱
  • Git 参考手册
  • 提问的智慧
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
首页
  • 基础

    • 全栈之路
    • 😎Awesome资源
  • 进阶

    • Python 工匠系列
    • 高阶知识点
  • 指南教程

    • Socket 编程
    • 异步编程
    • PEP 系列
  • Python 面试题
  • 2025 面试记录
  • 2022 面试记录
  • 2021 面试记录
  • 2020 面试记录
  • 2019 面试记录
  • 数据库索引原理
  • 基金

    • 基金知识
    • 基金经理
  • 细读经典

    • 德隆-三个知道
    • 孔曼子-摊大饼理论
    • 配置者说-躺赢之路
    • 资水-建立自己的投资体系
    • 反脆弱
  • Git 参考手册
  • 提问的智慧
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • 辨析

  • Sockets编程

  • Django

  • Flask

  • FastAPI

    • FastAPI 快速上手指南
      • FastAPI 依赖注入:从入门到实践
    • 全栈之路

    • 面试

    • 代码片段

    • 异步编程

    • 😎Awesome资源

    • PEP

    • Python工匠系列

    • 高阶知识点

    • Python 学习资源待整理
    • 设计模式

    • stackoverflow

    • 好“艹蛋”的 Python 呀!
    • FIFO | 待学清单📝
    • pip 安装及使用
    • 数据分析

    • 源码阅读计划

    • OOP

    • 关于 python 中的 setup.py
    • 并行分布式框架 Celery
    • 七种武器,让你的代码提高可维护性
    • 使用 pdb 调试 Python 代码
    • 每周一个 Python 标准库
    • 🐍Python
    • FastAPI
    佚名
    2025-07-04
    目录

    FastAPI 快速上手指南

    # 核心优势(相比 Flask/Django)

    1. 异步支持:原生支持 async/await,高性能
    2. 类型提示:Python 类型提示自动校验请求/响应
    3. 自动文档:自动生成 OpenAPI 文档(Swagger UI 和 ReDoc)
    4. 性能卓越:接近 Node.js/Go 的速度(基于 Starlette 和 Pydantic)

    # 1. 安装与环境

    pip install fastapi uvicorn[standard]
    
    1

    # 2. 基础结构(对比 Flask/Django)

    # main.py
    from fastapi import FastAPI
    
    app = FastAPI()  # 类似 Flask 的 app = Flask(__name__)
    
    @app.get("/")  # 路由装饰器类似 Flask
    async def root():
        return {"message": "Hello World"}
    
    # 运行命令:uvicorn main:app --reload
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10

    # 3. 核心功能快速掌握

    # 路径参数(类似 Flask)

    @app.get("/items/{item_id}")
    async def read_item(item_id: int):  # 类型自动转换和验证
        return {"item_id": item_id}
    
    1
    2
    3

    # 查询参数(自动解析)

    @app.get("/items/")
    async def list_items(skip: int = 0, limit: int = 10):  # 默认值处理
        return {"skip": skip, "limit": limit}
    
    1
    2
    3

    # 请求体(Pydantic 模型是核心)

    from pydantic import BaseModel
    
    class Item(BaseModel):
        name: str
        description: str = None  # 可选参数
        price: float
        tax: float = None  # 可选参数
    
    @app.post("/items/")
    async def create_item(item: Item):  # 模型自动验证
        item_dict = item.dict()
        if item.tax:
            total = item.price + item.tax
            item_dict.update({"total": total})
        return item_dict
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15

    # 响应模型(类似 Django DRF Serializers)

    @app.post("/items/", response_model=Item)  # 自动过滤未声明的字段
    async def create_item(item: Item):
        return item
    
    1
    2
    3

    # 4. 异步支持(比 Flask 更简单)

    import httpx
    
    @app.get("/github/{user}")
    async def fetch_github(user: str):
        async with httpx.AsyncClient() as client:
            response = await client.get(f"https://api.github.com/users/{user}")
            return response.json()
    
    1
    2
    3
    4
    5
    6
    7

    # 5. 依赖注入(强大特性)

    from fastapi import Depends
    
    def query_extractor(q: str = None):
        return q
    
    @app.get("/search")
    async def search(query: str = Depends(query_extractor)):
        return {"query": query}
    
    1
    2
    3
    4
    5
    6
    7
    8

    # 类形式依赖

    class Paginator:
        def __init__(self, page: int = 1, size: int = 10):
            self.page = page
            self.size = size
    
    @app.get("/products")
    async def list_products(paginator: Paginator = Depends()):
        return {"page": paginator.page, "size": paginator.size}
    
    1
    2
    3
    4
    5
    6
    7
    8

    # 6. 中间件(类似 Flask/Django)

    @app.middleware("http")
    async def add_process_time_header(request, call_next):
        start_time = time.time()
        response = await call_next(request)
        process_time = time.time() - start_time
        response.headers["X-Process-Time"] = str(process_time)
        return response
    
    1
    2
    3
    4
    5
    6
    7

    # 7. 错误处理

    from fastapi import HTTPException
    
    @app.get("/protected")
    async def protected_route(token: str):
        if token != "secret":
            raise HTTPException(
                status_code=401,
                detail="Invalid token",
                headers={"WWW-Authenticate": "Bearer"},
            )
        return {"access": "granted"}
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11

    # 自定义异常处理器

    from fastapi.exceptions import RequestValidationError
    
    @app.exception_handler(RequestValidationError)
    async def validation_exception_handler(request, exc):
        return JSONResponse(
            status_code=400,
            content={"detail": "Invalid data", "errors": exc.errors()},
        )
    
    1
    2
    3
    4
    5
    6
    7
    8

    # 8. 文件处理

    from fastapi import UploadFile, File
    
    @app.post("/upload")
    async def upload_file(file: UploadFile = File(...)):
        contents = await file.read()
        return {
            "filename": file.filename,
            "size": len(contents)
        }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9

    # 9. 数据库集成(以 SQLAlchemy 为例)

    # 依赖项管理数据库会话
    from sqlalchemy.orm import Session
    
    def get_db():
        db = SessionLocal()
        try:
            yield db
        finally:
            db.close()
    
    @app.get("/users/{user_id}")
    async def get_user(user_id: int, db: Session = Depends(get_db)):
        return db.query(User).filter(User.id == user_id).first()
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13

    # 10. 安全认证(OAuth2 密码流)

    from fastapi.security import OAuth2PasswordBearer
    
    oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
    
    @app.get("/users/me")
    async def read_current_user(token: str = Depends(oauth2_scheme)):
        user = decode_token(token)  # 自定义解码逻辑
        return user
    
    1
    2
    3
    4
    5
    6
    7
    8

    # 11. 自动文档

    • Swagger UI:http://localhost:8000/docs
    • ReDoc:http://localhost:8000/redoc

    Swagger 示例

    # 12. 部署生产

    # 使用 Gunicorn + Uvicorn 工作进程
    gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app
    
    1
    2

    # 推荐部署栈

    1. 反向代理:Nginx
    2. 进程管理:Gunicorn + Uvicorn
    3. 容器化:Docker(官方提供 Python 镜像)
    4. 云服务:AWS/GCP 或 Docker Swarm/Kubernetes

    # 迁移技巧(Flask/Django → FastAPI)

    1. 路由:装饰器语法类似 Flask
    2. 视图:将同步函数改为 async def
    3. 请求解析:用 Pydantic 模型替代 Flask 的 request.json
    4. 中间件:FastAPI 中间件兼容 ASGI 标准
    5. 依赖注入:替代 Flask 的全局 g 对象

    # 学习资源

    1. 官方文档 (opens new window)(含中文)
    2. FastAPI GitHub (opens new window)
    3. Awesome FastAPI (opens new window)
    graph TD
        A[FastAPI] --> B[路由]
        A --> C[Pydantic 模型]
        A --> D[依赖注入]
        A --> E[异步支持]
        B --> F[路径参数]
        B --> G[查询参数]
        C --> H[请求体验证]
        C --> I[响应模型]
        D --> J[数据库连接]
        D --> K[认证管理]
        E --> L[HTTP 客户端]
        E --> M[数据库操作]
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13

    提示:利用好 FastAPI 的自动文档和类型提示,开发效率可提升 2-3 倍!

    编辑 (opens new window)
    #FastAPI#异步编程
    上次更新: 2025-07-04, 02:30:37
    Awesome Flask 中文版
    FastAPI 依赖注入:从入门到实践

    ← Awesome Flask 中文版 FastAPI 依赖注入:从入门到实践→

    最近更新
    01
    FastAPI 依赖注入:从入门到实践
    07-04
    02
    MongoDB 与 PyMongo 使用指南
    07-04
    03
    本事与投资
    06-20
    更多文章>
    Theme by Vdoing | Copyright © 2019-2025 IMOYAO | 别院牧志
    • 跟随系统
    • 浅色模式
    • 深色模式
    • 阅读模式