跳转到内容
主菜单
主菜单
移至侧栏
隐藏
导航
首页
最近更改
随机页面
MediaWiki帮助
代码酷
搜索
搜索
中文(中国大陆)
外观
创建账号
登录
个人工具
创建账号
登录
未登录编辑者的页面
了解详情
贡献
讨论
编辑“︁
Python Fastap
”︁(章节)
页面
讨论
大陆简体
阅读
编辑
编辑源代码
查看历史
工具
工具
移至侧栏
隐藏
操作
阅读
编辑
编辑源代码
查看历史
常规
链入页面
相关更改
特殊页面
页面信息
外观
移至侧栏
隐藏
您的更改会在有权核准的用户核准后向读者展示。
警告:
您没有登录。如果您进行任何编辑,您的IP地址会公开展示。如果您
登录
或
创建账号
,您的编辑会以您的用户名署名,此外还有其他益处。
反垃圾检查。
不要
加入这个!
= Python FastAPI = '''FastAPI''' 是一个现代、快速(高性能)的 Python Web 框架,用于构建 API。它基于标准 Python 类型提示,使用 [[Starlette]] 和 [[Pydantic]] 构建,提供了极高的性能,接近 [[Node.js]] 和 [[Go]] 的速度。FastAPI 特别适合开发 RESTful API、微服务以及需要高性能的 Web 应用程序。 == 核心特性 == FastAPI 的主要特点包括: * '''高性能''':基于 [[ASGI]](异步服务器网关接口),支持异步请求处理。 * '''自动文档生成''':内置 [[Swagger UI]] 和 [[ReDoc]],自动生成交互式 API 文档。 * '''数据验证''':使用 [[Pydantic]] 进行请求和响应数据的自动验证。 * '''依赖注入系统''':简化代码组织,提高可维护性。 * '''类型安全''':利用 Python 类型提示,减少运行时错误。 == 安装 == FastAPI 可以通过 pip 安装: <syntaxhighlight lang="bash"> pip install fastapi </syntaxhighlight> 此外,需要一个 ASGI 服务器(如 [[Uvicorn]])来运行 FastAPI 应用: <syntaxhighlight lang="bash"> pip install uvicorn </syntaxhighlight> == 基本示例 == 以下是一个简单的 FastAPI 应用示例: <syntaxhighlight lang="python"> from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"message": "Hello, World!"} @app.get("/items/{item_id}") def read_item(item_id: int, q: str = None): return {"item_id": item_id, "q": q} </syntaxhighlight> 运行应用: <syntaxhighlight lang="bash"> uvicorn main:app --reload </syntaxhighlight> 访问 `http://127.0.0.1:8000/` 将返回: <syntaxhighlight lang="json"> {"message": "Hello, World!"} </syntaxhighlight> 访问 `http://127.0.0.1:8000/items/5?q=test` 将返回: <syntaxhighlight lang="json"> {"item_id": 5, "q": "test"} </syntaxhighlight> == 请求和响应模型 == FastAPI 使用 Pydantic 模型定义数据结构: <syntaxhighlight lang="python"> from pydantic import BaseModel from fastapi import FastAPI app = FastAPI() class Item(BaseModel): name: str price: float is_offer: bool = None @app.post("/items/") def create_item(item: Item): return item </syntaxhighlight> 发送 POST 请求: <syntaxhighlight lang="json"> { "name": "Laptop", "price": 999.99, "is_offer": true } </syntaxhighlight> 响应: <syntaxhighlight lang="json"> { "name": "Laptop", "price": 999.99, "is_offer": true } </syntaxhighlight> == 异步支持 == FastAPI 支持异步请求处理: <syntaxhighlight lang="python"> from fastapi import FastAPI import httpx app = FastAPI() @app.get("/async-example/") async def fetch_data(): async with httpx.AsyncClient() as client: response = await client.get("https://api.example.com/data") return response.json() </syntaxhighlight> == 依赖注入 == FastAPI 的依赖注入系统简化了代码复用: <syntaxhighlight lang="python"> from fastapi import Depends, FastAPI app = FastAPI() def common_parameters(q: str = None, skip: int = 0, limit: int = 100): return {"q": q, "skip": skip, "limit": limit} @app.get("/items/") def read_items(commons: dict = Depends(common_parameters)): return commons </syntaxhighlight> == 实际应用案例 == FastAPI 适用于多种场景,包括: * '''微服务架构''':构建轻量级、高性能的微服务。 * '''数据 API''':为前端应用或移动应用提供数据接口。 * '''机器学习 API''':部署机器学习模型作为 RESTful 服务。 === 机器学习 API 示例 === <syntaxhighlight lang="python"> from fastapi import FastAPI from pydantic import BaseModel import joblib app = FastAPI() model = joblib.load("model.pkl") class PredictionInput(BaseModel): feature1: float feature2: float @app.post("/predict/") def predict(input: PredictionInput): prediction = model.predict([[input.feature1, input.feature2]]) return {"prediction": prediction[0]} </syntaxhighlight> == 性能比较 == FastAPI 的性能接近原生 [[Go]] 和 [[Node.js]]: <mermaid> barChart title Web框架性能比较(请求/秒) x-axis 框架 y-axis 性能 bar FastAPI : 50000 bar Flask : 10000 bar Django : 5000 bar Node.js : 55000 bar Go : 60000 </mermaid> == 数学支持 == FastAPI 可以处理数学运算请求,例如计算圆的面积: <syntaxhighlight lang="python"> from fastapi import FastAPI from pydantic import BaseModel import math app = FastAPI() class Circle(BaseModel): radius: float @app.post("/area/") def calculate_area(circle: Circle): area = math.pi * circle.radius ** 2 return {"area": area} </syntaxhighlight> 数学公式表示为: <math> A = \pi r^2 </math> == 进阶主题 == * '''中间件''':自定义请求/响应处理流程。 * '''WebSockets''':实现实时双向通信。 * '''OAuth2 认证''':集成安全认证系统。 * '''数据库集成''':与 [[SQLAlchemy]] 或 [[Tortoise-ORM]] 配合使用。 == 总结 == FastAPI 是一个功能强大、易于使用的现代 Python Web 框架,特别适合构建高性能 API。它的自动文档生成、数据验证和异步支持使其成为 Python Web 开发的优秀选择。无论是初学者还是经验丰富的开发者,都能快速上手并构建高效的 Web 应用。 [[Category:编程语言]] [[Category:Python]] [[Category:Python Web 开发]]
摘要:
请注意,所有对代码酷的贡献均被视为依照知识共享署名-非商业性使用-相同方式共享发表(详情请见
代码酷:著作权
)。如果您不希望您的文字作品被随意编辑和分发传播,请不要在此提交。
您同时也向我们承诺,您提交的内容为您自己所创作,或是复制自公共领域或类似自由来源。
未经许可,请勿提交受著作权保护的作品!
取消
编辑帮助
(在新窗口中打开)