跳转至

教程 - 用户指南

本教程将一步步向您展示如何使用 FastAPI 的绝大部分特性。

各个章节的内容循序渐进,但是又围绕着单独的主题,所以您可以直接跳转到某个章节以解决您的特定需求。

本教程同样可以作为将来的参考手册,所以您可以随时回到本教程并查阅您需要的内容。

运行代码

所有代码片段都可以复制后直接使用(它们实际上是经过测试的 Python 文件)。

要运行任何示例,请将代码复制到 main.py 文件中,然后使用以下命令启动 fastapi dev

fast →fastapi dev main.py
FastAPI Starting development server 🚀

Searching for package file structure from directories
with __init__.py files
Importing from /home/user/code/awesomeapp

module 🐍 main.py

code Importing the FastAPI app object from the module with
the following code:

from main import app

app Using import string: main:app

server Server started at http://127.0.0.1:8000
server Documentation at http://127.0.0.1:8000/docs

tip Running in development mode, for production use:
fastapi run

Logs:

INFO Will watch for changes in these directories:
['/home/user/code/awesomeapp']
INFO Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C
to quit)
INFO Started reloader process [383138] using WatchFiles
INFO Started server process [383153]
INFO Waiting for application startup.
INFO Application startup complete.

restart ↻

强烈建议您在本地编写或复制代码,对其进行编辑并运行。

在编辑器中使用 FastAPI 会真正地展现出它的优势:只需要编写很少的代码,所有的类型检查,代码补全等等。


安装 FastAPI

第一个步骤是安装 FastAPI.

请确保您创建并激活一个虚拟环境,然后安装 FastAPI

fast →pip install "fastapi[standard]"

restart ↻

Note

当您使用 pip install "fastapi[standard]" 进行安装时,它会附带一些默认的可选标准依赖项。

如果您不想安装这些可选依赖,可以选择安装 pip install fastapi

进阶用户指南

在本教程-用户指南之后,您可以阅读进阶用户指南

进阶用户指南以本教程为基础,使用相同的概念,并教授一些额外的特性。

但是您应该先阅读教程-用户指南(即您现在正在阅读的内容)。

教程经过精心设计,使您可以仅通过教程-用户指南来开发一个完整的应用程序,然后根据您的需要,使用进阶用户指南中的一些其他概念,以不同的方式来扩展它。

Was this page helpful?