惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 三生石上(FineUI控件)
Martin Fowler
Martin Fowler
月光博客
月光博客
AI
AI
B
Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
C
CXSECURITY Database RSS Feed - CXSecurity.com
WordPress大学
WordPress大学
GbyAI
GbyAI
L
Lohrmann on Cybersecurity
O
OpenAI News
Schneier on Security
Schneier on Security
P
Palo Alto Networks Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
T
Troy Hunt's Blog
V2EX - 技术
V2EX - 技术
W
WeLiveSecurity
L
LINUX DO - 最新话题
人人都是产品经理
人人都是产品经理
S
Security Affairs
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
A
Arctic Wolf
Recorded Future
Recorded Future
Microsoft Security Blog
Microsoft Security Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
G
GRAHAM CLULEY
N
Netflix TechBlog - Medium
TaoSecurity Blog
TaoSecurity Blog
C
Check Point Blog
Scott Helme
Scott Helme
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Apple Machine Learning Research
Apple Machine Learning Research
PCI Perspectives
PCI Perspectives
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Vercel News
Vercel News
The Hacker News
The Hacker News
Y
Y Combinator Blog
Latest news
Latest news
SecWiki News
SecWiki News
Hugging Face - Blog
Hugging Face - Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Google Online Security Blog
Google Online Security Blog
Webroot Blog
Webroot Blog
Google DeepMind News
Google DeepMind News
Recent Commits to openclaw:main
Recent Commits to openclaw:main
C
Cisco Blogs
博客园_首页
H
Hackread – Cybersecurity News, Data Breaches, AI and More
宝玉的分享
宝玉的分享
L
LINUX DO - 热门话题

好好学习的郝

ClawdBot(OpenClaw)试用记录 编程辅助工具 Codex 入门篇 编程辅助工具 Claude Code 入门篇 Claude API 中转服务 Claude Relay Service LLM 接口管理和分发系统 New API 好好学Git:Git Submodule详解 编程辅助工具Cursor入门篇 好好学Golang:Golang问题记录 One API配置自定义渠道 好好学Docker:使用Docker安装配置AList 好好学Docker:容器指标查看工具ctop 好好学Docker:自建RustDesk Server 好好学Linux:Ubuntu18 升级到 Ubuntu22 好好学Docker:使用Docker安装配置FileBrowser 邮箱配置中的SPF、DKIM、DMARC记录 One API 开发环境配置 LLM 接口管理和分发系统 One API 好好学K8S:K8S中的Leader Election机制 好好学Golang:Viper库
FastAPI入门篇
本文作者: 好好学习的郝 · 2024-12-21 · via 好好学习的郝

FastAPI 是一个现代、快速(高性能)的 Python Web 框架,用于构建 API。它基于 Python 3.6 及以上版本,并且利用了 Python 类型提示的功能。FastAPI 旨在帮助开发者快速构建出高性能的 API,并且具有自动生成文档的功能。

参考文档:

2. FastAPI的特性

FastAPI的关键特性包括:

  • 快速:可与 NodeJS 和 Go 并肩的极高性能,是最快的 Python Web 框架之一。高性能归功于 Starlette 和 Pydantic,Starlette 提供了底层的异步功能,而 Pydantic 则处理数据解析和验证。
  • 高效编码:提高功能开发速度约 200% 至 300%。
  • 更少 bug:减少约 40% 的人为(开发者)导致错误。
  • 智能:极佳的编辑器支持。处处皆可自动补全,减少调试时间。
  • 简单:设计的易于使用和学习,阅读文档的时间更短。
  • 简短:使代码重复最小化。通过不同的参数声明实现丰富功能。bug 更少。
  • 健壮:生产可用级别的代码。还有自动生成的交互式文档。
  • 标准化:基于(并完全兼容)API 的相关开放标准:OpenAPI (以前被称为 Swagger) 和 JSON Schema

3. FastAPI与ASGI

Django是一个Python Web框架,同时也可以作为Web Server,只不过性能差一些。我们通常会在Django的上层配置一个WSGI或ASGI服务器,用来提升性能。

而FastAPI这个Python Web框架,本身是不可以作为Web Server的,因此必须要配置一个ASGI服务器。

ASGI(Asynchronous Server Gateway Interface)是一种异步服务器网关接口,它是WSGI(Web Server Gateway Interface)的扩展和进化。ASGI旨在为Python Web服务、框架和应用之间提供一个标准的异步接口,以适应现代Web开发中对异步处理和多种协议支持的需求。

ASGI的主要特点包括:

  • 异步处理能力:ASGI支持异步编程,允许同时处理多个请求,通过使用事件循环和协程实现高并发性能,从而更好地应对大量并发请求。
  • 多协议支持:ASGI不仅支持传统的HTTP请求,还支持WebSocket、HTTP/2以及未来的协议,使其能够适应不断发展的Web技术。
  • 性能提升:由于ASGI的异步特性,它能够更高效地处理异步请求,提升性能和响应速度。
  • 框架支持:现代的Python Web框架,如FastAPI、Tornado以及Django 3.1以后的版本,都支持ASGI,这使得开发者可以利用ASGI的优势构建高性能的Web应用程序。

ASGI服务器,如Uvicorn、Hypercorn和Daphne,实现了这种异步的网关接口,允许开发者构建异步Web应用程序。这些服务器能够处理来自客户端的请求,并将其传递给ASGI应用程序,同时ASGI应用程序可以异步地处理这些请求并返回响应。

