<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Starlette &#8211; 李辉 / Grey Li</title>
	<atom:link href="https://greyli.com/tag/starlette/feed/" rel="self" type="application/rss+xml" />
	<link>https://greyli.com</link>
	<description>一个编程和写作爱好者的在线记事本</description>
	<lastBuildDate>Thu, 06 Nov 2025 11:36:11 +0000</lastBuildDate>
	<language>zh-CN</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.9.26</generator>

<image>
	<url>https://greyli.com/wp-content/uploads/2025/03/avatar-500-compressed-144x144.jpg</url>
	<title>Starlette &#8211; 李辉 / Grey Li</title>
	<link>https://greyli.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>请不要把 Flask 和 FastAPI 放到一起比较</title>
		<link>https://greyli.com/flask-fastapi/</link>
		<comments>https://greyli.com/flask-fastapi/#comments</comments>
		<pubDate>Mon, 03 May 2021 14:14:40 +0000</pubDate>
		<dc:creator><![CDATA[李辉]]></dc:creator>
				<category><![CDATA[计算机与编程]]></category>
		<category><![CDATA[APIFlask]]></category>
		<category><![CDATA[FastAPI]]></category>
		<category><![CDATA[Flask]]></category>
		<category><![CDATA[Marshmallow]]></category>
		<category><![CDATA[Pydantic]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Starlette]]></category>

		<guid isPermaLink="false">https://greyli.com/?p=3704</guid>
		<description><![CDATA[The war has begun. Let&#8217;s end the war between Flas [&#8230;]]]></description>
				<content:encoded><![CDATA[
<blockquote>
<p><del>The war has begun.</del> Let&#8217;s end the war between Flask and FastAPI.</p>
</blockquote>
<p>去年在知乎上看到一篇文章，后来想找却找不到了，最后通过关键词「5 分钟」和「四年」在掘金上找到了原文——《<a href="https://juejin.cn/post/6844904051327369224">用它5分钟以后，我放弃用了四年的 Flask</a>》。作者先是给出了一个手动用 if 验证请求数据的 Flask 视图函数：</p>
<pre spellcheck="false" lang="python" cid="n3" mdtype="fences" class="">@app.route('/insert', methods=['POST'])
def insert():
    info = request.json
    name = info.get('name', '')
    if not name:
        return {'success': False, 'msg': 'name 参数不可省略，不可为空！'}
    age = info.get('age', 0)
    if not isinstance(age, int):
        return {'success': False, 'msg': 'age参数不是数字！'}
    age_after_10_years = age + 10
    msg = f'此人名叫：{name}，10年后，此人年龄：{age_after_10_years}'
    return {'success': True, 'msg': msg}</pre>
<p>然后给出了一个使用 Pydantic 编写数据模型类 + FastAPI 路径操作函数的代码：</p>
<pre spellcheck="false" lang="python" cid="n5" mdtype="fences" class="">class People(BaseModel):
    name: str
    age: int
    address: str
    salary: float
    
@app.post('/insert')
def insert(people: People):
    age_after_10_years = people.age + 10
    msg = f'此人名字叫做：{people.name}，十年后此人年龄：{age_after_10_years}'
    return {'success': True, 'msg': msg}</pre>
<p>通过这两段代码进行对比，文章作者得出结论「我用了 Flask 四年，但在使用了5分钟 FastApi 以后，我决定以后不再使用 Flask 了」。你确定你用了四年的是 Flask 而不是 Flash？在此后的很长一段时间里，经常看到类似的对比和结论，所以我打算用这篇文章来澄清这个非常普遍的误解。如果看到有人把 <a href="https://github.com/pallets/flask">Flask</a> 和 <a href="https://github.com/tiangolo/fastapi">FastAPI</a> 放到一起比较，请把这篇文章的链接丢过去。</p>
<blockquote>
<p>利益相关：笔者系 Flask 维护者和 APIFlask 作者。本文观点仅代表个人看法，与 Pallets 团队无关。</p>
</blockquote>
<h2>为什么 Flask 和 FastAPI 不能放到一起比较？</h2>
<p>我在此前介绍 <a href="https://github.com/greyli/apiflask">APIFlask</a> 的文章里一开始就提到过这件事情：</p>
<blockquote>
<p>经常看到有人把 FastAPI 和 Flask 放到一起比较，但是却没有意识到这完全是两种东西——前者是基于 Web 框架 Starlette 添加了 Web API 功能支持的（框架之上的）框架，而后者是和 Starlette 同类的通用 Web 框架。你怎么能让小明和骑电动车的小军赛跑然后还夸小军好快好强？</p>
</blockquote>
<p>前两天看了 Reddit 上 <a href="https://www.reddit.com/r/Python/comments/msbt3p/flask_20_is_coming_please_help_us_test/">Flask 2.0rc 帖子</a>下的很多回复，预感到在 Flask 2.0 发布后在中文网络上也许会出现许多类似的问题和讨论，所以想着还是值得单独写一篇文章来谈这件事。</p>
<p>受那个 Reddit 主题里某个评论启发，想到一个更好的比喻： Flask 和 FastAPI 就像是苹果和橙汁。你不能把苹果和添加了更多蔗糖和添加剂的橙汁放在一起比较哪一个更甜。苹果（Flask）应该和橙子（Starlette）比较，橙汁（FastAPI）当然也应该和苹果汁（基于 Flask 的 Web API 框架）进行比较。也就是说，Flask 是一个通用型框架，和 FastAPI 依赖的 Starlette 一样，而 FastAPI 是添加 Web API 支持的二次框架。因此，Flask 应该和 FastAPI 所依赖的 Starlette 进行比较，而 FastAPI 应该和基于 Flask 的 Web API 框架进行比较。</p>
<p>同理，FastAPI 也不能和 Django、Tornado、web2py、Bottle、CherryPy、Pyramid、Sanic 等通用型 Web 框架比较。</p>
<h2>更合理的比较对象是什么？</h2>
<p>既然「FastAPI 应该和基于 Flask 的 Web API 框架比较」，那么合适的比较对象有哪些？<a href="https://github.com/python-restx/flask-restx">Flask-RESTX</a>、<a href="https://github.com/plangrid/flask-rebar">Flask-Rebar</a>、<a href="https://github.com/jmcarp/flask-apispec">flask-apispec</a>、<a href="https://github.com/marshmallow-code/flask-smorest">flask-smorest</a>、<a href="https://github.com/flask-restful/flask-restful">Flask-RESTful</a>、<a href="https://github.com/miguelgrinberg/APIFairy">APIFairy</a> 这些虽然试图做成框架，但在具体实现上仍然是 Flask 扩展，所以真正公平合理的比较对象是：</p>
<ul>
<li><a href="https://github.com/pyeve/eve">Eve</a></li>
<li><a href="https://github.com/zalando/connexion">Connexion</a></li>
<li><a href="https://github.com/greyli/apiflask">APIFlask</a></li>
</ul>
<p>这三个框架都是基于 Flask 实现的 Web API 框架。不过 Eve 没有内置 OpenAPI 支持，而 Connexion 是一个 Spec-First 框架，也就是 OpenAPI spec 优先（先编写 spec，然后生成项目基础代码进行开发）的框架。因此，尽管 APIFlask 只是一个刚发布没多久的实验项目，但它是最适合和 FastAPI 进行比较的项目。</p>
<p>FastAPI 和 APIFlask 有着同样的组成结构，都是作为一层胶水粘起来一个 Web 框架和一个数据序列化/验证库，然后加一点 Web API 功能支持：</p>
<ul>
<li>FastAPI = <a href="https://github.com/encode/starlette">Starlette</a> + <a href="https://github.com/samuelcolvin/pydantic/">Pydantic</a></li>
<li>APIFlask = <a href="https://github.com/pallets/flask">Flask</a> + <a href="https://github.com/marshmallow-code/marshmallow">Marshmallow</a></li>
</ul>
<p>在主要功能上也有很多交集：</p>
<ul>
<li>自动反序列化和验证请求数据，自动生成错误响应</li>
<li>自动格式化和序列化响应数据</li>
<li>自动生成 OpenAPI specification 文件</li>
<li>自动生成交互式 API 文档</li>
</ul>
<p>当然，相对于发布已经三年的 FastAPI，APIFlask 还只是一个三个月大的新项目，还有很多地方需要改进和完善。如果你对 APIFlask 感兴趣的话，可以在<a href="https://greyli.com/hello-apiflask/">这篇文章</a>了解详细介绍或是在它的 <a href="https://github.com/greyli/apiflask">GitHub 仓库</a>查看源码。</p>
<h2>为什么会有这样的误解？</h2>
<p>为什么会有那么多人把 FastAPI 和 Flask 放到一起比较？在我看来有三个原因：</p>
<p>首先是 FastAPI 采用了和 Flask 类似的装饰器路由，很容易让人联想到 Flask。</p>
<p>二是 FastAPI 没有给它的项目构成做足够的说明。如果 FastAPI 在其介绍的第一句就加上「based on Starlette and Pydantic」而不是放到 Requirements 部分才提及，这样也许会让 <a href="https://github.com/encode/starlette">Starlette</a> 和 <a href="https://github.com/samuelcolvin/pydantic">Pydantic</a> 获得更多应有的关注，也就不会有这么多人拿 Flask 和它比较。</p>
<p>再就是 FastAPI 的推介者对 FastAPI 了解的不够多。不清楚它的项目结构，自然就不了解它和其他 Web 框架的区别。而介绍时为了带来足够的吸引力，推介者常常选择拉上和用户量足够大的「竞品」进行对比这种方式，所以才会有大量类似本文开头提到的那种文章。这些文章甚至完全没有提及 Starlette 和 Pydantic，只是一味强调「这是一个超高性能的、碾压 Flask 的框架」。</p>
<h2>FastAPI 不是银弹</h2>
<p>FastAPI 只是说它能把「功能开发速度提升约 200% 至 300%」，距离十倍还差了一些，自然不能算是银弹。但是这两年看到了很多对 FastAPI 的盲目吹捧，仿佛 FastAPI 就是完美的解决方案。这也许都要归功于 FastAPI 在其 README 和文档里「大胆」的措辞和承诺以及不厌其烦的特性介绍。举例来说，如果它只是说「Very high performance, it is comparable to some frameworks in Go and NodeJS」，那么用户也许就会认为「和 Go/NodeJS 有一拼」，但是说成「Very high performance, on par with NodeJS and Go」，那么用户就会想「和 Go/NodeJS 不相上下」（以至于中文翻译是「可与 NodeJS 和 Go 比肩的极高性能」），这当然会带来一些<a href="https://github.com/tiangolo/fastapi/issues/1664">争议</a>。再比如，如果只是说「double or triple the development speed」，那么用户大概会想「效率还不错」，但是它用了「Increase the speed to develop features by about 200% to 300%」，数学不好的用户就会惊呼「哇，提高 30 倍开发效率」。同时这种营销带来的狂热用户，也很容易被煽动去<a href="https://github.com/samuelcolvin/pydantic/issues/2678">给 Python Steering Council 施加压力</a>——在 Python 3.10 快要发布的时候突然跳出来要求撤销一个 PEP。</p>
<p>这种营销至上的项目运营方式带来的直接后果是糟糕的维护状态。FastAPI 似乎在慢慢变成一个翻译项目，在代码里的文档字符串都还没写的情况下，其用户文档就已经开始扩展到十几种语言。而这十几种语言的翻译和项目源码都放在同一个仓库里，这导致所有开启的近 300 个 PR 里有<a href="https://github.com/tiangolo/fastapi/pulls?q=is%3Apr+is%3Aopen+label%3Alang-all">过半是翻译</a>。issue tracker 和 discussion 不做区分的使用，这导致所有开启的近 600 个 issue 里有<a href="https://github.com/tiangolo/fastapi/issues?q=is%3Aissue+is%3Aopen+label%3Aquestion">九成是提问</a>）。我在此前创建过一个 <a href="https://github.com/tiangolo/fastapi/issues/2487">issue</a> 来反馈这个问题，但并没有得到回应。另外凭个人喜好来说，在每个 commit 信息里都加上 emoji 并不可爱。而每一个 commit 都要触发 bot 更新 changelog，带来的是一份丑陋的 commit 历史（所有 commit 里有<a href="https://github.com/tiangolo/fastapi/search?p=1&amp;q=Update+release+notes&amp;type=commits">三分之一是在更新 changelog</a>）。这些也许是发展社区或是让项目看起来很活跃的有效方法，但很显然这带来的是建立在混乱之上的虚假繁荣。</p>
<p>另外，许多推介文章都会在最后贴出来一张 benchmark 截图来证明 FastAPI 有多么 fast，但是完全不会提及的是：贴出来的 benchmark 对于开发生产应用来说有多大的意义？这里的 benchmark 背后有没有任何的 hacky？异步是否等同于高性能还是要看情况？框架本身的性能在一个请求处理流程中占多大的影响？asyncio 的生态怎么样？</p>
<p>从长远看这些大都是一些临时问题，而且 FastAPI 作者已经开始全职开发开源项目，这些问题在未来应该都会慢慢得到改善。指出这些是希望更多的人可以客观看待 FastAPI，吹捧并不能让一个东西变得更好，参与开发、介绍用法和回答社区提问是比盲目吹捧更有意义的事情。我当然期待 FastAPI 能够越来越好，也期待看到有更多优秀的 Python 框架出现，但我不喜欢过度炒作、盲目的吹捧和错误的对比。</p>
<h2>P.S. Flask 2.0 版本即将发布</h2>
<p>顺便说一句，Flask、Werkzeug、Jinja 等 Pallets 项目都将在 5 月 11 日（PyCon 开始）之前发布下一个主版本，主要包含下面这些新特性（完整变动见 <a href="https://flask.palletsprojects.com/en/master/changes/#version-2-0-0">changelog</a>）：</p>
<ul>
<li>Flask、Werkzeug 和 Click 添加了 type hints</li>
<li>Flask 实现了有限的 async/await 支持</li>
<li>Flask 支持嵌套蓝本</li>
<li>Flask 添加了快捷版本的 route 装饰器（即 <span spellcheck="false">@app.get</span>、<span spellcheck="false">@app.post</span> 等）</li>
<li>Flask 支持在视图类上使用 route 装饰器（我前两天刚提交了一个 <a href="https://github.com/pallets/flask/pull/3975">PR</a> 来实现这个功能，暂时不确定是否会被合并，在这先提前说一下 :p）</li>
<li>Werkzeug 的 multipart 解析性能大幅提升</li>
</ul>
<p>你可以使用下面的命令安装 Flask 2.0.0rc 版本进行测试：</p>
<pre spellcheck="false" lang="bash" cid="n361" mdtype="fences" class=""> $ pip install --pre flask</pre>
<p>欢迎反馈 bug 和提改进建议。关于 2.0 版本的详细介绍将会在发布后另外撰文说明。</p>
<h2>延伸阅读</h2>
<ul>
<li><a href="https://juejin.cn/post/6844904051327369224">用它 5 分钟以后，我放弃用了四年的 Flask</a></li>
<li><a href="https://greyli.com/hello-apiflask/">用它 5 分钟以后，我放弃用了四年的 FastAPI</a></li>
<li><a href="https://blog.miguelgrinberg.com/post/ignore-all-web-performance-benchmarks-including-this-one">Ignore All Web Performance Benchmarks, Including This One</a></li>
<li><a href="https://lucumr.pocoo.org/2020/1/1/async-pressure/">I&#8217;m not feeling the async pressure</a></li>
<li><a href="https://fastapi.tiangolo.com/benchmarks/">FastAPI &#8211; Benchmarks</a></li>
<li><a class="Link ztext-link" href="https://www.v2ex.com/t/774831" target="_blank" rel="noopener" data-offset-key="9ej3a-0-0" data-editable="true"><span data-offset-key="9ej3a-0-0">在 V2EX 上的相关讨论</span></a></li>
<li><a href="https://www.v2ex.com/t/776474">在 V2EX 上的后续讨论</a></li>
<li><a href="https://zhuanlan.zhihu.com/p/369591096">在知乎上的相关讨论</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>https://greyli.com/flask-fastapi/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
	</channel>
</rss>
