Python FastAPI

介绍

FastAPI 是 Python 里写 API 接口最快、最简单、最强的现代 Web 框架,写后端接口的 "超级工具包"https://fastapi.tiangolo.com/

  • 写接口速度极快
  • 自动生成文档 访问 /docs 自动出漂亮的接口页面
  • 自带数据校验
  • 性能接近 Go / Node
  • 代码超级简洁

FastAPI = Starlette(高性能 Web) + Pydantic(数据校验)

写一个最简单的接口

python 复制代码
# main.py
from fastapi import FastAPI

# 1. 创建 app
app = FastAPI()

# 2. 写接口(路径:/ ,GET请求)
@app.get("/")
def home():
    return {"message": "你好,FastAPI!"}

# 3. 再写一个接口
@app.get("/user")
def get_user():
    return {"name": "张三", "age": 20}

运行,Uvicorn 是 "高性能服务器",负责把接口暴露给别人访问,

  • Python 代码 → 交给 Python 解释器运行
  • FastAPI 应用 → 交给 Uvicorn 服务器运行

自动生成的接口文档地址

python 复制代码
#uvicorn:启动服务器
#main:去找 main.py 文件
#app:去找文件里的 app = FastAPI()
--reload:代码改了自动重启
uvicorn main:app --reload

最常用的写法是加上Pydantic一起用

python 复制代码
from pydantic import BaseModel

# 定义数据格式(你学过的 BaseModel)
class User(BaseModel):
    name: str
    age: int
    email: str

# 接收 JSON
@app.post("/add_user")
def add_user(user: User):
    # 直接用 user.name, user.age, user.email
    return {
        "msg": "添加成功",
        "name": user.name,
        "age": user.age
    }

FastAPI的生命周期

历史用法是,直接加入@app.on_event("startup")装饰器吗,现有的用法被整合到一起使用,

@asynccontextmanager,同时 也支持websocket @app.websocket

python 复制代码
from dotenv import load_dotenv
from fastapi import FastAPI
from langchain.agents import create_agent
from langchain_core.messages import HumanMessage
from langchain_mcp_adapters.client import MultiServerMCPClient
from pydantic import BaseModel
import uvicorn
from contextlib import asynccontextmanager  # 新增

load_dotenv()


agent = None
client = None


@asynccontextmanager
async def lifespan(app: FastAPI):
    global agent, client
    # ====================== 【服务启动时执行】 ======================
    print("🚀 服务启动,初始化 AI 智能体...")

    client = MultiServerMCPClient(
        {
            "math": {
                "transport": "stdio",
                "command": "python",
                "args": [r"D:\project\pyproject\agent\tools\Math.py"],
            },
        }
    )
    tools = await client.get_tools()
    agent = create_agent(model="deepseek-chat", tools=tools)

    # 服务运行中
    yield

    # ====================== 【服务关闭时执行】 ======================
    print("服务关闭,清理资源...")
    if client is not None:
        await client.close()  # 优雅关闭客户端


app = FastAPI(
    title="LangChain Agent API",
    lifespan=lifespan
)


# ====================== 请求模型 ======================
class ChatRequest(BaseModel):
    question: str


# ====================== Java 调用接口 ======================
@app.post("/agent/chat")
async def chat(request: ChatRequest):
    response = await agent.ainvoke({
        "messages": [
            HumanMessage(content=request.question)
        ]
    })
    answer = response["messages"][-1].content
    return {
        "code": 200,
        "message": "success",
        "data": answer
    }


# ====================== 启动服务 ======================
if __name__ == '__main__':
    uvicorn.run(app, host="0.0.0.0", port=19000)
相关推荐
曲幽4 天前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
CaffeinePro7 天前
依赖注入:FastAPI最核心的解耦能力案例解析
后端·fastapi
曲幽10 天前
刚部署的 LibreTranslate 频频翻车?我掏出了 20 年前的 StarDict 词典,用 FastAPI 搭了个本地词典翻译 API
python·fastapi·web·translate·goldendict·libretranslate·stardict·pystardict
CaffeinePro14 天前
Pydantic深度使用:数据校验、枚举、ORM映射
后端·fastapi
jay神16 天前
基于 FastAPI + Vue 的宠物领养管理系统
前端·vue.js·python·毕业设计·fastapi·宠物
染指111017 天前
6.AI大模型-搭建本地大模型服务体系
fastapi·oneapi
codeaideaai18 天前
使用UV创建python项目
python·fastapi·uv
放下华子我只抽RuiKe518 天前
FastAPI 全栈后端(八):部署与运维
运维·数据库·react.js·oracle·数据挖掘·前端框架·fastapi
SilentSamsara18 天前
模型部署实战:FastAPI + ONNX + Docker 的推理服务化
人工智能·pytorch·python·深度学习·机器学习·fastapi
放下华子我只抽RuiKe518 天前
FastAPI 全栈后端(七):测试与自动化
运维·前端·人工智能·react.js·前端框架·自动化·fastapi