2025-08-11初次了解
2025-08-12增加了async和apirouter和数据校验
2025-08-13更新了 url中的 path query参数获取,添加architecture
一个典型的fastapi项目的architecture
之前用过django、flask,想着不用学习fastapi吧,可是突然有一天,也许就是今天,大模型给生成的代码竟然直接是fastapi的了,这时候不了解也不行了。
fastapi有如下特点:
1、自带swagger的openapi
2、可以使用async定义的路由函数
3、APIRouter类似于flask blueprint
4、数据模型解析和校验
uvicorn main:app –reload
fastapi看起来和flask很类似,令我有点疑惑的就是async了。
fasatapi how-to?
如何获取url path参数?
如何获取url query参数?
截图中的user_message就是query参数
如何获取Form数据?
from fastapi import Form
特性:async
从来没有使用过fastapi的人,一定会诧异async def定义的路由函数,为什么要在def前面加上一个async呢?其实这个async正好是fastapi的精华。
特性:自带swagger
http://127.0.0.1:8000/docs#/
uvicorn main:app –reload
def vs async
同步的路由函数会被放到线程池中运行,但线程数有限,这种写法可以用但不推荐
async def 定义的路由函数会运行在事件循环线程
@app.get("/bad")
async def bad_endpoint():
time.sleep(5) # ❌ 同步阻塞, 结果:整个事件循环被卡住 5 秒,无法调度其他协程。
return {"msg": "done"}
使用await asyncio.sleep(5),访问/demo还是5秒后才会响应,但是主线程不会被完全阻塞,主线程还会去处理其他调用。
await 不是“后台运行”,而是“挂起+恢复”
❌ 错误理解:await 是“启动一个后台任务,然后继续”
✅ 正确理解:await 是“我在这里等,但我允许别人先运行,等完了我再继续”
fastapi中的APIRouter类似于flask中的blueprint
from fastapi import APIRouter
router = APIRouter(prefix="/v2")
@router.get("/info", response_class=JSONResponse)
async def v2_info():
import asyncio
await asyncio.sleep(5)
return JSONResponse(content={"message": "This is a v2 info endpoint."})
app.include_router(router)
fastapi的数据模型解析
class Item(BaseModel):
name: str
@router.post(“/items/”, response_class=JSONResponse)
async def create_item(item: Item):
# item to json
item_json = item.model_dump_json()
print(f"Received item: {item_json}")
return JSONResponse(content={"message": "Item created successfully", "item": item_json})
默认行为:Pydantic 模型只从 JSON 解析,也就是说前端要使用application/json
fastapi vs django vs flask, which one is the better one? please don’t care about it, just choose one ,and write your code.
python types
https://fastapi.tiangolo.com/python-types/
学习fastapi的另一个目的就是作为langchain\\langgraph的托管者,看github上面有几个脚手架,后面也可以参考一下
https://github.com/wassim249/fastapi-langgraph-agent-production-ready-template
https://github.com/JoshuaC215/agent-service-toolkit
评论前必须登录!
注册