# uv pip install "fastapi[standard]" uvicorn
# uvicorn main:app --reload --port 8080 --workers 4 [--reload开发用, 生产守护]
# /docs Swagger 界面接口文档
from fastapi import FastAPI, APIRouter
from fastapi import FastAPI, Header, Cookie, Query
from fastapi.responses import RedirectResponse, JSONResponse, StreamingResponse
from fastapi.middleware.cors import CORSMiddleware
from fastapi import UploadFile, File
from pydantic import BaseModel, Field, EmailStr
import shutil, json
app = FastAPI(
title="FastAPI-Project",
description="描述",
version="1.0.0",
terms_of_service="https://xxx.xx",
contact={
"name": "XiaoYi",
"url": "https://xxx.xx",
"email": "dev@example.com"
}
)
app.add_middleware(
CORSMiddleware,
allow_origins=["http://xxx.xx:5173"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
max_age=604800
)
router_group = APIRouter(prefix="/group", tags=["路由分组"])
# @router_group.get("/group")
@app.get("/item/{item_id}") # ge gt lt le
async def api(item_id: int, q: str = Query(default="0", ge=0), user_agent: str = Header(None), token: str = Cookie(None)):
return "api"
@app.get("/redirect")
async def redirect():
return RedirectResponse(url="/item")
@app.get("/login")
async def login():
resp = JSONResponse(content={"code": 0, "data": "ok"})
resp.set_cookie(
key="token_key",
value="token_value",
max_age=604800, # 单位: 秒
httponly=True,
secure=False,
path="/"
)
return resp
@app.post("/files") # File(...) 表示必须上传multipart/form-data形式文件
async def upload(files: list[UploadFile] = File(...)):
with open(f"uploads/{files[0].filename}", "wb") as buffer:
shutil.copyfileobj(files[0].file, buffer)
return {"Content-Type": files[0].content_type, "Size": files[0].size}
@app.get("/sse")
async def sse():
"""流式输出"""
async def gen():
yield f"data: {json.dumps({"status": "connected"})}\n\n"
yield f"event: event_name\ndata: {json.dumps({"data": "data"})}\n\n"
return StreamingResponse(gen(), media_type="text/event-stream", headers={
"Cache-Control": "no_cache",
"X-Accel-Buffering": "no"
})
class DTO(BaseModel):
name: str | None = Field(default=None, min_length=0, max_length=10, description="用户名")
age: int = Field(ge=0, description="年龄")
email: EmailStr
# uv pip install sqlmodel aiomysql
from sqlalchemy.ext.asyncio import create_async_engine
from sqlmodel.ext.asyncio.session import AsyncSession
from sqlmodel import SQLModel
engine = create_async_engine("mysql+aiomysql://root:password@127.0.0.1:3306/dbname")
async def init_db():
async with engine.begin() as conn:
await conn.run_sync(SQLModel.metadata.create_all)
# bool int Decimal str
from sqlmodel import Field, Column, BigInteger
class Base(SQLModel):
__abstract__ = True
def to_dict(self):
"""遍历所有列取属性值拼字典"""
return {c.name: getattr(self, c.name) for c in self.__table__.columns}
class Table(Base, table=True):
__tablename__ = "table"
id: int = Field(default=None, primary_key=True, sa_type=BigInteger, sa_column_kwargs={"autoincrement": True}, nullable=False, unique=True)
from sqlmodel import select
# await session.rollback() -- except
async def create():
async with AsyncSession(engine) as session:
session.add(Table())
await session.commit()
async def delete(row_id: int):
async with AsyncSession(engine) as session:
# Table 自定义表模型类名
row = await session.get(Table, row_id)
if row:
await session.delete(row)
await session.commit()
async def update(row_id: int):
async with AsyncSession(engine) as session:
row = await session.get(Table, row_id)
if row:
row.name = "new_name"
await session.commit()
async def query():
async with AsyncSession(engine) as session:
stat = select(Table).where(Table.id > 0)
row = (await session.exec(stat)).first()
rows = (await session.exec(stat)).all()
# 乐观锁
from sqlmodel import update
old_version = 0
stat = (
update(Table)
.where(Table.id == row.id, Table.version == old_version)
.values(name="new_name", version = old_version + 1)
)
res = await session.exec(stat) # res.rowcount = 0 表示他人改动过 需要重试
# 悲观锁
# 排他锁: 其他事务既不可读也不可写, 等我提交
stat = select(Table).where(Table.id == row_id).with_for_update()
row = (await session.exec(stat)).first() # 自动上锁
row.balance -= 100 # 操作
await session.commit() # 提交 自动释放锁
# 共享锁: 别人可读, 不可写
stat = select(Table).where(Table.id == row_id).with_for_update(read=True)
# 分页查询
from math import ceil
from sqlmodel import func, select
async def page_query(cur_page: int, page_size: int):
offset_val = (cur_page - 1) * page_size
async with AsyncSession(engine) as session:
stat = select(Table).order_by(Table.id.asc()).offset(offset_val).limit(page_size) # desc
rows = (await session.exec(stat)).all()
rows_data = [row.to_dict() for row in rows]
count_stat = select(func.count()).select_from(Table) # 统计总条数
total = (await session.exec(count_stat)).one()
total_pages = ceil(total / page_size)
return {"rows": rows_data, "total": total, "total_pages": total_pages}