总的来说,ASGI是构建现代、高性能、异步Web应用程序的关键技术,它通过支持异步处理和多协议,为Python Web开发提供了强大的支持。

4. 安装使用FastAPI

4.1. 安装FastAPI和Uvicorn

1、安装fastapi

1
pip install fastapi

2、安装uvicorn

1
pip install uvicorn

Uvicorn是一个轻量级的 ASGI 服务器,用于运行 FastAPI 应用。
生产环境的 ASGI 服务器通常使用 Uvicorn 或者 Hypercorn

4.2. Hello World

1、编写代码 main.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from typing import Union

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
def read_root():
return {"Hello": "World"}


@app.get("/items/{item_id}")
def read_item(item_id: int, q: Union[str, None] = None):
return {"item_id": item_id, "q": q}

2、运行代码

1
uvicorn main:app --reload

--reload 参数使得服务器在代码改变时自动重载,适用于开发阶段。

3、测试访问

1
2
curl http://127.0.0.1:8000
curl http://127.0.0.1:8000/items/5?q=somequery

4、查看接口文档
浏览器访问 http://127.0.0.1:8000/docs

我们会看到自动生成的交互式 API 文档(由 Swagger UI 生成)。

4.3. 启动命令常规化

uvicorn main:app --reload 这种启动命令,不方便记忆。
本节中,我们将启动命令改为:python main.py

实现方法:main.py 脚本中调用 uvicorn.run()

1
2
3
if __name__ == "__main__":
import uvicorn
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)

5. FastAPI基础

5.1. 路径操作和参数

FastAPI 允许定义路径操作装饰器(如 @app.get, @app.post 等),并直接在函数参数中声明预期的请求数据类型。

1
2
3
@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}

5.2. 请求体和JSON

对于需要请求体的接口,我们可以使用 Pydantic 模型来定义请求体的结构。

1
2
3
4
5
6
7
8
9
10
11
from pydantic import BaseModel

class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None

@app.post("/items/")
async def create_item(item: Item):
return {"name": item.name, "price": item.price}

5.3. 数据验证

FastAPI 会自动验证传入的数据是否符合预期的类型和结构,并在不符合时返回错误信息。

5.4. 文档和交互式API

访问 http://127.0.0.1:8000/docshttp://127.0.0.1:8000/redoc 可以查看自动生成的 API 文档。

这些文档是交互式的,可以直接在浏览器中测试 API。

5.5. 进阶使用

FastAPI 还支持依赖注入、中间件、安全性(如 OAuth2)、数据库集成等高级功能。

6. FastAPI项目结构规划

参考文档:

6.1. 推荐项目结构一

1
2
3
4
5
6
7
8
9
10
11
12
13
sampleproject
├── LICENSE.txt
├── noxfile.py
├── pyproject.toml
├── README.md
├── src
│   └── sample
│   ├── __init__.py
│   ├── package_data.dat
│   └── simple.py
└── tests
├── __init__.py
└── test_simple.py

6.2. 推荐项目结构二

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
my_fastapi_project/
├── app/
│ ├── __init__.py
│ ├── main.py # 入口文件
│ ├── core/
│ │ ├── __init__.py
│ │ ├── config.py # 配置文件
│ │ ├── security.py # 安全相关
│ │ └── ... # 其他核心功能
│ ├── api/
│ │ ├── __init__.py
│ │ ├── v1/
│ │ │ ├── __init__.py
│ │ │ ├── endpoints/
│ │ │ │ ├── __init__.py
│ │ │ │ ├── users.py # 用户相关接口
│ │ │ │ ├── items.py # 其他接口
│ │ │ │ └── ...
│ │ │ └── ... # 其他版本的API
│ ├── models/
│ │ ├── __init__.py
│ │ ├── user.py # 用户模型
│ │ ├── item.py # 其他模型
│ │ └── ...
│ ├── schemas/
│ │ ├── __init__.py
│ │ ├── user.py # 用户数据模型
│ │ ├── item.py # 其他数据模型
│ │ └── ...
│ ├── crud/
│ │ ├── __init__.py
│ │ ├── user.py # 用户CRUD操作
│ │ ├── item.py # 其他CRUD操作
│ │ └── ...
│ ├── db/
│ │ ├── __init__.py
│ │ ├── base.py # 数据库基础设置
│ │ ├── session.py # 数据库会话
│ │ └── ...
│ ├── tests/
│ │ ├── __init__.py
│ │ ├── test_main.py # 测试主文件
│ │ ├── test_users.py # 用户相关测试
│ │ └── ...
│ └── utils/
│ ├── __init__.py
│ ├── utils.py # 工具函数
│ └── ...
├── .env # 环境变量文件
├── alembic/ # 数据库迁移工具目录
│ ├── env.py
│ ├── script.py.mako
│ └── versions/
│ └── ...
├── alembic.ini # Alembic 配置文件
├── requirements.txt # 项目依赖
├── Dockerfile # Docker 配置文件
└── README.md # 项目说明文件

7. 小结

FastAPI 是一个强大的 Python Web 框架,特别适合用于构建 API。
通过上面的内容,我们可以快速开始使用 FastAPI 来构建我们的应用。
FastAPI 的文档和社区资源非常丰富,可以帮助我们深入了解和解决更复杂的问题。推荐阅读官方文档以获取更多高级特性和最佳实践。