当前位置: 首页 > news >正文

【Python】FastApi

一,概述

有时候,开发一个简单的后端应用,使用Spring显得太冗余、臃肿,这个时候FastAPI便是首选。

FastAPI 是一个现代化的高性能 Python Web 框架,专门用于构建 API(应用程序编程接口)。它基于 Python 3.7+ 的类型提示(Type Hints)特性,结合了 Starlette(用于 Web 处理)和 Pydantic(用于数据验证)两大组件。

核心特点

  1. 极高性能

    • 与 NodeJS 和 Go 相当的性能

    • 得益于 Starlette 和 Pydantic 的底层优化

  2. 快速开发

    • 自动生成交互式 API 文档(Swagger UI 和 ReDoc)

    • 智能编辑器支持,减少调试时间

  3. 类型安全

    • 基于 Python 类型提示

    • 在编码时即可捕获许多错误

  4. 异步支持

    • 原生支持 async/await

    • 适合 I/O 密集型应用

主要功能

  • 请求参数自动验证

  • 依赖注入系统

  • 安全与认证(OAuth2、JWT等)

  • WebSocket 支持

  • GraphQL 集成

  • 测试客户端

二,实例

from typing import Listfrom fastapi import FastAPI, Query, Header, Cookie, Requestfrom pydantic import BaseModelfrom route1 import route_apiclass Body(BaseModel):name: strsize: intdef __str__(self):return f"name={self.name},size={self.size}"# 创建应用实例
app = FastAPI()
# 导入模块路由
app.include_router(route_api)# 定义路由
@app.get("/")
async def read_root():return {"message": "欢迎使用 FastAPI"}"""
路径参数实例
"""@app.get("/items/{item_id}")
async def read_item(item_id: int | None, q: str | None = None):return {f"item_id={item_id} q={q}"}"""
查询参数
"""@app.get("/query/q1")
async def read_root(q: str = None):return {"message": f"q={q}"}@app.get("/query/q2")
async def read_root(q: str = Query(None, max_length=50, pattern=r'^\d+$')):return {"message": f"q={q}"}@app.get("/query/q3")
async def read_root(q: List[str] = Query(None, max_length=50)):# 多参数使用,如列表 http://127.0.0.1:8000/query/q3?q=123123&q=1231return {"message": f"q={q}"}"""Post相关"""@app.post("/post1", response_model=Body)
async def post_item(body: Body):print(body)return body"""添加Header头"""@app.get("/head")
async def read_root(q: List[str] = Query(None, max_length=50), user_agent: str = Header(None)):# 多参数使用,如列表 http://127.0.0.1:8080/query/q3?q=123123&q=1231return {"message": f"q={q} User-Agent=f{user_agent}"}"""获得Request"""@app.get("/request")
async def read_request(request: Request):"""此处便可以通过request获得Request对象"""return {"request": f"{request.method}"}if __name__ == '__main__':"""等效命令:reload是热部署,开发阶段直接修改代码生效uvicorn main:app --reload"""import uvicornuvicorn.run("main:app", port=8080, reload=True)

如果涉及多模块,则可使用Route

"""
路由的意义,在于大项目时,模块划分,而非单独只使用FastApi在一个文件中导致臃肿"""from fastapi import APIRouterroute_api = APIRouter()@route_api.get("/r1/get1")
async def get1():return {"method": "hello from route"}@route_api.get("/r1/get2")
async def get2(q: str | None = None):return {"method": f"hello {q} from route"}

可以直接在host后加docs路径,即可自动化生成api说明,如http://127.0.0.1:8080/docs,

http://www.dtcms.com/a/271299.html

相关文章:

  • P1009 [NOIP 1998 普及组] 阶乘之和
  • HashMap中get()、put()详解
  • 代码审计-shiro漏洞分析
  • Explain关键字
  • rt thread studio 和 KEIL对于使用rt thread 的中间件和组件,哪个更方便
  • Flask3.1打造极简CMS系统
  • VsCode 接入Continue 远程调用(持续扩展 + DeepSeek R1)— 免本地算力
  • ZECN致业:科创微光,照亮技术新征程
  • 200nl2sql
  • Linux建立本地软件仓库
  • 存储服务一NFS文件存储概述
  • 解锁HTML5页面生命周期API:前端开发的新视角
  • debug和release的区别,打印菱形,水仙花数,喝汽水问题,计算求和
  • 从互联网电脑迁移Dify到内网部署Dify方法记录
  • 语音识别核心模型的数学原理和公式
  • http get和http post的区别
  • 【软件工程】tob和toc含义理解
  • 【25软考网工】第十章 (3)网络冗余设计、广域网接入技术
  • Docker 高级管理 -- 容器通信技术与数据持久化
  • mysql 故障检测与处理
  • Linux 测开:日志分析 + 定位 Bug
  • Paimon 原子提交实现
  • 【Linux】Rocky Linux 安装 Docker 与 Docker-Compose
  • AI智能选股,DeepSeek智能分析股票测试
  • 搭建一款结合传统黄历功能的日历小程序
  • C++最小生成树算法详解
  • 人机协同的关键枢纽:软件工程3.0中对象模型与模型驱动的融合路径
  • Vue 3 中父子组件双向绑定的 4 种方式
  • 如何将 AWS EBS 卷从 gp2 批量迁移到 gp3:完整指南
  • 基于Spring Boot+Vue的DIY手工社预约管理系统(Echarts图形化、腾讯地图API)