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)
相关推荐
li星野10 小时前
从零构建安全文件上传系统:FastAPI + JWT + 密码哈希 + Streamlit 前端 + SQLite
安全·哈希算法·fastapi
郭庆汝1 天前
FastAPI使用笔记
笔记·fastapi
放下华子我只抽RuiKe52 天前
FastAPI 全栈后端(二):路由与数据模型
前端·人工智能·react.js·前端框架·html·fastapi
XGeFei2 天前
【Fastapi学习笔记(7)】—— Fastapi 中间件、前端跨域请求
笔记·学习·fastapi
li星野2 天前
构建安全的文件上传系统:FastAPI + JWT 认证 + Streamlit 前端 + SQLite 数据库
数据库·安全·fastapi
动能小子ohhh2 天前
DocForge平台的设计与开发--文件上传接口的实现
开发语言·人工智能·python·langchain·ocr·fastapi
XGeFei2 天前
【Fastapi学习笔记(6)】—— Fastapi文件上传、请求头自动转换
笔记·学习·fastapi
li星野4 天前
从零搭建带数据库的文件上传系统:FastAPI + Streamlit + SQLite+加上日志
数据库·sqlite·fastapi
海鸥-w4 天前
用python (fastapi)做项目第二天实现新闻列表和新闻详情接口
开发语言·python·fastapi
曲幽4 天前
FastAPI 身份验证总踩坑?这份 FastAPI Users “避坑指南”请收好
python·fastapi·web·jwt·oauth2·user·authentication