查看: 208|回复: 0

FastAPI异步性能对比:同步接口阻塞与async并发测试

[复制链接]
发表于 1 小时前 | 显示全部楼层 |阅读模式
FastAPI 是 Python 中面向 API 的现代 Web 框架,底层基于 Starlette(ASGI 高性能框架)和 Pydantic(数据验证库),并把 Python 类型提示纳入路由、参数和响应模型处理。它的核心卖点集中在三处:异步并发能力、自动数据校验、自动生成交互式文档。最小示例:
  1. from fastapi import FastAPI
  2. app = FastAPI()
  3. @app.get('/')
  4. async def read_root():
  5.     return {'message': 'Hello, FastAPI!'}
复制代码

这段代码创建了一个完整 API 端点,也是 FastAPI 路由写法的起点。

性能对比数据来自 Techempower Web Framework Benchmarks (Round 20):
FastAPI:约 25,000 请求/秒,延迟 2.1 ms,支持异步;
Flask:约 2,300 请求/秒,延迟 18.5 ms,不支持异步;
Django:约 1,900 请求/秒,延迟 22.3 ms,部分支持异步。
从这组数据看,FastAPI 在高并发 API 场景中相对 Flask、Django 可达到 10 倍以上吞吐提升。

同步和异步写法的差异可用下面代码验证。原文示例使用 time.sleep 模拟 IO,异步版本用 await asyncio.sleep;注意原文未显式给出 import asyncio,实际运行需要补上,否则会触发 NameError。
  1. import time
  2. import asyncio
  3. from fastapi import FastAPI
  4. app = FastAPI()
  5. @app.get('/sync')
  6. def sync_endpoint():
  7.     start_time = time.time()
  8.     for i in range(10):
  9.         time.sleep(1)
  10.     return {'time': time.time() - start_time}
  11. @app.get('/async')
  12. async def async_endpoint():
  13.     start_time = time.time()
  14.     for i in range(10):
  15.         await asyncio.sleep(1)
  16.     return {'time': time.time() - start_time}
复制代码

原文给出的测试结果是:同步 10 次耗时 10.02 秒;异步 10 次耗时 1.01 秒;异步 100 次耗时 1.03 秒;异步 1000 次耗时 1.12 秒。原理是:同步代码里的 time.sleep(1) 会阻塞当前线程,后续请求只能排队;异步代码用 await asyncio.sleep(1),等待期间事件循环可以调度其他请求,从而提升并发处理能力。原文还称当循环次数增加到 10000 次时,异步版本仍能在约 1 秒内完成,而同步版本需要 10000 秒。这里需要结合场景理解:异步优势主要体现在多个请求并发被事件循环调度时;如果是在单个请求内部连续 await 10000 次,等待时间仍会累计,不能把单请求串行等待直接压到 1 秒。压测时应区分单请求串行耗时与并发请求吞吐。

FastAPI 的开发体验同样依赖类型系统。用 Pydantic 定义 Item 模型后,请求体会被自动验证和转换:
  1. from pydantic import BaseModel
  2. class Item(BaseModel):
  3.     name: str
  4.     price: float
  5.     is_offer: bool = None
  6. @app.put('/items/{item_id}')
  7. async def update_item(item_id: int, item: Item):
  8.     return {'item_id': item_id, 'item_name': item.name}
复制代码

这段代码中 item_id 会被转换为 int,item 必须符合 Item 模型;name、price 为必填,is_offer 默认 None。原文使用 is_offer: bool = None,更严格的类型写法可考虑 Optional[bool] 或 bool | None,具体取决于 Python 与 Pydantic 版本。FastAPI 还会从这些声明自动生成 API 文档:访问 /docs 得到 Swagger UI,访问 /redoc 得到 ReDoc。

企业采用案例方面,原文列出 Uber 将 FastAPI 用于部分内部微服务,Netflix 用其构建某些数据科学 API,微软在部分 AI 服务中以 FastAPI 作为接口层。原文还给出电商平台迁移数据:原有 Flask 服务每秒处理 200 订单,迁移到 FastAPI 后提升到 2200 订单/秒,开发时间缩短 30%,主要收益来自自动验证和文档生成。

继续深入 FastAPI,可围绕这些模块展开:路由与请求处理,包括路径参数和查询参数;依赖注入系统;中间件与背景任务;OAuth2、JWT 等安全认证;SQLAlchemy 或 Tortoise-ORM 数据库集成。原文给出的复杂路由示例如下:
  1. @app.get('/users/{user_id}')
  2. async def read_user(
  3.     user_id: int,
  4.     q: str = None,
  5.     short: bool = False
  6. ):
  7.     user = get_user(user_id)
  8.     if q:
  9.         user['q'] = q
  10.     if not short:
  11.         user.update({'detail': 'This is detailed info'})
  12.     return user
复制代码

其中 user_id 是路径参数并被声明为 int,q 和 short 是可选查询参数,short 控制是否附加详细字段。整体来看,FastAPI 的“快”不是单一因素,而是 Starlette ASGI 异步栈、Pydantic 验证、类型提示驱动开发和自动文档共同作用的结果;适合构建高并发 API、微服务接口层以及需要快速产出文档的后端服务。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

指导单位

江苏省公安厅

江苏省通信管理局

浙江省台州刑侦支队

DEFCON GROUP 86025

Hacking Group 021A

旗下站点

态势感知中心

应急响应中心

红盟安全

联系我们

官方QQ群:112851260

官方邮箱:security#ihonker.org(#改成@)

官方核心成员

关注微信公众号

Archiver|手机版|小黑屋| ( 沪ICP备2021026908号 )

GMT+8, 2026-10-3 14:29 , Processed in 0.026551 second(s), 18 queries , Gzip On, Redis On.

Powered by ihonker.com

Copyright © 2015-现在.

  • 返回顶部