基础操作 路由 基本写法如下
1 2 3 4 5 6 7 8 9 10 from fastapi import FastAPIapp = FastAPI() @app.get("/" ) async def index (): return {"message" :"Welcome" }
发送参数 路径参数Path() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 from fastapi import FastAPI,Pathapp = FastAPI() @app.get("/{username}" ) async def index ( username: str = Path("root" ,min_length=2 , max_length=10 ) ): return {"message" :f"Welcome,{username} " }
查询参数Query() 1 2 3 4 5 6 7 8 9 10 11 12 from fastapi import FastAPI,Queryapp = FastAPI() @app.get("/" ) async def index ( username: str = Query("root" , min_length=2 , max_length=10 ) ): return {"message" :f"Welcome,{username} " }
请求体参数Field() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 from fastapi import FastAPIfrom pydantic import BaseModel,Fieldapp = FastAPI() class User (BaseModel ): username: str = Field("root" , min_length=2 , max_length=10 ) user_year: int = Field(..., gt=0 ) @app.get("/" ) async def index (user:User ): return {"message" :"Welcome" ,"information" :user}
接收请求 json 默认返回即json格式
html 装饰器指定响应类 1 2 3 4 5 6 7 8 9 10 11 12 from fastapi import FastAPI,Pathfrom fastapi.response import HTMLResponseapp = FastAPI() @app.get("/{username}" , response_class = HTMLResponse ) async def index (username: str = Path(... ) ): return f"<h1>Welcome,{username} <h1>"
返回响应对象 1 2 3 4 5 6 7 8 9 10 11 12 from fastapi import FastAPI,Pathfrom fastapi.response import HTMLResponseapp = FastAPI() @app.get("/{username}" ) async def index (username: str = Path(... ) ): return HTMLResponse(f"<h1>Welcome,{username} <h1>" )
file 1 2 3 4 5 6 7 8 9 10 11 12 13 from fastapi import FastAPI,Pathfrom fastapi.response import FileResponseapp = FastAPI() @app.get("/" ) async def index (): file_path = "./files/1.jpeg" return FileResponse(file_path)
自定义响应 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 from fastapi import FastAPIfrom pydantic import BaseModelapp = FastAPI() class User (BaseModel ): username: str user_year: int @app.get("/" , response_model = User ) async def index (): return { "username" : "root" , "user_year" : 1 }
异常处理 使用HTTPException
1 2 3 4 5 6 7 8 9 10 11 12 13 from fastapi import FastAPI,HTTPExceptionapp = FastAPI() @app.get("/{id}" ) async def index (id : int ): ids = [1 , 2 , 3 , 4 , 5 ] if id not in ids: raise HTTPException(status_code=404 , detail="当前id不存在" ) return {"message" :f"当前id是{id } " }
进阶 中间件 每个请求前、响应前均执行一次的代码,可以有多个中间件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 from fastapi import FastAPIapp = FastAPI() @app.middleware("http" ) async def middleware1 (request, call_next ): print ("中间件1 开始" ) response = await call_next(request) print ("中间件1 结束" ) return response @app.get("/" ) async def index (): return {"message" :"Welcome" }
依赖注入 共享通用逻辑,减少重复
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 from fastapi import FastAPI,Depends,Queryapp = FastAPI() async def common ( page: int = Query(0 , ge=0 ), page_size: int ): return {"page" :page, "page_size" : page_size} @app.get("/list" ) async def list (commons = Depends(common ) ): return commons
ORM 自动处理与数据库连接,使用面向对象编程操作数据库
使用sqlalchemy和aiomysql库
建表 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 from fastapi import FastAPIfrom sqlalchemy.ext.asyncio import create_async_engineapp = FastAPI() ASYNC_DATABASE_URL = "mysql+aiomysql://root:123456@localhost:3306/fastapi?charset=utf8" async_engine = create_async_engine( ASYNC_DATABASE_URL, echo=True , pool_size=10 , max_overflow=20 ) @app.get("/" ) async def index (): return {"message" :"Welcome" }
定义模型类 基类:创建时间、更新时间
书籍表:书名、作者、简介
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 from sqlalchemy.orm import DeclarativeBase,mapped_column,Mappedfrom sqlalchemy import DateTime, Stringfrom sqlalchemy.sql import funcclass Base (DeclarativeBase ): created_time : Mapped[datetime] = mapped_column(DateTime, insert_default=func.now(),default=func.now(),comment="创建时间" ) updated_time : Mapped[datetime] = mapped_column(DateTime, insert_default=func.now(), default=func.now(),onupdate=func.now(),comment="修改时间" ) class Book (Base ): __tablename__ = "book" book_id : Mapped[int ] = mapped_column(primary_key=True , comment="书籍id" ) book_name : Mapped[str ] = mapped_column(String(255 ),comment="名称" ) book_introduction : Mapped[str ] =mapped_column(String(255 ),comment="简介" )
建表 1 2 3 4 5 6 7 8 9 10 #寤鸿〃 @asynccontextmanager async def lifespan(app: FastAPI): async with async_engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) yield await async_engine.dispose() app = FastAPI(lifespan=lifespan)