From 602e9531584135f31fea0a8e68ae96eab2436a7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sun, 17 Nov 2024 23:31:41 +0100 Subject: [PATCH 01/10] =?UTF-8?q?=F0=9F=94=A5=20Remove=20obsolete=20tutori?= =?UTF-8?q?al=20translation=20to=20Chinese=20for=20`docs/zh/docs/tutorial/?= =?UTF-8?q?sql-databases.md`,=20it=20references=20files=20that=20are=20no?= =?UTF-8?q?=20longer=20on=20the=20repo=20(#12949)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/tutorial/sql-databases.md | 908 ------------------------- 1 file changed, 908 deletions(-) delete mode 100644 docs/zh/docs/tutorial/sql-databases.md diff --git a/docs/zh/docs/tutorial/sql-databases.md b/docs/zh/docs/tutorial/sql-databases.md deleted file mode 100644 index 06b373e6d..000000000 --- a/docs/zh/docs/tutorial/sql-databases.md +++ /dev/null @@ -1,908 +0,0 @@ -# SQL (关系型) 数据库 - -/// info - -这些文档即将被更新。🎉 - -当前版本假设Pydantic v1和SQLAlchemy版本小于2。 - -新的文档将包括Pydantic v2以及 SQLModel(也是基于SQLAlchemy),一旦SQLModel更新为为使用Pydantic v2。 - -/// - -**FastAPI**不需要你使用SQL(关系型)数据库。 - -但是您可以使用任何您想要的关系型数据库。 - -在这里,让我们看一个使用着[SQLAlchemy](https://www.sqlalchemy.org/)的示例。 - -您可以很容易地将其调整为任何SQLAlchemy支持的数据库,如: - -* PostgreSQL -* MySQL -* SQLite -* Oracle -* Microsoft SQL Server,等等其它数据库 - -在此示例中,我们将使用**SQLite**,因为它使用单个文件并且 在Python中具有集成支持。因此,您可以复制此示例并按原样来运行它。 - -稍后,对于您的产品级别的应用程序,您可能会要使用像**PostgreSQL**这样的数据库服务器。 - -/// tip - -这儿有一个**FastAPI**和**PostgreSQL**的官方项目生成器,全部基于**Docker**,包括前端和更多工具:https://github.com/tiangolo/full-stack-fastapi-postgresql - -/// - -/// note - -请注意,大部分代码是`SQLAlchemy`的标准代码,您可以用于任何框架。FastAPI特定的代码和往常一样少。 - -/// - -## ORMs(对象关系映射) - -**FastAPI**可与任何数据库在任何样式的库中一起与 数据库进行通信。 - -一种常见的模式是使用“ORM”:对象关系映射。 - -ORM 具有在代码和数据库表(“*关系型”)中的**对象**之间转换(“*映射*”)的工具。 - -使用 ORM,您通常会在 SQL 数据库中创建一个代表映射的类,该类的每个属性代表一个列,具有名称和类型。 - -例如,一个类`Pet`可以表示一个 SQL 表`pets`。 - -该类的每个*实例对象都代表数据库中的一行数据。* - -又例如,一个对象`orion_cat`(`Pet`的一个实例)可以有一个属性`orion_cat.type`, 对标数据库中的`type`列。并且该属性的值可以是其它,例如`"cat"`。 - -这些 ORM 还具有在表或实体之间建立关系的工具(比如创建多表关系)。 - -这样,您还可以拥有一个属性`orion_cat.owner`,它包含该宠物所有者的数据,这些数据取自另外一个表。 - -因此,`orion_cat.owner.name`可能是该宠物主人的姓名(来自表`owners`中的列`name`)。 - -它可能有一个像`"Arquilian"`(一种业务逻辑)。 - -当您尝试从您的宠物对象访问它时,ORM 将完成所有工作以从相应的表*所有者那里再获取信息。* - -常见的 ORM 例如:Django-ORM(Django 框架的一部分)、SQLAlchemy ORM(SQLAlchemy 的一部分,独立于框架)和 Peewee(独立于框架)等。 - -在这里,我们将看到如何使用**SQLAlchemy ORM**。 - -以类似的方式,您也可以使用任何其他 ORM。 - -/// tip - -在文档中也有一篇使用 Peewee 的等效的文章。 - -/// - -## 文件结构 - -对于这些示例,假设您有一个名为的目录`my_super_project`,其中包含一个名为的子目录`sql_app`,其结构如下: - -``` -. -└── sql_app - ├── __init__.py - ├── crud.py - ├── database.py - ├── main.py - ├── models.py - └── schemas.py -``` - -该文件`__init__.py`只是一个空文件,但它告诉 Python `sql_app` 是一个包。 - -现在让我们看看每个文件/模块的作用。 - -## 安装 SQLAlchemy - -首先你需要安装`SQLAlchemy`: - -
- -```console -$ pip install sqlalchemy - ----> 100% -``` - -
- -## 创建 SQLAlchemy 部件 - -让我们转到文件`sql_app/database.py`。 - -### 导入 SQLAlchemy 部件 - -```Python hl_lines="1-3" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -### 为 SQLAlchemy 定义数据库 URL地址 - -```Python hl_lines="5-6" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -在这个例子中,我们正在“连接”到一个 SQLite 数据库(用 SQLite 数据库打开一个文件)。 - -该文件将位于文件中的同一目录中`sql_app.db`。 - -这就是为什么最后一部分是`./sql_app.db`. - -如果您使用的是**PostgreSQL**数据库,则只需取消注释该行: - -```Python -SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" -``` - -...并根据您的数据库数据和相关凭据(也适用于 MySQL、MariaDB 或任何其他)对其进行调整。 - -/// tip - -如果您想使用不同的数据库,这是就是您必须修改的地方。 - -/// - -### 创建 SQLAlchemy 引擎 - -第一步,创建一个 SQLAlchemy的“引擎”。 - -我们稍后会将这个`engine`在其他地方使用。 - -```Python hl_lines="8-10" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -#### 注意 - -参数: - -```Python -connect_args={"check_same_thread": False} -``` - -...仅用于`SQLite`,在其他数据库不需要它。 - -/// info | 技术细节 - -默认情况下,SQLite 只允许一个线程与其通信,假设有多个线程的话,也只将处理一个独立的请求。 - -这是为了防止意外地为不同的事物(不同的请求)共享相同的连接。 - -但是在 FastAPI 中,使用普通函数(def)时,多个线程可以为同一个请求与数据库交互,所以我们需要使用`connect_args={"check_same_thread": False}`来让SQLite允许这样。 - -此外,我们将确保每个请求都在依赖项中获得自己的数据库连接会话,因此不需要该默认机制。 - -/// - -### 创建一个`SessionLocal`类 - -每个`SessionLocal`类的实例都会是一个数据库会话。当然该类本身还不是数据库会话。 - -但是一旦我们创建了一个`SessionLocal`类的实例,这个实例将是实际的数据库会话。 - -我们将它命名为`SessionLocal`是为了将它与我们从 SQLAlchemy 导入的`Session`区别开来。 - -稍后我们将使用`Session`(从 SQLAlchemy 导入的那个)。 - -要创建`SessionLocal`类,请使用函数`sessionmaker`: - -```Python hl_lines="11" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -### 创建一个`Base`类 - -现在我们将使用`declarative_base()`返回一个类。 - -稍后我们将继承这个类,来创建每个数据库模型或类(ORM 模型): - -```Python hl_lines="13" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -## 创建数据库模型 - -现在让我们看看文件`sql_app/models.py`。 - -### 用`Base`类来创建 SQLAlchemy 模型 - -我们将使用我们之前创建的`Base`类来创建 SQLAlchemy 模型。 - -/// tip - -SQLAlchemy 使用的“**模型**”这个术语 来指代与数据库交互的这些类和实例。 - -而 Pydantic 也使用“模型”这个术语 来指代不同的东西,即数据验证、转换以及文档类和实例。 - -/// - -从`database`(来自上面的`database.py`文件)导入`Base`。 - -创建从它继承的类。 - -这些类就是 SQLAlchemy 模型。 - -```Python hl_lines="4 7-8 18-19" -{!../../docs_src/sql_databases/sql_app/models.py!} -``` - -这个`__tablename__`属性是用来告诉 SQLAlchemy 要在数据库中为每个模型使用的数据库表的名称。 - -### 创建模型属性/列 - -现在创建所有模型(类)的属性。 - -这些属性中的每一个都代表其相应数据库表中的一列。 - -我们使用`Column`来表示 SQLAlchemy 中的默认值。 - -我们传递一个 SQLAlchemy “类型”,如`Integer`、`String`和`Boolean`,它定义了数据库中的类型,作为参数。 - -```Python hl_lines="1 10-13 21-24" -{!../../docs_src/sql_databases/sql_app/models.py!} -``` - -### 创建关系 - -现在创建关系。 - -为此,我们使用SQLAlchemy ORM提供的`relationship`。 - -这将或多或少会成为一种“神奇”属性,其中表示该表与其他相关的表中的值。 - -```Python hl_lines="2 15 26" -{!../../docs_src/sql_databases/sql_app/models.py!} -``` - -当访问 user 中的属性`items`时,如 中`my_user.items`,它将有一个`Item`SQLAlchemy 模型列表(来自`items`表),这些模型具有指向`users`表中此记录的外键。 - -当您访问`my_user.items`时,SQLAlchemy 实际上会从`items`表中的获取一批记录并在此处填充进去。 - -同样,当访问 Item中的属性`owner`时,它将包含表中的`User`SQLAlchemy 模型`users`。使用`owner_id`属性/列及其外键来了解要从`users`表中获取哪条记录。 - -## 创建 Pydantic 模型 - -现在让我们查看一下文件`sql_app/schemas.py`。 - -/// tip - -为了避免 SQLAlchemy*模型*和 Pydantic*模型*之间的混淆,我们将有`models.py`(SQLAlchemy 模型的文件)和`schemas.py`( Pydantic 模型的文件)。 - -这些 Pydantic 模型或多或少地定义了一个“schema”(一个有效的数据形状)。 - -因此,这将帮助我们在使用两者时避免混淆。 - -/// - -### 创建初始 Pydantic*模型*/模式 - -创建一个`ItemBase`和`UserBase`Pydantic*模型*(或者我们说“schema”),他们拥有创建或读取数据时具有的共同属性。 - -然后创建一个继承自他们的`ItemCreate`和`UserCreate`,并添加创建时所需的其他数据(或属性)。 - -因此在创建时也应当有一个`password`属性。 - -但是为了安全起见,`password`不会出现在其他同类 Pydantic*模型*中,例如通过API读取一个用户数据时,它不应当包含在内。 - -//// tab | Python 3.10+ - -```Python hl_lines="1 4-6 9-10 21-22 25-26" -{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3 6-8 11-12 23-24 27-28" -{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3 6-8 11-12 23-24 27-28" -{!> ../../docs_src/sql_databases/sql_app/schemas.py!} -``` - -//// - -#### SQLAlchemy 风格和 Pydantic 风格 - -请注意,SQLAlchemy*模型*使用 `=`来定义属性,并将类型作为参数传递给`Column`,例如: - -```Python -name = Column(String) -``` - -虽然 Pydantic*模型*使用`:` 声明类型,但新的类型注释语法/类型提示是: - -```Python -name: str -``` - -请牢记这一点,这样您在使用`:`还是`=`时就不会感到困惑。 - -### 创建用于读取/返回的Pydantic*模型/模式* - -现在创建当从 API 返回数据时、将在读取数据时使用的Pydantic*模型(schemas)。* - -例如,在创建一个项目之前,我们不知道分配给它的 ID 是什么,但是在读取它时(从 API 返回时)我们已经知道它的 ID。 - -同样,当读取用户时,我们现在可以声明`items`,将包含属于该用户的项目。 - -不仅是这些项目的 ID,还有我们在 Pydantic*模型*中定义的用于读取项目的所有数据:`Item`. - -//// tab | Python 3.10+ - -```Python hl_lines="13-15 29-32" -{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="15-17 31-34" -{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15-17 31-34" -{!> ../../docs_src/sql_databases/sql_app/schemas.py!} -``` - -//// - -/// tip - -请注意,读取用户(从 API 返回)时将使用不包括`password`的`User` Pydantic*模型*。 - -/// - -### 使用 Pydantic 的`orm_mode` - -现在,在用于查询的 Pydantic*模型*`Item`中`User`,添加一个内部`Config`类。 - -此类[`Config`](https://docs.pydantic.dev/latest/api/config/)用于为 Pydantic 提供配置。 - -在`Config`类中,设置属性`orm_mode = True`。 - -//// tab | Python 3.10+ - -```Python hl_lines="13 17-18 29 34-35" -{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="15 19-20 31 36-37" -{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15 19-20 31 36-37" -{!> ../../docs_src/sql_databases/sql_app/schemas.py!} -``` - -//// - -/// tip - -请注意,它使用`=`分配一个值,例如: - -`orm_mode = True` - -它不使用之前的`:`来类型声明。 - -这是设置配置值,而不是声明类型。 - -/// - -Pydantic`orm_mode`将告诉 Pydantic*模型*读取数据,即它不是一个`dict`,而是一个 ORM 模型(或任何其他具有属性的任意对象)。 - -这样,而不是仅仅试图从`dict`上 `id` 中获取值,如下所示: - -```Python -id = data["id"] -``` - -它还会尝试从属性中获取它,如: - -```Python -id = data.id -``` - -有了这个,Pydantic*模型*与 ORM 兼容,您只需在*路径操作*`response_model`的参数中声明它即可。 - -您将能够返回一个数据库模型,它将从中读取数据。 - -#### ORM 模式的技术细节 - -SQLAlchemy 和许多其他默认情况下是“延迟加载”。 - -这意味着,例如,除非您尝试访问包含该数据的属性,否则它们不会从数据库中获取关系数据。 - -例如,访问属性`items`: - -```Python -current_user.items -``` - -将使 SQLAlchemy 转到`items`表并获取该用户的项目,在调用`.items`之前不会去查询数据库。 - -没有`orm_mode`,如果您从*路径操作*返回一个 SQLAlchemy 模型,它不会包含关系数据。 - -即使您在 Pydantic 模型中声明了这些关系,也没有用处。 - -但是在 ORM 模式下,由于 Pydantic 本身会尝试从属性访问它需要的数据(而不是假设为 `dict`),你可以声明你想要返回的特定数据,它甚至可以从 ORM 中获取它。 - -## CRUD工具 - -现在让我们看看文件`sql_app/crud.py`。 - -在这个文件中,我们将编写可重用的函数用来与数据库中的数据进行交互。 - -**CRUD**分别为:增加(**C**reate)、查询(**R**ead)、更改(**U**pdate)、删除(**D**elete),即增删改查。 - -...虽然在这个例子中我们只是新增和查询。 - -### 读取数据 - -从 `sqlalchemy.orm`中导入`Session`,这将允许您声明`db`参数的类型,并在您的函数中进行更好的类型检查和完成。 - -导入之前的`models`(SQLAlchemy 模型)和`schemas`(Pydantic*模型*/模式)。 - -创建一些工具函数来完成: - -* 通过 ID 和电子邮件查询单个用户。 -* 查询多个用户。 -* 查询多个项目。 - -```Python hl_lines="1 3 6-7 10-11 14-15 27-28" -{!../../docs_src/sql_databases/sql_app/crud.py!} -``` - -/// tip - -通过创建仅专用于与数据库交互(获取用户或项目)的函数,独立于*路径操作函数*,您可以更轻松地在多个部分中重用它们,并为它们添加单元测试。 - -/// - -### 创建数据 - -现在创建工具函数来创建数据。 - -它的步骤是: - -* 使用您的数据创建一个 SQLAlchemy 模型*实例。* -* 使用`add`来将该实例对象添加到数据库会话。 -* 使用`commit`来将更改提交到数据库(以便保存它们)。 -* 使用`refresh`来刷新您的实例对象(以便它包含来自数据库的任何新数据,例如生成的 ID)。 - -```Python hl_lines="18-24 31-36" -{!../../docs_src/sql_databases/sql_app/crud.py!} -``` - -/// tip - -SQLAlchemy 模型`User`包含一个`hashed_password`,它应该是一个包含散列的安全密码。 - -但由于 API 客户端提供的是原始密码,因此您需要将其提取并在应用程序中生成散列密码。 - -然后将hashed_password参数与要保存的值一起传递。 - -/// - -/// warning - -此示例不安全,密码未经过哈希处理。 - -在现实生活中的应用程序中,您需要对密码进行哈希处理,并且永远不要以明文形式保存它们。 - -有关更多详细信息,请返回教程中的安全部分。 - -在这里,我们只关注数据库的工具和机制。 - -/// - -/// tip - -这里不是将每个关键字参数传递给Item并从Pydantic模型中读取每个参数,而是先生成一个字典,其中包含Pydantic模型的数据: - -`item.dict()` - -然后我们将dict的键值对 作为关键字参数传递给 SQLAlchemy `Item`: - -`Item(**item.dict())` - -然后我们传递 Pydantic模型未提供的额外关键字参数`owner_id`: - -`Item(**item.dict(), owner_id=user_id)` - -/// - -## 主**FastAPI**应用程序 - -现在在`sql_app/main.py`文件中 让我们集成和使用我们之前创建的所有其他部分。 - -### 创建数据库表 - -以非常简单的方式创建数据库表: - -//// tab | Python 3.9+ - -```Python hl_lines="7" -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` - -//// - -#### Alembic 注意 - -通常你可能会使用 Alembic,来进行格式化数据库(创建表等)。 - -而且您还可以将 Alembic 用于“迁移”(这是它的主要工作)。 - -“迁移”是每当您更改 SQLAlchemy 模型的结构、添加新属性等以在数据库中复制这些更改、添加新列、新表等时所需的一组步骤。 - -您可以在[Full Stack FastAPI Template](https://fastapi.tiangolo.com/zh/project-generation/)的模板中找到一个 FastAPI 项目中的 Alembic 示例。具体在[`alembic`代码目录中](https://github.com/tiangolo/full-stack-fastapi-template/tree/master/backend/app/alembic)。 - -### 创建依赖项 - -现在使用我们在`sql_app/database.py`文件中创建的`SessionLocal`来创建依赖项。 - -我们需要每个请求有一个独立的数据库会话/连接(`SessionLocal`),在整个请求中使用相同的会话,然后在请求完成后关闭它。 - -然后将为下一个请求创建一个新会话。 - -为此,我们将创建一个包含`yield`的依赖项,正如前面关于[Dependencies with`yield`](https://fastapi.tiangolo.com/zh/tutorial/dependencies/dependencies-with-yield/)的部分中所解释的那样。 - -我们的依赖项将创建一个新的 SQLAlchemy `SessionLocal`,它将在单个请求中使用,然后在请求完成后关闭它。 - -//// tab | Python 3.9+ - -```Python hl_lines="13-18" -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15-20" -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` - -//// - -/// info - -我们将`SessionLocal()`请求的创建和处理放在一个`try`块中。 - -然后我们在finally块中关闭它。 - -通过这种方式,我们确保数据库会话在请求后始终关闭。即使在处理请求时出现异常。 - -但是您不能从退出代码中引发另一个异常(在yield之后)。可以查阅 [Dependencies with yield and HTTPException](https://fastapi.tiangolo.com/zh/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-httpexception) - -/// - -*然后,当在路径操作函数*中使用依赖项时,我们使用`Session`,直接从 SQLAlchemy 导入的类型声明它。 - -*这将为我们在路径操作函数*中提供更好的编辑器支持,因为编辑器将知道`db`参数的类型`Session`: - -//// tab | Python 3.9+ - -```Python hl_lines="22 30 36 45 51" -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24 32 38 47 53" -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` - -//// - -/// info | 技术细节 - -参数`db`实际上是 type `SessionLocal`,但是这个类(用 创建`sessionmaker()`)是 SQLAlchemy 的“代理” `Session`,所以,编辑器并不真正知道提供了哪些方法。 - -但是通过将类型声明为Session,编辑器现在可以知道可用的方法(.add()、.query()、.commit()等)并且可以提供更好的支持(比如完成)。类型声明不影响实际对象。 - -/// - -### 创建您的**FastAPI** *路径操作* - -现在,到了最后,编写标准的**FastAPI** *路径操作*代码。 - -//// tab | Python 3.9+ - -```Python hl_lines="21-26 29-32 35-40 43-47 50-53" -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="23-28 31-34 37-42 45-49 52-55" -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` - -//// - -我们在依赖项中的每个请求之前利用`yield`创建数据库会话,然后关闭它。 - -所以我们就可以在*路径操作函数*中创建需要的依赖,就能直接获取会话。 - -这样,我们就可以直接从*路径操作函数*内部调用`crud.get_user`并使用该会话,来进行对数据库操作。 - -/// tip - -请注意,您返回的值是 SQLAlchemy 模型或 SQLAlchemy 模型列表。 - -但是由于所有路径操作的response_model都使用 Pydantic模型/使用orm_mode模式,因此您的 Pydantic 模型中声明的数据将从它们中提取并返回给客户端,并进行所有正常的过滤和验证。 - -/// - -/// tip - -另请注意,`response_models`应当是标准 Python 类型,例如`List[schemas.Item]`. - -但是由于它的内容/参数List是一个 使用orm_mode模式的Pydantic模型,所以数据将被正常检索并返回给客户端,所以没有问题。 - -/// - -### 关于 `def` 对比 `async def` - -*在这里,我们在路径操作函数*和依赖项中都使用着 SQLAlchemy 模型,它将与外部数据库进行通信。 - -这会需要一些“等待时间”。 - -但是由于 SQLAlchemy 不具有`await`直接使用的兼容性,因此类似于: - -```Python -user = await db.query(User).first() -``` - -...相反,我们可以使用: - -```Python -user = db.query(User).first() -``` - -然后我们应该声明*路径操作函数*和不带 的依赖关系`async def`,只需使用普通的`def`,如下: - -```Python hl_lines="2" -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - ... -``` - -/// info - -如果您需要异步连接到关系数据库,请参阅[Async SQL (Relational) Databases](https://fastapi.tiangolo.com/zh/advanced/async-sql-databases/) - -/// - -/// note | Very Technical Details - -如果您很好奇并且拥有深厚的技术知识,您可以在[Async](https://fastapi.tiangolo.com/zh/async/#very-technical-details)文档中查看有关如何处理 `async def`于`def`差别的技术细节。 - -/// - -## 迁移 - -因为我们直接使用 SQLAlchemy,并且我们不需要任何类型的插件来使用**FastAPI**,所以我们可以直接将数据库迁移至[Alembic](https://alembic.sqlalchemy.org/)进行集成。 - -由于与 SQLAlchemy 和 SQLAlchemy 模型相关的代码位于单独的独立文件中,您甚至可以使用 Alembic 执行迁移,而无需安装 FastAPI、Pydantic 或其他任何东西。 - -同样,您将能够在与**FastAPI**无关的代码的其他部分中使用相同的 SQLAlchemy 模型和实用程序。 - -例如,在具有[Celery](https://docs.celeryq.dev/)、[RQ](https://python-rq.org/)或[ARQ](https://arq-docs.helpmanual.io/)的后台任务工作者中。 - -## 审查所有文件 - -最后回顾整个案例,您应该有一个名为的目录`my_super_project`,其中包含一个名为`sql_app`。 - -`sql_app`中应该有以下文件: - -* `sql_app/__init__.py`:这是一个空文件。 - -* `sql_app/database.py`: - -```Python -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -* `sql_app/models.py`: - -```Python -{!../../docs_src/sql_databases/sql_app/models.py!} -``` - -* `sql_app/schemas.py`: - -//// tab | Python 3.10+ - -```Python -{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python -{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python -{!> ../../docs_src/sql_databases/sql_app/schemas.py!} -``` - -//// - -* `sql_app/crud.py`: - -```Python -{!../../docs_src/sql_databases/sql_app/crud.py!} -``` - -* `sql_app/main.py`: - -//// tab | Python 3.9+ - -```Python -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` - -//// - -## 执行项目 - -您可以复制这些代码并按原样使用它。 - -/// info - -事实上,这里的代码只是大多数测试代码的一部分。 - -/// - -你可以用 Uvicorn 运行它: - - -
- -```console -$ uvicorn sql_app.main:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -打开浏览器进入 http://127.0.0.1:8000/docs。 - -您将能够与您的**FastAPI**应用程序交互,从真实数据库中读取数据: - - - -## 直接与数据库交互 - -如果您想独立于 FastAPI 直接浏览 SQLite 数据库(文件)以调试其内容、添加表、列、记录、修改数据等,您可以使用[SQLite 的 DB Browser](https://sqlitebrowser.org/) - -它看起来像这样: - - - -您还可以使用[SQLite Viewer](https://inloop.github.io/sqlite-viewer/)或[ExtendsClass](https://extendsclass.com/sqlite-browser.html)等在线 SQLite 浏览器。 - -## 中间件替代数据库会话 - -如果你不能使用带有`yield`的依赖项——例如,如果你没有使用**Python 3.7**并且不能安装上面提到的**Python 3.6**的“backports” ——你可以使用类似的方法在“中间件”中设置会话。 - -“中间件”基本上是一个对每个请求都执行的函数,其中一些代码在端点函数之前执行,另一些代码在端点函数之后执行。 - -### 创建中间件 - -我们要添加的中间件(只是一个函数)将为每个请求创建一个新的 SQLAlchemy`SessionLocal`,将其添加到请求中,然后在请求完成后关闭它。 - -//// tab | Python 3.9+ - -```Python hl_lines="12-20" -{!> ../../docs_src/sql_databases/sql_app_py39/alt_main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14-22" -{!> ../../docs_src/sql_databases/sql_app/alt_main.py!} -``` - -//// - -/// info - -我们将`SessionLocal()`请求的创建和处理放在一个`try`块中。 - -然后我们在finally块中关闭它。 - -通过这种方式,我们确保数据库会话在请求后始终关闭,即使在处理请求时出现异常也会关闭。 - -/// - -### 关于`request.state` - -`request.state`是每个`Request`对象的属性。它用于存储附加到请求本身的任意对象,例如本例中的数据库会话。您可以在[Starlette 的关于`Request`state](https://www.starlette.io/requests/#other-state)的文档中了解更多信息。 - -对于这种情况下,它帮助我们确保在整个请求中使用单个数据库会话,然后关闭(在中间件中)。 - -### 使用`yield`依赖项与使用中间件的区别 - -在此处添加**中间件**与`yield`的依赖项的作用效果类似,但也有一些区别: - -* 中间件需要更多的代码并且更复杂一些。 -* 中间件必须是一个`async`函数。 - * 如果其中有代码必须“等待”网络,它可能会在那里“阻止”您的应用程序并稍微降低性能。 - * 尽管这里的`SQLAlchemy`工作方式可能不是很成问题。 - * 但是,如果您向等待大量I/O的中间件添加更多代码,则可能会出现问题。 -* *每个*请求都会运行一个中间件。 - * 将为每个请求创建一个连接。 - * 即使处理该请求的*路径操作*不需要数据库。 - -/// tip - -最好使用带有yield的依赖项,如果这足够满足用例需求 - -/// - -/// info - -带有`yield`的依赖项是最近刚加入**FastAPI**中的。 - -所以本教程的先前版本只有带有中间件的示例,并且可能有多个应用程序使用中间件进行数据库会话管理。 - -/// From a0c3282af0a47fe492676d8d02a33335231e8ffb Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 17 Nov 2024 22:32:05 +0000 Subject: [PATCH 02/10] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [skip ci] --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c58c4abc8..fa6da7090 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -12,6 +12,10 @@ hide: * 📝 Update includes for `docs/de/docs/advanced/using-request-directly.md`. PR [#12685](https://github.com/fastapi/fastapi/pull/12685) by [@alissadb](https://github.com/alissadb). * 📝 Update includes for `docs/de/docs/how-to/conditional-openapi.md`. PR [#12689](https://github.com/fastapi/fastapi/pull/12689) by [@alissadb](https://github.com/alissadb). +### Translations + +* 🔥 Remove obsolete tutorial translation to Chinese for `docs/zh/docs/tutorial/sql-databases.md`, it references files that are no longer on the repo. PR [#12949](https://github.com/fastapi/fastapi/pull/12949) by [@tiangolo](https://github.com/tiangolo). + ## 0.115.5 ### Refactors From 1c711e71472a68fd6d6e00068e803104707ed4cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Mon, 18 Nov 2024 03:25:44 +0100 Subject: [PATCH 03/10] =?UTF-8?q?=F0=9F=93=9D=20Update=20includes=20format?= =?UTF-8?q?=20in=20docs=20with=20an=20automated=20script=20(#12950)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/bn/docs/python-types.md | 50 +- .../docs/advanced/additional-status-codes.md | 52 +- .../de/docs/advanced/advanced-dependencies.md | 120 +-- docs/de/docs/advanced/async-tests.md | 8 +- docs/de/docs/advanced/behind-a-proxy.md | 20 +- docs/de/docs/advanced/custom-response.md | 60 +- docs/de/docs/advanced/events.md | 24 +- docs/de/docs/advanced/generate-clients.md | 56 +- docs/de/docs/advanced/middleware.md | 12 +- docs/de/docs/advanced/openapi-callbacks.md | 16 +- docs/de/docs/advanced/openapi-webhooks.md | 4 +- .../path-operation-advanced-configuration.md | 40 +- .../advanced/response-change-status-code.md | 4 +- docs/de/docs/advanced/response-cookies.md | 8 +- docs/de/docs/advanced/response-directly.md | 8 +- docs/de/docs/advanced/response-headers.md | 8 +- .../docs/advanced/security/oauth2-scopes.md | 528 +--------- docs/de/docs/advanced/settings.md | 126 +-- docs/de/docs/advanced/sub-applications.md | 12 +- docs/de/docs/advanced/templates.md | 4 +- docs/de/docs/advanced/testing-dependencies.md | 52 +- docs/de/docs/advanced/testing-events.md | 4 +- docs/de/docs/advanced/testing-websockets.md | 4 +- docs/de/docs/advanced/websockets.md | 80 +- docs/de/docs/advanced/wsgi.md | 4 +- docs/de/docs/how-to/custom-docs-ui-assets.md | 28 +- .../docs/how-to/custom-request-and-route.md | 24 +- docs/de/docs/how-to/extending-openapi.md | 20 +- docs/de/docs/how-to/graphql.md | 4 +- .../docs/how-to/separate-openapi-schemas.md | 162 +--- docs/de/docs/tutorial/background-tasks.md | 64 +- docs/de/docs/tutorial/body-fields.md | 104 +- docs/de/docs/tutorial/body-nested-models.md | 220 +---- docs/de/docs/tutorial/body-updates.md | 96 +- docs/de/docs/tutorial/body.md | 96 +- docs/de/docs/tutorial/cookie-params.md | 104 +- .../dependencies/classes-as-dependencies.md | 364 +------ ...pendencies-in-path-operation-decorators.md | 120 +-- .../dependencies/dependencies-with-yield.md | 110 +-- .../dependencies/global-dependencies.md | 30 +- docs/de/docs/tutorial/dependencies/index.md | 180 +--- .../tutorial/dependencies/sub-dependencies.md | 156 +-- docs/de/docs/tutorial/encoder.md | 16 +- docs/de/docs/tutorial/extra-data-types.md | 104 +- docs/de/docs/tutorial/extra-models.md | 80 +- docs/de/docs/tutorial/first-steps.md | 32 +- docs/de/docs/tutorial/handling-errors.md | 32 +- docs/de/docs/tutorial/header-params.md | 222 +---- docs/de/docs/tutorial/metadata.md | 24 +- .../tutorial/path-operation-configuration.md | 128 +-- .../path-params-numeric-validations.md | 230 +---- docs/de/docs/tutorial/path-params.md | 40 +- .../tutorial/query-params-str-validations.md | 708 +------------- docs/de/docs/tutorial/query-params.md | 72 +- docs/de/docs/tutorial/request-files.md | 260 +---- .../docs/tutorial/request-forms-and-files.md | 60 +- docs/de/docs/tutorial/request-forms.md | 60 +- docs/de/docs/tutorial/response-model.md | 264 +---- docs/de/docs/tutorial/security/first-steps.md | 90 +- .../tutorial/security/get-current-user.md | 290 +----- docs/de/docs/tutorial/security/oauth2-jwt.md | 208 +--- .../docs/tutorial/security/simple-oauth2.md | 260 +---- docs/de/docs/tutorial/static-files.md | 4 +- docs/de/docs/tutorial/testing.md | 19 +- docs/em/docs/advanced/additional-responses.md | 16 +- .../docs/advanced/additional-status-codes.md | 4 +- .../em/docs/advanced/advanced-dependencies.md | 16 +- docs/em/docs/advanced/async-tests.md | 16 +- docs/em/docs/advanced/behind-a-proxy.md | 16 +- docs/em/docs/advanced/custom-response.md | 60 +- docs/em/docs/advanced/dataclasses.md | 8 +- docs/em/docs/advanced/events.md | 24 +- docs/em/docs/advanced/generate-clients.md | 52 +- docs/em/docs/advanced/middleware.md | 12 +- docs/em/docs/advanced/openapi-callbacks.md | 16 +- .../path-operation-advanced-configuration.md | 32 +- .../advanced/response-change-status-code.md | 4 +- docs/em/docs/advanced/response-cookies.md | 8 +- docs/em/docs/advanced/response-directly.md | 8 +- docs/em/docs/advanced/response-headers.md | 8 +- .../docs/advanced/security/http-basic-auth.md | 12 +- .../docs/advanced/security/oauth2-scopes.md | 32 +- docs/em/docs/advanced/settings.md | 40 +- docs/em/docs/advanced/sub-applications.md | 12 +- docs/em/docs/advanced/templates.md | 4 +- docs/em/docs/advanced/testing-dependencies.md | 4 +- docs/em/docs/advanced/testing-events.md | 4 +- docs/em/docs/advanced/testing-websockets.md | 4 +- .../docs/advanced/using-request-directly.md | 4 +- docs/em/docs/advanced/websockets.md | 20 +- docs/em/docs/advanced/wsgi.md | 4 +- docs/em/docs/how-to/conditional-openapi.md | 4 +- .../docs/how-to/custom-request-and-route.md | 24 +- docs/em/docs/how-to/extending-openapi.md | 20 +- docs/em/docs/how-to/graphql.md | 4 +- docs/em/docs/tutorial/background-tasks.md | 28 +- docs/em/docs/tutorial/body-fields.md | 32 +- docs/em/docs/tutorial/body-multiple-params.md | 80 +- docs/em/docs/tutorial/body-nested-models.md | 220 +---- docs/em/docs/tutorial/body.md | 96 +- docs/em/docs/tutorial/cookie-params.md | 32 +- docs/em/docs/tutorial/cors.md | 4 +- docs/em/docs/tutorial/debugging.md | 4 +- .../dependencies/classes-as-dependencies.md | 112 +-- ...pendencies-in-path-operation-decorators.md | 16 +- .../dependencies/dependencies-with-yield.md | 28 +- .../dependencies/global-dependencies.md | 4 +- docs/em/docs/tutorial/dependencies/index.md | 48 +- .../tutorial/dependencies/sub-dependencies.md | 48 +- docs/em/docs/tutorial/encoder.md | 16 +- docs/em/docs/tutorial/extra-data-types.md | 32 +- docs/em/docs/tutorial/extra-models.md | 80 +- docs/em/docs/tutorial/first-steps.md | 32 +- docs/em/docs/tutorial/handling-errors.md | 32 +- docs/em/docs/tutorial/header-params.md | 72 +- docs/em/docs/tutorial/metadata.md | 20 +- docs/em/docs/tutorial/middleware.md | 8 +- .../tutorial/path-operation-configuration.md | 128 +-- .../path-params-numeric-validations.md | 52 +- docs/em/docs/tutorial/path-params.md | 40 +- .../tutorial/query-params-str-validations.md | 236 +---- docs/em/docs/tutorial/query-params.md | 72 +- docs/em/docs/tutorial/request-files.md | 64 +- .../docs/tutorial/request-forms-and-files.md | 8 +- docs/em/docs/tutorial/request-forms.md | 8 +- docs/em/docs/tutorial/response-model.md | 264 +---- docs/em/docs/tutorial/response-status-code.md | 12 +- docs/em/docs/tutorial/schema-extra-example.md | 64 +- docs/em/docs/tutorial/security/first-steps.md | 12 +- .../tutorial/security/get-current-user.md | 84 +- docs/em/docs/tutorial/security/oauth2-jwt.md | 64 +- .../docs/tutorial/security/simple-oauth2.md | 80 +- docs/em/docs/tutorial/sql-databases.md | 900 ------------------ docs/em/docs/tutorial/static-files.md | 4 +- docs/em/docs/tutorial/testing.md | 32 +- docs/en/docs/advanced/generate-clients.md | 8 +- docs/en/docs/advanced/settings.md | 126 +-- docs/en/docs/advanced/templates.md | 4 +- docs/en/docs/advanced/testing-events.md | 4 +- docs/en/docs/tutorial/debugging.md | 4 +- .../dependencies/dependencies-with-yield.md | 170 +--- docs/en/docs/tutorial/extra-data-types.md | 104 +- docs/en/docs/tutorial/handling-errors.md | 32 +- .../tutorial/query-params-str-validations.md | 708 +------------- docs/en/docs/tutorial/query-params.md | 72 +- .../docs/tutorial/request-forms-and-files.md | 60 +- .../docs/tutorial/security/simple-oauth2.md | 260 +---- docs/en/docs/tutorial/testing.md | 18 +- .../docs/advanced/additional-status-codes.md | 4 +- .../path-operation-advanced-configuration.md | 16 +- .../advanced/response-change-status-code.md | 4 +- docs/es/docs/advanced/response-directly.md | 8 +- docs/es/docs/advanced/response-headers.md | 8 +- docs/es/docs/how-to/graphql.md | 4 +- docs/es/docs/python-types.md | 65 +- docs/es/docs/tutorial/first-steps.md | 32 +- docs/es/docs/tutorial/path-params.md | 36 +- docs/es/docs/tutorial/query-params.md | 24 +- docs/fa/docs/advanced/sub-applications.md | 12 +- docs/fa/docs/tutorial/middleware.md | 8 +- .../docs/advanced/additional-status-codes.md | 4 +- .../docs/advanced/additional-status-codes.md | 4 +- docs/ja/docs/advanced/custom-response.md | 48 +- .../path-operation-advanced-configuration.md | 16 +- docs/ja/docs/advanced/response-directly.md | 8 +- docs/ja/docs/advanced/websockets.md | 20 +- docs/ja/docs/how-to/conditional-openapi.md | 4 +- docs/ja/docs/python-types.md | 65 +- docs/ja/docs/tutorial/background-tasks.md | 16 +- docs/ja/docs/tutorial/body-fields.md | 8 +- docs/ja/docs/tutorial/body-multiple-params.md | 20 +- docs/ja/docs/tutorial/body-nested-models.md | 44 +- docs/ja/docs/tutorial/body-updates.md | 16 +- docs/ja/docs/tutorial/body.md | 24 +- docs/ja/docs/tutorial/cookie-params.md | 8 +- docs/ja/docs/tutorial/cors.md | 4 +- docs/ja/docs/tutorial/debugging.md | 4 +- .../dependencies/classes-as-dependencies.md | 28 +- ...pendencies-in-path-operation-decorators.md | 16 +- .../dependencies/dependencies-with-yield.md | 28 +- docs/ja/docs/tutorial/dependencies/index.md | 12 +- .../tutorial/dependencies/sub-dependencies.md | 12 +- docs/ja/docs/tutorial/encoder.md | 4 +- docs/ja/docs/tutorial/extra-data-types.md | 8 +- docs/ja/docs/tutorial/extra-models.md | 20 +- docs/ja/docs/tutorial/first-steps.md | 32 +- docs/ja/docs/tutorial/handling-errors.md | 32 +- docs/ja/docs/tutorial/header-params.md | 16 +- docs/ja/docs/tutorial/metadata.md | 20 +- docs/ja/docs/tutorial/middleware.md | 8 +- .../tutorial/path-operation-configuration.md | 24 +- .../path-params-numeric-validations.md | 28 +- docs/ja/docs/tutorial/path-params.md | 36 +- .../tutorial/query-params-str-validations.md | 56 +- docs/ja/docs/tutorial/query-params.md | 24 +- .../docs/tutorial/request-forms-and-files.md | 8 +- docs/ja/docs/tutorial/request-forms.md | 8 +- docs/ja/docs/tutorial/response-model.md | 40 +- docs/ja/docs/tutorial/response-status-code.md | 12 +- docs/ja/docs/tutorial/schema-extra-example.md | 12 +- docs/ja/docs/tutorial/security/first-steps.md | 12 +- .../tutorial/security/get-current-user.md | 24 +- docs/ja/docs/tutorial/security/oauth2-jwt.md | 16 +- docs/ja/docs/tutorial/static-files.md | 4 +- docs/ja/docs/tutorial/testing.md | 32 +- .../ko/docs/advanced/advanced-dependencies.md | 120 +-- docs/ko/docs/advanced/events.md | 8 +- .../advanced/response-change-status-code.md | 4 +- docs/ko/docs/advanced/response-cookies.md | 8 +- docs/ko/docs/advanced/response-directly.md | 8 +- docs/ko/docs/advanced/response-headers.md | 8 +- docs/ko/docs/advanced/testing-events.md | 4 +- docs/ko/docs/advanced/testing-websockets.md | 4 +- .../docs/advanced/using-request-directly.md | 4 +- docs/ko/docs/advanced/wsgi.md | 4 +- docs/ko/docs/python-types.md | 65 +- docs/ko/docs/tutorial/background-tasks.md | 28 +- docs/ko/docs/tutorial/body-fields.md | 104 +- docs/ko/docs/tutorial/body-multiple-params.md | 20 +- docs/ko/docs/tutorial/body-nested-models.md | 44 +- docs/ko/docs/tutorial/body.md | 96 +- docs/ko/docs/tutorial/cookie-params.md | 104 +- docs/ko/docs/tutorial/cors.md | 4 +- docs/ko/docs/tutorial/debugging.md | 4 +- .../dependencies/classes-as-dependencies.md | 112 +-- ...pendencies-in-path-operation-decorators.md | 120 +-- .../dependencies/global-dependencies.md | 30 +- docs/ko/docs/tutorial/dependencies/index.md | 180 +--- docs/ko/docs/tutorial/encoder.md | 4 +- docs/ko/docs/tutorial/extra-data-types.md | 104 +- docs/ko/docs/tutorial/first-steps.md | 32 +- docs/ko/docs/tutorial/header-params.md | 16 +- docs/ko/docs/tutorial/metadata.md | 25 +- docs/ko/docs/tutorial/middleware.md | 8 +- .../tutorial/path-operation-configuration.md | 24 +- .../path-params-numeric-validations.md | 28 +- docs/ko/docs/tutorial/path-params.md | 36 +- .../tutorial/query-params-str-validations.md | 56 +- docs/ko/docs/tutorial/query-params.md | 24 +- docs/ko/docs/tutorial/request-files.md | 16 +- .../docs/tutorial/request-forms-and-files.md | 8 +- docs/ko/docs/tutorial/response-model.md | 40 +- docs/ko/docs/tutorial/response-status-code.md | 12 +- .../tutorial/security/get-current-user.md | 84 +- .../docs/tutorial/security/simple-oauth2.md | 76 +- docs/ko/docs/tutorial/static-files.md | 4 +- docs/nl/docs/python-types.md | 50 +- docs/pt/docs/advanced/additional-responses.md | 16 +- .../docs/advanced/additional-status-codes.md | 52 +- .../pt/docs/advanced/advanced-dependencies.md | 120 +-- docs/pt/docs/advanced/async-tests.md | 16 +- docs/pt/docs/advanced/custom-response.md | 60 +- docs/pt/docs/advanced/dataclasses.md | 8 +- docs/pt/docs/advanced/events.md | 24 +- docs/pt/docs/advanced/openapi-callbacks.md | 16 +- docs/pt/docs/advanced/openapi-webhooks.md | 4 +- .../path-operation-advanced-configuration.md | 16 +- .../advanced/response-change-status-code.md | 4 +- docs/pt/docs/advanced/response-cookies.md | 8 +- docs/pt/docs/advanced/response-directly.md | 8 +- docs/pt/docs/advanced/response-headers.md | 8 +- .../docs/advanced/security/http-basic-auth.md | 90 +- .../docs/advanced/security/oauth2-scopes.md | 528 +--------- docs/pt/docs/advanced/settings.md | 126 +-- docs/pt/docs/advanced/sub-applications.md | 12 +- docs/pt/docs/advanced/templates.md | 4 +- docs/pt/docs/advanced/testing-dependencies.md | 52 +- docs/pt/docs/advanced/testing-events.md | 4 +- docs/pt/docs/advanced/testing-websockets.md | 4 +- .../docs/advanced/using-request-directly.md | 4 +- docs/pt/docs/advanced/websockets.md | 4 +- docs/pt/docs/how-to/conditional-openapi.md | 4 +- docs/pt/docs/how-to/configure-swagger-ui.md | 16 +- docs/pt/docs/how-to/custom-docs-ui-assets.md | 28 +- .../docs/how-to/custom-request-and-route.md | 24 +- docs/pt/docs/how-to/extending-openapi.md | 21 +- docs/pt/docs/how-to/graphql.md | 4 +- .../docs/how-to/separate-openapi-schemas.md | 162 +--- docs/pt/docs/tutorial/body-fields.md | 8 +- docs/pt/docs/tutorial/body-multiple-params.md | 80 +- docs/pt/docs/tutorial/body-nested-models.md | 44 +- docs/pt/docs/tutorial/body-updates.md | 96 +- docs/pt/docs/tutorial/body.md | 24 +- docs/pt/docs/tutorial/cookie-param-models.md | 82 +- docs/pt/docs/tutorial/cookie-params.md | 104 +- docs/pt/docs/tutorial/cors.md | 4 +- docs/pt/docs/tutorial/debugging.md | 4 +- .../dependencies/classes-as-dependencies.md | 364 +------ ...pendencies-in-path-operation-decorators.md | 122 +-- .../dependencies/dependencies-with-yield.md | 66 +- .../dependencies/global-dependencies.md | 30 +- docs/pt/docs/tutorial/dependencies/index.md | 180 +--- .../tutorial/dependencies/sub-dependencies.md | 156 +-- docs/pt/docs/tutorial/encoder.md | 16 +- docs/pt/docs/tutorial/extra-data-types.md | 8 +- docs/pt/docs/tutorial/extra-models.md | 80 +- docs/pt/docs/tutorial/first-steps.md | 32 +- docs/pt/docs/tutorial/handling-errors.md | 28 +- docs/pt/docs/tutorial/header-param-models.md | 132 +-- docs/pt/docs/tutorial/header-params.md | 72 +- docs/pt/docs/tutorial/metadata.md | 24 +- docs/pt/docs/tutorial/middleware.md | 8 +- .../tutorial/path-operation-configuration.md | 128 +-- .../path-params-numeric-validations.md | 52 +- docs/pt/docs/tutorial/path-params.md | 36 +- docs/pt/docs/tutorial/query-param-models.md | 132 +-- .../tutorial/query-params-str-validations.md | 56 +- docs/pt/docs/tutorial/query-params.md | 72 +- docs/pt/docs/tutorial/request-form-models.md | 60 +- .../docs/tutorial/request-forms-and-files.md | 8 +- docs/pt/docs/tutorial/request-forms.md | 8 +- docs/pt/docs/tutorial/request_files.md | 260 +---- docs/pt/docs/tutorial/response-status-code.md | 12 +- docs/pt/docs/tutorial/schema-extra-example.md | 16 +- docs/pt/docs/tutorial/security/first-steps.md | 12 +- .../docs/tutorial/security/simple-oauth2.md | 260 +---- docs/pt/docs/tutorial/static-files.md | 4 +- docs/pt/docs/tutorial/testing.md | 16 +- docs/ru/docs/python-types.md | 65 +- docs/ru/docs/tutorial/background-tasks.md | 28 +- docs/ru/docs/tutorial/body-fields.md | 32 +- docs/ru/docs/tutorial/body-multiple-params.md | 224 +---- docs/ru/docs/tutorial/body-nested-models.md | 220 +---- docs/ru/docs/tutorial/body-updates.md | 96 +- docs/ru/docs/tutorial/body.md | 24 +- docs/ru/docs/tutorial/cookie-params.md | 32 +- docs/ru/docs/tutorial/cors.md | 4 +- docs/ru/docs/tutorial/debugging.md | 4 +- .../dependencies/classes-as-dependencies.md | 364 +------ ...pendencies-in-path-operation-decorators.md | 120 +-- .../dependencies/dependencies-with-yield.md | 80 +- .../dependencies/global-dependencies.md | 30 +- docs/ru/docs/tutorial/dependencies/index.md | 180 +--- .../tutorial/dependencies/sub-dependencies.md | 156 +-- docs/ru/docs/tutorial/encoder.md | 16 +- docs/ru/docs/tutorial/extra-data-types.md | 32 +- docs/ru/docs/tutorial/extra-models.md | 80 +- docs/ru/docs/tutorial/first-steps.md | 32 +- docs/ru/docs/tutorial/handling-errors.md | 32 +- docs/ru/docs/tutorial/header-params.md | 222 +---- docs/ru/docs/tutorial/metadata.md | 20 +- .../tutorial/path-operation-configuration.md | 128 +-- .../path-params-numeric-validations.md | 230 +---- docs/ru/docs/tutorial/path-params.md | 40 +- .../tutorial/query-params-str-validations.md | 732 +------------- docs/ru/docs/tutorial/query-params.md | 72 +- docs/ru/docs/tutorial/request-files.md | 260 +---- .../docs/tutorial/request-forms-and-files.md | 60 +- docs/ru/docs/tutorial/request-forms.md | 60 +- docs/ru/docs/tutorial/response-model.md | 264 +---- docs/ru/docs/tutorial/response-status-code.md | 12 +- docs/ru/docs/tutorial/schema-extra-example.md | 136 +-- docs/ru/docs/tutorial/security/first-steps.md | 90 +- docs/ru/docs/tutorial/static-files.md | 4 +- docs/ru/docs/tutorial/testing.md | 18 +- docs/tr/docs/advanced/testing-websockets.md | 4 +- docs/tr/docs/advanced/wsgi.md | 4 +- docs/tr/docs/python-types.md | 65 +- docs/tr/docs/tutorial/cookie-params.md | 104 +- docs/tr/docs/tutorial/first-steps.md | 32 +- docs/tr/docs/tutorial/path-params.md | 40 +- docs/tr/docs/tutorial/query-params.md | 72 +- docs/tr/docs/tutorial/request-forms.md | 60 +- docs/tr/docs/tutorial/static-files.md | 4 +- docs/uk/docs/python-types.md | 40 +- docs/uk/docs/tutorial/body-fields.md | 104 +- docs/uk/docs/tutorial/body.md | 96 +- docs/uk/docs/tutorial/cookie-params.md | 104 +- docs/uk/docs/tutorial/encoder.md | 16 +- docs/uk/docs/tutorial/extra-data-types.md | 104 +- docs/uk/docs/tutorial/first-steps.md | 28 +- docs/vi/docs/python-types.md | 50 +- .../docs/advanced/additional-status-codes.md | 4 +- .../zh/docs/advanced/advanced-dependencies.md | 16 +- docs/zh/docs/advanced/behind-a-proxy.md | 16 +- docs/zh/docs/advanced/custom-response.md | 44 +- docs/zh/docs/advanced/dataclasses.md | 8 +- docs/zh/docs/advanced/events.md | 8 +- docs/zh/docs/advanced/generate-clients.md | 52 +- docs/zh/docs/advanced/middleware.md | 12 +- docs/zh/docs/advanced/openapi-callbacks.md | 16 +- .../path-operation-advanced-configuration.md | 16 +- .../advanced/response-change-status-code.md | 4 +- docs/zh/docs/advanced/response-cookies.md | 8 +- docs/zh/docs/advanced/response-directly.md | 8 +- docs/zh/docs/advanced/response-headers.md | 9 +- .../docs/advanced/security/http-basic-auth.md | 90 +- .../docs/advanced/security/oauth2-scopes.md | 32 +- docs/zh/docs/advanced/settings.md | 118 +-- docs/zh/docs/advanced/sub-applications.md | 12 +- docs/zh/docs/advanced/templates.md | 4 +- docs/zh/docs/advanced/testing-dependencies.md | 4 +- docs/zh/docs/advanced/testing-events.md | 4 +- docs/zh/docs/advanced/testing-websockets.md | 4 +- .../docs/advanced/using-request-directly.md | 4 +- docs/zh/docs/advanced/websockets.md | 80 +- docs/zh/docs/advanced/wsgi.md | 4 +- docs/zh/docs/how-to/configure-swagger-ui.md | 16 +- docs/zh/docs/python-types.md | 65 +- docs/zh/docs/tutorial/body-fields.md | 104 +- docs/zh/docs/tutorial/body-multiple-params.md | 224 +---- docs/zh/docs/tutorial/body-nested-models.md | 220 +---- docs/zh/docs/tutorial/body-updates.md | 16 +- docs/zh/docs/tutorial/body.md | 96 +- docs/zh/docs/tutorial/cookie-params.md | 104 +- docs/zh/docs/tutorial/cors.md | 4 +- docs/zh/docs/tutorial/debugging.md | 4 +- .../dependencies/classes-as-dependencies.md | 112 +-- ...pendencies-in-path-operation-decorators.md | 16 +- .../dependencies/dependencies-with-yield.md | 170 +--- .../dependencies/global-dependencies.md | 4 +- docs/zh/docs/tutorial/dependencies/index.md | 12 +- .../tutorial/dependencies/sub-dependencies.md | 12 +- docs/zh/docs/tutorial/encoder.md | 16 +- docs/zh/docs/tutorial/extra-data-types.md | 104 +- docs/zh/docs/tutorial/extra-models.md | 80 +- docs/zh/docs/tutorial/first-steps.md | 32 +- docs/zh/docs/tutorial/handling-errors.md | 40 +- docs/zh/docs/tutorial/header-params.md | 222 +---- docs/zh/docs/tutorial/metadata.md | 20 +- docs/zh/docs/tutorial/middleware.md | 8 +- .../tutorial/path-operation-configuration.md | 24 +- .../path-params-numeric-validations.md | 134 +-- docs/zh/docs/tutorial/path-params.md | 36 +- .../tutorial/query-params-str-validations.md | 80 +- docs/zh/docs/tutorial/query-params.md | 72 +- docs/zh/docs/tutorial/request-files.md | 64 +- .../docs/tutorial/request-forms-and-files.md | 8 +- docs/zh/docs/tutorial/request-forms.md | 8 +- docs/zh/docs/tutorial/response-model.md | 96 +- docs/zh/docs/tutorial/response-status-code.md | 12 +- docs/zh/docs/tutorial/schema-extra-example.md | 84 +- docs/zh/docs/tutorial/security/first-steps.md | 38 +- .../tutorial/security/get-current-user.md | 24 +- docs/zh/docs/tutorial/security/oauth2-jwt.md | 160 +--- .../docs/tutorial/security/simple-oauth2.md | 20 +- docs/zh/docs/tutorial/static-files.md | 4 +- docs/zh/docs/tutorial/testing.md | 16 +- ...regex.py => tutorial004_regex_an_py310.py} | 0 439 files changed, 2134 insertions(+), 24948 deletions(-) delete mode 100644 docs/em/docs/tutorial/sql-databases.md rename docs_src/query_params_str_validations/{tutorial004_an_py310_regex.py => tutorial004_regex_an_py310.py} (100%) diff --git a/docs/bn/docs/python-types.md b/docs/bn/docs/python-types.md index 4a602b679..d98c2ec87 100644 --- a/docs/bn/docs/python-types.md +++ b/docs/bn/docs/python-types.md @@ -22,9 +22,8 @@ Python-এ ঐচ্ছিক "টাইপ হিন্ট" (যা "টাই চলুন একটি সাধারণ উদাহরণ দিয়ে শুরু করি: -```Python -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} + এই প্রোগ্রামটি কল করলে আউটপুট হয়: @@ -38,9 +37,8 @@ John Doe * প্রতিটির প্রথম অক্ষরকে `title()` ব্যবহার করে বড় হাতের অক্ষরে রূপান্তর করে। * তাদেরকে মাঝখানে একটি স্পেস দিয়ে concatenate করে। -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### এটি সম্পাদনা করুন @@ -82,9 +80,8 @@ John Doe এগুলিই "টাইপ হিন্ট": -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + এটি ডিফল্ট ভ্যালু ঘোষণা করার মত নয় যেমন: @@ -112,9 +109,8 @@ John Doe এই ফাংশনটি দেখুন, এটিতে ইতিমধ্যে টাইপ হিন্ট রয়েছে: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + এডিটর ভেরিয়েবলগুলির টাইপ জানার কারণে, আপনি শুধুমাত্র অটোকমপ্লিশনই পান না, আপনি এরর চেকও পান: @@ -122,9 +118,8 @@ John Doe এখন আপনি জানেন যে আপনাকে এটি ঠিক করতে হবে, `age`-কে একটি স্ট্রিং হিসেবে রূপান্তর করতে `str(age)` ব্যবহার করতে হবে: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## টাইপ ঘোষণা @@ -143,9 +138,8 @@ John Doe * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### টাইপ প্যারামিটার সহ জেনেরিক টাইপ @@ -369,9 +363,8 @@ Python 3.6 এবং তার উপরের সংস্করণগুলি একটি উদাহরণ হিসেবে, এই ফাংশনটি নিন: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial009c.py!} -``` +{* ../../docs_src/python_types/tutorial009c.py hl[1,4] *} + `name` প্যারামিটারটি `Optional[str]` হিসেবে সংজ্ঞায়িত হয়েছে, কিন্তু এটি **অপশনাল নয়**, আপনি প্যারামিটার ছাড়া ফাংশনটি কল করতে পারবেন না: @@ -387,9 +380,8 @@ say_hi(name=None) # এটি কাজ করে, None বৈধ 🎉 সুখবর হল, একবার আপনি Python 3.10 ব্যবহার করা শুরু করলে, আপনাকে এগুলোর ব্যাপারে আর চিন্তা করতে হবে না, যেহুতু আপনি | ব্যবহার করেই ইউনিয়ন ঘোষণা করতে পারবেন: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial009c_py310.py!} -``` +{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *} + এবং তারপর আপনাকে নামগুলি যেমন `Optional` এবং `Union` নিয়ে আর চিন্তা করতে হবে না। 😎 @@ -451,15 +443,13 @@ Python 3.10-এ, `Union` এবং `Optional` জেনেরিকস ব্য ধরুন আপনার কাছে `Person` নামে একটি ক্লাস আছে, যার একটি নাম আছে: -```Python hl_lines="1-3" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + তারপর আপনি একটি ভেরিয়েবলকে `Person` টাইপের হিসেবে ঘোষণা করতে পারেন: -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + এবং তারপর, আবার, আপনি এডিটর সাপোর্ট পেয়ে যাবেন: diff --git a/docs/de/docs/advanced/additional-status-codes.md b/docs/de/docs/advanced/additional-status-codes.md index 50702e7e6..b07bb90ab 100644 --- a/docs/de/docs/advanced/additional-status-codes.md +++ b/docs/de/docs/advanced/additional-status-codes.md @@ -14,57 +14,7 @@ Sie möchten aber auch, dass sie neue Artikel akzeptiert. Und wenn die Elemente Um dies zu erreichen, importieren Sie `JSONResponse`, und geben Sie Ihren Inhalt direkt zurück, indem Sie den gewünschten `status_code` setzen: -//// tab | Python 3.10+ - -```Python hl_lines="4 25" -{!> ../../docs_src/additional_status_codes/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4 25" -{!> ../../docs_src/additional_status_codes/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 26" -{!> ../../docs_src/additional_status_codes/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="2 23" -{!> ../../docs_src/additional_status_codes/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="4 25" -{!> ../../docs_src/additional_status_codes/tutorial001.py!} -``` - -//// +{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *} /// warning | Achtung diff --git a/docs/de/docs/advanced/advanced-dependencies.md b/docs/de/docs/advanced/advanced-dependencies.md index 80cbf1fd3..56eb7d454 100644 --- a/docs/de/docs/advanced/advanced-dependencies.md +++ b/docs/de/docs/advanced/advanced-dependencies.md @@ -18,35 +18,7 @@ Nicht die Klasse selbst (die bereits aufrufbar ist), sondern eine Instanz dieser Dazu deklarieren wir eine Methode `__call__`: -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/dependencies/tutorial011_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[12] *} In diesem Fall ist dieses `__call__` das, was **FastAPI** verwendet, um nach zusätzlichen Parametern und Unterabhängigkeiten zu suchen, und das ist es auch, was später aufgerufen wird, um einen Wert an den Parameter in Ihrer *Pfadoperation-Funktion* zu übergeben. @@ -54,35 +26,7 @@ In diesem Fall ist dieses `__call__` das, was **FastAPI** verwendet, um nach zus Und jetzt können wir `__init__` verwenden, um die Parameter der Instanz zu deklarieren, die wir zum `Parametrisieren` der Abhängigkeit verwenden können: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/dependencies/tutorial011_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[9] *} In diesem Fall wird **FastAPI** `__init__` nie berühren oder sich darum kümmern, wir werden es direkt in unserem Code verwenden. @@ -90,35 +34,7 @@ In diesem Fall wird **FastAPI** `__init__` nie berühren oder sich darum kümmer Wir könnten eine Instanz dieser Klasse erstellen mit: -//// tab | Python 3.9+ - -```Python hl_lines="18" -{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial011_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="16" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[18] *} Und auf diese Weise können wir unsere Abhängigkeit „parametrisieren“, die jetzt `"bar"` enthält, als das Attribut `checker.fixed_content`. @@ -134,35 +50,7 @@ checker(q="somequery") ... und übergibt, was immer das als Wert dieser Abhängigkeit in unserer *Pfadoperation-Funktion* zurückgibt, als den Parameter `fixed_content_included`: -//// tab | Python 3.9+ - -```Python hl_lines="22" -{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="21" -{!> ../../docs_src/dependencies/tutorial011_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="20" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[22] *} /// tip | Tipp diff --git a/docs/de/docs/advanced/async-tests.md b/docs/de/docs/advanced/async-tests.md index c118e588f..b82aadf00 100644 --- a/docs/de/docs/advanced/async-tests.md +++ b/docs/de/docs/advanced/async-tests.md @@ -32,15 +32,11 @@ Betrachten wir als einfaches Beispiel eine Dateistruktur ähnlich der in [Größ Die Datei `main.py` hätte als Inhalt: -```Python -{!../../docs_src/async_tests/main.py!} -``` +{* ../../docs_src/async_tests/main.py *} Die Datei `test_main.py` hätte die Tests für `main.py`, das könnte jetzt so aussehen: -```Python -{!../../docs_src/async_tests/test_main.py!} -``` +{* ../../docs_src/async_tests/test_main.py *} ## Es ausführen diff --git a/docs/de/docs/advanced/behind-a-proxy.md b/docs/de/docs/advanced/behind-a-proxy.md index 9da18a626..9e2282280 100644 --- a/docs/de/docs/advanced/behind-a-proxy.md +++ b/docs/de/docs/advanced/behind-a-proxy.md @@ -18,9 +18,7 @@ In diesem Fall würde der ursprüngliche Pfad `/app` tatsächlich unter `/api/v1 Auch wenn Ihr gesamter Code unter der Annahme geschrieben ist, dass es nur `/app` gibt. -```Python hl_lines="6" -{!../../docs_src/behind_a_proxy/tutorial001.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial001.py hl[6] *} Und der Proxy würde das **Pfadpräfix** on-the-fly **"entfernen**", bevor er die Anfrage an Uvicorn übermittelt, dafür sorgend, dass Ihre Anwendung davon überzeugt ist, dass sie unter `/app` bereitgestellt wird, sodass Sie nicht Ihren gesamten Code dahingehend aktualisieren müssen, das Präfix `/api/v1` zu verwenden. @@ -98,9 +96,7 @@ Sie können den aktuellen `root_path` abrufen, der von Ihrer Anwendung für jede Hier fügen wir ihn, nur zu Demonstrationszwecken, in die Nachricht ein. -```Python hl_lines="8" -{!../../docs_src/behind_a_proxy/tutorial001.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial001.py hl[8] *} Wenn Sie Uvicorn dann starten mit: @@ -127,9 +123,7 @@ wäre die Response etwa: Falls Sie keine Möglichkeit haben, eine Kommandozeilenoption wie `--root-path` oder ähnlich zu übergeben, können Sie als Alternative beim Erstellen Ihrer FastAPI-Anwendung den Parameter `root_path` setzen: -```Python hl_lines="3" -{!../../docs_src/behind_a_proxy/tutorial002.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial002.py hl[3] *} Die Übergabe des `root_path` an `FastAPI` wäre das Äquivalent zur Übergabe der `--root-path`-Kommandozeilenoption an Uvicorn oder Hypercorn. @@ -309,9 +303,7 @@ Wenn Sie eine benutzerdefinierte Liste von Servern (`servers`) übergeben und es Zum Beispiel: -```Python hl_lines="4-7" -{!../../docs_src/behind_a_proxy/tutorial003.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial003.py hl[4:7] *} Erzeugt ein OpenAPI-Schema, wie: @@ -358,9 +350,7 @@ Die Dokumentationsoberfläche interagiert mit dem von Ihnen ausgewählten Server Wenn Sie nicht möchten, dass **FastAPI** einen automatischen Server inkludiert, welcher `root_path` verwendet, können Sie den Parameter `root_path_in_servers=False` verwenden: -```Python hl_lines="9" -{!../../docs_src/behind_a_proxy/tutorial004.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial004.py hl[9] *} Dann wird er nicht in das OpenAPI-Schema aufgenommen. diff --git a/docs/de/docs/advanced/custom-response.md b/docs/de/docs/advanced/custom-response.md index 7738bfca4..43cb55e04 100644 --- a/docs/de/docs/advanced/custom-response.md +++ b/docs/de/docs/advanced/custom-response.md @@ -30,9 +30,7 @@ Das liegt daran, dass FastAPI standardmäßig jedes enthaltene Element überprü Wenn Sie jedoch sicher sind, dass der von Ihnen zurückgegebene Inhalt **mit JSON serialisierbar** ist, können Sie ihn direkt an die Response-Klasse übergeben und die zusätzliche Arbeit vermeiden, die FastAPI hätte, indem es Ihren zurückgegebenen Inhalt durch den `jsonable_encoder` leitet, bevor es ihn an die Response-Klasse übergibt. -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial001b.py!} -``` +{* ../../docs_src/custom_response/tutorial001b.py hl[2,7] *} /// info @@ -57,9 +55,7 @@ Um eine Response mit HTML direkt von **FastAPI** zurückzugeben, verwenden Sie ` * Importieren Sie `HTMLResponse`. * Übergeben Sie `HTMLResponse` als den Parameter `response_class` Ihres *Pfadoperation-Dekorators*. -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial002.py!} -``` +{* ../../docs_src/custom_response/tutorial002.py hl[2,7] *} /// info @@ -77,9 +73,7 @@ Wie in [Eine Response direkt zurückgeben](response-directly.md){.internal-link Das gleiche Beispiel von oben, das eine `HTMLResponse` zurückgibt, könnte so aussehen: -```Python hl_lines="2 7 19" -{!../../docs_src/custom_response/tutorial003.py!} -``` +{* ../../docs_src/custom_response/tutorial003.py hl[2,7,19] *} /// warning | Achtung @@ -103,9 +97,7 @@ Die `response_class` wird dann nur zur Dokumentation der OpenAPI-Pfadoperation* Es könnte zum Beispiel so etwas sein: -```Python hl_lines="7 21 23" -{!../../docs_src/custom_response/tutorial004.py!} -``` +{* ../../docs_src/custom_response/tutorial004.py hl[7,21,23] *} In diesem Beispiel generiert die Funktion `generate_html_response()` bereits eine `Response` und gibt sie zurück, anstatt das HTML in einem `str` zurückzugeben. @@ -144,9 +136,7 @@ Sie akzeptiert die folgenden Parameter: FastAPI (eigentlich Starlette) fügt automatisch einen Content-Length-Header ein. Außerdem wird es einen Content-Type-Header einfügen, der auf dem media_type basiert, und für Texttypen einen Zeichensatz (charset) anfügen. -```Python hl_lines="1 18" -{!../../docs_src/response_directly/tutorial002.py!} -``` +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} ### `HTMLResponse` @@ -156,9 +146,7 @@ Nimmt Text oder Bytes entgegen und gibt eine HTML-Response zurück, wie Sie oben Nimmt Text oder Bytes entgegen und gibt eine Plain-Text-Response zurück. -```Python hl_lines="2 7 9" -{!../../docs_src/custom_response/tutorial005.py!} -``` +{* ../../docs_src/custom_response/tutorial005.py hl[2,7,9] *} ### `JSONResponse` @@ -180,9 +168,7 @@ Eine alternative JSON-Response mit ../../docs_src/generate_clients/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-11 14-15 18 19 23" -{!> ../../docs_src/generate_clients/tutorial001.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial001_py39.py hl[7:9,12:13,16:17,21] *} Beachten Sie, dass die *Pfadoperationen* die Modelle definieren, welche diese für die Request- und Response-Payload verwenden, indem sie die Modelle `Item` und `ResponseMessage` verwenden. @@ -147,21 +133,7 @@ In vielen Fällen wird Ihre FastAPI-Anwendung größer sein und Sie werden wahrs Beispielsweise könnten Sie einen Abschnitt für **Items (Artikel)** und einen weiteren Abschnitt für **Users (Benutzer)** haben, und diese könnten durch Tags getrennt sein: -//// tab | Python 3.9+ - -```Python hl_lines="21 26 34" -{!> ../../docs_src/generate_clients/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="23 28 36" -{!> ../../docs_src/generate_clients/tutorial002.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial002_py39.py hl[21,26,34] *} ### Einen TypeScript-Client mit Tags generieren @@ -208,21 +180,7 @@ Hier verwendet sie beispielsweise den ersten Tag (Sie werden wahrscheinlich nur Anschließend können Sie diese benutzerdefinierte Funktion als Parameter `generate_unique_id_function` an **FastAPI** übergeben: -//// tab | Python 3.9+ - -```Python hl_lines="6-7 10" -{!> ../../docs_src/generate_clients/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8-9 12" -{!> ../../docs_src/generate_clients/tutorial003.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial003_py39.py hl[6:7,10] *} ### Einen TypeScript-Client mit benutzerdefinierten Operation-IDs generieren @@ -244,13 +202,7 @@ Aber für den generierten Client könnten wir die OpenAPI-Operation-IDs direkt v Wir könnten das OpenAPI-JSON in eine Datei `openapi.json` herunterladen und dann mit einem Skript wie dem folgenden **den vorangestellten Tag entfernen**: -//// tab | Python - -```Python -{!> ../../docs_src/generate_clients/tutorial004.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial004.py *} //// tab | Node.js diff --git a/docs/de/docs/advanced/middleware.md b/docs/de/docs/advanced/middleware.md index d2130c9b7..17b339788 100644 --- a/docs/de/docs/advanced/middleware.md +++ b/docs/de/docs/advanced/middleware.md @@ -57,17 +57,13 @@ Erzwingt, dass alle eingehenden Requests entweder `https` oder `wss` sein müsse Alle eingehenden Requests an `http` oder `ws` werden stattdessen an das sichere Schema umgeleitet. -```Python hl_lines="2 6" -{!../../docs_src/advanced_middleware/tutorial001.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial001.py hl[2,6] *} ## `TrustedHostMiddleware` Erzwingt, dass alle eingehenden Requests einen korrekt gesetzten `Host`-Header haben, um sich vor HTTP-Host-Header-Angriffen zu schützen. -```Python hl_lines="2 6-8" -{!../../docs_src/advanced_middleware/tutorial002.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial002.py hl[2,6:8] *} Die folgenden Argumente werden unterstützt: @@ -81,9 +77,7 @@ Verarbeitet GZip-Responses für alle Requests, die `"gzip"` im `Accept-Encoding` Diese Middleware verarbeitet sowohl Standard- als auch Streaming-Responses. -```Python hl_lines="2 6" -{!../../docs_src/advanced_middleware/tutorial003.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial003.py hl[2,6] *} Die folgenden Argumente werden unterstützt: diff --git a/docs/de/docs/advanced/openapi-callbacks.md b/docs/de/docs/advanced/openapi-callbacks.md index 4ee2874a3..53f06e24e 100644 --- a/docs/de/docs/advanced/openapi-callbacks.md +++ b/docs/de/docs/advanced/openapi-callbacks.md @@ -31,9 +31,7 @@ Sie verfügt über eine *Pfadoperation*, die einen `Invoice`-Body empfängt, und Dieser Teil ist ziemlich normal, der größte Teil des Codes ist Ihnen wahrscheinlich bereits bekannt: -```Python hl_lines="9-13 36-53" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[9:13,36:53] *} /// tip | Tipp @@ -92,9 +90,7 @@ Wenn Sie diese Sichtweise (des *externen Entwicklers*) vorübergehend übernehme Erstellen Sie zunächst einen neuen `APIRouter`, der einen oder mehrere Callbacks enthält. -```Python hl_lines="3 25" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[3,25] *} ### Die Callback-*Pfadoperation* erstellen @@ -105,9 +101,7 @@ Sie sollte wie eine normale FastAPI-*Pfadoperation* aussehen: * Sie sollte wahrscheinlich eine Deklaration des Bodys enthalten, die sie erhalten soll, z. B. `body: InvoiceEvent`. * Und sie könnte auch eine Deklaration der Response enthalten, die zurückgegeben werden soll, z. B. `response_model=InvoiceEventReceived`. -```Python hl_lines="16-18 21-22 28-32" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[16:18,21:22,28:32] *} Es gibt zwei Hauptunterschiede zu einer normalen *Pfadoperation*: @@ -175,9 +169,7 @@ An diesem Punkt haben Sie die benötigte(n) *Callback-Pfadoperation(en)* (diejen Verwenden Sie nun den Parameter `callbacks` im *Pfadoperation-Dekorator Ihrer API*, um das Attribut `.routes` (das ist eigentlich nur eine `list`e von Routen/*Pfadoperationen*) dieses Callback-Routers zu übergeben: -```Python hl_lines="35" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[35] *} /// tip | Tipp diff --git a/docs/de/docs/advanced/openapi-webhooks.md b/docs/de/docs/advanced/openapi-webhooks.md index 9f1bb6959..50b95eaf8 100644 --- a/docs/de/docs/advanced/openapi-webhooks.md +++ b/docs/de/docs/advanced/openapi-webhooks.md @@ -32,9 +32,7 @@ Webhooks sind in OpenAPI 3.1.0 und höher verfügbar und werden von FastAPI `0.9 Wenn Sie eine **FastAPI**-Anwendung erstellen, gibt es ein `webhooks`-Attribut, mit dem Sie *Webhooks* definieren können, genauso wie Sie *Pfadoperationen* definieren würden, zum Beispiel mit `@app.webhooks.post()`. -```Python hl_lines="9-13 36-53" -{!../../docs_src/openapi_webhooks/tutorial001.py!} -``` +{* ../../docs_src/openapi_webhooks/tutorial001.py hl[9:13,36:53] *} Die von Ihnen definierten Webhooks landen im **OpenAPI**-Schema und der automatischen **Dokumentations-Oberfläche**. diff --git a/docs/de/docs/advanced/path-operation-advanced-configuration.md b/docs/de/docs/advanced/path-operation-advanced-configuration.md index 53d395724..b6e88d2c9 100644 --- a/docs/de/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/de/docs/advanced/path-operation-advanced-configuration.md @@ -12,9 +12,7 @@ Mit dem Parameter `operation_id` können Sie die OpenAPI `operationId` festlegen Sie müssten sicherstellen, dass sie für jede Operation eindeutig ist. -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *} ### Verwendung des Namens der *Pfadoperation-Funktion* als operationId @@ -22,9 +20,7 @@ Wenn Sie die Funktionsnamen Ihrer API als `operationId`s verwenden möchten, kö Sie sollten dies tun, nachdem Sie alle Ihre *Pfadoperationen* hinzugefügt haben. -```Python hl_lines="2 12-21 24" -{!../../docs_src/path_operation_advanced_configuration/tutorial002.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2,12:21,24] *} /// tip | Tipp @@ -44,9 +40,7 @@ Auch wenn diese sich in unterschiedlichen Modulen (Python-Dateien) befinden. Um eine *Pfadoperation* aus dem generierten OpenAPI-Schema (und damit aus den automatischen Dokumentationssystemen) auszuschließen, verwenden Sie den Parameter `include_in_schema` und setzen Sie ihn auf `False`: -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *} ## Fortgeschrittene Beschreibung mittels Docstring @@ -56,9 +50,7 @@ Das Hinzufügen eines `\f` (ein maskiertes „Form Feed“-Zeichen) führt dazu, Sie wird nicht in der Dokumentation angezeigt, aber andere Tools (z. B. Sphinx) können den Rest verwenden. -```Python hl_lines="19-29" -{!../../docs_src/path_operation_advanced_configuration/tutorial004.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19:29] *} ## Zusätzliche Responses @@ -100,9 +92,7 @@ Sie können das OpenAPI-Schema für eine *Pfadoperation* erweitern, indem Sie de Dieses `openapi_extra` kann beispielsweise hilfreich sein, um OpenAPI-Erweiterungen zu deklarieren: -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial005.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial005.py hl[6] *} Wenn Sie die automatische API-Dokumentation öffnen, wird Ihre Erweiterung am Ende der spezifischen *Pfadoperation* angezeigt. @@ -149,9 +139,7 @@ Sie könnten sich beispielsweise dafür entscheiden, den Request mit Ihrem eigen Das könnte man mit `openapi_extra` machen: -```Python hl_lines="20-37 39-40" -{!../../docs_src/path_operation_advanced_configuration/tutorial006.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial006.py hl[20:37,39:40] *} In diesem Beispiel haben wir kein Pydantic-Modell deklariert. Tatsächlich wird der Requestbody nicht einmal als JSON geparst, sondern direkt als `bytes` gelesen und die Funktion `magic_data_reader ()` wäre dafür verantwortlich, ihn in irgendeiner Weise zu parsen. @@ -167,17 +155,13 @@ In der folgenden Anwendung verwenden wir beispielsweise weder die integrierte Fu //// tab | Pydantic v2 -```Python hl_lines="17-22 24" -{!> ../../docs_src/path_operation_advanced_configuration/tutorial007.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[17:22,24] *} //// //// tab | Pydantic v1 -```Python hl_lines="17-22 24" -{!> ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py hl[17:22,24] *} //// @@ -195,17 +179,13 @@ Und dann parsen wir in unserem Code diesen YAML-Inhalt direkt und verwenden dann //// tab | Pydantic v2 -```Python hl_lines="26-33" -{!> ../../docs_src/path_operation_advanced_configuration/tutorial007.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[26:33] *} //// //// tab | Pydantic v1 -```Python hl_lines="26-33" -{!> ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py hl[26:33] *} //// diff --git a/docs/de/docs/advanced/response-change-status-code.md b/docs/de/docs/advanced/response-change-status-code.md index 202df0d87..0aac32f4e 100644 --- a/docs/de/docs/advanced/response-change-status-code.md +++ b/docs/de/docs/advanced/response-change-status-code.md @@ -20,9 +20,7 @@ Sie können einen Parameter vom Typ `Response` in Ihrer *Pfadoperation-Funktion* Anschließend können Sie den `status_code` in diesem *vorübergehenden* Response-Objekt festlegen. -```Python hl_lines="1 9 12" -{!../../docs_src/response_change_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *} Und dann können Sie wie gewohnt jedes benötigte Objekt zurückgeben (ein `dict`, ein Datenbankmodell usw.). diff --git a/docs/de/docs/advanced/response-cookies.md b/docs/de/docs/advanced/response-cookies.md index 6f9d66e07..5fe2cf7e3 100644 --- a/docs/de/docs/advanced/response-cookies.md +++ b/docs/de/docs/advanced/response-cookies.md @@ -6,9 +6,7 @@ Sie können einen Parameter vom Typ `Response` in Ihrer *Pfadoperation-Funktion* Und dann können Sie Cookies in diesem *vorübergehenden* Response-Objekt setzen. -```Python hl_lines="1 8-9" -{!../../docs_src/response_cookies/tutorial002.py!} -``` +{* ../../docs_src/response_cookies/tutorial002.py hl[1,8:9] *} Anschließend können Sie wie gewohnt jedes gewünschte Objekt zurückgeben (ein `dict`, ein Datenbankmodell, usw.). @@ -26,9 +24,7 @@ Dazu können Sie eine Response erstellen, wie unter [Eine Response direkt zurüc Setzen Sie dann Cookies darin und geben Sie sie dann zurück: -```Python hl_lines="10-12" -{!../../docs_src/response_cookies/tutorial001.py!} -``` +{* ../../docs_src/response_cookies/tutorial001.py hl[10:12] *} /// tip | Tipp diff --git a/docs/de/docs/advanced/response-directly.md b/docs/de/docs/advanced/response-directly.md index fab2e3965..b84aa8ab9 100644 --- a/docs/de/docs/advanced/response-directly.md +++ b/docs/de/docs/advanced/response-directly.md @@ -34,9 +34,7 @@ Sie können beispielsweise kein Pydantic-Modell in eine `JSONResponse` einfügen In diesen Fällen können Sie den `jsonable_encoder` verwenden, um Ihre Daten zu konvertieren, bevor Sie sie an eine Response übergeben: -```Python hl_lines="6-7 21-22" -{!../../docs_src/response_directly/tutorial001.py!} -``` +{* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *} /// note | Technische Details @@ -56,9 +54,7 @@ Nehmen wir an, Sie möchten eine ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="2 4 8 12 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 154" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[4,8,12,46,64,105,107:115,121:124,128:134,139,155] *} Sehen wir uns diese Änderungen nun Schritt für Schritt an. @@ -136,71 +72,7 @@ Die erste Änderung ist, dass wir jetzt das OAuth2-Sicherheitsschema mit zwei ve Der `scopes`-Parameter erhält ein `dict` mit jedem Scope als Schlüssel und dessen Beschreibung als Wert: -//// tab | Python 3.10+ - -```Python hl_lines="62-65" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="62-65" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="63-66" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="61-64" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="62-65" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="62-65" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[62:65] *} Da wir diese Scopes jetzt deklarieren, werden sie in der API-Dokumentation angezeigt, wenn Sie sich einloggen/autorisieren. @@ -226,71 +98,7 @@ Aus Sicherheitsgründen sollten Sie jedoch sicherstellen, dass Sie in Ihrer Anwe /// -//// tab | Python 3.10+ - -```Python hl_lines="155" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="155" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="156" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="154" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="155" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="155" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[155] *} ## Scopes in *Pfadoperationen* und Abhängigkeiten deklarieren @@ -316,71 +124,7 @@ Wir tun dies hier, um zu demonstrieren, wie **FastAPI** auf verschiedenen Ebenen /// -//// tab | Python 3.10+ - -```Python hl_lines="4 139 170" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4 139 170" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 140 171" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="3 138 167" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="4 139 168" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="4 139 168" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[4,139,170] *} /// info | Technische Details @@ -406,71 +150,7 @@ Wir deklarieren auch einen speziellen Parameter vom Typ `SecurityScopes`, der au Diese `SecurityScopes`-Klasse ähnelt `Request` (`Request` wurde verwendet, um das Request-Objekt direkt zu erhalten). -//// tab | Python 3.10+ - -```Python hl_lines="8 105" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="8 105" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8 106" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7 104" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="8 105" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="8 105" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[8,105] *} ## Die `scopes` verwenden @@ -484,71 +164,7 @@ Wir erstellen eine `HTTPException`, die wir später an mehreren Stellen wiederve In diese Exception fügen wir (falls vorhanden) die erforderlichen Scopes als durch Leerzeichen getrennten String ein (unter Verwendung von `scope_str`). Wir fügen diesen String mit den Scopes in den Header `WWW-Authenticate` ein (das ist Teil der Spezifikation). -//// tab | Python 3.10+ - -```Python hl_lines="105 107-115" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="105 107-115" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="106 108-116" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="104 106-114" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="105 107-115" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="105 107-115" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[105,107:115] *} ## Den `username` und das Format der Daten überprüfen @@ -564,71 +180,7 @@ Anstelle beispielsweise eines `dict`s oder etwas anderem, was später in der Anw Wir verifizieren auch, dass wir einen Benutzer mit diesem Benutzernamen haben, und wenn nicht, lösen wir dieselbe Exception aus, die wir zuvor erstellt haben. -//// tab | Python 3.10+ - -```Python hl_lines="46 116-127" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="46 116-127" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="47 117-128" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="45 115-126" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="46 116-127" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="46 116-127" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[46,116:127] *} ## Die `scopes` verifizieren @@ -636,71 +188,7 @@ Wir überprüfen nun, ob das empfangenen Token alle Scopes enthält, die von die Hierzu verwenden wir `security_scopes.scopes`, das eine `list`e mit allen diesen Scopes als `str` enthält. -//// tab | Python 3.10+ - -```Python hl_lines="128-134" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="128-134" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="129-135" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="127-133" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="128-134" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="128-134" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[128:134] *} ## Abhängigkeitsbaum und Scopes diff --git a/docs/de/docs/advanced/settings.md b/docs/de/docs/advanced/settings.md index c90f74844..00cc2ac37 100644 --- a/docs/de/docs/advanced/settings.md +++ b/docs/de/docs/advanced/settings.md @@ -180,9 +180,7 @@ Sie können dieselben Validierungs-Funktionen und -Tools verwenden, die Sie für //// tab | Pydantic v2 -```Python hl_lines="2 5-8 11" -{!> ../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[2,5:8,11] *} //// @@ -194,9 +192,7 @@ In Pydantic v1 würden Sie `BaseSettings` direkt von `pydantic` statt von `pydan /// -```Python hl_lines="2 5-8 11" -{!> ../../docs_src/settings/tutorial001_pv1.py!} -``` +{* ../../docs_src/settings/tutorial001_pv1.py hl[2,5:8,11] *} //// @@ -214,9 +210,7 @@ Als Nächstes werden die Daten konvertiert und validiert. Wenn Sie also dieses ` Dann können Sie das neue `settings`-Objekt in Ihrer Anwendung verwenden: -```Python hl_lines="18-20" -{!../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[18:20] *} ### Den Server ausführen @@ -250,15 +244,11 @@ Sie könnten diese Einstellungen in eine andere Moduldatei einfügen, wie Sie in Sie könnten beispielsweise eine Datei `config.py` haben mit: -```Python -{!../../docs_src/settings/app01/config.py!} -``` +{* ../../docs_src/settings/app01/config.py *} Und dann verwenden Sie diese in einer Datei `main.py`: -```Python hl_lines="3 11-13" -{!../../docs_src/settings/app01/main.py!} -``` +{* ../../docs_src/settings/app01/main.py hl[3,11:13] *} /// tip | Tipp @@ -276,9 +266,7 @@ Dies könnte besonders beim Testen nützlich sein, da es sehr einfach ist, eine Ausgehend vom vorherigen Beispiel könnte Ihre Datei `config.py` so aussehen: -```Python hl_lines="10" -{!../../docs_src/settings/app02/config.py!} -``` +{* ../../docs_src/settings/app02/config.py hl[10] *} Beachten Sie, dass wir jetzt keine Standardinstanz `settings = Settings()` erstellen. @@ -286,35 +274,7 @@ Beachten Sie, dass wir jetzt keine Standardinstanz `settings = Settings()` erste Jetzt erstellen wir eine Abhängigkeit, die ein neues `config.Settings()` zurückgibt. -//// tab | Python 3.9+ - -```Python hl_lines="6 12-13" -{!> ../../docs_src/settings/app02_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="6 12-13" -{!> ../../docs_src/settings/app02_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="5 11-12" -{!> ../../docs_src/settings/app02/main.py!} -``` - -//// +{* ../../docs_src/settings/app02_an_py39/main.py hl[6,12:13] *} /// tip | Tipp @@ -326,43 +286,13 @@ Im Moment nehmen Sie an, dass `get_settings()` eine normale Funktion ist. Und dann können wir das von der *Pfadoperation-Funktion* als Abhängigkeit einfordern und es überall dort verwenden, wo wir es brauchen. -//// tab | Python 3.9+ - -```Python hl_lines="17 19-21" -{!> ../../docs_src/settings/app02_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17 19-21" -{!> ../../docs_src/settings/app02_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="16 18-20" -{!> ../../docs_src/settings/app02/main.py!} -``` - -//// +{* ../../docs_src/settings/app02_an_py39/main.py hl[17,19:21] *} ### Einstellungen und Tests Dann wäre es sehr einfach, beim Testen ein anderes Einstellungsobjekt bereitzustellen, indem man eine Abhängigkeitsüberschreibung für `get_settings` erstellt: -```Python hl_lines="9-10 13 21" -{!../../docs_src/settings/app02/test_main.py!} -``` +{* ../../docs_src/settings/app02/test_main.py hl[9:10,13,21] *} Bei der Abhängigkeitsüberschreibung legen wir einen neuen Wert für `admin_email` fest, wenn wir das neue `Settings`-Objekt erstellen, und geben dann dieses neue Objekt zurück. @@ -405,9 +335,7 @@ Und dann aktualisieren Sie Ihre `config.py` mit: //// tab | Pydantic v2 -```Python hl_lines="9" -{!> ../../docs_src/settings/app03_an/config.py!} -``` +{* ../../docs_src/settings/app03_an/config.py hl[9] *} /// tip | Tipp @@ -419,9 +347,7 @@ Das Attribut `model_config` wird nur für die Pydantic-Konfiguration verwendet. //// tab | Pydantic v1 -```Python hl_lines="9-10" -{!> ../../docs_src/settings/app03_an/config_pv1.py!} -``` +{* ../../docs_src/settings/app03_an/config_pv1.py hl[9:10] *} /// tip | Tipp @@ -462,35 +388,7 @@ würden wir dieses Objekt für jeden Request erstellen und die `.env`-Datei für Da wir jedoch den `@lru_cache`-Dekorator oben verwenden, wird das `Settings`-Objekt nur einmal erstellt, nämlich beim ersten Aufruf. ✔️ -//// tab | Python 3.9+ - -```Python hl_lines="1 11" -{!> ../../docs_src/settings/app03_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 11" -{!> ../../docs_src/settings/app03_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="1 10" -{!> ../../docs_src/settings/app03/main.py!} -``` - -//// +{* ../../docs_src/settings/app03_an_py39/main.py hl[1,11] *} Dann wird bei allen nachfolgenden Aufrufen von `get_settings()`, in den Abhängigkeiten für darauffolgende Requests, dasselbe Objekt zurückgegeben, das beim ersten Aufruf zurückgegeben wurde, anstatt den Code von `get_settings()` erneut auszuführen und ein neues `Settings`-Objekt zu erstellen. diff --git a/docs/de/docs/advanced/sub-applications.md b/docs/de/docs/advanced/sub-applications.md index 172b8d3c1..f123147b3 100644 --- a/docs/de/docs/advanced/sub-applications.md +++ b/docs/de/docs/advanced/sub-applications.md @@ -10,9 +10,7 @@ Wenn Sie zwei unabhängige FastAPI-Anwendungen mit deren eigenen unabhängigen O Erstellen Sie zunächst die Hauptanwendung **FastAPI** und deren *Pfadoperationen*: -```Python hl_lines="3 6-8" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[3,6:8] *} ### Unteranwendung @@ -20,9 +18,7 @@ Erstellen Sie dann Ihre Unteranwendung und deren *Pfadoperationen*. Diese Unteranwendung ist nur eine weitere Standard-FastAPI-Anwendung, aber diese wird „gemountet“: -```Python hl_lines="11 14-16" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11,14:16] *} ### Die Unteranwendung mounten @@ -30,9 +26,7 @@ Mounten Sie in Ihrer Top-Level-Anwendung `app` die Unteranwendung `subapi`. In diesem Fall wird sie im Pfad `/subapi` gemountet: -```Python hl_lines="11 19" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11,19] *} ### Es in der automatischen API-Dokumentation betrachten diff --git a/docs/de/docs/advanced/templates.md b/docs/de/docs/advanced/templates.md index 658a2592e..136ce6027 100644 --- a/docs/de/docs/advanced/templates.md +++ b/docs/de/docs/advanced/templates.md @@ -27,9 +27,7 @@ $ pip install jinja2 * Deklarieren Sie einen `Request`-Parameter in der *Pfadoperation*, welcher ein Template zurückgibt. * Verwenden Sie die von Ihnen erstellten `templates`, um eine `TemplateResponse` zu rendern und zurückzugeben, übergeben Sie den Namen des Templates, das Requestobjekt und ein „Kontext“-Dictionary mit Schlüssel-Wert-Paaren, die innerhalb des Jinja2-Templates verwendet werden sollen. -```Python hl_lines="4 11 15-18" -{!../../docs_src/templates/tutorial001.py!} -``` +{* ../../docs_src/templates/tutorial001.py hl[4,11,15:18] *} /// note | Hinweis diff --git a/docs/de/docs/advanced/testing-dependencies.md b/docs/de/docs/advanced/testing-dependencies.md index 3b4604da3..8299d6dd7 100644 --- a/docs/de/docs/advanced/testing-dependencies.md +++ b/docs/de/docs/advanced/testing-dependencies.md @@ -28,57 +28,7 @@ Um eine Abhängigkeit für das Testen zu überschreiben, geben Sie als Schlüsse Und dann ruft **FastAPI** diese Überschreibung anstelle der ursprünglichen Abhängigkeit auf. -//// tab | Python 3.10+ - -```Python hl_lines="26-27 30" -{!> ../../docs_src/dependency_testing/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="28-29 32" -{!> ../../docs_src/dependency_testing/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="29-30 33" -{!> ../../docs_src/dependency_testing/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="24-25 28" -{!> ../../docs_src/dependency_testing/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="28-29 32" -{!> ../../docs_src/dependency_testing/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependency_testing/tutorial001_an_py310.py hl[26:27,30] *} /// tip | Tipp diff --git a/docs/de/docs/advanced/testing-events.md b/docs/de/docs/advanced/testing-events.md index 3e63791c6..05d6bcb2b 100644 --- a/docs/de/docs/advanced/testing-events.md +++ b/docs/de/docs/advanced/testing-events.md @@ -2,6 +2,4 @@ Wenn Sie in Ihren Tests Ihre Event-Handler (`startup` und `shutdown`) ausführen wollen, können Sie den `TestClient` mit einer `with`-Anweisung verwenden: -```Python hl_lines="9-12 20-24" -{!../../docs_src/app_testing/tutorial003.py!} -``` +{* ../../docs_src/app_testing/tutorial003.py hl[9:12,20:24] *} diff --git a/docs/de/docs/advanced/testing-websockets.md b/docs/de/docs/advanced/testing-websockets.md index 5122e1f33..5932e6d6a 100644 --- a/docs/de/docs/advanced/testing-websockets.md +++ b/docs/de/docs/advanced/testing-websockets.md @@ -4,9 +4,7 @@ Sie können den schon bekannten `TestClient` zum Testen von WebSockets verwenden Dazu verwenden Sie den `TestClient` in einer `with`-Anweisung, eine Verbindung zum WebSocket herstellend: -```Python hl_lines="27-31" -{!../../docs_src/app_testing/tutorial002.py!} -``` +{* ../../docs_src/app_testing/tutorial002.py hl[27:31] *} /// note | Hinweis diff --git a/docs/de/docs/advanced/websockets.md b/docs/de/docs/advanced/websockets.md index 5bc5f6902..020c20bc0 100644 --- a/docs/de/docs/advanced/websockets.md +++ b/docs/de/docs/advanced/websockets.md @@ -38,17 +38,13 @@ In der Produktion hätten Sie eine der oben genannten Optionen. Aber es ist die einfachste Möglichkeit, sich auf die Serverseite von WebSockets zu konzentrieren und ein funktionierendes Beispiel zu haben: -```Python hl_lines="2 6-38 41-43" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[2,6:38,41:43] *} ## Einen `websocket` erstellen Erstellen Sie in Ihrer **FastAPI**-Anwendung einen `websocket`: -```Python hl_lines="1 46-47" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[1,46:47] *} /// note | Technische Details @@ -62,9 +58,7 @@ Sie können auch `from starlette.websockets import WebSocket` verwenden. In Ihrer WebSocket-Route können Sie Nachrichten `await`en und Nachrichten senden. -```Python hl_lines="48-52" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[48:52] *} Sie können Binär-, Text- und JSON-Daten empfangen und senden. @@ -115,57 +109,7 @@ In WebSocket-Endpunkten können Sie Folgendes aus `fastapi` importieren und verw Diese funktionieren auf die gleiche Weise wie für andere FastAPI-Endpunkte/*Pfadoperationen*: -//// tab | Python 3.10+ - -```Python hl_lines="68-69 82" -{!> ../../docs_src/websockets/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="68-69 82" -{!> ../../docs_src/websockets/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="69-70 83" -{!> ../../docs_src/websockets/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="66-67 79" -{!> ../../docs_src/websockets/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="68-69 81" -{!> ../../docs_src/websockets/tutorial002.py!} -``` - -//// +{* ../../docs_src/websockets/tutorial002_an_py310.py hl[68:69,82] *} /// info @@ -210,21 +154,7 @@ Damit können Sie den WebSocket verbinden und dann Nachrichten senden und empfan Wenn eine WebSocket-Verbindung geschlossen wird, löst `await websocket.receive_text()` eine `WebSocketDisconnect`-Exception aus, die Sie dann wie in folgendem Beispiel abfangen und behandeln können. -//// tab | Python 3.9+ - -```Python hl_lines="79-81" -{!> ../../docs_src/websockets/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="81-83" -{!> ../../docs_src/websockets/tutorial003.py!} -``` - -//// +{* ../../docs_src/websockets/tutorial003_py39.py hl[79:81] *} Zum Ausprobieren: diff --git a/docs/de/docs/advanced/wsgi.md b/docs/de/docs/advanced/wsgi.md index 50abc84d1..c0998a621 100644 --- a/docs/de/docs/advanced/wsgi.md +++ b/docs/de/docs/advanced/wsgi.md @@ -12,9 +12,7 @@ Wrappen Sie dann die WSGI-Anwendung (z. B. Flask) mit der Middleware. Und dann mounten Sie das auf einem Pfad. -```Python hl_lines="2-3 23" -{!../../docs_src/wsgi/tutorial001.py!} -``` +{* ../../docs_src/wsgi/tutorial001.py hl[2:3,23] *} ## Es ansehen diff --git a/docs/de/docs/how-to/custom-docs-ui-assets.md b/docs/de/docs/how-to/custom-docs-ui-assets.md index a292be69b..ab8cd9f6b 100644 --- a/docs/de/docs/how-to/custom-docs-ui-assets.md +++ b/docs/de/docs/how-to/custom-docs-ui-assets.md @@ -18,9 +18,7 @@ Der erste Schritt besteht darin, die automatischen Dokumentationen zu deaktivier Um diese zu deaktivieren, setzen Sie deren URLs beim Erstellen Ihrer `FastAPI`-App auf `None`: -```Python hl_lines="8" -{!../../docs_src/custom_docs_ui/tutorial001.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[8] *} ### Die benutzerdefinierten Dokumentationen hinzufügen @@ -36,9 +34,7 @@ Sie können die internen Funktionen von FastAPI wiederverwenden, um die HTML-Sei Und genau so für ReDoc ... -```Python hl_lines="2-6 11-19 22-24 27-33" -{!../../docs_src/custom_docs_ui/tutorial001.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[2:6,11:19,22:24,27:33] *} /// tip | Tipp @@ -54,9 +50,7 @@ Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „U Um nun testen zu können, ob alles funktioniert, erstellen Sie eine *Pfadoperation*: -```Python hl_lines="36-38" -{!../../docs_src/custom_docs_ui/tutorial001.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[36:38] *} ### Es ausprobieren @@ -124,9 +118,7 @@ Danach könnte Ihre Dateistruktur wie folgt aussehen: * Importieren Sie `StaticFiles`. * „Mounten“ Sie eine `StaticFiles()`-Instanz in einem bestimmten Pfad. -```Python hl_lines="7 11" -{!../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[7,11] *} ### Die statischen Dateien testen @@ -158,9 +150,7 @@ Wie bei der Verwendung eines benutzerdefinierten CDN besteht der erste Schritt d Um diese zu deaktivieren, setzen Sie deren URLs beim Erstellen Ihrer `FastAPI`-App auf `None`: -```Python hl_lines="9" -{!../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[9] *} ### Die benutzerdefinierten Dokumentationen, mit statischen Dateien, hinzufügen @@ -176,9 +166,7 @@ Auch hier können Sie die internen Funktionen von FastAPI wiederverwenden, um di Und genau so für ReDoc ... -```Python hl_lines="2-6 14-22 25-27 30-36" -{!../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[2:6,14:22,25:27,30:36] *} /// tip | Tipp @@ -194,9 +182,7 @@ Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „U Um nun testen zu können, ob alles funktioniert, erstellen Sie eine *Pfadoperation*: -```Python hl_lines="39-41" -{!../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[39:41] *} ### Benutzeroberfläche, mit statischen Dateien, testen diff --git a/docs/de/docs/how-to/custom-request-and-route.md b/docs/de/docs/how-to/custom-request-and-route.md index ef71d96dc..3e6f709b6 100644 --- a/docs/de/docs/how-to/custom-request-and-route.md +++ b/docs/de/docs/how-to/custom-request-and-route.md @@ -42,9 +42,7 @@ Wenn der Header kein `gzip` enthält, wird nicht versucht, den Body zu dekomprim Auf diese Weise kann dieselbe Routenklasse gzip-komprimierte oder unkomprimierte Requests verarbeiten. -```Python hl_lines="8-15" -{!../../docs_src/custom_request_and_route/tutorial001.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial001.py hl[8:15] *} ### Eine benutzerdefinierte `GzipRoute`-Klasse erstellen @@ -56,9 +54,7 @@ Diese Methode gibt eine Funktion zurück. Und diese Funktion empfängt einen Req Hier verwenden wir sie, um aus dem ursprünglichen Request einen `GzipRequest` zu erstellen. -```Python hl_lines="18-26" -{!../../docs_src/custom_request_and_route/tutorial001.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial001.py hl[18:26] *} /// note | Technische Details @@ -96,26 +92,18 @@ Wir können denselben Ansatz auch verwenden, um in einem Exceptionhandler auf de Alles, was wir tun müssen, ist, den Request innerhalb eines `try`/`except`-Blocks zu handhaben: -```Python hl_lines="13 15" -{!../../docs_src/custom_request_and_route/tutorial002.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial002.py hl[13,15] *} Wenn eine Exception auftritt, befindet sich die `Request`-Instanz weiterhin im Gültigkeitsbereich, sodass wir den Requestbody lesen und bei der Fehlerbehandlung verwenden können: -```Python hl_lines="16-18" -{!../../docs_src/custom_request_and_route/tutorial002.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial002.py hl[16:18] *} ## Benutzerdefinierte `APIRoute`-Klasse in einem Router Sie können auch den Parameter `route_class` eines `APIRouter` festlegen: -```Python hl_lines="26" -{!../../docs_src/custom_request_and_route/tutorial003.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial003.py hl[26] *} In diesem Beispiel verwenden die *Pfadoperationen* unter dem `router` die benutzerdefinierte `TimedRoute`-Klasse und haben in der Response einen zusätzlichen `X-Response-Time`-Header mit der Zeit, die zum Generieren der Response benötigt wurde: -```Python hl_lines="13-20" -{!../../docs_src/custom_request_and_route/tutorial003.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial003.py hl[13:20] *} diff --git a/docs/de/docs/how-to/extending-openapi.md b/docs/de/docs/how-to/extending-openapi.md index c895fb860..3b1459364 100644 --- a/docs/de/docs/how-to/extending-openapi.md +++ b/docs/de/docs/how-to/extending-openapi.md @@ -43,25 +43,19 @@ Fügen wir beispielsweise Strawberry-Dokumentation. diff --git a/docs/de/docs/how-to/separate-openapi-schemas.md b/docs/de/docs/how-to/separate-openapi-schemas.md index 974341dd2..4f6911e79 100644 --- a/docs/de/docs/how-to/separate-openapi-schemas.md +++ b/docs/de/docs/how-to/separate-openapi-schemas.md @@ -10,123 +10,13 @@ Sehen wir uns an, wie das funktioniert und wie Sie es bei Bedarf ändern können Nehmen wir an, Sie haben ein Pydantic-Modell mit Defaultwerten wie dieses: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!} - -# Code unterhalb weggelassen 👇 -``` - -
-👀 Vollständige Dateivorschau - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} -``` - -
- -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!} - -# Code unterhalb weggelassen 👇 -``` - -
-👀 Vollständige Dateivorschau - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} -``` - -
- -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!} - -# Code unterhalb weggelassen 👇 -``` - -
-👀 Vollständige Dateivorschau - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} -``` - -
- -//// +{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:7] hl[7] *} ### Modell für Eingabe Wenn Sie dieses Modell wie hier als Eingabe verwenden: -//// tab | Python 3.10+ - -```Python hl_lines="14" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!} - -# Code unterhalb weggelassen 👇 -``` - -
-👀 Vollständige Dateivorschau - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} -``` - -
- -//// - -//// tab | Python 3.9+ - -```Python hl_lines="16" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!} - -# Code unterhalb weggelassen 👇 -``` - -
-👀 Vollständige Dateivorschau - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} -``` - -
- -//// - -//// tab | Python 3.8+ - -```Python hl_lines="16" -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!} - -# Code unterhalb weggelassen 👇 -``` - -
-👀 Vollständige Dateivorschau - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} -``` - -
- -//// +{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:15] hl[14] *} ... dann ist das Feld `description` **nicht erforderlich**. Weil es den Defaultwert `None` hat. @@ -142,29 +32,7 @@ Sie können überprüfen, dass das Feld `description` in der Dokumentation kein Wenn Sie jedoch dasselbe Modell als Ausgabe verwenden, wie hier: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="21" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="21" -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} -``` - -//// +{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py hl[19] *} ... dann, weil `description` einen Defaultwert hat, wird es, wenn Sie für dieses Feld **nichts zurückgeben**, immer noch diesen **Defaultwert** haben. @@ -223,29 +91,7 @@ Unterstützung für `separate_input_output_schemas` wurde in FastAPI `0.102.0` h /// -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/separate_openapi_schemas/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/separate_openapi_schemas/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12" -{!> ../../docs_src/separate_openapi_schemas/tutorial002.py!} -``` - -//// +{* ../../docs_src/separate_openapi_schemas/tutorial002_py310.py hl[10] *} ### Gleiches Schema für Eingabe- und Ausgabemodelle in der Dokumentation diff --git a/docs/de/docs/tutorial/background-tasks.md b/docs/de/docs/tutorial/background-tasks.md index fc699daf4..05779e12c 100644 --- a/docs/de/docs/tutorial/background-tasks.md +++ b/docs/de/docs/tutorial/background-tasks.md @@ -15,9 +15,7 @@ Hierzu zählen beispielsweise: Importieren Sie zunächst `BackgroundTasks` und definieren Sie einen Parameter in Ihrer *Pfadoperation-Funktion* mit der Typdeklaration `BackgroundTasks`: -```Python hl_lines="1 13" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *} **FastAPI** erstellt für Sie das Objekt vom Typ `BackgroundTasks` und übergibt es als diesen Parameter. @@ -33,17 +31,13 @@ In diesem Fall schreibt die Taskfunktion in eine Datei (den Versand einer E-Mail Und da der Schreibvorgang nicht `async` und `await` verwendet, definieren wir die Funktion mit normalem `def`: -```Python hl_lines="6-9" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *} ## Den Hintergrundtask hinzufügen Übergeben Sie innerhalb Ihrer *Pfadoperation-Funktion* Ihre Taskfunktion mit der Methode `.add_task()` an das *Hintergrundtasks*-Objekt: -```Python hl_lines="14" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[14] *} `.add_task()` erhält als Argumente: @@ -57,57 +51,7 @@ Die Verwendung von `BackgroundTasks` funktioniert auch mit dem ../../docs_src/background_tasks/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="13 15 22 25" -{!> ../../docs_src/background_tasks/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14 16 23 26" -{!> ../../docs_src/background_tasks/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="11 13 20 23" -{!> ../../docs_src/background_tasks/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="13 15 22 25" -{!> ../../docs_src/background_tasks/tutorial002.py!} -``` - -//// +{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13,15,22,25] *} In obigem Beispiel werden die Nachrichten, *nachdem* die Response gesendet wurde, in die Datei `log.txt` geschrieben. diff --git a/docs/de/docs/tutorial/body-fields.md b/docs/de/docs/tutorial/body-fields.md index df3d7f939..9fddfb1f0 100644 --- a/docs/de/docs/tutorial/body-fields.md +++ b/docs/de/docs/tutorial/body-fields.md @@ -6,57 +6,7 @@ So wie Sie zusätzliche Validation und Metadaten in Parametern der **Pfadoperati Importieren Sie es zuerst: -//// tab | Python 3.10+ - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="2" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *} /// warning | Achtung @@ -68,57 +18,7 @@ Beachten Sie, dass `Field` direkt von `pydantic` importiert wird, nicht von `fas Dann können Sie `Field` mit Modellattributen deklarieren: -//// tab | Python 3.10+ - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12-15" -{!> ../../docs_src/body_fields/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="9-12" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *} `Field` funktioniert genauso wie `Query`, `Path` und `Body`, es hat die gleichen Parameter, usw. diff --git a/docs/de/docs/tutorial/body-nested-models.md b/docs/de/docs/tutorial/body-nested-models.md index 478064a8b..6287490c6 100644 --- a/docs/de/docs/tutorial/body-nested-models.md +++ b/docs/de/docs/tutorial/body-nested-models.md @@ -6,21 +6,7 @@ Mit **FastAPI** können Sie (dank Pydantic) beliebig tief verschachtelte Modelle Sie können ein Attribut als Kindtyp definieren, zum Beispiel eine Python-`list`e. -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *} Das bewirkt, dass `tags` eine Liste ist, wenngleich es nichts über den Typ der Elemente der Liste aussagt. @@ -34,9 +20,7 @@ In Python 3.9 oder darüber können Sie einfach `list` verwenden, um diese Typan In Python-Versionen vor 3.9 (3.6 und darüber), müssen Sie zuerst `List` von Pythons Standardmodul `typing` importieren. -```Python hl_lines="1" -{!> ../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *} ### Eine `list`e mit einem Typ-Parameter deklarieren @@ -65,29 +49,7 @@ Verwenden Sie dieselbe Standardsyntax für Modellattribute mit inneren Typen. In unserem Beispiel können wir also bewirken, dass `tags` spezifisch eine „Liste von Strings“ ist: -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *} ## Set-Typen @@ -97,29 +59,7 @@ Python hat einen Datentyp speziell für Mengen eindeutiger Dinge: das ../../docs_src/body_nested_models/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 14" -{!> ../../docs_src/body_nested_models/tutorial003.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *} Jetzt, selbst wenn Sie einen Request mit duplizierten Daten erhalten, werden diese zu einem Set eindeutiger Dinge konvertiert. @@ -141,57 +81,13 @@ Alles das beliebig tief verschachtelt. Wir können zum Beispiel ein `Image`-Modell definieren. -//// tab | Python 3.10+ - -```Python hl_lines="7-9" -{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9-11" -{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-11" -{!> ../../docs_src/body_nested_models/tutorial004.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *} ### Das Kindmodell als Typ verwenden Und dann können wir es als Typ eines Attributes verwenden. -//// tab | Python 3.10+ - -```Python hl_lines="18" -{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial004.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *} Das würde bedeuten, dass **FastAPI** einen Body erwartet wie: @@ -224,29 +120,7 @@ Um alle Optionen kennenzulernen, die Sie haben, schauen Sie sich ../../docs_src/body_nested_models/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4 10" -{!> ../../docs_src/body_nested_models/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 10" -{!> ../../docs_src/body_nested_models/tutorial005.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *} Es wird getestet, ob der String eine gültige URL ist, und als solche wird er in JSON Schema / OpenAPI dokumentiert. @@ -254,29 +128,7 @@ Es wird getestet, ob der String eine gültige URL ist, und als solche wird er in Sie können Pydantic-Modelle auch als Typen innerhalb von `list`, `set`, usw. verwenden: -//// tab | Python 3.10+ - -```Python hl_lines="18" -{!> ../../docs_src/body_nested_models/tutorial006_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial006_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial006.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *} Das wird einen JSON-Body erwarten (konvertieren, validieren, dokumentieren), wie: @@ -314,29 +166,7 @@ Beachten Sie, dass der `images`-Schlüssel jetzt eine Liste von Bild-Objekten ha Sie können beliebig tief verschachtelte Modelle definieren: -//// tab | Python 3.10+ - -```Python hl_lines="7 12 18 21 25" -{!> ../../docs_src/body_nested_models/tutorial007_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9 14 20 23 27" -{!> ../../docs_src/body_nested_models/tutorial007_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 14 20 23 27" -{!> ../../docs_src/body_nested_models/tutorial007.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *} /// info @@ -360,21 +190,7 @@ images: list[Image] so wie in: -//// tab | Python 3.9+ - -```Python hl_lines="13" -{!> ../../docs_src/body_nested_models/tutorial008_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15" -{!> ../../docs_src/body_nested_models/tutorial008.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial008_py39.py hl[13] *} ## Editor-Unterstützung überall @@ -404,21 +220,7 @@ Das schauen wir uns mal an. Im folgenden Beispiel akzeptieren Sie irgendein `dict`, solange es `int`-Schlüssel und `float`-Werte hat. -//// tab | Python 3.9+ - -```Python hl_lines="7" -{!> ../../docs_src/body_nested_models/tutorial009_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/body_nested_models/tutorial009.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial009_py39.py hl[7] *} /// tip | Tipp diff --git a/docs/de/docs/tutorial/body-updates.md b/docs/de/docs/tutorial/body-updates.md index 01a534a23..574016c58 100644 --- a/docs/de/docs/tutorial/body-updates.md +++ b/docs/de/docs/tutorial/body-updates.md @@ -6,29 +6,7 @@ Um einen Artikel zu aktualisieren, können Sie die ../../docs_src/body_updates/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="30-35" -{!> ../../docs_src/body_updates/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="30-35" -{!> ../../docs_src/body_updates/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *} `PUT` wird verwendet, um Daten zu empfangen, die die existierenden Daten ersetzen sollen. @@ -84,29 +62,7 @@ Das wird ein `dict` erstellen, mit nur den Daten, die gesetzt wurden als das `it Sie können das verwenden, um ein `dict` zu erstellen, das nur die (im Request) gesendeten Daten enthält, ohne Defaultwerte: -//// tab | Python 3.10+ - -```Python hl_lines="32" -{!> ../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="34" -{!> ../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="34" -{!> ../../docs_src/body_updates/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *} ### Pydantics `update`-Parameter verwenden @@ -122,29 +78,7 @@ Die Beispiele hier verwenden `.copy()` für die Kompatibilität mit Pydantic v1, Wie in `stored_item_model.model_copy(update=update_data)`: -//// tab | Python 3.10+ - -```Python hl_lines="33" -{!> ../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="35" -{!> ../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="35" -{!> ../../docs_src/body_updates/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *} ### Rekapitulation zum teilweisen Ersetzen @@ -161,29 +95,7 @@ Zusammengefasst, um Teil-Ersetzungen vorzunehmen: * Speichern Sie die Daten in Ihrer Datenbank. * Geben Sie das aktualisierte Modell zurück. -//// tab | Python 3.10+ - -```Python hl_lines="28-35" -{!> ../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="30-37" -{!> ../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="30-37" -{!> ../../docs_src/body_updates/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *} /// tip | Tipp diff --git a/docs/de/docs/tutorial/body.md b/docs/de/docs/tutorial/body.md index 1038ebe91..e25323786 100644 --- a/docs/de/docs/tutorial/body.md +++ b/docs/de/docs/tutorial/body.md @@ -22,21 +22,7 @@ Da aber davon abgeraten wird, zeigt die interaktive Dokumentation mit Swagger-Be Zuerst müssen Sie `BaseModel` von `pydantic` importieren: -//// tab | Python 3.10+ - -```Python hl_lines="2" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// +{* ../../docs_src/body/tutorial001_py310.py hl[2] *} ## Erstellen Sie Ihr Datenmodell @@ -44,21 +30,7 @@ Dann deklarieren Sie Ihr Datenmodell als eine Klasse, die von `BaseModel` erbt. Verwenden Sie Standard-Python-Typen für die Klassenattribute: -//// tab | Python 3.10+ - -```Python hl_lines="5-9" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="7-11" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// +{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *} Wie auch bei Query-Parametern gilt, wenn ein Modellattribut einen Defaultwert hat, ist das Attribut nicht erforderlich. Ansonsten ist es erforderlich. Verwenden Sie `None`, um es als optional zu kennzeichnen. @@ -86,21 +58,7 @@ Da `description` und `tax` optional sind (mit `None` als Defaultwert), wäre fol Um es zu Ihrer *Pfadoperation* hinzuzufügen, deklarieren Sie es auf die gleiche Weise, wie Sie Pfad- und Query-Parameter deklariert haben: -//// tab | Python 3.10+ - -```Python hl_lines="16" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// +{* ../../docs_src/body/tutorial001_py310.py hl[16] *} ... und deklarieren Sie seinen Typ als das Modell, welches Sie erstellt haben, `Item`. @@ -167,21 +125,7 @@ Es verbessert die Editor-Unterstützung für Pydantic-Modelle, mit: Innerhalb der Funktion können Sie alle Attribute des Modells direkt verwenden: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/body/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="21" -{!> ../../docs_src/body/tutorial002.py!} -``` - -//// +{* ../../docs_src/body/tutorial002_py310.py hl[19] *} ## Requestbody- + Pfad-Parameter @@ -189,21 +133,7 @@ Sie können Pfad- und Requestbody-Parameter gleichzeitig deklarieren. **FastAPI** erkennt, dass Funktionsparameter, die mit Pfad-Parametern übereinstimmen, **vom Pfad genommen** werden sollen, und dass Funktionsparameter, welche Pydantic-Modelle sind, **vom Requestbody genommen** werden sollen. -//// tab | Python 3.10+ - -```Python hl_lines="15-16" -{!> ../../docs_src/body/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17-18" -{!> ../../docs_src/body/tutorial003.py!} -``` - -//// +{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *} ## Requestbody- + Pfad- + Query-Parameter @@ -211,21 +141,7 @@ Sie können auch zur gleichen Zeit **Body-**, **Pfad-** und **Query-Parameter** **FastAPI** wird jeden Parameter korrekt erkennen und die Daten vom richtigen Ort holen. -//// tab | Python 3.10+ - -```Python hl_lines="16" -{!> ../../docs_src/body/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/body/tutorial004.py!} -``` - -//// +{* ../../docs_src/body/tutorial004_py310.py hl[16] *} Die Funktionsparameter werden wie folgt erkannt: diff --git a/docs/de/docs/tutorial/cookie-params.md b/docs/de/docs/tutorial/cookie-params.md index ecb14ad03..711c8c8e9 100644 --- a/docs/de/docs/tutorial/cookie-params.md +++ b/docs/de/docs/tutorial/cookie-params.md @@ -6,57 +6,7 @@ So wie `Query`- und `Path`-Parameter können Sie auch ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *} ### Deklarieren der Abhängigkeit im „Dependant“ So wie auch `Body`, `Query`, usw., verwenden Sie `Depends` mit den Parametern Ihrer *Pfadoperation-Funktion*: -//// tab | Python 3.10+ - -```Python hl_lines="13 18" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="15 20" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="16 21" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="11 16" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="15 20" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *} Obwohl Sie `Depends` in den Parametern Ihrer Funktion genauso verwenden wie `Body`, `Query`, usw., funktioniert `Depends` etwas anders. @@ -275,29 +125,7 @@ commons: Annotated[dict, Depends(common_parameters)] Da wir jedoch `Annotated` verwenden, können wir diesen `Annotated`-Wert in einer Variablen speichern und an mehreren Stellen verwenden: -//// tab | Python 3.10+ - -```Python hl_lines="12 16 21" -{!> ../../docs_src/dependencies/tutorial001_02_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14 18 23" -{!> ../../docs_src/dependencies/tutorial001_02_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15 19 24" -{!> ../../docs_src/dependencies/tutorial001_02_an.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *} /// tip | Tipp diff --git a/docs/de/docs/tutorial/dependencies/sub-dependencies.md b/docs/de/docs/tutorial/dependencies/sub-dependencies.md index 6da7c64de..66bdc7043 100644 --- a/docs/de/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/de/docs/tutorial/dependencies/sub-dependencies.md @@ -10,57 +10,7 @@ Diese können so **tief** verschachtelt sein, wie nötig. Sie könnten eine erste Abhängigkeit („Dependable“) wie folgt erstellen: -//// tab | Python 3.10+ - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-10" -{!> ../../docs_src/dependencies/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10 nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="6-7" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8 nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *} Diese deklariert einen optionalen Abfrageparameter `q` vom Typ `str` und gibt ihn dann einfach zurück. @@ -70,57 +20,7 @@ Das ist recht einfach (nicht sehr nützlich), hilft uns aber dabei, uns auf die Dann können Sie eine weitere Abhängigkeitsfunktion (ein „Dependable“) erstellen, die gleichzeitig eine eigene Abhängigkeit deklariert (also auch ein „Dependant“ ist): -//// tab | Python 3.10+ - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14" -{!> ../../docs_src/dependencies/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10 nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8 nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *} Betrachten wir die deklarierten Parameter: @@ -133,57 +33,7 @@ Betrachten wir die deklarierten Parameter: Diese Abhängigkeit verwenden wir nun wie folgt: -//// tab | Python 3.10+ - -```Python hl_lines="23" -{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23" -{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/dependencies/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10 nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8 nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="22" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *} /// info diff --git a/docs/de/docs/tutorial/encoder.md b/docs/de/docs/tutorial/encoder.md index 428eee287..5678d7b8f 100644 --- a/docs/de/docs/tutorial/encoder.md +++ b/docs/de/docs/tutorial/encoder.md @@ -20,21 +20,7 @@ Sie können für diese Fälle `jsonable_encoder` verwenden. Es nimmt ein Objekt entgegen, wie etwa ein Pydantic-Modell, und gibt eine JSON-kompatible Version zurück: -//// tab | Python 3.10+ - -```Python hl_lines="4 21" -{!> ../../docs_src/encoder/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="5 22" -{!> ../../docs_src/encoder/tutorial001.py!} -``` - -//// +{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *} In diesem Beispiel wird das Pydantic-Modell in ein `dict`, und das `datetime`-Objekt in ein `str` konvertiert. diff --git a/docs/de/docs/tutorial/extra-data-types.md b/docs/de/docs/tutorial/extra-data-types.md index 7581b4f87..334f32f7b 100644 --- a/docs/de/docs/tutorial/extra-data-types.md +++ b/docs/de/docs/tutorial/extra-data-types.md @@ -55,108 +55,8 @@ Hier sind einige der zusätzlichen Datentypen, die Sie verwenden können: Hier ist ein Beispiel für eine *Pfadoperation* mit Parametern, die einige der oben genannten Typen verwenden. -//// tab | Python 3.10+ - -```Python hl_lines="1 3 12-16" -{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="1 3 12-16" -{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 3 13-17" -{!> ../../docs_src/extra_data_types/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="1 2 11-15" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="1 2 12-16" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *} Beachten Sie, dass die Parameter innerhalb der Funktion ihren natürlichen Datentyp haben und Sie beispielsweise normale Datumsmanipulationen durchführen können, wie zum Beispiel: -//// tab | Python 3.10+ - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="19-20" -{!> ../../docs_src/extra_data_types/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="17-18" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *} diff --git a/docs/de/docs/tutorial/extra-models.md b/docs/de/docs/tutorial/extra-models.md index 4c2c158db..6aad1c0f4 100644 --- a/docs/de/docs/tutorial/extra-models.md +++ b/docs/de/docs/tutorial/extra-models.md @@ -20,21 +20,7 @@ Falls Ihnen das nichts sagt, in den [Sicherheits-Kapiteln](security/simple-oauth Hier der generelle Weg, wie die Modelle mit ihren Passwort-Feldern aussehen könnten, und an welchen Orten sie verwendet werden würden. -//// tab | Python 3.10+ - -```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" -{!> ../../docs_src/extra_models/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" -{!> ../../docs_src/extra_models/tutorial001.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *} /// info @@ -176,21 +162,7 @@ Die ganze Datenkonvertierung, -validierung, -dokumentation, usw. wird immer noch Auf diese Weise beschreiben wir nur noch die Unterschiede zwischen den Modellen (mit Klartext-`password`, mit `hashed_password`, und ohne Passwort): -//// tab | Python 3.10+ - -```Python hl_lines="7 13-14 17-18 21-22" -{!> ../../docs_src/extra_models/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 15-16 19-20 23-24" -{!> ../../docs_src/extra_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *} ## `Union`, oder `anyOf` @@ -206,21 +178,7 @@ Listen Sie, wenn Sie eine ../../docs_src/extra_models/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 14-15 18-20 33" -{!> ../../docs_src/extra_models/tutorial003.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *} ### `Union` in Python 3.10 @@ -242,21 +200,7 @@ Genauso können Sie eine Response deklarieren, die eine Liste von Objekten ist. Verwenden Sie dafür Pythons Standard `typing.List` (oder nur `list` in Python 3.9 und darüber): -//// tab | Python 3.9+ - -```Python hl_lines="18" -{!> ../../docs_src/extra_models/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 20" -{!> ../../docs_src/extra_models/tutorial004.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial004_py39.py hl[18] *} ## Response mit beliebigem `dict` @@ -266,21 +210,7 @@ Das ist nützlich, wenn Sie die gültigen Feld-/Attribut-Namen von vorneherein n In diesem Fall können Sie `typing.Dict` verwenden (oder nur `dict` in Python 3.9 und darüber): -//// tab | Python 3.9+ - -```Python hl_lines="6" -{!> ../../docs_src/extra_models/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 8" -{!> ../../docs_src/extra_models/tutorial005.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial005_py39.py hl[6] *} ## Zusammenfassung diff --git a/docs/de/docs/tutorial/first-steps.md b/docs/de/docs/tutorial/first-steps.md index debefb156..3104c8d61 100644 --- a/docs/de/docs/tutorial/first-steps.md +++ b/docs/de/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ Die einfachste FastAPI-Datei könnte wie folgt aussehen: -```Python -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} Kopieren Sie dies in eine Datei `main.py`. @@ -133,9 +131,7 @@ Ebenfalls können Sie es verwenden, um automatisch Code für Clients zu generier ### Schritt 1: Importieren von `FastAPI` -```Python hl_lines="1" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI` ist eine Python-Klasse, die die gesamte Funktionalität für Ihre API bereitstellt. @@ -149,9 +145,7 @@ Sie können alle Literal `...` setzen: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial006b_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial006b.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py hl[9] *} /// info @@ -573,57 +337,7 @@ Sie können deklarieren, dass ein Parameter `None` akzeptiert, aber dennoch erfo Um das zu machen, deklarieren Sie, dass `None` ein gültiger Typ ist, aber verwenden Sie dennoch `...` als Default: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial006c_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial006c_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006c.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py hl[9] *} /// tip | Tipp @@ -643,71 +357,7 @@ Wenn Sie einen Query-Parameter explizit mit `Query` auszeichnen, können Sie ihn Um zum Beispiel einen Query-Parameter `q` zu deklarieren, der mehrere Male in der URL vorkommen kann, schreiben Sie: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial011_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial011_py310.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial011_an_py310.py hl[9] *} Dann, mit einer URL wie: @@ -742,49 +392,7 @@ Die interaktive API-Dokumentation wird entsprechend aktualisiert und erlaubt jet Und Sie können auch eine Default-`list`e von Werten definieren, wenn keine übergeben werden: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial012_an.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial012_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial012.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial012_an_py39.py hl[9] *} Wenn Sie auf: @@ -807,35 +415,7 @@ gehen, wird der Default für `q` verwendet: `["foo", "bar"]`, und als Response e Sie können auch `list` direkt verwenden, anstelle von `List[str]` (oder `list[str]` in Python 3.9+): -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial013_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial013.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial013_an_py39.py hl[9] *} /// note | Hinweis @@ -861,111 +441,11 @@ Einige könnten noch nicht alle zusätzlichen Informationen anzeigen, die Sie de Sie können einen Titel hinzufügen – `title`: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial007_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial007_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial007.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial007_an_py310.py hl[10] *} Und eine Beschreibung – `description`: -//// tab | Python 3.10+ - -```Python hl_lines="14" -{!> ../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15" -{!> ../../docs_src/query_params_str_validations/tutorial008_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial008_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="13" -{!> ../../docs_src/query_params_str_validations/tutorial008.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial008_an_py310.py hl[14] *} ## Alias-Parameter @@ -985,57 +465,7 @@ Aber Sie möchten dennoch exakt `item-query` verwenden. Dann können Sie einen `alias` deklarieren, und dieser Alias wird verwendet, um den Parameter-Wert zu finden: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial009_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial009_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial009.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial009_an_py310.py hl[9] *} ## Parameter als deprecated ausweisen @@ -1045,57 +475,7 @@ Sie müssen ihn eine Weile dort belassen, weil Clients ihn benutzen, aber Sie m In diesem Fall fügen Sie den Parameter `deprecated=True` zu `Query` hinzu. -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/query_params_str_validations/tutorial010_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="16" -{!> ../../docs_src/query_params_str_validations/tutorial010_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="18" -{!> ../../docs_src/query_params_str_validations/tutorial010.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial010_an_py310.py hl[19] *} Die Dokumentation wird das so anzeigen: @@ -1105,57 +485,7 @@ Die Dokumentation wird das so anzeigen: Um einen Query-Parameter vom generierten OpenAPI-Schema auszuschließen (und daher von automatischen Dokumentations-Systemen), setzen Sie den Parameter `include_in_schema` in `Query` auf `False`. -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial014_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial014_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial014.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *} ## Zusammenfassung diff --git a/docs/de/docs/tutorial/query-params.md b/docs/de/docs/tutorial/query-params.md index e67fef79d..0b0f473e2 100644 --- a/docs/de/docs/tutorial/query-params.md +++ b/docs/de/docs/tutorial/query-params.md @@ -2,9 +2,7 @@ Wenn Sie in ihrer Funktion Parameter deklarieren, die nicht Teil der Pfad-Parameter sind, dann werden diese automatisch als „Query“-Parameter interpretiert. -```Python hl_lines="9" -{!../../docs_src/query_params/tutorial001.py!} -``` +{* ../../docs_src/query_params/tutorial001.py hl[9] *} Query-Parameter (Deutsch: Abfrage-Parameter) sind die Schlüssel-Wert-Paare, die nach dem `?` in einer URL aufgelistet sind, getrennt durch `&`-Zeichen. @@ -63,21 +61,7 @@ gehen, werden die Parameter-Werte Ihrer Funktion sein: Auf die gleiche Weise können Sie optionale Query-Parameter deklarieren, indem Sie deren Defaultwert auf `None` setzen: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial002.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *} In diesem Fall wird der Funktionsparameter `q` optional, und standardmäßig `None` sein. @@ -91,21 +75,7 @@ Beachten Sie auch, dass **FastAPI** intelligent genug ist, um zu erkennen, dass Sie können auch `bool`-Typen deklarieren und sie werden konvertiert: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial003.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *} Wenn Sie nun zu: @@ -147,21 +117,7 @@ Und Sie müssen sie auch nicht in einer spezifischen Reihenfolge deklarieren. Parameter werden anhand ihres Namens erkannt: -//// tab | Python 3.10+ - -```Python hl_lines="6 8" -{!> ../../docs_src/query_params/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8 10" -{!> ../../docs_src/query_params/tutorial004.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *} ## Erforderliche Query-Parameter @@ -171,9 +127,7 @@ Wenn Sie keinen spezifischen Wert haben wollen, sondern der Parameter einfach op Aber wenn Sie wollen, dass ein Query-Parameter erforderlich ist, vergeben Sie einfach keinen Defaultwert: -```Python hl_lines="6-7" -{!../../docs_src/query_params/tutorial005.py!} -``` +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} Hier ist `needy` ein erforderlicher Query-Parameter vom Typ `str`. @@ -219,21 +173,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy Und natürlich können Sie einige Parameter als erforderlich, einige mit Defaultwert, und einige als vollständig optional definieren: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params/tutorial006_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params/tutorial006.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *} In diesem Fall gibt es drei Query-Parameter: diff --git a/docs/de/docs/tutorial/request-files.md b/docs/de/docs/tutorial/request-files.md index cbfb4271f..1f01b0d1e 100644 --- a/docs/de/docs/tutorial/request-files.md +++ b/docs/de/docs/tutorial/request-files.md @@ -16,69 +16,13 @@ Das, weil hochgeladene Dateien als „Formulardaten“ gesendet werden. Importieren Sie `File` und `UploadFile` von `fastapi`: -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/request_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1" -{!> ../../docs_src/request_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/request_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[3] *} ## `File`-Parameter definieren Erstellen Sie Datei-Parameter, so wie Sie es auch mit `Body` und `Form` machen würden: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/request_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/request_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/request_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[9] *} /// info @@ -106,35 +50,7 @@ Aber es gibt viele Fälle, in denen Sie davon profitieren, `UploadFile` zu verwe Definieren Sie einen Datei-Parameter mit dem Typ `UploadFile`: -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/request_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="13" -{!> ../../docs_src/request_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="12" -{!> ../../docs_src/request_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[14] *} `UploadFile` zu verwenden, hat mehrere Vorzüge gegenüber `bytes`: @@ -217,91 +133,13 @@ Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls. Sie können eine Datei optional machen, indem Sie Standard-Typannotationen verwenden und den Defaultwert auf `None` setzen: -//// tab | Python 3.10+ - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10 18" -{!> ../../docs_src/request_files/tutorial001_02_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7 15" -{!> ../../docs_src/request_files/tutorial001_02_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *} ## `UploadFile` mit zusätzlichen Metadaten Sie können auch `File()` zusammen mit `UploadFile` verwenden, um zum Beispiel zusätzliche Metadaten zu setzen: -//// tab | Python 3.9+ - -```Python hl_lines="9 15" -{!> ../../docs_src/request_files/tutorial001_03_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8 14" -{!> ../../docs_src/request_files/tutorial001_03_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7 13" -{!> ../../docs_src/request_files/tutorial001_03.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *} ## Mehrere Datei-Uploads @@ -311,49 +149,7 @@ Diese werden demselben Formularfeld zugeordnet, welches mit den Formulardaten ge Um das zu machen, deklarieren Sie eine Liste von `bytes` oder `UploadFile`s: -//// tab | Python 3.9+ - -```Python hl_lines="10 15" -{!> ../../docs_src/request_files/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11 16" -{!> ../../docs_src/request_files/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="8 13" -{!> ../../docs_src/request_files/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="10 15" -{!> ../../docs_src/request_files/tutorial002.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *} Sie erhalten, wie deklariert, eine `list`e von `bytes` oder `UploadFile`s. @@ -369,49 +165,7 @@ Sie können auch `from starlette.responses import HTMLResponse` verwenden. Und so wie zuvor können Sie `File()` verwenden, um zusätzliche Parameter zu setzen, sogar für `UploadFile`: -//// tab | Python 3.9+ - -```Python hl_lines="11 18-20" -{!> ../../docs_src/request_files/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12 19-21" -{!> ../../docs_src/request_files/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.9+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="9 16" -{!> ../../docs_src/request_files/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="11 18" -{!> ../../docs_src/request_files/tutorial003.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *} ## Zusammenfassung diff --git a/docs/de/docs/tutorial/request-forms-and-files.md b/docs/de/docs/tutorial/request-forms-and-files.md index bdd1e0fac..3c5e11adf 100644 --- a/docs/de/docs/tutorial/request-forms-and-files.md +++ b/docs/de/docs/tutorial/request-forms-and-files.md @@ -12,69 +12,13 @@ Z. B. `pip install python-multipart`. ## `File` und `Form` importieren -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1" -{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/request_forms_and_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[3] *} ## `File` und `Form`-Parameter definieren Erstellen Sie Datei- und Formularparameter, so wie Sie es auch mit `Body` und `Query` machen würden: -//// tab | Python 3.9+ - -```Python hl_lines="10-12" -{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-11" -{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/request_forms_and_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[10:12] *} Die Datei- und Formularfelder werden als Formulardaten hochgeladen, und Sie erhalten diese Dateien und Formularfelder. diff --git a/docs/de/docs/tutorial/request-forms.md b/docs/de/docs/tutorial/request-forms.md index 2b6aeb41c..2f88caaba 100644 --- a/docs/de/docs/tutorial/request-forms.md +++ b/docs/de/docs/tutorial/request-forms.md @@ -14,69 +14,13 @@ Z. B. `pip install python-multipart`. Importieren Sie `Form` von `fastapi`: -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1" -{!> ../../docs_src/request_forms/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/request_forms/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[3] *} ## `Form`-Parameter definieren Erstellen Sie Formular-Parameter, so wie Sie es auch mit `Body` und `Query` machen würden: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/request_forms/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/request_forms/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[9] *} Zum Beispiel stellt eine der Möglichkeiten, die OAuth2 Spezifikation zu verwenden (genannt „password flow“), die Bedingung, einen `username` und ein `password` als Formularfelder zu senden. diff --git a/docs/de/docs/tutorial/response-model.md b/docs/de/docs/tutorial/response-model.md index aa27e0726..faf9be516 100644 --- a/docs/de/docs/tutorial/response-model.md +++ b/docs/de/docs/tutorial/response-model.md @@ -4,29 +4,7 @@ Sie können den Typ der ../../docs_src/response_model/tutorial001_01_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="18 23" -{!> ../../docs_src/response_model/tutorial001_01_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18 23" -{!> ../../docs_src/response_model/tutorial001_01.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *} FastAPI wird diesen Rückgabetyp verwenden, um: @@ -59,29 +37,7 @@ Sie können `response_model` in jeder möglichen *Pfadoperation* verwenden: * `@app.delete()` * usw. -//// tab | Python 3.10+ - -```Python hl_lines="17 22 24-27" -{!> ../../docs_src/response_model/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="17 22 24-27" -{!> ../../docs_src/response_model/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17 22 24-27" -{!> ../../docs_src/response_model/tutorial001.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial001_py310.py hl[17,22,24:27] *} /// note | Hinweis @@ -113,21 +69,7 @@ Sie können auch `response_model=None` verwenden, um das Erstellen eines Respons Im Folgenden deklarieren wir ein `UserIn`-Modell; es enthält ein Klartext-Passwort: -//// tab | Python 3.10+ - -```Python hl_lines="7 9" -{!> ../../docs_src/response_model/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 11" -{!> ../../docs_src/response_model/tutorial002.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial002_py310.py hl[7,9] *} /// info @@ -140,21 +82,7 @@ oder `pip install pydantic[email]`. Wir verwenden dieses Modell, um sowohl unsere Eingabe- als auch Ausgabedaten zu deklarieren: -//// tab | Python 3.10+ - -```Python hl_lines="16" -{!> ../../docs_src/response_model/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/response_model/tutorial002.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial002_py310.py hl[16] *} Immer wenn jetzt ein Browser einen Benutzer mit Passwort erzeugt, gibt die API dasselbe Passwort in der Response zurück. @@ -172,57 +100,15 @@ Speichern Sie niemals das Klartext-Passwort eines Benutzers, oder versenden Sie Wir können stattdessen ein Eingabemodell mit dem Klartext-Passwort, und ein Ausgabemodell ohne das Passwort erstellen: -//// tab | Python 3.10+ - -```Python hl_lines="9 11 16" -{!> ../../docs_src/response_model/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 11 16" -{!> ../../docs_src/response_model/tutorial003.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_py310.py hl[9,11,16] *} Obwohl unsere *Pfadoperation-Funktion* hier denselben `user` von der Eingabe zurückgibt, der das Passwort enthält: -//// tab | Python 3.10+ - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial003.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_py310.py hl[24] *} ... haben wir deklariert, dass `response_model` das Modell `UserOut` ist, welches das Passwort nicht enthält: -//// tab | Python 3.10+ - -```Python hl_lines="22" -{!> ../../docs_src/response_model/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="22" -{!> ../../docs_src/response_model/tutorial003.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_py310.py hl[22] *} Darum wird **FastAPI** sich darum kümmern, dass alle Daten, die nicht im Ausgabemodell deklariert sind, herausgefiltert werden (mittels Pydantic). @@ -246,21 +132,7 @@ Aber in den meisten Fällen, wenn wir so etwas machen, wollen wir nur, dass das Und in solchen Fällen können wir Klassen und Vererbung verwenden, um Vorteil aus den Typannotationen in der Funktion zu ziehen, was vom Editor und von Tools besser unterstützt wird, während wir gleichzeitig FastAPIs **Datenfilterung** behalten. -//// tab | Python 3.10+ - -```Python hl_lines="7-10 13-14 18" -{!> ../../docs_src/response_model/tutorial003_01_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-13 15-16 20" -{!> ../../docs_src/response_model/tutorial003_01.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_01_py310.py hl[7:10,13:14,18] *} Damit erhalten wir Tool-Unterstützung, vom Editor und mypy, da dieser Code hinsichtlich der Typen korrekt ist, aber wir erhalten auch die Datenfilterung von FastAPI. @@ -302,9 +174,7 @@ Es kann Fälle geben, bei denen Sie etwas zurückgeben, das kein gültiges Pydan Der häufigste Anwendungsfall ist, wenn Sie [eine Response direkt zurückgeben, wie es später im Handbuch für fortgeschrittene Benutzer erläutert wird](../advanced/response-directly.md){.internal-link target=_blank}. -```Python hl_lines="8 10-11" -{!> ../../docs_src/response_model/tutorial003_02.py!} -``` +{* ../../docs_src/response_model/tutorial003_02.py hl[8,10:11] *} Dieser einfache Anwendungsfall wird automatisch von FastAPI gehandhabt, weil die Annotation des Rückgabetyps die Klasse (oder eine Unterklasse von) `Response` ist. @@ -314,9 +184,7 @@ Und Tools werden auch glücklich sein, weil sowohl `RedirectResponse` als auch ` Sie können auch eine Unterklasse von `Response` in der Typannotation verwenden. -```Python hl_lines="8-9" -{!> ../../docs_src/response_model/tutorial003_03.py!} -``` +{* ../../docs_src/response_model/tutorial003_03.py hl[8:9] *} Das wird ebenfalls funktionieren, weil `RedirectResponse` eine Unterklasse von `Response` ist, und FastAPI sich um diesen einfachen Anwendungsfall automatisch kümmert. @@ -326,21 +194,7 @@ Aber wenn Sie ein beliebiges anderes Objekt zurückgeben, das kein gültiger Pyd Das gleiche wird passieren, wenn Sie eine Union mehrerer Typen haben, und einer oder mehrere sind nicht gültige Pydantic-Typen. Zum Beispiel funktioniert folgendes nicht 💥: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/response_model/tutorial003_04_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/response_model/tutorial003_04.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *} ... das scheitert, da die Typannotation kein Pydantic-Typ ist, und auch keine einzelne `Response`-Klasse, oder -Unterklasse, es ist eine Union (eines von beiden) von `Response` und `dict`. @@ -352,21 +206,7 @@ Aber Sie möchten dennoch den Rückgabetyp in der Funktion annotieren, um Unters In diesem Fall können Sie die Generierung des Responsemodells abschalten, indem Sie `response_model=None` setzen: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/response_model/tutorial003_05_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/response_model/tutorial003_05.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *} Das bewirkt, dass FastAPI die Generierung des Responsemodells unterlässt, und damit können Sie jede gewünschte Rückgabetyp-Annotation haben, ohne dass es Ihre FastAPI-Anwendung beeinflusst. 🤓 @@ -374,29 +214,7 @@ Das bewirkt, dass FastAPI die Generierung des Responsemodells unterlässt, und d Ihr Responsemodell könnte Defaultwerte haben, wie: -//// tab | Python 3.10+ - -```Python hl_lines="9 11-12" -{!> ../../docs_src/response_model/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11 13-14" -{!> ../../docs_src/response_model/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11 13-14" -{!> ../../docs_src/response_model/tutorial004.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *} * `description: Union[str, None] = None` (oder `str | None = None` in Python 3.10) hat einen Defaultwert `None`. * `tax: float = 10.5` hat einen Defaultwert `10.5`. @@ -410,29 +228,7 @@ Wenn Sie zum Beispiel Modelle mit vielen optionalen Attributen in einer NoSQL-Da Sie können den *Pfadoperation-Dekorator*-Parameter `response_model_exclude_unset=True` setzen: -//// tab | Python 3.10+ - -```Python hl_lines="22" -{!> ../../docs_src/response_model/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial004.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *} Die Defaultwerte werden dann nicht in der Response enthalten sein, sondern nur die tatsächlich gesetzten Werte. @@ -529,21 +325,7 @@ Das trifft auch auf `response_model_by_alias` zu, welches ähnlich funktioniert. /// -//// tab | Python 3.10+ - -```Python hl_lines="29 35" -{!> ../../docs_src/response_model/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="31 37" -{!> ../../docs_src/response_model/tutorial005.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *} /// tip | Tipp @@ -557,21 +339,7 @@ Die Syntax `{"name", "description"}` erzeugt ein `set` mit diesen zwei Werten. Wenn Sie vergessen, ein `set` zu verwenden, und stattdessen eine `list`e oder ein `tuple` übergeben, wird FastAPI die dennoch in ein `set` konvertieren, und es wird korrekt funktionieren: -//// tab | Python 3.10+ - -```Python hl_lines="29 35" -{!> ../../docs_src/response_model/tutorial006_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="31 37" -{!> ../../docs_src/response_model/tutorial006.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *} ## Zusammenfassung diff --git a/docs/de/docs/tutorial/security/first-steps.md b/docs/de/docs/tutorial/security/first-steps.md index 935b8ecca..8fa33db7e 100644 --- a/docs/de/docs/tutorial/security/first-steps.md +++ b/docs/de/docs/tutorial/security/first-steps.md @@ -20,35 +20,7 @@ Lassen Sie uns zunächst einfach den Code verwenden und sehen, wie er funktionie Kopieren Sie das Beispiel in eine Datei `main.py`: -//// tab | Python 3.9+ - -```Python -{!> ../../docs_src/security/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python -{!> ../../docs_src/security/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python -{!> ../../docs_src/security/tutorial001.py!} -``` - -//// +{* ../../docs_src/security/tutorial001_an_py39.py *} ## Ausführen @@ -154,35 +126,7 @@ In dem Fall gibt Ihnen **FastAPI** ebenfalls die Tools, die Sie zum Erstellen br Wenn wir eine Instanz der Klasse `OAuth2PasswordBearer` erstellen, übergeben wir den Parameter `tokenUrl`. Dieser Parameter enthält die URL, die der Client (das Frontend, das im Browser des Benutzers ausgeführt wird) verwendet, wenn er den `username` und das `password` sendet, um einen Token zu erhalten. -//// tab | Python 3.9+ - -```Python hl_lines="8" -{!> ../../docs_src/security/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="7" -{!> ../../docs_src/security/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="6" -{!> ../../docs_src/security/tutorial001.py!} -``` - -//// +{* ../../docs_src/security/tutorial001_an_py39.py hl[8] *} /// tip | Tipp @@ -220,35 +164,7 @@ Es kann also mit `Depends` verwendet werden. Jetzt können Sie dieses `oauth2_scheme` als Abhängigkeit `Depends` übergeben. -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/security/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/security/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/security/tutorial001.py!} -``` - -//// +{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *} Diese Abhängigkeit stellt einen `str` bereit, der dem Parameter `token` der *Pfadoperation-Funktion* zugewiesen wird. diff --git a/docs/de/docs/tutorial/security/get-current-user.md b/docs/de/docs/tutorial/security/get-current-user.md index 5f28f231f..38f7ffcbf 100644 --- a/docs/de/docs/tutorial/security/get-current-user.md +++ b/docs/de/docs/tutorial/security/get-current-user.md @@ -2,35 +2,7 @@ Im vorherigen Kapitel hat das Sicherheitssystem (das auf dem Dependency Injection System basiert) der *Pfadoperation-Funktion* einen `token` vom Typ `str` überreicht: -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/security/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/security/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/security/tutorial001.py!} -``` - -//// +{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *} Aber das ist immer noch nicht so nützlich. @@ -42,57 +14,7 @@ Erstellen wir zunächst ein Pydantic-Benutzermodell. So wie wir Pydantic zum Deklarieren von Bodys verwenden, können wir es auch überall sonst verwenden: -//// tab | Python 3.10+ - -```Python hl_lines="5 12-16" -{!> ../../docs_src/security/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="5 12-16" -{!> ../../docs_src/security/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="5 13-17" -{!> ../../docs_src/security/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="3 10-14" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="5 12-16" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// +{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:16] *} ## Eine `get_current_user`-Abhängigkeit erstellen @@ -104,169 +26,19 @@ Erinnern Sie sich, dass Abhängigkeiten Unterabhängigkeiten haben können? So wie wir es zuvor in der *Pfadoperation* direkt gemacht haben, erhält unsere neue Abhängigkeit `get_current_user` von der Unterabhängigkeit `oauth2_scheme` einen `token` vom Typ `str`: -//// tab | Python 3.10+ - -```Python hl_lines="25" -{!> ../../docs_src/security/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="25" -{!> ../../docs_src/security/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="26" -{!> ../../docs_src/security/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="23" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="25" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// +{* ../../docs_src/security/tutorial002_an_py310.py hl[25] *} ## Den Benutzer holen `get_current_user` wird eine von uns erstellte (gefakte) Hilfsfunktion verwenden, welche einen Token vom Typ `str` entgegennimmt und unser Pydantic-`User`-Modell zurückgibt: -//// tab | Python 3.10+ - -```Python hl_lines="19-22 26-27" -{!> ../../docs_src/security/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19-22 26-27" -{!> ../../docs_src/security/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20-23 27-28" -{!> ../../docs_src/security/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="17-20 24-25" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="19-22 26-27" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// +{* ../../docs_src/security/tutorial002_an_py310.py hl[19:22,26:27] *} ## Den aktuellen Benutzer einfügen Und jetzt können wir wiederum `Depends` mit unserem `get_current_user` in der *Pfadoperation* verwenden: -//// tab | Python 3.10+ - -```Python hl_lines="31" -{!> ../../docs_src/security/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="31" -{!> ../../docs_src/security/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="32" -{!> ../../docs_src/security/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="29" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="31" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// +{* ../../docs_src/security/tutorial002_an_py310.py hl[31] *} Beachten Sie, dass wir als Typ von `current_user` das Pydantic-Modell `User` deklarieren. @@ -320,57 +92,7 @@ Und alle (oder beliebige Teile davon) können Vorteil ziehen aus der Wiederverwe Und alle diese Tausenden von *Pfadoperationen* können nur drei Zeilen lang sein: -//// tab | Python 3.10+ - -```Python hl_lines="30-32" -{!> ../../docs_src/security/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="30-32" -{!> ../../docs_src/security/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="31-33" -{!> ../../docs_src/security/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="28-30" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="30-32" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// +{* ../../docs_src/security/tutorial002_an_py310.py hl[30:32] *} ## Zusammenfassung diff --git a/docs/de/docs/tutorial/security/oauth2-jwt.md b/docs/de/docs/tutorial/security/oauth2-jwt.md index 25c1e1c97..178a95d81 100644 --- a/docs/de/docs/tutorial/security/oauth2-jwt.md +++ b/docs/de/docs/tutorial/security/oauth2-jwt.md @@ -118,57 +118,7 @@ Und eine weitere, um zu überprüfen, ob ein empfangenes Passwort mit dem gespei Und noch eine, um einen Benutzer zu authentifizieren und zurückzugeben. -//// tab | Python 3.10+ - -```Python hl_lines="7 48 55-56 59-60 69-75" -{!> ../../docs_src/security/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="7 48 55-56 59-60 69-75" -{!> ../../docs_src/security/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="7 49 56-57 60-61 70-76" -{!> ../../docs_src/security/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="6 47 54-55 58-59 68-74" -{!> ../../docs_src/security/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="7 48 55-56 59-60 69-75" -{!> ../../docs_src/security/tutorial004.py!} -``` - -//// +{* ../../docs_src/security/tutorial004_an_py310.py hl[7,48,55:56,59:60,69:75] *} /// note | Hinweis @@ -204,57 +154,7 @@ Definieren Sie ein Pydantic-Modell, das im Token-Endpunkt für die Response verw Erstellen Sie eine Hilfsfunktion, um einen neuen Zugriffstoken zu generieren. -//// tab | Python 3.10+ - -```Python hl_lines="6 12-14 28-30 78-86" -{!> ../../docs_src/security/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="6 12-14 28-30 78-86" -{!> ../../docs_src/security/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="6 13-15 29-31 79-87" -{!> ../../docs_src/security/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="5 11-13 27-29 77-85" -{!> ../../docs_src/security/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="6 12-14 28-30 78-86" -{!> ../../docs_src/security/tutorial004.py!} -``` - -//// +{* ../../docs_src/security/tutorial004_an_py310.py hl[6,12:14,28:30,78:86] *} ## Die Abhängigkeiten aktualisieren @@ -264,57 +164,7 @@ Dekodieren Sie den empfangenen Token, validieren Sie ihn und geben Sie den aktue Wenn der Token ungültig ist, geben Sie sofort einen HTTP-Fehler zurück. -//// tab | Python 3.10+ - -```Python hl_lines="89-106" -{!> ../../docs_src/security/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="89-106" -{!> ../../docs_src/security/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="90-107" -{!> ../../docs_src/security/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="88-105" -{!> ../../docs_src/security/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="89-106" -{!> ../../docs_src/security/tutorial004.py!} -``` - -//// +{* ../../docs_src/security/tutorial004_an_py310.py hl[89:106] *} ## Die *Pfadoperation* `/token` aktualisieren @@ -322,57 +172,7 @@ Erstellen Sie ein `timedelta` mit der Ablaufz Erstellen Sie einen echten JWT-Zugriffstoken und geben Sie ihn zurück. -//// tab | Python 3.10+ - -```Python hl_lines="117-132" -{!> ../../docs_src/security/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="117-132" -{!> ../../docs_src/security/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="118-133" -{!> ../../docs_src/security/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="114-129" -{!> ../../docs_src/security/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="115-130" -{!> ../../docs_src/security/tutorial004.py!} -``` - -//// +{* ../../docs_src/security/tutorial004_an_py310.py hl[117:132] *} ### Technische Details zum JWT-„Subjekt“ `sub` diff --git a/docs/de/docs/tutorial/security/simple-oauth2.md b/docs/de/docs/tutorial/security/simple-oauth2.md index 2fa1385b0..c0c93cd26 100644 --- a/docs/de/docs/tutorial/security/simple-oauth2.md +++ b/docs/de/docs/tutorial/security/simple-oauth2.md @@ -52,57 +52,7 @@ Lassen Sie uns nun die von **FastAPI** bereitgestellten Werkzeuge verwenden, um Importieren Sie zunächst `OAuth2PasswordRequestForm` und verwenden Sie es als Abhängigkeit mit `Depends` in der *Pfadoperation* für `/token`: -//// tab | Python 3.10+ - -```Python hl_lines="4 78" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4 78" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 79" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="2 74" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="4 76" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *} `OAuth2PasswordRequestForm` ist eine Klassenabhängigkeit, die einen Formularbody deklariert mit: @@ -150,57 +100,7 @@ Wenn es keinen solchen Benutzer gibt, geben wir die Fehlermeldung „Incorrect u Für den Fehler verwenden wir die Exception `HTTPException`: -//// tab | Python 3.10+ - -```Python hl_lines="3 79-81" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3 79-81" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3 80-82" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="1 75-77" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="3 77-79" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *} ### Das Passwort überprüfen @@ -226,57 +126,7 @@ Wenn Ihre Datenbank gestohlen wird, hat der Dieb nicht die Klartext-Passwörter Der Dieb kann also nicht versuchen, die gleichen Passwörter in einem anderen System zu verwenden (da viele Benutzer überall das gleiche Passwort verwenden, wäre dies gefährlich). -//// tab | Python 3.10+ - -```Python hl_lines="82-85" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="82-85" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="83-86" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="78-81" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="80-83" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *} #### Über `**user_dict` @@ -318,57 +168,7 @@ Aber konzentrieren wir uns zunächst auf die spezifischen Details, die wir benö /// -//// tab | Python 3.10+ - -```Python hl_lines="87" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="87" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="88" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="83" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="85" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *} /// tip | Tipp @@ -394,57 +194,7 @@ Beide Abhängigkeiten geben nur dann einen HTTP-Error zurück, wenn der Benutzer In unserem Endpunkt erhalten wir also nur dann einen Benutzer, wenn der Benutzer existiert, korrekt authentifiziert wurde und aktiv ist: -//// tab | Python 3.10+ - -```Python hl_lines="58-66 69-74 94" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="58-66 69-74 94" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="59-67 70-75 95" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="56-64 67-70 88" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ nicht annotiert - -/// tip | Tipp - -Bevorzugen Sie die `Annotated`-Version, falls möglich. - -/// - -```Python hl_lines="58-66 69-72 90" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *} /// info diff --git a/docs/de/docs/tutorial/static-files.md b/docs/de/docs/tutorial/static-files.md index aa44e3f4e..50e86d68e 100644 --- a/docs/de/docs/tutorial/static-files.md +++ b/docs/de/docs/tutorial/static-files.md @@ -7,9 +7,7 @@ Mit `StaticFiles` können Sie statische Dateien aus einem Verzeichnis automatisc * Importieren Sie `StaticFiles`. * „Mounten“ Sie eine `StaticFiles()`-Instanz in einem bestimmten Pfad. -```Python hl_lines="2 6" -{!../../docs_src/static_files/tutorial001.py!} -``` +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} /// note | Technische Details diff --git a/docs/de/docs/tutorial/testing.md b/docs/de/docs/tutorial/testing.md index 53459342b..e7c1dda95 100644 --- a/docs/de/docs/tutorial/testing.md +++ b/docs/de/docs/tutorial/testing.md @@ -26,9 +26,7 @@ Verwenden Sie das `TestClient`-Objekt auf die gleiche Weise wie `httpx`. Schreiben Sie einfache `assert`-Anweisungen mit den Standard-Python-Ausdrücken, die Sie überprüfen müssen (wiederum, Standard-`pytest`). -```Python hl_lines="2 12 15-18" -{!../../docs_src/app_testing/tutorial001.py!} -``` +{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *} /// tip | Tipp @@ -74,9 +72,8 @@ Nehmen wir an, Sie haben eine Dateistruktur wie in [Größere Anwendungen](bigge In der Datei `main.py` haben Sie Ihre **FastAPI**-Anwendung: -```Python -{!../../docs_src/app_testing/main.py!} -``` +{* ../../docs_src/app_testing/main.py *} + ### Testdatei @@ -92,9 +89,8 @@ Dann könnten Sie eine Datei `test_main.py` mit Ihren Tests haben. Sie könnte s Da sich diese Datei im selben Package befindet, können Sie relative Importe verwenden, um das Objekt `app` aus dem `main`-Modul (`main.py`) zu importieren: -```Python hl_lines="3" -{!../../docs_src/app_testing/test_main.py!} -``` +{* ../../docs_src/app_testing/test_main.py hl[3] *} + ... und haben den Code für die Tests wie zuvor. @@ -178,9 +174,8 @@ Bevorzugen Sie die `Annotated`-Version, falls möglich. Anschließend könnten Sie `test_main.py` mit den erweiterten Tests aktualisieren: -```Python -{!> ../../docs_src/app_testing/app_b/test_main.py!} -``` +{* ../../docs_src/app_testing/app_b/test_main.py *} + Wenn Sie möchten, dass der Client Informationen im Request übergibt und Sie nicht wissen, wie das geht, können Sie suchen (googeln), wie es mit `httpx` gemacht wird, oder sogar, wie es mit `requests` gemacht wird, da das Design von HTTPX auf dem Design von Requests basiert. diff --git a/docs/em/docs/advanced/additional-responses.md b/docs/em/docs/advanced/additional-responses.md index e4442135e..655fc7ab6 100644 --- a/docs/em/docs/advanced/additional-responses.md +++ b/docs/em/docs/advanced/additional-responses.md @@ -26,9 +26,7 @@ 🖼, 📣 ➕1️⃣ 📨 ⏮️ 👔 📟 `404` & Pydantic 🏷 `Message`, 👆 💪 ✍: -```Python hl_lines="18 22" -{!../../docs_src/additional_responses/tutorial001.py!} -``` +{* ../../docs_src/additional_responses/tutorial001.py hl[18,22] *} /// note @@ -177,9 +175,7 @@ 🖼, 👆 💪 🚮 🌖 📻 🆎 `image/png`, 📣 👈 👆 *➡ 🛠️* 💪 📨 🎻 🎚 (⏮️ 📻 🆎 `application/json`) ⚖️ 🇩🇴 🖼: -```Python hl_lines="19-24 28" -{!../../docs_src/additional_responses/tutorial002.py!} -``` +{* ../../docs_src/additional_responses/tutorial002.py hl[19:24,28] *} /// note @@ -207,9 +203,7 @@ & 📨 ⏮️ 👔 📟 `200` 👈 ⚙️ 👆 `response_model`, ✋️ 🔌 🛃 `example`: -```Python hl_lines="20-31" -{!../../docs_src/additional_responses/tutorial003.py!} -``` +{* ../../docs_src/additional_responses/tutorial003.py hl[20:31] *} ⚫️ 🔜 🌐 🌀 & 🔌 👆 🗄, & 🎦 🛠️ 🩺: @@ -243,9 +237,7 @@ new_dict = {**old_dict, "new key": "new value"} 🖼: -```Python hl_lines="13-17 26" -{!../../docs_src/additional_responses/tutorial004.py!} -``` +{* ../../docs_src/additional_responses/tutorial004.py hl[13:17,26] *} ## 🌖 ℹ 🔃 🗄 📨 diff --git a/docs/em/docs/advanced/additional-status-codes.md b/docs/em/docs/advanced/additional-status-codes.md index 5eb2ec90e..907c7e68e 100644 --- a/docs/em/docs/advanced/additional-status-codes.md +++ b/docs/em/docs/advanced/additional-status-codes.md @@ -14,9 +14,7 @@ 🏆 👈, 🗄 `JSONResponse`, & 📨 👆 🎚 📤 🔗, ⚒ `status_code` 👈 👆 💚: -```Python hl_lines="4 25" -{!../../docs_src/additional_status_codes/tutorial001.py!} -``` +{* ../../docs_src/additional_status_codes/tutorial001.py hl[4,25] *} /// warning diff --git a/docs/em/docs/advanced/advanced-dependencies.md b/docs/em/docs/advanced/advanced-dependencies.md index 721428ce4..3404c2687 100644 --- a/docs/em/docs/advanced/advanced-dependencies.md +++ b/docs/em/docs/advanced/advanced-dependencies.md @@ -18,9 +18,7 @@ 👈, 👥 📣 👩‍🔬 `__call__`: -```Python hl_lines="10" -{!../../docs_src/dependencies/tutorial011.py!} -``` +{* ../../docs_src/dependencies/tutorial011.py hl[10] *} 👉 💼, 👉 `__call__` ⚫️❔ **FastAPI** 🔜 ⚙️ ✅ 🌖 🔢 & 🎧-🔗, & 👉 ⚫️❔ 🔜 🤙 🚶‍♀️ 💲 🔢 👆 *➡ 🛠️ 🔢* ⏪. @@ -28,9 +26,7 @@ & 🔜, 👥 💪 ⚙️ `__init__` 📣 🔢 👐 👈 👥 💪 ⚙️ "🔗" 🔗: -```Python hl_lines="7" -{!../../docs_src/dependencies/tutorial011.py!} -``` +{* ../../docs_src/dependencies/tutorial011.py hl[7] *} 👉 💼, **FastAPI** 🏆 🚫 ⏱ 👆 ⚖️ 💅 🔃 `__init__`, 👥 🔜 ⚙️ ⚫️ 🔗 👆 📟. @@ -38,9 +34,7 @@ 👥 💪 ✍ 👐 👉 🎓 ⏮️: -```Python hl_lines="16" -{!../../docs_src/dependencies/tutorial011.py!} -``` +{* ../../docs_src/dependencies/tutorial011.py hl[16] *} & 👈 🌌 👥 💪 "🔗" 👆 🔗, 👈 🔜 ✔️ `"bar"` 🔘 ⚫️, 🔢 `checker.fixed_content`. @@ -56,9 +50,7 @@ checker(q="somequery") ...& 🚶‍♀️ ⚫️❔ 👈 📨 💲 🔗 👆 *➡ 🛠️ 🔢* 🔢 `fixed_content_included`: -```Python hl_lines="20" -{!../../docs_src/dependencies/tutorial011.py!} -``` +{* ../../docs_src/dependencies/tutorial011.py hl[20] *} /// tip diff --git a/docs/em/docs/advanced/async-tests.md b/docs/em/docs/advanced/async-tests.md index 4d468acd4..283d4aa09 100644 --- a/docs/em/docs/advanced/async-tests.md +++ b/docs/em/docs/advanced/async-tests.md @@ -32,15 +32,11 @@ 📁 `main.py` 🔜 ✔️: -```Python -{!../../docs_src/async_tests/main.py!} -``` +{* ../../docs_src/async_tests/main.py *} 📁 `test_main.py` 🔜 ✔️ 💯 `main.py`, ⚫️ 💪 👀 💖 👉 🔜: -```Python -{!../../docs_src/async_tests/test_main.py!} -``` +{* ../../docs_src/async_tests/test_main.py *} ## 🏃 ⚫️ @@ -60,9 +56,7 @@ $ pytest 📑 `@pytest.mark.anyio` 💬 ✳ 👈 👉 💯 🔢 🔜 🤙 🔁: -```Python hl_lines="7" -{!../../docs_src/async_tests/test_main.py!} -``` +{* ../../docs_src/async_tests/test_main.py hl[7] *} /// tip @@ -72,9 +66,7 @@ $ pytest ⤴️ 👥 💪 ✍ `AsyncClient` ⏮️ 📱, & 📨 🔁 📨 ⚫️, ⚙️ `await`. -```Python hl_lines="9-12" -{!../../docs_src/async_tests/test_main.py!} -``` +{* ../../docs_src/async_tests/test_main.py hl[9:12] *} 👉 🌓: diff --git a/docs/em/docs/advanced/behind-a-proxy.md b/docs/em/docs/advanced/behind-a-proxy.md index 36aa2e6b3..8b14152c9 100644 --- a/docs/em/docs/advanced/behind-a-proxy.md +++ b/docs/em/docs/advanced/behind-a-proxy.md @@ -94,9 +94,7 @@ $ uvicorn main:app --root-path /api/v1 📥 👥 ✅ ⚫️ 📧 🎦 🎯. -```Python hl_lines="8" -{!../../docs_src/behind_a_proxy/tutorial001.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial001.py hl[8] *} ⤴️, 🚥 👆 ▶️ Uvicorn ⏮️: @@ -123,9 +121,7 @@ $ uvicorn main:app --root-path /api/v1 👐, 🚥 👆 🚫 ✔️ 🌌 🚚 📋 ⏸ 🎛 💖 `--root-path` ⚖️ 🌓, 👆 💪 ⚒ `root_path` 🔢 🕐❔ 🏗 👆 FastAPI 📱: -```Python hl_lines="3" -{!../../docs_src/behind_a_proxy/tutorial002.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial002.py hl[3] *} 🚶‍♀️ `root_path` `FastAPI` 🔜 🌓 🚶‍♀️ `--root-path` 📋 ⏸ 🎛 Uvicorn ⚖️ Hypercorn. @@ -305,9 +301,7 @@ $ uvicorn main:app --root-path /api/v1 🖼: -```Python hl_lines="4-7" -{!../../docs_src/behind_a_proxy/tutorial003.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial003.py hl[4:7] *} 🔜 🏗 🗄 🔗 💖: @@ -354,9 +348,7 @@ $ uvicorn main:app --root-path /api/v1 🚥 👆 🚫 💚 **FastAPI** 🔌 🏧 💽 ⚙️ `root_path`, 👆 💪 ⚙️ 🔢 `root_path_in_servers=False`: -```Python hl_lines="9" -{!../../docs_src/behind_a_proxy/tutorial004.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial004.py hl[9] *} & ⤴️ ⚫️ 🏆 🚫 🔌 ⚫️ 🗄 🔗. diff --git a/docs/em/docs/advanced/custom-response.md b/docs/em/docs/advanced/custom-response.md index 301f99957..ab95b3e7b 100644 --- a/docs/em/docs/advanced/custom-response.md +++ b/docs/em/docs/advanced/custom-response.md @@ -30,9 +30,7 @@ ✋️ 🚥 👆 🎯 👈 🎚 👈 👆 🛬 **🎻 ⏮️ 🎻**, 👆 💪 🚶‍♀️ ⚫️ 🔗 📨 🎓 & ❎ ➕ 🌥 👈 FastAPI 🔜 ✔️ 🚶‍♀️ 👆 📨 🎚 🔘 `jsonable_encoder` ⏭ 🚶‍♀️ ⚫️ 📨 🎓. -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial001b.py!} -``` +{* ../../docs_src/custom_response/tutorial001b.py hl[2,7] *} /// info @@ -57,9 +55,7 @@ * 🗄 `HTMLResponse`. * 🚶‍♀️ `HTMLResponse` 🔢 `response_class` 👆 *➡ 🛠️ 👨‍🎨*. -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial002.py!} -``` +{* ../../docs_src/custom_response/tutorial002.py hl[2,7] *} /// info @@ -77,9 +73,7 @@ 🎏 🖼 ⚪️➡️ 🔛, 🛬 `HTMLResponse`, 💪 👀 💖: -```Python hl_lines="2 7 19" -{!../../docs_src/custom_response/tutorial003.py!} -``` +{* ../../docs_src/custom_response/tutorial003.py hl[2,7,19] *} /// warning @@ -103,9 +97,7 @@ 🖼, ⚫️ 💪 🕳 💖: -```Python hl_lines="7 21 23" -{!../../docs_src/custom_response/tutorial004.py!} -``` +{* ../../docs_src/custom_response/tutorial004.py hl[7,21,23] *} 👉 🖼, 🔢 `generate_html_response()` ⏪ 🏗 & 📨 `Response` ↩️ 🛬 🕸 `str`. @@ -144,9 +136,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 🎚, ⚓️ 🔛 = & 🔁 = ✍ 🆎. -```Python hl_lines="1 18" -{!../../docs_src/response_directly/tutorial002.py!} -``` +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} ### `HTMLResponse` @@ -156,9 +146,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 ✊ ✍ ⚖️ 🔢 & 📨 ✅ ✍ 📨. -```Python hl_lines="2 7 9" -{!../../docs_src/custom_response/tutorial005.py!} -``` +{* ../../docs_src/custom_response/tutorial005.py hl[2,7,9] *} ### `JSONResponse` @@ -180,9 +168,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 /// -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial001.py!} -``` +{* ../../docs_src/custom_response/tutorial001.py hl[2,7] *} /// tip @@ -196,18 +182,14 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 👆 💪 📨 `RedirectResponse` 🔗: -```Python hl_lines="2 9" -{!../../docs_src/custom_response/tutorial006.py!} -``` +{* ../../docs_src/custom_response/tutorial006.py hl[2,9] *} --- ⚖️ 👆 💪 ⚙️ ⚫️ `response_class` 🔢: -```Python hl_lines="2 7 9" -{!../../docs_src/custom_response/tutorial006b.py!} -``` +{* ../../docs_src/custom_response/tutorial006b.py hl[2,7,9] *} 🚥 👆 👈, ⤴️ 👆 💪 📨 📛 🔗 ⚪️➡️ 👆 *➡ 🛠️* 🔢. @@ -217,17 +199,13 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 👆 💪 ⚙️ `status_code` 🔢 🌀 ⏮️ `response_class` 🔢: -```Python hl_lines="2 7 9" -{!../../docs_src/custom_response/tutorial006c.py!} -``` +{* ../../docs_src/custom_response/tutorial006c.py hl[2,7,9] *} ### `StreamingResponse` ✊ 🔁 🚂 ⚖️ 😐 🚂/🎻 & 🎏 📨 💪. -```Python hl_lines="2 14" -{!../../docs_src/custom_response/tutorial007.py!} -``` +{* ../../docs_src/custom_response/tutorial007.py hl[2,14] *} #### ⚙️ `StreamingResponse` ⏮️ 📁-💖 🎚 @@ -268,15 +246,11 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 📁 📨 🔜 🔌 ☑ `Content-Length`, `Last-Modified` & `ETag` 🎚. -```Python hl_lines="2 10" -{!../../docs_src/custom_response/tutorial009.py!} -``` +{* ../../docs_src/custom_response/tutorial009.py hl[2,10] *} 👆 💪 ⚙️ `response_class` 🔢: -```Python hl_lines="2 8 10" -{!../../docs_src/custom_response/tutorial009b.py!} -``` +{* ../../docs_src/custom_response/tutorial009b.py hl[2,8,10] *} 👉 💼, 👆 💪 📨 📁 ➡ 🔗 ⚪️➡️ 👆 *➡ 🛠️* 🔢. @@ -290,9 +264,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 👆 💪 ✍ `CustomORJSONResponse`. 👑 👜 👆 ✔️ ✍ `Response.render(content)` 👩‍🔬 👈 📨 🎚 `bytes`: -```Python hl_lines="9-14 17" -{!../../docs_src/custom_response/tutorial009c.py!} -``` +{* ../../docs_src/custom_response/tutorial009c.py hl[9:14,17] *} 🔜 ↩️ 🛬: @@ -318,9 +290,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 🖼 🔛, **FastAPI** 🔜 ⚙️ `ORJSONResponse` 🔢, 🌐 *➡ 🛠️*, ↩️ `JSONResponse`. -```Python hl_lines="2 4" -{!../../docs_src/custom_response/tutorial010.py!} -``` +{* ../../docs_src/custom_response/tutorial010.py hl[2,4] *} /// tip diff --git a/docs/em/docs/advanced/dataclasses.md b/docs/em/docs/advanced/dataclasses.md index ab76e5083..4dd597262 100644 --- a/docs/em/docs/advanced/dataclasses.md +++ b/docs/em/docs/advanced/dataclasses.md @@ -4,9 +4,7 @@ FastAPI 🏗 🔛 🔝 **Pydantic**, & 👤 ✔️ 🌏 👆 ❔ ⚙️ Pyda ✋️ FastAPI 🐕‍🦺 ⚙️ `dataclasses` 🎏 🌌: -```Python hl_lines="1 7-12 19-20" -{!../../docs_src/dataclasses/tutorial001.py!} -``` +{* ../../docs_src/dataclasses/tutorial001.py hl[1,7:12,19:20] *} 👉 🐕‍🦺 👏 **Pydantic**, ⚫️ ✔️ 🔗 🐕‍🦺 `dataclasses`. @@ -34,9 +32,7 @@ FastAPI 🏗 🔛 🔝 **Pydantic**, & 👤 ✔️ 🌏 👆 ❔ ⚙️ Pyda 👆 💪 ⚙️ `dataclasses` `response_model` 🔢: -```Python hl_lines="1 7-13 19" -{!../../docs_src/dataclasses/tutorial002.py!} -``` +{* ../../docs_src/dataclasses/tutorial002.py hl[1,7:13,19] *} 🎻 🔜 🔁 🗜 Pydantic 🎻. diff --git a/docs/em/docs/advanced/events.md b/docs/em/docs/advanced/events.md index 2eae2b366..68adb6d65 100644 --- a/docs/em/docs/advanced/events.md +++ b/docs/em/docs/advanced/events.md @@ -30,9 +30,7 @@ 👥 ✍ 🔁 🔢 `lifespan()` ⏮️ `yield` 💖 👉: -```Python hl_lines="16 19" -{!../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[16,19] *} 📥 👥 ⚖ 😥 *🕴* 🛠️ 🚚 🏷 🚮 (❌) 🏷 🔢 📖 ⏮️ 🎰 🏫 🏷 ⏭ `yield`. 👉 📟 🔜 🛠️ **⏭** 🈸 **▶️ ✊ 📨**, ⏮️ *🕴*. @@ -50,9 +48,7 @@ 🥇 👜 👀, 👈 👥 ⚖ 🔁 🔢 ⏮️ `yield`. 👉 📶 🎏 🔗 ⏮️ `yield`. -```Python hl_lines="14-19" -{!../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[14:19] *} 🥇 🍕 🔢, ⏭ `yield`, 🔜 🛠️ **⏭** 🈸 ▶️. @@ -64,9 +60,7 @@ 👈 🗜 🔢 🔘 🕳 🤙 "**🔁 🔑 👨‍💼**". -```Python hl_lines="1 13" -{!../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[1,13] *} **🔑 👨‍💼** 🐍 🕳 👈 👆 💪 ⚙️ `with` 📄, 🖼, `open()` 💪 ⚙️ 🔑 👨‍💼: @@ -88,9 +82,7 @@ async with lifespan(app): `lifespan` 🔢 `FastAPI` 📱 ✊ **🔁 🔑 👨‍💼**, 👥 💪 🚶‍♀️ 👆 🆕 `lifespan` 🔁 🔑 👨‍💼 ⚫️. -```Python hl_lines="22" -{!../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[22] *} ## 🎛 🎉 (😢) @@ -112,9 +104,7 @@ async with lifespan(app): 🚮 🔢 👈 🔜 🏃 ⏭ 🈸 ▶️, 📣 ⚫️ ⏮️ 🎉 `"startup"`: -```Python hl_lines="8" -{!../../docs_src/events/tutorial001.py!} -``` +{* ../../docs_src/events/tutorial001.py hl[8] *} 👉 💼, `startup` 🎉 🐕‍🦺 🔢 🔜 🔢 🏬 "💽" ( `dict`) ⏮️ 💲. @@ -126,9 +116,7 @@ async with lifespan(app): 🚮 🔢 👈 🔜 🏃 🕐❔ 🈸 🤫 🔽, 📣 ⚫️ ⏮️ 🎉 `"shutdown"`: -```Python hl_lines="6" -{!../../docs_src/events/tutorial002.py!} -``` +{* ../../docs_src/events/tutorial002.py hl[6] *} 📥, `shutdown` 🎉 🐕‍🦺 🔢 🔜 ✍ ✍ ⏸ `"Application shutdown"` 📁 `log.txt`. diff --git a/docs/em/docs/advanced/generate-clients.md b/docs/em/docs/advanced/generate-clients.md index f09d75623..a680c9051 100644 --- a/docs/em/docs/advanced/generate-clients.md +++ b/docs/em/docs/advanced/generate-clients.md @@ -16,21 +16,7 @@ ➡️ ▶️ ⏮️ 🙅 FastAPI 🈸: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9-11 14-15 18 19 23" -{!> ../../docs_src/generate_clients/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="7-9 12-13 16-17 21" -{!> ../../docs_src/generate_clients/tutorial001_py39.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial001.py hl[9:11,14:15,18,19,23] *} 👀 👈 *➡ 🛠️* 🔬 🏷 👫 ⚙️ 📨 🚀 & 📨 🚀, ⚙️ 🏷 `Item` & `ResponseMessage`. @@ -136,21 +122,7 @@ frontend-app@1.0.0 generate-client /home/user/code/frontend-app 🖼, 👆 💪 ✔️ 📄 **🏬** & ➕1️⃣ 📄 **👩‍💻**, & 👫 💪 👽 🔖: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="23 28 36" -{!> ../../docs_src/generate_clients/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="21 26 34" -{!> ../../docs_src/generate_clients/tutorial002_py39.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial002.py hl[23,28,36] *} ### 🏗 📕 👩‍💻 ⏮️ 🔖 @@ -197,21 +169,7 @@ FastAPI ⚙️ **😍 🆔** 🔠 *➡ 🛠️*, ⚫️ ⚙️ **🛠️ 🆔** 👆 💪 ⤴️ 🚶‍♀️ 👈 🛃 🔢 **FastAPI** `generate_unique_id_function` 🔢: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="8-9 12" -{!> ../../docs_src/generate_clients/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="6-7 10" -{!> ../../docs_src/generate_clients/tutorial003_py39.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial003.py hl[8:9,12] *} ### 🏗 📕 👩‍💻 ⏮️ 🛃 🛠️ 🆔 @@ -233,9 +191,7 @@ FastAPI ⚙️ **😍 🆔** 🔠 *➡ 🛠️*, ⚫️ ⚙️ **🛠️ 🆔** 👥 💪 ⏬ 🗄 🎻 📁 `openapi.json` & ⤴️ 👥 💪 **❎ 👈 🔡 🔖** ⏮️ ✍ 💖 👉: -```Python -{!../../docs_src/generate_clients/tutorial004.py!} -``` +{* ../../docs_src/generate_clients/tutorial004.py *} ⏮️ 👈, 🛠️ 🆔 🔜 📁 ⚪️➡️ 👜 💖 `items-get_items` `get_items`, 👈 🌌 👩‍💻 🚂 💪 🏗 🙅 👩‍🔬 📛. diff --git a/docs/em/docs/advanced/middleware.md b/docs/em/docs/advanced/middleware.md index 914ce4a30..cb04fa3fb 100644 --- a/docs/em/docs/advanced/middleware.md +++ b/docs/em/docs/advanced/middleware.md @@ -57,17 +57,13 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 🙆 📨 📨 `http` ⚖️ `ws` 🔜 ❎ 🔐 ⚖ ↩️. -```Python hl_lines="2 6" -{!../../docs_src/advanced_middleware/tutorial001.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial001.py hl[2,6] *} ## `TrustedHostMiddleware` 🛠️ 👈 🌐 📨 📨 ✔️ ☑ ⚒ `Host` 🎚, ✔ 💂‍♂ 🛡 🇺🇸🔍 🦠 🎚 👊. -```Python hl_lines="2 6-8" -{!../../docs_src/advanced_middleware/tutorial002.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial002.py hl[2,6:8] *} 📄 ❌ 🐕‍🦺: @@ -81,9 +77,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 🛠️ 🔜 🍵 👯‍♂️ 🐩 & 🎥 📨. -```Python hl_lines="2 6" -{!../../docs_src/advanced_middleware/tutorial003.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial003.py hl[2,6] *} 📄 ❌ 🐕‍🦺: diff --git a/docs/em/docs/advanced/openapi-callbacks.md b/docs/em/docs/advanced/openapi-callbacks.md index f7b5e7ed9..b0a821668 100644 --- a/docs/em/docs/advanced/openapi-callbacks.md +++ b/docs/em/docs/advanced/openapi-callbacks.md @@ -31,9 +31,7 @@ 👉 🍕 📶 😐, 🌅 📟 🎲 ⏪ 😰 👆: -```Python hl_lines="9-13 36-53" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[9:13,36:53] *} /// tip @@ -92,9 +90,7 @@ httpx.post(callback_url, json={"description": "Invoice paid", "paid": True}) 🥇 ✍ 🆕 `APIRouter` 👈 🔜 🔌 1️⃣ ⚖️ 🌅 ⏲. -```Python hl_lines="3 25" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[3,25] *} ### ✍ ⏲ *➡ 🛠️* @@ -105,9 +101,7 @@ httpx.post(callback_url, json={"description": "Invoice paid", "paid": True}) * ⚫️ 🔜 🎲 ✔️ 📄 💪 ⚫️ 🔜 📨, ✅ `body: InvoiceEvent`. * & ⚫️ 💪 ✔️ 📄 📨 ⚫️ 🔜 📨, ✅ `response_model=InvoiceEventReceived`. -```Python hl_lines="16-18 21-22 28-32" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[16:18,21:22,28:32] *} 📤 2️⃣ 👑 🔺 ⚪️➡️ 😐 *➡ 🛠️*: @@ -175,9 +169,7 @@ https://www.external.org/events/invoices/2expen51ve 🔜 ⚙️ 🔢 `callbacks` *👆 🛠️ ➡ 🛠️ 👨‍🎨* 🚶‍♀️ 🔢 `.routes` (👈 🤙 `list` 🛣/*➡ 🛠️*) ⚪️➡️ 👈 ⏲ 📻: -```Python hl_lines="35" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[35] *} /// tip diff --git a/docs/em/docs/advanced/path-operation-advanced-configuration.md b/docs/em/docs/advanced/path-operation-advanced-configuration.md index 47e89a90f..9d9d5fa8d 100644 --- a/docs/em/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/em/docs/advanced/path-operation-advanced-configuration.md @@ -12,9 +12,7 @@ 👆 🔜 ✔️ ⚒ 💭 👈 ⚫️ 😍 🔠 🛠️. -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *} ### ⚙️ *➡ 🛠️ 🔢* 📛 { @@ -22,9 +20,7 @@ 👆 🔜 ⚫️ ⏮️ ❎ 🌐 👆 *➡ 🛠️*. -```Python hl_lines="2 12-21 24" -{!../../docs_src/path_operation_advanced_configuration/tutorial002.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2,12:21,24] *} /// tip @@ -44,9 +40,7 @@ 🚫 *➡ 🛠️* ⚪️➡️ 🏗 🗄 🔗 (& ➡️, ⚪️➡️ 🏧 🧾 ⚙️), ⚙️ 🔢 `include_in_schema` & ⚒ ⚫️ `False`: -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *} ## 🏧 📛 ⚪️➡️ #️⃣ @@ -56,9 +50,7 @@ ⚫️ 🏆 🚫 🎦 🆙 🧾, ✋️ 🎏 🧰 (✅ 🐉) 🔜 💪 ⚙️ 🎂. -```Python hl_lines="19-29" -{!../../docs_src/path_operation_advanced_configuration/tutorial004.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19:29] *} ## 🌖 📨 @@ -100,9 +92,7 @@ 👉 `openapi_extra` 💪 👍, 🖼, 📣 [🗄 ↔](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions): -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial005.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial005.py hl[6] *} 🚥 👆 📂 🏧 🛠️ 🩺, 👆 ↔ 🔜 🎦 🆙 🔝 🎯 *➡ 🛠️*. @@ -149,9 +139,7 @@ 👆 💪 👈 ⏮️ `openapi_extra`: -```Python hl_lines="20-37 39-40" -{!../../docs_src/path_operation_advanced_configuration/tutorial006.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial006.py hl[20:37,39:40] *} 👉 🖼, 👥 🚫 📣 🙆 Pydantic 🏷. 👐, 📨 💪 🚫 🎻 🎻, ⚫️ ✍ 🔗 `bytes`, & 🔢 `magic_data_reader()` 🔜 🈚 🎻 ⚫️ 🌌. @@ -165,9 +153,7 @@ 🖼, 👉 🈸 👥 🚫 ⚙️ FastAPI 🛠️ 🛠️ ⚗ 🎻 🔗 ⚪️➡️ Pydantic 🏷 🚫 🏧 🔬 🎻. 👐, 👥 📣 📨 🎚 🆎 📁, 🚫 🎻: -```Python hl_lines="17-22 24" -{!../../docs_src/path_operation_advanced_configuration/tutorial007.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[17:22,24] *} 👐, 👐 👥 🚫 ⚙️ 🔢 🛠️ 🛠️, 👥 ⚙️ Pydantic 🏷 ❎ 🏗 🎻 🔗 💽 👈 👥 💚 📨 📁. @@ -175,9 +161,7 @@ & ⤴️ 👆 📟, 👥 🎻 👈 📁 🎚 🔗, & ⤴️ 👥 🔄 ⚙️ 🎏 Pydantic 🏷 ✔ 📁 🎚: -```Python hl_lines="26-33" -{!../../docs_src/path_operation_advanced_configuration/tutorial007.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[26:33] *} /// tip diff --git a/docs/em/docs/advanced/response-change-status-code.md b/docs/em/docs/advanced/response-change-status-code.md index 7f2e8c157..4933484dd 100644 --- a/docs/em/docs/advanced/response-change-status-code.md +++ b/docs/em/docs/advanced/response-change-status-code.md @@ -20,9 +20,7 @@ & ⤴️ 👆 💪 ⚒ `status_code` 👈 *🔀* 📨 🎚. -```Python hl_lines="1 9 12" -{!../../docs_src/response_change_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *} & ⤴️ 👆 💪 📨 🙆 🎚 👆 💪, 👆 🛎 🔜 ( `dict`, 💽 🏷, ♒️). diff --git a/docs/em/docs/advanced/response-cookies.md b/docs/em/docs/advanced/response-cookies.md index 0fe47baec..d9fdbaa87 100644 --- a/docs/em/docs/advanced/response-cookies.md +++ b/docs/em/docs/advanced/response-cookies.md @@ -6,9 +6,7 @@ & ⤴️ 👆 💪 ⚒ 🍪 👈 *🔀* 📨 🎚. -```Python hl_lines="1 8-9" -{!../../docs_src/response_cookies/tutorial002.py!} -``` +{* ../../docs_src/response_cookies/tutorial002.py hl[1,8:9] *} & ⤴️ 👆 💪 📨 🙆 🎚 👆 💪, 👆 🛎 🔜 ( `dict`, 💽 🏷, ♒️). @@ -26,9 +24,7 @@ ⤴️ ⚒ 🍪 ⚫️, & ⤴️ 📨 ⚫️: -```Python hl_lines="10-12" -{!../../docs_src/response_cookies/tutorial001.py!} -``` +{* ../../docs_src/response_cookies/tutorial001.py hl[10:12] *} /// tip diff --git a/docs/em/docs/advanced/response-directly.md b/docs/em/docs/advanced/response-directly.md index 335c381c7..29819a205 100644 --- a/docs/em/docs/advanced/response-directly.md +++ b/docs/em/docs/advanced/response-directly.md @@ -34,9 +34,7 @@ 📚 💼, 👆 💪 ⚙️ `jsonable_encoder` 🗜 👆 📊 ⏭ 🚶‍♀️ ⚫️ 📨: -```Python hl_lines="6-7 21-22" -{!../../docs_src/response_directly/tutorial001.py!} -``` +{* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *} /// note | 📡 ℹ @@ -56,9 +54,7 @@ 👆 💪 🚮 👆 📂 🎚 🎻, 🚮 ⚫️ `Response`, & 📨 ⚫️: -```Python hl_lines="1 18" -{!../../docs_src/response_directly/tutorial002.py!} -``` +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} ## 🗒 diff --git a/docs/em/docs/advanced/response-headers.md b/docs/em/docs/advanced/response-headers.md index d577347fe..e9e1b62d2 100644 --- a/docs/em/docs/advanced/response-headers.md +++ b/docs/em/docs/advanced/response-headers.md @@ -6,9 +6,7 @@ & ⤴️ 👆 💪 ⚒ 🎚 👈 *🔀* 📨 🎚. -```Python hl_lines="1 7-8" -{!../../docs_src/response_headers/tutorial002.py!} -``` +{* ../../docs_src/response_headers/tutorial002.py hl[1,7:8] *} & ⤴️ 👆 💪 📨 🙆 🎚 👆 💪, 👆 🛎 🔜 ( `dict`, 💽 🏷, ♒️). @@ -24,9 +22,7 @@ ✍ 📨 🔬 [📨 📨 🔗](response-directly.md){.internal-link target=_blank} & 🚶‍♀️ 🎚 🌖 🔢: -```Python hl_lines="10-12" -{!../../docs_src/response_headers/tutorial001.py!} -``` +{* ../../docs_src/response_headers/tutorial001.py hl[10:12] *} /// note | 📡 ℹ diff --git a/docs/em/docs/advanced/security/http-basic-auth.md b/docs/em/docs/advanced/security/http-basic-auth.md index e6fe3e32c..73736f3b3 100644 --- a/docs/em/docs/advanced/security/http-basic-auth.md +++ b/docs/em/docs/advanced/security/http-basic-auth.md @@ -20,9 +20,7 @@ * ⚫️ 📨 🎚 🆎 `HTTPBasicCredentials`: * ⚫️ 🔌 `username` & `password` 📨. -```Python hl_lines="2 6 10" -{!../../docs_src/security/tutorial006.py!} -``` +{* ../../docs_src/security/tutorial006.py hl[2,6,10] *} 🕐❔ 👆 🔄 📂 📛 🥇 🕰 (⚖️ 🖊 "🛠️" 🔼 🩺) 🖥 🔜 💭 👆 👆 🆔 & 🔐: @@ -42,9 +40,7 @@ ⤴️ 👥 💪 ⚙️ `secrets.compare_digest()` 🚚 👈 `credentials.username` `"stanleyjobson"`, & 👈 `credentials.password` `"swordfish"`. -```Python hl_lines="1 11-21" -{!../../docs_src/security/tutorial007.py!} -``` +{* ../../docs_src/security/tutorial007.py hl[1,11:21] *} 👉 🔜 🎏: @@ -108,6 +104,4 @@ if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": ⏮️ 🔍 👈 🎓 ❌, 📨 `HTTPException` ⏮️ 👔 📟 4️⃣0️⃣1️⃣ (🎏 📨 🕐❔ 🙅‍♂ 🎓 🚚) & 🚮 🎚 `WWW-Authenticate` ⚒ 🖥 🎦 💳 📋 🔄: -```Python hl_lines="23-27" -{!../../docs_src/security/tutorial007.py!} -``` +{* ../../docs_src/security/tutorial007.py hl[23:27] *} diff --git a/docs/em/docs/advanced/security/oauth2-scopes.md b/docs/em/docs/advanced/security/oauth2-scopes.md index f4d1a3b82..b8c49bd11 100644 --- a/docs/em/docs/advanced/security/oauth2-scopes.md +++ b/docs/em/docs/advanced/security/oauth2-scopes.md @@ -62,9 +62,7 @@ Oauth2️⃣ 👫 🎻. 🥇, ➡️ 🔜 👀 🍕 👈 🔀 ⚪️➡️ 🖼 👑 **🔰 - 👩‍💻 🦮** [Oauth2️⃣ ⏮️ 🔐 (& 🔁), 📨 ⏮️ 🥙 🤝](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. 🔜 ⚙️ Oauth2️⃣ ↔: -```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[2,4,8,12,46,64,105,107:115,121:124,128:134,139,155] *} 🔜 ➡️ 📄 👈 🔀 🔁 🔁. @@ -74,9 +72,7 @@ Oauth2️⃣ 👫 🎻. `scopes` 🔢 📨 `dict` ⏮️ 🔠 ↔ 🔑 & 📛 💲: -```Python hl_lines="62-65" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[62:65] *} ↩️ 👥 🔜 📣 📚 ↔, 👫 🔜 🎦 🆙 🛠️ 🩺 🕐❔ 👆 🕹-/✔. @@ -102,9 +98,7 @@ Oauth2️⃣ 👫 🎻. /// -```Python hl_lines="155" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[155] *} ## 📣 ↔ *➡ 🛠️* & 🔗 @@ -130,9 +124,7 @@ Oauth2️⃣ 👫 🎻. /// -```Python hl_lines="4 139 168" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[4,139,168] *} /// info | 📡 ℹ @@ -158,9 +150,7 @@ Oauth2️⃣ 👫 🎻. 👉 `SecurityScopes` 🎓 🎏 `Request` (`Request` ⚙️ 🤚 📨 🎚 🔗). -```Python hl_lines="8 105" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[8,105] *} ## ⚙️ `scopes` @@ -174,9 +164,7 @@ Oauth2️⃣ 👫 🎻. 👉 ⚠, 👥 🔌 ↔ 🚚 (🚥 🙆) 🎻 👽 🚀 (⚙️ `scope_str`). 👥 🚮 👈 🎻 ⚗ ↔ `WWW-Authenticate` 🎚 (👉 🍕 🔌). -```Python hl_lines="105 107-115" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[105,107:115] *} ## ✔ `username` & 💽 💠 @@ -192,9 +180,7 @@ Oauth2️⃣ 👫 🎻. 👥 ✔ 👈 👥 ✔️ 👩‍💻 ⏮️ 👈 🆔, & 🚥 🚫, 👥 🤚 👈 🎏 ⚠ 👥 ✍ ⏭. -```Python hl_lines="46 116-127" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[46,116:127] *} ## ✔ `scopes` @@ -202,9 +188,7 @@ Oauth2️⃣ 👫 🎻. 👉, 👥 ⚙️ `security_scopes.scopes`, 👈 🔌 `list` ⏮️ 🌐 👫 ↔ `str`. -```Python hl_lines="128-134" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[128:134] *} ## 🔗 🌲 & ↔ diff --git a/docs/em/docs/advanced/settings.md b/docs/em/docs/advanced/settings.md index 59fb71d73..7fdd0d68a 100644 --- a/docs/em/docs/advanced/settings.md +++ b/docs/em/docs/advanced/settings.md @@ -148,9 +148,7 @@ Hello World from Python 👆 💪 ⚙️ 🌐 🎏 🔬 ⚒ & 🧰 👆 ⚙️ Pydantic 🏷, 💖 🎏 📊 🆎 & 🌖 🔬 ⏮️ `Field()`. -```Python hl_lines="2 5-8 11" -{!../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[2,5:8,11] *} /// tip @@ -166,9 +164,7 @@ Hello World from Python ⤴️ 👆 💪 ⚙️ 🆕 `settings` 🎚 👆 🈸: -```Python hl_lines="18-20" -{!../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[18:20] *} ### 🏃 💽 @@ -202,15 +198,11 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app 🖼, 👆 💪 ✔️ 📁 `config.py` ⏮️: -```Python -{!../../docs_src/settings/app01/config.py!} -``` +{* ../../docs_src/settings/app01/config.py *} & ⤴️ ⚙️ ⚫️ 📁 `main.py`: -```Python hl_lines="3 11-13" -{!../../docs_src/settings/app01/main.py!} -``` +{* ../../docs_src/settings/app01/main.py hl[3,11:13] *} /// tip @@ -228,9 +220,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app 👟 ⚪️➡️ ⏮️ 🖼, 👆 `config.py` 📁 💪 👀 💖: -```Python hl_lines="10" -{!../../docs_src/settings/app02/config.py!} -``` +{* ../../docs_src/settings/app02/config.py hl[10] *} 👀 👈 🔜 👥 🚫 ✍ 🔢 👐 `settings = Settings()`. @@ -238,9 +228,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app 🔜 👥 ✍ 🔗 👈 📨 🆕 `config.Settings()`. -```Python hl_lines="5 11-12" -{!../../docs_src/settings/app02/main.py!} -``` +{* ../../docs_src/settings/app02/main.py hl[5,11:12] *} /// tip @@ -252,17 +240,13 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app & ⤴️ 👥 💪 🚚 ⚫️ ⚪️➡️ *➡ 🛠️ 🔢* 🔗 & ⚙️ ⚫️ 🙆 👥 💪 ⚫️. -```Python hl_lines="16 18-20" -{!../../docs_src/settings/app02/main.py!} -``` +{* ../../docs_src/settings/app02/main.py hl[16,18:20] *} ### ⚒ & 🔬 ⤴️ ⚫️ 🔜 📶 ⏩ 🚚 🎏 ⚒ 🎚 ⏮️ 🔬 🏗 🔗 🔐 `get_settings`: -```Python hl_lines="9-10 13 21" -{!../../docs_src/settings/app02/test_main.py!} -``` +{* ../../docs_src/settings/app02/test_main.py hl[9:10,13,21] *} 🔗 🔐 👥 ⚒ 🆕 💲 `admin_email` 🕐❔ 🏗 🆕 `Settings` 🎚, & ⤴️ 👥 📨 👈 🆕 🎚. @@ -303,9 +287,7 @@ APP_NAME="ChimichangApp" & ⤴️ ℹ 👆 `config.py` ⏮️: -```Python hl_lines="9-10" -{!../../docs_src/settings/app03/config.py!} -``` +{* ../../docs_src/settings/app03/config.py hl[9:10] *} 📥 👥 ✍ 🎓 `Config` 🔘 👆 Pydantic `Settings` 🎓, & ⚒ `env_file` 📁 ⏮️ 🇨🇻 📁 👥 💚 ⚙️. @@ -338,9 +320,7 @@ def get_settings(): ✋️ 👥 ⚙️ `@lru_cache` 👨‍🎨 🔛 🔝, `Settings` 🎚 🔜 ✍ 🕴 🕐, 🥇 🕰 ⚫️ 🤙. 👶 👶 -```Python hl_lines="1 10" -{!../../docs_src/settings/app03/main.py!} -``` +{* ../../docs_src/settings/app03/main.py hl[1,10] *} ⤴️ 🙆 🏁 🤙 `get_settings()` 🔗 ⏭ 📨, ↩️ 🛠️ 🔗 📟 `get_settings()` & 🏗 🆕 `Settings` 🎚, ⚫️ 🔜 📨 🎏 🎚 👈 📨 🔛 🥇 🤙, 🔄 & 🔄. diff --git a/docs/em/docs/advanced/sub-applications.md b/docs/em/docs/advanced/sub-applications.md index e19f3f234..7a802cd77 100644 --- a/docs/em/docs/advanced/sub-applications.md +++ b/docs/em/docs/advanced/sub-applications.md @@ -10,9 +10,7 @@ 🥇, ✍ 👑, 🔝-🎚, **FastAPI** 🈸, & 🚮 *➡ 🛠️*: -```Python hl_lines="3 6-8" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[3,6:8] *} ### 🎧-🈸 @@ -20,9 +18,7 @@ 👉 🎧-🈸 ➕1️⃣ 🐩 FastAPI 🈸, ✋️ 👉 1️⃣ 👈 🔜 "🗻": -```Python hl_lines="11 14-16" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11,14:16] *} ### 🗻 🎧-🈸 @@ -30,9 +26,7 @@ 👉 💼, ⚫️ 🔜 📌 ➡ `/subapi`: -```Python hl_lines="11 19" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11,19] *} ### ✅ 🏧 🛠️ 🩺 diff --git a/docs/em/docs/advanced/templates.md b/docs/em/docs/advanced/templates.md index 53428151d..ad4d4fc71 100644 --- a/docs/em/docs/advanced/templates.md +++ b/docs/em/docs/advanced/templates.md @@ -27,9 +27,7 @@ $ pip install jinja2 * 📣 `Request` 🔢 *➡ 🛠️* 👈 🔜 📨 📄. * ⚙️ `templates` 👆 ✍ ✍ & 📨 `TemplateResponse`, 🚶‍♀️ `request` 1️⃣ 🔑-💲 👫 Jinja2️⃣ "🔑". -```Python hl_lines="4 11 15-18" -{!../../docs_src/templates/tutorial001.py!} -``` +{* ../../docs_src/templates/tutorial001.py hl[4,11,15:18] *} /// note diff --git a/docs/em/docs/advanced/testing-dependencies.md b/docs/em/docs/advanced/testing-dependencies.md index 027767df1..b2b4b480d 100644 --- a/docs/em/docs/advanced/testing-dependencies.md +++ b/docs/em/docs/advanced/testing-dependencies.md @@ -28,9 +28,7 @@ & ⤴️ **FastAPI** 🔜 🤙 👈 🔐 ↩️ ⏮️ 🔗. -```Python hl_lines="28-29 32" -{!../../docs_src/dependency_testing/tutorial001.py!} -``` +{* ../../docs_src/dependency_testing/tutorial001.py hl[28:29,32] *} /// tip diff --git a/docs/em/docs/advanced/testing-events.md b/docs/em/docs/advanced/testing-events.md index 071d49c21..f62e9e069 100644 --- a/docs/em/docs/advanced/testing-events.md +++ b/docs/em/docs/advanced/testing-events.md @@ -2,6 +2,4 @@ 🕐❔ 👆 💪 👆 🎉 🐕‍🦺 (`startup` & `shutdown`) 🏃 👆 💯, 👆 💪 ⚙️ `TestClient` ⏮️ `with` 📄: -```Python hl_lines="9-12 20-24" -{!../../docs_src/app_testing/tutorial003.py!} -``` +{* ../../docs_src/app_testing/tutorial003.py hl[9:12,20:24] *} diff --git a/docs/em/docs/advanced/testing-websockets.md b/docs/em/docs/advanced/testing-websockets.md index 62939c343..2a01de629 100644 --- a/docs/em/docs/advanced/testing-websockets.md +++ b/docs/em/docs/advanced/testing-websockets.md @@ -4,9 +4,7 @@ 👉, 👆 ⚙️ `TestClient` `with` 📄, 🔗*️⃣: -```Python hl_lines="27-31" -{!../../docs_src/app_testing/tutorial002.py!} -``` +{* ../../docs_src/app_testing/tutorial002.py hl[27:31] *} /// note diff --git a/docs/em/docs/advanced/using-request-directly.md b/docs/em/docs/advanced/using-request-directly.md index 3eb0067ad..9530d49bc 100644 --- a/docs/em/docs/advanced/using-request-directly.md +++ b/docs/em/docs/advanced/using-request-directly.md @@ -29,9 +29,7 @@ 👈 👆 💪 🔐 📨 🔗. -```Python hl_lines="1 7-8" -{!../../docs_src/using_request_directly/tutorial001.py!} -``` +{* ../../docs_src/using_request_directly/tutorial001.py hl[1,7:8] *} 📣 *➡ 🛠️ 🔢* 🔢 ⏮️ 🆎 ➖ `Request` **FastAPI** 🔜 💭 🚶‍♀️ `Request` 👈 🔢. diff --git a/docs/em/docs/advanced/websockets.md b/docs/em/docs/advanced/websockets.md index 4b260e20a..cc6e5c5f0 100644 --- a/docs/em/docs/advanced/websockets.md +++ b/docs/em/docs/advanced/websockets.md @@ -38,17 +38,13 @@ $ pip install websockets ✋️ ⚫️ 🙅 🌌 🎯 🔛 💽-🚄 *️⃣ & ✔️ 👷 🖼: -```Python hl_lines="2 6-38 41-43" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[2,6:38,41:43] *} ## ✍ `websocket` 👆 **FastAPI** 🈸, ✍ `websocket`: -```Python hl_lines="1 46-47" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[1,46:47] *} /// note | 📡 ℹ @@ -62,9 +58,7 @@ $ pip install websockets 👆 *️⃣ 🛣 👆 💪 `await` 📧 & 📨 📧. -```Python hl_lines="48-52" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[48:52] *} 👆 💪 📨 & 📨 💱, ✍, & 🎻 💽. @@ -115,9 +109,7 @@ $ uvicorn main:app --reload 👫 👷 🎏 🌌 🎏 FastAPI 🔗/*➡ 🛠️*: -```Python hl_lines="66-77 76-91" -{!../../docs_src/websockets/tutorial002.py!} -``` +{* ../../docs_src/websockets/tutorial002.py hl[66:77,76:91] *} /// info @@ -162,9 +154,7 @@ $ uvicorn main:app --reload 🕐❔ *️⃣ 🔗 📪, `await websocket.receive_text()` 🔜 🤚 `WebSocketDisconnect` ⚠, ❔ 👆 💪 ⤴️ ✊ & 🍵 💖 👉 🖼. -```Python hl_lines="81-83" -{!../../docs_src/websockets/tutorial003.py!} -``` +{* ../../docs_src/websockets/tutorial003.py hl[81:83] *} 🔄 ⚫️ 👅: diff --git a/docs/em/docs/advanced/wsgi.md b/docs/em/docs/advanced/wsgi.md index 8c0008c74..d923347d5 100644 --- a/docs/em/docs/advanced/wsgi.md +++ b/docs/em/docs/advanced/wsgi.md @@ -12,9 +12,7 @@ & ⤴️ 🗻 👈 🔽 ➡. -```Python hl_lines="2-3 22" -{!../../docs_src/wsgi/tutorial001.py!} -``` +{* ../../docs_src/wsgi/tutorial001.py hl[2:3,22] *} ## ✅ ⚫️ diff --git a/docs/em/docs/how-to/conditional-openapi.md b/docs/em/docs/how-to/conditional-openapi.md index a5932933a..e47ea0c35 100644 --- a/docs/em/docs/how-to/conditional-openapi.md +++ b/docs/em/docs/how-to/conditional-openapi.md @@ -29,9 +29,7 @@ 🖼: -```Python hl_lines="6 11" -{!../../docs_src/conditional_openapi/tutorial001.py!} -``` +{* ../../docs_src/conditional_openapi/tutorial001.py hl[6,11] *} 📥 👥 📣 ⚒ `openapi_url` ⏮️ 🎏 🔢 `"/openapi.json"`. diff --git a/docs/em/docs/how-to/custom-request-and-route.md b/docs/em/docs/how-to/custom-request-and-route.md index cd8811d4e..8974e7d95 100644 --- a/docs/em/docs/how-to/custom-request-and-route.md +++ b/docs/em/docs/how-to/custom-request-and-route.md @@ -42,9 +42,7 @@ 👈 🌌, 🎏 🛣 🎓 💪 🍵 🗜 🗜 ⚖️ 🗜 📨. -```Python hl_lines="8-15" -{!../../docs_src/custom_request_and_route/tutorial001.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial001.py hl[8:15] *} ### ✍ 🛃 `GzipRoute` 🎓 @@ -56,9 +54,7 @@ 📥 👥 ⚙️ ⚫️ ✍ `GzipRequest` ⚪️➡️ ⏮️ 📨. -```Python hl_lines="18-26" -{!../../docs_src/custom_request_and_route/tutorial001.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial001.py hl[18:26] *} /// note | 📡 ℹ @@ -96,26 +92,18 @@ 🌐 👥 💪 🍵 📨 🔘 `try`/`except` 🍫: -```Python hl_lines="13 15" -{!../../docs_src/custom_request_and_route/tutorial002.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial002.py hl[13,15] *} 🚥 ⚠ 📉, `Request` 👐 🔜 ↔, 👥 💪 ✍ & ⚒ ⚙️ 📨 💪 🕐❔ 🚚 ❌: -```Python hl_lines="16-18" -{!../../docs_src/custom_request_and_route/tutorial002.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial002.py hl[16:18] *} ## 🛃 `APIRoute` 🎓 📻 👆 💪 ⚒ `route_class` 🔢 `APIRouter`: -```Python hl_lines="26" -{!../../docs_src/custom_request_and_route/tutorial003.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial003.py hl[26] *} 👉 🖼, *➡ 🛠️* 🔽 `router` 🔜 ⚙️ 🛃 `TimedRoute` 🎓, & 🔜 ✔️ ➕ `X-Response-Time` 🎚 📨 ⏮️ 🕰 ⚫️ ✊ 🏗 📨: -```Python hl_lines="13-20" -{!../../docs_src/custom_request_and_route/tutorial003.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial003.py hl[13:20] *} diff --git a/docs/em/docs/how-to/extending-openapi.md b/docs/em/docs/how-to/extending-openapi.md index 698c78ec1..c3e6c7f66 100644 --- a/docs/em/docs/how-to/extending-openapi.md +++ b/docs/em/docs/how-to/extending-openapi.md @@ -46,25 +46,19 @@ 🥇, ✍ 🌐 👆 **FastAPI** 🈸 🛎: -```Python hl_lines="1 4 7-9" -{!../../docs_src/extending_openapi/tutorial001.py!} -``` +{* ../../docs_src/extending_openapi/tutorial001.py hl[1,4,7:9] *} ### 🏗 🗄 🔗 ⤴️, ⚙️ 🎏 🚙 🔢 🏗 🗄 🔗, 🔘 `custom_openapi()` 🔢: -```Python hl_lines="2 15-20" -{!../../docs_src/extending_openapi/tutorial001.py!} -``` +{* ../../docs_src/extending_openapi/tutorial001.py hl[2,15:20] *} ### 🔀 🗄 🔗 🔜 👆 💪 🚮 📄 ↔, ❎ 🛃 `x-logo` `info` "🎚" 🗄 🔗: -```Python hl_lines="21-23" -{!../../docs_src/extending_openapi/tutorial001.py!} -``` +{* ../../docs_src/extending_openapi/tutorial001.py hl[21:23] *} ### 💾 🗄 🔗 @@ -74,17 +68,13 @@ ⚫️ 🔜 🏗 🕴 🕐, & ⤴️ 🎏 💾 🔗 🔜 ⚙️ ⏭ 📨. -```Python hl_lines="13-14 24-25" -{!../../docs_src/extending_openapi/tutorial001.py!} -``` +{* ../../docs_src/extending_openapi/tutorial001.py hl[13:14,24:25] *} ### 🔐 👩‍🔬 🔜 👆 💪 ❎ `.openapi()` 👩‍🔬 ⏮️ 👆 🆕 🔢. -```Python hl_lines="28" -{!../../docs_src/extending_openapi/tutorial001.py!} -``` +{* ../../docs_src/extending_openapi/tutorial001.py hl[28] *} ### ✅ ⚫️ diff --git a/docs/em/docs/how-to/graphql.md b/docs/em/docs/how-to/graphql.md index 5d0d95567..083e9ebd2 100644 --- a/docs/em/docs/how-to/graphql.md +++ b/docs/em/docs/how-to/graphql.md @@ -35,9 +35,7 @@ 📥 🤪 🎮 ❔ 👆 💪 🛠️ 🍓 ⏮️ FastAPI: -```Python hl_lines="3 22 25-26" -{!../../docs_src/graphql/tutorial001.py!} -``` +{* ../../docs_src/graphql/tutorial001.py hl[3,22,25:26] *} 👆 💪 💡 🌅 🔃 🍓 🍓 🧾. diff --git a/docs/em/docs/tutorial/background-tasks.md b/docs/em/docs/tutorial/background-tasks.md index 6b14c6135..aed60c754 100644 --- a/docs/em/docs/tutorial/background-tasks.md +++ b/docs/em/docs/tutorial/background-tasks.md @@ -15,9 +15,7 @@ 🥇, 🗄 `BackgroundTasks` & 🔬 🔢 👆 *➡ 🛠️ 🔢* ⏮️ 🆎 📄 `BackgroundTasks`: -```Python hl_lines="1 13" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *} **FastAPI** 🔜 ✍ 🎚 🆎 `BackgroundTasks` 👆 & 🚶‍♀️ ⚫️ 👈 🔢. @@ -33,17 +31,13 @@ & ✍ 🛠️ 🚫 ⚙️ `async` & `await`, 👥 🔬 🔢 ⏮️ 😐 `def`: -```Python hl_lines="6-9" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *} ## 🚮 🖥 📋 🔘 👆 *➡ 🛠️ 🔢*, 🚶‍♀️ 👆 📋 🔢 *🖥 📋* 🎚 ⏮️ 👩‍🔬 `.add_task()`: -```Python hl_lines="14" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[14] *} `.add_task()` 📨 ❌: @@ -57,21 +51,7 @@ **FastAPI** 💭 ⚫️❔ 🔠 💼 & ❔ 🏤-⚙️ 🎏 🎚, 👈 🌐 🖥 📋 🔗 👯‍♂️ & 🏃 🖥 ⏮️: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="13 15 22 25" -{!> ../../docs_src/background_tasks/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="11 13 20 23" -{!> ../../docs_src/background_tasks/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/background_tasks/tutorial002.py hl[13,15,22,25] *} 👉 🖼, 📧 🔜 ✍ `log.txt` 📁 *⏮️* 📨 📨. diff --git a/docs/em/docs/tutorial/body-fields.md b/docs/em/docs/tutorial/body-fields.md index be39b4a9a..f202284b5 100644 --- a/docs/em/docs/tutorial/body-fields.md +++ b/docs/em/docs/tutorial/body-fields.md @@ -6,21 +6,7 @@ 🥇, 👆 ✔️ 🗄 ⚫️: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="2" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/body_fields/tutorial001.py hl[4] *} /// warning @@ -32,21 +18,7 @@ 👆 💪 ⤴️ ⚙️ `Field` ⏮️ 🏷 🔢: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="9-12" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/body_fields/tutorial001.py hl[11:14] *} `Field` 👷 🎏 🌌 `Query`, `Path` & `Body`, ⚫️ ✔️ 🌐 🎏 🔢, ♒️. diff --git a/docs/em/docs/tutorial/body-multiple-params.md b/docs/em/docs/tutorial/body-multiple-params.md index 2e20c83f9..3a2f2bd54 100644 --- a/docs/em/docs/tutorial/body-multiple-params.md +++ b/docs/em/docs/tutorial/body-multiple-params.md @@ -8,21 +8,7 @@ & 👆 💪 📣 💪 🔢 📦, ⚒ 🔢 `None`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="19-21" -{!> ../../docs_src/body_multiple_params/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="17-19" -{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial001.py hl[19:21] *} /// note @@ -45,21 +31,7 @@ ✋️ 👆 💪 📣 💗 💪 🔢, ✅ `item` & `user`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial002.py hl[22] *} 👉 💼, **FastAPI** 🔜 👀 👈 📤 🌅 🌘 1️⃣ 💪 🔢 🔢 (2️⃣ 🔢 👈 Pydantic 🏷). @@ -100,21 +72,7 @@ ✋️ 👆 💪 💡 **FastAPI** 😥 ⚫️ ➕1️⃣ 💪 🔑 ⚙️ `Body`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial003.py hl[22] *} 👉 💼, **FastAPI** 🔜 ⌛ 💪 💖: @@ -154,21 +112,7 @@ q: str | None = None 🖼: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="26" -{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial004.py hl[27] *} /// info @@ -190,21 +134,7 @@ item: Item = Body(embed=True) : -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="15" -{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial005.py hl[17] *} 👉 💼 **FastAPI** 🔜 ⌛ 💪 💖: diff --git a/docs/em/docs/tutorial/body-nested-models.md b/docs/em/docs/tutorial/body-nested-models.md index 3b56b7a07..6c8d5a610 100644 --- a/docs/em/docs/tutorial/body-nested-models.md +++ b/docs/em/docs/tutorial/body-nested-models.md @@ -6,21 +6,7 @@ 👆 💪 🔬 🔢 🏾. 🖼, 🐍 `list`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial001.py hl[14] *} 👉 🔜 ⚒ `tags` 📇, 👐 ⚫️ 🚫 📣 🆎 🔣 📇. @@ -34,9 +20,7 @@ ✋️ 🐍 ⏬ ⏭ 3️⃣.9️⃣ (3️⃣.6️⃣ & 🔛), 👆 🥇 💪 🗄 `List` ⚪️➡️ 🐩 🐍 `typing` 🕹: -```Python hl_lines="1" -{!> ../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *} ### 📣 `list` ⏮️ 🆎 🔢 @@ -65,29 +49,7 @@ my_list: List[str] , 👆 🖼, 👥 💪 ⚒ `tags` 🎯 "📇 🎻": -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial002_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial002.py hl[14] *} ## ⚒ 🆎 @@ -97,29 +59,7 @@ my_list: List[str] ⤴️ 👥 💪 📣 `tags` ⚒ 🎻: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="1 14" -{!> ../../docs_src/body_nested_models/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial003_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial003.py hl[1,14] *} ⏮️ 👉, 🚥 👆 📨 📨 ⏮️ ❎ 📊, ⚫️ 🔜 🗜 ⚒ 😍 🏬. @@ -141,57 +81,13 @@ my_list: List[str] 🖼, 👥 💪 🔬 `Image` 🏷: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9-11" -{!> ../../docs_src/body_nested_models/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="9-11" -{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7-9" -{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial004.py hl[9:11] *} ### ⚙️ 📊 🆎 & ⤴️ 👥 💪 ⚙️ ⚫️ 🆎 🔢: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="18" -{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial004.py hl[20] *} 👉 🔜 ⛓ 👈 **FastAPI** 🔜 ⌛ 💪 🎏: @@ -224,29 +120,7 @@ my_list: List[str] 🖼, `Image` 🏷 👥 ✔️ `url` 🏑, 👥 💪 📣 ⚫️ ↩️ `str`, Pydantic `HttpUrl`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="4 10" -{!> ../../docs_src/body_nested_models/tutorial005.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="4 10" -{!> ../../docs_src/body_nested_models/tutorial005_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="2 8" -{!> ../../docs_src/body_nested_models/tutorial005_py310.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial005.py hl[4,10] *} 🎻 🔜 ✅ ☑ 📛, & 📄 🎻 🔗 / 🗄 ✅. @@ -254,29 +128,7 @@ my_list: List[str] 👆 💪 ⚙️ Pydantic 🏷 🏾 `list`, `set`, ♒️: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial006.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial006_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="18" -{!> ../../docs_src/body_nested_models/tutorial006_py310.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial006.py hl[20] *} 👉 🔜 ⌛ (🗜, ✔, 📄, ♒️) 🎻 💪 💖: @@ -314,29 +166,7 @@ my_list: List[str] 👆 💪 🔬 🎲 🙇 🐦 🏷: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9 14 20 23 27" -{!> ../../docs_src/body_nested_models/tutorial007.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="9 14 20 23 27" -{!> ../../docs_src/body_nested_models/tutorial007_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7 12 18 21 25" -{!> ../../docs_src/body_nested_models/tutorial007_py310.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial007.py hl[9,14,20,23,27] *} /// info @@ -360,21 +190,7 @@ images: list[Image] : -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="15" -{!> ../../docs_src/body_nested_models/tutorial008.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="13" -{!> ../../docs_src/body_nested_models/tutorial008_py39.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial008.py hl[15] *} ## 👨‍🎨 🐕‍🦺 🌐 @@ -404,21 +220,7 @@ images: list[Image] 👉 💼, 👆 🔜 🚫 🙆 `dict` 📏 ⚫️ ✔️ `int` 🔑 ⏮️ `float` 💲: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/body_nested_models/tutorial009.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/body_nested_models/tutorial009_py39.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial009.py hl[9] *} /// tip diff --git a/docs/em/docs/tutorial/body.md b/docs/em/docs/tutorial/body.md index 3468fc512..09e1d7cca 100644 --- a/docs/em/docs/tutorial/body.md +++ b/docs/em/docs/tutorial/body.md @@ -22,21 +22,7 @@ 🥇, 👆 💪 🗄 `BaseModel` ⚪️➡️ `pydantic`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="4" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="2" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial001.py hl[4] *} ## ✍ 👆 💽 🏷 @@ -44,21 +30,7 @@ ⚙️ 🐩 🐍 🆎 🌐 🔢: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="7-11" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="5-9" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial001.py hl[7:11] *} 🎏 🕐❔ 📣 🔢 🔢, 🕐❔ 🏷 🔢 ✔️ 🔢 💲, ⚫️ 🚫 ✔. ⏪, ⚫️ ✔. ⚙️ `None` ⚒ ⚫️ 📦. @@ -86,21 +58,7 @@ 🚮 ⚫️ 👆 *➡ 🛠️*, 📣 ⚫️ 🎏 🌌 👆 📣 ➡ & 🔢 🔢: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="18" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="16" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial001.py hl[18] *} ...& 📣 🚮 🆎 🏷 👆 ✍, `Item`. @@ -167,21 +125,7 @@ 🔘 🔢, 👆 💪 🔐 🌐 🔢 🏷 🎚 🔗: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="21" -{!> ../../docs_src/body/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="19" -{!> ../../docs_src/body/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial002.py hl[21] *} ## 📨 💪 ➕ ➡ 🔢 @@ -189,21 +133,7 @@ **FastAPI** 🔜 🤔 👈 🔢 🔢 👈 🏏 ➡ 🔢 🔜 **✊ ⚪️➡️ ➡**, & 👈 🔢 🔢 👈 📣 Pydantic 🏷 🔜 **✊ ⚪️➡️ 📨 💪**. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="17-18" -{!> ../../docs_src/body/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="15-16" -{!> ../../docs_src/body/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial003.py hl[17:18] *} ## 📨 💪 ➕ ➡ ➕ 🔢 🔢 @@ -211,21 +141,7 @@ **FastAPI** 🔜 🤔 🔠 👫 & ✊ 📊 ⚪️➡️ ☑ 🥉. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="18" -{!> ../../docs_src/body/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="16" -{!> ../../docs_src/body/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial004.py hl[18] *} 🔢 🔢 🔜 🤔 ⏩: diff --git a/docs/em/docs/tutorial/cookie-params.md b/docs/em/docs/tutorial/cookie-params.md index 5126eab0a..4699fe2a5 100644 --- a/docs/em/docs/tutorial/cookie-params.md +++ b/docs/em/docs/tutorial/cookie-params.md @@ -6,21 +6,7 @@ 🥇 🗄 `Cookie`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="1" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001.py hl[3] *} ## 📣 `Cookie` 🔢 @@ -28,21 +14,7 @@ 🥇 💲 🔢 💲, 👆 💪 🚶‍♀️ 🌐 ➕ 🔬 ⚖️ ✍ 🔢: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001.py hl[9] *} /// note | 📡 ℹ diff --git a/docs/em/docs/tutorial/cors.md b/docs/em/docs/tutorial/cors.md index 801d66fdd..44ab4adc5 100644 --- a/docs/em/docs/tutorial/cors.md +++ b/docs/em/docs/tutorial/cors.md @@ -46,9 +46,7 @@ * 🎯 🇺🇸🔍 👩‍🔬 (`POST`, `PUT`) ⚖️ 🌐 👫 ⏮️ 🃏 `"*"`. * 🎯 🇺🇸🔍 🎚 ⚖️ 🌐 👫 ⏮️ 🃏 `"*"`. -```Python hl_lines="2 6-11 13-19" -{!../../docs_src/cors/tutorial001.py!} -``` +{* ../../docs_src/cors/tutorial001.py hl[2,6:11,13:19] *} 🔢 🔢 ⚙️ `CORSMiddleware` 🛠️ 🚫 🔢, 👆 🔜 💪 🎯 🛠️ 🎯 🇨🇳, 👩‍🔬, ⚖️ 🎚, ✔ 🖥 ✔ ⚙️ 👫 ✖️-🆔 🔑. diff --git a/docs/em/docs/tutorial/debugging.md b/docs/em/docs/tutorial/debugging.md index 9320370d6..97e61a763 100644 --- a/docs/em/docs/tutorial/debugging.md +++ b/docs/em/docs/tutorial/debugging.md @@ -6,9 +6,7 @@ 👆 FastAPI 🈸, 🗄 & 🏃 `uvicorn` 🔗: -```Python hl_lines="1 15" -{!../../docs_src/debugging/tutorial001.py!} -``` +{* ../../docs_src/debugging/tutorial001.py hl[1,15] *} ### 🔃 `__name__ == "__main__"` diff --git a/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md index 3e58d506c..41938bc7b 100644 --- a/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,21 +6,7 @@ ⏮️ 🖼, 👥 🛬 `dict` ⚪️➡️ 👆 🔗 ("☑"): -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001.py hl[9] *} ✋️ ⤴️ 👥 🤚 `dict` 🔢 `commons` *➡ 🛠️ 🔢*. @@ -83,57 +69,15 @@ fluffy = Cat(name="Mr Fluffy") ⤴️, 👥 💪 🔀 🔗 "☑" `common_parameters` ⚪️➡️ 🔛 🎓 `CommonQueryParams`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="11-15" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="9-13" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002.py hl[11:15] *} 💸 🙋 `__init__` 👩‍🔬 ⚙️ ✍ 👐 🎓: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="10" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002.py hl[12] *} ...⚫️ ✔️ 🎏 🔢 👆 ⏮️ `common_parameters`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="6" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001.py hl[9] *} 📚 🔢 ⚫️❔ **FastAPI** 🔜 ⚙️ "❎" 🔗. @@ -149,21 +93,7 @@ fluffy = Cat(name="Mr Fluffy") 🔜 👆 💪 📣 👆 🔗 ⚙️ 👉 🎓. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002.py hl[19] *} **FastAPI** 🤙 `CommonQueryParams` 🎓. 👉 ✍ "👐" 👈 🎓 & 👐 🔜 🚶‍♀️ 🔢 `commons` 👆 🔢. @@ -203,21 +133,7 @@ commons = Depends(CommonQueryParams) ...: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial003.py hl[19] *} ✋️ 📣 🆎 💡 👈 🌌 👆 👨‍🎨 🔜 💭 ⚫️❔ 🔜 🚶‍♀️ 🔢 `commons`, & ⤴️ ⚫️ 💪 ℹ 👆 ⏮️ 📟 🛠️, 🆎 ✅, ♒️: @@ -251,21 +167,7 @@ commons: CommonQueryParams = Depends() 🎏 🖼 🔜 ⤴️ 👀 💖: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial004.py hl[19] *} ...& **FastAPI** 🔜 💭 ⚫️❔. diff --git a/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index cd36ad100..ab144a497 100644 --- a/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -14,9 +14,7 @@ ⚫️ 🔜 `list` `Depends()`: -```Python hl_lines="17" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[17] *} 👉 🔗 🔜 🛠️/❎ 🎏 🌌 😐 🔗. ✋️ 👫 💲 (🚥 👫 📨 🙆) 🏆 🚫 🚶‍♀️ 👆 *➡ 🛠️ 🔢*. @@ -46,17 +44,13 @@ 👫 💪 📣 📨 📄 (💖 🎚) ⚖️ 🎏 🎧-🔗: -```Python hl_lines="6 11" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[6,11] *} ### 🤚 ⚠ 👫 🔗 💪 `raise` ⚠, 🎏 😐 🔗: -```Python hl_lines="8 13" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[8,13] *} ### 📨 💲 @@ -64,9 +58,7 @@ , 👆 💪 🏤-⚙️ 😐 🔗 (👈 📨 💲) 👆 ⏪ ⚙️ 👱 🙆, & ✋️ 💲 🏆 🚫 ⚙️, 🔗 🔜 🛠️: -```Python hl_lines="9 14" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[9,14] *} ## 🔗 👪 *➡ 🛠️* diff --git a/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md index 2896be39d..1b37b1cf2 100644 --- a/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md @@ -29,21 +29,15 @@ FastAPI 🐕‍🦺 🔗 👈 ../../docs_src/dependencies/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="6-7" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001.py hl[8:11] *} 👈 ⚫️. @@ -67,41 +53,13 @@ ### 🗄 `Depends` -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="1" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001.py hl[3] *} ### 📣 🔗, "⚓️" 🎏 🌌 👆 ⚙️ `Body`, `Query`, ♒️. ⏮️ 👆 *➡ 🛠️ 🔢* 🔢, ⚙️ `Depends` ⏮️ 🆕 🔢: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="15 20" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="11 16" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001.py hl[15,20] *} 👐 👆 ⚙️ `Depends` 🔢 👆 🔢 🎏 🌌 👆 ⚙️ `Body`, `Query`, ♒️, `Depends` 👷 👄 🎏. diff --git a/docs/em/docs/tutorial/dependencies/sub-dependencies.md b/docs/em/docs/tutorial/dependencies/sub-dependencies.md index a1e7be134..6d622e952 100644 --- a/docs/em/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/em/docs/tutorial/dependencies/sub-dependencies.md @@ -10,21 +10,7 @@ 👆 💪 ✍ 🥇 🔗 ("☑") 💖: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="6-7" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005.py hl[8:9] *} ⚫️ 📣 📦 🔢 🔢 `q` `str`, & ⤴️ ⚫️ 📨 ⚫️. @@ -34,21 +20,7 @@ ⤴️ 👆 💪 ✍ ➕1️⃣ 🔗 🔢 ("☑") 👈 🎏 🕰 📣 🔗 🚮 👍 (⚫️ "⚓️" 💁‍♂️): -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="11" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005.py hl[13] *} ➡️ 🎯 🔛 🔢 📣: @@ -61,21 +33,7 @@ ⤴️ 👥 💪 ⚙️ 🔗 ⏮️: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="22" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005.py hl[22] *} /// info diff --git a/docs/em/docs/tutorial/encoder.md b/docs/em/docs/tutorial/encoder.md index 21419ef21..ad05f701e 100644 --- a/docs/em/docs/tutorial/encoder.md +++ b/docs/em/docs/tutorial/encoder.md @@ -20,21 +20,7 @@ ⚫️ 📨 🎚, 💖 Pydantic 🏷, & 📨 🎻 🔗 ⏬: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="5 22" -{!> ../../docs_src/encoder/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="4 21" -{!> ../../docs_src/encoder/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/encoder/tutorial001.py hl[5,22] *} 👉 🖼, ⚫️ 🔜 🗜 Pydantic 🏷 `dict`, & `datetime` `str`. diff --git a/docs/em/docs/tutorial/extra-data-types.md b/docs/em/docs/tutorial/extra-data-types.md index 1d473bd93..f15a74b4a 100644 --- a/docs/em/docs/tutorial/extra-data-types.md +++ b/docs/em/docs/tutorial/extra-data-types.md @@ -55,36 +55,8 @@ 📥 🖼 *➡ 🛠️* ⏮️ 🔢 ⚙️ 🔛 🆎. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="1 3 12-16" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="1 2 11-15" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001.py hl[1,3,12:16] *} 🗒 👈 🔢 🔘 🔢 ✔️ 👫 🐠 💽 🆎, & 👆 💪, 🖼, 🎭 😐 📅 🎭, 💖: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="17-18" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001.py hl[18:19] *} diff --git a/docs/em/docs/tutorial/extra-models.md b/docs/em/docs/tutorial/extra-models.md index 4fdf196e8..19ab5b798 100644 --- a/docs/em/docs/tutorial/extra-models.md +++ b/docs/em/docs/tutorial/extra-models.md @@ -20,21 +20,7 @@ 📥 🏢 💭 ❔ 🏷 💪 👀 💖 ⏮️ 👫 🔐 🏑 & 🥉 🌐❔ 👫 ⚙️: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" -{!> ../../docs_src/extra_models/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" -{!> ../../docs_src/extra_models/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial001.py hl[9,11,16,22,24,29:30,33:35,40:41] *} ### 🔃 `**user_in.dict()` @@ -168,21 +154,7 @@ UserInDB( 👈 🌌, 👥 💪 📣 🔺 🖖 🏷 (⏮️ 🔢 `password`, ⏮️ `hashed_password` & 🍵 🔐): -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9 15-16 19-20 23-24" -{!> ../../docs_src/extra_models/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7 13-14 17-18 21-22" -{!> ../../docs_src/extra_models/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial002.py hl[9,15:16,19:20,23:24] *} ## `Union` ⚖️ `anyOf` @@ -198,21 +170,7 @@ UserInDB( /// -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="1 14-15 18-20 33" -{!> ../../docs_src/extra_models/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="1 14-15 18-20 33" -{!> ../../docs_src/extra_models/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial003.py hl[1,14:15,18:20,33] *} ### `Union` 🐍 3️⃣.1️⃣0️⃣ @@ -234,21 +192,7 @@ some_variable: PlaneItem | CarItem 👈, ⚙️ 🐩 🐍 `typing.List` (⚖️ `list` 🐍 3️⃣.9️⃣ & 🔛): -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="1 20" -{!> ../../docs_src/extra_models/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="18" -{!> ../../docs_src/extra_models/tutorial004_py39.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial004.py hl[1,20] *} ## 📨 ⏮️ ❌ `dict` @@ -258,21 +202,7 @@ some_variable: PlaneItem | CarItem 👉 💼, 👆 💪 ⚙️ `typing.Dict` (⚖️ `dict` 🐍 3️⃣.9️⃣ & 🔛): -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="1 8" -{!> ../../docs_src/extra_models/tutorial005.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="6" -{!> ../../docs_src/extra_models/tutorial005_py39.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial005.py hl[1,8] *} ## 🌃 diff --git a/docs/em/docs/tutorial/first-steps.md b/docs/em/docs/tutorial/first-steps.md index d6762422e..a8f936b01 100644 --- a/docs/em/docs/tutorial/first-steps.md +++ b/docs/em/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ 🙅 FastAPI 📁 💪 👀 💖 👉: -```Python -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} 📁 👈 📁 `main.py`. @@ -133,9 +131,7 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ### 🔁 1️⃣: 🗄 `FastAPI` -```Python hl_lines="1" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI` 🐍 🎓 👈 🚚 🌐 🛠️ 👆 🛠️. @@ -149,9 +145,7 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ### 🔁 2️⃣: ✍ `FastAPI` "👐" -```Python hl_lines="3" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[3] *} 📥 `app` 🔢 🔜 "👐" 🎓 `FastAPI`. @@ -171,9 +165,7 @@ $ uvicorn main:app --reload 🚥 👆 ✍ 👆 📱 💖: -```Python hl_lines="3" -{!../../docs_src/first_steps/tutorial002.py!} -``` +{* ../../docs_src/first_steps/tutorial002.py hl[3] *} & 🚮 ⚫️ 📁 `main.py`, ⤴️ 👆 🔜 🤙 `uvicorn` 💖: @@ -250,9 +242,7 @@ https://example.com/items/foo #### 🔬 *➡ 🛠️ 👨‍🎨* -```Python hl_lines="6" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[6] *} `@app.get("/")` 💬 **FastAPI** 👈 🔢 ▶️️ 🔛 🈚 🚚 📨 👈 🚶: @@ -306,9 +296,7 @@ https://example.com/items/foo * **🛠️**: `get`. * **🔢**: 🔢 🔛 "👨‍🎨" (🔛 `@app.get("/")`). -```Python hl_lines="7" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[7] *} 👉 🐍 🔢. @@ -320,9 +308,7 @@ https://example.com/items/foo 👆 💪 🔬 ⚫️ 😐 🔢 ↩️ `async def`: -```Python hl_lines="7" -{!../../docs_src/first_steps/tutorial003.py!} -``` +{* ../../docs_src/first_steps/tutorial003.py hl[7] *} /// note @@ -332,9 +318,7 @@ https://example.com/items/foo ### 🔁 5️⃣: 📨 🎚 -```Python hl_lines="8" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[8] *} 👆 💪 📨 `dict`, `list`, ⭐ 💲 `str`, `int`, ♒️. diff --git a/docs/em/docs/tutorial/handling-errors.md b/docs/em/docs/tutorial/handling-errors.md index e0edae51a..d73b730e1 100644 --- a/docs/em/docs/tutorial/handling-errors.md +++ b/docs/em/docs/tutorial/handling-errors.md @@ -25,9 +25,7 @@ ### 🗄 `HTTPException` -```Python hl_lines="1" -{!../../docs_src/handling_errors/tutorial001.py!} -``` +{* ../../docs_src/handling_errors/tutorial001.py hl[1] *} ### 🤚 `HTTPException` 👆 📟 @@ -41,9 +39,7 @@ 👉 🖼, 🕐❔ 👩‍💻 📨 🏬 🆔 👈 🚫 🔀, 🤚 ⚠ ⏮️ 👔 📟 `404`: -```Python hl_lines="11" -{!../../docs_src/handling_errors/tutorial001.py!} -``` +{* ../../docs_src/handling_errors/tutorial001.py hl[11] *} ### 📉 📨 @@ -81,9 +77,7 @@ ✋️ 💼 👆 💪 ⚫️ 🏧 😐, 👆 💪 🚮 🛃 🎚: -```Python hl_lines="14" -{!../../docs_src/handling_errors/tutorial002.py!} -``` +{* ../../docs_src/handling_errors/tutorial002.py hl[14] *} ## ❎ 🛃 ⚠ 🐕‍🦺 @@ -95,9 +89,7 @@ 👆 💪 🚮 🛃 ⚠ 🐕‍🦺 ⏮️ `@app.exception_handler()`: -```Python hl_lines="5-7 13-18 24" -{!../../docs_src/handling_errors/tutorial003.py!} -``` +{* ../../docs_src/handling_errors/tutorial003.py hl[5:7,13:18,24] *} 📥, 🚥 👆 📨 `/unicorns/yolo`, *➡ 🛠️* 🔜 `raise` `UnicornException`. @@ -135,9 +127,7 @@ ⚠ 🐕‍🦺 🔜 📨 `Request` & ⚠. -```Python hl_lines="2 14-16" -{!../../docs_src/handling_errors/tutorial004.py!} -``` +{* ../../docs_src/handling_errors/tutorial004.py hl[2,14:16] *} 🔜, 🚥 👆 🚶 `/items/foo`, ↩️ 💆‍♂ 🔢 🎻 ❌ ⏮️: @@ -188,9 +178,7 @@ path -> item_id 🖼, 👆 💪 💚 📨 ✅ ✍ 📨 ↩️ 🎻 👫 ❌: -```Python hl_lines="3-4 9-11 22" -{!../../docs_src/handling_errors/tutorial004.py!} -``` +{* ../../docs_src/handling_errors/tutorial004.py hl[3:4,9:11,22] *} /// note | 📡 ℹ @@ -206,9 +194,7 @@ path -> item_id 👆 💪 ⚙️ ⚫️ ⏪ 🛠️ 👆 📱 🕹 💪 & ℹ ⚫️, 📨 ⚫️ 👩‍💻, ♒️. -```Python hl_lines="14" -{!../../docs_src/handling_errors/tutorial005.py!} -``` +{* ../../docs_src/handling_errors/tutorial005.py hl[14] *} 🔜 🔄 📨 ❌ 🏬 💖: @@ -266,8 +252,6 @@ from starlette.exceptions import HTTPException as StarletteHTTPException 🚥 👆 💚 ⚙️ ⚠ ⤴️ ⏮️ 🎏 🔢 ⚠ 🐕‍🦺 ⚪️➡️ **FastAPI**, 👆 💪 🗄 & 🏤-⚙️ 🔢 ⚠ 🐕‍🦺 ⚪️➡️ `fastapi.exception_handlers`: -```Python hl_lines="2-5 15 21" -{!../../docs_src/handling_errors/tutorial006.py!} -``` +{* ../../docs_src/handling_errors/tutorial006.py hl[2:5,15,21] *} 👉 🖼 👆 `print`😅 ❌ ⏮️ 📶 🎨 📧, ✋️ 👆 🤚 💭. 👆 💪 ⚙️ ⚠ & ⤴️ 🏤-⚙️ 🔢 ⚠ 🐕‍🦺. diff --git a/docs/em/docs/tutorial/header-params.md b/docs/em/docs/tutorial/header-params.md index d9eafe77e..fa5e3a22b 100644 --- a/docs/em/docs/tutorial/header-params.md +++ b/docs/em/docs/tutorial/header-params.md @@ -6,21 +6,7 @@ 🥇 🗄 `Header`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="3" -{!> ../../docs_src/header_params/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="1" -{!> ../../docs_src/header_params/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial001.py hl[3] *} ## 📣 `Header` 🔢 @@ -28,21 +14,7 @@ 🥇 💲 🔢 💲, 👆 💪 🚶‍♀️ 🌐 ➕ 🔬 ⚖️ ✍ 🔢: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/header_params/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial001.py hl[9] *} /// note | 📡 ℹ @@ -74,21 +46,7 @@ 🚥 🤔 👆 💪 ❎ 🏧 🛠️ 🎦 🔠, ⚒ 🔢 `convert_underscores` `Header` `False`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="10" -{!> ../../docs_src/header_params/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="8" -{!> ../../docs_src/header_params/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial002.py hl[10] *} /// warning @@ -106,29 +64,7 @@ 🖼, 📣 🎚 `X-Token` 👈 💪 😑 🌅 🌘 🕐, 👆 💪 ✍: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial003_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/header_params/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial003.py hl[9] *} 🚥 👆 🔗 ⏮️ 👈 *➡ 🛠️* 📨 2️⃣ 🇺🇸🔍 🎚 💖: diff --git a/docs/em/docs/tutorial/metadata.md b/docs/em/docs/tutorial/metadata.md index a30db113d..eaf605de1 100644 --- a/docs/em/docs/tutorial/metadata.md +++ b/docs/em/docs/tutorial/metadata.md @@ -17,9 +17,7 @@ 👆 💪 ⚒ 👫 ⏩: -```Python hl_lines="3-16 19-31" -{!../../docs_src/metadata/tutorial001.py!} -``` +{* ../../docs_src/metadata/tutorial001.py hl[3:16,19:31] *} /// tip @@ -51,9 +49,7 @@ ✍ 🗃 👆 🔖 & 🚶‍♀️ ⚫️ `openapi_tags` 🔢: -```Python hl_lines="3-16 18" -{!../../docs_src/metadata/tutorial004.py!} -``` +{* ../../docs_src/metadata/tutorial004.py hl[3:16,18] *} 👀 👈 👆 💪 ⚙️ ✍ 🔘 📛, 🖼 "💳" 🔜 🎦 🦁 (**💳**) & "🎀" 🔜 🎦 ❕ (_🎀_). @@ -67,9 +63,7 @@ ⚙️ `tags` 🔢 ⏮️ 👆 *➡ 🛠️* (& `APIRouter`Ⓜ) 🛠️ 👫 🎏 🔖: -```Python hl_lines="21 26" -{!../../docs_src/metadata/tutorial004.py!} -``` +{* ../../docs_src/metadata/tutorial004.py hl[21,26] *} /// info @@ -97,9 +91,7 @@ 🖼, ⚒ ⚫️ 🍦 `/api/v1/openapi.json`: -```Python hl_lines="3" -{!../../docs_src/metadata/tutorial002.py!} -``` +{* ../../docs_src/metadata/tutorial002.py hl[3] *} 🚥 👆 💚 ❎ 🗄 🔗 🍕 👆 💪 ⚒ `openapi_url=None`, 👈 🔜 ❎ 🧾 👩‍💻 🔢 👈 ⚙️ ⚫️. @@ -116,6 +108,4 @@ 🖼, ⚒ 🦁 🎚 🍦 `/documentation` & ❎ 📄: -```Python hl_lines="3" -{!../../docs_src/metadata/tutorial003.py!} -``` +{* ../../docs_src/metadata/tutorial003.py hl[3] *} diff --git a/docs/em/docs/tutorial/middleware.md b/docs/em/docs/tutorial/middleware.md index a794ab019..d203471e8 100644 --- a/docs/em/docs/tutorial/middleware.md +++ b/docs/em/docs/tutorial/middleware.md @@ -31,9 +31,7 @@ * ⤴️ ⚫️ 📨 `response` 🏗 🔗 *➡ 🛠️*. * 👆 💪 ⤴️ 🔀 🌅 `response` ⏭ 🛬 ⚫️. -```Python hl_lines="8-9 11 14" -{!../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[8:9,11,14] *} /// tip @@ -59,9 +57,7 @@ 🖼, 👆 💪 🚮 🛃 🎚 `X-Process-Time` ⚗ 🕰 🥈 👈 ⚫️ ✊ 🛠️ 📨 & 🏗 📨: -```Python hl_lines="10 12-13" -{!../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *} ## 🎏 🛠️ diff --git a/docs/em/docs/tutorial/path-operation-configuration.md b/docs/em/docs/tutorial/path-operation-configuration.md index deb71c807..c6030c089 100644 --- a/docs/em/docs/tutorial/path-operation-configuration.md +++ b/docs/em/docs/tutorial/path-operation-configuration.md @@ -16,29 +16,7 @@ ✋️ 🚥 👆 🚫 💭 ⚫️❔ 🔠 🔢 📟, 👆 💪 ⚙️ ⌨ 📉 `status`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="3 17" -{!> ../../docs_src/path_operation_configuration/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="3 17" -{!> ../../docs_src/path_operation_configuration/tutorial001_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="1 15" -{!> ../../docs_src/path_operation_configuration/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial001.py hl[3,17] *} 👈 👔 📟 🔜 ⚙️ 📨 & 🔜 🚮 🗄 🔗. @@ -54,29 +32,7 @@ 👆 💪 🚮 🔖 👆 *➡ 🛠️*, 🚶‍♀️ 🔢 `tags` ⏮️ `list` `str` (🛎 1️⃣ `str`): -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="17 22 27" -{!> ../../docs_src/path_operation_configuration/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="17 22 27" -{!> ../../docs_src/path_operation_configuration/tutorial002_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="15 20 25" -{!> ../../docs_src/path_operation_configuration/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial002.py hl[17,22,27] *} 👫 🔜 🚮 🗄 🔗 & ⚙️ 🏧 🧾 🔢: @@ -90,37 +46,13 @@ **FastAPI** 🐕‍🦺 👈 🎏 🌌 ⏮️ ✅ 🎻: -```Python hl_lines="1 8-10 13 18" -{!../../docs_src/path_operation_configuration/tutorial002b.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial002b.py hl[1,8:10,13,18] *} ## 📄 & 📛 👆 💪 🚮 `summary` & `description`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="20-21" -{!> ../../docs_src/path_operation_configuration/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="20-21" -{!> ../../docs_src/path_operation_configuration/tutorial003_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="18-19" -{!> ../../docs_src/path_operation_configuration/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial003.py hl[20:21] *} ## 📛 ⚪️➡️ #️⃣ @@ -128,29 +60,7 @@ 👆 💪 ✍ #️⃣ , ⚫️ 🔜 🔬 & 🖥 ☑ (✊ 🔘 🏧 #️⃣ 📐). -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="19-27" -{!> ../../docs_src/path_operation_configuration/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="19-27" -{!> ../../docs_src/path_operation_configuration/tutorial004_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="17-25" -{!> ../../docs_src/path_operation_configuration/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial004.py hl[19:27] *} ⚫️ 🔜 ⚙️ 🎓 🩺: @@ -160,29 +70,7 @@ 👆 💪 ✔ 📨 📛 ⏮️ 🔢 `response_description`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="21" -{!> ../../docs_src/path_operation_configuration/tutorial005.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="21" -{!> ../../docs_src/path_operation_configuration/tutorial005_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="19" -{!> ../../docs_src/path_operation_configuration/tutorial005_py310.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial005.py hl[21] *} /// info @@ -204,9 +92,7 @@ 🚥 👆 💪 ™ *➡ 🛠️* 😢, ✋️ 🍵 ❎ ⚫️, 🚶‍♀️ 🔢 `deprecated`: -```Python hl_lines="16" -{!../../docs_src/path_operation_configuration/tutorial006.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial006.py hl[16] *} ⚫️ 🔜 🎯 ™ 😢 🎓 🩺: diff --git a/docs/em/docs/tutorial/path-params-numeric-validations.md b/docs/em/docs/tutorial/path-params-numeric-validations.md index 74dbb55f7..b45e0557b 100644 --- a/docs/em/docs/tutorial/path-params-numeric-validations.md +++ b/docs/em/docs/tutorial/path-params-numeric-validations.md @@ -6,21 +6,7 @@ 🥇, 🗄 `Path` ⚪️➡️ `fastapi`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="3" -{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="1" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial001.py hl[3] *} ## 📣 🗃 @@ -28,21 +14,7 @@ 🖼, 📣 `title` 🗃 💲 ➡ 🔢 `item_id` 👆 💪 🆎: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="8" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial001.py hl[10] *} /// note @@ -70,9 +42,7 @@ , 👆 💪 📣 👆 🔢: -```Python hl_lines="7" -{!../../docs_src/path_params_numeric_validations/tutorial002.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial002.py hl[7] *} ## ✔ 🔢 👆 💪, 🎱 @@ -82,9 +52,7 @@ 🐍 🏆 🚫 🕳 ⏮️ 👈 `*`, ✋️ ⚫️ 🔜 💭 👈 🌐 📄 🔢 🔜 🤙 🇨🇻 ❌ (🔑-💲 👫), 💭 kwargs. 🚥 👫 🚫 ✔️ 🔢 💲. -```Python hl_lines="7" -{!../../docs_src/path_params_numeric_validations/tutorial003.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *} ## 🔢 🔬: 👑 🌘 ⚖️ 🌓 @@ -92,9 +60,7 @@ 📥, ⏮️ `ge=1`, `item_id` 🔜 💪 🔢 🔢 "`g`🅾 🌘 ⚖️ `e`🅾" `1`. -```Python hl_lines="8" -{!../../docs_src/path_params_numeric_validations/tutorial004.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial004.py hl[8] *} ## 🔢 🔬: 🌘 🌘 & 🌘 🌘 ⚖️ 🌓 @@ -103,9 +69,7 @@ * `gt`: `g`🅾 `t`👲 * `le`: `l`👭 🌘 ⚖️ `e`🅾 -```Python hl_lines="9" -{!../../docs_src/path_params_numeric_validations/tutorial005.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial005.py hl[9] *} ## 🔢 🔬: 🎈, 🌘 🌘 & 🌘 🌘 @@ -117,9 +81,7 @@ & 🎏 lt. -```Python hl_lines="11" -{!../../docs_src/path_params_numeric_validations/tutorial006.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial006.py hl[11] *} ## 🌃 diff --git a/docs/em/docs/tutorial/path-params.md b/docs/em/docs/tutorial/path-params.md index daf5417eb..a914dc905 100644 --- a/docs/em/docs/tutorial/path-params.md +++ b/docs/em/docs/tutorial/path-params.md @@ -2,9 +2,7 @@ 👆 💪 📣 ➡ "🔢" ⚖️ "🔢" ⏮️ 🎏 ❕ ⚙️ 🐍 📁 🎻: -```Python hl_lines="6-7" -{!../../docs_src/path_params/tutorial001.py!} -``` +{* ../../docs_src/path_params/tutorial001.py hl[6:7] *} 💲 ➡ 🔢 `item_id` 🔜 🚶‍♀️ 👆 🔢 ❌ `item_id`. @@ -18,9 +16,7 @@ 👆 💪 📣 🆎 ➡ 🔢 🔢, ⚙️ 🐩 🐍 🆎 ✍: -```Python hl_lines="7" -{!../../docs_src/path_params/tutorial002.py!} -``` +{* ../../docs_src/path_params/tutorial002.py hl[7] *} 👉 💼, `item_id` 📣 `int`. @@ -121,17 +117,13 @@ ↩️ *➡ 🛠️* 🔬 ✔, 👆 💪 ⚒ 💭 👈 ➡ `/users/me` 📣 ⏭ 1️⃣ `/users/{user_id}`: -```Python hl_lines="6 11" -{!../../docs_src/path_params/tutorial003.py!} -``` +{* ../../docs_src/path_params/tutorial003.py hl[6,11] *} ⏪, ➡ `/users/{user_id}` 🔜 🏏 `/users/me`, "💭" 👈 ⚫️ 📨 🔢 `user_id` ⏮️ 💲 `"me"`. ➡, 👆 🚫🔜 ↔ ➡ 🛠️: -```Python hl_lines="6 11" -{!../../docs_src/path_params/tutorial003b.py!} -``` +{* ../../docs_src/path_params/tutorial003b.py hl[6,11] *} 🥇 🕐 🔜 🕧 ⚙️ ↩️ ➡ 🏏 🥇. @@ -147,9 +139,7 @@ ⤴️ ✍ 🎓 🔢 ⏮️ 🔧 💲, ❔ 🔜 💪 ☑ 💲: -```Python hl_lines="1 6-9" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *} /// info @@ -167,9 +157,7 @@ ⤴️ ✍ *➡ 🔢* ⏮️ 🆎 ✍ ⚙️ 🔢 🎓 👆 ✍ (`ModelName`): -```Python hl_lines="16" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[16] *} ### ✅ 🩺 @@ -185,17 +173,13 @@ 👆 💪 🔬 ⚫️ ⏮️ *🔢 👨‍🎓* 👆 ✍ 🔢 `ModelName`: -```Python hl_lines="17" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[17] *} #### 🤚 *🔢 💲* 👆 💪 🤚 ☑ 💲 ( `str` 👉 💼) ⚙️ `model_name.value`, ⚖️ 🏢, `your_enum_member.value`: -```Python hl_lines="20" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[20] *} /// tip @@ -209,9 +193,7 @@ 👫 🔜 🗜 👫 🔗 💲 (🎻 👉 💼) ⏭ 🛬 👫 👩‍💻: -```Python hl_lines="18 21 23" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *} 👆 👩‍💻 👆 🔜 🤚 🎻 📨 💖: @@ -250,9 +232,7 @@ , 👆 💪 ⚙️ ⚫️ ⏮️: -```Python hl_lines="6" -{!../../docs_src/path_params/tutorial004.py!} -``` +{* ../../docs_src/path_params/tutorial004.py hl[6] *} /// tip diff --git a/docs/em/docs/tutorial/query-params-str-validations.md b/docs/em/docs/tutorial/query-params-str-validations.md index f75c0a26f..dbaab5735 100644 --- a/docs/em/docs/tutorial/query-params-str-validations.md +++ b/docs/em/docs/tutorial/query-params-str-validations.md @@ -4,21 +4,7 @@ ➡️ ✊ 👉 🈸 🖼: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial001.py hl[9] *} 🔢 🔢 `q` 🆎 `Union[str, None]` (⚖️ `str | None` 🐍 3️⃣.1️⃣0️⃣), 👈 ⛓ 👈 ⚫️ 🆎 `str` ✋️ 💪 `None`, & 👐, 🔢 💲 `None`, FastAPI 🔜 💭 ⚫️ 🚫 ✔. @@ -38,41 +24,13 @@ FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`. 🏆 👈, 🥇 🗄 `Query` ⚪️➡️ `fastapi`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="3" -{!> ../../docs_src/query_params_str_validations/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="1" -{!> ../../docs_src/query_params_str_validations/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[3] *} ## ⚙️ `Query` 🔢 💲 & 🔜 ⚙️ ⚫️ 🔢 💲 👆 🔢, ⚒ 🔢 `max_length` 5️⃣0️⃣: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[9] *} 👥 ✔️ ❎ 🔢 💲 `None` 🔢 ⏮️ `Query()`, 👥 💪 🔜 ⚒ 🔢 💲 ⏮️ 🔢 `Query(default=None)`, ⚫️ 🍦 🎏 🎯 ⚖ 👈 🔢 💲. @@ -134,41 +92,13 @@ q: Union[str, None] = Query(default=None, max_length=50) 👆 💪 🚮 🔢 `min_length`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial003.py hl[10] *} ## 🚮 🥔 🧬 👆 💪 🔬 🥔 🧬 👈 🔢 🔜 🏏: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial004.py hl[11] *} 👉 🎯 🥔 🧬 ✅ 👈 📨 🔢 💲: @@ -186,9 +116,7 @@ q: Union[str, None] = Query(default=None, max_length=50) ➡️ 💬 👈 👆 💚 📣 `q` 🔢 🔢 ✔️ `min_length` `3`, & ✔️ 🔢 💲 `"fixedquery"`: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial005.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial005.py hl[7] *} /// note @@ -218,17 +146,13 @@ q: Union[str, None] = Query(default=None, min_length=3) , 🕐❔ 👆 💪 📣 💲 ✔ ⏪ ⚙️ `Query`, 👆 💪 🎯 🚫 📣 🔢 💲: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial006.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial006.py hl[7] *} ### ✔ ⏮️ ❕ (`...`) 📤 🎛 🌌 🎯 📣 👈 💲 ✔. 👆 💪 ⚒ `default` 🔢 🔑 💲 `...`: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial006b.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial006b.py hl[7] *} /// info @@ -246,21 +170,7 @@ q: Union[str, None] = Query(default=None, min_length=3) 👈, 👆 💪 📣 👈 `None` ☑ 🆎 ✋️ ⚙️ `default=...`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006c.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial006c_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial006c.py hl[9] *} /// tip @@ -272,9 +182,7 @@ Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ 🚥 👆 💭 😬 ⚙️ `...`, 👆 💪 🗄 & ⚙️ `Required` ⚪️➡️ Pydantic: -```Python hl_lines="2 8" -{!../../docs_src/query_params_str_validations/tutorial006d.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial006d.py hl[2,8] *} /// tip @@ -288,29 +196,7 @@ Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ 🖼, 📣 🔢 🔢 `q` 👈 💪 😑 💗 🕰 📛, 👆 💪 ✍: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial011_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial011.py hl[9] *} ⤴️, ⏮️ 📛 💖: @@ -345,21 +231,7 @@ http://localhost:8000/items/?q=foo&q=bar & 👆 💪 🔬 🔢 `list` 💲 🚥 👌 🚚: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial012.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial012_py39.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial012.py hl[9] *} 🚥 👆 🚶: @@ -382,9 +254,7 @@ http://localhost:8000/items/ 👆 💪 ⚙️ `list` 🔗 ↩️ `List[str]` (⚖️ `list[str]` 🐍 3️⃣.9️⃣ ➕): -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial013.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial013.py hl[7] *} /// note @@ -410,39 +280,11 @@ http://localhost:8000/items/ 👆 💪 🚮 `title`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial007.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial007_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial007.py hl[10] *} & `description`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="13" -{!> ../../docs_src/query_params_str_validations/tutorial008.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial008_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial008.py hl[13] *} ## 📛 🔢 @@ -462,21 +304,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems ⤴️ 👆 💪 📣 `alias`, & 👈 📛 ⚫️❔ 🔜 ⚙️ 🔎 🔢 💲: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial009.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial009_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial009.py hl[9] *} ## 😛 🔢 @@ -486,21 +314,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems ⤴️ 🚶‍♀️ 🔢 `deprecated=True` `Query`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="18" -{!> ../../docs_src/query_params_str_validations/tutorial010.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="16" -{!> ../../docs_src/query_params_str_validations/tutorial010_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial010.py hl[18] *} 🩺 🔜 🎦 ⚫️ 💖 👉: @@ -510,21 +324,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems 🚫 🔢 🔢 ⚪️➡️ 🏗 🗄 🔗 (& ➡️, ⚪️➡️ 🏧 🧾 ⚙️), ⚒ 🔢 `include_in_schema` `Query` `False`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial014.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial014_py310.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial014.py hl[10] *} ## 🌃 diff --git a/docs/em/docs/tutorial/query-params.md b/docs/em/docs/tutorial/query-params.md index c8432f182..5c8d868a9 100644 --- a/docs/em/docs/tutorial/query-params.md +++ b/docs/em/docs/tutorial/query-params.md @@ -2,9 +2,7 @@ 🕐❔ 👆 📣 🎏 🔢 🔢 👈 🚫 🍕 ➡ 🔢, 👫 🔁 🔬 "🔢" 🔢. -```Python hl_lines="9" -{!../../docs_src/query_params/tutorial001.py!} -``` +{* ../../docs_src/query_params/tutorial001.py hl[9] *} 🔢 ⚒ 🔑-💲 👫 👈 🚶 ⏮️ `?` 📛, 🎏 `&` 🦹. @@ -63,21 +61,7 @@ http://127.0.0.1:8000/items/?skip=20 🎏 🌌, 👆 💪 📣 📦 🔢 🔢, ⚒ 👫 🔢 `None`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/query_params/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial002.py hl[9] *} 👉 💼, 🔢 🔢 `q` 🔜 📦, & 🔜 `None` 🔢. @@ -91,21 +75,7 @@ http://127.0.0.1:8000/items/?skip=20 👆 💪 📣 `bool` 🆎, & 👫 🔜 🗜: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/query_params/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial003.py hl[9] *} 👉 💼, 🚥 👆 🚶: @@ -148,21 +118,7 @@ http://127.0.0.1:8000/items/foo?short=yes 👫 🔜 🔬 📛: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="8 10" -{!> ../../docs_src/query_params/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="6 8" -{!> ../../docs_src/query_params/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial004.py hl[8,10] *} ## ✔ 🔢 🔢 @@ -172,9 +128,7 @@ http://127.0.0.1:8000/items/foo?short=yes ✋️ 🕐❔ 👆 💚 ⚒ 🔢 🔢 ✔, 👆 💪 🚫 📣 🙆 🔢 💲: -```Python hl_lines="6-7" -{!../../docs_src/query_params/tutorial005.py!} -``` +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} 📥 🔢 🔢 `needy` ✔ 🔢 🔢 🆎 `str`. @@ -218,21 +172,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy & ↗️, 👆 💪 🔬 🔢 ✔, ✔️ 🔢 💲, & 🍕 📦: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="10" -{!> ../../docs_src/query_params/tutorial006.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="8" -{!> ../../docs_src/query_params/tutorial006_py310.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial006.py hl[10] *} 👉 💼, 📤 3️⃣ 🔢 🔢: diff --git a/docs/em/docs/tutorial/request-files.md b/docs/em/docs/tutorial/request-files.md index 9dcad81b4..c3bdeafd4 100644 --- a/docs/em/docs/tutorial/request-files.md +++ b/docs/em/docs/tutorial/request-files.md @@ -16,17 +16,13 @@ 🗄 `File` & `UploadFile` ⚪️➡️ `fastapi`: -```Python hl_lines="1" -{!../../docs_src/request_files/tutorial001.py!} -``` +{* ../../docs_src/request_files/tutorial001.py hl[1] *} ## 🔬 `File` 🔢 ✍ 📁 🔢 🎏 🌌 👆 🔜 `Body` ⚖️ `Form`: -```Python hl_lines="7" -{!../../docs_src/request_files/tutorial001.py!} -``` +{* ../../docs_src/request_files/tutorial001.py hl[7] *} /// info @@ -54,9 +50,7 @@ 🔬 📁 🔢 ⏮️ 🆎 `UploadFile`: -```Python hl_lines="12" -{!../../docs_src/request_files/tutorial001.py!} -``` +{* ../../docs_src/request_files/tutorial001.py hl[12] *} ⚙️ `UploadFile` ✔️ 📚 📈 🤭 `bytes`: @@ -139,29 +133,13 @@ contents = myfile.file.read() 👆 💪 ⚒ 📁 📦 ⚙️ 🐩 🆎 ✍ & ⚒ 🔢 💲 `None`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7 14" -{!> ../../docs_src/request_files/tutorial001_02_py310.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_02.py hl[9,17] *} ## `UploadFile` ⏮️ 🌖 🗃 👆 💪 ⚙️ `File()` ⏮️ `UploadFile`, 🖼, ⚒ 🌖 🗃: -```Python hl_lines="13" -{!../../docs_src/request_files/tutorial001_03.py!} -``` +{* ../../docs_src/request_files/tutorial001_03.py hl[13] *} ## 💗 📁 📂 @@ -171,21 +149,7 @@ contents = myfile.file.read() ⚙️ 👈, 📣 📇 `bytes` ⚖️ `UploadFile`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="10 15" -{!> ../../docs_src/request_files/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="8 13" -{!> ../../docs_src/request_files/tutorial002_py39.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial002.py hl[10,15] *} 👆 🔜 📨, 📣, `list` `bytes` ⚖️ `UploadFile`Ⓜ. @@ -201,21 +165,7 @@ contents = myfile.file.read() & 🎏 🌌 ⏭, 👆 💪 ⚙️ `File()` ⚒ 🌖 🔢, `UploadFile`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="18" -{!> ../../docs_src/request_files/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="16" -{!> ../../docs_src/request_files/tutorial003_py39.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial003.py hl[18] *} ## 🌃 diff --git a/docs/em/docs/tutorial/request-forms-and-files.md b/docs/em/docs/tutorial/request-forms-and-files.md index 80793dae4..680b1a96a 100644 --- a/docs/em/docs/tutorial/request-forms-and-files.md +++ b/docs/em/docs/tutorial/request-forms-and-files.md @@ -12,17 +12,13 @@ ## 🗄 `File` & `Form` -```Python hl_lines="1" -{!../../docs_src/request_forms_and_files/tutorial001.py!} -``` +{* ../../docs_src/request_forms_and_files/tutorial001.py hl[1] *} ## 🔬 `File` & `Form` 🔢 ✍ 📁 & 📨 🔢 🎏 🌌 👆 🔜 `Body` ⚖️ `Query`: -```Python hl_lines="8" -{!../../docs_src/request_forms_and_files/tutorial001.py!} -``` +{* ../../docs_src/request_forms_and_files/tutorial001.py hl[8] *} 📁 & 📨 🏑 🔜 📂 📨 📊 & 👆 🔜 📨 📁 & 📨 🏑. diff --git a/docs/em/docs/tutorial/request-forms.md b/docs/em/docs/tutorial/request-forms.md index d364d2c92..1cc1ea5dc 100644 --- a/docs/em/docs/tutorial/request-forms.md +++ b/docs/em/docs/tutorial/request-forms.md @@ -14,17 +14,13 @@ 🗄 `Form` ⚪️➡️ `fastapi`: -```Python hl_lines="1" -{!../../docs_src/request_forms/tutorial001.py!} -``` +{* ../../docs_src/request_forms/tutorial001.py hl[1] *} ## 🔬 `Form` 🔢 ✍ 📨 🔢 🎏 🌌 👆 🔜 `Body` ⚖️ `Query`: -```Python hl_lines="7" -{!../../docs_src/request_forms/tutorial001.py!} -``` +{* ../../docs_src/request_forms/tutorial001.py hl[7] *} 🖼, 1️⃣ 🌌 Oauth2️⃣ 🔧 💪 ⚙️ (🤙 "🔐 💧") ⚫️ ✔ 📨 `username` & `password` 📨 🏑. diff --git a/docs/em/docs/tutorial/response-model.md b/docs/em/docs/tutorial/response-model.md index fb5c17dd6..477376458 100644 --- a/docs/em/docs/tutorial/response-model.md +++ b/docs/em/docs/tutorial/response-model.md @@ -4,29 +4,7 @@ 👆 💪 ⚙️ **🆎 ✍** 🎏 🌌 👆 🔜 🔢 💽 🔢 **🔢**, 👆 💪 ⚙️ Pydantic 🏷, 📇, 📖, 📊 💲 💖 🔢, 🎻, ♒️. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="18 23" -{!> ../../docs_src/response_model/tutorial001_01.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="18 23" -{!> ../../docs_src/response_model/tutorial001_01_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="16 21" -{!> ../../docs_src/response_model/tutorial001_01_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial001_01.py hl[18,23] *} FastAPI 🔜 ⚙️ 👉 📨 🆎: @@ -59,29 +37,7 @@ FastAPI 🔜 ⚙️ 👉 📨 🆎: * `@app.delete()` * ♒️. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="17 22 24-27" -{!> ../../docs_src/response_model/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="17 22 24-27" -{!> ../../docs_src/response_model/tutorial001_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="17 22 24-27" -{!> ../../docs_src/response_model/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial001.py hl[17,22,24:27] *} /// note @@ -113,21 +69,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** 📥 👥 📣 `UserIn` 🏷, ⚫️ 🔜 🔌 🔢 🔐: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9 11" -{!> ../../docs_src/response_model/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7 9" -{!> ../../docs_src/response_model/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial002.py hl[9,11] *} /// info @@ -140,21 +82,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** & 👥 ⚙️ 👉 🏷 📣 👆 🔢 & 🎏 🏷 📣 👆 🔢: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="18" -{!> ../../docs_src/response_model/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="16" -{!> ../../docs_src/response_model/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial002.py hl[18] *} 🔜, 🕐❔ 🖥 🏗 👩‍💻 ⏮️ 🔐, 🛠️ 🔜 📨 🎏 🔐 📨. @@ -172,57 +100,15 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** 👥 💪 ↩️ ✍ 🔢 🏷 ⏮️ 🔢 🔐 & 🔢 🏷 🍵 ⚫️: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9 11 16" -{!> ../../docs_src/response_model/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="9 11 16" -{!> ../../docs_src/response_model/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003.py hl[9,11,16] *} 📥, ✋️ 👆 *➡ 🛠️ 🔢* 🛬 🎏 🔢 👩‍💻 👈 🔌 🔐: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003.py hl[24] *} ...👥 📣 `response_model` 👆 🏷 `UserOut`, 👈 🚫 🔌 🔐: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="22" -{!> ../../docs_src/response_model/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="22" -{!> ../../docs_src/response_model/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003.py hl[22] *} , **FastAPI** 🔜 ✊ 💅 🖥 👅 🌐 💽 👈 🚫 📣 🔢 🏷 (⚙️ Pydantic). @@ -246,21 +132,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** & 👈 💼, 👥 💪 ⚙️ 🎓 & 🧬 ✊ 📈 🔢 **🆎 ✍** 🤚 👍 🐕‍🦺 👨‍🎨 & 🧰, & 🤚 FastAPI **💽 🖥**. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9-13 15-16 20" -{!> ../../docs_src/response_model/tutorial003_01.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7-10 13-14 18" -{!> ../../docs_src/response_model/tutorial003_01_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_01.py hl[9:13,15:16,20] *} ⏮️ 👉, 👥 🤚 🏭 🐕‍🦺, ⚪️➡️ 👨‍🎨 & ✍ 👉 📟 ☑ ⚖ 🆎, ✋️ 👥 🤚 💽 🖥 ⚪️➡️ FastAPI. @@ -302,9 +174,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 🏆 ⚠ 💼 🔜 [🛬 📨 🔗 🔬 ⏪ 🏧 🩺](../advanced/response-directly.md){.internal-link target=_blank}. -```Python hl_lines="8 10-11" -{!> ../../docs_src/response_model/tutorial003_02.py!} -``` +{* ../../docs_src/response_model/tutorial003_02.py hl[8,10:11] *} 👉 🙅 💼 🍵 🔁 FastAPI ↩️ 📨 🆎 ✍ 🎓 (⚖️ 🏿) `Response`. @@ -314,9 +184,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 👆 💪 ⚙️ 🏿 `Response` 🆎 ✍: -```Python hl_lines="8-9" -{!> ../../docs_src/response_model/tutorial003_03.py!} -``` +{* ../../docs_src/response_model/tutorial003_03.py hl[8:9] *} 👉 🔜 👷 ↩️ `RedirectResponse` 🏿 `Response`, & FastAPI 🔜 🔁 🍵 👉 🙅 💼. @@ -326,21 +194,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 🎏 🔜 🔨 🚥 👆 ✔️ 🕳 💖 🇪🇺 🖖 🎏 🆎 🌐❔ 1️⃣ ⚖️ 🌅 👫 🚫 ☑ Pydantic 🆎, 🖼 👉 🔜 ❌ 👶: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="10" -{!> ../../docs_src/response_model/tutorial003_04.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="8" -{!> ../../docs_src/response_model/tutorial003_04_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_04.py hl[10] *} ...👉 ❌ ↩️ 🆎 ✍ 🚫 Pydantic 🆎 & 🚫 👁 `Response` 🎓 ⚖️ 🏿, ⚫️ 🇪🇺 (🙆 2️⃣) 🖖 `Response` & `dict`. @@ -352,21 +206,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 👉 💼, 👆 💪 ❎ 📨 🏷 ⚡ ⚒ `response_model=None`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/response_model/tutorial003_05.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/response_model/tutorial003_05_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_05.py hl[9] *} 👉 🔜 ⚒ FastAPI 🚶 📨 🏷 ⚡ & 👈 🌌 👆 💪 ✔️ 🙆 📨 🆎 ✍ 👆 💪 🍵 ⚫️ 🤕 👆 FastAPI 🈸. 👶 @@ -374,29 +214,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 👆 📨 🏷 💪 ✔️ 🔢 💲, 💖: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="11 13-14" -{!> ../../docs_src/response_model/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="11 13-14" -{!> ../../docs_src/response_model/tutorial004_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="9 11-12" -{!> ../../docs_src/response_model/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial004.py hl[11,13:14] *} * `description: Union[str, None] = None` (⚖️ `str | None = None` 🐍 3️⃣.1️⃣0️⃣) ✔️ 🔢 `None`. * `tax: float = 10.5` ✔️ 🔢 `10.5`. @@ -410,29 +228,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 👆 💪 ⚒ *➡ 🛠️ 👨‍🎨* 🔢 `response_model_exclude_unset=True`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial004_py39.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="22" -{!> ../../docs_src/response_model/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial004.py hl[24] *} & 👈 🔢 💲 🏆 🚫 🔌 📨, 🕴 💲 🤙 ⚒. @@ -521,21 +317,7 @@ FastAPI 🙃 🥃 (🤙, Pydantic 🙃 🥃) 🤔 👈, ✋️ `description`, `t /// -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="31 37" -{!> ../../docs_src/response_model/tutorial005.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="29 35" -{!> ../../docs_src/response_model/tutorial005_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial005.py hl[31,37] *} /// tip @@ -549,21 +331,7 @@ FastAPI 🙃 🥃 (🤙, Pydantic 🙃 🥃) 🤔 👈, ✋️ `description`, `t 🚥 👆 💭 ⚙️ `set` & ⚙️ `list` ⚖️ `tuple` ↩️, FastAPI 🔜 🗜 ⚫️ `set` & ⚫️ 🔜 👷 ☑: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="31 37" -{!> ../../docs_src/response_model/tutorial006.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="29 35" -{!> ../../docs_src/response_model/tutorial006_py310.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial006.py hl[31,37] *} ## 🌃 diff --git a/docs/em/docs/tutorial/response-status-code.md b/docs/em/docs/tutorial/response-status-code.md index 478060326..413ceb916 100644 --- a/docs/em/docs/tutorial/response-status-code.md +++ b/docs/em/docs/tutorial/response-status-code.md @@ -8,9 +8,7 @@ * `@app.delete()` * ♒️. -```Python hl_lines="6" -{!../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} /// note @@ -76,9 +74,7 @@ FastAPI 💭 👉, & 🔜 🏭 🗄 🩺 👈 🇵🇸 📤 🙅‍♂ 📨 ➡️ 👀 ⏮️ 🖼 🔄: -```Python hl_lines="6" -{!../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} `201` 👔 📟 "✍". @@ -86,9 +82,7 @@ FastAPI 💭 👉, & 🔜 🏭 🗄 🩺 👈 🇵🇸 📤 🙅‍♂ 📨 👆 💪 ⚙️ 🏪 🔢 ⚪️➡️ `fastapi.status`. -```Python hl_lines="1 6" -{!../../docs_src/response_status_code/tutorial002.py!} -``` +{* ../../docs_src/response_status_code/tutorial002.py hl[1,6] *} 👫 🏪, 👫 🧑‍🤝‍🧑 🎏 🔢, ✋️ 👈 🌌 👆 💪 ⚙️ 👨‍🎨 📋 🔎 👫: diff --git a/docs/em/docs/tutorial/schema-extra-example.md b/docs/em/docs/tutorial/schema-extra-example.md index e4f877a8e..1bd314c51 100644 --- a/docs/em/docs/tutorial/schema-extra-example.md +++ b/docs/em/docs/tutorial/schema-extra-example.md @@ -8,21 +8,7 @@ 👆 💪 📣 `example` Pydantic 🏷 ⚙️ `Config` & `schema_extra`, 🔬 Pydantic 🩺: 🔗 🛃: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="15-23" -{!> ../../docs_src/schema_extra_example/tutorial001.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="13-21" -{!> ../../docs_src/schema_extra_example/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial001.py hl[15:23] *} 👈 ➕ ℹ 🔜 🚮-🔢 **🎻 🔗** 👈 🏷, & ⚫️ 🔜 ⚙️ 🛠️ 🩺. @@ -40,21 +26,7 @@ 👆 💪 ⚙️ 👉 🚮 `example` 🔠 🏑: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="4 10-13" -{!> ../../docs_src/schema_extra_example/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="2 8-11" -{!> ../../docs_src/schema_extra_example/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial002.py hl[4,10:13] *} /// warning @@ -80,21 +52,7 @@ 📥 👥 🚶‍♀️ `example` 📊 ⌛ `Body()`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="20-25" -{!> ../../docs_src/schema_extra_example/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="18-23" -{!> ../../docs_src/schema_extra_example/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial003.py hl[20:25] *} ### 🖼 🩺 🎚 @@ -115,21 +73,7 @@ * `value`: 👉 ☑ 🖼 🎦, ✅ `dict`. * `externalValue`: 🎛 `value`, 📛 ☝ 🖼. 👐 👉 5️⃣📆 🚫 🐕‍🦺 📚 🧰 `value`. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="21-47" -{!> ../../docs_src/schema_extra_example/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="19-45" -{!> ../../docs_src/schema_extra_example/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial004.py hl[21:47] *} ### 🖼 🩺 🎚 diff --git a/docs/em/docs/tutorial/security/first-steps.md b/docs/em/docs/tutorial/security/first-steps.md index 21c48757f..8fb459a65 100644 --- a/docs/em/docs/tutorial/security/first-steps.md +++ b/docs/em/docs/tutorial/security/first-steps.md @@ -20,9 +20,7 @@ 📁 🖼 📁 `main.py`: -```Python -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py *} ## 🏃 ⚫️ @@ -128,9 +126,7 @@ Oauth2️⃣ 🔧 👈 👩‍💻 ⚖️ 🛠️ 💪 🔬 💽 👈 🔓 👩 🕐❔ 👥 ✍ 👐 `OAuth2PasswordBearer` 🎓 👥 🚶‍♀️ `tokenUrl` 🔢. 👉 🔢 🔌 📛 👈 👩‍💻 (🕸 🏃 👩‍💻 🖥) 🔜 ⚙️ 📨 `username` & `password` ✔ 🤚 🤝. -```Python hl_lines="6" -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[6] *} /// tip @@ -168,9 +164,7 @@ oauth2_scheme(some, parameters) 🔜 👆 💪 🚶‍♀️ 👈 `oauth2_scheme` 🔗 ⏮️ `Depends`. -```Python hl_lines="10" -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[10] *} 👉 🔗 🔜 🚚 `str` 👈 🛠️ 🔢 `token` *➡ 🛠️ 🔢*. diff --git a/docs/em/docs/tutorial/security/get-current-user.md b/docs/em/docs/tutorial/security/get-current-user.md index 4e5b4ebfc..2f4a26f35 100644 --- a/docs/em/docs/tutorial/security/get-current-user.md +++ b/docs/em/docs/tutorial/security/get-current-user.md @@ -2,9 +2,7 @@ ⏮️ 📃 💂‍♂ ⚙️ (❔ 🧢 🔛 🔗 💉 ⚙️) 🤝 *➡ 🛠️ 🔢* `token` `str`: -```Python hl_lines="10" -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[10] *} ✋️ 👈 🚫 👈 ⚠. @@ -16,21 +14,7 @@ 🎏 🌌 👥 ⚙️ Pydantic 📣 💪, 👥 💪 ⚙️ ⚫️ 🙆 🙆: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="5 12-16" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="3 10-14" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial002.py hl[5,12:16] *} ## ✍ `get_current_user` 🔗 @@ -42,61 +26,19 @@ 🎏 👥 🔨 ⏭ *➡ 🛠️* 🔗, 👆 🆕 🔗 `get_current_user` 🔜 📨 `token` `str` ⚪️➡️ 🎧-🔗 `oauth2_scheme`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="25" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="23" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial002.py hl[25] *} ## 🤚 👩‍💻 `get_current_user` 🔜 ⚙️ (❌) 🚙 🔢 👥 ✍, 👈 ✊ 🤝 `str` & 📨 👆 Pydantic `User` 🏷: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="19-22 26-27" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="17-20 24-25" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial002.py hl[19:22,26:27] *} ## 💉 ⏮️ 👩‍💻 🔜 👥 💪 ⚙️ 🎏 `Depends` ⏮️ 👆 `get_current_user` *➡ 🛠️*: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="31" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="29" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial002.py hl[31] *} 👀 👈 👥 📣 🆎 `current_user` Pydantic 🏷 `User`. @@ -150,21 +92,7 @@ & 🌐 👉 💯 *➡ 🛠️* 💪 🤪 3️⃣ ⏸: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="30-32" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="28-30" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial002.py hl[30:32] *} ## 🌃 diff --git a/docs/em/docs/tutorial/security/oauth2-jwt.md b/docs/em/docs/tutorial/security/oauth2-jwt.md index 95fa58f71..ee7bc2d28 100644 --- a/docs/em/docs/tutorial/security/oauth2-jwt.md +++ b/docs/em/docs/tutorial/security/oauth2-jwt.md @@ -118,21 +118,7 @@ $ pip install "passlib[bcrypt]" & ➕1️⃣ 1️⃣ 🔓 & 📨 👩‍💻. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="7 48 55-56 59-60 69-75" -{!> ../../docs_src/security/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="6 47 54-55 58-59 68-74" -{!> ../../docs_src/security/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial004.py hl[7,48,55:56,59:60,69:75] *} /// note @@ -168,21 +154,7 @@ $ openssl rand -hex 32 ✍ 🚙 🔢 🏗 🆕 🔐 🤝. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="6 12-14 28-30 78-86" -{!> ../../docs_src/security/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="5 11-13 27-29 77-85" -{!> ../../docs_src/security/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial004.py hl[6,12:14,28:30,78:86] *} ## ℹ 🔗 @@ -192,21 +164,7 @@ $ openssl rand -hex 32 🚥 🤝 ❌, 📨 🇺🇸🔍 ❌ ▶️️ ↖️. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="89-106" -{!> ../../docs_src/security/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="88-105" -{!> ../../docs_src/security/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial004.py hl[89:106] *} ## ℹ `/token` *➡ 🛠️* @@ -214,21 +172,7 @@ $ openssl rand -hex 32 ✍ 🎰 🥙 🔐 🤝 & 📨 ⚫️. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="115-130" -{!> ../../docs_src/security/tutorial004.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="114-129" -{!> ../../docs_src/security/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial004.py hl[115:130] *} ### 📡 ℹ 🔃 🥙 "📄" `sub` diff --git a/docs/em/docs/tutorial/security/simple-oauth2.md b/docs/em/docs/tutorial/security/simple-oauth2.md index 43d928ce7..1fd513d48 100644 --- a/docs/em/docs/tutorial/security/simple-oauth2.md +++ b/docs/em/docs/tutorial/security/simple-oauth2.md @@ -52,21 +52,7 @@ Oauth2️⃣ 👫 🎻. 🥇, 🗄 `OAuth2PasswordRequestForm`, & ⚙️ ⚫️ 🔗 ⏮️ `Depends` *➡ 🛠️* `/token`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="4 76" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="2 74" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial003.py hl[4,76] *} `OAuth2PasswordRequestForm` 🎓 🔗 👈 📣 📨 💪 ⏮️: @@ -114,21 +100,7 @@ Oauth2️⃣ 🔌 🤙 *🚚* 🏑 `grant_type` ⏮️ 🔧 💲 `password`, ✋ ❌, 👥 ⚙️ ⚠ `HTTPException`: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="3 77-79" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="1 75-77" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial003.py hl[3,77:79] *} ### ✅ 🔐 @@ -154,21 +126,7 @@ Oauth2️⃣ 🔌 🤙 *🚚* 🏑 `grant_type` ⏮️ 🔧 💲 `password`, ✋ , 🧙‍♀ 🏆 🚫 💪 🔄 ⚙️ 👈 🎏 🔐 ➕1️⃣ ⚙️ (📚 👩‍💻 ⚙️ 🎏 🔐 🌐, 👉 🔜 ⚠). -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="80-83" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="78-81" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial003.py hl[80:83] *} #### 🔃 `**user_dict` @@ -210,21 +168,7 @@ UserInDB( /// -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="85" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="83" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial003.py hl[85] *} /// tip @@ -250,21 +194,7 @@ UserInDB( , 👆 🔗, 👥 🔜 🕴 🤚 👩‍💻 🚥 👩‍💻 🔀, ☑ 🔓, & 🦁: -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="58-66 69-72 90" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="55-64 67-70 88" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial003.py hl[58:66,69:72,90] *} /// info diff --git a/docs/em/docs/tutorial/sql-databases.md b/docs/em/docs/tutorial/sql-databases.md deleted file mode 100644 index 49162dd62..000000000 --- a/docs/em/docs/tutorial/sql-databases.md +++ /dev/null @@ -1,900 +0,0 @@ -# 🗄 (🔗) 💽 - -**FastAPI** 🚫 🚚 👆 ⚙️ 🗄 (🔗) 💽. - -✋️ 👆 💪 ⚙️ 🙆 🔗 💽 👈 👆 💚. - -📥 👥 🔜 👀 🖼 ⚙️ 🇸🇲. - -👆 💪 💪 🛠️ ⚫️ 🙆 💽 🐕‍🦺 🇸🇲, 💖: - -* ✳ -* ✳ -* 🗄 -* 🐸 -* 🤸‍♂ 🗄 💽, ♒️. - -👉 🖼, 👥 🔜 ⚙️ **🗄**, ↩️ ⚫️ ⚙️ 👁 📁 & 🐍 ✔️ 🛠️ 🐕‍🦺. , 👆 💪 📁 👉 🖼 & 🏃 ⚫️. - -⏪, 👆 🏭 🈸, 👆 💪 💚 ⚙️ 💽 💽 💖 **✳**. - -/// tip - -📤 🛂 🏗 🚂 ⏮️ **FastAPI** & **✳**, 🌐 ⚓️ 🔛 **☁**, 🔌 🕸 & 🌖 🧰: https://github.com/tiangolo/full-stack-fastapi-postgresql - -/// - -/// note - -👀 👈 📚 📟 🐩 `SQLAlchemy` 📟 👆 🔜 ⚙️ ⏮️ 🙆 🛠️. - - **FastAPI** 🎯 📟 🤪 🕧. - -/// - -## 🐜 - -**FastAPI** 👷 ⏮️ 🙆 💽 & 🙆 👗 🗃 💬 💽. - -⚠ ⚓ ⚙️ "🐜": "🎚-🔗 🗺" 🗃. - -🐜 ✔️ 🧰 🗜 ("*🗺*") 🖖 *🎚* 📟 & 💽 🏓 ("*🔗*"). - -⏮️ 🐜, 👆 🛎 ✍ 🎓 👈 🎨 🏓 🗄 💽, 🔠 🔢 🎓 🎨 🏓, ⏮️ 📛 & 🆎. - -🖼 🎓 `Pet` 💪 🎨 🗄 🏓 `pets`. - -& 🔠 *👐* 🎚 👈 🎓 🎨 ⏭ 💽. - -🖼 🎚 `orion_cat` (👐 `Pet`) 💪 ✔️ 🔢 `orion_cat.type`, 🏓 `type`. & 💲 👈 🔢 💪, ✅ `"cat"`. - -👫 🐜 ✔️ 🧰 ⚒ 🔗 ⚖️ 🔗 🖖 🏓 ⚖️ 👨‍💼. - -👉 🌌, 👆 💪 ✔️ 🔢 `orion_cat.owner` & 👨‍💼 🔜 🔌 💽 👉 🐶 👨‍💼, ✊ ⚪️➡️ 🏓 *👨‍💼*. - -, `orion_cat.owner.name` 💪 📛 (⚪️➡️ `name` 🏓 `owners` 🏓) 👉 🐶 👨‍💼. - -⚫️ 💪 ✔️ 💲 💖 `"Arquilian"`. - -& 🐜 🔜 🌐 👷 🤚 ℹ ⚪️➡️ 🔗 🏓 *👨‍💼* 🕐❔ 👆 🔄 🔐 ⚫️ ⚪️➡️ 👆 🐶 🎚. - -⚠ 🐜 🖼: ✳-🐜 (🍕 ✳ 🛠️), 🇸🇲 🐜 (🍕 🇸🇲, 🔬 🛠️) & 🏒 (🔬 🛠️), 👪 🎏. - -📥 👥 🔜 👀 ❔ 👷 ⏮️ **🇸🇲 🐜**. - -🎏 🌌 👆 💪 ⚙️ 🙆 🎏 🐜. - -/// tip - -📤 🌓 📄 ⚙️ 🏒 📥 🩺. - -/// - -## 📁 📊 - -👫 🖼, ➡️ 💬 👆 ✔️ 📁 📛 `my_super_project` 👈 🔌 🎧-📁 🤙 `sql_app` ⏮️ 📊 💖 👉: - -``` -. -└── sql_app - ├── __init__.py - ├── crud.py - ├── database.py - ├── main.py - ├── models.py - └── schemas.py -``` - -📁 `__init__.py` 🛁 📁, ✋️ ⚫️ 💬 🐍 👈 `sql_app` ⏮️ 🌐 🚮 🕹 (🐍 📁) 📦. - -🔜 ➡️ 👀 ⚫️❔ 🔠 📁/🕹 🔨. - -## ❎ `SQLAlchemy` - -🥇 👆 💪 ❎ `SQLAlchemy`: - -
- -```console -$ pip install sqlalchemy - ----> 100% -``` - -
- -## ✍ 🇸🇲 🍕 - -➡️ 🔗 📁 `sql_app/database.py`. - -### 🗄 🇸🇲 🍕 - -```Python hl_lines="1-3" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -### ✍ 💽 📛 🇸🇲 - -```Python hl_lines="5-6" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -👉 🖼, 👥 "🔗" 🗄 💽 (📂 📁 ⏮️ 🗄 💽). - -📁 🔜 🔎 🎏 📁 📁 `sql_app.db`. - -👈 ⚫️❔ 🏁 🍕 `./sql_app.db`. - -🚥 👆 ⚙️ **✳** 💽 ↩️, 👆 🔜 ✔️ ✍ ⏸: - -```Python -SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" -``` - -...& 🛠️ ⚫️ ⏮️ 👆 💽 📊 & 🎓 (📊 ✳, ✳ ⚖️ 🙆 🎏). - -/// tip - -👉 👑 ⏸ 👈 👆 🔜 ✔️ 🔀 🚥 👆 💚 ⚙️ 🎏 💽. - -/// - -### ✍ 🇸🇲 `engine` - -🥇 🔁 ✍ 🇸🇲 "🚒". - -👥 🔜 ⏪ ⚙️ 👉 `engine` 🎏 🥉. - -```Python hl_lines="8-10" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -#### 🗒 - -❌: - -```Python -connect_args={"check_same_thread": False} -``` - -...💪 🕴 `SQLite`. ⚫️ 🚫 💪 🎏 💽. - -/// info | 📡 ℹ - -🔢 🗄 🔜 🕴 ✔ 1️⃣ 🧵 🔗 ⏮️ ⚫️, 🤔 👈 🔠 🧵 🔜 🍵 🔬 📨. - -👉 ❎ 😫 🤝 🎏 🔗 🎏 👜 (🎏 📨). - -✋️ FastAPI, ⚙️ 😐 🔢 (`def`) 🌅 🌘 1️⃣ 🧵 💪 🔗 ⏮️ 💽 🎏 📨, 👥 💪 ⚒ 🗄 💭 👈 ⚫️ 🔜 ✔ 👈 ⏮️ `connect_args={"check_same_thread": False}`. - -, 👥 🔜 ⚒ 💭 🔠 📨 🤚 🚮 👍 💽 🔗 🎉 🔗, 📤 🙅‍♂ 💪 👈 🔢 🛠️. - -/// - -### ✍ `SessionLocal` 🎓 - -🔠 👐 `SessionLocal` 🎓 🔜 💽 🎉. 🎓 ⚫️ 🚫 💽 🎉. - -✋️ 🕐 👥 ✍ 👐 `SessionLocal` 🎓, 👉 👐 🔜 ☑ 💽 🎉. - -👥 📛 ⚫️ `SessionLocal` 🔬 ⚫️ ⚪️➡️ `Session` 👥 🏭 ⚪️➡️ 🇸🇲. - -👥 🔜 ⚙️ `Session` (1️⃣ 🗄 ⚪️➡️ 🇸🇲) ⏪. - -✍ `SessionLocal` 🎓, ⚙️ 🔢 `sessionmaker`: - -```Python hl_lines="11" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -### ✍ `Base` 🎓 - -🔜 👥 🔜 ⚙️ 🔢 `declarative_base()` 👈 📨 🎓. - -⏪ 👥 🔜 😖 ⚪️➡️ 👉 🎓 ✍ 🔠 💽 🏷 ⚖️ 🎓 (🐜 🏷): - -```Python hl_lines="13" -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -## ✍ 💽 🏷 - -➡️ 🔜 👀 📁 `sql_app/models.py`. - -### ✍ 🇸🇲 🏷 ⚪️➡️ `Base` 🎓 - -👥 🔜 ⚙️ 👉 `Base` 🎓 👥 ✍ ⏭ ✍ 🇸🇲 🏷. - -/// tip - -🇸🇲 ⚙️ ⚖ "**🏷**" 🔗 👉 🎓 & 👐 👈 🔗 ⏮️ 💽. - -✋️ Pydantic ⚙️ ⚖ "**🏷**" 🔗 🕳 🎏, 💽 🔬, 🛠️, & 🧾 🎓 & 👐. - -/// - -🗄 `Base` ⚪️➡️ `database` (📁 `database.py` ⚪️➡️ 🔛). - -✍ 🎓 👈 😖 ⚪️➡️ ⚫️. - -👫 🎓 🇸🇲 🏷. - -```Python hl_lines="4 7-8 18-19" -{!../../docs_src/sql_databases/sql_app/models.py!} -``` - -`__tablename__` 🔢 💬 🇸🇲 📛 🏓 ⚙️ 💽 🔠 👫 🏷. - -### ✍ 🏷 🔢/🏓 - -🔜 ✍ 🌐 🏷 (🎓) 🔢. - -🔠 👫 🔢 🎨 🏓 🚮 🔗 💽 🏓. - -👥 ⚙️ `Column` ⚪️➡️ 🇸🇲 🔢 💲. - -& 👥 🚶‍♀️ 🇸🇲 🎓 "🆎", `Integer`, `String`, & `Boolean`, 👈 🔬 🆎 💽, ❌. - -```Python hl_lines="1 10-13 21-24" -{!../../docs_src/sql_databases/sql_app/models.py!} -``` - -### ✍ 💛 - -🔜 ✍ 💛. - -👉, 👥 ⚙️ `relationship` 🚚 🇸🇲 🐜. - -👉 🔜 ▶️️, 🌅 ⚖️ 🌘, "🎱" 🔢 👈 🔜 🔌 💲 ⚪️➡️ 🎏 🏓 🔗 👉 1️⃣. - -```Python hl_lines="2 15 26" -{!../../docs_src/sql_databases/sql_app/models.py!} -``` - -🕐❔ 🔐 🔢 `items` `User`, `my_user.items`, ⚫️ 🔜 ✔️ 📇 `Item` 🇸🇲 🏷 (⚪️➡️ `items` 🏓) 👈 ✔️ 💱 🔑 ☝ 👉 ⏺ `users` 🏓. - -🕐❔ 👆 🔐 `my_user.items`, 🇸🇲 🔜 🤙 🚶 & ☕ 🏬 ⚪️➡️ 💽 `items` 🏓 & 🔗 👫 📥. - -& 🕐❔ 🔐 🔢 `owner` `Item`, ⚫️ 🔜 🔌 `User` 🇸🇲 🏷 ⚪️➡️ `users` 🏓. ⚫️ 🔜 ⚙️ `owner_id` 🔢/🏓 ⏮️ 🚮 💱 🔑 💭 ❔ ⏺ 🤚 ⚪️➡️ `users` 🏓. - -## ✍ Pydantic 🏷 - -🔜 ➡️ ✅ 📁 `sql_app/schemas.py`. - -/// tip - -❎ 😨 🖖 🇸🇲 *🏷* & Pydantic *🏷*, 👥 🔜 ✔️ 📁 `models.py` ⏮️ 🇸🇲 🏷, & 📁 `schemas.py` ⏮️ Pydantic 🏷. - -👫 Pydantic 🏷 🔬 🌅 ⚖️ 🌘 "🔗" (☑ 📊 💠). - -👉 🔜 ℹ 👥 ❎ 😨 ⏪ ⚙️ 👯‍♂️. - -/// - -### ✍ ▶️ Pydantic *🏷* / 🔗 - -✍ `ItemBase` & `UserBase` Pydantic *🏷* (⚖️ ➡️ 💬 "🔗") ✔️ ⚠ 🔢 ⏪ 🏗 ⚖️ 👂 📊. - -& ✍ `ItemCreate` & `UserCreate` 👈 😖 ⚪️➡️ 👫 (👫 🔜 ✔️ 🎏 🔢), ➕ 🙆 🌖 📊 (🔢) 💪 🏗. - -, 👩‍💻 🔜 ✔️ `password` 🕐❔ 🏗 ⚫️. - -✋️ 💂‍♂, `password` 🏆 🚫 🎏 Pydantic *🏷*, 🖼, ⚫️ 🏆 🚫 📨 ⚪️➡️ 🛠️ 🕐❔ 👂 👩‍💻. - -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="3 6-8 11-12 23-24 27-28" -{!> ../../docs_src/sql_databases/sql_app/schemas.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="3 6-8 11-12 23-24 27-28" -{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="1 4-6 9-10 21-22 25-26" -{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} -``` - -//// - -#### 🇸🇲 👗 & Pydantic 👗 - -👀 👈 🇸🇲 *🏷* 🔬 🔢 ⚙️ `=`, & 🚶‍♀️ 🆎 🔢 `Column`, 💖: - -```Python -name = Column(String) -``` - -⏪ Pydantic *🏷* 📣 🆎 ⚙️ `:`, 🆕 🆎 ✍ ❕/🆎 🔑: - -```Python -name: str -``` - -✔️ ⚫️ 🤯, 👆 🚫 🤚 😕 🕐❔ ⚙️ `=` & `:` ⏮️ 👫. - -### ✍ Pydantic *🏷* / 🔗 👂 / 📨 - -🔜 ✍ Pydantic *🏷* (🔗) 👈 🔜 ⚙️ 🕐❔ 👂 💽, 🕐❔ 🛬 ⚫️ ⚪️➡️ 🛠️. - -🖼, ⏭ 🏗 🏬, 👥 🚫 💭 ⚫️❔ 🔜 🆔 🛠️ ⚫️, ✋️ 🕐❔ 👂 ⚫️ (🕐❔ 🛬 ⚫️ ⚪️➡️ 🛠️) 👥 🔜 ⏪ 💭 🚮 🆔. - -🎏 🌌, 🕐❔ 👂 👩‍💻, 👥 💪 🔜 📣 👈 `items` 🔜 🔌 🏬 👈 💭 👉 👩‍💻. - -🚫 🕴 🆔 📚 🏬, ✋️ 🌐 💽 👈 👥 🔬 Pydantic *🏷* 👂 🏬: `Item`. - -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="15-17 31-34" -{!> ../../docs_src/sql_databases/sql_app/schemas.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="15-17 31-34" -{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="13-15 29-32" -{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} -``` - -//// - -/// tip - -👀 👈 `User`, Pydantic *🏷* 👈 🔜 ⚙️ 🕐❔ 👂 👩‍💻 (🛬 ⚫️ ⚪️➡️ 🛠️) 🚫 🔌 `password`. - -/// - -### ⚙️ Pydantic `orm_mode` - -🔜, Pydantic *🏷* 👂, `Item` & `User`, 🚮 🔗 `Config` 🎓. - -👉 `Config` 🎓 ⚙️ 🚚 📳 Pydantic. - -`Config` 🎓, ⚒ 🔢 `orm_mode = True`. - -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="15 19-20 31 36-37" -{!> ../../docs_src/sql_databases/sql_app/schemas.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="15 19-20 31 36-37" -{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python hl_lines="13 17-18 29 34-35" -{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} -``` - -//// - -/// tip - -👀 ⚫️ ⚖ 💲 ⏮️ `=`, 💖: - -`orm_mode = True` - -⚫️ 🚫 ⚙️ `:` 🆎 📄 ⏭. - -👉 ⚒ 📁 💲, 🚫 📣 🆎. - -/// - -Pydantic `orm_mode` 🔜 💬 Pydantic *🏷* ✍ 💽 🚥 ⚫️ 🚫 `dict`, ✋️ 🐜 🏷 (⚖️ 🙆 🎏 ❌ 🎚 ⏮️ 🔢). - -👉 🌌, ↩️ 🕴 🔄 🤚 `id` 💲 ⚪️➡️ `dict`,: - -```Python -id = data["id"] -``` - -⚫️ 🔜 🔄 🤚 ⚫️ ⚪️➡️ 🔢,: - -```Python -id = data.id -``` - -& ⏮️ 👉, Pydantic *🏷* 🔗 ⏮️ 🐜, & 👆 💪 📣 ⚫️ `response_model` ❌ 👆 *➡ 🛠️*. - -👆 🔜 💪 📨 💽 🏷 & ⚫️ 🔜 ✍ 💽 ⚪️➡️ ⚫️. - -#### 📡 ℹ 🔃 🐜 📳 - -🇸🇲 & 📚 🎏 🔢 "🙃 🚚". - -👈 ⛓, 🖼, 👈 👫 🚫 ☕ 💽 💛 ⚪️➡️ 💽 🚥 👆 🔄 🔐 🔢 👈 🔜 🔌 👈 💽. - -🖼, 🔐 🔢 `items`: - -```Python -current_user.items -``` - -🔜 ⚒ 🇸🇲 🚶 `items` 🏓 & 🤚 🏬 👉 👩‍💻, ✋️ 🚫 ⏭. - -🍵 `orm_mode`, 🚥 👆 📨 🇸🇲 🏷 ⚪️➡️ 👆 *➡ 🛠️*, ⚫️ 🚫🔜 🔌 💛 💽. - -🚥 👆 📣 📚 💛 👆 Pydantic 🏷. - -✋️ ⏮️ 🐜 📳, Pydantic ⚫️ 🔜 🔄 🔐 💽 ⚫️ 💪 ⚪️➡️ 🔢 (↩️ 🤔 `dict`), 👆 💪 📣 🎯 💽 👆 💚 📨 & ⚫️ 🔜 💪 🚶 & 🤚 ⚫️, ⚪️➡️ 🐜. - -## 💩 🇨🇻 - -🔜 ➡️ 👀 📁 `sql_app/crud.py`. - -👉 📁 👥 🔜 ✔️ ♻ 🔢 🔗 ⏮️ 💽 💽. - -**💩** 👟 ⚪️➡️: **🅱**📧, **Ⓜ**💳, **👤** = , & **🇨🇮**📧. - -...👐 👉 🖼 👥 🕴 🏗 & 👂. - -### ✍ 💽 - -🗄 `Session` ⚪️➡️ `sqlalchemy.orm`, 👉 🔜 ✔ 👆 📣 🆎 `db` 🔢 & ✔️ 👻 🆎 ✅ & 🛠️ 👆 🔢. - -🗄 `models` (🇸🇲 🏷) & `schemas` (Pydantic *🏷* / 🔗). - -✍ 🚙 🔢: - -* ✍ 👁 👩‍💻 🆔 & 📧. -* ✍ 💗 👩‍💻. -* ✍ 💗 🏬. - -```Python hl_lines="1 3 6-7 10-11 14-15 27-28" -{!../../docs_src/sql_databases/sql_app/crud.py!} -``` - -/// tip - -🏗 🔢 👈 🕴 💡 🔗 ⏮️ 💽 (🤚 👩‍💻 ⚖️ 🏬) 🔬 👆 *➡ 🛠️ 🔢*, 👆 💪 🌖 💪 ♻ 👫 💗 🍕 & 🚮 ⚒ 💯 👫. - -/// - -### ✍ 💽 - -🔜 ✍ 🚙 🔢 ✍ 💽. - -🔁: - -* ✍ 🇸🇲 🏷 *👐* ⏮️ 👆 📊. -* `add` 👈 👐 🎚 👆 💽 🎉. -* `commit` 🔀 💽 (👈 👫 🖊). -* `refresh` 👆 👐 (👈 ⚫️ 🔌 🙆 🆕 📊 ⚪️➡️ 💽, 💖 🏗 🆔). - -```Python hl_lines="18-24 31-36" -{!../../docs_src/sql_databases/sql_app/crud.py!} -``` - -/// tip - -🇸🇲 🏷 `User` 🔌 `hashed_password` 👈 🔜 🔌 🔐 #️⃣ ⏬ 🔐. - -✋️ ⚫️❔ 🛠️ 👩‍💻 🚚 ⏮️ 🔐, 👆 💪 ⚗ ⚫️ & 🏗 #️⃣ 🔐 👆 🈸. - - & ⤴️ 🚶‍♀️ `hashed_password` ❌ ⏮️ 💲 🖊. - -/// - -/// warning - -👉 🖼 🚫 🔐, 🔐 🚫#️⃣. - -🎰 👨‍❤‍👨 🈸 👆 🔜 💪 #️⃣ 🔐 & 🙅 🖊 👫 🔢. - -🌅 ℹ, 🚶 🔙 💂‍♂ 📄 🔰. - -📥 👥 🎯 🕴 🔛 🧰 & 👨‍🔧 💽. - -/// - -/// tip - -↩️ 🚶‍♀️ 🔠 🇨🇻 ❌ `Item` & 👂 🔠 1️⃣ 👫 ⚪️➡️ Pydantic *🏷*, 👥 🏭 `dict` ⏮️ Pydantic *🏷*'Ⓜ 📊 ⏮️: - -`item.dict()` - - & ⤴️ 👥 🚶‍♀️ `dict`'Ⓜ 🔑-💲 👫 🇨🇻 ❌ 🇸🇲 `Item`, ⏮️: - -`Item(**item.dict())` - - & ⤴️ 👥 🚶‍♀️ ➕ 🇨🇻 ❌ `owner_id` 👈 🚫 🚚 Pydantic *🏷*, ⏮️: - -`Item(**item.dict(), owner_id=user_id)` - -/// - -## 👑 **FastAPI** 📱 - -& 🔜 📁 `sql_app/main.py` ➡️ 🛠️ & ⚙️ 🌐 🎏 🍕 👥 ✍ ⏭. - -### ✍ 💽 🏓 - -📶 🙃 🌌 ✍ 💽 🏓: - -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="9" -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="7" -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` - -//// - -#### ⚗ 🗒 - -🛎 👆 🔜 🎲 🔢 👆 💽 (✍ 🏓, ♒️) ⏮️ . - -& 👆 🔜 ⚙️ ⚗ "🛠️" (👈 🚮 👑 👨‍🏭). - -"🛠️" ⚒ 🔁 💪 🕐❔ 👆 🔀 📊 👆 🇸🇲 🏷, 🚮 🆕 🔢, ♒️. 🔁 👈 🔀 💽, 🚮 🆕 🏓, 🆕 🏓, ♒️. - -👆 💪 🔎 🖼 ⚗ FastAPI 🏗 📄 ⚪️➡️ [🏗 ⚡ - 📄](../project-generation.md){.internal-link target=_blank}. 🎯 `alembic` 📁 ℹ 📟. - -### ✍ 🔗 - -🔜 ⚙️ `SessionLocal` 🎓 👥 ✍ `sql_app/database.py` 📁 ✍ 🔗. - -👥 💪 ✔️ 🔬 💽 🎉/🔗 (`SessionLocal`) 📍 📨, ⚙️ 🎏 🎉 🔘 🌐 📨 & ⤴️ 🔐 ⚫️ ⏮️ 📨 🏁. - -& ⤴️ 🆕 🎉 🔜 ✍ ⏭ 📨. - -👈, 👥 🔜 ✍ 🆕 🔗 ⏮️ `yield`, 🔬 ⏭ 📄 🔃 [🔗 ⏮️ `yield`](dependencies/dependencies-with-yield.md){.internal-link target=_blank}. - -👆 🔗 🔜 ✍ 🆕 🇸🇲 `SessionLocal` 👈 🔜 ⚙️ 👁 📨, & ⤴️ 🔐 ⚫️ 🕐 📨 🏁. - -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="15-20" -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="13-18" -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` - -//// - -/// info - -👥 🚮 🏗 `SessionLocal()` & 🚚 📨 `try` 🍫. - - & ⤴️ 👥 🔐 ⚫️ `finally` 🍫. - -👉 🌌 👥 ⚒ 💭 💽 🎉 🕧 📪 ⏮️ 📨. 🚥 📤 ⚠ ⏪ 🏭 📨. - -✋️ 👆 💪 🚫 🤚 ➕1️⃣ ⚠ ⚪️➡️ 🚪 📟 (⏮️ `yield`). 👀 🌖 [🔗 ⏮️ `yield` & `HTTPException`](dependencies/dependencies-with-yield.md#yield-httpexception){.internal-link target=_blank} - -/// - -& ⤴️, 🕐❔ ⚙️ 🔗 *➡ 🛠️ 🔢*, 👥 📣 ⚫️ ⏮️ 🆎 `Session` 👥 🗄 🔗 ⚪️➡️ 🇸🇲. - -👉 🔜 ⤴️ 🤝 👥 👍 👨‍🎨 🐕‍🦺 🔘 *➡ 🛠️ 🔢*, ↩️ 👨‍🎨 🔜 💭 👈 `db` 🔢 🆎 `Session`: - -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="24 32 38 47 53" -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="22 30 36 45 51" -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` - -//// - -/// info | 📡 ℹ - -🔢 `db` 🤙 🆎 `SessionLocal`, ✋️ 👉 🎓 (✍ ⏮️ `sessionmaker()`) "🗳" 🇸🇲 `Session`,, 👨‍🎨 🚫 🤙 💭 ⚫️❔ 👩‍🔬 🚚. - -✋️ 📣 🆎 `Session`, 👨‍🎨 🔜 💪 💭 💪 👩‍🔬 (`.add()`, `.query()`, `.commit()`, ♒️) & 💪 🚚 👍 🐕‍🦺 (💖 🛠️). 🆎 📄 🚫 📉 ☑ 🎚. - -/// - -### ✍ 👆 **FastAPI** *➡ 🛠️* - -🔜, 😒, 📥 🐩 **FastAPI** *➡ 🛠️* 📟. - -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="23-28 31-34 37-42 45-49 52-55" -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="21-26 29-32 35-40 43-47 50-53" -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` - -//// - -👥 🏗 💽 🎉 ⏭ 🔠 📨 🔗 ⏮️ `yield`, & ⤴️ 📪 ⚫️ ⏮️. - -& ⤴️ 👥 💪 ✍ 🚚 🔗 *➡ 🛠️ 🔢*, 🤚 👈 🎉 🔗. - -⏮️ 👈, 👥 💪 🤙 `crud.get_user` 🔗 ⚪️➡️ 🔘 *➡ 🛠️ 🔢* & ⚙️ 👈 🎉. - -/// tip - -👀 👈 💲 👆 📨 🇸🇲 🏷, ⚖️ 📇 🇸🇲 🏷. - -✋️ 🌐 *➡ 🛠️* ✔️ `response_model` ⏮️ Pydantic *🏷* / 🔗 ⚙️ `orm_mode`, 💽 📣 👆 Pydantic 🏷 🔜 ⚗ ⚪️➡️ 👫 & 📨 👩‍💻, ⏮️ 🌐 😐 ⛽ & 🔬. - -/// - -/// tip - -👀 👈 📤 `response_models` 👈 ✔️ 🐩 🐍 🆎 💖 `List[schemas.Item]`. - -✋️ 🎚/🔢 👈 `List` Pydantic *🏷* ⏮️ `orm_mode`, 💽 🔜 🗃 & 📨 👩‍💻 🛎, 🍵 ⚠. - -/// - -### 🔃 `def` 🆚 `async def` - -📥 👥 ⚙️ 🇸🇲 📟 🔘 *➡ 🛠️ 🔢* & 🔗, &, 🔄, ⚫️ 🔜 🚶 & 🔗 ⏮️ 🔢 💽. - -👈 💪 ⚠ 🚚 "⌛". - -✋️ 🇸🇲 🚫 ✔️ 🔗 ⚙️ `await` 🔗, 🔜 ⏮️ 🕳 💖: - -```Python -user = await db.query(User).first() -``` - -...& ↩️ 👥 ⚙️: - -```Python -user = db.query(User).first() -``` - -⤴️ 👥 🔜 📣 *➡ 🛠️ 🔢* & 🔗 🍵 `async def`, ⏮️ 😐 `def`,: - -```Python hl_lines="2" -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - ... -``` - -/// info - -🚥 👆 💪 🔗 👆 🔗 💽 🔁, 👀 [🔁 🗄 (🔗) 💽](../advanced/async-sql-databases.md){.internal-link target=_blank}. - -/// - -/// note | 📶 📡 ℹ - -🚥 👆 😟 & ✔️ ⏬ 📡 💡, 👆 💪 ✅ 📶 📡 ℹ ❔ 👉 `async def` 🆚 `def` 🍵 [🔁](../async.md#i_2){.internal-link target=_blank} 🩺. - -/// - -## 🛠️ - -↩️ 👥 ⚙️ 🇸🇲 🔗 & 👥 🚫 🚚 🙆 😇 🔌-⚫️ 👷 ⏮️ **FastAPI**, 👥 💪 🛠️ 💽 🛠️ ⏮️ 🔗. - -& 📟 🔗 🇸🇲 & 🇸🇲 🏷 🖖 🎏 🔬 📁, 👆 🔜 💪 🎭 🛠️ ⏮️ ⚗ 🍵 ✔️ ❎ FastAPI, Pydantic, ⚖️ 🕳 🙆. - -🎏 🌌, 👆 🔜 💪 ⚙️ 🎏 🇸🇲 🏷 & 🚙 🎏 🍕 👆 📟 👈 🚫 🔗 **FastAPI**. - -🖼, 🖥 📋 👨‍🏭 ⏮️ 🥒, 🅿, ⚖️ 📶. - -## 📄 🌐 📁 - - 💭 👆 🔜 ✔️ 📁 📛 `my_super_project` 👈 🔌 🎧-📁 🤙 `sql_app`. - -`sql_app` 🔜 ✔️ 📄 📁: - -* `sql_app/__init__.py`: 🛁 📁. - -* `sql_app/database.py`: - -```Python -{!../../docs_src/sql_databases/sql_app/database.py!} -``` - -* `sql_app/models.py`: - -```Python -{!../../docs_src/sql_databases/sql_app/models.py!} -``` - -* `sql_app/schemas.py`: - -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python -{!> ../../docs_src/sql_databases/sql_app/schemas.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python -{!> ../../docs_src/sql_databases/sql_app_py39/schemas.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python -{!> ../../docs_src/sql_databases/sql_app_py310/schemas.py!} -``` - -//// - -* `sql_app/crud.py`: - -```Python -{!../../docs_src/sql_databases/sql_app/crud.py!} -``` - -* `sql_app/main.py`: - -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python -{!> ../../docs_src/sql_databases/sql_app/main.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python -{!> ../../docs_src/sql_databases/sql_app_py39/main.py!} -``` - -//// - -## ✅ ⚫️ - -👆 💪 📁 👉 📟 & ⚙️ ⚫️. - -/// info - -👐, 📟 🎦 📥 🍕 💯. 🌅 📟 👉 🩺. - -/// - -⤴️ 👆 💪 🏃 ⚫️ ⏮️ Uvicorn: - - -
- -```console -$ uvicorn sql_app.main:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -& ⤴️, 👆 💪 📂 👆 🖥 http://127.0.0.1:8000/docs. - -& 👆 🔜 💪 🔗 ⏮️ 👆 **FastAPI** 🈸, 👂 📊 ⚪️➡️ 🎰 💽: - - - -## 🔗 ⏮️ 💽 🔗 - -🚥 👆 💚 🔬 🗄 💽 (📁) 🔗, ➡ FastAPI, ℹ 🚮 🎚, 🚮 🏓, 🏓, ⏺, 🔀 📊, ♒️. 👆 💪 ⚙️ 💽 🖥 🗄. - -⚫️ 🔜 👀 💖 👉: - - - -👆 💪 ⚙️ 💳 🗄 🖥 💖 🗄 📋 ⚖️ ExtendsClass. - -## 🎛 💽 🎉 ⏮️ 🛠️ - -🚥 👆 💪 🚫 ⚙️ 🔗 ⏮️ `yield` - 🖼, 🚥 👆 🚫 ⚙️ **🐍 3️⃣.7️⃣** & 💪 🚫 ❎ "🐛" 🤔 🔛 **🐍 3️⃣.6️⃣** - 👆 💪 ⚒ 🆙 🎉 "🛠️" 🎏 🌌. - -"🛠️" 🌖 🔢 👈 🕧 🛠️ 🔠 📨, ⏮️ 📟 🛠️ ⏭, & 📟 🛠️ ⏮️ 🔗 🔢. - -### ✍ 🛠️ - -🛠️ 👥 🔜 🚮 (🔢) 🔜 ✍ 🆕 🇸🇲 `SessionLocal` 🔠 📨, 🚮 ⚫️ 📨 & ⤴️ 🔐 ⚫️ 🕐 📨 🏁. - -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python hl_lines="14-22" -{!> ../../docs_src/sql_databases/sql_app/alt_main.py!} -``` - -//// - -//// tab | 🐍 3️⃣.9️⃣ & 🔛 - -```Python hl_lines="12-20" -{!> ../../docs_src/sql_databases/sql_app_py39/alt_main.py!} -``` - -//// - -/// info - -👥 🚮 🏗 `SessionLocal()` & 🚚 📨 `try` 🍫. - - & ⤴️ 👥 🔐 ⚫️ `finally` 🍫. - -👉 🌌 👥 ⚒ 💭 💽 🎉 🕧 📪 ⏮️ 📨. 🚥 📤 ⚠ ⏪ 🏭 📨. - -/// - -### 🔃 `request.state` - -`request.state` 🏠 🔠 `Request` 🎚. ⚫️ 📤 🏪 ❌ 🎚 📎 📨 ⚫️, 💖 💽 🎉 👉 💼. 👆 💪 ✍ 🌅 🔃 ⚫️ 💃 🩺 🔃 `Request` 🇵🇸. - -👥 👉 💼, ⚫️ ℹ 👥 🚚 👁 💽 🎉 ⚙️ 🔘 🌐 📨, & ⤴️ 🔐 ⏮️ (🛠️). - -### 🔗 ⏮️ `yield` ⚖️ 🛠️ - -❎ **🛠️** 📥 🎏 ⚫️❔ 🔗 ⏮️ `yield` 🔨, ⏮️ 🔺: - -* ⚫️ 🚚 🌖 📟 & 👄 🌅 🏗. -* 🛠️ ✔️ `async` 🔢. - * 🚥 📤 📟 ⚫️ 👈 ✔️ "⌛" 🕸, ⚫️ 💪 "🍫" 👆 🈸 📤 & 📉 🎭 🍖. - * 👐 ⚫️ 🎲 🚫 📶 ⚠ 📥 ⏮️ 🌌 `SQLAlchemy` 👷. - * ✋️ 🚥 👆 🚮 🌖 📟 🛠️ 👈 ✔️ 📚 👤/🅾 ⌛, ⚫️ 💪 ⤴️ ⚠. -* 🛠️ 🏃 *🔠* 📨. - * , 🔗 🔜 ✍ 🔠 📨. - * 🕐❔ *➡ 🛠️* 👈 🍵 👈 📨 🚫 💪 💽. - -/// tip - -⚫️ 🎲 👍 ⚙️ 🔗 ⏮️ `yield` 🕐❔ 👫 🥃 ⚙️ 💼. - -/// - -/// info - -🔗 ⏮️ `yield` 🚮 ⏳ **FastAPI**. - -⏮️ ⏬ 👉 🔰 🕴 ✔️ 🖼 ⏮️ 🛠️ & 📤 🎲 📚 🈸 ⚙️ 🛠️ 💽 🎉 🧾. - -/// diff --git a/docs/em/docs/tutorial/static-files.md b/docs/em/docs/tutorial/static-files.md index c9bb9ff6a..6ff6e37a9 100644 --- a/docs/em/docs/tutorial/static-files.md +++ b/docs/em/docs/tutorial/static-files.md @@ -7,9 +7,7 @@ * 🗄 `StaticFiles`. * "🗻" `StaticFiles()` 👐 🎯 ➡. -```Python hl_lines="2 6" -{!../../docs_src/static_files/tutorial001.py!} -``` +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} /// note | 📡 ℹ diff --git a/docs/em/docs/tutorial/testing.md b/docs/em/docs/tutorial/testing.md index 27cf9f16e..cb4a1ca21 100644 --- a/docs/em/docs/tutorial/testing.md +++ b/docs/em/docs/tutorial/testing.md @@ -26,9 +26,7 @@ ✍ 🙅 `assert` 📄 ⏮️ 🐩 🐍 🧬 👈 👆 💪 ✅ (🔄, 🐩 `pytest`). -```Python hl_lines="2 12 15-18" -{!../../docs_src/app_testing/tutorial001.py!} -``` +{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *} /// tip @@ -74,9 +72,7 @@ 📁 `main.py` 👆 ✔️ 👆 **FastAPI** 📱: -```Python -{!../../docs_src/app_testing/main.py!} -``` +{* ../../docs_src/app_testing/main.py *} ### 🔬 📁 @@ -92,9 +88,7 @@ ↩️ 👉 📁 🎏 📦, 👆 💪 ⚙️ ⚖ 🗄 🗄 🎚 `app` ⚪️➡️ `main` 🕹 (`main.py`): -```Python hl_lines="3" -{!../../docs_src/app_testing/test_main.py!} -``` +{* ../../docs_src/app_testing/test_main.py hl[3] *} ...& ✔️ 📟 💯 💖 ⏭. @@ -122,29 +116,13 @@ 👯‍♂️ *➡ 🛠️* 🚚 `X-Token` 🎚. -//// tab | 🐍 3️⃣.6️⃣ & 🔛 - -```Python -{!> ../../docs_src/app_testing/app_b/main.py!} -``` - -//// - -//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - -```Python -{!> ../../docs_src/app_testing/app_b_py310/main.py!} -``` - -//// +{* ../../docs_src/app_testing/app_b/main.py *} ### ↔ 🔬 📁 👆 💪 ⤴️ ℹ `test_main.py` ⏮️ ↔ 💯: -```Python -{!> ../../docs_src/app_testing/app_b/test_main.py!} -``` +{* ../../docs_src/app_testing/app_b/test_main.py *} 🕐❔ 👆 💪 👩‍💻 🚶‍♀️ ℹ 📨 & 👆 🚫 💭 ❔, 👆 💪 🔎 (🇺🇸🔍) ❔ ⚫️ `httpx`, ⚖️ ❔ ⚫️ ⏮️ `requests`, 🇸🇲 🔧 ⚓️ 🔛 📨' 🔧. diff --git a/docs/en/docs/advanced/generate-clients.md b/docs/en/docs/advanced/generate-clients.md index fe4194ac7..3b9dc83f0 100644 --- a/docs/en/docs/advanced/generate-clients.md +++ b/docs/en/docs/advanced/generate-clients.md @@ -206,13 +206,7 @@ But for the generated client we could **modify** the OpenAPI operation IDs right We could download the OpenAPI JSON to a file `openapi.json` and then we could **remove that prefixed tag** with a script like this: -//// tab | Python - -```Python -{!> ../../docs_src/generate_clients/tutorial004.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial004.py *} //// tab | Node.js diff --git a/docs/en/docs/advanced/settings.md b/docs/en/docs/advanced/settings.md index 01810c438..1af19a045 100644 --- a/docs/en/docs/advanced/settings.md +++ b/docs/en/docs/advanced/settings.md @@ -62,9 +62,7 @@ You can use all the same validation features and tools you use for Pydantic mode //// tab | Pydantic v2 -```Python hl_lines="2 5-8 11" -{!> ../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[2,5:8,11] *} //// @@ -76,9 +74,7 @@ In Pydantic v1 you would import `BaseSettings` directly from `pydantic` instead /// -```Python hl_lines="2 5-8 11" -{!> ../../docs_src/settings/tutorial001_pv1.py!} -``` +{* ../../docs_src/settings/tutorial001_pv1.py hl[2,5:8,11] *} //// @@ -96,9 +92,7 @@ Next it will convert and validate the data. So, when you use that `settings` obj Then you can use the new `settings` object in your application: -```Python hl_lines="18-20" -{!../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[18:20] *} ### Run the server @@ -132,15 +126,11 @@ You could put those settings in another module file as you saw in [Bigger Applic For example, you could have a file `config.py` with: -```Python -{!../../docs_src/settings/app01/config.py!} -``` +{* ../../docs_src/settings/app01/config.py *} And then use it in a file `main.py`: -```Python hl_lines="3 11-13" -{!../../docs_src/settings/app01/main.py!} -``` +{* ../../docs_src/settings/app01/main.py hl[3,11:13] *} /// tip @@ -158,9 +148,7 @@ This could be especially useful during testing, as it's very easy to override a Coming from the previous example, your `config.py` file could look like: -```Python hl_lines="10" -{!../../docs_src/settings/app02/config.py!} -``` +{* ../../docs_src/settings/app02/config.py hl[10] *} Notice that now we don't create a default instance `settings = Settings()`. @@ -168,35 +156,7 @@ Notice that now we don't create a default instance `settings = Settings()`. Now we create a dependency that returns a new `config.Settings()`. -//// tab | Python 3.9+ - -```Python hl_lines="6 12-13" -{!> ../../docs_src/settings/app02_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="6 12-13" -{!> ../../docs_src/settings/app02_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="5 11-12" -{!> ../../docs_src/settings/app02/main.py!} -``` - -//// +{* ../../docs_src/settings/app02_an_py39/main.py hl[6,12:13] *} /// tip @@ -208,43 +168,13 @@ For now you can assume `get_settings()` is a normal function. And then we can require it from the *path operation function* as a dependency and use it anywhere we need it. -//// tab | Python 3.9+ - -```Python hl_lines="17 19-21" -{!> ../../docs_src/settings/app02_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17 19-21" -{!> ../../docs_src/settings/app02_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="16 18-20" -{!> ../../docs_src/settings/app02/main.py!} -``` - -//// +{* ../../docs_src/settings/app02_an_py39/main.py hl[17,19:21] *} ### Settings and testing Then it would be very easy to provide a different settings object during testing by creating a dependency override for `get_settings`: -```Python hl_lines="9-10 13 21" -{!../../docs_src/settings/app02/test_main.py!} -``` +{* ../../docs_src/settings/app02/test_main.py hl[9:10,13,21] *} In the dependency override we set a new value for the `admin_email` when creating the new `Settings` object, and then we return that new object. @@ -287,9 +217,7 @@ And then update your `config.py` with: //// tab | Pydantic v2 -```Python hl_lines="9" -{!> ../../docs_src/settings/app03_an/config.py!} -``` +{* ../../docs_src/settings/app03_an/config.py hl[9] *} /// tip @@ -301,9 +229,7 @@ The `model_config` attribute is used just for Pydantic configuration. You can re //// tab | Pydantic v1 -```Python hl_lines="9-10" -{!> ../../docs_src/settings/app03_an/config_pv1.py!} -``` +{* ../../docs_src/settings/app03_an/config_pv1.py hl[9:10] *} /// tip @@ -344,35 +270,7 @@ we would create that object for each request, and we would be reading the `.env` But as we are using the `@lru_cache` decorator on top, the `Settings` object will be created only once, the first time it's called. ✔️ -//// tab | Python 3.9+ - -```Python hl_lines="1 11" -{!> ../../docs_src/settings/app03_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 11" -{!> ../../docs_src/settings/app03_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1 10" -{!> ../../docs_src/settings/app03/main.py!} -``` - -//// +{* ../../docs_src/settings/app03_an_py39/main.py hl[1,11] *} Then for any subsequent call of `get_settings()` in the dependencies for the next requests, instead of executing the internal code of `get_settings()` and creating a new `Settings` object, it will return the same object that was returned on the first call, again and again. diff --git a/docs/en/docs/advanced/templates.md b/docs/en/docs/advanced/templates.md index 76f0ef1de..d9b0ca6f1 100644 --- a/docs/en/docs/advanced/templates.md +++ b/docs/en/docs/advanced/templates.md @@ -27,9 +27,7 @@ $ pip install jinja2 * Declare a `Request` parameter in the *path operation* that will return a template. * Use the `templates` you created to render and return a `TemplateResponse`, pass the name of the template, the request object, and a "context" dictionary with key-value pairs to be used inside of the Jinja2 template. -```Python hl_lines="4 11 15-18" -{!../../docs_src/templates/tutorial001.py!} -``` +{* ../../docs_src/templates/tutorial001.py hl[4,11,15:18] *} /// note diff --git a/docs/en/docs/advanced/testing-events.md b/docs/en/docs/advanced/testing-events.md index f48907c7c..0c554c4ec 100644 --- a/docs/en/docs/advanced/testing-events.md +++ b/docs/en/docs/advanced/testing-events.md @@ -2,6 +2,4 @@ When you need your event handlers (`startup` and `shutdown`) to run in your tests, you can use the `TestClient` with a `with` statement: -```Python hl_lines="9-12 20-24" -{!../../docs_src/app_testing/tutorial003.py!} -``` +{* ../../docs_src/app_testing/tutorial003.py hl[9:12,20:24] *} diff --git a/docs/en/docs/tutorial/debugging.md b/docs/en/docs/tutorial/debugging.md index 6c0177853..90dd908f7 100644 --- a/docs/en/docs/tutorial/debugging.md +++ b/docs/en/docs/tutorial/debugging.md @@ -6,9 +6,7 @@ You can connect the debugger in your editor, for example with Visual Studio Code In your FastAPI application, import and run `uvicorn` directly: -```Python hl_lines="1 15" -{!../../docs_src/debugging/tutorial001.py!} -``` +{* ../../docs_src/debugging/tutorial001.py hl[1,15] *} ### About `__name__ == "__main__"` diff --git a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md index 70b5945a4..2b97ba39e 100644 --- a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md @@ -29,21 +29,15 @@ For example, you could use this to create a database session and close it after Only the code prior to and including the `yield` statement is executed before creating a response: -```Python hl_lines="2-4" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[2:4] *} The yielded value is what is injected into *path operations* and other dependencies: -```Python hl_lines="4" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[4] *} The code following the `yield` statement is executed after creating the response but before sending it: -```Python hl_lines="5-6" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[5:6] *} /// tip @@ -63,9 +57,7 @@ So, you can look for that specific exception inside the dependency with `except In the same way, you can use `finally` to make sure the exit steps are executed, no matter if there was an exception or not. -```Python hl_lines="3 5" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[3,5] *} ## Sub-dependencies with `yield` @@ -75,35 +67,7 @@ You can have sub-dependencies and "trees" of sub-dependencies of any size and sh For example, `dependency_c` can have a dependency on `dependency_b`, and `dependency_b` on `dependency_a`: -//// tab | Python 3.9+ - -```Python hl_lines="6 14 22" -{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="5 13 21" -{!> ../../docs_src/dependencies/tutorial008_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="4 12 20" -{!> ../../docs_src/dependencies/tutorial008.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[6,14,22] *} And all of them can use `yield`. @@ -111,35 +75,7 @@ In this case `dependency_c`, to execute its exit code, needs the value from `dep And, in turn, `dependency_b` needs the value from `dependency_a` (here named `dep_a`) to be available for its exit code. -//// tab | Python 3.9+ - -```Python hl_lines="18-19 26-27" -{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17-18 25-26" -{!> ../../docs_src/dependencies/tutorial008_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="16-17 24-25" -{!> ../../docs_src/dependencies/tutorial008.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[18:19,26:27] *} The same way, you could have some dependencies with `yield` and some other dependencies with `return`, and have some of those depend on some of the others. @@ -171,35 +107,7 @@ But it's there for you if you need it. 🤓 /// -//// tab | Python 3.9+ - -```Python hl_lines="18-22 31" -{!> ../../docs_src/dependencies/tutorial008b_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17-21 30" -{!> ../../docs_src/dependencies/tutorial008b_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="16-20 29" -{!> ../../docs_src/dependencies/tutorial008b.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial008b_an_py39.py hl[18:22,31] *} An alternative you could use to catch exceptions (and possibly also raise another `HTTPException`) is to create a [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. @@ -207,35 +115,7 @@ An alternative you could use to catch exceptions (and possibly also raise anothe If you catch an exception using `except` in a dependency with `yield` and you don't raise it again (or raise a new exception), FastAPI won't be able to notice there was an exception, the same way that would happen with regular Python: -//// tab | Python 3.9+ - -```Python hl_lines="15-16" -{!> ../../docs_src/dependencies/tutorial008c_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14-15" -{!> ../../docs_src/dependencies/tutorial008c_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="13-14" -{!> ../../docs_src/dependencies/tutorial008c.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial008c_an_py39.py hl[15:16] *} In this case, the client will see an *HTTP 500 Internal Server Error* response as it should, given that we are not raising an `HTTPException` or similar, but the server will **not have any logs** or any other indication of what was the error. 😱 @@ -245,35 +125,7 @@ If you catch an exception in a dependency with `yield`, unless you are raising a You can re-raise the same exception using `raise`: -//// tab | Python 3.9+ - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial008d_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="16" -{!> ../../docs_src/dependencies/tutorial008d_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="15" -{!> ../../docs_src/dependencies/tutorial008d.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial008d_an_py39.py hl[17] *} Now the client will get the same *HTTP 500 Internal Server Error* response, but the server will have our custom `InternalError` in the logs. 😎 @@ -403,9 +255,7 @@ In Python, you can create Context Managers by ../../docs_src/extra_data_types/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="1 3 12-16" -{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 3 13-17" -{!> ../../docs_src/extra_data_types/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1 2 11-15" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1 2 12-16" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *} Note that the parameters inside the function have their natural data type, and you can, for example, perform normal date manipulations, like: -//// tab | Python 3.10+ - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="19-20" -{!> ../../docs_src/extra_data_types/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="17-18" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *} diff --git a/docs/en/docs/tutorial/handling-errors.md b/docs/en/docs/tutorial/handling-errors.md index 537cb3e72..4d969747f 100644 --- a/docs/en/docs/tutorial/handling-errors.md +++ b/docs/en/docs/tutorial/handling-errors.md @@ -25,9 +25,7 @@ To return HTTP responses with errors to the client you use `HTTPException`. ### Import `HTTPException` -```Python hl_lines="1" -{!../../docs_src/handling_errors/tutorial001.py!} -``` +{* ../../docs_src/handling_errors/tutorial001.py hl[1] *} ### Raise an `HTTPException` in your code @@ -41,9 +39,7 @@ The benefit of raising an exception over `return`ing a value will be more eviden In this example, when the client requests an item by an ID that doesn't exist, raise an exception with a status code of `404`: -```Python hl_lines="11" -{!../../docs_src/handling_errors/tutorial001.py!} -``` +{* ../../docs_src/handling_errors/tutorial001.py hl[11] *} ### The resulting response @@ -81,9 +77,7 @@ You probably won't need to use it directly in your code. But in case you needed it for an advanced scenario, you can add custom headers: -```Python hl_lines="14" -{!../../docs_src/handling_errors/tutorial002.py!} -``` +{* ../../docs_src/handling_errors/tutorial002.py hl[14] *} ## Install custom exception handlers @@ -95,9 +89,7 @@ And you want to handle this exception globally with FastAPI. You could add a custom exception handler with `@app.exception_handler()`: -```Python hl_lines="5-7 13-18 24" -{!../../docs_src/handling_errors/tutorial003.py!} -``` +{* ../../docs_src/handling_errors/tutorial003.py hl[5:7,13:18,24] *} Here, if you request `/unicorns/yolo`, the *path operation* will `raise` a `UnicornException`. @@ -135,9 +127,7 @@ To override it, import the `RequestValidationError` and use it with `@app.except The exception handler will receive a `Request` and the exception. -```Python hl_lines="2 14-16" -{!../../docs_src/handling_errors/tutorial004.py!} -``` +{* ../../docs_src/handling_errors/tutorial004.py hl[2,14:16] *} Now, if you go to `/items/foo`, instead of getting the default JSON error with: @@ -188,9 +178,7 @@ The same way, you can override the `HTTPException` handler. For example, you could want to return a plain text response instead of JSON for these errors: -```Python hl_lines="3-4 9-11 22" -{!../../docs_src/handling_errors/tutorial004.py!} -``` +{* ../../docs_src/handling_errors/tutorial004.py hl[3:4,9:11,22] *} /// note | Technical Details @@ -206,9 +194,7 @@ The `RequestValidationError` contains the `body` it received with invalid data. You could use it while developing your app to log the body and debug it, return it to the user, etc. -```Python hl_lines="14" -{!../../docs_src/handling_errors/tutorial005.py!} -``` +{* ../../docs_src/handling_errors/tutorial005.py hl[14] *} Now try sending an invalid item like: @@ -264,8 +250,6 @@ from starlette.exceptions import HTTPException as StarletteHTTPException If you want to use the exception along with the same default exception handlers from **FastAPI**, you can import and reuse the default exception handlers from `fastapi.exception_handlers`: -```Python hl_lines="2-5 15 21" -{!../../docs_src/handling_errors/tutorial006.py!} -``` +{* ../../docs_src/handling_errors/tutorial006.py hl[2:5,15,21] *} In this example you are just `print`ing the error with a very expressive message, but you get the idea. You can use the exception and then just reuse the default exception handlers. diff --git a/docs/en/docs/tutorial/query-params-str-validations.md b/docs/en/docs/tutorial/query-params-str-validations.md index 12778d7fe..1bf16334d 100644 --- a/docs/en/docs/tutorial/query-params-str-validations.md +++ b/docs/en/docs/tutorial/query-params-str-validations.md @@ -4,21 +4,7 @@ Let's take this application as example: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial001.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial001_py310.py hl[7] *} The query parameter `q` is of type `Union[str, None]` (or `str | None` in Python 3.10), that means that it's of type `str` but could also be `None`, and indeed, the default value is `None`, so FastAPI will know it's not required. @@ -123,21 +109,7 @@ Now let's jump to the fun stuff. 🎉 Now that we have this `Annotated` where we can put more information (in this case some additional validation), add `Query` inside of `Annotated`, and set the parameter `max_length` to `50`: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial002_an.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial002_an_py310.py hl[9] *} Notice that the default value is still `None`, so the parameter is still optional. @@ -167,21 +139,7 @@ For new code and whenever possible, use `Annotated` as explained above. There ar This is how you would use `Query()` as the default value of your function parameter, setting the parameter `max_length` to 50: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial002.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial002_py310.py hl[7] *} As in this case (without using `Annotated`) we have to replace the default value `None` in the function with `Query()`, we now need to set the default value with the parameter `Query(default=None)`, it serves the same purpose of defining that default value (at least for FastAPI). @@ -281,113 +239,13 @@ Because `Annotated` can have more than one metadata annotation, you could now ev You can also add a parameter `min_length`: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial003.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial003_an_py310.py hl[10] *} ## Add regular expressions You can define a regular expression `pattern` that the parameter should match: -//// tab | Python 3.10+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12" -{!> ../../docs_src/query_params_str_validations/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial004.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial004_an_py310.py hl[11] *} This specific regular expression pattern checks that the received parameter value: @@ -405,11 +263,9 @@ Before Pydantic version 2 and before FastAPI 0.100.0, the parameter was called ` You could still see some code using it: -//// tab | Python 3.10+ Pydantic v1 +//// tab | Pydantic v1 -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial004_an_py310_regex.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial004_regex_an_py310.py hl[11] *} //// @@ -421,35 +277,7 @@ You can, of course, use default values other than `None`. Let's say that you want to declare the `q` query parameter to have a `min_length` of `3`, and to have a default value of `"fixedquery"`: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial005.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial005_an_py39.py hl[9] *} /// note @@ -491,77 +319,13 @@ q: Union[str, None] = Query(default=None, min_length=3) So, when you need to declare a value as required while using `Query`, you can simply not declare a default value: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial006.py!} -``` - -/// tip - -Notice that, even though in this case the `Query()` is used as the function parameter default value, we don't pass the `default=None` to `Query()`. - -Still, probably better to use the `Annotated` version. 😉 - -/// - -//// +{* ../../docs_src/query_params_str_validations/tutorial006_an_py39.py hl[9] *} ### Required with Ellipsis (`...`) There's an alternative way to explicitly declare that a value is required. You can set the default to the literal value `...`: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial006b_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial006b.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py hl[9] *} /// info @@ -579,57 +343,7 @@ You can declare that a parameter can accept `None`, but that it's still required To do that, you can declare that `None` is a valid type but still use `...` as the default: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial006c_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial006c_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006c.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py hl[9] *} /// tip @@ -649,71 +363,7 @@ When you define a query parameter explicitly with `Query` you can also declare i For example, to declare a query parameter `q` that can appear multiple times in the URL, you can write: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial011_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial011_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial011_an_py310.py hl[9] *} Then, with a URL like: @@ -748,49 +398,7 @@ The interactive API docs will update accordingly, to allow multiple values: And you can also define a default `list` of values if none are provided: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial012_an.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial012_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial012.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial012_an_py39.py hl[9] *} If you go to: @@ -813,35 +421,7 @@ the default of `q` will be: `["foo", "bar"]` and your response will be: You can also use `list` directly instead of `List[str]` (or `list[str]` in Python 3.9+): -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial013_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial013.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial013_an_py39.py hl[9] *} /// note @@ -867,111 +447,11 @@ Some of them might not show all the extra information declared yet, although in You can add a `title`: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial007_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial007_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial007.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial007_an_py310.py hl[10] *} And a `description`: -//// tab | Python 3.10+ - -```Python hl_lines="14" -{!> ../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15" -{!> ../../docs_src/query_params_str_validations/tutorial008_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial008_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="13" -{!> ../../docs_src/query_params_str_validations/tutorial008.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial008_an_py310.py hl[14] *} ## Alias parameters @@ -991,57 +471,7 @@ But you still need it to be exactly `item-query`... Then you can declare an `alias`, and that alias is what will be used to find the parameter value: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial009_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial009_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial009.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial009_an_py310.py hl[9] *} ## Deprecating parameters @@ -1051,57 +481,7 @@ You have to leave it there a while because there are clients using it, but you w Then pass the parameter `deprecated=True` to `Query`: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/query_params_str_validations/tutorial010_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="16" -{!> ../../docs_src/query_params_str_validations/tutorial010_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="18" -{!> ../../docs_src/query_params_str_validations/tutorial010.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial010_an_py310.py hl[19] *} The docs will show it like this: @@ -1111,57 +491,7 @@ The docs will show it like this: To exclude a query parameter from the generated OpenAPI schema (and thus, from the automatic documentation systems), set the parameter `include_in_schema` of `Query` to `False`: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial014_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial014_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial014.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *} ## Recap diff --git a/docs/en/docs/tutorial/query-params.md b/docs/en/docs/tutorial/query-params.md index 0d31d453d..c8477387c 100644 --- a/docs/en/docs/tutorial/query-params.md +++ b/docs/en/docs/tutorial/query-params.md @@ -2,9 +2,7 @@ When you declare other function parameters that are not part of the path parameters, they are automatically interpreted as "query" parameters. -```Python hl_lines="9" -{!../../docs_src/query_params/tutorial001.py!} -``` +{* ../../docs_src/query_params/tutorial001.py hl[9] *} The query is the set of key-value pairs that go after the `?` in a URL, separated by `&` characters. @@ -63,21 +61,7 @@ The parameter values in your function will be: The same way, you can declare optional query parameters, by setting their default to `None`: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial002.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *} In this case, the function parameter `q` will be optional, and will be `None` by default. @@ -91,21 +75,7 @@ Also notice that **FastAPI** is smart enough to notice that the path parameter ` You can also declare `bool` types, and they will be converted: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial003.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *} In this case, if you go to: @@ -148,21 +118,7 @@ And you don't have to declare them in any specific order. They will be detected by name: -//// tab | Python 3.10+ - -```Python hl_lines="6 8" -{!> ../../docs_src/query_params/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8 10" -{!> ../../docs_src/query_params/tutorial004.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *} ## Required query parameters @@ -172,9 +128,7 @@ If you don't want to add a specific value but just make it optional, set the def But when you want to make a query parameter required, you can just not declare any default value: -```Python hl_lines="6-7" -{!../../docs_src/query_params/tutorial005.py!} -``` +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} Here the query parameter `needy` is a required query parameter of type `str`. @@ -220,21 +174,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy And of course, you can define some parameters as required, some as having a default value, and some entirely optional: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params/tutorial006_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params/tutorial006.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *} In this case, there are 3 query parameters: diff --git a/docs/en/docs/tutorial/request-forms-and-files.md b/docs/en/docs/tutorial/request-forms-and-files.md index d60fc4c00..21e4bbd30 100644 --- a/docs/en/docs/tutorial/request-forms-and-files.md +++ b/docs/en/docs/tutorial/request-forms-and-files.md @@ -16,69 +16,13 @@ $ pip install python-multipart ## Import `File` and `Form` -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1" -{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/request_forms_and_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[3] *} ## Define `File` and `Form` parameters Create file and form parameters the same way you would for `Body` or `Query`: -//// tab | Python 3.9+ - -```Python hl_lines="10-12" -{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-11" -{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/request_forms_and_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[10:12] *} The files and form fields will be uploaded as form data and you will receive the files and form fields. diff --git a/docs/en/docs/tutorial/security/simple-oauth2.md b/docs/en/docs/tutorial/security/simple-oauth2.md index dc15bef20..1b70aa811 100644 --- a/docs/en/docs/tutorial/security/simple-oauth2.md +++ b/docs/en/docs/tutorial/security/simple-oauth2.md @@ -52,57 +52,7 @@ Now let's use the utilities provided by **FastAPI** to handle this. First, import `OAuth2PasswordRequestForm`, and use it as a dependency with `Depends` in the *path operation* for `/token`: -//// tab | Python 3.10+ - -```Python hl_lines="4 78" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4 78" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 79" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="2 74" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="4 76" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *} `OAuth2PasswordRequestForm` is a class dependency that declares a form body with: @@ -150,57 +100,7 @@ If there is no such user, we return an error saying "Incorrect username or passw For the error, we use the exception `HTTPException`: -//// tab | Python 3.10+ - -```Python hl_lines="3 79-81" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3 79-81" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3 80-82" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1 75-77" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="3 77-79" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *} ### Check the password @@ -226,57 +126,7 @@ If your database is stolen, the thief won't have your users' plaintext passwords So, the thief won't be able to try to use those same passwords in another system (as many users use the same password everywhere, this would be dangerous). -//// tab | Python 3.10+ - -```Python hl_lines="82-85" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="82-85" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="83-86" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="78-81" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="80-83" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *} #### About `**user_dict` @@ -318,57 +168,7 @@ But for now, let's focus on the specific details we need. /// -//// tab | Python 3.10+ - -```Python hl_lines="87" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="87" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="88" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="83" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="85" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *} /// tip @@ -394,57 +194,7 @@ Both of these dependencies will just return an HTTP error if the user doesn't ex So, in our endpoint, we will only get a user if the user exists, was correctly authenticated, and is active: -//// tab | Python 3.10+ - -```Python hl_lines="58-66 69-74 94" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="58-66 69-74 94" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="59-67 70-75 95" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="56-64 67-70 88" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="58-66 69-72 90" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *} /// info diff --git a/docs/en/docs/tutorial/testing.md b/docs/en/docs/tutorial/testing.md index a204f596f..35940d920 100644 --- a/docs/en/docs/tutorial/testing.md +++ b/docs/en/docs/tutorial/testing.md @@ -30,9 +30,7 @@ Use the `TestClient` object the same way as you do with `httpx`. Write simple `assert` statements with the standard Python expressions that you need to check (again, standard `pytest`). -```Python hl_lines="2 12 15-18" -{!../../docs_src/app_testing/tutorial001.py!} -``` +{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *} /// tip @@ -78,9 +76,7 @@ Let's say you have a file structure as described in [Bigger Applications](bigger In the file `main.py` you have your **FastAPI** app: -```Python -{!../../docs_src/app_testing/main.py!} -``` +{* ../../docs_src/app_testing/main.py *} ### Testing file @@ -96,9 +92,8 @@ Then you could have a file `test_main.py` with your tests. It could live on the Because this file is in the same package, you can use relative imports to import the object `app` from the `main` module (`main.py`): -```Python hl_lines="3" -{!../../docs_src/app_testing/test_main.py!} -``` +{* ../../docs_src/app_testing/test_main.py hl[3] *} + ...and have the code for the tests just like before. @@ -182,9 +177,8 @@ Prefer to use the `Annotated` version if possible. You could then update `test_main.py` with the extended tests: -```Python -{!> ../../docs_src/app_testing/app_b/test_main.py!} -``` +{* ../../docs_src/app_testing/app_b/test_main.py *} + Whenever you need the client to pass information in the request and you don't know how to, you can search (Google) how to do it in `httpx`, or even how to do it with `requests`, as HTTPX's design is based on Requests' design. diff --git a/docs/es/docs/advanced/additional-status-codes.md b/docs/es/docs/advanced/additional-status-codes.md index 4a0625c25..b72798c2b 100644 --- a/docs/es/docs/advanced/additional-status-codes.md +++ b/docs/es/docs/advanced/additional-status-codes.md @@ -14,9 +14,7 @@ Pero también quieres que acepte nuevos ítems. Cuando los ítems no existan ant Para conseguir esto importa `JSONResponse` y devuelve ahí directamente tu contenido, asignando el `status_code` que quieras: -```Python hl_lines="4 25" -{!../../docs_src/additional_status_codes/tutorial001.py!} -``` +{* ../../docs_src/additional_status_codes/tutorial001.py hl[4,25] *} /// warning | Advertencia diff --git a/docs/es/docs/advanced/path-operation-advanced-configuration.md b/docs/es/docs/advanced/path-operation-advanced-configuration.md index 12399d581..600e2e074 100644 --- a/docs/es/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/es/docs/advanced/path-operation-advanced-configuration.md @@ -12,9 +12,7 @@ Puedes asignar el `operationId` de OpenAPI para ser usado en tu *operación de p En este caso tendrías que asegurarte de que sea único para cada operación. -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *} ### Usando el nombre de la *función de la operación de path* en el operationId @@ -22,9 +20,7 @@ Si quieres usar tus nombres de funciones de API como `operationId`s, puedes iter Deberías hacerlo después de adicionar todas tus *operaciones de path*. -```Python hl_lines="2 12 13 14 15 16 17 18 19 20 21 24" -{!../../docs_src/path_operation_advanced_configuration/tutorial002.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2,12,13,14,15,16,17,18,19,20,21,24] *} /// tip | Consejo @@ -44,9 +40,7 @@ Incluso si están en diferentes módulos (archivos Python). Para excluir una *operación de path* del esquema OpenAPI generado (y por tanto del la documentación generada automáticamente), usa el parámetro `include_in_schema` y asigna el valor como `False`; -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *} ## Descripción avanzada desde el docstring @@ -56,6 +50,4 @@ Agregar un `\f` (un carácter de "form feed" escapado) hace que **FastAPI** trun No será mostrado en la documentación, pero otras herramientas (como Sphinx) serán capaces de usar el resto. -```Python hl_lines="19 20 21 22 23 24 25 26 27 28 29" -{!../../docs_src/path_operation_advanced_configuration/tutorial004.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19,20,21,22,23,24,25,26,27,28,29] *} diff --git a/docs/es/docs/advanced/response-change-status-code.md b/docs/es/docs/advanced/response-change-status-code.md index ddfd05a77..6a44ea94e 100644 --- a/docs/es/docs/advanced/response-change-status-code.md +++ b/docs/es/docs/advanced/response-change-status-code.md @@ -20,9 +20,7 @@ Puedes declarar un parámetro de tipo `Response` en tu *función de la operació Y luego puedes establecer el `status_code` en ese objeto de respuesta *temporal*. -```Python hl_lines="1 9 12" -{!../../docs_src/response_change_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *} Y luego puedes retornar cualquier objeto que necesites, como normalmente lo harías (un `dict`, un modelo de base de datos, etc). diff --git a/docs/es/docs/advanced/response-directly.md b/docs/es/docs/advanced/response-directly.md index 8800d2510..3cab11d99 100644 --- a/docs/es/docs/advanced/response-directly.md +++ b/docs/es/docs/advanced/response-directly.md @@ -34,9 +34,7 @@ Por ejemplo, no puedes poner un modelo Pydantic en una `JSONResponse` sin primer Para esos casos, puedes usar el `jsonable_encoder` para convertir tus datos antes de pasarlos a la respuesta: -```Python hl_lines="4 6 20 21" -{!../../docs_src/response_directly/tutorial001.py!} -``` +{* ../../docs_src/response_directly/tutorial001.py hl[4,6,20,21] *} /// note | Detalles Técnicos @@ -56,9 +54,7 @@ Digamos que quieres devolver una respuesta documentación de Strawberry. diff --git a/docs/es/docs/python-types.md b/docs/es/docs/python-types.md index 156907ad1..de502314e 100644 --- a/docs/es/docs/python-types.md +++ b/docs/es/docs/python-types.md @@ -22,9 +22,8 @@ Si eres un experto en Python y ya lo sabes todo sobre los type hints, salta al s Comencemos con un ejemplo simple: -```Python -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} + Llamar este programa nos muestra el siguiente output: @@ -38,9 +37,8 @@ La función hace lo siguiente: * Convierte la primera letra de cada uno en una letra mayúscula con `title()`. * Las concatena con un espacio en la mitad. -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### Edítalo @@ -82,9 +80,8 @@ Eso es todo. Esos son los "type hints": -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + No es lo mismo a declarar valores por defecto, como sería con: @@ -112,9 +109,8 @@ Con esto puedes moverte hacia abajo viendo las opciones hasta que encuentras una Mira esta función que ya tiene type hints: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + Como el editor conoce el tipo de las variables no solo obtienes auto-completado, si no que también obtienes chequeo de errores: @@ -122,9 +118,8 @@ Como el editor conoce el tipo de las variables no solo obtienes auto-completado, Ahora que sabes que tienes que arreglarlo convierte `age` a un string con `str(age)`: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## Declarando tipos @@ -143,9 +138,8 @@ Por ejemplo, puedes usar: * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### Tipos con sub-tipos @@ -161,9 +155,8 @@ Por ejemplo, vamos a definir una variable para que sea una `list` compuesta de ` De `typing`, importa `List` (con una `L` mayúscula): -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[1] *} + Declara la variable con la misma sintaxis de los dos puntos (`:`). @@ -171,9 +164,8 @@ Pon `List` como el tipo. Como la lista es un tipo que permite tener un "sub-tipo" pones el sub-tipo en corchetes `[]`: -```Python hl_lines="4" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[4] *} + Esto significa: la variable `items` es una `list` y cada uno de los ítems en esta lista es un `str`. @@ -191,9 +183,8 @@ El editor aún sabe que es un `str` y provee soporte para ello. Harías lo mismo para declarar `tuple`s y `set`s: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial007.py!} -``` +{* ../../docs_src/python_types/tutorial007.py hl[1,4] *} + Esto significa: @@ -208,9 +199,8 @@ El primer sub-tipo es para los keys del `dict`. El segundo sub-tipo es para los valores del `dict`: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial008.py!} -``` +{* ../../docs_src/python_types/tutorial008.py hl[1,4] *} + Esto significa: @@ -224,15 +214,13 @@ También puedes declarar una clase como el tipo de una variable. Digamos que tienes una clase `Person`con un nombre: -```Python hl_lines="1-3" -{!../../docs_src/python_types/tutorial009.py!} -``` +{* ../../docs_src/python_types/tutorial009.py hl[1:3] *} + Entonces puedes declarar una variable que sea de tipo `Person`: -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial009.py!} -``` +{* ../../docs_src/python_types/tutorial009.py hl[6] *} + Una vez más tendrás todo el soporte del editor: @@ -252,9 +240,8 @@ Y obtienes todo el soporte del editor con el objeto resultante. Tomado de la documentación oficial de Pydantic: -```Python -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py *} + /// info | Información diff --git a/docs/es/docs/tutorial/first-steps.md b/docs/es/docs/tutorial/first-steps.md index 68df00e64..4cc4cc11d 100644 --- a/docs/es/docs/tutorial/first-steps.md +++ b/docs/es/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ Un archivo muy simple de FastAPI podría verse así: -```Python -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} Copia eso a un archivo `main.py`. @@ -133,9 +131,7 @@ También podrías usarlo para generar código automáticamente, para los cliente ### Paso 1: importa `FastAPI` -```Python hl_lines="1" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI` es una clase de Python que provee toda la funcionalidad para tu API. @@ -149,9 +145,7 @@ También puedes usar toda la funcionalidad de 連結
します。 -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### 編集 @@ -82,9 +80,8 @@ John Doe それが「型ヒント」です: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + これは、以下のようにデフォルト値を宣言するのと同じではありません: @@ -112,9 +109,8 @@ John Doe この関数を見てください。すでに型ヒントを持っています: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + エディタは変数の型を知っているので、補完だけでなく、エラーチェックをすることもできます。 @@ -122,9 +118,8 @@ John Doe これで`age`を`str(age)`で文字列に変換して修正する必要があることがわかります: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## 型の宣言 @@ -143,9 +138,8 @@ John Doe * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### 型パラメータを持つジェネリック型 @@ -161,9 +155,8 @@ John Doe `typing`から`List`をインポートします(大文字の`L`を含む): -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[1] *} + 同じようにコロン(`:`)の構文で変数を宣言します。 @@ -171,9 +164,8 @@ John Doe リストはいくつかの内部の型を含む型なので、それらを角括弧で囲んでいます。 -```Python hl_lines="4" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[4] *} + /// tip | 豆知識 @@ -199,9 +191,8 @@ John Doe `tuple`と`set`の宣言も同様です: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial007.py!} -``` +{* ../../docs_src/python_types/tutorial007.py hl[1,4] *} + つまり: @@ -217,9 +208,8 @@ John Doe 2番目の型パラメータは`dict`の値です。 -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial008.py!} -``` +{* ../../docs_src/python_types/tutorial008.py hl[1,4] *} + つまり: @@ -256,15 +246,13 @@ John Doe 例えば、`Person`クラスという名前のクラスがあるとしましょう: -```Python hl_lines="1 2 3" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1,2,3] *} + 変数の型を`Person`として宣言することができます: -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + そして、再び、すべてのエディタのサポートを得ることができます: @@ -284,9 +272,8 @@ John Doe Pydanticの公式ドキュメントから引用: -```Python -{!../../docs_src/python_types/tutorial011.py!} -``` +{* ../../docs_src/python_types/tutorial011.py *} + /// info | 情報 diff --git a/docs/ja/docs/tutorial/background-tasks.md b/docs/ja/docs/tutorial/background-tasks.md index 8a4bc161c..650a079fb 100644 --- a/docs/ja/docs/tutorial/background-tasks.md +++ b/docs/ja/docs/tutorial/background-tasks.md @@ -15,9 +15,7 @@ まず初めに、`BackgroundTasks` をインポートし、` BackgroundTasks` の型宣言と共に、*path operation 関数* のパラメーターを定義します: -```Python hl_lines="1 13" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *} **FastAPI** は、`BackgroundTasks` 型のオブジェクトを作成し、そのパラメーターに渡します。 @@ -33,17 +31,13 @@ また、書き込み操作では `async` と `await` を使用しないため、通常の `def` で関数を定義します。 -```Python hl_lines="6-9" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *} ## バックグラウンドタスクの追加 *path operations 関数* 内で、`.add_task()` メソッドを使用してタスク関数を *background tasks* オブジェクトに渡します。 -```Python hl_lines="14" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[14] *} `.add_task()` は以下の引数を受け取ります: @@ -57,9 +51,7 @@ **FastAPI** は、それぞれの場合の処理​​方法と同じオブジェクトの再利用方法を知っているため、すべてのバックグラウンドタスクがマージされ、バックグラウンドで後で実行されます。 -```Python hl_lines="13 15 22 25" -{!../../docs_src/background_tasks/tutorial002.py!} -``` +{* ../../docs_src/background_tasks/tutorial002.py hl[13,15,22,25] *} この例では、レスポンスが送信された *後* にメッセージが `log.txt` ファイルに書き込まれます。 diff --git a/docs/ja/docs/tutorial/body-fields.md b/docs/ja/docs/tutorial/body-fields.md index 5b3b3622b..0466320f1 100644 --- a/docs/ja/docs/tutorial/body-fields.md +++ b/docs/ja/docs/tutorial/body-fields.md @@ -6,9 +6,7 @@ まず、以下のようにインポートします: -```Python hl_lines="4" -{!../../docs_src/body_fields/tutorial001.py!} -``` +{* ../../docs_src/body_fields/tutorial001.py hl[4] *} /// warning | 注意 @@ -20,9 +18,7 @@ 以下のように`Field`をモデルの属性として使用することができます: -```Python hl_lines="11 12 13 14" -{!../../docs_src/body_fields/tutorial001.py!} -``` +{* ../../docs_src/body_fields/tutorial001.py hl[11,12,13,14] *} `Field`は`Query`や`Path`、`Body`と同じように動作し、全く同様のパラメータなどを持ちます。 diff --git a/docs/ja/docs/tutorial/body-multiple-params.md b/docs/ja/docs/tutorial/body-multiple-params.md index 982c23565..cbfdda4b2 100644 --- a/docs/ja/docs/tutorial/body-multiple-params.md +++ b/docs/ja/docs/tutorial/body-multiple-params.md @@ -8,9 +8,7 @@ また、デフォルトの`None`を設定することで、ボディパラメータをオプションとして宣言することもできます: -```Python hl_lines="19 20 21" -{!../../docs_src/body_multiple_params/tutorial001.py!} -``` +{* ../../docs_src/body_multiple_params/tutorial001.py hl[19,20,21] *} /// note | 備考 @@ -33,9 +31,7 @@ しかし、`item`と`user`のように複数のボディパラメータを宣言することもできます: -```Python hl_lines="22" -{!../../docs_src/body_multiple_params/tutorial002.py!} -``` +{* ../../docs_src/body_multiple_params/tutorial002.py hl[22] *} この場合、**FastAPI**は関数内に複数のボディパラメータ(Pydanticモデルである2つのパラメータ)があることに気付きます。 @@ -77,9 +73,7 @@ しかし、`Body`を使用して、**FastAPI** に別のボディキーとして扱うように指示することができます: -```Python hl_lines="23" -{!../../docs_src/body_multiple_params/tutorial003.py!} -``` +{* ../../docs_src/body_multiple_params/tutorial003.py hl[23] *} この場合、**FastAPI** は以下のようなボディを期待します: @@ -114,9 +108,7 @@ q: str = None 以下において: -```Python hl_lines="27" -{!../../docs_src/body_multiple_params/tutorial004.py!} -``` +{* ../../docs_src/body_multiple_params/tutorial004.py hl[27] *} /// info | 情報 @@ -138,9 +130,7 @@ item: Item = Body(..., embed=True) 以下において: -```Python hl_lines="17" -{!../../docs_src/body_multiple_params/tutorial005.py!} -``` +{* ../../docs_src/body_multiple_params/tutorial005.py hl[17] *} この場合、**FastAPI** は以下のようなボディを期待します: diff --git a/docs/ja/docs/tutorial/body-nested-models.md b/docs/ja/docs/tutorial/body-nested-models.md index dc2d5e81a..a1680d10f 100644 --- a/docs/ja/docs/tutorial/body-nested-models.md +++ b/docs/ja/docs/tutorial/body-nested-models.md @@ -6,9 +6,7 @@ 属性をサブタイプとして定義することができます。例えば、Pythonの`list`は以下のように定義できます: -```Python hl_lines="12" -{!../../docs_src/body_nested_models/tutorial001.py!} -``` +{* ../../docs_src/body_nested_models/tutorial001.py hl[12] *} これにより、各項目の型は宣言されていませんが、`tags`はある項目のリストになります。 @@ -20,9 +18,7 @@ まず、Pythonの標準の`typing`モジュールから`List`をインポートします: -```Python hl_lines="1" -{!../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *} ### タイプパラメータを持つ`List`の宣言 @@ -43,9 +39,7 @@ my_list: List[str] そのため、以下の例では`tags`を具体的な「文字列のリスト」にすることができます: -```Python hl_lines="14" -{!../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[14] *} ## セット型 @@ -55,9 +49,7 @@ my_list: List[str] そのため、以下のように、`Set`をインポートして`str`の`set`として`tags`を宣言することができます: -```Python hl_lines="1 14" -{!../../docs_src/body_nested_models/tutorial003.py!} -``` +{* ../../docs_src/body_nested_models/tutorial003.py hl[1,14] *} これを使えば、データが重複しているリクエストを受けた場合でも、ユニークな項目のセットに変換されます。 @@ -79,17 +71,13 @@ Pydanticモデルの各属性には型があります。 例えば、`Image`モデルを定義することができます: -```Python hl_lines="9 10 11" -{!../../docs_src/body_nested_models/tutorial004.py!} -``` +{* ../../docs_src/body_nested_models/tutorial004.py hl[9,10,11] *} ### サブモデルを型として使用 そして、それを属性の型として使用することができます: -```Python hl_lines="20" -{!../../docs_src/body_nested_models/tutorial004.py!} -``` +{* ../../docs_src/body_nested_models/tutorial004.py hl[20] *} これは **FastAPI** が以下のようなボディを期待することを意味します: @@ -122,9 +110,7 @@ Pydanticモデルの各属性には型があります。 例えば、`Image`モデルのように`url`フィールドがある場合、`str`の代わりにPydanticの`HttpUrl`を指定することができます: -```Python hl_lines="4 10" -{!../../docs_src/body_nested_models/tutorial005.py!} -``` +{* ../../docs_src/body_nested_models/tutorial005.py hl[4,10] *} 文字列は有効なURLであることが確認され、そのようにJSONスキーマ・OpenAPIで文書化されます。 @@ -132,9 +118,7 @@ Pydanticモデルの各属性には型があります。 Pydanticモデルを`list`や`set`などのサブタイプとして使用することもできます: -```Python hl_lines="20" -{!../../docs_src/body_nested_models/tutorial006.py!} -``` +{* ../../docs_src/body_nested_models/tutorial006.py hl[20] *} これは、次のようなJSONボディを期待します(変換、検証、ドキュメントなど): @@ -172,9 +156,7 @@ Pydanticモデルを`list`や`set`などのサブタイプとして使用する 深くネストされた任意のモデルを定義することができます: -```Python hl_lines="9 14 20 23 27" -{!../../docs_src/body_nested_models/tutorial007.py!} -``` +{* ../../docs_src/body_nested_models/tutorial007.py hl[9,14,20,23,27] *} /// info | 情報 @@ -192,9 +174,7 @@ images: List[Image] 以下のように: -```Python hl_lines="15" -{!../../docs_src/body_nested_models/tutorial008.py!} -``` +{* ../../docs_src/body_nested_models/tutorial008.py hl[15] *} ## あらゆる場所でのエディタサポート @@ -224,9 +204,7 @@ Pydanticモデルではなく、`dict`を直接使用している場合はこの この場合、`int`のキーと`float`の値を持つものであれば、どんな`dict`でも受け入れることができます: -```Python hl_lines="15" -{!../../docs_src/body_nested_models/tutorial009.py!} -``` +{* ../../docs_src/body_nested_models/tutorial009.py hl[15] *} /// tip | 豆知識 diff --git a/docs/ja/docs/tutorial/body-updates.md b/docs/ja/docs/tutorial/body-updates.md index fcaeb0d16..ffbe52e1d 100644 --- a/docs/ja/docs/tutorial/body-updates.md +++ b/docs/ja/docs/tutorial/body-updates.md @@ -6,9 +6,7 @@ `jsonable_encoder`を用いて、入力データをJSON形式で保存できるデータに変換することができます(例:NoSQLデータベース)。例えば、`datetime`を`str`に変換します。 -```Python hl_lines="30 31 32 33 34 35" -{!../../docs_src/body_updates/tutorial001.py!} -``` +{* ../../docs_src/body_updates/tutorial001.py hl[30,31,32,33,34,35] *} 既存のデータを置き換えるべきデータを受け取るために`PUT`は使用されます。 @@ -56,9 +54,7 @@ これを使うことで、デフォルト値を省略して、設定された(リクエストで送られた)データのみを含む`dict`を生成することができます: -```Python hl_lines="34" -{!../../docs_src/body_updates/tutorial002.py!} -``` +{* ../../docs_src/body_updates/tutorial002.py hl[34] *} ### Pydanticの`update`パラメータ @@ -66,9 +62,7 @@ `stored_item_model.copy(update=update_data)`のように: -```Python hl_lines="35" -{!../../docs_src/body_updates/tutorial002.py!} -``` +{* ../../docs_src/body_updates/tutorial002.py hl[35] *} ### 部分的更新のまとめ @@ -85,9 +79,7 @@ * データをDBに保存します。 * 更新されたモデルを返します。 -```Python hl_lines="30 31 32 33 34 35 36 37" -{!../../docs_src/body_updates/tutorial002.py!} -``` +{* ../../docs_src/body_updates/tutorial002.py hl[30,31,32,33,34,35,36,37] *} /// tip | 豆知識 diff --git a/docs/ja/docs/tutorial/body.md b/docs/ja/docs/tutorial/body.md index 277ee79c8..8376959d5 100644 --- a/docs/ja/docs/tutorial/body.md +++ b/docs/ja/docs/tutorial/body.md @@ -22,9 +22,7 @@ GET リクエストでボディを送信することは、仕様では未定義 ます初めに、 `pydantic` から `BaseModel` をインポートする必要があります: -```Python hl_lines="2" -{!../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[2] *} ## データモデルの作成 @@ -32,9 +30,7 @@ GET リクエストでボディを送信することは、仕様では未定義 すべての属性にpython標準の型を使用します: -```Python hl_lines="5-9" -{!../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[5:9] *} クエリパラメータの宣言と同様に、モデル属性がデフォルト値をもつとき、必須な属性ではなくなります。それ以外は必須になります。オプショナルな属性にしたい場合は `None` を使用してください。 @@ -62,9 +58,7 @@ GET リクエストでボディを送信することは、仕様では未定義 *パスオペレーション* に加えるために、パスパラメータやクエリパラメータと同じ様に宣言します: -```Python hl_lines="16" -{!../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[16] *} ...そして、作成したモデル `Item` で型を宣言します。 @@ -131,9 +125,7 @@ GET リクエストでボディを送信することは、仕様では未定義 関数内部で、モデルの全ての属性に直接アクセスできます: -```Python hl_lines="19" -{!../../docs_src/body/tutorial002.py!} -``` +{* ../../docs_src/body/tutorial002.py hl[19] *} ## リクエストボディ + パスパラメータ @@ -141,9 +133,7 @@ GET リクエストでボディを送信することは、仕様では未定義 **FastAPI** はパスパラメータである関数パラメータは**パスから受け取り**、Pydanticモデルによって宣言された関数パラメータは**リクエストボディから受け取る**ということを認識します。 -```Python hl_lines="15-16" -{!../../docs_src/body/tutorial003.py!} -``` +{* ../../docs_src/body/tutorial003.py hl[15:16] *} ## リクエストボディ + パスパラメータ + クエリパラメータ @@ -151,9 +141,7 @@ GET リクエストでボディを送信することは、仕様では未定義 **FastAPI** はそれぞれを認識し、適切な場所からデータを取得します。 -```Python hl_lines="16" -{!../../docs_src/body/tutorial004.py!} -``` +{* ../../docs_src/body/tutorial004.py hl[16] *} 関数パラメータは以下の様に認識されます: diff --git a/docs/ja/docs/tutorial/cookie-params.md b/docs/ja/docs/tutorial/cookie-params.md index 7f029b483..13af6d3c7 100644 --- a/docs/ja/docs/tutorial/cookie-params.md +++ b/docs/ja/docs/tutorial/cookie-params.md @@ -6,9 +6,7 @@ まず、`Cookie`をインポートします: -```Python hl_lines="3" -{!../../docs_src/cookie_params/tutorial001.py!} -``` +{* ../../docs_src/cookie_params/tutorial001.py hl[3] *} ## `Cookie`のパラメータを宣言 @@ -16,9 +14,7 @@ 最初の値がデフォルト値で、追加の検証パラメータや注釈パラメータをすべて渡すことができます: -```Python hl_lines="9" -{!../../docs_src/cookie_params/tutorial001.py!} -``` +{* ../../docs_src/cookie_params/tutorial001.py hl[9] *} /// note | 技術詳細 diff --git a/docs/ja/docs/tutorial/cors.md b/docs/ja/docs/tutorial/cors.md index 9834a460b..f7bd59b70 100644 --- a/docs/ja/docs/tutorial/cors.md +++ b/docs/ja/docs/tutorial/cors.md @@ -46,9 +46,7 @@ * 特定のHTTPメソッド (`POST`、`PUT`) またはワイルドカード `"*"` を使用してすべて許可。 * 特定のHTTPヘッダー、またはワイルドカード `"*"`を使用してすべて許可。 -```Python hl_lines="2 6-11 13-19" -{!../../docs_src/cors/tutorial001.py!} -``` +{* ../../docs_src/cors/tutorial001.py hl[2,6:11,13:19] *} `CORSMiddleware` 実装のデフォルトのパラメータはCORSに関して制限を与えるものになっているので、ブラウザにドメインを跨いで特定のオリジン、メソッド、またはヘッダーを使用可能にするためには、それらを明示的に有効にする必要があります diff --git a/docs/ja/docs/tutorial/debugging.md b/docs/ja/docs/tutorial/debugging.md index 7413332a8..6c29679ef 100644 --- a/docs/ja/docs/tutorial/debugging.md +++ b/docs/ja/docs/tutorial/debugging.md @@ -6,9 +6,7 @@ Visual Studio CodeやPyCharmなどを使用して、エディター上でデバ FastAPIアプリケーション上で、`uvicorn` を直接インポートして実行します: -```Python hl_lines="1 15" -{!../../docs_src/debugging/tutorial001.py!} -``` +{* ../../docs_src/debugging/tutorial001.py hl[1,15] *} ### `__name__ == "__main__"` について diff --git a/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md index 55885a61f..80153529e 100644 --- a/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,9 +6,7 @@ 前の例では、依存関係("dependable")から`dict`を返していました: -```Python hl_lines="9" -{!../../docs_src/dependencies/tutorial001.py!} -``` +{* ../../docs_src/dependencies/tutorial001.py hl[9] *} しかし、*path operation関数*のパラメータ`commons`に`dict`が含まれています。 @@ -71,21 +69,15 @@ FastAPIが実際にチェックしているのは、それが「呼び出し可 そこで、上で紹介した依存関係の`common_parameters`を`CommonQueryParams`クラスに変更します: -```Python hl_lines="11 12 13 14 15" -{!../../docs_src/dependencies/tutorial002.py!} -``` +{* ../../docs_src/dependencies/tutorial002.py hl[11,12,13,14,15] *} クラスのインスタンスを作成するために使用される`__init__`メソッドに注目してください: -```Python hl_lines="12" -{!../../docs_src/dependencies/tutorial002.py!} -``` +{* ../../docs_src/dependencies/tutorial002.py hl[12] *} ...以前の`common_parameters`と同じパラメータを持っています: -```Python hl_lines="8" -{!../../docs_src/dependencies/tutorial001.py!} -``` +{* ../../docs_src/dependencies/tutorial001.py hl[8] *} これらのパラメータは **FastAPI** が依存関係を「解決」するために使用するものです。 @@ -101,9 +93,7 @@ FastAPIが実際にチェックしているのは、それが「呼び出し可 これで、このクラスを使用して依存関係を宣言することができます。 -```Python hl_lines="19" -{!../../docs_src/dependencies/tutorial002.py!} -``` +{* ../../docs_src/dependencies/tutorial002.py hl[19] *} **FastAPI** は`CommonQueryParams`クラスを呼び出します。これにより、そのクラスの「インスタンス」が作成され、インスタンスはパラメータ`commons`として関数に渡されます。 @@ -143,9 +133,7 @@ commons = Depends(CommonQueryParams) 以下にあるように: -```Python hl_lines="19" -{!../../docs_src/dependencies/tutorial003.py!} -``` +{* ../../docs_src/dependencies/tutorial003.py hl[19] *} しかし、型を宣言することは推奨されています。そうすれば、エディタは`commons`のパラメータとして何が渡されるかを知ることができ、コードの補完や型チェックなどを行うのに役立ちます: @@ -179,9 +167,7 @@ commons: CommonQueryParams = Depends() 同じ例では以下のようになります: -```Python hl_lines="19" -{!../../docs_src/dependencies/tutorial004.py!} -``` +{* ../../docs_src/dependencies/tutorial004.py hl[19] *} ...そして **FastAPI** は何をすべきか知っています。 diff --git a/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 3b78f4e0b..0fb15ae02 100644 --- a/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -14,9 +14,7 @@ それは`Depends()`の`list`であるべきです: -```Python hl_lines="17" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[17] *} これらの依存関係は、通常の依存関係と同様に実行・解決されます。しかし、それらの値(何かを返す場合)は*path operation関数*には渡されません。 @@ -38,17 +36,13 @@ これらはリクエストの要件(ヘッダのようなもの)やその他のサブ依存関係を宣言することができます: -```Python hl_lines="6 11" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[6,11] *} ### 例外の発生 これらの依存関係は通常の依存関係と同じように、例外を`raise`発生させることができます: -```Python hl_lines="8 13" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[8,13] *} ### 戻り値 @@ -56,9 +50,7 @@ つまり、すでにどこかで使っている通常の依存関係(値を返すもの)を再利用することができ、値は使われなくても依存関係は実行されます: -```Python hl_lines="9 14" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[9,14] *} ## *path operations*のグループに対する依存関係 diff --git a/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md index bd4e689bf..35a69de0d 100644 --- a/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md @@ -41,21 +41,15 @@ pip install async-exit-stack async-generator レスポンスを送信する前に`yield`文を含む前のコードのみが実行されます。 -```Python hl_lines="2 3 4" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[2,3,4] *} 生成された値は、*path operations*や他の依存関係に注入されるものです: -```Python hl_lines="4" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[4] *} `yield`文に続くコードは、レスポンスが送信された後に実行されます: -```Python hl_lines="5 6" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[5,6] *} /// tip | 豆知識 @@ -75,9 +69,7 @@ pip install async-exit-stack async-generator 同様に、`finally`を用いて例外があったかどうかにかかわらず、終了ステップを確実に実行することができます。 -```Python hl_lines="3 5" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[3,5] *} ## `yield`を持つサブ依存関係 @@ -87,9 +79,7 @@ pip install async-exit-stack async-generator 例えば、`dependency_c`は`dependency_b`と`dependency_b`に依存する`dependency_a`に、依存することができます: -```Python hl_lines="4 12 20" -{!../../docs_src/dependencies/tutorial008.py!} -``` +{* ../../docs_src/dependencies/tutorial008.py hl[4,12,20] *} そして、それらはすべて`yield`を使用することができます。 @@ -97,9 +87,7 @@ pip install async-exit-stack async-generator そして、`dependency_b`は`dependency_a`(ここでは`dep_a`という名前)の値を終了コードで利用できるようにする必要があります。 -```Python hl_lines="16 17 24 25" -{!../../docs_src/dependencies/tutorial008.py!} -``` +{* ../../docs_src/dependencies/tutorial008.py hl[16,17,24,25] *} 同様に、`yield`と`return`が混在した依存関係を持つこともできます。 @@ -233,9 +221,7 @@ Pythonでは、`typing.Union`を使用します: -```Python hl_lines="1 14 15 18 19 20 33" -{!../../docs_src/extra_models/tutorial003.py!} -``` +{* ../../docs_src/extra_models/tutorial003.py hl[1,14,15,18,19,20,33] *} ## モデルのリスト @@ -178,9 +172,7 @@ OpenAPIでは`anyOf`で定義されます。 そのためには、標準のPythonの`typing.List`を使用する: -```Python hl_lines="1 20" -{!../../docs_src/extra_models/tutorial004.py!} -``` +{* ../../docs_src/extra_models/tutorial004.py hl[1,20] *} ## 任意の`dict`を持つレスポンス @@ -190,9 +182,7 @@ OpenAPIでは`anyOf`で定義されます。 この場合、`typing.Dict`を使用することができます: -```Python hl_lines="1 8" -{!../../docs_src/extra_models/tutorial005.py!} -``` +{* ../../docs_src/extra_models/tutorial005.py hl[1,8] *} ## まとめ diff --git a/docs/ja/docs/tutorial/first-steps.md b/docs/ja/docs/tutorial/first-steps.md index 3691d13d2..d14f0cbec 100644 --- a/docs/ja/docs/tutorial/first-steps.md +++ b/docs/ja/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ 最もシンプルなFastAPIファイルは以下のようになります: -```Python -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} これを`main.py`にコピーします。 @@ -133,9 +131,7 @@ OpenAPIスキーマは、FastAPIに含まれている2つのインタラクテ ### Step 1: `FastAPI`をインポート -```Python hl_lines="1" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI`は、APIのすべての機能を提供するPythonクラスです。 @@ -149,9 +145,7 @@ OpenAPIスキーマは、FastAPIに含まれている2つのインタラクテ ### Step 2: `FastAPI`の「インスタンス」を生成 -```Python hl_lines="3" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[3] *} ここで、`app`変数が`FastAPI`クラスの「インスタンス」になります。 これが、すべてのAPIを作成するための主要なポイントになります。 @@ -170,9 +164,7 @@ $ uvicorn main:app --reload 以下のようなアプリを作成したとき: -```Python hl_lines="3" -{!../../docs_src/first_steps/tutorial002.py!} -``` +{* ../../docs_src/first_steps/tutorial002.py hl[3] *} そして、それを`main.py`ファイルに置き、次のように`uvicorn`を呼び出します: @@ -249,9 +241,7 @@ APIを構築するときは、通常、これらの特定のHTTPメソッドを #### *パスオペレーションデコレータ*を定義 -```Python hl_lines="6" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[6] *} `@app.get("/")`は直下の関数が下記のリクエストの処理を担当することを**FastAPI**に伝えます: * パス `/` @@ -304,9 +294,7 @@ Pythonにおける`@something`シンタックスはデコレータと呼ばれ * **オペレーション**: は`get`です。 * **関数**: 「デコレータ」の直下にある関数 (`@app.get("/")`の直下) です。 -```Python hl_lines="7" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[7] *} これは、Pythonの関数です。 @@ -318,9 +306,7 @@ Pythonにおける`@something`シンタックスはデコレータと呼ばれ `async def`の代わりに通常の関数として定義することもできます: -```Python hl_lines="7" -{!../../docs_src/first_steps/tutorial003.py!} -``` +{* ../../docs_src/first_steps/tutorial003.py hl[7] *} /// note | 備考 @@ -330,9 +316,7 @@ Pythonにおける`@something`シンタックスはデコレータと呼ばれ ### Step 5: コンテンツの返信 -```Python hl_lines="8" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[8] *} `dict`、`list`、`str`、`int`などを返すことができます。 diff --git a/docs/ja/docs/tutorial/handling-errors.md b/docs/ja/docs/tutorial/handling-errors.md index d270fd75b..9a46cc738 100644 --- a/docs/ja/docs/tutorial/handling-errors.md +++ b/docs/ja/docs/tutorial/handling-errors.md @@ -25,9 +25,7 @@ HTTPレスポンスをエラーでクライアントに返すには、`HTTPExcep ### `HTTPException`のインポート -```Python hl_lines="1" -{!../../docs_src/handling_errors/tutorial001.py!} -``` +{* ../../docs_src/handling_errors/tutorial001.py hl[1] *} ### コード内での`HTTPException`の発生 @@ -41,9 +39,7 @@ Pythonの例外なので、`return`ではなく、`raise`です。 この例では、クライアントが存在しないIDでアイテムを要求した場合、`404`のステータスコードを持つ例外を発生させます: -```Python hl_lines="11" -{!../../docs_src/handling_errors/tutorial001.py!} -``` +{* ../../docs_src/handling_errors/tutorial001.py hl[11] *} ### レスポンス結果 @@ -81,9 +77,7 @@ Pythonの例外なので、`return`ではなく、`raise`です。 しかし、高度なシナリオのために必要な場合には、カスタムヘッダーを追加することができます: -```Python hl_lines="14" -{!../../docs_src/handling_errors/tutorial002.py!} -``` +{* ../../docs_src/handling_errors/tutorial002.py hl[14] *} ## カスタム例外ハンドラのインストール @@ -95,9 +89,7 @@ Pythonの例外なので、`return`ではなく、`raise`です。 カスタム例外ハンドラを`@app.exception_handler()`で追加することができます: -```Python hl_lines="5 6 7 13 14 15 16 17 18 24" -{!../../docs_src/handling_errors/tutorial003.py!} -``` +{* ../../docs_src/handling_errors/tutorial003.py hl[5,6,7,13,14,15,16,17,18,24] *} ここで、`/unicorns/yolo`をリクエストすると、*path operation*は`UnicornException`を`raise`します。 @@ -135,9 +127,7 @@ Pythonの例外なので、`return`ではなく、`raise`です。 この例外ハンドラは`Requset`と例外を受け取ります。 -```Python hl_lines="2 14 15 16" -{!../../docs_src/handling_errors/tutorial004.py!} -``` +{* ../../docs_src/handling_errors/tutorial004.py hl[2,14,15,16] *} これで、`/items/foo`にアクセスすると、デフォルトのJSONエラーの代わりに以下が返されます: @@ -188,9 +178,7 @@ path -> item_id 例えば、これらのエラーに対しては、JSONではなくプレーンテキストを返すようにすることができます: -```Python hl_lines="3 4 9 10 11 22" -{!../../docs_src/handling_errors/tutorial004.py!} -``` +{* ../../docs_src/handling_errors/tutorial004.py hl[3,4,9,10,11,22] *} /// note | 技術詳細 @@ -206,9 +194,7 @@ path -> item_id アプリ開発中に本体のログを取ってデバッグしたり、ユーザーに返したりなどに使用することができます。 -```Python hl_lines="14" -{!../../docs_src/handling_errors/tutorial005.py!} -``` +{* ../../docs_src/handling_errors/tutorial005.py hl[14] *} ここで、以下のような無効な項目を送信してみてください: @@ -268,9 +254,7 @@ from starlette.exceptions import HTTPException as StarletteHTTPException デフォルトの例外ハンドラを`fastapi.exception_handlers`からインポートして再利用することができます: -```Python hl_lines="2 3 4 5 15 21" -{!../../docs_src/handling_errors/tutorial006.py!} -``` +{* ../../docs_src/handling_errors/tutorial006.py hl[2,3,4,5,15,21] *} この例では、非常に表現力のあるメッセージでエラーを`print`しています。 diff --git a/docs/ja/docs/tutorial/header-params.md b/docs/ja/docs/tutorial/header-params.md index c741005d3..ac89afbdb 100644 --- a/docs/ja/docs/tutorial/header-params.md +++ b/docs/ja/docs/tutorial/header-params.md @@ -6,9 +6,7 @@ まず、`Header`をインポートします: -```Python hl_lines="3" -{!../../docs_src/header_params/tutorial001.py!} -``` +{* ../../docs_src/header_params/tutorial001.py hl[3] *} ## `Header`のパラメータの宣言 @@ -16,9 +14,7 @@ 最初の値がデフォルト値で、追加の検証パラメータや注釈パラメータをすべて渡すことができます。 -```Python hl_lines="9" -{!../../docs_src/header_params/tutorial001.py!} -``` +{* ../../docs_src/header_params/tutorial001.py hl[9] *} /// note | 技術詳細 @@ -50,9 +46,7 @@ もしなんらかの理由でアンダースコアからハイフンへの自動変換を無効にする必要がある場合は、`Header`の`convert_underscores`に`False`を設定してください: -```Python hl_lines="9" -{!../../docs_src/header_params/tutorial002.py!} -``` +{* ../../docs_src/header_params/tutorial002.py hl[9] *} /// warning | 注意 @@ -70,9 +64,7 @@ 例えば、複数回出現する可能性のある`X-Token`のヘッダを定義するには、以下のように書くことができます: -```Python hl_lines="9" -{!../../docs_src/header_params/tutorial003.py!} -``` +{* ../../docs_src/header_params/tutorial003.py hl[9] *} もし、その*path operation*で通信する場合は、次のように2つのHTTPヘッダーを送信します: diff --git a/docs/ja/docs/tutorial/metadata.md b/docs/ja/docs/tutorial/metadata.md index 201322cb4..b93dedcb9 100644 --- a/docs/ja/docs/tutorial/metadata.md +++ b/docs/ja/docs/tutorial/metadata.md @@ -13,9 +13,7 @@ これらを設定するには、パラメータ `title`、`description`、`version` を使用します: -```Python hl_lines="4-6" -{!../../docs_src/metadata/tutorial001.py!} -``` +{* ../../docs_src/metadata/tutorial001.py hl[4:6] *} この設定では、自動APIドキュメントは以下の様になります: @@ -41,9 +39,7 @@ タグのためのメタデータを作成し、それを `openapi_tags` パラメータに渡します。 -```Python hl_lines="3-16 18" -{!../../docs_src/metadata/tutorial004.py!} -``` +{* ../../docs_src/metadata/tutorial004.py hl[3:16,18] *} 説明文 (description) の中で Markdown を使用できることに注意してください。たとえば、「login」は太字 (**login**) で表示され、「fancy」は斜体 (_fancy_) で表示されます。 @@ -57,9 +53,7 @@ `tags` パラメーターを使用して、それぞれの *path operations* (および `APIRouter`) を異なるタグに割り当てます: -```Python hl_lines="21 26" -{!../../docs_src/metadata/tutorial004.py!} -``` +{* ../../docs_src/metadata/tutorial004.py hl[21,26] *} /// info | 情報 @@ -87,9 +81,7 @@ たとえば、`/api/v1/openapi.json` で提供されるように設定するには: -```Python hl_lines="3" -{!../../docs_src/metadata/tutorial002.py!} -``` +{* ../../docs_src/metadata/tutorial002.py hl[3] *} OpenAPIスキーマを完全に無効にする場合は、`openapi_url=None` を設定できます。これにより、それを使用するドキュメントUIも無効になります。 @@ -106,6 +98,4 @@ OpenAPIスキーマを完全に無効にする場合は、`openapi_url=None` を たとえば、`/documentation` でSwagger UIが提供されるように設定し、ReDocを無効にするには: -```Python hl_lines="3" -{!../../docs_src/metadata/tutorial003.py!} -``` +{* ../../docs_src/metadata/tutorial003.py hl[3] *} diff --git a/docs/ja/docs/tutorial/middleware.md b/docs/ja/docs/tutorial/middleware.md index 3a3d8bb22..326e9145c 100644 --- a/docs/ja/docs/tutorial/middleware.md +++ b/docs/ja/docs/tutorial/middleware.md @@ -31,9 +31,7 @@ * 次に、対応する*path operation*によって生成された `response` を返します。 * その後、`response` を返す前にさらに `response` を変更することもできます。 -```Python hl_lines="8-9 11 14" -{!../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[8:9,11,14] *} /// tip | 豆知識 @@ -59,9 +57,7 @@ 例えば、リクエストの処理とレスポンスの生成にかかった秒数を含むカスタムヘッダー `X-Process-Time` を追加できます: -```Python hl_lines="10 12-13" -{!../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *} ## その他のミドルウェア diff --git a/docs/ja/docs/tutorial/path-operation-configuration.md b/docs/ja/docs/tutorial/path-operation-configuration.md index 36223d35d..0cc38cb25 100644 --- a/docs/ja/docs/tutorial/path-operation-configuration.md +++ b/docs/ja/docs/tutorial/path-operation-configuration.md @@ -16,9 +16,7 @@ しかし、それぞれの番号コードが何のためのものか覚えていない場合は、`status`のショートカット定数を使用することができます: -```Python hl_lines="3 17" -{!../../docs_src/path_operation_configuration/tutorial001.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial001.py hl[3,17] *} そのステータスコードはレスポンスで使用され、OpenAPIスキーマに追加されます。 @@ -34,9 +32,7 @@ `tags`パラメータを`str`の`list`(通常は1つの`str`)と一緒に渡すと、*path operation*にタグを追加できます: -```Python hl_lines="17 22 27" -{!../../docs_src/path_operation_configuration/tutorial002.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial002.py hl[17,22,27] *} これらはOpenAPIスキーマに追加され、自動ドキュメントのインターフェースで使用されます: @@ -46,9 +42,7 @@ `summary`と`description`を追加できます: -```Python hl_lines="20-21" -{!../../docs_src/path_operation_configuration/tutorial003.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial003.py hl[20:21] *} ## docstringを用いた説明 @@ -56,9 +50,7 @@ docstringにMarkdownを記述すれば、正しく解釈されて表示されます。(docstringのインデントを考慮して) -```Python hl_lines="19-27" -{!../../docs_src/path_operation_configuration/tutorial004.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial004.py hl[19:27] *} これは対話的ドキュメントで使用されます: @@ -68,9 +60,7 @@ docstringにdeprecated
としてマークする必要があるが、それを削除しない場合は、`deprecated`パラメータを渡します: -```Python hl_lines="16" -{!../../docs_src/path_operation_configuration/tutorial006.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial006.py hl[16] *} 対話的ドキュメントでは非推奨と明記されます: diff --git a/docs/ja/docs/tutorial/path-params-numeric-validations.md b/docs/ja/docs/tutorial/path-params-numeric-validations.md index 7d55ad30c..13a71f72f 100644 --- a/docs/ja/docs/tutorial/path-params-numeric-validations.md +++ b/docs/ja/docs/tutorial/path-params-numeric-validations.md @@ -6,9 +6,7 @@ まず初めに、`fastapi`から`Path`をインポートします: -```Python hl_lines="1" -{!../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial001.py hl[1] *} ## メタデータの宣言 @@ -16,9 +14,7 @@ 例えば、パスパラメータ`item_id`に対して`title`のメタデータを宣言するには以下のようにします: -```Python hl_lines="8" -{!../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial001.py hl[8] *} /// note | 備考 @@ -46,9 +42,7 @@ Pythonは「デフォルト」を持たない値の前に「デフォルト」 そのため、以下のように関数を宣言することができます: -```Python hl_lines="8" -{!../../docs_src/path_params_numeric_validations/tutorial002.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial002.py hl[8] *} ## 必要に応じてパラメータを並び替えるトリック @@ -58,9 +52,7 @@ Pythonは「デフォルト」を持たない値の前に「デフォルト」 Pythonはその`*`で何かをすることはありませんが、それ以降のすべてのパラメータがキーワード引数(キーと値のペア)として呼ばれるべきものであると知っているでしょう。それはkwargsとしても知られています。たとえデフォルト値がなくても。 -```Python hl_lines="8" -{!../../docs_src/path_params_numeric_validations/tutorial003.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[8] *} ## 数値の検証: 以上 @@ -68,9 +60,7 @@ Pythonはその`*`で何かをすることはありませんが、それ以降 ここで、`ge=1`の場合、`item_id`は`1`「より大きい`g`か、同じ`e`」整数でなれけばなりません。 -```Python hl_lines="8" -{!../../docs_src/path_params_numeric_validations/tutorial004.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial004.py hl[8] *} ## 数値の検証: より大きいと小なりイコール @@ -79,9 +69,7 @@ Pythonはその`*`で何かをすることはありませんが、それ以降 * `gt`: より大きい(`g`reater `t`han) * `le`: 小なりイコール(`l`ess than or `e`qual) -```Python hl_lines="9" -{!../../docs_src/path_params_numeric_validations/tutorial005.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial005.py hl[9] *} ## 数値の検証: 浮動小数点、 大なり小なり @@ -93,9 +81,7 @@ Pythonはその`*`で何かをすることはありませんが、それ以降 これはltも同じです。 -```Python hl_lines="11" -{!../../docs_src/path_params_numeric_validations/tutorial006.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial006.py hl[11] *} ## まとめ diff --git a/docs/ja/docs/tutorial/path-params.md b/docs/ja/docs/tutorial/path-params.md index d86a27cb4..1893ec12f 100644 --- a/docs/ja/docs/tutorial/path-params.md +++ b/docs/ja/docs/tutorial/path-params.md @@ -2,9 +2,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメータ」や「パス変数」を宣言できます: -```Python hl_lines="6 7" -{!../../docs_src/path_params/tutorial001.py!} -``` +{* ../../docs_src/path_params/tutorial001.py hl[6,7] *} パスパラメータ `item_id` の値は、引数 `item_id` として関数に渡されます。 @@ -18,9 +16,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー 標準のPythonの型アノテーションを使用して、関数内のパスパラメータの型を宣言できます: -```Python hl_lines="7" -{!../../docs_src/path_params/tutorial002.py!} -``` +{* ../../docs_src/path_params/tutorial002.py hl[7] *} ここでは、 `item_id` は `int` として宣言されています。 @@ -121,9 +117,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー *path operations* は順に評価されるので、 `/users/me` が `/users/{user_id}` よりも先に宣言されているか確認する必要があります: -```Python hl_lines="6 11" -{!../../docs_src/path_params/tutorial003.py!} -``` +{* ../../docs_src/path_params/tutorial003.py hl[6,11] *} それ以外の場合、 `/users/{users_id}` は `/users/me` としてもマッチします。値が「"me"」であるパラメータ `user_id` を受け取ると「考え」ます。 @@ -139,9 +133,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー そして、固定値のクラス属性を作ります。すると、その値が使用可能な値となります: -```Python hl_lines="1 6 7 8 9" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[1,6,7,8,9] *} /// info | 情報 @@ -159,9 +151,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー 次に、作成したenumクラスである`ModelName`を使用した型アノテーションをもつ*パスパラメータ*を作成します: -```Python hl_lines="16" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[16] *} ### ドキュメントの確認 @@ -177,17 +167,13 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー これは、作成した列挙型 `ModelName` の*列挙型メンバ*と比較できます: -```Python hl_lines="17" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[17] *} #### *列挙値*の取得 `model_name.value` 、もしくは一般に、 `your_enum_member.value` を使用して実際の値 (この場合は `str`) を取得できます。 -```Python hl_lines="20" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[20] *} /// tip | 豆知識 @@ -201,9 +187,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー それらはクライアントに返される前に適切な値 (この場合は文字列) に変換されます。 -```Python hl_lines="18 21 23" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *} クライアントは以下の様なJSONレスポンスを得ます: @@ -242,9 +226,7 @@ Starletteのオプションを直接使用することで、以下のURLの様 したがって、以下の様に使用できます: -```Python hl_lines="6" -{!../../docs_src/path_params/tutorial004.py!} -``` +{* ../../docs_src/path_params/tutorial004.py hl[6] *} /// tip | 豆知識 diff --git a/docs/ja/docs/tutorial/query-params-str-validations.md b/docs/ja/docs/tutorial/query-params-str-validations.md index 6450c91c4..22b89e452 100644 --- a/docs/ja/docs/tutorial/query-params-str-validations.md +++ b/docs/ja/docs/tutorial/query-params-str-validations.md @@ -4,9 +4,7 @@ 以下のアプリケーションを例にしてみましょう: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial001.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial001.py hl[9] *} クエリパラメータ `q` は `Optional[str]` 型で、`None` を許容する `str` 型を意味しており、デフォルトは `None` です。そのため、FastAPIはそれが必須ではないと理解します。 @@ -26,17 +24,13 @@ FastAPIは、 `q` はデフォルト値が `=None` であるため、必須で そのために、まずは`fastapi`から`Query`をインポートします: -```Python hl_lines="3" -{!../../docs_src/query_params_str_validations/tutorial002.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[3] *} ## デフォルト値として`Query`を使用 パラメータのデフォルト値として使用し、パラメータ`max_length`を50に設定します: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial002.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[9] *} デフォルト値`None`を`Query(default=None)`に置き換える必要があるので、`Query`の最初の引数はデフォルト値を定義するのと同じです。 @@ -86,17 +80,13 @@ q: Union[str, None] = Query(default=None, max_length=50) パラメータ`min_length`も追加することができます: -```Python hl_lines="10" -{!../../docs_src/query_params_str_validations/tutorial003.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial003.py hl[10] *} ## 正規表現の追加 パラメータが一致するべき正規表現を定義することができます: -```Python hl_lines="11" -{!../../docs_src/query_params_str_validations/tutorial004.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial004.py hl[11] *} この特定の正規表現は受け取ったパラメータの値をチェックします: @@ -114,9 +104,7 @@ q: Union[str, None] = Query(default=None, max_length=50) クエリパラメータ`q`の`min_length`を`3`とし、デフォルト値を`fixedquery`としてみましょう: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial005.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial005.py hl[7] *} /// note | 備考 @@ -146,9 +134,7 @@ q: Union[str, None] = Query(default=None, min_length=3) そのため、`Query`を使用して必須の値を宣言する必要がある場合は、第一引数に`...`を使用することができます: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial006.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial006.py hl[7] *} /// info | 情報 @@ -164,9 +150,7 @@ q: Union[str, None] = Query(default=None, min_length=3) 例えば、URL内に複数回出現するクエリパラメータ`q`を宣言するには以下のように書きます: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial011.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial011.py hl[9] *} そしてURLは以下です: @@ -201,9 +185,7 @@ http://localhost:8000/items/?q=foo&q=bar また、値が指定されていない場合はデフォルトの`list`を定義することもできます。 -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial012.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial012.py hl[9] *} 以下のURLを開くと: @@ -226,9 +208,7 @@ http://localhost:8000/items/ `List[str]`の代わりに直接`list`を使うこともできます: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial013.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial013.py hl[7] *} /// note | 備考 @@ -254,15 +234,11 @@ http://localhost:8000/items/ `title`を追加できます: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial007.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial007.py hl[9] *} `description`を追加できます: -```Python hl_lines="13" -{!../../docs_src/query_params_str_validations/tutorial008.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial008.py hl[13] *} ## エイリアスパラメータ @@ -282,9 +258,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems それならば、`alias`を宣言することができます。エイリアスはパラメータの値を見つけるのに使用されます: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial009.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial009.py hl[9] *} ## 非推奨パラメータ @@ -294,9 +268,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems その場合、`Query`にパラメータ`deprecated=True`を渡します: -```Python hl_lines="18" -{!../../docs_src/query_params_str_validations/tutorial010.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial010.py hl[18] *} ドキュメントは以下のようになります: diff --git a/docs/ja/docs/tutorial/query-params.md b/docs/ja/docs/tutorial/query-params.md index 71f78eca5..74e455579 100644 --- a/docs/ja/docs/tutorial/query-params.md +++ b/docs/ja/docs/tutorial/query-params.md @@ -2,9 +2,7 @@ パスパラメータではない関数パラメータを宣言すると、それらは自動的に "クエリ" パラメータとして解釈されます。 -```Python hl_lines="9" -{!../../docs_src/query_params/tutorial001.py!} -``` +{* ../../docs_src/query_params/tutorial001.py hl[9] *} クエリはURL内で `?` の後に続くキーとバリューの組で、 `&` で区切られています。 @@ -63,9 +61,7 @@ http://127.0.0.1:8000/items/?skip=20 同様に、デフォルト値を `None` とすることで、オプショナルなクエリパラメータを宣言できます: -```Python hl_lines="9" -{!../../docs_src/query_params/tutorial002.py!} -``` +{* ../../docs_src/query_params/tutorial002.py hl[9] *} この場合、関数パラメータ `q` はオプショナルとなり、デフォルトでは `None` になります。 @@ -79,9 +75,7 @@ http://127.0.0.1:8000/items/?skip=20 `bool` 型も宣言できます。これは以下の様に変換されます: -```Python hl_lines="9" -{!../../docs_src/query_params/tutorial003.py!} -``` +{* ../../docs_src/query_params/tutorial003.py hl[9] *} この場合、以下にアクセスすると: @@ -123,9 +117,7 @@ http://127.0.0.1:8000/items/foo?short=yes 名前で判別されます: -```Python hl_lines="8 10" -{!../../docs_src/query_params/tutorial004.py!} -``` +{* ../../docs_src/query_params/tutorial004.py hl[8,10] *} ## 必須のクエリパラメータ @@ -135,9 +127,7 @@ http://127.0.0.1:8000/items/foo?short=yes しかしクエリパラメータを必須にしたい場合は、ただデフォルト値を宣言しなければよいです: -```Python hl_lines="6-7" -{!../../docs_src/query_params/tutorial005.py!} -``` +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} ここで、クエリパラメータ `needy` は `str` 型の必須のクエリパラメータです @@ -181,9 +171,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy そして当然、あるパラメータを必須に、別のパラメータにデフォルト値を設定し、また別のパラメータをオプショナルにできます: -```Python hl_lines="10" -{!../../docs_src/query_params/tutorial006.py!} -``` +{* ../../docs_src/query_params/tutorial006.py hl[10] *} この場合、3つのクエリパラメータがあります。: diff --git a/docs/ja/docs/tutorial/request-forms-and-files.md b/docs/ja/docs/tutorial/request-forms-and-files.md index 1e4237b20..110e3106a 100644 --- a/docs/ja/docs/tutorial/request-forms-and-files.md +++ b/docs/ja/docs/tutorial/request-forms-and-files.md @@ -12,17 +12,13 @@ ## `File`と`Form`のインポート -```Python hl_lines="1" -{!../../docs_src/request_forms_and_files/tutorial001.py!} -``` +{* ../../docs_src/request_forms_and_files/tutorial001.py hl[1] *} ## `File`と`Form`のパラメータの定義 ファイルやフォームのパラメータは`Body`や`Query`の場合と同じように作成します: -```Python hl_lines="8" -{!../../docs_src/request_forms_and_files/tutorial001.py!} -``` +{* ../../docs_src/request_forms_and_files/tutorial001.py hl[8] *} ファイルとフォームフィールドがフォームデータとしてアップロードされ、ファイルとフォームフィールドを受け取ります。 diff --git a/docs/ja/docs/tutorial/request-forms.md b/docs/ja/docs/tutorial/request-forms.md index f130c067f..eca2cd6dc 100644 --- a/docs/ja/docs/tutorial/request-forms.md +++ b/docs/ja/docs/tutorial/request-forms.md @@ -14,17 +14,13 @@ JSONの代わりにフィールドを受け取る場合は、`Form`を使用し `fastapi`から`Form`をインポートします: -```Python hl_lines="1" -{!../../docs_src/request_forms/tutorial001.py!} -``` +{* ../../docs_src/request_forms/tutorial001.py hl[1] *} ## `Form`のパラメータの定義 `Body`や`Query`の場合と同じようにフォームパラメータを作成します: -```Python hl_lines="7" -{!../../docs_src/request_forms/tutorial001.py!} -``` +{* ../../docs_src/request_forms/tutorial001.py hl[7] *} 例えば、OAuth2仕様が使用できる方法の1つ(「パスワードフロー」と呼ばれる)では、フォームフィールドとして`username`と`password`を送信する必要があります。 diff --git a/docs/ja/docs/tutorial/response-model.md b/docs/ja/docs/tutorial/response-model.md index 97821f125..b8464a4c7 100644 --- a/docs/ja/docs/tutorial/response-model.md +++ b/docs/ja/docs/tutorial/response-model.md @@ -8,9 +8,7 @@ * `@app.delete()` * など。 -```Python hl_lines="17" -{!../../docs_src/response_model/tutorial001.py!} -``` +{* ../../docs_src/response_model/tutorial001.py hl[17] *} /// note | 備考 @@ -41,15 +39,11 @@ FastAPIは`response_model`を使って以下のことをします: ここでは`UserIn`モデルを宣言しています。それには平文のパスワードが含まれています: -```Python hl_lines="9 11" -{!../../docs_src/response_model/tutorial002.py!} -``` +{* ../../docs_src/response_model/tutorial002.py hl[9,11] *} そして、このモデルを使用して入力を宣言し、同じモデルを使って出力を宣言しています: -```Python hl_lines="17 18" -{!../../docs_src/response_model/tutorial002.py!} -``` +{* ../../docs_src/response_model/tutorial002.py hl[17,18] *} これで、ブラウザがパスワードを使ってユーザーを作成する際に、APIがレスポンスで同じパスワードを返すようになりました。 @@ -67,21 +61,15 @@ FastAPIは`response_model`を使って以下のことをします: 代わりに、平文のパスワードを持つ入力モデルと、パスワードを持たない出力モデルを作成することができます: -```Python hl_lines="9 11 16" -{!../../docs_src/response_model/tutorial003.py!} -``` +{* ../../docs_src/response_model/tutorial003.py hl[9,11,16] *} ここでは、*path operation関数*がパスワードを含む同じ入力ユーザーを返しているにもかかわらず: -```Python hl_lines="24" -{!../../docs_src/response_model/tutorial003.py!} -``` +{* ../../docs_src/response_model/tutorial003.py hl[24] *} ...`response_model`を`UserOut`と宣言したことで、パスワードが含まれていません: -```Python hl_lines="22" -{!../../docs_src/response_model/tutorial003.py!} -``` +{* ../../docs_src/response_model/tutorial003.py hl[22] *} そのため、**FastAPI** は出力モデルで宣言されていない全てのデータをフィルタリングしてくれます(Pydanticを使用)。 @@ -99,9 +87,7 @@ FastAPIは`response_model`を使って以下のことをします: レスポンスモデルにはデフォルト値を設定することができます: -```Python hl_lines="11 13 14" -{!../../docs_src/response_model/tutorial004.py!} -``` +{* ../../docs_src/response_model/tutorial004.py hl[11,13,14] *} * `description: str = None`は`None`がデフォルト値です。 * `tax: float = 10.5`は`10.5`がデフォルト値です。 @@ -115,9 +101,7 @@ FastAPIは`response_model`を使って以下のことをします: *path operation デコレータ*に`response_model_exclude_unset=True`パラメータを設定することができます: -```Python hl_lines="24" -{!../../docs_src/response_model/tutorial004.py!} -``` +{* ../../docs_src/response_model/tutorial004.py hl[24] *} そして、これらのデフォルト値はレスポンスに含まれず、実際に設定された値のみが含まれます。 @@ -205,9 +189,7 @@ FastAPIは十分に賢いので(実際には、Pydanticが十分に賢い)`d /// -```Python hl_lines="31 37" -{!../../docs_src/response_model/tutorial005.py!} -``` +{* ../../docs_src/response_model/tutorial005.py hl[31,37] *} /// tip | 豆知識 @@ -221,9 +203,7 @@ FastAPIは十分に賢いので(実際には、Pydanticが十分に賢い)`d もし`set`を使用することを忘れて、代わりに`list`や`tuple`を使用しても、FastAPIはそれを`set`に変換して正しく動作します: -```Python hl_lines="31 37" -{!../../docs_src/response_model/tutorial006.py!} -``` +{* ../../docs_src/response_model/tutorial006.py hl[31,37] *} ## まとめ diff --git a/docs/ja/docs/tutorial/response-status-code.md b/docs/ja/docs/tutorial/response-status-code.md index 56bcdaf6c..6d197d543 100644 --- a/docs/ja/docs/tutorial/response-status-code.md +++ b/docs/ja/docs/tutorial/response-status-code.md @@ -8,9 +8,7 @@ * `@app.delete()` * など。 -```Python hl_lines="6" -{!../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} /// note | 備考 @@ -76,9 +74,7 @@ HTTPでは、レスポンスの一部として3桁の数字のステータス 先ほどの例をもう一度見てみましょう: -```Python hl_lines="6" -{!../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} `201`は「作成完了」のためのステータスコードです。 @@ -86,9 +82,7 @@ HTTPでは、レスポンスの一部として3桁の数字のステータス `fastapi.status`の便利な変数を利用することができます。 -```Python hl_lines="1 6" -{!../../docs_src/response_status_code/tutorial002.py!} -``` +{* ../../docs_src/response_status_code/tutorial002.py hl[1,6] *} それらは便利です。それらは同じ番号を保持しており、その方法ではエディタの自動補完を使用してそれらを見つけることができます。 diff --git a/docs/ja/docs/tutorial/schema-extra-example.md b/docs/ja/docs/tutorial/schema-extra-example.md index 44dfad737..1834e67b2 100644 --- a/docs/ja/docs/tutorial/schema-extra-example.md +++ b/docs/ja/docs/tutorial/schema-extra-example.md @@ -10,9 +10,7 @@ JSON Schemaの追加情報を宣言する方法はいくつかあります。 Pydanticのドキュメント: スキーマのカスタマイズで説明されているように、`Config`と`schema_extra`を使ってPydanticモデルの例を宣言することができます: -```Python hl_lines="15 16 17 18 19 20 21 22 23" -{!../../docs_src/schema_extra_example/tutorial001.py!} -``` +{* ../../docs_src/schema_extra_example/tutorial001.py hl[15,16,17,18,19,20,21,22,23] *} その追加情報はそのまま出力され、JSON Schemaに追加されます。 @@ -20,9 +18,7 @@ JSON Schemaの追加情報を宣言する方法はいくつかあります。 後述する`Field`、`Path`、`Query`、`Body`などでは、任意の引数を関数に渡すことでJSON Schemaの追加情報を宣言することもできます: -```Python hl_lines="4 10 11 12 13" -{!../../docs_src/schema_extra_example/tutorial002.py!} -``` +{* ../../docs_src/schema_extra_example/tutorial002.py hl[4,10,11,12,13] *} /// warning | 注意 @@ -36,9 +32,7 @@ JSON Schemaの追加情報を宣言する方法はいくつかあります。 例えば、`Body`にボディリクエストの`example`を渡すことができます: -```Python hl_lines="21 22 23 24 25 26" -{!../../docs_src/schema_extra_example/tutorial003.py!} -``` +{* ../../docs_src/schema_extra_example/tutorial003.py hl[21,22,23,24,25,26] *} ## ドキュメントのUIの例 diff --git a/docs/ja/docs/tutorial/security/first-steps.md b/docs/ja/docs/tutorial/security/first-steps.md index 6ace1b542..0ce0f929b 100644 --- a/docs/ja/docs/tutorial/security/first-steps.md +++ b/docs/ja/docs/tutorial/security/first-steps.md @@ -20,9 +20,7 @@ `main.py`に、下記の例をコピーします: -```Python -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py *} ## 実行 @@ -128,9 +126,7 @@ OAuth2は、バックエンドやAPIがユーザーを認証するサーバー `OAuth2PasswordBearer` クラスのインスタンスを作成する時に、パラメーター`tokenUrl`を渡します。このパラメーターには、クライアント (ユーザーのブラウザで動作するフロントエンド) がトークンを取得するために`ユーザー名`と`パスワード`を送信するURLを指定します。 -```Python hl_lines="6" -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[6] *} /// tip | 豆知識 @@ -168,9 +164,7 @@ oauth2_scheme(some, parameters) これで`oauth2_scheme`を`Depends`で依存関係に渡すことができます。 -```Python hl_lines="10" -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[10] *} この依存関係は、*path operation function*のパラメーター`token`に代入される`str`を提供します。 diff --git a/docs/ja/docs/tutorial/security/get-current-user.md b/docs/ja/docs/tutorial/security/get-current-user.md index 898bbd797..9fc46c07c 100644 --- a/docs/ja/docs/tutorial/security/get-current-user.md +++ b/docs/ja/docs/tutorial/security/get-current-user.md @@ -2,9 +2,7 @@ 一つ前の章では、(依存性注入システムに基づいた)セキュリティシステムは、 *path operation関数* に `str` として `token` を与えていました: -```Python hl_lines="10" -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[10] *} しかし、それはまだそんなに有用ではありません。 @@ -16,9 +14,7 @@ ボディを宣言するのにPydanticを使用するのと同じやり方で、Pydanticを別のどんなところでも使うことができます: -```Python hl_lines="5 12-16" -{!../../docs_src/security/tutorial002.py!} -``` +{* ../../docs_src/security/tutorial002.py hl[5,12:16] *} ## 依存関係 `get_current_user` を作成 @@ -30,25 +26,19 @@ 以前直接 *path operation* の中でしていたのと同じように、新しい依存関係である `get_current_user` は `str` として `token` を受け取るようになります: -```Python hl_lines="25" -{!../../docs_src/security/tutorial002.py!} -``` +{* ../../docs_src/security/tutorial002.py hl[25] *} ## ユーザーの取得 `get_current_user` は作成した(偽物の)ユーティリティ関数を使って、 `str` としてトークンを受け取り、先ほどのPydanticの `User` モデルを返却します: -```Python hl_lines="19-22 26-27" -{!../../docs_src/security/tutorial002.py!} -``` +{* ../../docs_src/security/tutorial002.py hl[19:22,26:27] *} ## 現在のユーザーの注入 ですので、 `get_current_user` に対して同様に *path operation* の中で `Depends` を利用できます。 -```Python hl_lines="31" -{!../../docs_src/security/tutorial002.py!} -``` +{* ../../docs_src/security/tutorial002.py hl[31] *} Pydanticモデルの `User` として、 `current_user` の型を宣言することに注意してください。 @@ -103,9 +93,7 @@ Pydanticモデルの `User` として、 `current_user` の型を宣言するこ さらに、こうした何千もの *path operations* は、たった3行で表現できるのです: -```Python hl_lines="30-32" -{!../../docs_src/security/tutorial002.py!} -``` +{* ../../docs_src/security/tutorial002.py hl[30:32] *} ## まとめ diff --git a/docs/ja/docs/tutorial/security/oauth2-jwt.md b/docs/ja/docs/tutorial/security/oauth2-jwt.md index 825a1b2b3..4859819cc 100644 --- a/docs/ja/docs/tutorial/security/oauth2-jwt.md +++ b/docs/ja/docs/tutorial/security/oauth2-jwt.md @@ -118,9 +118,7 @@ PassLibのcontextには、検証だけが許された非推奨の古いハッシ さらに、ユーザーを認証して返す関数も作成します。 -```Python hl_lines="7 48 55-56 59-60 69-75" -{!../../docs_src/security/tutorial004.py!} -``` +{* ../../docs_src/security/tutorial004.py hl[7,48,55:56,59:60,69:75] *} /// note | 備考 @@ -156,9 +154,7 @@ JWTトークンの署名に使用するアルゴリズム`"HS256"`を指定し 新しいアクセストークンを生成するユーティリティ関数を作成します。 -```Python hl_lines="6 12-14 28-30 78-86" -{!../../docs_src/security/tutorial004.py!} -``` +{* ../../docs_src/security/tutorial004.py hl[6,12:14,28:30,78:86] *} ## 依存関係の更新 @@ -168,9 +164,7 @@ JWTトークンの署名に使用するアルゴリズム`"HS256"`を指定し トークンが無効な場合は、すぐにHTTPエラーを返します。 -```Python hl_lines="89-106" -{!../../docs_src/security/tutorial004.py!} -``` +{* ../../docs_src/security/tutorial004.py hl[89:106] *} ## `/token` パスオペレーションの更新 @@ -178,9 +172,7 @@ JWTトークンの署名に使用するアルゴリズム`"HS256"`を指定し JWTアクセストークンを作成し、それを返します。 -```Python hl_lines="115-130" -{!../../docs_src/security/tutorial004.py!} -``` +{* ../../docs_src/security/tutorial004.py hl[115:130] *} ### JWTの"subject" `sub` についての技術的な詳細 diff --git a/docs/ja/docs/tutorial/static-files.md b/docs/ja/docs/tutorial/static-files.md index 37ea22dd7..f63f3f3b1 100644 --- a/docs/ja/docs/tutorial/static-files.md +++ b/docs/ja/docs/tutorial/static-files.md @@ -7,9 +7,7 @@ * `StaticFiles` をインポート。 * `StaticFiles()` インスタンスを生成し、特定のパスに「マウント」。 -```Python hl_lines="2 6" -{!../../docs_src/static_files/tutorial001.py!} -``` +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} /// note | 技術詳細 diff --git a/docs/ja/docs/tutorial/testing.md b/docs/ja/docs/tutorial/testing.md index b7e80cb8d..fe6c8c6b4 100644 --- a/docs/ja/docs/tutorial/testing.md +++ b/docs/ja/docs/tutorial/testing.md @@ -18,9 +18,7 @@ チェックしたい Python の標準的な式と共に、シンプルに `assert` 文を記述します。 -```Python hl_lines="2 12 15-18" -{!../../docs_src/app_testing/tutorial001.py!} -``` +{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *} /// tip | 豆知識 @@ -56,17 +54,13 @@ FastAPIアプリケーションへのリクエストの送信とは別に、テ **FastAPI** アプリに `main.py` ファイルがあるとします: -```Python -{!../../docs_src/app_testing/main.py!} -``` +{* ../../docs_src/app_testing/main.py *} ### テストファイル 次に、テストを含む `test_main.py` ファイルを作成し、`main` モジュール (`main.py`) から `app` をインポートします: -```Python -{!../../docs_src/app_testing/test_main.py!} -``` +{* ../../docs_src/app_testing/test_main.py *} ## テスト: 例の拡張 @@ -83,29 +77,13 @@ FastAPIアプリケーションへのリクエストの送信とは別に、テ これらの *path operation* には `X-Token` ヘッダーが必要です。 -//// tab | Python 3.10+ - -```Python -{!> ../../docs_src/app_testing/app_b_py310/main.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python -{!> ../../docs_src/app_testing/app_b/main.py!} -``` - -//// +{* ../../docs_src/app_testing/app_b_py310/main.py *} ### 拡張版テストファイル 次に、先程のものに拡張版のテストを加えた、`test_main_b.py` を作成します。 -```Python -{!> ../../docs_src/app_testing/app_b/test_main.py!} -``` +{* ../../docs_src/app_testing/app_b/test_main.py *} リクエストに情報を渡せるクライアントが必要で、その方法がわからない場合はいつでも、`httpx` での実現方法を検索 (Google) できます。 diff --git a/docs/ko/docs/advanced/advanced-dependencies.md b/docs/ko/docs/advanced/advanced-dependencies.md index aa5a332f8..7fa043fa3 100644 --- a/docs/ko/docs/advanced/advanced-dependencies.md +++ b/docs/ko/docs/advanced/advanced-dependencies.md @@ -18,35 +18,7 @@ Python에는 클래스의 인스턴스를 "호출 가능"하게 만드는 방법 이를 위해 `__call__` 메서드를 선언합니다: -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/dependencies/tutorial011_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | 참고 - -가능하다면 `Annotated` 버전을 사용하는 것이 좋습니다. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[12] *} 이 경우, **FastAPI**는 추가 매개변수와 하위 의존성을 확인하기 위해 `__call__`을 사용하게 되며, 나중에 *경로 연산 함수*에서 매개변수에 값을 전달할 때 이를 호출하게 됩니다. @@ -55,35 +27,7 @@ Python에는 클래스의 인스턴스를 "호출 가능"하게 만드는 방법 이제 `__init__`을 사용하여 의존성을 "매개변수화"할 수 있는 인스턴스의 매개변수를 선언할 수 있습니다: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/dependencies/tutorial011_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | 참고 - -가능하다면 `Annotated` 버전을 사용하는 것이 좋습니다. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[9] *} 이 경우, **FastAPI**는 `__init__`에 전혀 관여하지 않으며, 우리는 이 메서드를 코드에서 직접 사용하게 됩니다. @@ -91,35 +35,7 @@ Python에는 클래스의 인스턴스를 "호출 가능"하게 만드는 방법 다음과 같이 이 클래스의 인스턴스를 생성할 수 있습니다: -//// tab | Python 3.9+ - -```Python hl_lines="18" -{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial011_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | 참고 - -가능하다면 `Annotated` 버전을 사용하는 것이 좋습니다. - -/// - -```Python hl_lines="16" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[18] *} 이렇게 하면 `checker.fixed_content` 속성에 `"bar"`라는 값을 담아 의존성을 "매개변수화"할 수 있습니다. @@ -136,35 +52,7 @@ checker(q="somequery") ...그리고 이때 반환되는 값을 *경로 연산 함수*의 `fixed_content_included` 매개변수로 전달합니다: -//// tab | Python 3.9+ - -```Python hl_lines="22" -{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="21" -{!> ../../docs_src/dependencies/tutorial011_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | 참고 - -가능하다면 `Annotated` 버전을 사용하는 것이 좋습니다. - -/// - -```Python hl_lines="20" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[22] *} /// tip | 참고 diff --git a/docs/ko/docs/advanced/events.md b/docs/ko/docs/advanced/events.md index 273c9a479..ae349e7be 100644 --- a/docs/ko/docs/advanced/events.md +++ b/docs/ko/docs/advanced/events.md @@ -14,9 +14,7 @@ 응용 프로그램을 시작하기 전에 실행하려는 함수를 "startup" 이벤트로 선언합니다: -```Python hl_lines="8" -{!../../docs_src/events/tutorial001.py!} -``` +{* ../../docs_src/events/tutorial001.py hl[8] *} 이 경우 `startup` 이벤트 핸들러 함수는 단순히 몇 가지 값으로 구성된 `dict` 형식의 "데이터베이스"를 초기화합니다. @@ -28,9 +26,7 @@ 응용 프로그램이 종료될 때 실행하려는 함수를 추가하려면 `"shutdown"` 이벤트로 선언합니다: -```Python hl_lines="6" -{!../../docs_src/events/tutorial002.py!} -``` +{* ../../docs_src/events/tutorial002.py hl[6] *} 이 예제에서 `shutdown` 이벤트 핸들러 함수는 `"Application shutdown"`이라는 텍스트가 적힌 `log.txt` 파일을 추가할 것입니다. diff --git a/docs/ko/docs/advanced/response-change-status-code.md b/docs/ko/docs/advanced/response-change-status-code.md index f3cdd2ba5..1ba9aa3cc 100644 --- a/docs/ko/docs/advanced/response-change-status-code.md +++ b/docs/ko/docs/advanced/response-change-status-code.md @@ -20,9 +20,7 @@ 그리고 이 *임시* 응답 객체에서 `status_code`를 설정할 수 있습니다. -```Python hl_lines="1 9 12" -{!../../docs_src/response_change_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *} 그리고 평소처럼 원하는 객체(`dict`, 데이터베이스 모델 등)를 반환할 수 있습니다. diff --git a/docs/ko/docs/advanced/response-cookies.md b/docs/ko/docs/advanced/response-cookies.md index f762e94b5..327f20afe 100644 --- a/docs/ko/docs/advanced/response-cookies.md +++ b/docs/ko/docs/advanced/response-cookies.md @@ -6,9 +6,7 @@ 그런 다음 해당 *임시* 응답 객체에서 쿠키를 설정할 수 있습니다. -```Python hl_lines="1 8-9" -{!../../docs_src/response_cookies/tutorial002.py!} -``` +{* ../../docs_src/response_cookies/tutorial002.py hl[1,8:9] *} 그런 다음 필요한 객체(`dict`, 데이터베이스 모델 등)를 반환할 수 있습니다. @@ -25,9 +23,7 @@ 이를 위해 [Response를 직접 반환하기](response-directly.md){.internal-link target=_blank}에서 설명한 대로 응답을 생성할 수 있습니다. 그런 다음 쿠키를 설정하고 반환하면 됩니다: -```Python hl_lines="1 18" -{!../../docs_src/response_directly/tutorial002.py!} -``` +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} /// tip `Response` 매개변수를 사용하지 않고 응답을 직접 반환하는 경우, FastAPI는 이를 직접 반환한다는 점에 유의하세요. diff --git a/docs/ko/docs/advanced/response-directly.md b/docs/ko/docs/advanced/response-directly.md index aedebff9d..08d63c43c 100644 --- a/docs/ko/docs/advanced/response-directly.md +++ b/docs/ko/docs/advanced/response-directly.md @@ -34,9 +34,7 @@ Pydantic 모델로 데이터 변환을 수행하지 않으며, 내용을 다른 이러한 경우, 데이터를 응답에 전달하기 전에 `jsonable_encoder`를 사용하여 변환할 수 있습니다: -```Python hl_lines="6-7 21-22" -{!../../docs_src/response_directly/tutorial001.py!} -``` +{* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *} /// note | 기술적 세부 사항 @@ -55,9 +53,7 @@ Pydantic 모델로 데이터 변환을 수행하지 않으며, 내용을 다른 XML 내용을 문자열에 넣고, 이를 `Response`에 넣어 반환할 수 있습니다: -```Python hl_lines="1 18" -{!../../docs_src/response_directly/tutorial002.py!} -``` +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} ## 참고 사항 `Response`를 직접 반환할 때, 그 데이터는 자동으로 유효성 검사되거나, 변환(직렬화)되거나, 문서화되지 않습니다. diff --git a/docs/ko/docs/advanced/response-headers.md b/docs/ko/docs/advanced/response-headers.md index 974a06969..e8abe0be2 100644 --- a/docs/ko/docs/advanced/response-headers.md +++ b/docs/ko/docs/advanced/response-headers.md @@ -6,9 +6,7 @@ 그런 다음, 여러분은 해당 *임시* 응답 객체에서 헤더를 설정할 수 있습니다. -```Python hl_lines="1 7-8" -{!../../docs_src/response_headers/tutorial002.py!} -``` +{* ../../docs_src/response_headers/tutorial002.py hl[1,7:8] *} 그 후, 일반적으로 사용하듯이 필요한 객체(`dict`, 데이터베이스 모델 등)를 반환할 수 있습니다. @@ -24,9 +22,7 @@ [응답을 직접 반환하기](response-directly.md){.internal-link target=_blank}에서 설명한 대로 응답을 생성하고, 헤더를 추가 매개변수로 전달하세요. -```Python hl_lines="10-12" -{!../../docs_src/response_headers/tutorial001.py!} -``` +{* ../../docs_src/response_headers/tutorial001.py hl[10:12] *} /// note | 기술적 세부사항 diff --git a/docs/ko/docs/advanced/testing-events.md b/docs/ko/docs/advanced/testing-events.md index dc082412a..502762f23 100644 --- a/docs/ko/docs/advanced/testing-events.md +++ b/docs/ko/docs/advanced/testing-events.md @@ -2,6 +2,4 @@ 테스트에서 이벤트 핸들러(`startup` 및 `shutdown`)를 실행해야 하는 경우, `with` 문과 함께 `TestClient`를 사용할 수 있습니다. -```Python hl_lines="9-12 20-24" -{!../../docs_src/app_testing/tutorial003.py!} -``` +{* ../../docs_src/app_testing/tutorial003.py hl[9:12,20:24] *} diff --git a/docs/ko/docs/advanced/testing-websockets.md b/docs/ko/docs/advanced/testing-websockets.md index f1580c3c3..9f3b4a451 100644 --- a/docs/ko/docs/advanced/testing-websockets.md +++ b/docs/ko/docs/advanced/testing-websockets.md @@ -4,9 +4,7 @@ 이를 위해 `with` 문에서 `TestClient`를 사용하여 WebSocket에 연결합니다: -```Python hl_lines="27-31" -{!../../docs_src/app_testing/tutorial002.py!} -``` +{* ../../docs_src/app_testing/tutorial002.py hl[27:31] *} /// note | 참고 diff --git a/docs/ko/docs/advanced/using-request-directly.md b/docs/ko/docs/advanced/using-request-directly.md index 027ea9fad..bfa4fa4db 100644 --- a/docs/ko/docs/advanced/using-request-directly.md +++ b/docs/ko/docs/advanced/using-request-directly.md @@ -29,9 +29,7 @@ 이를 위해서는 요청에 직접 접근해야 합니다. -```Python hl_lines="1 7-8" -{!../../docs_src/using_request_directly/tutorial001.py!} -``` +{* ../../docs_src/using_request_directly/tutorial001.py hl[1,7:8] *} *경로 작동 함수* 매개변수를 `Request` 타입으로 선언하면 **FastAPI**가 해당 매개변수에 `Request` 객체를 전달하는 것을 알게 됩니다. diff --git a/docs/ko/docs/advanced/wsgi.md b/docs/ko/docs/advanced/wsgi.md index 87aabf203..3e9de3e6c 100644 --- a/docs/ko/docs/advanced/wsgi.md +++ b/docs/ko/docs/advanced/wsgi.md @@ -12,9 +12,7 @@ 그 후, 해당 경로에 마운트합니다. -```Python hl_lines="2-3 23" -{!../../docs_src/wsgi/tutorial001.py!} -``` +{* ../../docs_src/wsgi/tutorial001.py hl[2:3,23] *} ## 확인하기 diff --git a/docs/ko/docs/python-types.md b/docs/ko/docs/python-types.md index 7cc98ba76..18d4b341e 100644 --- a/docs/ko/docs/python-types.md +++ b/docs/ko/docs/python-types.md @@ -22,9 +22,8 @@ 간단한 예제부터 시작해봅시다: -```Python -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} + 이 프로그램을 실행한 결과값: @@ -38,9 +37,8 @@ John Doe * `title()`로 각 첫 문자를 대문자로 변환시킵니다. * 두 단어를 중간에 공백을 두고 연결합니다. -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### 코드 수정 @@ -82,9 +80,8 @@ John Doe 이게 "타입 힌트"입니다: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + 타입힌트는 다음과 같이 기본 값을 선언하는 것과는 다릅니다: @@ -112,9 +109,8 @@ John Doe 아래 함수를 보면, 이미 타입 힌트가 적용되어 있는 걸 볼 수 있습니다: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + 편집기가 변수의 타입을 알고 있기 때문에, 자동완성 뿐 아니라 에러도 확인할 수 있습니다: @@ -122,9 +118,8 @@ John Doe 이제 고쳐야하는 걸 알기 때문에, `age`를 `str(age)`과 같이 문자열로 바꾸게 됩니다: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## 타입 선언 @@ -143,9 +138,8 @@ John Doe * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### 타입 매개변수를 활용한 Generic(제네릭) 타입 @@ -161,9 +155,8 @@ John Doe `typing`에서 `List`(대문자 `L`)를 import 합니다. -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[1] *} + 콜론(`:`) 문법을 이용하여 변수를 선언합니다. @@ -171,9 +164,8 @@ John Doe 이때 배열은 내부 타입을 포함하는 타입이기 때문에 대괄호 안에 넣어줍니다. -```Python hl_lines="4" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[4] *} + /// tip | 팁 @@ -199,9 +191,8 @@ John Doe `tuple`과 `set`도 동일하게 선언할 수 있습니다. -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial007.py!} -``` +{* ../../docs_src/python_types/tutorial007.py hl[1,4] *} + 이 뜻은 아래와 같습니다: @@ -216,9 +207,8 @@ John Doe 두 번째 매개변수는 `dict`의 값(value)입니다. -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial008.py!} -``` +{* ../../docs_src/python_types/tutorial008.py hl[1,4] *} + 이 뜻은 아래와 같습니다: @@ -255,15 +245,13 @@ John Doe 이름(name)을 가진 `Person` 클래스가 있다고 해봅시다. -```Python hl_lines="1-3" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + 그렇게 하면 변수를 `Person`이라고 선언할 수 있게 됩니다. -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + 그리고 역시나 모든 에디터 도움을 받게 되겠죠. @@ -283,9 +271,8 @@ John Doe Pydantic 공식 문서 예시: -```Python -{!../../docs_src/python_types/tutorial011.py!} -``` +{* ../../docs_src/python_types/tutorial011.py *} + /// info | 정보 diff --git a/docs/ko/docs/tutorial/background-tasks.md b/docs/ko/docs/tutorial/background-tasks.md index 27f265608..a2c4abbd9 100644 --- a/docs/ko/docs/tutorial/background-tasks.md +++ b/docs/ko/docs/tutorial/background-tasks.md @@ -15,9 +15,7 @@ FastAPI에서는 응답을 반환한 후에 실행할 백그라운드 작업을 먼저 아래와 같이 `BackgroundTasks`를 임포트하고, `BackgroundTasks`를 _경로 작동 함수_ 에서 매개변수로 가져오고 정의합니다. -```Python hl_lines="1 13" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *} **FastAPI** 는 `BackgroundTasks` 개체를 생성하고, 매개 변수로 전달합니다. @@ -33,17 +31,13 @@ FastAPI에서는 응답을 반환한 후에 실행할 백그라운드 작업을 그리고 이 작업은 `async`와 `await`를 사용하지 않으므로 일반 `def` 함수로 선언합니다. -```Python hl_lines="6-9" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *} ## 백그라운드 작업 추가 _경로 작동 함수_ 내에서 작업 함수를 `.add_task()` 함수 통해 _백그라운드 작업_ 개체에 전달합니다. -```Python hl_lines="14" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[14] *} `.add_task()` 함수는 다음과 같은 인자를 받습니다 : @@ -57,21 +51,7 @@ _경로 작동 함수_ 내에서 작업 함수를 `.add_task()` 함수 통해 _ **FastAPI**는 각 경우에 수행할 작업과 동일한 개체를 내부적으로 재사용하기에, 모든 백그라운드 작업이 함께 병합되고 나중에 백그라운드에서 실행됩니다. -//// tab | Python 3.6 and above - -```Python hl_lines="13 15 22 25" -{!> ../../docs_src/background_tasks/tutorial002.py!} -``` - -//// - -//// tab | Python 3.10 and above - -```Python hl_lines="11 13 20 23" -{!> ../../docs_src/background_tasks/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/background_tasks/tutorial002.py hl[13,15,22,25] *} 이 예제에서는 응답이 반환된 후에 `log.txt` 파일에 메시지가 기록됩니다. diff --git a/docs/ko/docs/tutorial/body-fields.md b/docs/ko/docs/tutorial/body-fields.md index f6532f369..4708e7099 100644 --- a/docs/ko/docs/tutorial/body-fields.md +++ b/docs/ko/docs/tutorial/body-fields.md @@ -6,57 +6,7 @@ 먼저 이를 임포트해야 합니다: -//// tab | Python 3.10+ - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="2" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *} /// warning | 경고 @@ -68,57 +18,7 @@ 그 다음 모델 어트리뷰트와 함께 `Field`를 사용할 수 있습니다: -//// tab | Python 3.10+ - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12-15" -{!> ../../docs_src/body_fields/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="9-12" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *} `Field`는 `Query`, `Path`와 `Body`와 같은 방식으로 동작하며, 모두 같은 매개변수들 등을 가집니다. diff --git a/docs/ko/docs/tutorial/body-multiple-params.md b/docs/ko/docs/tutorial/body-multiple-params.md index 569ff016e..edf892dfa 100644 --- a/docs/ko/docs/tutorial/body-multiple-params.md +++ b/docs/ko/docs/tutorial/body-multiple-params.md @@ -10,9 +10,7 @@ 또한, 기본 값을 `None`으로 설정해 본문 매개변수를 선택사항으로 선언할 수 있습니다. -```Python hl_lines="19-21" -{!../../docs_src/body_multiple_params/tutorial001.py!} -``` +{* ../../docs_src/body_multiple_params/tutorial001.py hl[19:21] *} /// note | 참고 @@ -35,9 +33,7 @@ 하지만, 다중 본문 매개변수 역시 선언할 수 있습니다. 예. `item`과 `user`: -```Python hl_lines="22" -{!../../docs_src/body_multiple_params/tutorial002.py!} -``` +{* ../../docs_src/body_multiple_params/tutorial002.py hl[22] *} 이 경우에, **FastAPI**는 이 함수 안에 한 개 이상의 본문 매개변수(Pydantic 모델인 두 매개변수)가 있다고 알 것입니다. @@ -79,9 +75,7 @@ FastAPI는 요청을 자동으로 변환해, 매개변수의 `item`과 `user`를 하지만, **FastAPI**의 `Body`를 사용해 다른 본문 키로 처리하도록 제어할 수 있습니다: -```Python hl_lines="23" -{!../../docs_src/body_multiple_params/tutorial003.py!} -``` +{* ../../docs_src/body_multiple_params/tutorial003.py hl[23] *} 이 경우에는 **FastAPI**는 본문을 이와 같이 예측할 것입니다: @@ -110,9 +104,7 @@ FastAPI는 요청을 자동으로 변환해, 매개변수의 `item`과 `user`를 기본적으로 단일 값은 쿼리 매개변수로 해석되므로, 명시적으로 `Query`를 추가할 필요가 없고, 아래처럼 할 수 있습니다: -```Python hl_lines="27" -{!../../docs_src/body_multiple_params/tutorial004.py!} -``` +{* ../../docs_src/body_multiple_params/tutorial004.py hl[27] *} 이렇게: @@ -134,9 +126,7 @@ Pydantic 모델 `Item`의 `item`을 본문 매개변수로 오직 한개만 갖 하지만, 만약 모델 내용에 `item `키를 가진 JSON으로 예측하길 원한다면, 추가적인 본문 매개변수를 선언한 것처럼 `Body`의 특별한 매개변수인 `embed`를 사용할 수 있습니다: -```Python hl_lines="17" -{!../../docs_src/body_multiple_params/tutorial005.py!} -``` +{* ../../docs_src/body_multiple_params/tutorial005.py hl[17] *} 아래 처럼: diff --git a/docs/ko/docs/tutorial/body-nested-models.md b/docs/ko/docs/tutorial/body-nested-models.md index e9b1d2e18..ebd7b3ba6 100644 --- a/docs/ko/docs/tutorial/body-nested-models.md +++ b/docs/ko/docs/tutorial/body-nested-models.md @@ -5,9 +5,7 @@ 어트리뷰트를 서브타입으로 정의할 수 있습니다. 예를 들어 파이썬 `list`는: -```Python hl_lines="14" -{!../../docs_src/body_nested_models/tutorial001.py!} -``` +{* ../../docs_src/body_nested_models/tutorial001.py hl[14] *} 이는 `tags`를 항목 리스트로 만듭니다. 각 항목의 타입을 선언하지 않더라도요. @@ -19,9 +17,7 @@ 먼저, 파이썬 표준 `typing` 모듈에서 `List`를 임포트합니다: -```Python hl_lines="1" -{!../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *} ### 타입 매개변수로 `List` 선언 @@ -42,9 +38,7 @@ my_list: List[str] 마찬가지로 예제에서 `tags`를 구체적으로 "문자열의 리스트"로 만들 수 있습니다: -```Python hl_lines="14" -{!../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[14] *} ## 집합 타입 @@ -54,9 +48,7 @@ my_list: List[str] 그렇다면 `Set`을 임포트 하고 `tags`를 `str`의 `set`으로 선언할 수 있습니다: -```Python hl_lines="1 14" -{!../../docs_src/body_nested_models/tutorial003.py!} -``` +{* ../../docs_src/body_nested_models/tutorial003.py hl[1,14] *} 덕분에 중복 데이터가 있는 요청을 수신하더라도 고유한 항목들의 집합으로 변환됩니다. @@ -78,17 +70,13 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. 예를 들어, `Image` 모델을 선언할 수 있습니다: -```Python hl_lines="9-11" -{!../../docs_src/body_nested_models/tutorial004.py!} -``` +{* ../../docs_src/body_nested_models/tutorial004.py hl[9:11] *} ### 서브모듈을 타입으로 사용 그리고 어트리뷰트의 타입으로 사용할 수 있습니다: -```Python hl_lines="20" -{!../../docs_src/body_nested_models/tutorial004.py!} -``` +{* ../../docs_src/body_nested_models/tutorial004.py hl[20] *} 이는 **FastAPI**가 다음과 유사한 본문을 기대한다는 것을 의미합니다: @@ -121,9 +109,7 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. 예를 들어 `Image` 모델 안에 `url` 필드를 `str` 대신 Pydantic의 `HttpUrl`로 선언할 수 있습니다: -```Python hl_lines="4 10" -{!../../docs_src/body_nested_models/tutorial005.py!} -``` +{* ../../docs_src/body_nested_models/tutorial005.py hl[4,10] *} 이 문자열이 유효한 URL인지 검사하고 JSON 스키마/OpenAPI로 문서화 됩니다. @@ -131,9 +117,7 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. `list`, `set` 등의 서브타입으로 Pydantic 모델을 사용할 수도 있습니다: -```Python hl_lines="20" -{!../../docs_src/body_nested_models/tutorial006.py!} -``` +{* ../../docs_src/body_nested_models/tutorial006.py hl[20] *} 아래와 같은 JSON 본문으로 예상(변환, 검증, 문서화 등을)합니다: @@ -171,9 +155,7 @@ Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. 단독으로 깊게 중첩된 모델을 정의할 수 있습니다: -```Python hl_lines="9 14 20 23 27" -{!../../docs_src/body_nested_models/tutorial007.py!} -``` +{* ../../docs_src/body_nested_models/tutorial007.py hl[9,14,20,23,27] *} /// info | 정보 @@ -191,9 +173,7 @@ images: List[Image] 이를 아래처럼: -```Python hl_lines="15" -{!../../docs_src/body_nested_models/tutorial008.py!} -``` +{* ../../docs_src/body_nested_models/tutorial008.py hl[15] *} ## 어디서나 편집기 지원 @@ -223,9 +203,7 @@ Pydantic 모델 대신에 `dict`를 직접 사용하여 작업할 경우, 이러 이 경우, `float` 값을 가진 `int` 키가 있는 모든 `dict`를 받아들입니다: -```Python hl_lines="15" -{!../../docs_src/body_nested_models/tutorial009.py!} -``` +{* ../../docs_src/body_nested_models/tutorial009.py hl[15] *} /// tip | 팁 diff --git a/docs/ko/docs/tutorial/body.md b/docs/ko/docs/tutorial/body.md index 9e614ef1c..b3914fa4b 100644 --- a/docs/ko/docs/tutorial/body.md +++ b/docs/ko/docs/tutorial/body.md @@ -22,21 +22,7 @@ 먼저 `pydantic`에서 `BaseModel`를 임포트해야 합니다: -//// tab | Python 3.10+ - -```Python hl_lines="2" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// +{* ../../docs_src/body/tutorial001_py310.py hl[2] *} ## 여러분의 데이터 모델 만들기 @@ -44,21 +30,7 @@ 모든 어트리뷰트에 대해 표준 파이썬 타입을 사용합니다: -//// tab | Python 3.10+ - -```Python hl_lines="5-9" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="7-11" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// +{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *} 쿼리 매개변수를 선언할 때와 같이, 모델 어트리뷰트가 기본 값을 가지고 있어도 이는 필수가 아닙니다. 그외에는 필수입니다. 그저 `None`을 사용하여 선택적으로 만들 수 있습니다. @@ -86,21 +58,7 @@ 여러분의 *경로 작동*에 추가하기 위해, 경로 매개변수 그리고 쿼리 매개변수에서 선언했던 것과 같은 방식으로 선언하면 됩니다. -//// tab | Python 3.10+ - -```Python hl_lines="16" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// +{* ../../docs_src/body/tutorial001_py310.py hl[16] *} ...그리고 만들어낸 모델인 `Item`으로 타입을 선언합니다. @@ -167,21 +125,7 @@ 함수 안에서 모델 객체의 모든 어트리뷰트에 직접 접근 가능합니다: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/body/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="21" -{!> ../../docs_src/body/tutorial002.py!} -``` - -//// +{* ../../docs_src/body/tutorial002_py310.py hl[19] *} ## 요청 본문 + 경로 매개변수 @@ -189,21 +133,7 @@ **FastAPI**는 경로 매개변수와 일치하는 함수 매개변수가 **경로에서 가져와야 한다**는 것을 인지하며, Pydantic 모델로 선언된 그 함수 매개변수는 **요청 본문에서 가져와야 한다**는 것을 인지할 것입니다. -//// tab | Python 3.10+ - -```Python hl_lines="15-16" -{!> ../../docs_src/body/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17-18" -{!> ../../docs_src/body/tutorial003.py!} -``` - -//// +{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *} ## 요청 본문 + 경로 + 쿼리 매개변수 @@ -211,21 +141,7 @@ **FastAPI**는 각각을 인지하고 데이터를 옳바른 위치에 가져올 것입니다. -//// tab | Python 3.10+ - -```Python hl_lines="16" -{!> ../../docs_src/body/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/body/tutorial004.py!} -``` - -//// +{* ../../docs_src/body/tutorial004_py310.py hl[16] *} 함수 매개변수는 다음을 따라서 인지하게 됩니다: diff --git a/docs/ko/docs/tutorial/cookie-params.md b/docs/ko/docs/tutorial/cookie-params.md index 427539210..fba756d49 100644 --- a/docs/ko/docs/tutorial/cookie-params.md +++ b/docs/ko/docs/tutorial/cookie-params.md @@ -6,57 +6,7 @@ 먼저 `Cookie`를 임포트합니다: -//// tab | Python 3.10+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[3] *} ## `Cookie` 매개변수 선언 @@ -64,57 +14,7 @@ 첫 번째 값은 기본값이며, 추가 검증이나 어노테이션 매개변수 모두 전달할 수 있습니다: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/cookie_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9] *} /// note | 기술 세부사항 diff --git a/docs/ko/docs/tutorial/cors.md b/docs/ko/docs/tutorial/cors.md index 0222e6258..1ef5a7480 100644 --- a/docs/ko/docs/tutorial/cors.md +++ b/docs/ko/docs/tutorial/cors.md @@ -46,9 +46,7 @@ * 특정한 HTTP 메소드(`POST`, `PUT`) 또는 와일드카드 `"*"` 를 사용한 모든 HTTP 메소드. * 특정한 HTTP 헤더 또는 와일드카드 `"*"` 를 사용한 모든 HTTP 헤더. -```Python hl_lines="2 6-11 13-19" -{!../../docs_src/cors/tutorial001.py!} -``` +{* ../../docs_src/cors/tutorial001.py hl[2,6:11,13:19] *} `CORSMiddleware` 에서 사용하는 기본 매개변수는 제한적이므로, 브라우저가 교차-도메인 상황에서 특정한 출처, 메소드, 헤더 등을 사용할 수 있도록 하려면 이들을 명시적으로 허용해야 합니다. diff --git a/docs/ko/docs/tutorial/debugging.md b/docs/ko/docs/tutorial/debugging.md index fcb68b565..e42f1ba88 100644 --- a/docs/ko/docs/tutorial/debugging.md +++ b/docs/ko/docs/tutorial/debugging.md @@ -6,9 +6,7 @@ FastAPI 애플리케이션에서 `uvicorn`을 직접 임포트하여 실행합니다 -```Python hl_lines="1 15" -{!../../docs_src/debugging/tutorial001.py!} -``` +{* ../../docs_src/debugging/tutorial001.py hl[1,15] *} ### `__name__ == "__main__"` 에 대하여 diff --git a/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md index 41e48aefc..3e5cdcc8c 100644 --- a/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,21 +6,7 @@ 이전 예제에서, 우리는 의존성(의존 가능한) 함수에서 `딕셔너리`객체를 반환하고 있었습니다: -//// tab | 파이썬 3.6 이상 - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="7" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001.py hl[9] *} 우리는 *경로 작동 함수*의 매개변수 `commons`에서 `딕셔너리` 객체를 얻습니다. @@ -81,57 +67,15 @@ FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래 그래서, 우리는 위 예제에서의 `common_paramenters` 의존성을 클래스 `CommonQueryParams`로 바꿀 수 있습니다. -//// tab | 파이썬 3.6 이상 - -```Python hl_lines="11-15" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="9-13" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002.py hl[11:15] *} 클래스의 인스턴스를 생성하는 데 사용되는 `__init__` 메서드에 주목하기 바랍니다: -//// tab | 파이썬 3.6 이상 - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="10" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002.py hl[12] *} ...이전 `common_parameters`와 동일한 매개변수를 가집니다: -//// tab | 파이썬 3.6 이상 - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="6" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001.py hl[9] *} 이 매개변수들은 **FastAPI**가 의존성을 "해결"하기 위해 사용할 것입니다 @@ -147,21 +91,7 @@ FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래 이제 아래의 클래스를 이용해서 의존성을 정의할 수 있습니다. -//// tab | 파이썬 3.6 이상 - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002.py hl[19] *} **FastAPI**는 `CommonQueryParams` 클래스를 호출합니다. 이것은 해당 클래스의 "인스턴스"를 생성하고 그 인스턴스는 함수의 매개변수 `commons`로 전달됩니다. @@ -200,21 +130,7 @@ commons = Depends(CommonQueryParams) ..전체적인 코드는 아래와 같습니다: -//// tab | 파이썬 3.6 이상 - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial003.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial003.py hl[19] *} 그러나 자료형을 선언하면 에디터가 매개변수 `commons`로 전달될 것이 무엇인지 알게 되고, 이를 통해 코드 완성, 자료형 확인 등에 도움이 될 수 있으므로 권장됩니다. @@ -248,21 +164,7 @@ commons: CommonQueryParams = Depends() 아래에 같은 예제가 있습니다: -//// tab | 파이썬 3.6 이상 - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial004.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial004.py hl[19] *} ...이렇게 코드를 단축하여도 **FastAPI**는 무엇을 해야하는지 알고 있습니다. diff --git a/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index fab636b7f..4a3854cef 100644 --- a/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -14,35 +14,7 @@ `Depends()`로 된 `list`이어야합니다: -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[19] *} 이러한 의존성들은 기존 의존성들과 같은 방식으로 실행/해결됩니다. 그러나 값은 (무엇이든 반환한다면) *경로 작동 함수*에 제공되지 않습니다. @@ -72,69 +44,13 @@ (헤더같은) 요청 요구사항이나 하위-의존성을 선언할 수 있습니다: -//// tab | Python 3.9+ - -```Python hl_lines="8 13" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="7 12" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="6 11" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[8,13] *} ### 오류 발생시키기 다음 의존성은 기존 의존성과 동일하게 예외를 `raise`를 일으킬 수 있습니다: -//// tab | Python 3.9+ - -```Python hl_lines="10 15" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 14" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="8 13" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[10,15] *} ### 값 반환하기 @@ -142,35 +58,7 @@ 그래서 이미 다른 곳에서 사용된 (값을 반환하는) 일반적인 의존성을 재사용할 수 있고, 비록 값은 사용되지 않지만 의존성은 실행될 것입니다: -//// tab | Python 3.9+ - -```Python hl_lines="11 16" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10 15" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="9 14" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[11,16] *} ## *경로 작동* 모음에 대한 의존성 diff --git a/docs/ko/docs/tutorial/dependencies/global-dependencies.md b/docs/ko/docs/tutorial/dependencies/global-dependencies.md index 0ad8b55fd..0d0e7684d 100644 --- a/docs/ko/docs/tutorial/dependencies/global-dependencies.md +++ b/docs/ko/docs/tutorial/dependencies/global-dependencies.md @@ -6,35 +6,7 @@ 그런 경우에, 애플리케이션의 모든 *경로 작동*에 적용될 것입니다: -//// tab | Python 3.9+ - -```Python hl_lines="16" -{!> ../../docs_src/dependencies/tutorial012_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="16" -{!> ../../docs_src/dependencies/tutorial012_an.py!} -``` - -//// - -//// tab | Python 3.8 Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="15" -{!> ../../docs_src/dependencies/tutorial012.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial012_an_py39.py hl[16] *} 그리고 [*경로 작동 데코레이터*에 `dependencies` 추가하기](dependencies-in-path-operation-decorators.md){.internal-link target=_blank}에 대한 아이디어는 여전히 적용되지만 여기에서는 앱에 있는 모든 *경로 작동*에 적용됩니다. diff --git a/docs/ko/docs/tutorial/dependencies/index.md b/docs/ko/docs/tutorial/dependencies/index.md index 1aba6e787..b35a41e37 100644 --- a/docs/ko/docs/tutorial/dependencies/index.md +++ b/docs/ko/docs/tutorial/dependencies/index.md @@ -31,57 +31,7 @@ *경로 작동 함수*가 가질 수 있는 모든 매개변수를 갖는 단순한 함수입니다: -//// tab | Python 3.10+ - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="8-11" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-12" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="6-7" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="8-11" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *} 이게 다입니다. @@ -113,113 +63,13 @@ FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 ### `Depends` 불러오기 -//// tab | Python 3.10+ - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *} ### "의존자"에 의존성 명시하기 *경로 작동 함수*의 매개변수로 `Body`, `Query` 등을 사용하는 방식과 같이 새로운 매개변수로 `Depends`를 사용합니다: -//// tab | Python 3.10+ - -```Python hl_lines="13 18" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="15 20" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="16 21" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="11 16" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ Annotated가 없는 경우 - -/// tip | 팁 - -가능하다면 `Annotated`가 달린 버전을 권장합니다. - -/// - -```Python hl_lines="15 20" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *} 비록 `Body`, `Query` 등을 사용하는 것과 같은 방식으로 여러분의 함수의 매개변수에 있는 `Depends`를 사용하지만, `Depends`는 약간 다르게 작동합니다. @@ -276,29 +126,7 @@ commons: Annotated[dict, Depends(common_parameters)] 하지만 `Annotated`를 사용하고 있기에, `Annotated` 값을 변수에 저장하고 여러 장소에서 사용할 수 있습니다: -//// tab | Python 3.10+ - -```Python hl_lines="12 16 21" -{!> ../../docs_src/dependencies/tutorial001_02_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14 18 23" -{!> ../../docs_src/dependencies/tutorial001_02_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15 19 24" -{!> ../../docs_src/dependencies/tutorial001_02_an.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *} /// tip | 팁 diff --git a/docs/ko/docs/tutorial/encoder.md b/docs/ko/docs/tutorial/encoder.md index 52277f258..4323957f4 100644 --- a/docs/ko/docs/tutorial/encoder.md +++ b/docs/ko/docs/tutorial/encoder.md @@ -20,9 +20,7 @@ JSON 호환 가능 데이터만 수신하는 `fake_db` 데이터베이스가 존 Pydantic 모델과 같은 객체를 받고 JSON 호환 가능한 버전으로 반환합니다: -```Python hl_lines="5 22" -{!../../docs_src/encoder/tutorial001.py!} -``` +{* ../../docs_src/encoder/tutorial001.py hl[5,22] *} 이 예시는 Pydantic 모델을 `dict`로, `datetime` 형식을 `str`로 변환합니다. diff --git a/docs/ko/docs/tutorial/extra-data-types.md b/docs/ko/docs/tutorial/extra-data-types.md index 8baaa64fc..4a41ba0dc 100644 --- a/docs/ko/docs/tutorial/extra-data-types.md +++ b/docs/ko/docs/tutorial/extra-data-types.md @@ -55,108 +55,8 @@ 위의 몇몇 자료형을 매개변수로 사용하는 *경로 작동* 예시입니다. -//// tab | Python 3.10+ - -```Python hl_lines="1 3 12-16" -{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="1 3 12-16" -{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 3 13-17" -{!> ../../docs_src/extra_data_types/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1 2 11-15" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1 2 12-16" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *} 함수 안의 매개변수가 그들만의 데이터 자료형을 가지고 있으며, 예를 들어, 다음과 같이 날짜를 조작할 수 있음을 참고하십시오: -//// tab | Python 3.10+ - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="19-20" -{!> ../../docs_src/extra_data_types/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="17-18" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *} diff --git a/docs/ko/docs/tutorial/first-steps.md b/docs/ko/docs/tutorial/first-steps.md index 4a689b74a..174f00d46 100644 --- a/docs/ko/docs/tutorial/first-steps.md +++ b/docs/ko/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ 가장 단순한 FastAPI 파일은 다음과 같이 보일 것입니다: -```Python -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} 위 코드를 `main.py`에 복사합니다. @@ -133,9 +131,7 @@ API와 통신하는 클라이언트(프론트엔드, 모바일, IoT 애플리케 ### 1 단계: `FastAPI` 임포트 -```Python hl_lines="1" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI`는 당신의 API를 위한 모든 기능을 제공하는 파이썬 클래스입니다. @@ -149,9 +145,7 @@ API와 통신하는 클라이언트(프론트엔드, 모바일, IoT 애플리케 ### 2 단계: `FastAPI` "인스턴스" 생성 -```Python hl_lines="3" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[3] *} 여기에서 `app` 변수는 `FastAPI` 클래스의 "인스턴스"가 됩니다. @@ -171,9 +165,7 @@ $ uvicorn main:app --reload 아래처럼 앱을 만든다면: -```Python hl_lines="3" -{!../../docs_src/first_steps/tutorial002.py!} -``` +{* ../../docs_src/first_steps/tutorial002.py hl[3] *} 이를 `main.py` 파일에 넣고, `uvicorn`을 아래처럼 호출해야 합니다: @@ -250,9 +242,7 @@ API를 설계할 때 일반적으로 특정 행동을 수행하기 위해 특정 #### *경로 작동 데코레이터* 정의 -```Python hl_lines="6" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[6] *} `@app.get("/")`은 **FastAPI**에게 바로 아래에 있는 함수가 다음으로 이동하는 요청을 처리한다는 것을 알려줍니다. @@ -306,9 +296,7 @@ API를 설계할 때 일반적으로 특정 행동을 수행하기 위해 특정 * **작동**: 은 `get`입니다. * **함수**: 는 "데코레이터" 아래에 있는 함수입니다 (`@app.get("/")` 아래). -```Python hl_lines="7" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[7] *} 이것은 파이썬 함수입니다. @@ -320,9 +308,7 @@ URL "`/`"에 대한 `GET` 작동을 사용하는 요청을 받을 때마다 **Fa `async def`을 이용하는 대신 일반 함수로 정의할 수 있습니다: -```Python hl_lines="7" -{!../../docs_src/first_steps/tutorial003.py!} -``` +{* ../../docs_src/first_steps/tutorial003.py hl[7] *} /// note | 참고 @@ -332,9 +318,7 @@ URL "`/`"에 대한 `GET` 작동을 사용하는 요청을 받을 때마다 **Fa ### 5 단계: 콘텐츠 반환 -```Python hl_lines="8" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[8] *} `dict`, `list`, 단일값을 가진 `str`, `int` 등을 반환할 수 있습니다. diff --git a/docs/ko/docs/tutorial/header-params.md b/docs/ko/docs/tutorial/header-params.md index 972f52a33..7379eb2a0 100644 --- a/docs/ko/docs/tutorial/header-params.md +++ b/docs/ko/docs/tutorial/header-params.md @@ -6,9 +6,7 @@ 먼저 `Header`를 임포트합니다: -```Python hl_lines="3" -{!../../docs_src/header_params/tutorial001.py!} -``` +{* ../../docs_src/header_params/tutorial001.py hl[3] *} ## `Header` 매개변수 선언 @@ -16,9 +14,7 @@ 첫 번째 값은 기본값이며, 추가 검증이나 어노테이션 매개변수 모두 전달할 수 있습니다: -```Python hl_lines="9" -{!../../docs_src/header_params/tutorial001.py!} -``` +{* ../../docs_src/header_params/tutorial001.py hl[9] *} /// note | 기술 세부사항 @@ -50,9 +46,7 @@ 만약 언더스코어를 하이픈으로 자동 변환을 비활성화해야 할 어떤 이유가 있다면, `Header`의 `convert_underscores` 매개변수를 `False`로 설정하십시오: -```Python hl_lines="10" -{!../../docs_src/header_params/tutorial002.py!} -``` +{* ../../docs_src/header_params/tutorial002.py hl[10] *} /// warning | 경고 @@ -70,9 +64,7 @@ 예를 들어, 두 번 이상 나타날 수 있는 `X-Token`헤더를 선언하려면, 다음과 같이 작성합니다: -```Python hl_lines="9" -{!../../docs_src/header_params/tutorial003.py!} -``` +{* ../../docs_src/header_params/tutorial003.py hl[9] *} 다음과 같은 두 개의 HTTP 헤더를 전송하여 해당 *경로* 와 통신할 경우: diff --git a/docs/ko/docs/tutorial/metadata.md b/docs/ko/docs/tutorial/metadata.md index 87531152c..a50dfa2e7 100644 --- a/docs/ko/docs/tutorial/metadata.md +++ b/docs/ko/docs/tutorial/metadata.md @@ -1,4 +1,3 @@ - # 메타데이터 및 문서화 URL **FastAPI** 응용 프로그램에서 다양한 메타데이터 구성을 사용자 맞춤 설정할 수 있습니다. @@ -19,9 +18,7 @@ OpenAPI 명세 및 자동화된 API 문서 UI에 사용되는 다음 필드를 다음과 같이 설정할 수 있습니다: -```Python hl_lines="3-16 19-32" -{!../../docs_src/metadata/tutorial001.py!} -``` +{* ../../docs_src/metadata/tutorial001.py hl[3:16,19:32] *} /// tip @@ -39,9 +36,7 @@ OpenAPI 3.1.0 및 FastAPI 0.99.0부터 `license_info`에 `identifier`를 URL 대 예: -```Python hl_lines="31" -{!../../docs_src/metadata/tutorial001_1.py!} -``` +{* ../../docs_src/metadata/tutorial001_1.py hl[31] *} ## 태그에 대한 메타데이터 @@ -61,9 +56,7 @@ OpenAPI 3.1.0 및 FastAPI 0.99.0부터 `license_info`에 `identifier`를 URL 대 `users` 및 `items`에 대한 태그 예시와 함께 메타데이터를 생성하고 이를 `openapi_tags` 매개변수로 전달해 보겠습니다: -```Python hl_lines="3-16 18" -{!../../docs_src/metadata/tutorial004.py!} -``` +{* ../../docs_src/metadata/tutorial004.py hl[3:16,18] *} 설명 안에 마크다운을 사용할 수 있습니다. 예를 들어 "login"은 굵게(**login**) 표시되고, "fancy"는 기울임꼴(_fancy_)로 표시됩니다. @@ -77,9 +70,7 @@ OpenAPI 3.1.0 및 FastAPI 0.99.0부터 `license_info`에 `identifier`를 URL 대 `tags` 매개변수를 *경로 작동* 및 `APIRouter`와 함께 사용하여 태그에 할당할 수 있습니다: -```Python hl_lines="21 26" -{!../../docs_src/metadata/tutorial004.py!} -``` +{* ../../docs_src/metadata/tutorial004.py hl[21,26] *} /// info @@ -107,9 +98,7 @@ OpenAPI 구조는 기본적으로 `/openapi.json`에서 제공됩니다. 예를 들어, 이를 `/api/v1/openapi.json`에 제공하도록 설정하려면: -```Python hl_lines="3" -{!../../docs_src/metadata/tutorial002.py!} -``` +{* ../../docs_src/metadata/tutorial002.py hl[3] *} OpenAPI 구조를 완전히 비활성화하려면 `openapi_url=None`으로 설정할 수 있으며, 이를 사용하여 문서화 사용자 인터페이스도 비활성화됩니다. @@ -126,6 +115,4 @@ OpenAPI 구조를 완전히 비활성화하려면 `openapi_url=None`으로 설 예를 들어, Swagger UI를 `/documentation`에서 제공하고 ReDoc을 비활성화하려면: -```Python hl_lines="3" -{!../../docs_src/metadata/tutorial003.py!} -``` +{* ../../docs_src/metadata/tutorial003.py hl[3] *} diff --git a/docs/ko/docs/tutorial/middleware.md b/docs/ko/docs/tutorial/middleware.md index 0547066f1..3cd752a0e 100644 --- a/docs/ko/docs/tutorial/middleware.md +++ b/docs/ko/docs/tutorial/middleware.md @@ -31,9 +31,7 @@ * 그런 다음, *경로 작업*에 의해 생성된 `response` 를 반환합니다. * `response`를 반환하기 전에 추가로 `response`를 수정할 수 있습니다. -```Python hl_lines="8-9 11 14" -{!../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[8:9,11,14] *} /// tip | 팁 @@ -59,9 +57,7 @@ 예를 들어, 요청을 수행하고 응답을 생성하는데 까지 걸린 시간 값을 가지고 있는 `X-Process-Time` 같은 사용자 정의 헤더를 추가할 수 있습니다. -```Python hl_lines="10 12-13" -{!../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *} ## 다른 미들웨어 diff --git a/docs/ko/docs/tutorial/path-operation-configuration.md b/docs/ko/docs/tutorial/path-operation-configuration.md index 75a9c71ce..81914182a 100644 --- a/docs/ko/docs/tutorial/path-operation-configuration.md +++ b/docs/ko/docs/tutorial/path-operation-configuration.md @@ -16,9 +16,7 @@ 하지만 각 코드의 의미를 모른다면, `status`에 있는 단축 상수들을 사용할수 있습니다: -```Python hl_lines="3 17" -{!../../docs_src/path_operation_configuration/tutorial001.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial001.py hl[3,17] *} 각 상태 코드들은 응답에 사용되며, OpenAPI 스키마에 추가됩니다. @@ -34,9 +32,7 @@ (보통 단일 `str`인) `str`로 구성된 `list`와 함께 매개변수 `tags`를 전달하여, `경로 작동`에 태그를 추가할 수 있습니다: -```Python hl_lines="17 22 27" -{!../../docs_src/path_operation_configuration/tutorial002.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial002.py hl[17,22,27] *} 전달된 태그들은 OpenAPI의 스키마에 추가되며, 자동 문서 인터페이스에서 사용됩니다: @@ -46,9 +42,7 @@ `summary`와 `description`을 추가할 수 있습니다: -```Python hl_lines="20-21" -{!../../docs_src/path_operation_configuration/tutorial003.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial003.py hl[20:21] *} ## 독스트링으로 만든 기술 @@ -56,9 +50,7 @@ 마크다운 문법으로 독스트링을 작성할 수 있습니다, 작성된 마크다운 형식의 독스트링은 (마크다운의 들여쓰기를 고려하여) 올바르게 화면에 출력됩니다. -```Python hl_lines="19-27" -{!../../docs_src/path_operation_configuration/tutorial004.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial004.py hl[19:27] *} 이는 대화형 문서에서 사용됩니다: @@ -68,9 +60,7 @@ `response_description` 매개변수로 응답에 관한 설명을 명시할 수 있습니다: -```Python hl_lines="21" -{!../../docs_src/path_operation_configuration/tutorial005.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial005.py hl[21] *} /// info | 정보 @@ -92,9 +82,7 @@ OpenAPI는 각 *경로 작동*이 응답에 관한 설명을 요구할 것을 단일 *경로 작동*을 없애지 않고 지원중단을 해야한다면, `deprecated` 매개변수를 전달하면 됩니다. -```Python hl_lines="16" -{!../../docs_src/path_operation_configuration/tutorial006.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial006.py hl[16] *} 대화형 문서에 지원중단이라고 표시됩니다. diff --git a/docs/ko/docs/tutorial/path-params-numeric-validations.md b/docs/ko/docs/tutorial/path-params-numeric-validations.md index 736f2dc1d..f21c9290e 100644 --- a/docs/ko/docs/tutorial/path-params-numeric-validations.md +++ b/docs/ko/docs/tutorial/path-params-numeric-validations.md @@ -6,9 +6,7 @@ 먼저 `fastapi`에서 `Path`를 임포트합니다: -```Python hl_lines="3" -{!../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial001.py hl[3] *} ## 메타데이터 선언 @@ -16,9 +14,7 @@ 예를 들어, `title` 메타데이터 값을 경로 매개변수 `item_id`에 선언하려면 다음과 같이 입력할 수 있습니다: -```Python hl_lines="10" -{!../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial001.py hl[10] *} /// note | 참고 @@ -46,9 +42,7 @@ 따라서 함수를 다음과 같이 선언 할 수 있습니다: -```Python hl_lines="7" -{!../../docs_src/path_params_numeric_validations/tutorial002.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial002.py hl[7] *} ## 필요한 경우 매개변수 정렬하기, 트릭 @@ -58,9 +52,7 @@ 파이썬은 `*`으로 아무런 행동도 하지 않지만, 따르는 매개변수들은 kwargs로도 알려진 키워드 인자(키-값 쌍)여야 함을 인지합니다. 기본값을 가지고 있지 않더라도 그렇습니다. -```Python hl_lines="7" -{!../../docs_src/path_params_numeric_validations/tutorial003.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *} ## 숫자 검증: 크거나 같음 @@ -68,9 +60,7 @@ 여기서 `ge=1`인 경우, `item_id`는 `1`보다 "크거나(`g`reater) 같은(`e`qual)" 정수형 숫자여야 합니다. -```Python hl_lines="8" -{!../../docs_src/path_params_numeric_validations/tutorial004.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial004.py hl[8] *} ## 숫자 검증: 크거나 같음 및 작거나 같음 @@ -79,9 +69,7 @@ * `gt`: 크거나(`g`reater `t`han) * `le`: 작거나 같은(`l`ess than or `e`qual) -```Python hl_lines="9" -{!../../docs_src/path_params_numeric_validations/tutorial005.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial005.py hl[9] *} ## 숫자 검증: 부동소수, 크거나 및 작거나 @@ -93,9 +81,7 @@ lt 역시 마찬가지입니다. -```Python hl_lines="11" -{!../../docs_src/path_params_numeric_validations/tutorial006.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial006.py hl[11] *} ## 요약 diff --git a/docs/ko/docs/tutorial/path-params.md b/docs/ko/docs/tutorial/path-params.md index 21808e2ca..b72787e0b 100644 --- a/docs/ko/docs/tutorial/path-params.md +++ b/docs/ko/docs/tutorial/path-params.md @@ -2,9 +2,7 @@ 파이썬의 포맷 문자열 리터럴에서 사용되는 문법을 이용하여 경로 "매개변수" 또는 "변수"를 선언할 수 있습니다: -```Python hl_lines="6-7" -{!../../docs_src/path_params/tutorial001.py!} -``` +{* ../../docs_src/path_params/tutorial001.py hl[6:7] *} 경로 매개변수 `item_id`의 값은 함수의 `item_id` 인자로 전달됩니다. @@ -18,9 +16,7 @@ 파이썬 표준 타입 어노테이션을 사용하여 함수에 있는 경로 매개변수의 타입을 선언할 수 있습니다: -```Python hl_lines="7" -{!../../docs_src/path_params/tutorial002.py!} -``` +{* ../../docs_src/path_params/tutorial002.py hl[7] *} 위의 예시에서, `item_id`는 `int`로 선언되었습니다. @@ -121,9 +117,7 @@ *경로 작동*은 순차적으로 실행되기 때문에 `/users/{user_id}` 이전에 `/users/me`를 먼저 선언해야 합니다: -```Python hl_lines="6 11" -{!../../docs_src/path_params/tutorial003.py!} -``` +{* ../../docs_src/path_params/tutorial003.py hl[6,11] *} 그렇지 않으면 `/users/{user_id}`는 `/users/me` 요청 또한 매개변수 `user_id`의 값이 `"me"`인 것으로 "생각하게" 됩니다. @@ -139,9 +133,7 @@ 가능한 값들에 해당하는 고정된 값의 클래스 어트리뷰트들을 만듭니다: -```Python hl_lines="1 6-9" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *} /// info | 정보 @@ -159,9 +151,7 @@ 생성한 열거형 클래스(`ModelName`)를 사용하는 타입 어노테이션으로 *경로 매개변수*를 만듭니다: -```Python hl_lines="16" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[16] *} ### 문서 확인 @@ -177,17 +167,13 @@ 열거형 `ModelName`의 *열거형 멤버*를 비교할 수 있습니다: -```Python hl_lines="17" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[17] *} #### *열거형 값* 가져오기 `model_name.value` 또는 일반적으로 `your_enum_member.value`를 이용하여 실제 값(위 예시의 경우 `str`)을 가져올 수 있습니다: -```Python hl_lines="20" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[20] *} /// tip | 팁 @@ -201,9 +187,7 @@ 클라이언트에 반환하기 전에 해당 값(이 경우 문자열)으로 변환됩니다: -```Python hl_lines="18 21 23" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *} 클라이언트는 아래의 JSON 응답을 얻습니다: @@ -242,9 +226,7 @@ Starlette의 옵션을 직접 이용하여 다음과 같은 URL을 사용함으 따라서 다음과 같이 사용할 수 있습니다: -```Python hl_lines="6" -{!../../docs_src/path_params/tutorial004.py!} -``` +{* ../../docs_src/path_params/tutorial004.py hl[6] *} /// tip | 팁 diff --git a/docs/ko/docs/tutorial/query-params-str-validations.md b/docs/ko/docs/tutorial/query-params-str-validations.md index 71f884e83..f2ca453ac 100644 --- a/docs/ko/docs/tutorial/query-params-str-validations.md +++ b/docs/ko/docs/tutorial/query-params-str-validations.md @@ -4,9 +4,7 @@ 이 응용 프로그램을 예로 들어보겠습니다: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial001.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial001.py hl[9] *} 쿼리 매개변수 `q`는 `Optional[str]` 자료형입니다. 즉, `str` 자료형이지만 `None` 역시 될 수 있음을 뜻하고, 실제로 기본값은 `None`이기 때문에 FastAPI는 이 매개변수가 필수가 아니라는 것을 압니다. @@ -26,17 +24,13 @@ FastAPI는 `q`의 기본값이 `= None`이기 때문에 필수가 아님을 압 이를 위해 먼저 `fastapi`에서 `Query`를 임포트합니다: -```Python hl_lines="3" -{!../../docs_src/query_params_str_validations/tutorial002.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[3] *} ## 기본값으로 `Query` 사용 이제 `Query`를 매개변수의 기본값으로 사용하여 `max_length` 매개변수를 50으로 설정합니다: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial002.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[9] *} 기본값 `None`을 `Query(None)`으로 바꿔야 하므로, `Query`의 첫 번째 매개변수는 기본값을 정의하는 것과 같은 목적으로 사용됩니다. @@ -86,17 +80,13 @@ q: str = Query(None, max_length=50) 매개변수 `min_length` 또한 추가할 수 있습니다: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial003.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial003.py hl[9] *} ## 정규식 추가 매개변수와 일치해야 하는 정규표현식을 정의할 수 있습니다: -```Python hl_lines="10" -{!../../docs_src/query_params_str_validations/tutorial004.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial004.py hl[10] *} 이 특정 정규표현식은 전달 받은 매개변수 값을 검사합니다: @@ -114,9 +104,7 @@ q: str = Query(None, max_length=50) `min_length`가 `3`이고, 기본값이 `"fixedquery"`인 쿼리 매개변수 `q`를 선언해봅시다: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial005.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial005.py hl[7] *} /// note | 참고 @@ -146,9 +134,7 @@ q: Optional[str] = Query(None, min_length=3) 그래서 `Query`를 필수값으로 만들어야 할 때면, 첫 번째 인자로 `...`를 사용할 수 있습니다: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial006.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial006.py hl[7] *} /// info | 정보 @@ -164,9 +150,7 @@ q: Optional[str] = Query(None, min_length=3) 예를 들어, URL에서 여러번 나오는 `q` 쿼리 매개변수를 선언하려면 다음과 같이 작성할 수 있습니다: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial011.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial011.py hl[9] *} 아래와 같은 URL을 사용합니다: @@ -201,9 +185,7 @@ http://localhost:8000/items/?q=foo&q=bar 그리고 제공된 값이 없으면 기본 `list` 값을 정의할 수도 있습니다: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial012.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial012.py hl[9] *} 아래로 이동한다면: @@ -226,9 +208,7 @@ http://localhost:8000/items/ `List[str]` 대신 `list`를 직접 사용할 수도 있습니다: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial013.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial013.py hl[7] *} /// note | 참고 @@ -254,15 +234,11 @@ http://localhost:8000/items/ `title`을 추가할 수 있습니다: -```Python hl_lines="10" -{!../../docs_src/query_params_str_validations/tutorial007.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial007.py hl[10] *} 그리고 `description`도 추가할 수 있습니다: -```Python hl_lines="13" -{!../../docs_src/query_params_str_validations/tutorial008.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial008.py hl[13] *} ## 별칭 매개변수 @@ -282,9 +258,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems 이럴 경우 `alias`를 선언할 수 있으며, 해당 별칭은 매개변수 값을 찾는 데 사용됩니다: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial009.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial009.py hl[9] *} ## 매개변수 사용하지 않게 하기 @@ -294,9 +268,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems 그렇다면 `deprecated=True` 매개변수를 `Query`로 전달합니다: -```Python hl_lines="18" -{!../../docs_src/query_params_str_validations/tutorial010.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial010.py hl[18] *} 문서가 아래와 같이 보일겁니다: diff --git a/docs/ko/docs/tutorial/query-params.md b/docs/ko/docs/tutorial/query-params.md index 7fa3e8c53..d5b9837c4 100644 --- a/docs/ko/docs/tutorial/query-params.md +++ b/docs/ko/docs/tutorial/query-params.md @@ -2,9 +2,7 @@ 경로 매개변수의 일부가 아닌 다른 함수 매개변수를 선언하면 "쿼리" 매개변수로 자동 해석합니다. -```Python hl_lines="9" -{!../../docs_src/query_params/tutorial001.py!} -``` +{* ../../docs_src/query_params/tutorial001.py hl[9] *} 쿼리는 URL에서 `?` 후에 나오고 `&`으로 구분되는 키-값 쌍의 집합입니다. @@ -63,9 +61,7 @@ http://127.0.0.1:8000/items/?skip=20 같은 방법으로 기본값을 `None`으로 설정하여 선택적 매개변수를 선언할 수 있습니다: -```Python hl_lines="9" -{!../../docs_src/query_params/tutorial002.py!} -``` +{* ../../docs_src/query_params/tutorial002.py hl[9] *} 이 경우 함수 매개변수 `q`는 선택적이며 기본값으로 `None` 값이 됩니다. @@ -87,9 +83,7 @@ FastAPI는 `q`가 `= None`이므로 선택적이라는 것을 인지합니다. `bool` 형으로 선언할 수도 있고, 아래처럼 변환됩니다: -```Python hl_lines="9" -{!../../docs_src/query_params/tutorial003.py!} -``` +{* ../../docs_src/query_params/tutorial003.py hl[9] *} 이 경우, 아래로 이동하면: @@ -132,9 +126,7 @@ http://127.0.0.1:8000/items/foo?short=yes 매개변수들은 이름으로 감지됩니다: -```Python hl_lines="8 10" -{!../../docs_src/query_params/tutorial004.py!} -``` +{* ../../docs_src/query_params/tutorial004.py hl[8,10] *} ## 필수 쿼리 매개변수 @@ -144,9 +136,7 @@ http://127.0.0.1:8000/items/foo?short=yes 그러나 쿼리 매개변수를 필수로 만들려면 단순히 기본값을 선언하지 않으면 됩니다: -```Python hl_lines="6-7" -{!../../docs_src/query_params/tutorial005.py!} -``` +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} 여기 쿼리 매개변수 `needy`는 `str`형인 필수 쿼리 매개변수입니다. @@ -190,9 +180,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy 그리고 물론, 일부 매개변수는 필수로, 다른 일부는 기본값을, 또 다른 일부는 선택적으로 선언할 수 있습니다: -```Python hl_lines="10" -{!../../docs_src/query_params/tutorial006.py!} -``` +{* ../../docs_src/query_params/tutorial006.py hl[10] *} 위 예시에서는 3가지 쿼리 매개변수가 있습니다: diff --git a/docs/ko/docs/tutorial/request-files.md b/docs/ko/docs/tutorial/request-files.md index ca0f43978..9162b353c 100644 --- a/docs/ko/docs/tutorial/request-files.md +++ b/docs/ko/docs/tutorial/request-files.md @@ -16,17 +16,13 @@ `fastapi` 에서 `File` 과 `UploadFile` 을 임포트 합니다: -```Python hl_lines="1" -{!../../docs_src/request_files/tutorial001.py!} -``` +{* ../../docs_src/request_files/tutorial001.py hl[1] *} ## `File` 매개변수 정의 `Body` 및 `Form` 과 동일한 방식으로 파일의 매개변수를 생성합니다: -```Python hl_lines="7" -{!../../docs_src/request_files/tutorial001.py!} -``` +{* ../../docs_src/request_files/tutorial001.py hl[7] *} /// info | 정보 @@ -54,9 +50,7 @@ File의 본문을 선언할 때, 매개변수가 쿼리 매개변수 또는 본 `File` 매개변수를 `UploadFile` 타입으로 정의합니다: -```Python hl_lines="12" -{!../../docs_src/request_files/tutorial001.py!} -``` +{* ../../docs_src/request_files/tutorial001.py hl[12] *} `UploadFile` 을 사용하는 것은 `bytes` 과 비교해 다음과 같은 장점이 있습니다: @@ -142,9 +136,7 @@ HTML의 폼들(`
`)이 서버에 데이터를 전송하는 방식은 이 기능을 사용하기 위해 , `bytes` 의 `List` 또는 `UploadFile` 를 선언하기 바랍니다: -```Python hl_lines="10 15" -{!../../docs_src/request_files/tutorial002.py!} -``` +{* ../../docs_src/request_files/tutorial002.py hl[10,15] *} 선언한대로, `bytes` 의 `list` 또는 `UploadFile` 들을 전송받을 것입니다. diff --git a/docs/ko/docs/tutorial/request-forms-and-files.md b/docs/ko/docs/tutorial/request-forms-and-files.md index 75bca9f15..dc1bda21a 100644 --- a/docs/ko/docs/tutorial/request-forms-and-files.md +++ b/docs/ko/docs/tutorial/request-forms-and-files.md @@ -12,17 +12,13 @@ ## `File` 및 `Form` 업로드 -```Python hl_lines="1" -{!../../docs_src/request_forms_and_files/tutorial001.py!} -``` +{* ../../docs_src/request_forms_and_files/tutorial001.py hl[1] *} ## `File` 및 `Form` 매개변수 정의 `Body` 및 `Query`와 동일한 방식으로 파일과 폼의 매개변수를 생성합니다: -```Python hl_lines="8" -{!../../docs_src/request_forms_and_files/tutorial001.py!} -``` +{* ../../docs_src/request_forms_and_files/tutorial001.py hl[8] *} 파일과 폼 필드는 폼 데이터 형식으로 업로드되어 파일과 폼 필드로 전달됩니다. diff --git a/docs/ko/docs/tutorial/response-model.md b/docs/ko/docs/tutorial/response-model.md index 6ba9654d6..a71d649f9 100644 --- a/docs/ko/docs/tutorial/response-model.md +++ b/docs/ko/docs/tutorial/response-model.md @@ -8,9 +8,7 @@ * `@app.delete()` * 기타. -```Python hl_lines="17" -{!../../docs_src/response_model/tutorial001.py!} -``` +{* ../../docs_src/response_model/tutorial001.py hl[17] *} /// note | 참고 @@ -41,15 +39,11 @@ FastAPI는 이 `response_model`를 사용하여: 여기서 우리는 평문 비밀번호를 포함하는 `UserIn` 모델을 선언합니다: -```Python hl_lines="9 11" -{!../../docs_src/response_model/tutorial002.py!} -``` +{* ../../docs_src/response_model/tutorial002.py hl[9,11] *} 그리고 이 모델을 사용하여 입력을 선언하고 같은 모델로 출력을 선언합니다: -```Python hl_lines="17-18" -{!../../docs_src/response_model/tutorial002.py!} -``` +{* ../../docs_src/response_model/tutorial002.py hl[17:18] *} 이제 브라우저가 비밀번호로 사용자를 만들 때마다 API는 응답으로 동일한 비밀번호를 반환합니다. @@ -67,21 +61,15 @@ FastAPI는 이 `response_model`를 사용하여: 대신 평문 비밀번호로 입력 모델을 만들고 해당 비밀번호 없이 출력 모델을 만들 수 있습니다: -```Python hl_lines="9 11 16" -{!../../docs_src/response_model/tutorial003.py!} -``` +{* ../../docs_src/response_model/tutorial003.py hl[9,11,16] *} 여기서 *경로 작동 함수*가 비밀번호를 포함하는 동일한 입력 사용자를 반환할지라도: -```Python hl_lines="24" -{!../../docs_src/response_model/tutorial003.py!} -``` +{* ../../docs_src/response_model/tutorial003.py hl[24] *} ...`response_model`을 `UserOut` 모델로 선언했기 때문에 비밀번호를 포함하지 않습니다: -```Python hl_lines="22" -{!../../docs_src/response_model/tutorial003.py!} -``` +{* ../../docs_src/response_model/tutorial003.py hl[22] *} 따라서 **FastAPI**는 출력 모델에서 선언하지 않은 모든 데이터를 (Pydantic을 사용하여) 필터링합니다. @@ -99,9 +87,7 @@ FastAPI는 이 `response_model`를 사용하여: 응답 모델은 아래와 같이 기본값을 가질 수 있습니다: -```Python hl_lines="11 13-14" -{!../../docs_src/response_model/tutorial004.py!} -``` +{* ../../docs_src/response_model/tutorial004.py hl[11,13:14] *} * `description: Optional[str] = None`은 기본값으로 `None`을 갖습니다. * `tax: float = 10.5`는 기본값으로 `10.5`를 갖습니다. @@ -115,9 +101,7 @@ FastAPI는 이 `response_model`를 사용하여: *경로 작동 데코레이터* 매개변수를 `response_model_exclude_unset=True`로 설정 할 수 있습니다: -```Python hl_lines="24" -{!../../docs_src/response_model/tutorial004.py!} -``` +{* ../../docs_src/response_model/tutorial004.py hl[24] *} 이러한 기본값은 응답에 포함되지 않고 실제로 설정된 값만 포함됩니다. @@ -207,9 +191,7 @@ Pydantic 모델이 하나만 있고 출력에서 ​​일부 데이터를 제 /// -```Python hl_lines="31 37" -{!../../docs_src/response_model/tutorial005.py!} -``` +{* ../../docs_src/response_model/tutorial005.py hl[31,37] *} /// tip | 팁 @@ -223,9 +205,7 @@ Pydantic 모델이 하나만 있고 출력에서 ​​일부 데이터를 제 `list` 또는 `tuple` 대신 `set`을 사용하는 법을 잊었더라도, FastAPI는 `set`으로 변환하고 정상적으로 작동합니다: -```Python hl_lines="31 37" -{!../../docs_src/response_model/tutorial006.py!} -``` +{* ../../docs_src/response_model/tutorial006.py hl[31,37] *} ## 요약 diff --git a/docs/ko/docs/tutorial/response-status-code.md b/docs/ko/docs/tutorial/response-status-code.md index 8e3a16645..bcaf7843b 100644 --- a/docs/ko/docs/tutorial/response-status-code.md +++ b/docs/ko/docs/tutorial/response-status-code.md @@ -8,9 +8,7 @@ * `@app.delete()` * 기타 -```Python hl_lines="6" -{!../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} /// note | 참고 @@ -76,9 +74,7 @@ HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다 상기 예시 참고: -```Python hl_lines="6" -{!../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} `201` 은 "생성됨"를 의미하는 상태 코드입니다. @@ -86,9 +82,7 @@ HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다 `fastapi.status` 의 편의 변수를 사용할 수 있습니다. -```Python hl_lines="1 6" -{!../../docs_src/response_status_code/tutorial002.py!} -``` +{* ../../docs_src/response_status_code/tutorial002.py hl[1,6] *} 이것은 단순히 작업을 편리하게 하기 위한 것으로, HTTP 상태 코드와 동일한 번호를 갖고있지만, 이를 사용하면 편집기의 자동완성 기능을 사용할 수 있습니다: diff --git a/docs/ko/docs/tutorial/security/get-current-user.md b/docs/ko/docs/tutorial/security/get-current-user.md index cf550735a..98ef3885e 100644 --- a/docs/ko/docs/tutorial/security/get-current-user.md +++ b/docs/ko/docs/tutorial/security/get-current-user.md @@ -2,9 +2,7 @@ 이전 장에서 (의존성 주입 시스템을 기반으로 한)보안 시스템은 *경로 작동 함수*에서 `str`로 `token`을 제공했습니다: -```Python hl_lines="10" -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[10] *} 그러나 아직도 유용하지 않습니다. @@ -16,21 +14,7 @@ Pydantic을 사용하여 본문을 선언하는 것과 같은 방식으로 다른 곳에서 사용할 수 있습니다. -//// tab | 파이썬 3.7 이상 - -```Python hl_lines="5 12-16" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="3 10-14" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial002.py hl[5,12:16] *} ## `get_current_user` 의존성 생성하기 @@ -42,61 +26,19 @@ Pydantic을 사용하여 본문을 선언하는 것과 같은 방식으로 다 이전에 *경로 작동*에서 직접 수행했던 것과 동일하게 새 종속성 `get_current_user`는 하위 종속성 `oauth2_scheme`에서 `str`로 `token`을 수신합니다. -//// tab | 파이썬 3.7 이상 - -```Python hl_lines="25" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="23" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial002.py hl[25] *} ## 유저 가져오기 `get_current_user`는 토큰을 `str`로 취하고 Pydantic `User` 모델을 반환하는 우리가 만든 (가짜) 유틸리티 함수를 사용합니다. -//// tab | 파이썬 3.7 이상 - -```Python hl_lines="19-22 26-27" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="17-20 24-25" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial002.py hl[19:22,26:27] *} ## 현재 유저 주입하기 이제 *경로 작동*에서 `get_current_user`와 동일한 `Depends`를 사용할 수 있습니다. -//// tab | 파이썬 3.7 이상 - -```Python hl_lines="31" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="29" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial002.py hl[31] *} Pydantic 모델인 `User`로 `current_user`의 타입을 선언하는 것을 알아야 합니다. @@ -150,21 +92,7 @@ Pydantic 모델인 `User`로 `current_user`의 타입을 선언하는 것을 알 그리고 이 수천 개의 *경로 작동*은 모두 3줄 정도로 줄일 수 있습니다. -//// tab | 파이썬 3.7 이상 - -```Python hl_lines="30-32" -{!> ../../docs_src/security/tutorial002.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="28-30" -{!> ../../docs_src/security/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial002.py hl[30:32] *} ## 요약 diff --git a/docs/ko/docs/tutorial/security/simple-oauth2.md b/docs/ko/docs/tutorial/security/simple-oauth2.md index fd18c1d47..ddc7430af 100644 --- a/docs/ko/docs/tutorial/security/simple-oauth2.md +++ b/docs/ko/docs/tutorial/security/simple-oauth2.md @@ -52,21 +52,7 @@ OAuth2의 경우 문자열일 뿐입니다. 먼저 `OAuth2PasswordRequestForm`을 가져와 `/token`에 대한 *경로 작동*에서 `Depends`의 의존성으로 사용합니다. -//// tab | 파이썬 3.7 이상 - -```Python hl_lines="4 76" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="2 74" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial003.py hl[4,76] *} `OAuth2PasswordRequestForm`은 다음을 사용하여 폼 본문을 선언하는 클래스 의존성입니다: @@ -114,21 +100,7 @@ OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` 오류의 경우 `HTTPException` 예외를 사용합니다: -//// tab | 파이썬 3.7 이상 - -```Python hl_lines="3 77-79" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="1 75-77" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial003.py hl[3,77:79] *} ### 패스워드 확인하기 @@ -156,19 +128,11 @@ OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` //// tab | P파이썬 3.7 이상 -```Python hl_lines="80-83" -{!> ../../docs_src/security/tutorial003.py!} -``` +{* ../../docs_src/security/tutorial003.py hl[80:83] *} //// -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="78-81" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_py310.py hl[78:81] *} #### `**user_dict`에 대해 @@ -210,21 +174,7 @@ UserInDB( /// -//// tab | 파이썬 3.7 이상 - -```Python hl_lines="85" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="83" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial003.py hl[85] *} /// 팁 @@ -250,21 +200,7 @@ UserInDB( 따라서 엔드포인트에서는 사용자가 존재하고 올바르게 인증되었으며 활성 상태인 경우에만 사용자를 얻습니다: -//// tab | 파이썬 3.7 이상 - -```Python hl_lines="58-66 69-72 90" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// - -//// tab | 파이썬 3.10 이상 - -```Python hl_lines="55-64 67-70 88" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/security/tutorial003.py hl[58:66,69:72,90] *} /// 정보 diff --git a/docs/ko/docs/tutorial/static-files.md b/docs/ko/docs/tutorial/static-files.md index af785f206..9db5e1c67 100644 --- a/docs/ko/docs/tutorial/static-files.md +++ b/docs/ko/docs/tutorial/static-files.md @@ -7,9 +7,7 @@ * `StaticFiles` 임포트합니다. * 특정 경로에 `StaticFiles()` 인스턴스를 "마운트" 합니다. -```Python hl_lines="2 6" -{!../../docs_src/static_files/tutorial001.py!} -``` +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} /// note | 기술적 세부사항 diff --git a/docs/nl/docs/python-types.md b/docs/nl/docs/python-types.md index 00052037c..fb8b1e5fd 100644 --- a/docs/nl/docs/python-types.md +++ b/docs/nl/docs/python-types.md @@ -22,9 +22,8 @@ Als je een Python expert bent en alles al weet over type hints, sla dan dit hoof Laten we beginnen met een eenvoudig voorbeeld: -```Python -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} + Het aanroepen van dit programma leidt tot het volgende resultaat: @@ -39,9 +38,8 @@ De functie voert het volgende uit: `` * Voeg samen met een spatie in het midden. -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### Bewerk het @@ -83,9 +81,8 @@ Dat is alles. Dat zijn de "type hints": -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + Dit is niet hetzelfde als het declareren van standaardwaarden zoals bij: @@ -113,9 +110,8 @@ Nu kun je de opties bekijken en er doorheen scrollen totdat je de optie vindt di Bekijk deze functie, deze heeft al type hints: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + Omdat de editor de types van de variabelen kent, krijgt u niet alleen aanvulling, maar ook controles op fouten: @@ -123,9 +119,8 @@ Omdat de editor de types van de variabelen kent, krijgt u niet alleen aanvulling Nu weet je hoe je het moet oplossen, converteer `age` naar een string met `str(age)`: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## Types declareren @@ -144,9 +139,8 @@ Je kunt bijvoorbeeld het volgende gebruiken: * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### Generieke types met typeparameters @@ -370,9 +364,8 @@ Het gaat alleen om de woorden en naamgeving. Maar die naamgeving kan invloed heb Laten we als voorbeeld deze functie nemen: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial009c.py!} -``` +{* ../../docs_src/python_types/tutorial009c.py hl[1,4] *} + De parameter `name` is gedefinieerd als `Optional[str]`, maar is **niet optioneel**, je kunt de functie niet aanroepen zonder de parameter: @@ -388,9 +381,8 @@ say_hi(name=None) # Dit werkt, None is geldig 🎉 Het goede nieuws is dat als je eenmaal Python 3.10 gebruikt, je je daar geen zorgen meer over hoeft te maken, omdat je dan gewoon `|` kunt gebruiken om unions van types te definiëren: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial009c_py310.py!} -``` +{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *} + Dan hoef je je geen zorgen te maken over namen als `Optional` en `Union`. 😎 @@ -452,15 +444,13 @@ Je kunt een klasse ook declareren als het type van een variabele. Stel dat je een klasse `Person` hebt, met een naam: -```Python hl_lines="1-3" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + Vervolgens kun je een variabele van het type `Persoon` declareren: -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + Dan krijg je ook nog eens volledige editorondersteuning: diff --git a/docs/pt/docs/advanced/additional-responses.md b/docs/pt/docs/advanced/additional-responses.md index 58e75ad93..1060d18af 100644 --- a/docs/pt/docs/advanced/additional-responses.md +++ b/docs/pt/docs/advanced/additional-responses.md @@ -26,9 +26,7 @@ O **FastAPI** pegará este modelo, gerará o esquema JSON dele e incluirá no lo Por exemplo, para declarar um outro retorno com o status code `404` e um modelo do Pydantic chamado `Message`, você pode escrever: -```Python hl_lines="18 22" -{!../../docs_src/additional_responses/tutorial001.py!} -``` +{* ../../docs_src/additional_responses/tutorial001.py hl[18,22] *} /// note | Nota @@ -177,9 +175,7 @@ Você pode utilizar o mesmo parâmetro `responses` para adicionar diferentes med Por exemplo, você pode adicionar um media type adicional de `image/png`, declarando que a sua *operação de caminho* pode retornar um objeto JSON (com o media type `application/json`) ou uma imagem PNG: -```Python hl_lines="19-24 28" -{!../../docs_src/additional_responses/tutorial002.py!} -``` +{* ../../docs_src/additional_responses/tutorial002.py hl[19:24,28] *} /// note | Nota @@ -207,9 +203,7 @@ Por exemplo, você pode declarar um retorno com o código de status `404` que ut E um retorno com o código de status `200` que utiliza o seu `response_model`, porém inclui um `example` customizado: -```Python hl_lines="20-31" -{!../../docs_src/additional_responses/tutorial003.py!} -``` +{* ../../docs_src/additional_responses/tutorial003.py hl[20:31] *} Isso será combinado e incluído em seu OpenAPI, e disponibilizado na documentação da sua API: @@ -243,9 +237,7 @@ Você pode utilizar essa técnica para reutilizar alguns retornos predefinidos n Por exemplo: -```Python hl_lines="13-17 26" -{!../../docs_src/additional_responses/tutorial004.py!} -``` +{* ../../docs_src/additional_responses/tutorial004.py hl[13:17,26] *} ## Mais informações sobre retornos OpenAPI diff --git a/docs/pt/docs/advanced/additional-status-codes.md b/docs/pt/docs/advanced/additional-status-codes.md index 5fe970d2a..06d619151 100644 --- a/docs/pt/docs/advanced/additional-status-codes.md +++ b/docs/pt/docs/advanced/additional-status-codes.md @@ -14,57 +14,7 @@ Mas você também deseja aceitar novos itens. E quando os itens não existiam, e Para conseguir isso, importe `JSONResponse` e retorne o seu conteúdo diretamente, definindo o `status_code` que você deseja: -//// tab | Python 3.10+ - -```Python hl_lines="4 25" -{!> ../../docs_src/additional_status_codes/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4 25" -{!> ../../docs_src/additional_status_codes/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 26" -{!> ../../docs_src/additional_status_codes/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Faça uso da versão `Annotated` quando possível. - -/// - -```Python hl_lines="2 23" -{!> ../../docs_src/additional_status_codes/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Faça uso da versão `Annotated` quando possível. - -/// - -```Python hl_lines="4 25" -{!> ../../docs_src/additional_status_codes/tutorial001.py!} -``` - -//// +{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *} /// warning | Aviso diff --git a/docs/pt/docs/advanced/advanced-dependencies.md b/docs/pt/docs/advanced/advanced-dependencies.md index 52fe121f9..f57abba61 100644 --- a/docs/pt/docs/advanced/advanced-dependencies.md +++ b/docs/pt/docs/advanced/advanced-dependencies.md @@ -18,35 +18,7 @@ Não propriamente a classe (que já é um chamável), mas a instância desta cla Para fazer isso, nós declaramos o método `__call__`: -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/dependencies/tutorial011_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[12] *} Neste caso, o `__call__` é o que o **FastAPI** utilizará para verificar parâmetros adicionais e sub dependências, e isso é o que será chamado para passar o valor ao parâmetro na sua *função de operação de rota* posteriormente. @@ -54,35 +26,7 @@ Neste caso, o `__call__` é o que o **FastAPI** utilizará para verificar parâm E agora, nós podemos utilizar o `__init__` para declarar os parâmetros da instância que podemos utilizar para "parametrizar" a dependência: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/dependencies/tutorial011_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[9] *} Neste caso, o **FastAPI** nunca tocará ou se importará com o `__init__`, nós vamos utilizar diretamente em nosso código. @@ -90,35 +34,7 @@ Neste caso, o **FastAPI** nunca tocará ou se importará com o `__init__`, nós Nós poderíamos criar uma instância desta classe com: -//// tab | Python 3.9+ - -```Python hl_lines="18" -{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial011_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="16" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[18] *} E deste modo nós podemos "parametrizar" a nossa dependência, que agora possui `"bar"` dentro dele, como o atributo `checker.fixed_content`. @@ -134,35 +50,7 @@ checker(q="somequery") ...e passar o que quer que isso retorne como valor da dependência em nossa *função de operação de rota* como o parâmetro `fixed_content_included`: -//// tab | Python 3.9+ - -```Python hl_lines="22" -{!> ../../docs_src/dependencies/tutorial011_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="21" -{!> ../../docs_src/dependencies/tutorial011_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="20" -{!> ../../docs_src/dependencies/tutorial011.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[22] *} /// tip | Dica diff --git a/docs/pt/docs/advanced/async-tests.md b/docs/pt/docs/advanced/async-tests.md index 8fae97298..a2b79426c 100644 --- a/docs/pt/docs/advanced/async-tests.md +++ b/docs/pt/docs/advanced/async-tests.md @@ -32,15 +32,11 @@ Para um exemplos simples, vamos considerar uma estrutura de arquivos semelhante O arquivo `main.py` teria: -```Python -{!../../docs_src/async_tests/main.py!} -``` +{* ../../docs_src/async_tests/main.py *} O arquivo `test_main.py` teria os testes para para o arquivo `main.py`, ele poderia ficar assim: -```Python -{!../../docs_src/async_tests/test_main.py!} -``` +{* ../../docs_src/async_tests/test_main.py *} ## Executá-lo @@ -60,9 +56,7 @@ $ pytest O marcador `@pytest.mark.anyio` informa ao pytest que esta função de teste deve ser invocada de maneira assíncrona: -```Python hl_lines="7" -{!../../docs_src/async_tests/test_main.py!} -``` +{* ../../docs_src/async_tests/test_main.py hl[7] *} /// tip | Dica @@ -72,9 +66,7 @@ Note que a função de teste é `async def` agora, no lugar de apenas `def` como Então podemos criar um `AsyncClient` com a aplicação, e enviar requisições assíncronas para ela utilizando `await`. -```Python hl_lines="9-12" -{!../../docs_src/async_tests/test_main.py!} -``` +{* ../../docs_src/async_tests/test_main.py hl[9:12] *} Isso é equivalente a: diff --git a/docs/pt/docs/advanced/custom-response.md b/docs/pt/docs/advanced/custom-response.md index 5f673d7ce..a0bcc2b97 100644 --- a/docs/pt/docs/advanced/custom-response.md +++ b/docs/pt/docs/advanced/custom-response.md @@ -30,9 +30,7 @@ Isso ocorre por que, por padrão, o FastAPI irá verificar cada item dentro do d Mas se você tem certeza que o conteúdo que você está retornando é **serializável com JSON**, você pode passá-lo diretamente para a classe de resposta e evitar o trabalho extra que o FastAPI teria ao passar o conteúdo pelo `jsonable_encoder` antes de passar para a classe de resposta. -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial001b.py!} -``` +{* ../../docs_src/custom_response/tutorial001b.py hl[2,7] *} /// info | Informação @@ -57,9 +55,7 @@ Para retornar uma resposta com HTML diretamente do **FastAPI**, utilize `HTMLRes * Importe `HTMLResponse` * Passe `HTMLResponse` como o parâmetro de `response_class` do seu *decorador de operação de rota*. -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial002.py!} -``` +{* ../../docs_src/custom_response/tutorial002.py hl[2,7] *} /// info | Informação @@ -77,9 +73,7 @@ Como visto em [Retornando uma Resposta Diretamente](response-directly.md){.inter O mesmo exemplo de antes, retornando uma `HTMLResponse`, poderia parecer com: -```Python hl_lines="2 7 19" -{!../../docs_src/custom_response/tutorial003.py!} -``` +{* ../../docs_src/custom_response/tutorial003.py hl[2,7,19] *} /// warning | Aviso @@ -103,9 +97,7 @@ A `response_class` será usada apenas para documentar o OpenAPI da *operação d Por exemplo, poderia ser algo como: -```Python hl_lines="7 21 23" -{!../../docs_src/custom_response/tutorial004.py!} -``` +{* ../../docs_src/custom_response/tutorial004.py hl[7,21,23] *} Neste exemplo, a função `generate_html_response()` já cria e retorna uma `Response` em vez de retornar o HTML em uma `str`. @@ -144,9 +136,7 @@ Ela aceita os seguintes parâmetros: O FastAPI (Starlette, na verdade) irá incluir o cabeçalho Content-Length automaticamente. Ele também irá incluir o cabeçalho Content-Type, baseado no `media_type` e acrescentando uma codificação para tipos textuais. -```Python hl_lines="1 18" -{!../../docs_src/response_directly/tutorial002.py!} -``` +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} ### `HTMLResponse` @@ -156,9 +146,7 @@ Usa algum texto ou sequência de bytes e retorna uma resposta HTML. Como você l Usa algum texto ou sequência de bytes para retornar uma resposta de texto não formatado. -```Python hl_lines="2 7 9" -{!../../docs_src/custom_response/tutorial005.py!} -``` +{* ../../docs_src/custom_response/tutorial005.py hl[2,7,9] *} ### `JSONResponse` @@ -192,9 +180,7 @@ Essa resposta requer a instalação do pacote `ujson`, com o comando `pip instal /// -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial001.py!} -``` +{* ../../docs_src/custom_response/tutorial001.py hl[2,7] *} /// tip | Dica @@ -208,17 +194,13 @@ Retorna um redirecionamento HTTP. Utiliza o código de status 307 (Redirecioname Você pode retornar uma `RedirectResponse` diretamente: -```Python hl_lines="2 9" -{!../../docs_src/custom_response/tutorial006.py!} -``` +{* ../../docs_src/custom_response/tutorial006.py hl[2,9] *} --- Ou você pode utilizá-la no parâmetro `response_class`: -```Python hl_lines="2 7 9" -{!../../docs_src/custom_response/tutorial006b.py!} -``` +{* ../../docs_src/custom_response/tutorial006b.py hl[2,7,9] *} Se você fizer isso, então você pode retornar a URL diretamente da sua *função de operação de rota* @@ -228,17 +210,13 @@ Neste caso, o `status_code` utilizada será o padrão de `RedirectResponse`, que Você também pode utilizar o parâmetro `status_code` combinado com o parâmetro `response_class`: -```Python hl_lines="2 7 9" -{!../../docs_src/custom_response/tutorial006c.py!} -``` +{* ../../docs_src/custom_response/tutorial006c.py hl[2,7,9] *} ### `StreamingResponse` Recebe uma gerador assíncrono ou um gerador/iterador comum e retorna o corpo da requisição continuamente (stream). -```Python hl_lines="2 14" -{!../../docs_src/custom_response/tutorial007.py!} -``` +{* ../../docs_src/custom_response/tutorial007.py hl[2,14] *} #### Utilizando `StreamingResponse` com objetos semelhantes a arquivos @@ -279,15 +257,11 @@ Recebe um conjunto de argumentos do construtor diferente dos outros tipos de res Respostas de Arquivos incluem o tamanho do arquivo, data da última modificação e ETags apropriados, nos cabeçalhos `Content-Length`, `Last-Modified` e `ETag`, respectivamente. -```Python hl_lines="2 10" -{!../../docs_src/custom_response/tutorial009.py!} -``` +{* ../../docs_src/custom_response/tutorial009.py hl[2,10] *} Você também pode usar o parâmetro `response_class`: -```Python hl_lines="2 8 10" -{!../../docs_src/custom_response/tutorial009b.py!} -``` +{* ../../docs_src/custom_response/tutorial009b.py hl[2,8,10] *} Nesse caso, você pode retornar o caminho do arquivo diretamente da sua *função de operação de rota*. @@ -301,9 +275,7 @@ Vamos supor também que você queira retornar um JSON indentado e formatado, ent Você poderia criar uma classe `CustomORJSONResponse`. A principal coisa a ser feita é sobrecarregar o método render da classe Response, `Response.render(content)`, que retorna o conteúdo em bytes, para retornar o conteúdo que você deseja: -```Python hl_lines="9-14 17" -{!../../docs_src/custom_response/tutorial009c.py!} -``` +{* ../../docs_src/custom_response/tutorial009c.py hl[9:14,17] *} Agora em vez de retornar: @@ -329,9 +301,7 @@ O padrão que define isso é o `default_response_class`. No exemplo abaixo, o **FastAPI** irá utilizar `ORJSONResponse` por padrão, em todas as *operações de rota*, em vez de `JSONResponse`. -```Python hl_lines="2 4" -{!../../docs_src/custom_response/tutorial010.py!} -``` +{* ../../docs_src/custom_response/tutorial010.py hl[2,4] *} /// tip | Dica diff --git a/docs/pt/docs/advanced/dataclasses.md b/docs/pt/docs/advanced/dataclasses.md index af603ada7..600c8c268 100644 --- a/docs/pt/docs/advanced/dataclasses.md +++ b/docs/pt/docs/advanced/dataclasses.md @@ -4,9 +4,7 @@ FastAPI é construído em cima do **Pydantic**, e eu tenho mostrado como usar mo Mas o FastAPI também suporta o uso de `dataclasses` da mesma forma: -```Python hl_lines="1 7-12 19-20" -{!../../docs_src/dataclasses/tutorial001.py!} -``` +{* ../../docs_src/dataclasses/tutorial001.py hl[1,7:12,19:20] *} Isso ainda é suportado graças ao **Pydantic**, pois ele tem suporte interno para `dataclasses`. @@ -34,9 +32,7 @@ Mas se você tem um monte de dataclasses por aí, este é um truque legal para u Você também pode usar `dataclasses` no parâmetro `response_model`: -```Python hl_lines="1 7-13 19" -{!../../docs_src/dataclasses/tutorial002.py!} -``` +{* ../../docs_src/dataclasses/tutorial002.py hl[1,7:13,19] *} A dataclass será automaticamente convertida para uma dataclass Pydantic. diff --git a/docs/pt/docs/advanced/events.md b/docs/pt/docs/advanced/events.md index 783dbfc83..504b6db57 100644 --- a/docs/pt/docs/advanced/events.md +++ b/docs/pt/docs/advanced/events.md @@ -31,9 +31,7 @@ Vamos iniciar com um exemplo e ver isso detalhadamente. Nós criamos uma função assíncrona chamada `lifespan()` com `yield` como este: -```Python hl_lines="16 19" -{!../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[16,19] *} Aqui nós estamos simulando a *inicialização* custosa do carregamento do modelo colocando a (falsa) função de modelo no dicionário com modelos de _machine learning_ antes do `yield`. Este código será executado **antes** da aplicação **começar a receber requisições**, durante a *inicialização*. @@ -51,9 +49,7 @@ Talvez você precise inicializar uma nova versão, ou apenas cansou de executá- A primeira coisa a notar, é que estamos definindo uma função assíncrona com `yield`. Isso é muito semelhante à Dependências com `yield`. -```Python hl_lines="14-19" -{!../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[14:19] *} A primeira parte da função, antes do `yield`, será executada **antes** da aplicação inicializar. @@ -65,9 +61,7 @@ Se você verificar, a função está decorada com um `@asynccontextmanager`. Que converte a função em algo chamado de "**Gerenciador de Contexto Assíncrono**". -```Python hl_lines="1 13" -{!../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[1,13] *} Um **gerenciador de contexto** em Python é algo que você pode usar em uma declaração `with`, por exemplo, `open()` pode ser usado como um gerenciador de contexto: @@ -89,9 +83,7 @@ No nosso exemplo de código acima, nós não usamos ele diretamente, mas nós pa O parâmetro `lifespan` da aplicação `FastAPI` usa um **Gerenciador de Contexto Assíncrono**, então nós podemos passar nosso novo gerenciador de contexto assíncrono do `lifespan` para ele. -```Python hl_lines="22" -{!../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[22] *} ## Eventos alternativos (deprecados) @@ -113,9 +105,7 @@ Essas funções podem ser declaradas com `async def` ou `def` normal. Para adicionar uma função que deve rodar antes da aplicação iniciar, declare-a com o evento `"startup"`: -```Python hl_lines="8" -{!../../docs_src/events/tutorial001.py!} -``` +{* ../../docs_src/events/tutorial001.py hl[8] *} Nesse caso, a função de manipulação de evento `startup` irá inicializar os itens do "banco de dados" (só um `dict`) com alguns valores. @@ -127,9 +117,7 @@ E sua aplicação não irá começar a receber requisições até que todos os m Para adicionar uma função que deve ser executada quando a aplicação estiver encerrando, declare ela com o evento `"shutdown"`: -```Python hl_lines="6" -{!../../docs_src/events/tutorial002.py!} -``` +{* ../../docs_src/events/tutorial002.py hl[6] *} Aqui, a função de manipulação de evento `shutdown` irá escrever uma linha de texto `"Application shutdown"` no arquivo `log.txt`. diff --git a/docs/pt/docs/advanced/openapi-callbacks.md b/docs/pt/docs/advanced/openapi-callbacks.md index c66ababa0..b0659d3d6 100644 --- a/docs/pt/docs/advanced/openapi-callbacks.md +++ b/docs/pt/docs/advanced/openapi-callbacks.md @@ -31,9 +31,7 @@ Ele terá uma *operação de rota* que receberá um corpo `Invoice`, e um parâm Essa parte é bastante normal, a maior parte do código provavelmente já é familiar para você: -```Python hl_lines="9-13 36-53" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[9:13,36:53] *} /// tip | Dica @@ -92,9 +90,7 @@ Adotar temporariamente esse ponto de vista (do *desenvolvedor externo*) pode aju Primeiramente crie um novo `APIRouter` que conterá um ou mais callbacks. -```Python hl_lines="3 25" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[3,25] *} ### Crie a *operação de rota* do callback @@ -105,9 +101,7 @@ Ele deve parecer exatamente como uma *operação de rota* normal do FastAPI: * Ele provavelmente deveria ter uma declaração do corpo que deveria receber, por exemplo. `body: InvoiceEvent`. * E também deveria ter uma declaração de um código de status de resposta, por exemplo. `response_model=InvoiceEventReceived`. -```Python hl_lines="16-18 21-22 28-32" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[16:18,21:22,28:32] *} Há 2 diferenças principais de uma *operação de rota* normal: @@ -175,9 +169,7 @@ Nesse ponto você tem a(s) *operação de rota de callback* necessária(s) (a(s) Agora use o parâmetro `callbacks` no decorador da *operação de rota de sua API* para passar o atributo `.routes` (que é na verdade apenas uma `list` de rotas/*operações de rota*) do roteador de callback que você criou acima: -```Python hl_lines="35" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[35] *} /// tip | Dica diff --git a/docs/pt/docs/advanced/openapi-webhooks.md b/docs/pt/docs/advanced/openapi-webhooks.md index 344fe6371..f35922234 100644 --- a/docs/pt/docs/advanced/openapi-webhooks.md +++ b/docs/pt/docs/advanced/openapi-webhooks.md @@ -32,9 +32,7 @@ Webhooks estão disponíveis a partir do OpenAPI 3.1.0, e possui suporte do Fast Quando você cria uma aplicação com o **FastAPI**, existe um atributo chamado `webhooks`, que você utilizar para defini-los da mesma maneira que você definiria as suas **operações de rotas**, utilizando por exemplo `@app.webhooks.post()`. -```Python hl_lines="9-13 36-53" -{!../../docs_src/openapi_webhooks/tutorial001.py!} -``` +{* ../../docs_src/openapi_webhooks/tutorial001.py hl[9:13,36:53] *} Os webhooks que você define aparecerão no esquema do **OpenAPI** e na **página de documentação** gerada automaticamente. diff --git a/docs/pt/docs/advanced/path-operation-advanced-configuration.md b/docs/pt/docs/advanced/path-operation-advanced-configuration.md index 04f5cc9a3..411d0f9a7 100644 --- a/docs/pt/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/pt/docs/advanced/path-operation-advanced-configuration.md @@ -155,17 +155,13 @@ Por exemplo, nesta aplicação nós não usamos a funcionalidade integrada ao Fa //// tab | Pydantic v2 -```Python hl_lines="17-22 24" -{!> ../../docs_src/path_operation_advanced_configuration/tutorial007.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[17:22,24] *} //// //// tab | Pydantic v1 -```Python hl_lines="17-22 24" -{!> ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py hl[17:22,24] *} //// @@ -183,17 +179,13 @@ E então no nosso código, nós analisamos o conteúdo YAML diretamente, e estam //// tab | Pydantic v2 -```Python hl_lines="26-33" -{!> ../../docs_src/path_operation_advanced_configuration/tutorial007.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[26:33] *} //// //// tab | Pydantic v1 -```Python hl_lines="26-33" -{!> ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py hl[26:33] *} //// diff --git a/docs/pt/docs/advanced/response-change-status-code.md b/docs/pt/docs/advanced/response-change-status-code.md index 2ac5eca18..358c12d54 100644 --- a/docs/pt/docs/advanced/response-change-status-code.md +++ b/docs/pt/docs/advanced/response-change-status-code.md @@ -20,9 +20,7 @@ Você pode declarar um parâmetro do tipo `Response` em sua *função de operaç E então você pode definir o `status_code` neste objeto de retorno temporal. -```Python hl_lines="1 9 12" -{!../../docs_src/response_change_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *} E então você pode retornar qualquer objeto que você precise, como você faria normalmente (um `dict`, um modelo de banco de dados, etc.). diff --git a/docs/pt/docs/advanced/response-cookies.md b/docs/pt/docs/advanced/response-cookies.md index cd8f39db3..eed69f222 100644 --- a/docs/pt/docs/advanced/response-cookies.md +++ b/docs/pt/docs/advanced/response-cookies.md @@ -6,9 +6,7 @@ Você pode declarar um parâmetro do tipo `Response` na sua *função de operaç E então você pode definir cookies nesse objeto de resposta *temporário*. -```Python hl_lines="1 8-9" -{!../../docs_src/response_cookies/tutorial002.py!} -``` +{* ../../docs_src/response_cookies/tutorial002.py hl[1,8:9] *} Em seguida, você pode retornar qualquer objeto que precise, como normalmente faria (um `dict`, um modelo de banco de dados, etc). @@ -26,9 +24,7 @@ Para fazer isso, você pode criar uma resposta como descrito em [Retornando uma Então, defina os cookies nela e a retorne: -```Python hl_lines="10-12" -{!../../docs_src/response_cookies/tutorial001.py!} -``` +{* ../../docs_src/response_cookies/tutorial001.py hl[10:12] *} /// tip | Dica diff --git a/docs/pt/docs/advanced/response-directly.md b/docs/pt/docs/advanced/response-directly.md index fd2a0eef1..ea717be00 100644 --- a/docs/pt/docs/advanced/response-directly.md +++ b/docs/pt/docs/advanced/response-directly.md @@ -34,9 +34,7 @@ Por exemplo, você não pode colocar um modelo do Pydantic em uma `JSONResponse` Para esses casos, você pode usar o `jsonable_encoder` para converter seus dados antes de repassá-los para a resposta: -```Python hl_lines="6-7 21-22" -{!../../docs_src/response_directly/tutorial001.py!} -``` +{* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *} /// note | Detalhes Técnicos @@ -56,9 +54,7 @@ Vamos dizer quer retornar uma resposta ../../docs_src/security/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="2 7 11" -{!> ../../docs_src/security/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="2 6 10" -{!> ../../docs_src/security/tutorial006.py!} -``` - -//// +{* ../../docs_src/security/tutorial006_an_py39.py hl[4,8,12] *} Quando você tentar abrir a URL pela primeira vez (ou clicar no botão "Executar" nos documentos) o navegador vai pedir pelo seu usuário e senha: @@ -68,35 +40,7 @@ Para lidar com isso, primeiramente nós convertemos o `username` e o `password` Então nós podemos utilizar o `secrets.compare_digest()` para garantir que o `credentials.username` é `"stanleyjobson"`, e que o `credentials.password` é `"swordfish"`. -//// tab | Python 3.9+ - -```Python hl_lines="1 12-24" -{!> ../../docs_src/security/tutorial007_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 12-24" -{!> ../../docs_src/security/tutorial007_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="1 11-21" -{!> ../../docs_src/security/tutorial007.py!} -``` - -//// +{* ../../docs_src/security/tutorial007_an_py39.py hl[1,12:24] *} Isso seria parecido com: @@ -161,32 +105,4 @@ Deste modo, ao utilizar `secrets.compare_digest()` no código de sua aplicação Após detectar que as credenciais estão incorretas, retorne um `HTTPException` com o status 401 (o mesmo retornado quando nenhuma credencial foi informada) e adicione o cabeçalho `WWW-Authenticate` para fazer com que o navegador mostre o prompt de login novamente: -//// tab | Python 3.9+ - -```Python hl_lines="26-30" -{!> ../../docs_src/security/tutorial007_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="26-30" -{!> ../../docs_src/security/tutorial007_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="23-27" -{!> ../../docs_src/security/tutorial007.py!} -``` - -//// +{* ../../docs_src/security/tutorial007_an_py39.py hl[26:30] *} diff --git a/docs/pt/docs/advanced/security/oauth2-scopes.md b/docs/pt/docs/advanced/security/oauth2-scopes.md index 49fb75944..1d53f42d8 100644 --- a/docs/pt/docs/advanced/security/oauth2-scopes.md +++ b/docs/pt/docs/advanced/security/oauth2-scopes.md @@ -62,71 +62,7 @@ Para o OAuth2, eles são apenas strings. Primeiro, vamos olhar rapidamente as partes que mudam dos exemplos do **Tutorial - Guia de Usuário** para [OAuth2 com Senha (e hash), Bearer com tokens JWT](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. Agora utilizando escopos OAuth2: -//// tab | Python 3.10+ - -```Python hl_lines="5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="2 5 9 13 48 66 107 109-117 123-126 130-136 141 157" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[5,9,13,47,65,106,108:116,122:125,129:135,140,156] *} Agora vamos revisar essas mudanças passo a passo. @@ -136,71 +72,7 @@ A primeira mudança é que agora nós estamos declarando o esquema de segurança O parâmetro `scopes` recebe um `dict` contendo cada escopo como chave e a descrição como valor: -//// tab | Python 3.10+ - -```Python hl_lines="63-66" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="63-66" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="64-67" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="62-65" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="63-66" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="63-66" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[63:66] *} Pelo motivo de estarmos declarando estes escopos, eles aparecerão nos documentos da API quando você se autenticar/autorizar. @@ -226,71 +98,7 @@ Porém em sua aplicação, por segurança, você deve garantir que você apenas /// -//// tab | Python 3.10+ - -```Python hl_lines="156" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="156" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="157" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="155" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="156" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="156" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[156] *} ## Declare escopos em *operações de rota* e dependências @@ -316,71 +124,7 @@ Nós estamos fazendo isso aqui para demonstrar como o **FastAPI** lida com escop /// -//// tab | Python 3.10+ - -```Python hl_lines="5 140 171" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="5 140 171" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="5 141 172" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="4 139 168" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="5 140 169" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="5 140 169" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[5,140,171] *} /// info | Informações Técnicas @@ -406,71 +150,7 @@ Nós também declaramos um parâmetro especial do tipo `SecurityScopes`, importa A classe `SecurityScopes` é semelhante à classe `Request` (`Request` foi utilizada para obter o objeto da requisição diretamente). -//// tab | Python 3.10+ - -```Python hl_lines="9 106" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9 106" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 107" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="8 105" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="9 106" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="9 106" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[9,106] *} ## Utilize os `scopes` @@ -484,71 +164,7 @@ Nós criamos uma `HTTPException` que nós podemos reutilizar (`raise`) mais tard Nesta exceção, nós incluímos os escopos necessários (se houver algum) como uma string separada por espaços (utilizando `scope_str`). Nós colocamos esta string contendo os escopos no cabeçalho `WWW-Authenticate` (isso é parte da especificação). -//// tab | Python 3.10+ - -```Python hl_lines="106 108-116" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="106 108-116" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="107 109-117" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="105 107-115" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="106 108-116" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="106 108-116" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[106,108:116] *} ## Verifique o `username` e o formato dos dados @@ -564,71 +180,7 @@ No lugar de, por exemplo, um `dict`, ou alguma outra coisa, que poderia quebrar Nós também verificamos que nós temos um usuário com o "*username*", e caso contrário, nós levantamos a mesma exceção que criamos anteriormente. -//// tab | Python 3.10+ - -```Python hl_lines="47 117-128" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="47 117-128" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="48 118-129" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="46 116-127" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="47 117-128" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="47 117-128" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[47,117:128] *} ## Verifique os `scopes` @@ -636,71 +188,7 @@ Nós verificamos agora que todos os escopos necessários, por essa dependência Para isso, nós utilizamos `security_scopes.scopes`, que contém uma `list` com todos esses escopos como uma `str`. -//// tab | Python 3.10+ - -```Python hl_lines="129-135" -{!> ../../docs_src/security/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="129-135" -{!> ../../docs_src/security/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="130-136" -{!> ../../docs_src/security/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="128-134" -{!> ../../docs_src/security/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="129-135" -{!> ../../docs_src/security/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="129-135" -{!> ../../docs_src/security/tutorial005.py!} -``` - -//// +{* ../../docs_src/security/tutorial005_an_py310.py hl[129:135] *} ## Árvore de dependência e escopos diff --git a/docs/pt/docs/advanced/settings.md b/docs/pt/docs/advanced/settings.md index d32b70ed4..00a39b0af 100644 --- a/docs/pt/docs/advanced/settings.md +++ b/docs/pt/docs/advanced/settings.md @@ -180,9 +180,7 @@ Você pode utilizar todas as ferramentas e funcionalidades de validação que s //// tab | Pydantic v2 -```Python hl_lines="2 5-8 11" -{!> ../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[2,5:8,11] *} //// @@ -194,9 +192,7 @@ Na versão 1 do Pydantic você importaria `BaseSettings` diretamente do módulo /// -```Python hl_lines="2 5-8 11" -{!> ../../docs_src/settings/tutorial001_pv1.py!} -``` +{* ../../docs_src/settings/tutorial001_pv1.py hl[2,5:8,11] *} //// @@ -214,9 +210,7 @@ Depois ele irá converter e validar os dados. Assim, quando você utilizar aquel Depois, Você pode utilizar o novo objeto `settings` na sua aplicação: -```Python hl_lines="18-20" -{!../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[18:20] *} ### Executando o servidor @@ -250,15 +244,11 @@ Você também pode incluir essas configurações em um arquivo de um módulo sep Por exemplo, você pode adicionar um arquivo `config.py` com: -```Python -{!../../docs_src/settings/app01/config.py!} -``` +{* ../../docs_src/settings/app01/config.py *} E utilizar essa configuração em `main.py`: -```Python hl_lines="3 11-13" -{!../../docs_src/settings/app01/main.py!} -``` +{* ../../docs_src/settings/app01/main.py hl[3,11:13] *} /// dica @@ -276,9 +266,7 @@ Isso é especialmente útil durante os testes, já que é bastante simples sobre Baseando-se no exemplo anterior, seu arquivo `config.py` seria parecido com isso: -```Python hl_lines="10" -{!../../docs_src/settings/app02/config.py!} -``` +{* ../../docs_src/settings/app02/config.py hl[10] *} Perceba que dessa vez não criamos uma instância padrão `settings = Settings()`. @@ -286,35 +274,7 @@ Perceba que dessa vez não criamos uma instância padrão `settings = Settings() Agora criamos a dependência que retorna um novo objeto `config.Settings()`. -//// tab | Python 3.9+ - -```Python hl_lines="6 12-13" -{!> ../../docs_src/settings/app02_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="6 12-13" -{!> ../../docs_src/settings/app02_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="5 11-12" -{!> ../../docs_src/settings/app02/main.py!} -``` - -//// +{* ../../docs_src/settings/app02_an_py39/main.py hl[6,12:13] *} /// dica @@ -326,43 +286,13 @@ Por enquanto, você pode considerar `get_settings()` como uma função normal. E então podemos declarar essas configurações como uma dependência na função de operação da rota e utilizar onde for necessário. -//// tab | Python 3.9+ - -```Python hl_lines="17 19-21" -{!> ../../docs_src/settings/app02_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17 19-21" -{!> ../../docs_src/settings/app02_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="16 18-20" -{!> ../../docs_src/settings/app02/main.py!} -``` - -//// +{* ../../docs_src/settings/app02_an_py39/main.py hl[17,19:21] *} ### Configurações e testes Então seria muito fácil fornecer uma configuração diferente durante a execução dos testes sobrescrevendo a dependência de `get_settings`: -```Python hl_lines="9-10 13 21" -{!../../docs_src/settings/app02/test_main.py!} -``` +{* ../../docs_src/settings/app02/test_main.py hl[9:10,13,21] *} Na sobrescrita da dependência, definimos um novo valor para `admin_email` quando instanciamos um novo objeto `Settings`, e então retornamos esse novo objeto. @@ -405,9 +335,7 @@ E então adicionar o seguinte código em `config.py`: //// tab | Pydantic v2 -```Python hl_lines="9" -{!> ../../docs_src/settings/app03_an/config.py!} -``` +{* ../../docs_src/settings/app03_an/config.py hl[9] *} /// dica @@ -419,9 +347,7 @@ O atributo `model_config` é usado apenas para configuração do Pydantic. Você //// tab | Pydantic v1 -```Python hl_lines="9-10" -{!> ../../docs_src/settings/app03_an/config_pv1.py!} -``` +{* ../../docs_src/settings/app03_an/config_pv1.py hl[9:10] *} /// dica @@ -462,35 +388,7 @@ Iriamos criar um novo objeto a cada requisição, e estaríamos lendo o arquivo Mas como estamos utilizando o decorador `@lru_cache` acima, o objeto `Settings` é criado apenas uma vez, na primeira vez que a função é chamada. ✔️ -//// tab | Python 3.9+ - -```Python hl_lines="1 11" -{!> ../../docs_src/settings/app03_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 11" -{!> ../../docs_src/settings/app03_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="1 10" -{!> ../../docs_src/settings/app03/main.py!} -``` - -//// +{* ../../docs_src/settings/app03_an_py39/main.py hl[1,11] *} Dessa forma, todas as chamadas da função `get_settings()` nas dependências das próximas requisições, em vez de executar o código interno de `get_settings()` e instanciar um novo objeto `Settings`, irão retornar o mesmo objeto que foi retornado na primeira chamada, de novo e de novo. diff --git a/docs/pt/docs/advanced/sub-applications.md b/docs/pt/docs/advanced/sub-applications.md index 7f0381cc2..efc6bef64 100644 --- a/docs/pt/docs/advanced/sub-applications.md +++ b/docs/pt/docs/advanced/sub-applications.md @@ -10,9 +10,7 @@ Se você precisar ter duas aplicações FastAPI independentes, cada uma com seu Primeiro, crie a aplicação principal, de nível superior, **FastAPI**, e suas *operações de rota*: -```Python hl_lines="3 6-8" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[3,6:8] *} ### Sub-aplicação @@ -20,9 +18,7 @@ Em seguida, crie sua sub-aplicação e suas *operações de rota*. Essa sub-aplicação é apenas outra aplicação FastAPI padrão, mas esta é a que será "montada": -```Python hl_lines="11 14-16" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11,14:16] *} ### Monte a sub-aplicação @@ -30,9 +26,7 @@ Na sua aplicação de nível superior, `app`, monte a sub-aplicação, `subapi`. Neste caso, ela será montada no caminho `/subapi`: -```Python hl_lines="11 19" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11,19] *} ### Verifique a documentação automática da API diff --git a/docs/pt/docs/advanced/templates.md b/docs/pt/docs/advanced/templates.md index 2314fed91..4d22bfbbf 100644 --- a/docs/pt/docs/advanced/templates.md +++ b/docs/pt/docs/advanced/templates.md @@ -25,9 +25,7 @@ $ pip install jinja2 * Declare um parâmetro `Request` no *path operation* que retornará um template. * Use o `template` que você criou para renderizar e retornar uma `TemplateResponse`, passe o nome do template, o request object, e um "context" dict com pares chave-valor a serem usados dentro do template do Jinja2. -```Python hl_lines="4 11 15-18" -{!../../docs_src/templates/tutorial001.py!} -``` +{* ../../docs_src/templates/tutorial001.py hl[4,11,15:18] *} /// note diff --git a/docs/pt/docs/advanced/testing-dependencies.md b/docs/pt/docs/advanced/testing-dependencies.md index 94594e7e9..3ede4741d 100644 --- a/docs/pt/docs/advanced/testing-dependencies.md +++ b/docs/pt/docs/advanced/testing-dependencies.md @@ -28,57 +28,7 @@ Para sobrepor a dependência para os testes, você coloca como chave a dependên E então o **FastAPI** chamará a sobreposição no lugar da dependência original. -//// tab | Python 3.10+ - -```Python hl_lines="26-27 30" -{!> ../../docs_src/dependency_testing/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="28-29 32" -{!> ../../docs_src/dependency_testing/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="29-30 33" -{!> ../../docs_src/dependency_testing/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="24-25 28" -{!> ../../docs_src/dependency_testing/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="28-29 32" -{!> ../../docs_src/dependency_testing/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependency_testing/tutorial001_an_py310.py hl[26:27,30] *} /// tip | Dica diff --git a/docs/pt/docs/advanced/testing-events.md b/docs/pt/docs/advanced/testing-events.md index b6796e835..6113c9913 100644 --- a/docs/pt/docs/advanced/testing-events.md +++ b/docs/pt/docs/advanced/testing-events.md @@ -2,6 +2,4 @@ Quando você precisa que os seus manipuladores de eventos (`startup` e `shutdown`) sejam executados em seus testes, você pode utilizar o `TestClient` usando a instrução `with`: -```Python hl_lines="9-12 20-24" -{!../../docs_src/app_testing/tutorial003.py!} -``` +{* ../../docs_src/app_testing/tutorial003.py hl[9:12,20:24] *} diff --git a/docs/pt/docs/advanced/testing-websockets.md b/docs/pt/docs/advanced/testing-websockets.md index 99e1a6db4..942771bc9 100644 --- a/docs/pt/docs/advanced/testing-websockets.md +++ b/docs/pt/docs/advanced/testing-websockets.md @@ -4,9 +4,7 @@ Você pode usar o mesmo `TestClient` para testar WebSockets. Para isso, você utiliza o `TestClient` dentro de uma instrução `with`, conectando com o WebSocket: -```Python hl_lines="27-31" -{!../../docs_src/app_testing/tutorial002.py!} -``` +{* ../../docs_src/app_testing/tutorial002.py hl[27:31] *} /// note | Nota diff --git a/docs/pt/docs/advanced/using-request-directly.md b/docs/pt/docs/advanced/using-request-directly.md index df7e01833..f31e2ed15 100644 --- a/docs/pt/docs/advanced/using-request-directly.md +++ b/docs/pt/docs/advanced/using-request-directly.md @@ -29,9 +29,7 @@ Vamos imaginar que você deseja obter o endereço de IP/host do cliente dentro d Para isso você precisa acessar a requisição diretamente. -```Python hl_lines="1 7-8" -{!../../docs_src/using_request_directly/tutorial001.py!} -``` +{* ../../docs_src/using_request_directly/tutorial001.py hl[1,7:8] *} Ao declarar o parâmetro com o tipo sendo um `Request` em sua *função de operação de rota*, o **FastAPI** saberá como passar o `Request` neste parâmetro. diff --git a/docs/pt/docs/advanced/websockets.md b/docs/pt/docs/advanced/websockets.md index 694f2bb5d..82e443886 100644 --- a/docs/pt/docs/advanced/websockets.md +++ b/docs/pt/docs/advanced/websockets.md @@ -38,9 +38,7 @@ Na produção, você teria uma das opções acima. Mas é a maneira mais simples de focar no lado do servidor de WebSockets e ter um exemplo funcional: -```Python hl_lines="2 6-38 41-43" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[2,6:38,41:43] *} ## Criando um `websocket` diff --git a/docs/pt/docs/how-to/conditional-openapi.md b/docs/pt/docs/how-to/conditional-openapi.md index 675b812e6..6b44e9c81 100644 --- a/docs/pt/docs/how-to/conditional-openapi.md +++ b/docs/pt/docs/how-to/conditional-openapi.md @@ -29,9 +29,7 @@ Você pode usar facilmente as mesmas configurações do Pydantic para configurar Por exemplo: -```Python hl_lines="6 11" -{!../../docs_src/conditional_openapi/tutorial001.py!} -``` +{* ../../docs_src/conditional_openapi/tutorial001.py hl[6,11] *} Aqui declaramos a configuração `openapi_url` com o mesmo padrão de `"/openapi.json"`. diff --git a/docs/pt/docs/how-to/configure-swagger-ui.md b/docs/pt/docs/how-to/configure-swagger-ui.md index 58bb1557c..915b2b5c5 100644 --- a/docs/pt/docs/how-to/configure-swagger-ui.md +++ b/docs/pt/docs/how-to/configure-swagger-ui.md @@ -18,9 +18,7 @@ Sem alterar as configurações, o destaque de sintaxe é habilitado por padrão: Mas você pode desabilitá-lo definindo `syntaxHighlight` como `False`: -```Python hl_lines="3" -{!../../docs_src/configure_swagger_ui/tutorial001.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial001.py hl[3] *} ...e então o Swagger UI não mostrará mais o destaque de sintaxe: @@ -30,9 +28,7 @@ Mas você pode desabilitá-lo definindo `syntaxHighlight` como `False`: Da mesma forma que você pode definir o tema de destaque de sintaxe com a chave `"syntaxHighlight.theme"` (observe que há um ponto no meio): -```Python hl_lines="3" -{!../../docs_src/configure_swagger_ui/tutorial002.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial002.py hl[3] *} Essa configuração alteraria o tema de cores de destaque de sintaxe: @@ -44,17 +40,13 @@ O FastAPI inclui alguns parâmetros de configuração padrão apropriados para a Inclui estas configurações padrão: -```Python -{!../../fastapi/openapi/docs.py[ln:7-23]!} -``` +{* ../../fastapi/openapi/docs.py ln[7:23] *} Você pode substituir qualquer um deles definindo um valor diferente no argumento `swagger_ui_parameters`. Por exemplo, para desabilitar `deepLinking` você pode passar essas configurações para `swagger_ui_parameters`: -```Python hl_lines="3" -{!../../docs_src/configure_swagger_ui/tutorial003.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial003.py hl[3] *} ## Outros parâmetros da UI do Swagger diff --git a/docs/pt/docs/how-to/custom-docs-ui-assets.md b/docs/pt/docs/how-to/custom-docs-ui-assets.md index 00dd144c9..3adc7529e 100644 --- a/docs/pt/docs/how-to/custom-docs-ui-assets.md +++ b/docs/pt/docs/how-to/custom-docs-ui-assets.md @@ -18,9 +18,7 @@ O primeiro passo é desativar a documentação automática, pois por padrão, el Para desativá-los, defina suas URLs como `None` ao criar seu aplicativo `FastAPI`: -```Python hl_lines="8" -{!../../docs_src/custom_docs_ui/tutorial001.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[8] *} ### Incluir a documentação personalizada @@ -36,9 +34,7 @@ Você pode reutilizar as funções internas do FastAPI para criar as páginas HT E de forma semelhante para o ReDoc... -```Python hl_lines="2-6 11-19 22-24 27-33" -{!../../docs_src/custom_docs_ui/tutorial001.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[2:6,11:19,22:24,27:33] *} /// tip | Dica @@ -54,9 +50,7 @@ Swagger UI lidará com isso nos bastidores para você, mas ele precisa desse aux Agora, para poder testar se tudo funciona, crie uma *operação de rota*: -```Python hl_lines="36-38" -{!../../docs_src/custom_docs_ui/tutorial001.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[36:38] *} ### Teste @@ -124,9 +118,7 @@ Depois disso, sua estrutura de arquivos deve se parecer com: * Importe `StaticFiles`. * "Monte" a instância `StaticFiles()` em um caminho específico. -```Python hl_lines="7 11" -{!../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[7,11] *} ### Teste os arquivos estáticos @@ -158,9 +150,7 @@ Da mesma forma que ao usar um CDN personalizado, o primeiro passo é desativar a Para desativá-los, defina suas URLs como `None` ao criar seu aplicativo `FastAPI`: -```Python hl_lines="9" -{!../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[9] *} ### Incluir a documentação personalizada para arquivos estáticos @@ -176,9 +166,7 @@ Novamente, você pode reutilizar as funções internas do FastAPI para criar as E de forma semelhante para o ReDoc... -```Python hl_lines="2-6 14-22 25-27 30-36" -{!../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[2:6,14:22,25:27,30:36] *} /// tip | Dica @@ -194,9 +182,7 @@ Swagger UI lidará com isso nos bastidores para você, mas ele precisa desse aux Agora, para poder testar se tudo funciona, crie uma *operação de rota*: -```Python hl_lines="39-41" -{!../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[39:41] *} ### Teste a UI de Arquivos Estáticos diff --git a/docs/pt/docs/how-to/custom-request-and-route.md b/docs/pt/docs/how-to/custom-request-and-route.md index 64325eed9..8f432f6fe 100644 --- a/docs/pt/docs/how-to/custom-request-and-route.md +++ b/docs/pt/docs/how-to/custom-request-and-route.md @@ -42,9 +42,7 @@ Se não houver `gzip` no cabeçalho, ele não tentará descomprimir o corpo. Dessa forma, a mesma classe de rota pode lidar com requisições comprimidas ou não comprimidas. -```Python hl_lines="8-15" -{!../../docs_src/custom_request_and_route/tutorial001.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial001.py hl[8:15] *} ### Criar uma classe `GzipRoute` personalizada @@ -56,9 +54,7 @@ Esse método retorna uma função. E essa função é o que irá receber uma req Aqui nós usamos para criar um `GzipRequest` a partir da requisição original. -```Python hl_lines="18-26" -{!../../docs_src/custom_request_and_route/tutorial001.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial001.py hl[18:26] *} /// note | Detalhes Técnicos @@ -96,26 +92,18 @@ Também podemos usar essa mesma abordagem para acessar o corpo da requisição e Tudo que precisamos fazer é manipular a requisição dentro de um bloco `try`/`except`: -```Python hl_lines="13 15" -{!../../docs_src/custom_request_and_route/tutorial002.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial002.py hl[13,15] *} Se uma exceção ocorrer, a instância `Request` ainda estará em escopo, então podemos ler e fazer uso do corpo da requisição ao lidar com o erro: -```Python hl_lines="16-18" -{!../../docs_src/custom_request_and_route/tutorial002.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial002.py hl[16:18] *} ## Classe `APIRoute` personalizada em um router você também pode definir o parametro `route_class` de uma `APIRouter`; -```Python hl_lines="26" -{!../../docs_src/custom_request_and_route/tutorial003.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial003.py hl[26] *} Nesse exemplo, as *operações de rota* sob o `router` irão usar a classe `TimedRoute` personalizada, e terão um cabeçalho extra `X-Response-Time` na resposta com o tempo que levou para gerar a resposta: -```Python hl_lines="13-20" -{!../../docs_src/custom_request_and_route/tutorial003.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial003.py hl[13:20] *} diff --git a/docs/pt/docs/how-to/extending-openapi.md b/docs/pt/docs/how-to/extending-openapi.md index 40917325b..b4785edc1 100644 --- a/docs/pt/docs/how-to/extending-openapi.md +++ b/docs/pt/docs/how-to/extending-openapi.md @@ -1,4 +1,3 @@ - # Extendendo o OpenAPI Existem alguns casos em que pode ser necessário modificar o esquema OpenAPI gerado. @@ -44,25 +43,19 @@ Por exemplo, vamos adicionar documentação do Strawberry. diff --git a/docs/pt/docs/how-to/separate-openapi-schemas.md b/docs/pt/docs/how-to/separate-openapi-schemas.md index 50d321d4c..291b0e163 100644 --- a/docs/pt/docs/how-to/separate-openapi-schemas.md +++ b/docs/pt/docs/how-to/separate-openapi-schemas.md @@ -10,123 +10,13 @@ Vamos ver como isso funciona e como alterar se for necessário. Digamos que você tenha um modelo Pydantic com valores padrão, como este: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!} - -# Code below omitted 👇 -``` - -
-👀 Visualização completa do arquivo - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} -``` - -
- -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!} - -# Code below omitted 👇 -``` - -
-👀 Visualização completa do arquivo - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} -``` - -
- -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!} - -# Code below omitted 👇 -``` - -
-👀 Visualização completa do arquivo - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} -``` - -
- -//// +{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:7] hl[7] *} ### Modelo para Entrada Se você usar esse modelo como entrada, como aqui: -//// tab | Python 3.10+ - -```Python hl_lines="14" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!} - -# Code below omitted 👇 -``` - -
-👀 Visualização completa do arquivo - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} -``` - -
- -//// - -//// tab | Python 3.9+ - -```Python hl_lines="16" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!} - -# Code below omitted 👇 -``` - -
-👀 Visualização completa do arquivo - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} -``` - -
- -//// - -//// tab | Python 3.8+ - -```Python hl_lines="16" -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!} - -# Code below omitted 👇 -``` - -
-👀 Visualização completa do arquivo - -```Python -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} -``` - -
- -//// +{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:15] hl[14] *} ... então o campo `description` não será obrigatório. Porque ele tem um valor padrão de `None`. @@ -142,29 +32,7 @@ Você pode confirmar que na documentação, o campo `description` não tem um ** Mas se você usar o mesmo modelo como saída, como aqui: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="21" -{!> ../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="21" -{!> ../../docs_src/separate_openapi_schemas/tutorial001.py!} -``` - -//// +{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py hl[19] *} ... então, como `description` tem um valor padrão, se você **não retornar nada** para esse campo, ele ainda terá o **valor padrão**. @@ -223,29 +91,7 @@ O suporte para `separate_input_output_schemas` foi adicionado no FastAPI `0.102. /// -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/separate_openapi_schemas/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/separate_openapi_schemas/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12" -{!> ../../docs_src/separate_openapi_schemas/tutorial002.py!} -``` - -//// +{* ../../docs_src/separate_openapi_schemas/tutorial002_py310.py hl[10] *} ### Mesmo Esquema para Modelos de Entrada e Saída na Documentação diff --git a/docs/pt/docs/tutorial/body-fields.md b/docs/pt/docs/tutorial/body-fields.md index ac0b85ab5..e7dfb07f2 100644 --- a/docs/pt/docs/tutorial/body-fields.md +++ b/docs/pt/docs/tutorial/body-fields.md @@ -6,9 +6,7 @@ Da mesma forma que você pode declarar validações adicionais e metadados nos p Primeiro, você tem que importá-lo: -```Python hl_lines="4" -{!../../docs_src/body_fields/tutorial001.py!} -``` +{* ../../docs_src/body_fields/tutorial001.py hl[4] *} /// warning | Aviso @@ -20,9 +18,7 @@ Note que `Field` é importado diretamente do `pydantic`, não do `fastapi` como Você pode então utilizar `Field` com atributos do modelo: -```Python hl_lines="11-14" -{!../../docs_src/body_fields/tutorial001.py!} -``` +{* ../../docs_src/body_fields/tutorial001.py hl[11:14] *} `Field` funciona da mesma forma que `Query`, `Path` e `Body`, ele possui todos os mesmos parâmetros, etc. diff --git a/docs/pt/docs/tutorial/body-multiple-params.md b/docs/pt/docs/tutorial/body-multiple-params.md index ad4931b11..eda9b4dff 100644 --- a/docs/pt/docs/tutorial/body-multiple-params.md +++ b/docs/pt/docs/tutorial/body-multiple-params.md @@ -8,21 +8,7 @@ Primeiro, é claro, você pode misturar `Path`, `Query` e declarações de parâ E você também pode declarar parâmetros de corpo como opcionais, definindo o valor padrão com `None`: -//// tab | Python 3.10+ - -```Python hl_lines="17-19" -{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="19-21" -{!> ../../docs_src/body_multiple_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial001_py310.py hl[17:19] *} /// note | Nota @@ -45,21 +31,7 @@ No exemplo anterior, as *operações de rota* esperariam um JSON no corpo conten Mas você pode também declarar múltiplos parâmetros de corpo, por exemplo, `item` e `user`: -//// tab | Python 3.10+ - -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *} Neste caso, o **FastAPI** perceberá que existe mais de um parâmetro de corpo na função (dois parâmetros que são modelos Pydantic). @@ -100,21 +72,7 @@ Se você declará-lo como é, porque é um valor singular, o **FastAPI** assumir Mas você pode instruir o **FastAPI** para tratá-lo como outra chave do corpo usando `Body`: -//// tab | Python 3.8+ - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial003.py!} -``` - -//// - -//// tab | Python 3.10+ - -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial003.py hl[22] *} Neste caso, o **FastAPI** esperará um corpo como: @@ -154,21 +112,7 @@ q: str | None = None Por exemplo: -//// tab | Python 3.10+ - -```Python hl_lines="26" -{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial004_py310.py hl[26] *} /// info | Informação @@ -190,21 +134,7 @@ item: Item = Body(embed=True) como em: -//// tab | Python 3.10+ - -```Python hl_lines="15" -{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial005_py310.py hl[15] *} Neste caso o **FastAPI** esperará um corpo como: diff --git a/docs/pt/docs/tutorial/body-nested-models.md b/docs/pt/docs/tutorial/body-nested-models.md index bbe72a744..2954ae3db 100644 --- a/docs/pt/docs/tutorial/body-nested-models.md +++ b/docs/pt/docs/tutorial/body-nested-models.md @@ -6,9 +6,7 @@ Com o **FastAPI**, você pode definir, validar, documentar e usar modelos profun Você pode definir um atributo como um subtipo. Por exemplo, uma `list` do Python: -```Python hl_lines="14" -{!../../docs_src/body_nested_models/tutorial001.py!} -``` +{* ../../docs_src/body_nested_models/tutorial001.py hl[14] *} Isso fará com que tags seja uma lista de itens mesmo sem declarar o tipo dos elementos desta lista. @@ -20,9 +18,7 @@ Mas o Python tem uma maneira específica de declarar listas com tipos internos o Primeiramente, importe `List` do módulo `typing` que já vem por padrão no Python: -```Python hl_lines="1" -{!../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *} ### Declare a `List` com um parâmetro de tipo @@ -44,9 +40,7 @@ Use a mesma sintaxe padrão para atributos de modelo com tipos internos. Portanto, em nosso exemplo, podemos fazer com que `tags` sejam especificamente uma "lista de strings": -```Python hl_lines="14" -{!../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[14] *} ## Tipo "set" @@ -58,9 +52,7 @@ E que o Python tem um tipo de dados especial para conjuntos de itens únicos, o Então podemos importar `Set` e declarar `tags` como um `set` de `str`s: -```Python hl_lines="1 14" -{!../../docs_src/body_nested_models/tutorial003.py!} -``` +{* ../../docs_src/body_nested_models/tutorial003.py hl[1,14] *} Com isso, mesmo que você receba uma requisição contendo dados duplicados, ela será convertida em um conjunto de itens exclusivos. @@ -82,17 +74,13 @@ Tudo isso, aninhado arbitrariamente. Por exemplo, nós podemos definir um modelo `Image`: -```Python hl_lines="9-11" -{!../../docs_src/body_nested_models/tutorial004.py!} -``` +{* ../../docs_src/body_nested_models/tutorial004.py hl[9:11] *} ### Use o sub-modelo como um tipo E então podemos usa-lo como o tipo de um atributo: -```Python hl_lines="20" -{!../../docs_src/body_nested_models/tutorial004.py!} -``` +{* ../../docs_src/body_nested_models/tutorial004.py hl[20] *} Isso significa que o **FastAPI** vai esperar um corpo similar à: @@ -125,9 +113,7 @@ Para ver todas as opções possíveis, cheque a documentação para os ../../../docs_src/body_updates/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="30-35" -{!> ../../../docs_src/body_updates/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="30-35" -{!> ../../../docs_src/body_updates/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *} `PUT` é usado para receber dados que devem substituir os dados existentes. @@ -84,29 +62,7 @@ Isso gera um `dict` com apenas os dados definidos ao criar o modelo `item`, excl Então, você pode usar isso para gerar um `dict` com apenas os dados definidos (enviados na solicitação), omitindo valores padrão: -//// tab | Python 3.10+ - -```Python hl_lines="32" -{!> ../../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="34" -{!> ../../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="34" -{!> ../../../docs_src/body_updates/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *} ### Usando o parâmetro `update` do Pydantic @@ -122,29 +78,7 @@ Os exemplos aqui usam `.copy()` para compatibilidade com o Pydantic v1, mas voc Como `stored_item_model.model_copy(update=update_data)`: -//// tab | Python 3.10+ - -```Python hl_lines="33" -{!> ../../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="35" -{!> ../../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="35" -{!> ../../../docs_src/body_updates/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *} ### Recapitulando as atualizações parciais @@ -161,29 +95,7 @@ Resumindo, para aplicar atualizações parciais você pode: * Salvar os dados no seu banco de dados. * Retornar o modelo atualizado. -//// tab | Python 3.10+ - -```Python hl_lines="28-35" -{!> ../../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="30-37" -{!> ../../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="30-37" -{!> ../../../docs_src/body_updates/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *} /// tip | Dica diff --git a/docs/pt/docs/tutorial/body.md b/docs/pt/docs/tutorial/body.md index f3a1fda75..2508d7981 100644 --- a/docs/pt/docs/tutorial/body.md +++ b/docs/pt/docs/tutorial/body.md @@ -22,9 +22,7 @@ Como é desencorajado, a documentação interativa com Swagger UI não irá most Primeiro, você precisa importar `BaseModel` do `pydantic`: -```Python hl_lines="4" -{!../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[4] *} ## Crie seu modelo de dados @@ -32,9 +30,7 @@ Então você declara seu modelo de dados como uma classe que herda `BaseModel`. Utilize os tipos Python padrão para todos os atributos: -```Python hl_lines="7-11" -{!../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[7:11] *} Assim como quando declaramos parâmetros de consulta, quando um atributo do modelo possui um valor padrão, ele se torna opcional. Caso contrário, se torna obrigatório. Use `None` para torná-lo opcional. @@ -62,9 +58,7 @@ Por exemplo, o modelo acima declara um JSON "`object`" (ou `dict` no Python) com Para adicionar o corpo na *função de operação de rota*, declare-o da mesma maneira que você declarou parâmetros de rota e consulta: -```Python hl_lines="18" -{!../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[18] *} ...E declare o tipo como o modelo que você criou, `Item`. @@ -131,9 +125,7 @@ Melhora o suporte do editor para seus modelos Pydantic com:: Dentro da função, você pode acessar todos os atributos do objeto do modelo diretamente: -```Python hl_lines="21" -{!../../docs_src/body/tutorial002.py!} -``` +{* ../../docs_src/body/tutorial002.py hl[21] *} ## Corpo da requisição + parâmetros de rota @@ -141,9 +133,7 @@ Você pode declarar parâmetros de rota e corpo da requisição ao mesmo tempo. O **FastAPI** irá reconhecer que os parâmetros da função que combinam com parâmetros de rota devem ser **retirados da rota**, e parâmetros da função que são declarados como modelos Pydantic sejam **retirados do corpo da requisição**. -```Python hl_lines="17-18" -{!../../docs_src/body/tutorial003.py!} -``` +{* ../../docs_src/body/tutorial003.py hl[17:18] *} ## Corpo da requisição + parâmetros de rota + parâmetros de consulta @@ -151,9 +141,7 @@ Você também pode declarar parâmetros de **corpo**, **rota** e **consulta**, a O **FastAPI** irá reconhecer cada um deles e retirar a informação do local correto. -```Python hl_lines="18" -{!../../docs_src/body/tutorial004.py!} -``` +{* ../../docs_src/body/tutorial004.py hl[18] *} Os parâmetros da função serão reconhecidos conforme abaixo: diff --git a/docs/pt/docs/tutorial/cookie-param-models.md b/docs/pt/docs/tutorial/cookie-param-models.md index 671e0d74f..3d46ba44c 100644 --- a/docs/pt/docs/tutorial/cookie-param-models.md +++ b/docs/pt/docs/tutorial/cookie-param-models.md @@ -20,57 +20,7 @@ Essa mesma técnica se aplica para `Query`, `Cookie`, e `Header`. 😎 Declare o parâmetro de **cookie** que você precisa em um **modelo Pydantic**, e depois declare o parâmetro como um `Cookie`: -//// tab | Python 3.10+ - -```Python hl_lines="9-12 16" -{!> ../../docs_src/cookie_param_models/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9-12 16" -{!> ../../docs_src/cookie_param_models/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10-13 17" -{!> ../../docs_src/cookie_param_models/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="7-10 14" -{!> ../../docs_src/cookie_param_models/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="9-12 16" -{!> ../../docs_src/cookie_param_models/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *} O **FastAPI** irá **extrair** os dados para **cada campo** dos **cookies** recebidos na requisição e lhe fornecer o modelo Pydantic que você definiu. @@ -102,35 +52,7 @@ Agora a sua API possui o poder de contrar o seu próprio ../../docs_src/cookie_param_models/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/cookie_param_models/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/cookie_param_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/cookie_param_models/tutorial002_an_py39.py hl[10] *} Se o cliente tentar enviar alguns **cookies extras**, eles receberão um retorno de **erro**. diff --git a/docs/pt/docs/tutorial/cookie-params.md b/docs/pt/docs/tutorial/cookie-params.md index 50bec8cf7..da85d796e 100644 --- a/docs/pt/docs/tutorial/cookie-params.md +++ b/docs/pt/docs/tutorial/cookie-params.md @@ -6,57 +6,7 @@ Você pode definir parâmetros de Cookie da mesma maneira que define paramêtros Primeiro importe `Cookie`: -//// tab | Python 3.10+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[3] *} ## Declare parâmetros de `Cookie` @@ -65,57 +15,7 @@ Então declare os paramêtros de cookie usando a mesma estrutura que em `Path` e Você pode definir o valor padrão, assim como todas as validações extras ou parâmetros de anotação: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/cookie_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9] *} /// note | Detalhes Técnicos diff --git a/docs/pt/docs/tutorial/cors.md b/docs/pt/docs/tutorial/cors.md index 326101bd2..0ab07a3c2 100644 --- a/docs/pt/docs/tutorial/cors.md +++ b/docs/pt/docs/tutorial/cors.md @@ -46,9 +46,7 @@ Você também pode especificar se o seu backend permite: * Métodos HTTP específicos (`POST`, `PUT`) ou todos eles com o curinga `"*"`. * Cabeçalhos HTTP específicos ou todos eles com o curinga `"*"`. -```Python hl_lines="2 6-11 13-19" -{!../../docs_src/cors/tutorial001.py!} -``` +{* ../../docs_src/cors/tutorial001.py hl[2,6:11,13:19] *} Os parâmetros padrão usados ​​pela implementação `CORSMiddleware` são restritivos por padrão, então você precisará habilitar explicitamente as origens, métodos ou cabeçalhos específicos para que os navegadores tenham permissão para usá-los em um contexto de domínios diferentes. diff --git a/docs/pt/docs/tutorial/debugging.md b/docs/pt/docs/tutorial/debugging.md index fca162988..67b764457 100644 --- a/docs/pt/docs/tutorial/debugging.md +++ b/docs/pt/docs/tutorial/debugging.md @@ -6,9 +6,7 @@ Você pode conectar o depurador no seu editor, por exemplo, com o Visual Studio Em seu aplicativo FastAPI, importe e execute `uvicorn` diretamente: -```Python hl_lines="1 15" -{!../../docs_src/debugging/tutorial001.py!} -``` +{* ../../docs_src/debugging/tutorial001.py hl[1,15] *} ### Sobre `__name__ == "__main__"` diff --git a/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md index fcf71d08c..ef67aa979 100644 --- a/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,57 +6,7 @@ Antes de nos aprofundarmos no sistema de **Injeção de Dependência**, vamos me No exemplo anterior, nós retornávamos um `dict` da nossa dependência ("injetável"): -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[9] *} Mas assim obtemos um `dict` como valor do parâmetro `commons` na *função de operação de rota*. @@ -119,165 +69,15 @@ Isso também se aplica a objetos chamáveis que não recebem nenhum parâmetro. Então, podemos mudar o "injetável" na dependência `common_parameters` acima para a classe `CommonQueryParams`: -//// tab | Python 3.10+ - -```Python hl_lines="11-15" -{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11-15" -{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12-16" -{!> ../../docs_src/dependencies/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="9-13" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="11-15" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[11:15] *} Observe o método `__init__` usado para criar uma instância da classe: -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[12] *} ...ele possui os mesmos parâmetros que nosso `common_parameters` anterior: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="6" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8] *} Esses parâmetros são utilizados pelo **FastAPI** para "definir" a dependência. @@ -293,57 +93,7 @@ Os dados serão convertidos, validados, documentados no esquema da OpenAPI e etc Agora você pode declarar sua dependência utilizando essa classe. -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/dependencies/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[19] *} O **FastAPI** chama a classe `CommonQueryParams`. Isso cria uma "instância" dessa classe e é a instância que será passada para o parâmetro `commons` na sua função. @@ -437,57 +187,7 @@ commons = Depends(CommonQueryParams) ...como em: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/dependencies/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial003.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial003_an_py310.py hl[19] *} Mas declarar o tipo é encorajado por que é a forma que o seu editor de texto sabe o que será passado como valor do parâmetro `commons`. @@ -575,57 +275,7 @@ Você declara a dependência como o tipo do parâmetro, e utiliza `Depends()` se O mesmo exemplo ficaria então dessa forma: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/dependencies/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial004.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial004_an_py310.py hl[19] *} ...e o **FastAPI** saberá o que fazer. diff --git a/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 89c34855e..d7d31bb45 100644 --- a/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -14,35 +14,7 @@ O *decorador da operação de rota* recebe um argumento opcional `dependencies`. Ele deve ser uma lista de `Depends()`: -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[19] *} Essas dependências serão executadas/resolvidas da mesma forma que dependências comuns. Mas o valor delas (se existir algum) não será passado para a sua *função de operação de rota*. @@ -72,69 +44,13 @@ Você pode utilizar as mesmas *funções* de dependências que você usaria norm Dependências podem declarar requisitos de requisições (como cabeçalhos) ou outras subdependências: -//// tab | Python 3.9+ - -```Python hl_lines="8 13" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="7 12" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível - -/// - -```Python hl_lines="6 11" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[8,13] *} ### Levantando exceções Essas dependências podem levantar exceções, da mesma forma que dependências comuns: -//// tab | Python 3.9+ - -```Python hl_lines="10 15" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 14" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível - -/// - -```Python hl_lines="8 13" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[10,15] *} ### Valores de retorno @@ -142,37 +58,7 @@ E elas também podem ou não retornar valores, eles não serão utilizados. Então, você pode reutilizar uma dependência comum (que retorna um valor) que já seja utilizada em outro lugar, e mesmo que o valor não seja utilizado, a dependência será executada: -//// tab | Python 3.9+ - -```Python hl_lines="11 16" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10 15" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip | Dica - - - -/// - - Utilize a versão com `Annotated` se possível - -```Python hl_lines="9 14" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[11,16] *} ## Dependências para um grupo de *operações de rota* diff --git a/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md index 90c1e02e0..eaf711197 100644 --- a/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md @@ -29,21 +29,15 @@ Por exemplo, você poderia utilizar isso para criar uma sessão do banco de dado Apenas o código anterior a declaração com `yield` e o código contendo essa declaração são executados antes de criar uma resposta. -```Python hl_lines="2-4" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[2:4] *} O valor gerado (yielded) é o que é injetado nas *operações de rota* e outras dependências. -```Python hl_lines="4" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[4] *} O código após o `yield` é executado após a resposta ser entregue: -```Python hl_lines="5-6" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[5:6] *} /// tip | Dica @@ -207,35 +201,7 @@ Uma alternativa que você pode utilizar para capturar exceções (e possivelment Se você capturar uma exceção com `except` em uma dependência que utilize `yield` e ela não for levantada novamente (ou uma nova exceção for levantada), o FastAPI não será capaz de identifcar que houve uma exceção, da mesma forma que aconteceria com Python puro: -//// tab | Python 3.9+ - -```Python hl_lines="15-16" -{!> ../../docs_src/dependencies/tutorial008c_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14-15" -{!> ../../docs_src/dependencies/tutorial008c_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-annotated - -/// tip | dica - -utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="13-14" -{!> ../../docs_src/dependencies/tutorial008c.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial008c_an_py39.py hl[15:16] *} Neste caso, o cliente irá ver uma resposta *HTTP 500 Internal Server Error* como deveria acontecer, já que não estamos levantando nenhuma `HTTPException` ou coisa parecida, mas o servidor **não terá nenhum log** ou qualquer outra indicação de qual foi o erro. 😱 @@ -245,21 +211,7 @@ Se você capturar uma exceção em uma dependência com `yield`, a menos que voc Você pode relançar a mesma exceção utilizando `raise`: -//// tab | Python 3.9+ - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial008d_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="16" -{!> ../../docs_src/dependencies/tutorial008d_an.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial008d_an_py39.py hl[17] *} //// tab | python 3.8+ non-annotated @@ -269,9 +221,7 @@ Utilize a versão com `Annotated` se possível. /// -```Python hl_lines="15" -{!> ../../docs_src/dependencies/tutorial008d.py!} -``` +{* ../../docs_src/dependencies/tutorial008d.py hl[15] *} //// @@ -402,9 +352,7 @@ Em python, você pode criar Gerenciadores de Contexto ao ../../docs_src/dependencies/tutorial012_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="16" -{!> ../../docs_src/dependencies/tutorial012_an.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="15" -{!> ../../docs_src/dependencies/tutorial012.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial012_an_py39.py hl[16] *} E todos os conceitos apresentados na sessão sobre [adicionar dependências em *decoradores de operação de rota*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} ainda se aplicam, mas nesse caso, para todas as *operações de rota* da aplicação. diff --git a/docs/pt/docs/tutorial/dependencies/index.md b/docs/pt/docs/tutorial/dependencies/index.md index 0f411ff1e..1500b715a 100644 --- a/docs/pt/docs/tutorial/dependencies/index.md +++ b/docs/pt/docs/tutorial/dependencies/index.md @@ -31,57 +31,7 @@ Primeiro vamos focar na dependência. Ela é apenas uma função que pode receber os mesmos parâmetros de uma *função de operação de rota*: -//// tab | Python 3.10+ - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="8-11" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-12" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="6-7" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="8-11" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *} E pronto. @@ -113,113 +63,13 @@ Certifique-se de [Atualizar a versão do FastAPI](../../deployment/versions.md#a ### Importando `Depends` -//// tab | Python 3.10+ - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *} ### Declarando a dependência, no "dependente" Da mesma forma que você utiliza `Body`, `Query`, etc. Como parâmetros de sua *função de operação de rota*, utilize `Depends` com um novo parâmetro: -//// tab | Python 3.10+ - -```Python hl_lines="13 18" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="15 20" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="16 21" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="11 16" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="15 20" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *} Ainda que `Depends` seja utilizado nos parâmetros da função da mesma forma que `Body`, `Query`, etc, `Depends` funciona de uma forma um pouco diferente. @@ -276,29 +126,7 @@ commons: Annotated[dict, Depends(common_parameters)] Mas como estamos utilizando `Annotated`, podemos guardar esse valor `Annotated` em uma variável e utilizá-la em múltiplos locais: -//// tab | Python 3.10+ - -```Python hl_lines="12 16 21" -{!> ../../docs_src/dependencies/tutorial001_02_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14 18 23" -{!> ../../docs_src/dependencies/tutorial001_02_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15 19 24" -{!> ../../docs_src/dependencies/tutorial001_02_an.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *} /// tip | Dica diff --git a/docs/pt/docs/tutorial/dependencies/sub-dependencies.md b/docs/pt/docs/tutorial/dependencies/sub-dependencies.md index 4c0f42dbb..3975ce182 100644 --- a/docs/pt/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/pt/docs/tutorial/dependencies/sub-dependencies.md @@ -10,57 +10,7 @@ O **FastAPI** se encarrega de resolver essas dependências. Você pode criar uma primeira dependência (injetável) dessa forma: -//// tab | Python 3.10+ - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-10" -{!> ../../docs_src/dependencies/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10 non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="6-7" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *} Esse código declara um parâmetro de consulta opcional, `q`, com o tipo `str`, e então retorna esse parâmetro. @@ -70,57 +20,7 @@ Isso é bastante simples (e não muito útil), mas irá nos ajudar a focar em co Então, você pode criar uma outra função para uma dependência (um "injetável") que ao mesmo tempo declara sua própria dependência (o que faz dela um "dependente" também): -//// tab | Python 3.10+ - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14" -{!> ../../docs_src/dependencies/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10 non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *} Vamos focar nos parâmetros declarados: @@ -133,57 +33,7 @@ Vamos focar nos parâmetros declarados: Então podemos utilizar a dependência com: -//// tab | Python 3.10+ - -```Python hl_lines="23" -{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23" -{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/dependencies/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10 non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="22" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *} /// info | Informação diff --git a/docs/pt/docs/tutorial/encoder.md b/docs/pt/docs/tutorial/encoder.md index d89c71fc8..87c6322e1 100644 --- a/docs/pt/docs/tutorial/encoder.md +++ b/docs/pt/docs/tutorial/encoder.md @@ -20,21 +20,7 @@ Você pode usar a função `jsonable_encoder` para resolver isso. A função recebe um objeto, como um modelo Pydantic e retorna uma versão compatível com JSON: -//// tab | Python 3.10+ - -```Python hl_lines="4 21" -{!> ../../docs_src/encoder/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="5 22" -{!> ../../docs_src/encoder/tutorial001.py!} -``` - -//// +{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *} Neste exemplo, ele converteria o modelo Pydantic em um `dict`, e o `datetime` em um `str`. diff --git a/docs/pt/docs/tutorial/extra-data-types.md b/docs/pt/docs/tutorial/extra-data-types.md index 78f7ac694..09c838be0 100644 --- a/docs/pt/docs/tutorial/extra-data-types.md +++ b/docs/pt/docs/tutorial/extra-data-types.md @@ -55,12 +55,8 @@ Aqui estão alguns dos tipos de dados adicionais que você pode usar: Aqui está um exemplo de *operação de rota* com parâmetros utilizando-se de alguns dos tipos acima. -```Python hl_lines="1 3 12-16" -{!../../docs_src/extra_data_types/tutorial001.py!} -``` +{* ../../docs_src/extra_data_types/tutorial001.py hl[1,3,12:16] *} Note que os parâmetros dentro da função tem seu tipo de dados natural, e você pode, por exemplo, realizar manipulações normais de data, como: -```Python hl_lines="18-19" -{!../../docs_src/extra_data_types/tutorial001.py!} -``` +{* ../../docs_src/extra_data_types/tutorial001.py hl[18:19] *} diff --git a/docs/pt/docs/tutorial/extra-models.md b/docs/pt/docs/tutorial/extra-models.md index 03227f2bb..cccef16e3 100644 --- a/docs/pt/docs/tutorial/extra-models.md +++ b/docs/pt/docs/tutorial/extra-models.md @@ -20,21 +20,7 @@ Se não souber, você aprenderá o que é uma "senha hash" nos [capítulos de se Aqui está uma ideia geral de como os modelos poderiam parecer com seus campos de senha e os lugares onde são usados: -//// tab | Python 3.8 and above - -```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" -{!> ../../docs_src/extra_models/tutorial001.py!} -``` - -//// - -//// tab | Python 3.10 and above - -```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" -{!> ../../docs_src/extra_models/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial001.py hl[9,11,16,22,24,29:30,33:35,40:41] *} ### Sobre `**user_in.dict()` @@ -168,21 +154,7 @@ Toda conversão de dados, validação, documentação, etc. ainda funcionará no Dessa forma, podemos declarar apenas as diferenças entre os modelos (com `password` em texto claro, com `hashed_password` e sem senha): -//// tab | Python 3.8 and above - -```Python hl_lines="9 15-16 19-20 23-24" -{!> ../../docs_src/extra_models/tutorial002.py!} -``` - -//// - -//// tab | Python 3.10 and above - -```Python hl_lines="7 13-14 17-18 21-22" -{!> ../../docs_src/extra_models/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial002.py hl[9,15:16,19:20,23:24] *} ## `Union` ou `anyOf` @@ -198,21 +170,7 @@ Ao definir um ../../docs_src/extra_models/tutorial003.py!} -``` - -//// - -//// tab | Python 3.10 and above - -```Python hl_lines="1 14-15 18-20 33" -{!> ../../docs_src/extra_models/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial003.py hl[1,14:15,18:20,33] *} ### `Union` no Python 3.10 @@ -234,21 +192,7 @@ Da mesma forma, você pode declarar respostas de listas de objetos. Para isso, use o padrão Python `typing.List` (ou simplesmente `list` no Python 3.9 e superior): -//// tab | Python 3.8 and above - -```Python hl_lines="1 20" -{!> ../../docs_src/extra_models/tutorial004.py!} -``` - -//// - -//// tab | Python 3.9 and above - -```Python hl_lines="18" -{!> ../../docs_src/extra_models/tutorial004_py39.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial004.py hl[1,20] *} ## Resposta com `dict` arbitrário @@ -258,21 +202,7 @@ Isso é útil se você não souber os nomes de campo / atributo válidos (que se Neste caso, você pode usar `typing.Dict` (ou simplesmente dict no Python 3.9 e superior): -//// tab | Python 3.8 and above - -```Python hl_lines="1 8" -{!> ../../docs_src/extra_models/tutorial005.py!} -``` - -//// - -//// tab | Python 3.9 and above - -```Python hl_lines="6" -{!> ../../docs_src/extra_models/tutorial005_py39.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial005.py hl[1,8] *} ## Em resumo diff --git a/docs/pt/docs/tutorial/first-steps.md b/docs/pt/docs/tutorial/first-steps.md index f301c18b6..523b8f05c 100644 --- a/docs/pt/docs/tutorial/first-steps.md +++ b/docs/pt/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ O arquivo FastAPI mais simples pode se parecer com: -```Python -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} Copie o conteúdo para um arquivo `main.py`. @@ -133,9 +131,7 @@ Você também pode usá-lo para gerar código automaticamente para clientes que ### Passo 1: importe `FastAPI` -```Python hl_lines="1" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI` é uma classe Python que fornece todas as funcionalidades para sua API. @@ -149,9 +145,7 @@ Você pode usar todas as funcionalidades do ../../docs_src/header_param_models/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9-14 18" -{!> ../../docs_src/header_param_models/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10-15 19" -{!> ../../docs_src/header_param_models/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="7-12 16" -{!> ../../docs_src/header_param_models/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="9-14 18" -{!> ../../docs_src/header_param_models/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="7-12 16" -{!> ../../docs_src/header_param_models/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *} O **FastAPI** irá **extrair** os dados de **cada campo** a partir dos **cabeçalhos** da requisição e te retornará o modelo do Pydantic que você definiu. @@ -96,71 +32,7 @@ Em alguns casos de uso especiais (provavelmente não muito comuns), você pode q Você pode usar a configuração dos modelos do Pydantic para proibir (`forbid`) quaisquer campos `extra`: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/header_param_models/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/header_param_models/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/header_param_models/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/header_param_models/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/header_param_models/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/header_param_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/header_param_models/tutorial002_an_py310.py hl[10] *} Se um cliente tentar enviar alguns **cabeçalhos extra**, eles irão receber uma resposta de **erro**. diff --git a/docs/pt/docs/tutorial/header-params.md b/docs/pt/docs/tutorial/header-params.md index ac61d0305..d071bcc35 100644 --- a/docs/pt/docs/tutorial/header-params.md +++ b/docs/pt/docs/tutorial/header-params.md @@ -6,21 +6,7 @@ Você pode definir parâmetros de Cabeçalho da mesma maneira que define paramê Primeiro importe `Header`: -//// tab | Python 3.10+ - -```Python hl_lines="1" -{!> ../../docs_src/header_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/header_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial001_py310.py hl[1] *} ## Declare parâmetros de `Header` @@ -28,21 +14,7 @@ Então declare os paramêtros de cabeçalho usando a mesma estrutura que em `Pat O primeiro valor é o valor padrão, você pode passar todas as validações adicionais ou parâmetros de anotação: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/header_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial001_py310.py hl[7] *} /// note | Detalhes Técnicos @@ -74,21 +46,7 @@ Portanto, você pode usar `user_agent` como faria normalmente no código Python, Se por algum motivo você precisar desabilitar a conversão automática de sublinhados para hífens, defina o parâmetro `convert_underscores` de `Header` para `False`: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/header_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/header_params/tutorial002.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial002_py310.py hl[8] *} /// warning | Aviso @@ -106,29 +64,7 @@ Você receberá todos os valores do cabeçalho duplicado como uma `list` Python. Por exemplo, para declarar um cabeçalho de `X-Token` que pode aparecer mais de uma vez, você pode escrever: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/header_params/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial003.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial003_py310.py hl[7] *} Se você se comunicar com essa *operação de caminho* enviando dois cabeçalhos HTTP como: diff --git a/docs/pt/docs/tutorial/metadata.md b/docs/pt/docs/tutorial/metadata.md index 5db2882b9..57effb3ff 100644 --- a/docs/pt/docs/tutorial/metadata.md +++ b/docs/pt/docs/tutorial/metadata.md @@ -18,9 +18,7 @@ Você pode definir os seguintes campos que são usados na especificação OpenAP Você pode defini-los da seguinte maneira: -```Python hl_lines="3-16 19-32" -{!../../docs_src/metadata/tutorial001.py!} -``` +{* ../../docs_src/metadata/tutorial001.py hl[3:16,19:32] *} /// tip | Dica @@ -38,9 +36,7 @@ Desde o OpenAPI 3.1.0 e FastAPI 0.99.0, você também pode definir o license_inf Por exemplo: -```Python hl_lines="31" -{!../../docs_src/metadata/tutorial001_1.py!} -``` +{* ../../docs_src/metadata/tutorial001_1.py hl[31] *} ## Metadados para tags @@ -62,9 +58,7 @@ Vamos tentar isso em um exemplo com tags para `users` e `items`. Crie metadados para suas tags e passe-os para o parâmetro `openapi_tags`: -```Python hl_lines="3-16 18" -{!../../docs_src/metadata/tutorial004.py!} -``` +{* ../../docs_src/metadata/tutorial004.py hl[3:16,18] *} Observe que você pode usar Markdown dentro das descrições. Por exemplo, "login" será exibido em negrito (**login**) e "fancy" será exibido em itálico (_fancy_). @@ -78,9 +72,7 @@ Você não precisa adicionar metadados para todas as tags que você usa. Use o parâmetro `tags` com suas *operações de rota* (e `APIRouter`s) para atribuí-los a diferentes tags: -```Python hl_lines="21 26" -{!../../docs_src/metadata/tutorial004.py!} -``` +{* ../../docs_src/metadata/tutorial004.py hl[21,26] *} /// info | Informação @@ -108,9 +100,7 @@ Mas você pode configurá-lo com o parâmetro `openapi_url`. Por exemplo, para defini-lo para ser servido em `/api/v1/openapi.json`: -```Python hl_lines="3" -{!../../docs_src/metadata/tutorial002.py!} -``` +{* ../../docs_src/metadata/tutorial002.py hl[3] *} Se você quiser desativar completamente o esquema OpenAPI, pode definir `openapi_url=None`, o que também desativará as interfaces de documentação que o utilizam. @@ -127,6 +117,4 @@ Você pode configurar as duas interfaces de documentação incluídas: Por exemplo, para definir o Swagger UI para ser servido em `/documentation` e desativar o ReDoc: -```Python hl_lines="3" -{!../../docs_src/metadata/tutorial003.py!} -``` +{* ../../docs_src/metadata/tutorial003.py hl[3] *} diff --git a/docs/pt/docs/tutorial/middleware.md b/docs/pt/docs/tutorial/middleware.md index d1b798356..32b81c646 100644 --- a/docs/pt/docs/tutorial/middleware.md +++ b/docs/pt/docs/tutorial/middleware.md @@ -31,9 +31,7 @@ A função middleware recebe: * Então ela retorna a `response` gerada pela *operação de rota* correspondente. * Você pode então modificar ainda mais o `response` antes de retorná-lo. -```Python hl_lines="8-9 11 14" -{!../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[8:9,11,14] *} /// tip | Dica @@ -59,9 +57,7 @@ E também depois que a `response` é gerada, antes de retorná-la. Por exemplo, você pode adicionar um cabeçalho personalizado `X-Process-Time` contendo o tempo em segundos que levou para processar a solicitação e gerar uma resposta: -```Python hl_lines="10 12-13" -{!../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *} ## Outros middlewares diff --git a/docs/pt/docs/tutorial/path-operation-configuration.md b/docs/pt/docs/tutorial/path-operation-configuration.md index 5f3cc82fb..f183c9d23 100644 --- a/docs/pt/docs/tutorial/path-operation-configuration.md +++ b/docs/pt/docs/tutorial/path-operation-configuration.md @@ -16,29 +16,7 @@ Você pode passar diretamente o código `int`, como `404`. Mas se você não se lembrar o que cada código numérico significa, pode usar as constantes de atalho em `status`: -//// tab | Python 3.8 and above - -```Python hl_lines="3 17" -{!> ../../docs_src/path_operation_configuration/tutorial001.py!} -``` - -//// - -//// tab | Python 3.9 and above - -```Python hl_lines="3 17" -{!> ../../docs_src/path_operation_configuration/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.10 and above - -```Python hl_lines="1 15" -{!> ../../docs_src/path_operation_configuration/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial001.py hl[3,17] *} Esse código de status será usado na resposta e será adicionado ao esquema OpenAPI. @@ -54,29 +32,7 @@ Você também poderia usar `from starlette import status`. Você pode adicionar tags para sua *operação de rota*, passe o parâmetro `tags` com uma `list` de `str` (comumente apenas um `str`): -//// tab | Python 3.8 and above - -```Python hl_lines="17 22 27" -{!> ../../docs_src/path_operation_configuration/tutorial002.py!} -``` - -//// - -//// tab | Python 3.9 and above - -```Python hl_lines="17 22 27" -{!> ../../docs_src/path_operation_configuration/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.10 and above - -```Python hl_lines="15 20 25" -{!> ../../docs_src/path_operation_configuration/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial002.py hl[17,22,27] *} Eles serão adicionados ao esquema OpenAPI e usados pelas interfaces de documentação automática: @@ -90,37 +46,13 @@ Nestes casos, pode fazer sentido armazenar as tags em um `Enum`. **FastAPI** suporta isso da mesma maneira que com strings simples: -```Python hl_lines="1 8-10 13 18" -{!../../docs_src/path_operation_configuration/tutorial002b.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial002b.py hl[1,8:10,13,18] *} ## Resumo e descrição Você pode adicionar um `summary` e uma `description`: -//// tab | Python 3.8 and above - -```Python hl_lines="20-21" -{!> ../../docs_src/path_operation_configuration/tutorial003.py!} -``` - -//// - -//// tab | Python 3.9 and above - -```Python hl_lines="20-21" -{!> ../../docs_src/path_operation_configuration/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.10 and above - -```Python hl_lines="18-19" -{!> ../../docs_src/path_operation_configuration/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial003.py hl[20:21] *} ## Descrição do docstring @@ -128,29 +60,7 @@ Como as descrições tendem a ser longas e cobrir várias linhas, você pode dec Você pode escrever Markdown na docstring, ele será interpretado e exibido corretamente (levando em conta a indentação da docstring). -//// tab | Python 3.8 and above - -```Python hl_lines="19-27" -{!> ../../docs_src/path_operation_configuration/tutorial004.py!} -``` - -//// - -//// tab | Python 3.9 and above - -```Python hl_lines="19-27" -{!> ../../docs_src/path_operation_configuration/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.10 and above - -```Python hl_lines="17-25" -{!> ../../docs_src/path_operation_configuration/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial004.py hl[19:27] *} Ela será usada nas documentações interativas: @@ -161,29 +71,7 @@ Ela será usada nas documentações interativas: Você pode especificar a descrição da resposta com o parâmetro `response_description`: -//// tab | Python 3.8 and above - -```Python hl_lines="21" -{!> ../../docs_src/path_operation_configuration/tutorial005.py!} -``` - -//// - -//// tab | Python 3.9 and above - -```Python hl_lines="21" -{!> ../../docs_src/path_operation_configuration/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.10 and above - -```Python hl_lines="19" -{!> ../../docs_src/path_operation_configuration/tutorial005_py310.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial005.py hl[21] *} /// info | Informação @@ -205,9 +93,7 @@ Então, se você não fornecer uma, o **FastAPI** irá gerar automaticamente uma Se você precisar marcar uma *operação de rota* como descontinuada, mas sem removê-la, passe o parâmetro `deprecated`: -```Python hl_lines="16" -{!../../docs_src/path_operation_configuration/tutorial006.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial006.py hl[16] *} Ela será claramente marcada como descontinuada nas documentações interativas: diff --git a/docs/pt/docs/tutorial/path-params-numeric-validations.md b/docs/pt/docs/tutorial/path-params-numeric-validations.md index 3361f86c5..3aea1188d 100644 --- a/docs/pt/docs/tutorial/path-params-numeric-validations.md +++ b/docs/pt/docs/tutorial/path-params-numeric-validations.md @@ -6,21 +6,7 @@ Do mesmo modo que você pode declarar mais validações e metadados para parâme Primeiro, importe `Path` de `fastapi`: -//// tab | Python 3.10+ - -```Python hl_lines="1" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial001_py310.py hl[1] *} ## Declare metadados @@ -28,21 +14,7 @@ Você pode declarar todos os parâmetros da mesma maneira que na `Query`. Por exemplo para declarar um valor de metadado `title` para o parâmetro de rota `item_id` você pode digitar: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial001_py310.py hl[8] *} /// note | Nota @@ -70,9 +42,7 @@ Isso não faz diferença para o **FastAPI**. Ele vai detectar os parâmetros pel Então, você pode declarar sua função assim: -```Python hl_lines="7" -{!../../docs_src/path_params_numeric_validations/tutorial002.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial002.py hl[7] *} ## Ordene os parâmetros de a acordo com sua necessidade, truques @@ -82,9 +52,7 @@ Passe `*`, como o primeiro parâmetro da função. O Python não vai fazer nada com esse `*`, mas ele vai saber que a partir dali os parâmetros seguintes deverão ser chamados argumentos nomeados (pares chave-valor), também conhecidos como kwargs. Mesmo que eles não possuam um valor padrão. -```Python hl_lines="7" -{!../../docs_src/path_params_numeric_validations/tutorial003.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *} ## Validações numéricas: maior que ou igual @@ -92,9 +60,7 @@ Com `Query` e `Path` (e outras que você verá mais tarde) você pode declarar r Aqui, com `ge=1`, `item_id` precisará ser um número inteiro maior que ("`g`reater than") ou igual ("`e`qual") a 1. -```Python hl_lines="8" -{!../../docs_src/path_params_numeric_validations/tutorial004.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial004.py hl[8] *} ## Validações numéricas: maior que e menor que ou igual @@ -103,9 +69,7 @@ O mesmo se aplica para: * `gt`: maior que (`g`reater `t`han) * `le`: menor que ou igual (`l`ess than or `e`qual) -```Python hl_lines="9" -{!../../docs_src/path_params_numeric_validations/tutorial005.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial005.py hl[9] *} ## Validações numéricas: valores do tipo float, maior que e menor que @@ -117,9 +81,7 @@ Assim, `0.5` seria um valor válido. Mas `0.0` ou `0` não seria. E o mesmo para lt. -```Python hl_lines="11" -{!../../docs_src/path_params_numeric_validations/tutorial006.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial006.py hl[11] *} ## Recapitulando diff --git a/docs/pt/docs/tutorial/path-params.md b/docs/pt/docs/tutorial/path-params.md index 64f8a0253..ecf77d676 100644 --- a/docs/pt/docs/tutorial/path-params.md +++ b/docs/pt/docs/tutorial/path-params.md @@ -2,9 +2,7 @@ Você pode declarar os "parâmetros" ou "variáveis" com a mesma sintaxe utilizada pelo formato de strings do Python: -```Python hl_lines="6-7" -{!../../docs_src/path_params/tutorial001.py!} -``` +{* ../../docs_src/path_params/tutorial001.py hl[6:7] *} O valor do parâmetro que foi passado à `item_id` será passado para a sua função como o argumento `item_id`. @@ -18,9 +16,7 @@ Então, se você rodar este exemplo e for até ../../docs_src/query_param_models/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="8-12 16" -{!> ../../docs_src/query_param_models/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10-14 18" -{!> ../../docs_src/query_param_models/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="9-13 17" -{!> ../../docs_src/query_param_models/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="8-12 16" -{!> ../../docs_src/query_param_models/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="9-13 17" -{!> ../../docs_src/query_param_models/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *} O **FastAPI** **extrairá** os dados para **cada campo** dos **parâmetros de consulta** presentes na requisição, e fornecerá o modelo Pydantic que você definiu. @@ -97,71 +33,7 @@ Em alguns casos especiais (provavelmente não muito comuns), você queira **rest Você pode usar a configuração do modelo Pydantic para `forbid` (proibir) qualquer campo `extra`: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/query_param_models/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_param_models/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/query_param_models/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/query_param_models/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_param_models/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/query_param_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/query_param_models/tutorial002_an_py310.py hl[10] *} Caso um cliente tente enviar alguns dados **extras** nos **parâmetros de consulta**, eles receberão um retorno de **erro**. diff --git a/docs/pt/docs/tutorial/query-params-str-validations.md b/docs/pt/docs/tutorial/query-params-str-validations.md index 2fa0eeba0..8c4f2e655 100644 --- a/docs/pt/docs/tutorial/query-params-str-validations.md +++ b/docs/pt/docs/tutorial/query-params-str-validations.md @@ -4,9 +4,7 @@ O **FastAPI** permite que você declare informações adicionais e validações Vamos utilizar essa aplicação como exemplo: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial001.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial001.py hl[9] *} O parâmetro de consulta `q` é do tipo `Union[str, None]`, o que significa que é do tipo `str` mas que também pode ser `None`, e de fato, o valor padrão é `None`, então o FastAPI saberá que não é obrigatório. @@ -26,17 +24,13 @@ Nós iremos forçar que mesmo o parâmetro `q` seja opcional, sempre que informa Para isso, primeiro importe `Query` de `fastapi`: -```Python hl_lines="3" -{!../../docs_src/query_params_str_validations/tutorial002.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[3] *} ## Use `Query` como o valor padrão Agora utilize-o como valor padrão do seu parâmetro, definindo o parâmetro `max_length` para 50: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial002.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[9] *} Note que substituímos o valor padrão de `None` para `Query(default=None)`, o primeiro parâmetro de `Query` serve para o mesmo propósito: definir o valor padrão do parâmetro. @@ -86,17 +80,13 @@ Isso irá validar os dados, mostrar um erro claro quando os dados forem inválid Você também pode incluir um parâmetro `min_length`: -```Python hl_lines="10" -{!../../docs_src/query_params_str_validations/tutorial003.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial003.py hl[10] *} ## Adicionando expressões regulares Você pode definir uma expressão regular que combine com um padrão esperado pelo parâmetro: -```Python hl_lines="11" -{!../../docs_src/query_params_str_validations/tutorial004.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial004.py hl[11] *} Essa expressão regular específica verifica se o valor recebido no parâmetro: @@ -114,9 +104,7 @@ Da mesma maneira que você utiliza `None` como o primeiro argumento para ser uti Vamos dizer que você queira que o parâmetro de consulta `q` tenha um `min_length` de `3`, e um valor padrão de `"fixedquery"`, então declararíamos assim: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial005.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial005.py hl[7] *} /// note | Observação @@ -146,9 +134,7 @@ q: Union[str, None] = Query(default=None, min_length=3) Então, quando você precisa declarar um parâmetro obrigatório utilizando o `Query`, você pode utilizar `...` como o primeiro argumento: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial006.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial006.py hl[7] *} /// info | Informação @@ -164,9 +150,7 @@ Quando você declara explicitamente um parâmetro com `Query` você pode declar Por exemplo, para declarar que o parâmetro `q` pode aparecer diversas vezes na URL, você escreveria: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial011.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial011.py hl[9] *} Então, com uma URL assim: @@ -201,9 +185,7 @@ A documentação interativa da API irá atualizar de acordo, permitindo múltipl E você também pode definir uma lista (`list`) de valores padrão caso nenhum seja informado: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial012.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial012.py hl[9] *} Se você for até: @@ -226,9 +208,7 @@ O valor padrão de `q` será: `["foo", "bar"]` e sua resposta será: Você também pode utilizar o tipo `list` diretamente em vez de `List[str]`: -```Python hl_lines="7" -{!../../docs_src/query_params_str_validations/tutorial013.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial013.py hl[7] *} /// note | Observação @@ -254,15 +234,11 @@ Algumas delas não exibem todas as informações extras que declaramos, ainda qu Você pode adicionar um `title`: -```Python hl_lines="10" -{!../../docs_src/query_params_str_validations/tutorial007.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial007.py hl[10] *} E uma `description`: -```Python hl_lines="13" -{!../../docs_src/query_params_str_validations/tutorial008.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial008.py hl[13] *} ## Apelidos (alias) de parâmetros @@ -282,9 +258,7 @@ Mas ainda você precisa que o nome seja exatamente `item-query`... Então você pode declarar um `alias`, e esse apelido (alias) que será utilizado para encontrar o valor do parâmetro: -```Python hl_lines="9" -{!../../docs_src/query_params_str_validations/tutorial009.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial009.py hl[9] *} ## Parâmetros descontinuados @@ -294,9 +268,7 @@ Você tem que deixá-lo ativo por um tempo, já que existem clientes o utilizand Então você passa o parâmetro `deprecated=True` para `Query`: -```Python hl_lines="18" -{!../../docs_src/query_params_str_validations/tutorial010.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial010.py hl[18] *} Na documentação aparecerá assim: diff --git a/docs/pt/docs/tutorial/query-params.md b/docs/pt/docs/tutorial/query-params.md index 89b951de6..8199de5af 100644 --- a/docs/pt/docs/tutorial/query-params.md +++ b/docs/pt/docs/tutorial/query-params.md @@ -2,9 +2,7 @@ Quando você declara outros parâmetros na função que não fazem parte dos parâmetros da rota, esses parâmetros são automaticamente interpretados como parâmetros de "consulta". -```Python hl_lines="9" -{!../../docs_src/query_params/tutorial001.py!} -``` +{* ../../docs_src/query_params/tutorial001.py hl[9] *} A consulta é o conjunto de pares chave-valor que vai depois de `?` na URL, separado pelo caractere `&`. @@ -63,21 +61,7 @@ Os valores dos parâmetros na sua função serão: Da mesma forma, você pode declarar parâmetros de consulta opcionais, definindo o valor padrão para `None`: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial002.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *} Nesse caso, o parâmetro da função `q` será opcional, e `None` será o padrão. @@ -91,21 +75,7 @@ Você também pode notar que o **FastAPI** é esperto o suficiente para perceber Você também pode declarar tipos `bool`, e eles serão convertidos: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial003.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *} Nesse caso, se você for para: @@ -147,21 +117,7 @@ E você não precisa declarar eles em nenhuma ordem específica. Eles serão detectados pelo nome: -//// tab | Python 3.10+ - -```Python hl_lines="6 8" -{!> ../../docs_src/query_params/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8 10" -{!> ../../docs_src/query_params/tutorial004.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *} ## Parâmetros de consulta obrigatórios @@ -171,9 +127,7 @@ Caso você não queira adicionar um valor específico mas queira apenas torná-l Porém, quando você quiser fazer com que o parâmetro de consulta seja obrigatório, você pode simplesmente não declarar nenhum valor como padrão. -```Python hl_lines="6-7" -{!../../docs_src/query_params/tutorial005.py!} -``` +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} Aqui o parâmetro de consulta `needy` é um valor obrigatório, do tipo `str`. @@ -217,21 +171,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy E claro, você pode definir alguns parâmetros como obrigatórios, alguns possuindo um valor padrão, e outros sendo totalmente opcionais: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params/tutorial006_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params/tutorial006.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *} Nesse caso, existem 3 parâmetros de consulta: diff --git a/docs/pt/docs/tutorial/request-form-models.md b/docs/pt/docs/tutorial/request-form-models.md index 7128a0ae2..ea0e63d38 100644 --- a/docs/pt/docs/tutorial/request-form-models.md +++ b/docs/pt/docs/tutorial/request-form-models.md @@ -24,35 +24,7 @@ Isto é suportado desde a versão `0.113.0` do FastAPI. 🤓 Você precisa apenas declarar um **modelo Pydantic** com os campos que deseja receber como **campos de formulários**, e então declarar o parâmetro como um `Form`: -//// tab | Python 3.9+ - -```Python hl_lines="9-11 15" -{!> ../../docs_src/request_form_models/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8-10 14" -{!> ../../docs_src/request_form_models/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="7-9 13" -{!> ../../docs_src/request_form_models/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *} O **FastAPI** irá **extrair** as informações para **cada campo** dos **dados do formulário** na requisição e dar para você o modelo Pydantic que você definiu. @@ -76,35 +48,7 @@ Isso é suportado deste a versão `0.114.0` do FastAPI. 🤓 Você pode utilizar a configuração de modelo do Pydantic para `proibir` qualquer campo `extra`: -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/request_form_models/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/request_form_models/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefira utilizar a versão `Annotated` se possível. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/request_form_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/request_form_models/tutorial002_an_py39.py hl[12] *} Caso um cliente tente enviar informações adicionais, ele receberá um retorno de **erro**. diff --git a/docs/pt/docs/tutorial/request-forms-and-files.md b/docs/pt/docs/tutorial/request-forms-and-files.md index 77c099eb3..b08d87013 100644 --- a/docs/pt/docs/tutorial/request-forms-and-files.md +++ b/docs/pt/docs/tutorial/request-forms-and-files.md @@ -12,17 +12,13 @@ Por exemplo: `pip install python-multipart`. ## Importe `File` e `Form` -```Python hl_lines="1" -{!../../docs_src/request_forms_and_files/tutorial001.py!} -``` +{* ../../docs_src/request_forms_and_files/tutorial001.py hl[1] *} ## Defina parâmetros de `File` e `Form` Crie parâmetros de arquivo e formulário da mesma forma que você faria para `Body` ou `Query`: -```Python hl_lines="8" -{!../../docs_src/request_forms_and_files/tutorial001.py!} -``` +{* ../../docs_src/request_forms_and_files/tutorial001.py hl[8] *} Os arquivos e campos de formulário serão carregados como dados de formulário e você receberá os arquivos e campos de formulário. diff --git a/docs/pt/docs/tutorial/request-forms.md b/docs/pt/docs/tutorial/request-forms.md index 367fca072..756ceb581 100644 --- a/docs/pt/docs/tutorial/request-forms.md +++ b/docs/pt/docs/tutorial/request-forms.md @@ -14,17 +14,13 @@ Ex: `pip install python-multipart`. Importe `Form` de `fastapi`: -```Python hl_lines="1" -{!../../docs_src/request_forms/tutorial001.py!} -``` +{* ../../docs_src/request_forms/tutorial001.py hl[1] *} ## Declare parâmetros de `Form` Crie parâmetros de formulário da mesma forma que você faria para `Body` ou `Query`: -```Python hl_lines="7" -{!../../docs_src/request_forms/tutorial001.py!} -``` +{* ../../docs_src/request_forms/tutorial001.py hl[7] *} Por exemplo, em uma das maneiras que a especificação OAuth2 pode ser usada (chamada "fluxo de senha"), é necessário enviar um `username` e uma `password` como campos do formulário. diff --git a/docs/pt/docs/tutorial/request_files.md b/docs/pt/docs/tutorial/request_files.md index 39bfe284a..15c1ad825 100644 --- a/docs/pt/docs/tutorial/request_files.md +++ b/docs/pt/docs/tutorial/request_files.md @@ -16,69 +16,13 @@ Isso se deve por que arquivos enviados são enviados como "dados de formulário" Importe `File` e `UploadFile` do `fastapi`: -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/request_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1" -{!> ../../docs_src/request_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/request_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[3] *} ## Defina os parâmetros de `File` Cria os parâmetros do arquivo da mesma forma que você faria para `Body` ou `Form`: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/request_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/request_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/request_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[9] *} /// info | Informação @@ -106,35 +50,7 @@ Mas existem vários casos em que você pode se beneficiar ao usar `UploadFile`. Defina um parâmetro de arquivo com o tipo `UploadFile` -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/request_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="13" -{!> ../../docs_src/request_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="12" -{!> ../../docs_src/request_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[14] *} Utilizando `UploadFile` tem várias vantagens sobre `bytes`: @@ -217,91 +133,13 @@ Isso não é uma limitação do **FastAPI**, é uma parte do protocolo HTTP. Você pode definir um arquivo como opcional utilizando as anotações de tipo padrão e definindo o valor padrão como `None`: -//// tab | Python 3.10+ - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10 18" -{!> ../../docs_src/request_files/tutorial001_02_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated`, se possível - -/// - -```Python hl_lines="7 15" -{!> ../../docs_src/request_files/tutorial001_02_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated`, se possível - -/// - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *} ## `UploadFile` com Metadados Adicionais Você também pode utilizar `File()` com `UploadFile`, por exemplo, para definir metadados adicionais: -//// tab | Python 3.9+ - -```Python hl_lines="9 15" -{!> ../../docs_src/request_files/tutorial001_03_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8 14" -{!> ../../docs_src/request_files/tutorial001_03_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível - -/// - -```Python hl_lines="7 13" -{!> ../../docs_src/request_files/tutorial001_03.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *} ## Envio de Múltiplos Arquivos @@ -311,49 +149,7 @@ Ele ficam associados ao mesmo "campo do formulário" enviado com "form data". Para usar isso, declare uma lista de `bytes` ou `UploadFile`: -//// tab | Python 3.9+ - -```Python hl_lines="10 15" -{!> ../../docs_src/request_files/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11 16" -{!> ../../docs_src/request_files/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível - -/// - -```Python hl_lines="8 13" -{!> ../../docs_src/request_files/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível - -/// - -```Python hl_lines="10 15" -{!> ../../docs_src/request_files/tutorial002.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *} Você irá receber, como delcarado uma lista (`list`) de `bytes` ou `UploadFile`s, @@ -369,49 +165,7 @@ O **FastAPI** fornece as mesmas `starlette.responses` como `fastapi.responses` a E da mesma forma que antes, você pode utilizar `File()` para definir parâmetros adicionais, até mesmo para `UploadFile`: -//// tab | Python 3.9+ - -```Python hl_lines="11 18-20" -{!> ../../docs_src/request_files/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12 19-21" -{!> ../../docs_src/request_files/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.9+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="9 16" -{!> ../../docs_src/request_files/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Utilize a versão com `Annotated` se possível. - -/// - -```Python hl_lines="11 18" -{!> ../../docs_src/request_files/tutorial003.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *} ## Recapitulando diff --git a/docs/pt/docs/tutorial/response-status-code.md b/docs/pt/docs/tutorial/response-status-code.md index 2c8924925..48957f67a 100644 --- a/docs/pt/docs/tutorial/response-status-code.md +++ b/docs/pt/docs/tutorial/response-status-code.md @@ -8,9 +8,7 @@ Da mesma forma que você pode especificar um modelo de resposta, você também p * `@app.delete()` * etc. -```Python hl_lines="6" -{!../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} /// note | Nota @@ -77,9 +75,7 @@ Para saber mais sobre cada código de status e qual código serve para quê, ver Vamos ver o exemplo anterior novamente: -```Python hl_lines="6" -{!../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} `201` é o código de status para "Criado". @@ -87,9 +83,7 @@ Mas você não precisa memorizar o que cada um desses códigos significa. Você pode usar as variáveis de conveniência de `fastapi.status`. -```Python hl_lines="1 6" -{!../../docs_src/response_status_code/tutorial002.py!} -``` +{* ../../docs_src/response_status_code/tutorial002.py hl[1,6] *} Eles são apenas uma conveniência, eles possuem o mesmo número, mas dessa forma você pode usar o autocomplete do editor para encontrá-los: diff --git a/docs/pt/docs/tutorial/schema-extra-example.md b/docs/pt/docs/tutorial/schema-extra-example.md index dd95d4c7d..5d3498d7d 100644 --- a/docs/pt/docs/tutorial/schema-extra-example.md +++ b/docs/pt/docs/tutorial/schema-extra-example.md @@ -8,9 +8,7 @@ Aqui estão várias formas de se fazer isso. Você pode declarar um `example` para um modelo Pydantic usando `Config` e `schema_extra`, conforme descrito em Documentação do Pydantic: Schema customization: -```Python hl_lines="15-23" -{!../../docs_src/schema_extra_example/tutorial001.py!} -``` +{* ../../docs_src/schema_extra_example/tutorial001.py hl[15:23] *} Essas informações extras serão adicionadas como se encontram no **JSON Schema** de resposta desse modelo e serão usadas na documentação da API. @@ -28,9 +26,7 @@ Ao usar `Field ()` com modelos Pydantic, você também pode declarar informaçõ Você pode usar isso para adicionar um `example` para cada campo: -```Python hl_lines="4 10-13" -{!../../docs_src/schema_extra_example/tutorial002.py!} -``` +{* ../../docs_src/schema_extra_example/tutorial002.py hl[4,10:13] *} /// warning | Atenção @@ -56,9 +52,7 @@ você também pode declarar um dado `example` ou um grupo de `examples` com info Aqui nós passamos um `example` dos dados esperados por `Body()`: -```Python hl_lines="21-26" -{!../../docs_src/schema_extra_example/tutorial003.py!} -``` +{* ../../docs_src/schema_extra_example/tutorial003.py hl[21:26] *} ### Exemplo na UI da documentação @@ -79,9 +73,7 @@ Cada `dict` de exemplo específico em `examples` pode conter: * `value`: O próprio exemplo mostrado, ex: um `dict`. * `externalValue`: alternativa ao `value`, uma URL apontando para o exemplo. Embora isso possa não ser suportado por tantas ferramentas quanto `value`. -```Python hl_lines="22-48" -{!../../docs_src/schema_extra_example/tutorial004.py!} -``` +{* ../../docs_src/schema_extra_example/tutorial004.py hl[22:48] *} ### Exemplos na UI da documentação diff --git a/docs/pt/docs/tutorial/security/first-steps.md b/docs/pt/docs/tutorial/security/first-steps.md index 02871c90a..f4dea8e14 100644 --- a/docs/pt/docs/tutorial/security/first-steps.md +++ b/docs/pt/docs/tutorial/security/first-steps.md @@ -19,9 +19,7 @@ Vamos primeiro usar o código e ver como funciona, e depois voltaremos para ente ## Crie um `main.py` Copie o exemplo em um arquivo `main.py`: -```Python -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py *} ## Execute-o @@ -135,9 +133,7 @@ Neste exemplo, nós vamos usar o **OAuth2** com o fluxo de **Senha**, usando um Quando nós criamos uma instância da classe `OAuth2PasswordBearer`, nós passamos pelo parâmetro `tokenUrl` Esse parâmetro contém a URL que o client (o frontend rodando no browser do usuário) vai usar para mandar o `username` e `senha` para obter um token. -```Python hl_lines="6" -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[6] *} /// tip | Dica @@ -179,9 +175,7 @@ Então, pode ser usado com `Depends`. Agora você pode passar aquele `oauth2_scheme` em uma dependência com `Depends`. -```Python hl_lines="10" -{!../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[10] *} Esse dependência vai fornecer uma `str` que é atribuído ao parâmetro `token da *função do path operation* diff --git a/docs/pt/docs/tutorial/security/simple-oauth2.md b/docs/pt/docs/tutorial/security/simple-oauth2.md index 4e55f8c25..1cf05785e 100644 --- a/docs/pt/docs/tutorial/security/simple-oauth2.md +++ b/docs/pt/docs/tutorial/security/simple-oauth2.md @@ -52,57 +52,7 @@ Agora vamos usar os utilitários fornecidos pelo **FastAPI** para lidar com isso Primeiro, importe `OAuth2PasswordRequestForm` e use-o como uma dependência com `Depends` na *operação de rota* para `/token`: -//// tab | Python 3.10+ - -```Python hl_lines="4 78" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4 78" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 79" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira usar a versão `Annotated`, se possível. - -/// - -```Python hl_lines="2 74" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira usar a versão `Annotated`, se possível. - -/// - -```Python hl_lines="4 76" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *} `OAuth2PasswordRequestForm` é uma dependência de classe que declara um corpo de formulário com: @@ -150,57 +100,7 @@ Se não existir tal usuário, retornaremos um erro dizendo "Incorrect username o Para o erro, usamos a exceção `HTTPException`: -//// tab | Python 3.10+ - -```Python hl_lines="3 79-81" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3 79-81" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3 80-82" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira usar a versão `Annotated`, se possível. - -/// - -```Python hl_lines="1 75-77" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira usar a versão `Annotated`, se possível. - -/// - -```Python hl_lines="3 77-79" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *} ### Confira a password (senha) @@ -226,57 +126,7 @@ Se o seu banco de dados for roubado, o ladrão não terá as senhas em texto sim Assim, o ladrão não poderá tentar usar essas mesmas senhas em outro sistema (como muitos usuários usam a mesma senha em todos os lugares, isso seria perigoso). -//// tab | Python 3.10+ - -```Python hl_lines="82-85" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="82-85" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="83-86" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira usar a versão `Annotated`, se possível. - -/// - -```Python hl_lines="78-81" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira usar a versão `Annotated`, se possível. - -/// - -```Python hl_lines="80-83" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *} #### Sobre `**user_dict` @@ -318,57 +168,7 @@ Mas, por enquanto, vamos nos concentrar nos detalhes específicos de que precisa /// -//// tab | Python 3.10+ - -```Python hl_lines="87" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="87" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="88" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira usar a versão `Annotated`, se possível. - -/// - -```Python hl_lines="83" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira usar a versão `Annotated`, se possível. - -/// - -```Python hl_lines="85" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *} /// tip | Dica @@ -394,57 +194,7 @@ Ambas as dependências retornarão apenas um erro HTTP se o usuário não existi Portanto, em nosso endpoint, só obteremos um usuário se o usuário existir, tiver sido autenticado corretamente e estiver ativo: -//// tab | Python 3.10+ - -```Python hl_lines="58-66 69-74 94" -{!> ../../docs_src/security/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="58-66 69-74 94" -{!> ../../docs_src/security/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="59-67 70-75 95" -{!> ../../docs_src/security/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Dica - -Prefira usar a versão `Annotated`, se possível. - -/// - -```Python hl_lines="56-64 67-70 88" -{!> ../../docs_src/security/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Dica - -Prefira usar a versão `Annotated`, se possível. - -/// - -```Python hl_lines="58-66 69-72 90" -{!> ../../docs_src/security/tutorial003.py!} -``` - -//// +{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *} /// info | Informação diff --git a/docs/pt/docs/tutorial/static-files.md b/docs/pt/docs/tutorial/static-files.md index aba4b8221..0660078f4 100644 --- a/docs/pt/docs/tutorial/static-files.md +++ b/docs/pt/docs/tutorial/static-files.md @@ -7,9 +7,7 @@ Você pode servir arquivos estáticos automaticamente de um diretório usando `S * Importe `StaticFiles`. * "Monte" uma instância de `StaticFiles()` em um caminho específico. -```Python hl_lines="2 6" -{!../../docs_src/static_files/tutorial001.py!} -``` +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} /// note | Detalhes técnicos diff --git a/docs/pt/docs/tutorial/testing.md b/docs/pt/docs/tutorial/testing.md index 4f8eaa299..8eb2f29b7 100644 --- a/docs/pt/docs/tutorial/testing.md +++ b/docs/pt/docs/tutorial/testing.md @@ -30,9 +30,7 @@ Use o objeto `TestClient` da mesma forma que você faz com `httpx`. Escreva instruções `assert` simples com as expressões Python padrão que você precisa verificar (novamente, `pytest` padrão). -```Python hl_lines="2 12 15-18" -{!../../docs_src/app_testing/tutorial001.py!} -``` +{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *} /// tip | Dica @@ -78,9 +76,7 @@ Digamos que você tenha uma estrutura de arquivo conforme descrito em [Aplicativ No arquivo `main.py` você tem seu aplicativo **FastAPI**: -```Python -{!../../docs_src/app_testing/main.py!} -``` +{* ../../docs_src/app_testing/main.py *} ### Arquivo de teste @@ -96,9 +92,7 @@ Então você poderia ter um arquivo `test_main.py` com seus testes. Ele poderia Como esse arquivo está no mesmo pacote, você pode usar importações relativas para importar o objeto `app` do módulo `main` (`main.py`): -```Python hl_lines="3" -{!../../docs_src/app_testing/test_main.py!} -``` +{* ../../docs_src/app_testing/test_main.py hl[3] *} ...e ter o código para os testes como antes. @@ -182,9 +176,7 @@ Prefira usar a versão `Annotated` se possível. Você pode então atualizar `test_main.py` com os testes estendidos: -```Python -{!> ../../docs_src/app_testing/app_b/test_main.py!} -``` +{* ../../docs_src/app_testing/app_b/test_main.py *} Sempre que você precisar que o cliente passe informações na requisição e não souber como, você pode pesquisar (no Google) como fazer isso no `httpx`, ou até mesmo como fazer isso com `requests`, já que o design do HTTPX é baseado no design do Requests. diff --git a/docs/ru/docs/python-types.md b/docs/ru/docs/python-types.md index e5905304a..b1d4715fd 100644 --- a/docs/ru/docs/python-types.md +++ b/docs/ru/docs/python-types.md @@ -22,9 +22,8 @@ Python имеет поддержку необязательных аннотац Давайте начнем с простого примера: -```Python -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} + Вызов этой программы выводит: @@ -38,9 +37,8 @@ John Doe * Преобразует первую букву содержимого каждой переменной в верхний регистр с `title()`. * Соединяет их через пробел. -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### Отредактируем пример @@ -82,9 +80,8 @@ John Doe Это аннотации типов: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + Это не то же самое, что объявление значений по умолчанию, например: @@ -112,9 +109,8 @@ John Doe Проверьте эту функцию, она уже имеет аннотации типов: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + Поскольку редактор знает типы переменных, вы получаете не только дополнение, но и проверки ошибок: @@ -122,9 +118,8 @@ John Doe Теперь вы знаете, что вам нужно исправить, преобразовав `age` в строку с `str(age)`: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## Объявление типов @@ -143,9 +138,8 @@ John Doe * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### Generic-типы с параметрами типов @@ -161,9 +155,8 @@ John Doe Импортируйте `List` из `typing` (с заглавной `L`): -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[1] *} + Объявите переменную с тем же синтаксисом двоеточия (`:`). @@ -171,9 +164,8 @@ John Doe Поскольку список является типом, содержащим некоторые внутренние типы, вы помещаете их в квадратные скобки: -```Python hl_lines="4" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[4] *} + /// tip @@ -199,9 +191,8 @@ John Doe Вы бы сделали то же самое, чтобы объявить `tuple` и `set`: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial007.py!} -``` +{* ../../docs_src/python_types/tutorial007.py hl[1,4] *} + Это означает: @@ -216,9 +207,8 @@ John Doe Второй параметр типа предназначен для значений `dict`: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial008.py!} -``` +{* ../../docs_src/python_types/tutorial008.py hl[1,4] *} + Это означает: @@ -255,15 +245,13 @@ John Doe Допустим, у вас есть класс `Person` с полем `name`: -```Python hl_lines="1-3" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + Тогда вы можете объявить переменную типа `Person`: -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + И снова вы получаете полную поддержку редактора: @@ -283,9 +271,8 @@ John Doe Взято из официальной документации Pydantic: -```Python -{!../../docs_src/python_types/tutorial011.py!} -``` +{* ../../docs_src/python_types/tutorial011.py *} + /// info diff --git a/docs/ru/docs/tutorial/background-tasks.md b/docs/ru/docs/tutorial/background-tasks.md index a4f98f643..bf2e9dec3 100644 --- a/docs/ru/docs/tutorial/background-tasks.md +++ b/docs/ru/docs/tutorial/background-tasks.md @@ -15,9 +15,7 @@ Сначала импортируйте `BackgroundTasks`, потом добавьте в функцию параметр с типом `BackgroundTasks`: -```Python hl_lines="1 13" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *} **FastAPI** создаст объект класса `BackgroundTasks` для вас и запишет его в параметр. @@ -33,17 +31,13 @@ Так как операция записи не использует `async` и `await`, мы определим ее как обычную `def`: -```Python hl_lines="6-9" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *} ## Добавление фоновой задачи Внутри функции вызовите метод `.add_task()` у объекта *background tasks* и передайте ему функцию, которую хотите выполнить в фоне: -```Python hl_lines="14" -{!../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[14] *} `.add_task()` принимает следующие аргументы: @@ -57,21 +51,7 @@ **FastAPI** знает, что нужно сделать в каждом случае и как переиспользовать тот же объект `BackgroundTasks`, так чтобы все фоновые задачи собрались и запустились вместе в фоне: -//// tab | Python 3.10+ - -```Python hl_lines="11 13 20 23" -{!> ../../docs_src/background_tasks/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="13 15 22 25" -{!> ../../docs_src/background_tasks/tutorial002.py!} -``` - -//// +{* ../../docs_src/background_tasks/tutorial002_py310.py hl[11,13,20,23] *} В этом примере сообщения будут записаны в `log.txt` *после* того, как ответ сервера был отправлен. diff --git a/docs/ru/docs/tutorial/body-fields.md b/docs/ru/docs/tutorial/body-fields.md index 0c4cbb09c..5ed5f59fc 100644 --- a/docs/ru/docs/tutorial/body-fields.md +++ b/docs/ru/docs/tutorial/body-fields.md @@ -6,21 +6,7 @@ Сначала вы должны импортировать его: -//// tab | Python 3.10+ - -```Python hl_lines="2" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_fields/tutorial001_py310.py hl[2] *} /// warning | Внимание @@ -32,21 +18,7 @@ Вы можете использовать функцию `Field` с атрибутами модели: -//// tab | Python 3.10+ - -```Python hl_lines="9-12" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_fields/tutorial001_py310.py hl[9:12] *} Функция `Field` работает так же, как `Query`, `Path` и `Body`, у неё такие же параметры и т.д. diff --git a/docs/ru/docs/tutorial/body-multiple-params.md b/docs/ru/docs/tutorial/body-multiple-params.md index 594e1dbca..9300aa1bd 100644 --- a/docs/ru/docs/tutorial/body-multiple-params.md +++ b/docs/ru/docs/tutorial/body-multiple-params.md @@ -8,57 +8,7 @@ Вы также можете объявить параметры тела запроса как необязательные, установив значение по умолчанию, равное `None`: -//// tab | Python 3.10+ - -```Python hl_lines="18-20" -{!> ../../docs_src/body_multiple_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="18-20" -{!> ../../docs_src/body_multiple_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="19-21" -{!> ../../docs_src/body_multiple_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Заметка - -Рекомендуется использовать `Annotated` версию, если это возможно. - -/// - -```Python hl_lines="17-19" -{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Заметка - -Рекомендуется использовать версию с `Annotated`, если это возможно. - -/// - -```Python hl_lines="19-21" -{!> ../../docs_src/body_multiple_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *} /// note | Заметка @@ -81,21 +31,7 @@ Но вы также можете объявить множество параметров тела запроса, например `item` и `user`: -//// tab | Python 3.10+ - -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *} В этом случае **FastAPI** заметит, что в функции есть более одного параметра тела (два параметра, которые являются моделями Pydantic). @@ -136,57 +72,7 @@ Но вы можете указать **FastAPI** обрабатывать его, как ещё один ключ тела запроса, используя `Body`: -//// tab | Python 3.10+ - -```Python hl_lines="23" -{!> ../../docs_src/body_multiple_params/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23" -{!> ../../docs_src/body_multiple_params/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/body_multiple_params/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Заметка - -Рекомендуется использовать `Annotated` версию, если это возможно. - -/// - -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Заметка - -Рекомендуется использовать `Annotated` версию, если это возможно. - -/// - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial003.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *} В этом случае, **FastAPI** будет ожидать тело запроса в формате: @@ -226,57 +112,7 @@ q: str | None = None Например: -//// tab | Python 3.10+ - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="28" -{!> ../../docs_src/body_multiple_params/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Заметка - -Рекомендуется использовать `Annotated` версию, если это возможно. - -/// - -```Python hl_lines="25" -{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Заметка - -Рекомендуется использовать `Annotated` версию, если это возможно. - -/// - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[27] *} /// info | Информация @@ -298,57 +134,7 @@ item: Item = Body(embed=True) так же, как в этом примере: -//// tab | Python 3.10+ - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/body_multiple_params/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Заметка - -Рекомендуется использовать `Annotated` версию, если это возможно. - -/// - -```Python hl_lines="15" -{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Заметка - -Рекомендуется использовать `Annotated` версию, если это возможно. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *} В этом случае **FastAPI** будет ожидать тело запроса в формате: diff --git a/docs/ru/docs/tutorial/body-nested-models.md b/docs/ru/docs/tutorial/body-nested-models.md index 9abd4f432..430092892 100644 --- a/docs/ru/docs/tutorial/body-nested-models.md +++ b/docs/ru/docs/tutorial/body-nested-models.md @@ -6,21 +6,7 @@ Вы можете определять атрибут как подтип. Например, тип `list` в Python: -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *} Это приведёт к тому, что обьект `tags` преобразуется в список, несмотря на то что тип его элементов не объявлен. @@ -34,9 +20,7 @@ Но в версиях Python до 3.9 (начиная с 3.6) сначала вам необходимо импортировать `List` из стандартного модуля `typing` в Python: -```Python hl_lines="1" -{!> ../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *} ### Объявление `list` с указанием типов для вложенных элементов @@ -65,29 +49,7 @@ my_list: List[str] Таким образом, в нашем примере мы можем явно указать тип данных для поля `tags` как "список строк": -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *} ## Типы множеств @@ -97,29 +59,7 @@ my_list: List[str] Тогда мы можем обьявить поле `tags` как множество строк: -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 14" -{!> ../../docs_src/body_nested_models/tutorial003.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *} С помощью этого, даже если вы получите запрос с повторяющимися данными, они будут преобразованы в множество уникальных элементов. @@ -141,57 +81,13 @@ my_list: List[str] Например, мы можем определить модель `Image`: -//// tab | Python 3.10+ - -```Python hl_lines="7-9" -{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9-11" -{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-11" -{!> ../../docs_src/body_nested_models/tutorial004.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *} ### Использование вложенной модели в качестве типа Также мы можем использовать эту модель как тип атрибута: -//// tab | Python 3.10+ - -```Python hl_lines="18" -{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial004.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *} Это означает, что **FastAPI** будет ожидать тело запроса, аналогичное этому: @@ -224,29 +120,7 @@ my_list: List[str] Например, так как в модели `Image` у нас есть поле `url`, то мы можем объявить его как тип `HttpUrl` из модуля Pydantic вместо типа `str`: -//// tab | Python 3.10+ - -```Python hl_lines="2 8" -{!> ../../docs_src/body_nested_models/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4 10" -{!> ../../docs_src/body_nested_models/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 10" -{!> ../../docs_src/body_nested_models/tutorial005.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *} Строка будет проверена на соответствие допустимому URL-адресу и задокументирована в JSON схему / OpenAPI. @@ -254,29 +128,7 @@ my_list: List[str] Вы также можете использовать модели Pydantic в качестве типов вложенных в `list`, `set` и т.д: -//// tab | Python 3.10+ - -```Python hl_lines="18" -{!> ../../docs_src/body_nested_models/tutorial006_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial006_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial006.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *} Такая реализация будет ожидать (конвертировать, валидировать, документировать и т.д) JSON-содержимое в следующем формате: @@ -314,29 +166,7 @@ my_list: List[str] Вы можете определять модели с произвольным уровнем вложенности: -//// tab | Python 3.10+ - -```Python hl_lines="7 12 18 21 25" -{!> ../../docs_src/body_nested_models/tutorial007_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9 14 20 23 27" -{!> ../../docs_src/body_nested_models/tutorial007_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 14 20 23 27" -{!> ../../docs_src/body_nested_models/tutorial007.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *} /// info | Информация @@ -360,21 +190,7 @@ images: list[Image] например так: -//// tab | Python 3.9+ - -```Python hl_lines="13" -{!> ../../docs_src/body_nested_models/tutorial008_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15" -{!> ../../docs_src/body_nested_models/tutorial008.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial008_py39.py hl[13] *} ## Универсальная поддержка редактора @@ -404,21 +220,7 @@ images: list[Image] В этом случае вы принимаете `dict`, пока у него есть ключи типа `int` со значениями типа `float`: -//// tab | Python 3.9+ - -```Python hl_lines="7" -{!> ../../docs_src/body_nested_models/tutorial009_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/body_nested_models/tutorial009.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial009_py39.py hl[7] *} /// tip | Совет diff --git a/docs/ru/docs/tutorial/body-updates.md b/docs/ru/docs/tutorial/body-updates.md index c80952f70..99f475a41 100644 --- a/docs/ru/docs/tutorial/body-updates.md +++ b/docs/ru/docs/tutorial/body-updates.md @@ -6,29 +6,7 @@ Вы можете использовать функцию `jsonable_encoder` для преобразования входных данных в JSON, так как нередки случаи, когда работать можно только с простыми типами данных (например, для хранения в NoSQL-базе данных). -//// tab | Python 3.10+ - -```Python hl_lines="28-33" -{!> ../../docs_src/body_updates/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="30-35" -{!> ../../docs_src/body_updates/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="30-35" -{!> ../../docs_src/body_updates/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *} `PUT` используется для получения данных, которые должны полностью заменить существующие данные. @@ -74,29 +52,7 @@ В результате будет сгенерирован словарь, содержащий только те данные, которые были заданы при создании модели `item`, без учета значений по умолчанию. Затем вы можете использовать это для создания словаря только с теми данными, которые были установлены (отправлены в запросе), опуская значения по умолчанию: -//// tab | Python 3.10+ - -```Python hl_lines="32" -{!> ../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="34" -{!> ../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="34" -{!> ../../docs_src/body_updates/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *} ### Использование параметра `update` в Pydantic @@ -104,29 +60,7 @@ Например, `stored_item_model.copy(update=update_data)`: -//// tab | Python 3.10+ - -```Python hl_lines="33" -{!> ../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="35" -{!> ../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="35" -{!> ../../docs_src/body_updates/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *} ### Кратко о частичном обновлении @@ -143,29 +77,7 @@ * Сохранить данные в своей БД. * Вернуть обновленную модель. -//// tab | Python 3.10+ - -```Python hl_lines="28-35" -{!> ../../docs_src/body_updates/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="30-37" -{!> ../../docs_src/body_updates/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="30-37" -{!> ../../docs_src/body_updates/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *} /// tip | Подсказка diff --git a/docs/ru/docs/tutorial/body.md b/docs/ru/docs/tutorial/body.md index 62927f0d1..2c9110226 100644 --- a/docs/ru/docs/tutorial/body.md +++ b/docs/ru/docs/tutorial/body.md @@ -22,9 +22,7 @@ Первое, что вам необходимо сделать, это импортировать `BaseModel` из пакета `pydantic`: -```Python hl_lines="4" -{!../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[4] *} ## Создание вашей собственной модели @@ -32,9 +30,7 @@ Используйте аннотации типов Python для всех атрибутов: -```Python hl_lines="7-11" -{!../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[7:11] *} Также как и при описании параметров запроса, когда атрибут модели имеет значение по умолчанию, он является необязательным. Иначе он обязателен. Используйте `None`, чтобы сделать его необязательным без использования конкретных значений по умолчанию. @@ -62,9 +58,7 @@ Чтобы добавить параметр к вашему *обработчику*, объявите его также, как вы объявляли параметры пути или параметры запроса: -```Python hl_lines="18" -{!../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[18] *} ...и укажите созданную модель в качестве типа параметра, `Item`. @@ -131,9 +125,7 @@ Внутри функции вам доступны все атрибуты объекта модели напрямую: -```Python hl_lines="21" -{!../../docs_src/body/tutorial002.py!} -``` +{* ../../docs_src/body/tutorial002.py hl[21] *} ## Тело запроса + параметры пути @@ -141,9 +133,7 @@ **FastAPI** распознает, какие параметры функции соответствуют параметрам пути и должны быть **получены из пути**, а какие параметры функции, объявленные как модели Pydantic, должны быть **получены из тела запроса**. -```Python hl_lines="17-18" -{!../../docs_src/body/tutorial003.py!} -``` +{* ../../docs_src/body/tutorial003.py hl[17:18] *} ## Тело запроса + параметры пути + параметры запроса @@ -151,9 +141,7 @@ **FastAPI** распознает каждый из них и возьмет данные из правильного источника. -```Python hl_lines="18" -{!../../docs_src/body/tutorial004.py!} -``` +{* ../../docs_src/body/tutorial004.py hl[18] *} Параметры функции распознаются следующим образом: diff --git a/docs/ru/docs/tutorial/cookie-params.md b/docs/ru/docs/tutorial/cookie-params.md index 88533f7f8..d1ed943d7 100644 --- a/docs/ru/docs/tutorial/cookie-params.md +++ b/docs/ru/docs/tutorial/cookie-params.md @@ -6,21 +6,7 @@ Сначала импортируйте `Cookie`: -//// tab | Python 3.10+ - -```Python hl_lines="1" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_py310.py hl[1] *} ## Объявление параметров `Cookie` @@ -28,21 +14,7 @@ Первое значение - это значение по умолчанию, вы можете передать все дополнительные параметры проверки или аннотации: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_py310.py hl[7] *} /// note | Технические детали diff --git a/docs/ru/docs/tutorial/cors.md b/docs/ru/docs/tutorial/cors.md index 622cd5a98..e8bf04576 100644 --- a/docs/ru/docs/tutorial/cors.md +++ b/docs/ru/docs/tutorial/cors.md @@ -46,9 +46,7 @@ * Отдельных HTTP-методов (`POST`, `PUT`) или всех вместе, используя `"*"`. * Отдельных HTTP-заголовков или всех вместе, используя `"*"`. -```Python hl_lines="2 6-11 13-19" -{!../../docs_src/cors/tutorial001.py!} -``` +{* ../../docs_src/cors/tutorial001.py hl[2,6:11,13:19] *} `CORSMiddleware` использует для параметров "запрещающие" значения по умолчанию, поэтому вам нужно явным образом разрешить использование отдельных источников, методов или заголовков, чтобы браузеры могли использовать их в кросс-доменном контексте. diff --git a/docs/ru/docs/tutorial/debugging.md b/docs/ru/docs/tutorial/debugging.md index 0feeaa20c..05806f087 100644 --- a/docs/ru/docs/tutorial/debugging.md +++ b/docs/ru/docs/tutorial/debugging.md @@ -6,9 +6,7 @@ В вашем FastAPI приложении, импортируйте и вызовите `uvicorn` напрямую: -```Python hl_lines="1 15" -{!../../docs_src/debugging/tutorial001.py!} -``` +{* ../../docs_src/debugging/tutorial001.py hl[1,15] *} ### Описание `__name__ == "__main__"` diff --git a/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md index 486ff9ea9..8037872b9 100644 --- a/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,57 +6,7 @@ В предыдущем примере мы возвращали `словарь` из нашей зависимости: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[9] *} Но затем мы получаем `словарь` в параметре `commons` *функции операции пути*. И мы знаем, что редакторы не могут обеспечить достаточную поддержку для `словаря`, поскольку они не могут знать их ключи и типы значений. @@ -117,165 +67,15 @@ fluffy = Cat(name="Mr Fluffy") Теперь мы можем изменить зависимость `common_parameters`, указанную выше, на класс `CommonQueryParams`: -//// tab | Python 3.10+ - -```Python hl_lines="11-15" -{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11-15" -{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="12-16" -{!> ../../docs_src/dependencies/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="9-13" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="11-15" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[11:15] *} Обратите внимание на метод `__init__`, используемый для создания экземпляра класса: -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[12] *} ...имеет те же параметры, что и ранее используемая функция `common_parameters`: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="10" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="6" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8] *} Эти параметры и будут использоваться **FastAPI** для "решения" зависимости. @@ -291,57 +91,7 @@ fluffy = Cat(name="Mr Fluffy") Теперь вы можете объявить свою зависимость, используя этот класс. -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="20" -{!> ../../docs_src/dependencies/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[19] *} **FastAPI** вызывает класс `CommonQueryParams`. При этом создается "экземпляр" этого класса, который будет передан в качестве параметра `commons` в вашу функцию. @@ -435,57 +185,7 @@ commons = Depends(CommonQueryParams) ...как тут: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="20" -{!> ../../docs_src/dependencies/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial003.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial003_an_py310.py hl[19] *} Но объявление типа приветствуется, так как в этом случае ваш редактор будет знать, что будет передано в качестве параметра `commons`, и тогда он сможет помочь вам с автодополнением, проверкой типов и т.д: @@ -572,57 +272,7 @@ commons: CommonQueryParams = Depends() Аналогичный пример будет выглядеть следующим образом: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="20" -{!> ../../docs_src/dependencies/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial004.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial004_an_py310.py hl[19] *} ...и **FastAPI** будет знать, что делать. diff --git a/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 305ce46cb..f9b9dec25 100644 --- a/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -14,35 +14,7 @@ Это должен быть `list` состоящий из `Depends()`: -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 без Annotated - -/// подсказка - -Рекомендуется использовать версию с Annotated, если возможно. - -/// - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[19] *} Зависимости из dependencies выполнятся так же, как и обычные зависимости. Но их значения (если они были) не будут переданы в *функцию операции пути*. @@ -72,69 +44,13 @@ Они могут объявлять требования к запросу (например заголовки) или другие подзависимости: -//// tab | Python 3.9+ - -```Python hl_lines="8 13" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="7 12" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 без Annotated - -/// подсказка - -Рекомендуется использовать версию с Annotated, если возможно. - -/// - -```Python hl_lines="6 11" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[8,13] *} ### Вызов исключений Зависимости из dependencies могут вызывать исключения с помощью `raise`, как и обычные зависимости: -//// tab | Python 3.9+ - -```Python hl_lines="10 15" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 14" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 без Annotated - -/// подсказка - -Рекомендуется использовать версию с Annotated, если возможно. - -/// - -```Python hl_lines="8 13" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[10,15] *} ### Возвращаемые значения @@ -142,35 +58,7 @@ Таким образом, вы можете переиспользовать обычную зависимость (возвращающую значение), которую вы уже используете где-то в другом месте, и хотя значение не будет использоваться, зависимость будет выполнена: -//// tab | Python 3.9+ - -```Python hl_lines="11 16" -{!> ../../docs_src/dependencies/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10 15" -{!> ../../docs_src/dependencies/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8 без Annotated - -/// подсказка - -Рекомендуется использовать версию с Annotated, если возможно. - -/// - -```Python hl_lines="9 14" -{!> ../../docs_src/dependencies/tutorial006.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[11,16] *} ## Dependencies для группы *операций путей* diff --git a/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md index 83f8ec0d2..e64f6777c 100644 --- a/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md @@ -29,21 +29,15 @@ FastAPI поддерживает зависимости, которые выпо Перед созданием ответа будет выполнен только код до и включая `yield`. -```Python hl_lines="2-4" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[2:4] *} Полученное значение и есть то, что будет внедрено в функцию операции пути и другие зависимости: -```Python hl_lines="4" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[4] *} Код, следующий за оператором `yield`, выполняется после доставки ответа: -```Python hl_lines="5-6" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[5:6] *} /// tip | Подсказка @@ -63,9 +57,7 @@ FastAPI поддерживает зависимости, которые выпо Таким же образом можно использовать `finally`, чтобы убедиться, что обязательные шаги при выходе выполнены, независимо от того, было ли исключение или нет. -```Python hl_lines="3 5" -{!../../docs_src/dependencies/tutorial007.py!} -``` +{* ../../docs_src/dependencies/tutorial007.py hl[3,5] *} ## Подзависимости с `yield` @@ -75,35 +67,7 @@ FastAPI поддерживает зависимости, которые выпо Например, `dependency_c` может иметь зависимость от `dependency_b`, а `dependency_b` от `dependency_a`: -//// tab | Python 3.9+ - -```Python hl_lines="6 14 22" -{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="5 13 21" -{!> ../../docs_src/dependencies/tutorial008_an.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="4 12 20" -{!> ../../docs_src/dependencies/tutorial008.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[6,14,22] *} И все они могут использовать `yield`. @@ -111,35 +75,7 @@ FastAPI поддерживает зависимости, которые выпо И, в свою очередь, `dependency_b` нуждается в том, чтобы значение из `dependency_a` (здесь `dep_a`) было доступно для ее завершающего кода. -//// tab | Python 3.9+ - -```Python hl_lines="18-19 26-27" -{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="17-18 25-26" -{!> ../../docs_src/dependencies/tutorial008_an.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="16-17 24-25" -{!> ../../docs_src/dependencies/tutorial008.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[18:19,26:27] *} Точно так же можно иметь часть зависимостей с `yield`, часть с `return`, и какие-то из них могут зависеть друг от друга. @@ -303,9 +239,7 @@ with open("./somefile.txt") as f: Вы также можете использовать их внутри зависимостей **FastAPI** с `yield`, используя операторы `with` или `async with` внутри функции зависимости: -```Python hl_lines="1-9 13" -{!../../docs_src/dependencies/tutorial010.py!} -``` +{* ../../docs_src/dependencies/tutorial010.py hl[1:9,13] *} /// tip | Подсказка diff --git a/docs/ru/docs/tutorial/dependencies/global-dependencies.md b/docs/ru/docs/tutorial/dependencies/global-dependencies.md index a4dfeb8ac..5d2e70f6e 100644 --- a/docs/ru/docs/tutorial/dependencies/global-dependencies.md +++ b/docs/ru/docs/tutorial/dependencies/global-dependencies.md @@ -6,35 +6,7 @@ В этом случае они будут применяться ко всем *операциям пути* в приложении: -//// tab | Python 3.9+ - -```Python hl_lines="16" -{!> ../../docs_src/dependencies/tutorial012_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="16" -{!> ../../docs_src/dependencies/tutorial012_an.py!} -``` - -//// - -//// tab | Python 3.8 non-Annotated - -/// tip | Подсказка - -Рекомендуется использовать 'Annotated' версию, если это возможно. - -/// - -```Python hl_lines="15" -{!> ../../docs_src/dependencies/tutorial012.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial012_an_py39.py hl[16] *} Все способы [добавления зависимостей в *декораторах операций пути*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} по-прежнему применимы, но в данном случае зависимости применяются ко всем *операциям пути* приложения. diff --git a/docs/ru/docs/tutorial/dependencies/index.md b/docs/ru/docs/tutorial/dependencies/index.md index b6cf7c780..28790bd5a 100644 --- a/docs/ru/docs/tutorial/dependencies/index.md +++ b/docs/ru/docs/tutorial/dependencies/index.md @@ -29,57 +29,7 @@ Давайте для начала сфокусируемся на зависимостях. Это просто функция, которая может принимать все те же параметры, что и *функции обработки пути*: -//// tab | Python 3.10+ - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="8-11" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-12" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Подсказка - -Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. - -/// - -```Python hl_lines="6-7" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Подсказка - -Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. - -/// - -```Python hl_lines="8-11" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *} **И всё.** @@ -111,113 +61,13 @@ ### Import `Depends` -//// tab | Python 3.10+ - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Подсказка - -Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Подсказка - -Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *} ### Объявите зависимость в "зависимом" Точно так же, как вы использовали `Body`, `Query` и т.д. с вашей *функцией обработки пути* для параметров, используйте `Depends` с новым параметром: -//// tab | Python 3.10+ - -```Python hl_lines="13 18" -{!> ../../docs_src/dependencies/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="15 20" -{!> ../../docs_src/dependencies/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="16 21" -{!> ../../docs_src/dependencies/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Подсказка - -Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. - -/// - -```Python hl_lines="11 16" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Подсказка - -Настоятельно рекомендуем использовать `Annotated` версию насколько это возможно. - -/// - -```Python hl_lines="15 20" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *} `Depends` работает немного иначе. Вы передаёте в `Depends` одиночный параметр, который будет похож на функцию. @@ -270,29 +120,7 @@ commons: Annotated[dict, Depends(common_parameters)] Но потому что мы используем `Annotated`, мы можем хранить `Annotated` значение в переменной и использовать его в нескольких местах: -//// tab | Python 3.10+ - -```Python hl_lines="12 16 21" -{!> ../../docs_src/dependencies/tutorial001_02_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14 18 23" -{!> ../../docs_src/dependencies/tutorial001_02_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15 19 24" -{!> ../../docs_src/dependencies/tutorial001_02_an.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *} /// tip | Подсказка diff --git a/docs/ru/docs/tutorial/dependencies/sub-dependencies.md b/docs/ru/docs/tutorial/dependencies/sub-dependencies.md index 0e8cb20e7..5e8de0c4a 100644 --- a/docs/ru/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/ru/docs/tutorial/dependencies/sub-dependencies.md @@ -10,57 +10,7 @@ Можно создать первую зависимость следующим образом: -//// tab | Python 3.10+ - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="9-10" -{!> ../../docs_src/dependencies/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10 без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="6-7" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.6 без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="8-9" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *} Она объявляет необязательный параметр запроса `q` как строку, а затем возвращает его. @@ -70,57 +20,7 @@ Затем можно создать еще одну функцию зависимости, которая в то же время содержит внутри себя первую зависимость (таким образом, она тоже является "зависимой"): -//// tab | Python 3.10+ - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="14" -{!> ../../docs_src/dependencies/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10 без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.6 без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="13" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *} Остановимся на объявленных параметрах: @@ -133,57 +33,7 @@ Затем мы можем использовать зависимость вместе с: -//// tab | Python 3.10+ - -```Python hl_lines="23" -{!> ../../docs_src/dependencies/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23" -{!> ../../docs_src/dependencies/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="24" -{!> ../../docs_src/dependencies/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10 без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.6 без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="22" -{!> ../../docs_src/dependencies/tutorial005.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *} /// info | Дополнительная информация diff --git a/docs/ru/docs/tutorial/encoder.md b/docs/ru/docs/tutorial/encoder.md index 523644ac8..4ed5039b3 100644 --- a/docs/ru/docs/tutorial/encoder.md +++ b/docs/ru/docs/tutorial/encoder.md @@ -20,21 +20,7 @@ Она принимает объект, например, модель Pydantic, и возвращает его версию, совместимую с JSON: -//// tab | Python 3.10+ - -```Python hl_lines="4 21" -{!> ../../docs_src/encoder/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="5 22" -{!> ../../docs_src/encoder/tutorial001.py!} -``` - -//// +{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *} В данном примере она преобразует Pydantic модель в `dict`, а `datetime` - в `str`. diff --git a/docs/ru/docs/tutorial/extra-data-types.md b/docs/ru/docs/tutorial/extra-data-types.md index 82cb0ff7a..6d6d4aa9f 100644 --- a/docs/ru/docs/tutorial/extra-data-types.md +++ b/docs/ru/docs/tutorial/extra-data-types.md @@ -55,36 +55,8 @@ Вот пример *операции пути* с параметрами, который демонстрирует некоторые из вышеперечисленных типов. -//// tab | Python 3.8 и выше - -```Python hl_lines="1 3 12-16" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// - -//// tab | Python 3.10 и выше - -```Python hl_lines="1 2 11-15" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001.py hl[1,3,12:16] *} Обратите внимание, что параметры внутри функции имеют свой естественный тип данных, и вы, например, можете выполнять обычные манипуляции с датами, такие как: -//// tab | Python 3.8 и выше - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// - -//// tab | Python 3.10 и выше - -```Python hl_lines="17-18" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001.py hl[18:19] *} diff --git a/docs/ru/docs/tutorial/extra-models.md b/docs/ru/docs/tutorial/extra-models.md index 241f70779..5b51aa402 100644 --- a/docs/ru/docs/tutorial/extra-models.md +++ b/docs/ru/docs/tutorial/extra-models.md @@ -20,21 +20,7 @@ Ниже изложена основная идея того, как могут выглядеть эти модели с полями для паролей, а также описаны места, где они используются: -//// tab | Python 3.10+ - -```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" -{!> ../../docs_src/extra_models/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" -{!> ../../docs_src/extra_models/tutorial001.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *} ### Про `**user_in.dict()` @@ -168,21 +154,7 @@ UserInDB( В этом случае мы можем определить только различия между моделями (с `password` в чистом виде, с `hashed_password` и без пароля): -//// tab | Python 3.10+ - -```Python hl_lines="7 13-14 17-18 21-22" -{!> ../../docs_src/extra_models/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 15-16 19-20 23-24" -{!> ../../docs_src/extra_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *} ## `Union` или `anyOf` @@ -198,21 +170,7 @@ UserInDB( /// -//// tab | Python 3.10+ - -```Python hl_lines="1 14-15 18-20 33" -{!> ../../docs_src/extra_models/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 14-15 18-20 33" -{!> ../../docs_src/extra_models/tutorial003.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *} ### `Union` в Python 3.10 @@ -234,21 +192,7 @@ some_variable: PlaneItem | CarItem Для этого используйте `typing.List` из стандартной библиотеки Python (или просто `list` в Python 3.9 и выше): -//// tab | Python 3.9+ - -```Python hl_lines="18" -{!> ../../docs_src/extra_models/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 20" -{!> ../../docs_src/extra_models/tutorial004.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial004_py39.py hl[18] *} ## Ответ с произвольным `dict` @@ -258,21 +202,7 @@ some_variable: PlaneItem | CarItem В этом случае вы можете использовать `typing.Dict` (или просто `dict` в Python 3.9 и выше): -//// tab | Python 3.9+ - -```Python hl_lines="6" -{!> ../../docs_src/extra_models/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 8" -{!> ../../docs_src/extra_models/tutorial005.py!} -``` - -//// +{* ../../docs_src/extra_models/tutorial005_py39.py hl[6] *} ## Резюме diff --git a/docs/ru/docs/tutorial/first-steps.md b/docs/ru/docs/tutorial/first-steps.md index 309f26c4f..cb3d19a71 100644 --- a/docs/ru/docs/tutorial/first-steps.md +++ b/docs/ru/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ Самый простой FastAPI файл может выглядеть так: -```Python -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} Скопируйте в файл `main.py`. @@ -133,9 +131,7 @@ OpenAPI описывает схему API. Эта схема содержит о ### Шаг 1: импортируйте `FastAPI` -```Python hl_lines="1" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI` это класс в Python, который предоставляет всю функциональность для API. @@ -149,9 +145,7 @@ OpenAPI описывает схему API. Эта схема содержит о ### Шаг 2: создайте экземпляр `FastAPI` -```Python hl_lines="3" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[3] *} Переменная `app` является экземпляром класса `FastAPI`. @@ -171,9 +165,7 @@ $ uvicorn main:app --reload Если создать такое приложение: -```Python hl_lines="3" -{!../../docs_src/first_steps/tutorial002.py!} -``` +{* ../../docs_src/first_steps/tutorial002.py hl[3] *} И поместить его в `main.py`, тогда вызов `uvicorn` будет таким: @@ -250,9 +242,7 @@ https://example.com/items/foo #### Определите *декоратор операции пути (path operation decorator)* -```Python hl_lines="6" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[6] *} Декоратор `@app.get("/")` указывает **FastAPI**, что функция, прямо под ним, отвечает за обработку запросов, поступающих по адресу: @@ -306,9 +296,7 @@ https://example.com/items/foo * **операция**: `get`. * **функция**: функция ниже "декоратора" (ниже `@app.get("/")`). -```Python hl_lines="7" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[7] *} Это обычная Python функция. @@ -320,9 +308,7 @@ https://example.com/items/foo Вы также можете определить ее как обычную функцию вместо `async def`: -```Python hl_lines="7" -{!../../docs_src/first_steps/tutorial003.py!} -``` +{* ../../docs_src/first_steps/tutorial003.py hl[7] *} /// note | Технические детали @@ -332,9 +318,7 @@ https://example.com/items/foo ### Шаг 5: верните результат -```Python hl_lines="8" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[8] *} Вы можете вернуть `dict`, `list`, отдельные значения `str`, `int` и т.д. diff --git a/docs/ru/docs/tutorial/handling-errors.md b/docs/ru/docs/tutorial/handling-errors.md index a06644376..c596abe1f 100644 --- a/docs/ru/docs/tutorial/handling-errors.md +++ b/docs/ru/docs/tutorial/handling-errors.md @@ -25,9 +25,7 @@ ### Импортируйте `HTTPException` -```Python hl_lines="1" -{!../../docs_src/handling_errors/tutorial001.py!} -``` +{* ../../docs_src/handling_errors/tutorial001.py hl[1] *} ### Вызовите `HTTPException` в своем коде @@ -41,9 +39,7 @@ В данном примере, когда клиент запрашивает элемент по несуществующему ID, возникает исключение со статус-кодом `404`: -```Python hl_lines="11" -{!../../docs_src/handling_errors/tutorial001.py!} -``` +{* ../../docs_src/handling_errors/tutorial001.py hl[11] *} ### Возвращаемый ответ @@ -81,9 +77,7 @@ Но в случае, если это необходимо для продвинутого сценария, можно добавить пользовательские заголовки: -```Python hl_lines="14" -{!../../docs_src/handling_errors/tutorial002.py!} -``` +{* ../../docs_src/handling_errors/tutorial002.py hl[14] *} ## Установка пользовательских обработчиков исключений @@ -95,9 +89,7 @@ Можно добавить собственный обработчик исключений с помощью `@app.exception_handler()`: -```Python hl_lines="5-7 13-18 24" -{!../../docs_src/handling_errors/tutorial003.py!} -``` +{* ../../docs_src/handling_errors/tutorial003.py hl[5:7,13:18,24] *} Здесь, если запросить `/unicorns/yolo`, то *операция пути* вызовет `UnicornException`. @@ -135,9 +127,7 @@ Обработчик исключения получит объект `Request` и исключение. -```Python hl_lines="2 14-16" -{!../../docs_src/handling_errors/tutorial004.py!} -``` +{* ../../docs_src/handling_errors/tutorial004.py hl[2,14:16] *} Теперь, если перейти к `/items/foo`, то вместо стандартной JSON-ошибки с: @@ -188,9 +178,7 @@ path -> item_id Например, для этих ошибок можно вернуть обычный текстовый ответ вместо JSON: -```Python hl_lines="3-4 9-11 22" -{!../../docs_src/handling_errors/tutorial004.py!} -``` +{* ../../docs_src/handling_errors/tutorial004.py hl[3:4,9:11,22] *} /// note | Технические детали @@ -206,9 +194,7 @@ path -> item_id Вы можете использовать его при разработке приложения для регистрации тела и его отладки, возврата пользователю и т.д. -```Python hl_lines="14" -{!../../docs_src/handling_errors/tutorial005.py!} -``` +{* ../../docs_src/handling_errors/tutorial005.py hl[14] *} Теперь попробуйте отправить недействительный элемент, например: @@ -266,8 +252,6 @@ from starlette.exceptions import HTTPException as StarletteHTTPException Если вы хотите использовать исключение вместе с теми же обработчиками исключений по умолчанию из **FastAPI**, вы можете импортировать и повторно использовать обработчики исключений по умолчанию из `fastapi.exception_handlers`: -```Python hl_lines="2-5 15 21" -{!../../docs_src/handling_errors/tutorial006.py!} -``` +{* ../../docs_src/handling_errors/tutorial006.py hl[2:5,15,21] *} В этом примере вы просто `выводите в терминал` ошибку с очень выразительным сообщением, но идея вам понятна. Вы можете использовать исключение, а затем просто повторно использовать стандартные обработчики исключений. diff --git a/docs/ru/docs/tutorial/header-params.md b/docs/ru/docs/tutorial/header-params.md index 904709b04..e892cfc07 100644 --- a/docs/ru/docs/tutorial/header-params.md +++ b/docs/ru/docs/tutorial/header-params.md @@ -6,57 +6,7 @@ Сперва импортируйте `Header`: -//// tab | Python 3.10+ - -```Python hl_lines="3" -{!> ../../docs_src/header_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/header_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/header_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/header_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/header_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial001_an_py310.py hl[3] *} ## Объявление параметров `Header` @@ -64,57 +14,7 @@ Первое значение является значением по умолчанию, вы можете передать все дополнительные параметры валидации или аннотации: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/header_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/header_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial001_an_py310.py hl[9] *} /// note | Технические детали @@ -146,57 +46,7 @@ Если по какой-либо причине вам необходимо отключить автоматическое преобразование подчеркиваний в дефисы, установите для параметра `convert_underscores` в `Header` значение `False`: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/header_params/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11" -{!> ../../docs_src/header_params/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12" -{!> ../../docs_src/header_params/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/header_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/header_params/tutorial002.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial002_an_py310.py hl[10] *} /// warning | Внимание @@ -214,71 +64,7 @@ Например, чтобы объявить заголовок `X-Token`, который может появляться более одного раза, вы можете написать: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/header_params/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/header_params/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.9+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/header_params/tutorial003.py!} -``` - -//// +{* ../../docs_src/header_params/tutorial003_an_py310.py hl[9] *} Если вы взаимодействуете с этой *операцией пути*, отправляя два HTTP-заголовка, таких как: diff --git a/docs/ru/docs/tutorial/metadata.md b/docs/ru/docs/tutorial/metadata.md index ae739a043..f07073508 100644 --- a/docs/ru/docs/tutorial/metadata.md +++ b/docs/ru/docs/tutorial/metadata.md @@ -17,9 +17,7 @@ Вы можете задать их следующим образом: -```Python hl_lines="3-16 19-31" -{!../../docs_src/metadata/tutorial001.py!} -``` +{* ../../docs_src/metadata/tutorial001.py hl[3:16,19:31] *} /// tip | Подсказка @@ -51,9 +49,7 @@ Создайте метаданные для ваших тегов и передайте их в параметре `openapi_tags`: -```Python hl_lines="3-16 18" -{!../../docs_src/metadata/tutorial004.py!} -``` +{* ../../docs_src/metadata/tutorial004.py hl[3:16,18] *} Помните, что вы можете использовать Markdown внутри описания, к примеру "login" будет отображен жирным шрифтом (**login**) и "fancy" будет отображаться курсивом (_fancy_). @@ -66,9 +62,7 @@ ### Используйте собственные теги Используйте параметр `tags` с вашими *операциями пути* (и `APIRouter`ами), чтобы присвоить им различные теги: -```Python hl_lines="21 26" -{!../../docs_src/metadata/tutorial004.py!} -``` +{* ../../docs_src/metadata/tutorial004.py hl[21,26] *} /// info | Дополнительная информация @@ -96,9 +90,7 @@ К примеру, чтобы задать её отображение по адресу `/api/v1/openapi.json`: -```Python hl_lines="3" -{!../../docs_src/metadata/tutorial002.py!} -``` +{* ../../docs_src/metadata/tutorial002.py hl[3] *} Если вы хотите отключить схему OpenAPI полностью, вы можете задать `openapi_url=None`, это также отключит пользовательские интерфейсы документации, которые его использует. @@ -115,6 +107,4 @@ К примеру, чтобы задать отображение Swagger UI по адресу `/documentation` и отключить ReDoc: -```Python hl_lines="3" -{!../../docs_src/metadata/tutorial003.py!} -``` +{* ../../docs_src/metadata/tutorial003.py hl[3] *} diff --git a/docs/ru/docs/tutorial/path-operation-configuration.md b/docs/ru/docs/tutorial/path-operation-configuration.md index ac12b7084..af471ca69 100644 --- a/docs/ru/docs/tutorial/path-operation-configuration.md +++ b/docs/ru/docs/tutorial/path-operation-configuration.md @@ -16,29 +16,7 @@ Но если вы не помните, для чего нужен каждый числовой код, вы можете использовать сокращенные константы в параметре `status`: -//// tab | Python 3.10+ - -```Python hl_lines="1 15" -{!> ../../docs_src/path_operation_configuration/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3 17" -{!> ../../docs_src/path_operation_configuration/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3 17" -{!> ../../docs_src/path_operation_configuration/tutorial001.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial001_py310.py hl[1,15] *} Этот код состояния будет использован в ответе и будет добавлен в схему OpenAPI. @@ -54,29 +32,7 @@ Вы можете добавлять теги к вашим *операциям пути*, добавив параметр `tags` с `list` заполненным `str`-значениями (обычно в нём только одна строка): -//// tab | Python 3.10+ - -```Python hl_lines="15 20 25" -{!> ../../docs_src/path_operation_configuration/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="17 22 27" -{!> ../../docs_src/path_operation_configuration/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17 22 27" -{!> ../../docs_src/path_operation_configuration/tutorial002.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial002_py310.py hl[15,20,25] *} Они будут добавлены в схему OpenAPI и будут использованы в автоматической документации интерфейса: @@ -90,37 +46,13 @@ **FastAPI** поддерживает это так же, как и в случае с обычными строками: -```Python hl_lines="1 8-10 13 18" -{!../../docs_src/path_operation_configuration/tutorial002b.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial002b.py hl[1,8:10,13,18] *} ## Краткое и развёрнутое содержание Вы можете добавить параметры `summary` и `description`: -//// tab | Python 3.10+ - -```Python hl_lines="18-19" -{!> ../../docs_src/path_operation_configuration/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="20-21" -{!> ../../docs_src/path_operation_configuration/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20-21" -{!> ../../docs_src/path_operation_configuration/tutorial003.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial003_py310.py hl[18:19] *} ## Описание из строк документации @@ -128,29 +60,7 @@ Вы можете использовать Markdown в строке документации, и он будет интерпретирован и отображён корректно (с учетом отступа в строке документации). -//// tab | Python 3.10+ - -```Python hl_lines="17-25" -{!> ../../docs_src/path_operation_configuration/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19-27" -{!> ../../docs_src/path_operation_configuration/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="19-27" -{!> ../../docs_src/path_operation_configuration/tutorial004.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial004_py310.py hl[17:25] *} Он будет использован в интерактивной документации: @@ -160,29 +70,7 @@ Вы можете указать описание ответа с помощью параметра `response_description`: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/path_operation_configuration/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="21" -{!> ../../docs_src/path_operation_configuration/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="21" -{!> ../../docs_src/path_operation_configuration/tutorial005.py!} -``` - -//// +{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[19] *} /// info | Дополнительная информация @@ -204,9 +92,7 @@ OpenAPI указывает, что каждой *операции пути* не Если вам необходимо пометить *операцию пути* как устаревшую, при этом не удаляя её, передайте параметр `deprecated`: -```Python hl_lines="16" -{!../../docs_src/path_operation_configuration/tutorial006.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial006.py hl[16] *} Он будет четко помечен как устаревший в интерактивной документации: diff --git a/docs/ru/docs/tutorial/path-params-numeric-validations.md b/docs/ru/docs/tutorial/path-params-numeric-validations.md index ed19576a2..dca267f78 100644 --- a/docs/ru/docs/tutorial/path-params-numeric-validations.md +++ b/docs/ru/docs/tutorial/path-params-numeric-validations.md @@ -6,57 +6,7 @@ Сначала импортируйте `Path` из `fastapi`, а также импортируйте `Annotated`: -//// tab | Python 3.10+ - -```Python hl_lines="1 3" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="1 3" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3-4" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *} /// info | Информация @@ -74,57 +24,7 @@ Например, чтобы указать значение метаданных `title` для path-параметра `item_id`, вы можете написать: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *} /// note | Примечание @@ -174,21 +74,7 @@ Path-параметр всегда является обязательным, п Но имейте в виду, что если вы используете `Annotated`, вы не столкнётесь с этой проблемой, так как вы не используете `Query()` или `Path()` в качестве значения по умолчанию для параметра функции. -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/path_params_numeric_validations/tutorial002_an.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py hl[10] *} ## Задайте нужный вам порядок параметров, полезные приёмы @@ -213,29 +99,13 @@ Path-параметр всегда является обязательным, п Python не будет ничего делать с `*`, но он будет знать, что все следующие параметры являются именованными аргументами (парами ключ-значение), также известными как kwargs, даже если у них нет значений по умолчанию. -```Python hl_lines="7" -{!../../docs_src/path_params_numeric_validations/tutorial003.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *} ### Лучше с `Annotated` Имейте в виду, что если вы используете `Annotated`, то, поскольку вы не используете значений по умолчанию для параметров функции, то у вас не возникнет подобной проблемы и вам не придётся использовать `*`. -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/path_params_numeric_validations/tutorial003_an.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *} ## Валидация числовых данных: больше или равно @@ -243,35 +113,7 @@ Python не будет ничего делать с `*`, но он будет з В этом примере при указании `ge=1`, параметр `item_id` должен быть больше или равен `1` ("`g`reater than or `e`qual"). -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/path_params_numeric_validations/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/path_params_numeric_validations/tutorial004.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *} ## Валидация числовых данных: больше и меньше или равно @@ -280,35 +122,7 @@ Python не будет ничего делать с `*`, но он будет з * `gt`: больше (`g`reater `t`han) * `le`: меньше или равно (`l`ess than or `e`qual) -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/path_params_numeric_validations/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/path_params_numeric_validations/tutorial005.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *} ## Валидация числовых данных: числа с плавающей точкой, больше и меньше @@ -320,35 +134,7 @@ Python не будет ничего делать с `*`, но он будет з То же самое справедливо и для lt. -//// tab | Python 3.9+ - -```Python hl_lines="13" -{!> ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12" -{!> ../../docs_src/path_params_numeric_validations/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/path_params_numeric_validations/tutorial006.py!} -``` - -//// +{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *} ## Резюме diff --git a/docs/ru/docs/tutorial/path-params.md b/docs/ru/docs/tutorial/path-params.md index ba23ba5ea..5c2d82a65 100644 --- a/docs/ru/docs/tutorial/path-params.md +++ b/docs/ru/docs/tutorial/path-params.md @@ -2,9 +2,7 @@ Вы можете определить "параметры" или "переменные" пути, используя синтаксис форматированных строк Python: -```Python hl_lines="6-7" -{!../../docs_src/path_params/tutorial001.py!} -``` +{* ../../docs_src/path_params/tutorial001.py hl[6:7] *} Значение параметра пути `item_id` будет передано в функцию в качестве аргумента `item_id`. @@ -18,9 +16,7 @@ Вы можете объявить тип параметра пути в функции, используя стандартные аннотации типов Python. -```Python hl_lines="7" -{!../../docs_src/path_params/tutorial002.py!} -``` +{* ../../docs_src/path_params/tutorial002.py hl[7] *} Здесь, `item_id` объявлен типом `int`. @@ -122,17 +118,13 @@ Поскольку *операции пути* выполняются в порядке их объявления, необходимо, чтобы путь для `/users/me` был объявлен раньше, чем путь для `/users/{user_id}`: -```Python hl_lines="6 11" -{!../../docs_src/path_params/tutorial003.py!} -``` +{* ../../docs_src/path_params/tutorial003.py hl[6,11] *} Иначе путь для `/users/{user_id}` также будет соответствовать `/users/me`, "подразумевая", что он получает параметр `user_id` со значением `"me"`. Аналогично, вы не можете переопределить операцию с путем: -```Python hl_lines="6 11" -{!../../docs_src/path_params/tutorial003b.py!} -``` +{* ../../docs_src/path_params/tutorial003b.py hl[6,11] *} Первый будет выполняться всегда, так как путь совпадает первым. @@ -148,9 +140,7 @@ Затем создайте атрибуты класса с фиксированными допустимыми значениями: -```Python hl_lines="1 6-9" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *} /// info | Дополнительная информация @@ -168,9 +158,7 @@ Определите *параметр пути*, используя в аннотации типа класс перечисления (`ModelName`), созданный ранее: -```Python hl_lines="16" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[16] *} ### Проверьте документацию @@ -186,17 +174,13 @@ Вы можете сравнить это значение с *элементом перечисления* класса `ModelName`: -```Python hl_lines="17" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[17] *} #### Получение *значения перечисления* Можно получить фактическое значение (в данном случае - `str`) с помощью `model_name.value` или в общем случае `your_enum_member.value`: -```Python hl_lines="20" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[20] *} /// tip | Подсказка @@ -210,9 +194,7 @@ Они будут преобразованы в соответствующие значения (в данном случае - строки) перед их возвратом клиенту: -```Python hl_lines="18 21 23" -{!../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *} Вы отправите клиенту такой JSON-ответ: ```JSON @@ -250,9 +232,7 @@ OpenAPI не поддерживает способов объявления *п Можете использовать так: -```Python hl_lines="6" -{!../../docs_src/path_params/tutorial004.py!} -``` +{* ../../docs_src/path_params/tutorial004.py hl[6] *} /// tip | Подсказка diff --git a/docs/ru/docs/tutorial/query-params-str-validations.md b/docs/ru/docs/tutorial/query-params-str-validations.md index f76570ce8..32a98ff22 100644 --- a/docs/ru/docs/tutorial/query-params-str-validations.md +++ b/docs/ru/docs/tutorial/query-params-str-validations.md @@ -4,21 +4,7 @@ Давайте рассмотрим следующий пример: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial001.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial001_py310.py hl[7] *} Query-параметр `q` имеет тип `Union[str, None]` (или `str | None` в Python 3.10). Это означает, что входной параметр будет типа `str`, но может быть и `None`. Ещё параметр имеет значение по умолчанию `None`, из-за чего FastAPI определит параметр как необязательный. @@ -113,21 +99,7 @@ q: Annotated[Union[str, None]] = None Теперь, когда у нас есть `Annotated`, где мы можем добавить больше метаданных, добавим `Query` со значением параметра `max_length` равным 50: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial002_an.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial002_an_py310.py hl[9] *} Обратите внимание, что значение по умолчанию всё ещё `None`, так что параметр остаётся необязательным. @@ -151,21 +123,7 @@ q: Annotated[Union[str, None]] = None Вот как вы могли бы использовать `Query()` в качестве значения по умолчанию параметра вашей функции, установив для параметра `max_length` значение 50: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial002.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial002_py310.py hl[7] *} В таком случае (без использования `Annotated`), мы заменили значение по умолчанию с `None` на `Query()` в функции. Теперь нам нужно установить значение по умолчанию для query-параметра `Query(default=None)`, что необходимо для тех же целей, как когда ранее просто указывалось значение по умолчанию (по крайней мере, для FastAPI). @@ -265,113 +223,13 @@ q: str = Query(default="rick") Вы также можете добавить параметр `min_length`: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial003.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial003_an_py310.py hl[10] *} ## Регулярные выражения Вы можете определить регулярное выражение, которому должен соответствовать параметр: -//// tab | Python 3.10+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12" -{!> ../../docs_src/query_params_str_validations/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial004.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial004_an_py310.py hl[11] *} Данное регулярное выражение проверяет, что полученное значение параметра: @@ -389,35 +247,7 @@ q: str = Query(default="rick") Например, вы хотите для параметра запроса `q` указать, что он должен состоять минимум из 3 символов (`min_length=3`) и иметь значение по умолчанию `"fixedquery"`: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial005.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial005_an_py39.py hl[9] *} /// note | Технические детали @@ -459,77 +289,13 @@ q: Union[str, None] = Query(default=None, min_length=3) В таком случае, чтобы сделать query-параметр `Query` обязательным, вы можете просто не указывать значение по умолчанию: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial006.py!} -``` - -/// tip | Подсказка - -Обратите внимание, что даже когда `Query()` используется как значение по умолчанию для параметра функции, мы не передаём `default=None` в `Query()`. - -Лучше будет использовать версию с `Annotated`. 😉 - -/// - -//// +{* ../../docs_src/query_params_str_validations/tutorial006_an_py39.py hl[9] *} ### Обязательный параметр с Ellipsis (`...`) Альтернативный способ указать обязательность параметра запроса - это указать параметр `default` через многоточие `...`: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial006b_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial006b.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py hl[9] *} /// info | Дополнительная информация @@ -547,57 +313,7 @@ q: Union[str, None] = Query(default=None, min_length=3) Чтобы этого добиться, вам нужно определить `None` как валидный тип для параметра запроса, но также указать `default=...`: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial006c_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial006c_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial006c.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py hl[9] *} /// tip | Подсказка @@ -609,35 +325,7 @@ Pydantic, мощь которого используется в FastAPI для Если вас смущает `...`, вы можете использовать `Required` из Pydantic: -//// tab | Python 3.9+ - -```Python hl_lines="4 10" -{!> ../../docs_src/query_params_str_validations/tutorial006d_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="2 9" -{!> ../../docs_src/query_params_str_validations/tutorial006d_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="2 8" -{!> ../../docs_src/query_params_str_validations/tutorial006d.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial006d_an_py39.py hl[4,10] *} /// tip | Подсказка @@ -651,71 +339,7 @@ Pydantic, мощь которого используется в FastAPI для Например, query-параметр `q` может быть указан в URL несколько раз. И если вы ожидаете такой формат запроса, то можете указать это следующим образом: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial011_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial011_py310.py!} -``` - -//// - -//// tab | Python 3.9+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011_py39.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial011.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial011_an_py310.py hl[9] *} Затем, получив такой URL: @@ -750,49 +374,7 @@ http://localhost:8000/items/?q=foo&q=bar Вы также можете указать тип `list` со списком значений по умолчанию на случай, если вам их не предоставят: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial012_an.py!} -``` - -//// - -//// tab | Python 3.9+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial012_py39.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial012.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial012_an_py39.py hl[9] *} Если вы перейдёте по ссылке: @@ -815,35 +397,7 @@ http://localhost:8000/items/ Вы также можете использовать `list` напрямую вместо `List[str]` (или `list[str]` в Python 3.9+): -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial013_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial013.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial013_an_py39.py hl[9] *} /// note | Технические детали @@ -869,111 +423,11 @@ http://localhost:8000/items/ Вы можете указать название query-параметра, используя параметр `title`: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial007_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial007_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial007.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial007_an_py310.py hl[10] *} Добавить описание, используя параметр `description`: -//// tab | Python 3.10+ - -```Python hl_lines="14" -{!> ../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15" -{!> ../../docs_src/query_params_str_validations/tutorial008_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial008_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="13" -{!> ../../docs_src/query_params_str_validations/tutorial008.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial008_an_py310.py hl[14] *} ## Псевдонимы параметров @@ -993,57 +447,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems Тогда вы можете объявить `псевдоним`, и этот псевдоним будет использоваться для поиска значения параметра запроса: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial009_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/query_params_str_validations/tutorial009_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/query_params_str_validations/tutorial009.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial009_an_py310.py hl[9] *} ## Устаревшие параметры @@ -1053,57 +457,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems Тогда для `Query` укажите параметр `deprecated=True`: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="19" -{!> ../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/query_params_str_validations/tutorial010_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="16" -{!> ../../docs_src/query_params_str_validations/tutorial010_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="18" -{!> ../../docs_src/query_params_str_validations/tutorial010.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial010_an_py310.py hl[19] *} В документации это будет отображено следующим образом: @@ -1113,57 +467,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems Чтобы исключить query-параметр из генерируемой OpenAPI схемы (а также из системы автоматической генерации документации), укажите в `Query` параметр `include_in_schema=False`: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/query_params_str_validations/tutorial014_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/query_params_str_validations/tutorial014_py310.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать версию с `Annotated` если возможно. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/query_params_str_validations/tutorial014.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *} ## Резюме diff --git a/docs/ru/docs/tutorial/query-params.md b/docs/ru/docs/tutorial/query-params.md index 2c697224c..547d9831d 100644 --- a/docs/ru/docs/tutorial/query-params.md +++ b/docs/ru/docs/tutorial/query-params.md @@ -2,9 +2,7 @@ Когда вы объявляете параметры функции, которые не являются параметрами пути, они автоматически интерпретируются как "query"-параметры. -```Python hl_lines="9" -{!../../docs_src/query_params/tutorial001.py!} -``` +{* ../../docs_src/query_params/tutorial001.py hl[9] *} Query-параметры представляют из себя набор пар ключ-значение, которые идут после знака `?` в URL-адресе, разделенные символами `&`. @@ -63,21 +61,7 @@ http://127.0.0.1:8000/items/?skip=20 Аналогично, вы можете объявлять необязательные query-параметры, установив их значение по умолчанию, равное `None`: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial002.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *} В этом случае, параметр `q` будет не обязательным и будет иметь значение `None` по умолчанию. @@ -91,21 +75,7 @@ http://127.0.0.1:8000/items/?skip=20 Вы также можете объявлять параметры с типом `bool`, которые будут преобразованы соответственно: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial003.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *} В этом случае, если вы сделаете запрос: @@ -148,21 +118,7 @@ http://127.0.0.1:8000/items/foo?short=yes Они будут обнаружены по именам: -//// tab | Python 3.10+ - -```Python hl_lines="6 8" -{!> ../../docs_src/query_params/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8 10" -{!> ../../docs_src/query_params/tutorial004.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *} ## Обязательные query-параметры @@ -172,9 +128,7 @@ http://127.0.0.1:8000/items/foo?short=yes Но если вы хотите сделать query-параметр обязательным, вы можете просто не указывать значение по умолчанию: -```Python hl_lines="6-7" -{!../../docs_src/query_params/tutorial005.py!} -``` +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} Здесь параметр запроса `needy` является обязательным параметром с типом данных `str`. @@ -218,21 +172,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy Конечно, вы можете определить некоторые параметры как обязательные, некоторые - со значением по умполчанию, а некоторые - полностью необязательные: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params/tutorial006_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params/tutorial006.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *} В этом примере, у нас есть 3 параметра запроса: diff --git a/docs/ru/docs/tutorial/request-files.md b/docs/ru/docs/tutorial/request-files.md index 836d6efed..2cfa4e1dc 100644 --- a/docs/ru/docs/tutorial/request-files.md +++ b/docs/ru/docs/tutorial/request-files.md @@ -16,69 +16,13 @@ Импортируйте `File` и `UploadFile` из модуля `fastapi`: -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/request_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="1" -{!> ../../docs_src/request_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/request_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[3] *} ## Определите параметры `File` Создайте параметры `File` так же, как вы это делаете для `Body` или `Form`: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/request_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="8" -{!> ../../docs_src/request_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/request_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[9] *} /// info | Дополнительная информация @@ -106,35 +50,7 @@ Определите параметр файла с типом `UploadFile`: -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/request_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="13" -{!> ../../docs_src/request_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="12" -{!> ../../docs_src/request_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[14] *} Использование `UploadFile` имеет ряд преимуществ перед `bytes`: @@ -217,91 +133,13 @@ contents = myfile.file.read() Вы можете сделать загрузку файла необязательной, используя стандартные аннотации типов и установив значение по умолчанию `None`: -//// tab | Python 3.10+ - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="10 18" -{!> ../../docs_src/request_files/tutorial001_02_an.py!} -``` - -//// - -//// tab | Python 3.10+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="7 15" -{!> ../../docs_src/request_files/tutorial001_02_py310.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="9 17" -{!> ../../docs_src/request_files/tutorial001_02.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *} ## `UploadFile` с дополнительными метаданными Вы также можете использовать `File()` вместе с `UploadFile`, например, для установки дополнительных метаданных: -//// tab | Python 3.9+ - -```Python hl_lines="9 15" -{!> ../../docs_src/request_files/tutorial001_03_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="8 14" -{!> ../../docs_src/request_files/tutorial001_03_an.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="7 13" -{!> ../../docs_src/request_files/tutorial001_03.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *} ## Загрузка нескольких файлов @@ -311,49 +149,7 @@ contents = myfile.file.read() Для этого необходимо объявить список `bytes` или `UploadFile`: -//// tab | Python 3.9+ - -```Python hl_lines="10 15" -{!> ../../docs_src/request_files/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="11 16" -{!> ../../docs_src/request_files/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.9+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="8 13" -{!> ../../docs_src/request_files/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="10 15" -{!> ../../docs_src/request_files/tutorial002.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *} Вы получите, как и было объявлено, список `list` из `bytes` или `UploadFile`. @@ -369,49 +165,7 @@ contents = myfile.file.read() Так же, как и раньше, вы можете использовать `File()` для задания дополнительных параметров, даже для `UploadFile`: -//// tab | Python 3.9+ - -```Python hl_lines="11 18-20" -{!> ../../docs_src/request_files/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="12 19-21" -{!> ../../docs_src/request_files/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.9+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="9 16" -{!> ../../docs_src/request_files/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="11 18" -{!> ../../docs_src/request_files/tutorial003.py!} -``` - -//// +{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *} ## Резюме diff --git a/docs/ru/docs/tutorial/request-forms-and-files.md b/docs/ru/docs/tutorial/request-forms-and-files.md index fd98ec953..116c0cdb1 100644 --- a/docs/ru/docs/tutorial/request-forms-and-files.md +++ b/docs/ru/docs/tutorial/request-forms-and-files.md @@ -12,69 +12,13 @@ ## Импортируйте `File` и `Form` -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="1" -{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/request_forms_and_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[3] *} ## Определите параметры `File` и `Form` Создайте параметры файла и формы таким же образом, как для `Body` или `Query`: -//// tab | Python 3.9+ - -```Python hl_lines="10-12" -{!> ../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="9-11" -{!> ../../docs_src/request_forms_and_files/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.6+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="8" -{!> ../../docs_src/request_forms_and_files/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[10:12] *} Файлы и поля формы будут загружены в виде данных формы, и вы получите файлы и поля формы. diff --git a/docs/ru/docs/tutorial/request-forms.md b/docs/ru/docs/tutorial/request-forms.md index cd17613de..b33ea044b 100644 --- a/docs/ru/docs/tutorial/request-forms.md +++ b/docs/ru/docs/tutorial/request-forms.md @@ -14,69 +14,13 @@ Импортируйте `Form` из `fastapi`: -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1" -{!> ../../docs_src/request_forms/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать 'Annotated' версию, если это возможно. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/request_forms/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[3] *} ## Определение параметров `Form` Создайте параметры формы так же, как это делается для `Body` или `Query`: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/request_forms/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Рекомендуется использовать 'Annotated' версию, если это возможно. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/request_forms/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[9] *} Например, в одном из способов использования спецификации OAuth2 (называемом "потоком пароля") требуется отправить `username` и `password` в виде полей формы. diff --git a/docs/ru/docs/tutorial/response-model.md b/docs/ru/docs/tutorial/response-model.md index c55be38ef..b3c29281c 100644 --- a/docs/ru/docs/tutorial/response-model.md +++ b/docs/ru/docs/tutorial/response-model.md @@ -4,29 +4,7 @@ FastAPI позволяет использовать **аннотации типов** таким же способом, как и для ввода данных в **параметры** функции, вы можете использовать модели Pydantic, списки, словари, скалярные типы (такие, как int, bool и т.д.). -//// tab | Python 3.10+ - -```Python hl_lines="16 21" -{!> ../../docs_src/response_model/tutorial001_01_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="18 23" -{!> ../../docs_src/response_model/tutorial001_01_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18 23" -{!> ../../docs_src/response_model/tutorial001_01.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *} FastAPI будет использовать этот возвращаемый тип для: @@ -59,29 +37,7 @@ FastAPI будет использовать этот возвращаемый т * `@app.delete()` * и др. -//// tab | Python 3.10+ - -```Python hl_lines="17 22 24-27" -{!> ../../docs_src/response_model/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="17 22 24-27" -{!> ../../docs_src/response_model/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17 22 24-27" -{!> ../../docs_src/response_model/tutorial001.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial001_py310.py hl[17,22,24:27] *} /// note | Технические детали @@ -113,21 +69,7 @@ FastAPI будет использовать значение `response_model` д Здесь мы объявили модель `UserIn`, которая хранит пользовательский пароль в открытом виде: -//// tab | Python 3.10+ - -```Python hl_lines="7 9" -{!> ../../docs_src/response_model/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 11" -{!> ../../docs_src/response_model/tutorial002.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial002_py310.py hl[7,9] *} /// info | Информация @@ -139,21 +81,7 @@ FastAPI будет использовать значение `response_model` д Далее мы используем нашу модель в аннотациях типа как для аргумента функции, так и для выходного значения: -//// tab | Python 3.10+ - -```Python hl_lines="16" -{!> ../../docs_src/response_model/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/response_model/tutorial002.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial002_py310.py hl[16] *} Теперь всякий раз, когда клиент создает пользователя с паролем, API будет возвращать его пароль в ответе. @@ -171,57 +99,15 @@ FastAPI будет использовать значение `response_model` д Вместо этого мы можем создать входную модель, хранящую пароль в открытом виде и выходную модель без пароля: -//// tab | Python 3.10+ - -```Python hl_lines="9 11 16" -{!> ../../docs_src/response_model/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 11 16" -{!> ../../docs_src/response_model/tutorial003.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_py310.py hl[9,11,16] *} В таком случае, даже несмотря на то, что наша *функция операции пути* возвращает тот же самый объект пользователя с паролем, полученным на вход: -//// tab | Python 3.10+ - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial003.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_py310.py hl[24] *} ...мы указали в `response_model` модель `UserOut`, в которой отсутствует поле, содержащее пароль - и он будет исключен из ответа: -//// tab | Python 3.10+ - -```Python hl_lines="22" -{!> ../../docs_src/response_model/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="22" -{!> ../../docs_src/response_model/tutorial003.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_py310.py hl[22] *} Таким образом **FastAPI** позаботится о фильтрации ответа и исключит из него всё, что не указано в выходной модели (при помощи Pydantic). @@ -245,21 +131,7 @@ FastAPI будет использовать значение `response_model` д И в таких случаях мы можем использовать классы и наследование, чтобы пользоваться преимуществами **аннотаций типов** и получать более полную статическую проверку типов. Но при этом все так же получать **фильтрацию ответа** от FastAPI. -//// tab | Python 3.10+ - -```Python hl_lines="7-10 13-14 18" -{!> ../../docs_src/response_model/tutorial003_01_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-13 15-16 20" -{!> ../../docs_src/response_model/tutorial003_01.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_01_py310.py hl[7:10,13:14,18] *} Таким образом, мы получаем поддержку редактора кода и mypy в части типов, сохраняя при этом фильтрацию данных от FastAPI. @@ -301,9 +173,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма Самый частый сценарий использования - это [возвращать Response напрямую, как описано в расширенной документации](../advanced/response-directly.md){.internal-link target=_blank}. -```Python hl_lines="8 10-11" -{!> ../../docs_src/response_model/tutorial003_02.py!} -``` +{* ../../docs_src/response_model/tutorial003_02.py hl[8,10:11] *} Это поддерживается FastAPI по-умолчанию, т.к. аннотация проставлена в классе (или подклассе) `Response`. @@ -313,9 +183,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма Вы также можете указать подкласс `Response` в аннотации типа: -```Python hl_lines="8-9" -{!> ../../docs_src/response_model/tutorial003_03.py!} -``` +{* ../../docs_src/response_model/tutorial003_03.py hl[8:9] *} Это сработает, потому что `RedirectResponse` является подклассом `Response` и FastAPI автоматически обработает этот простейший случай. @@ -325,21 +193,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма То же самое произошло бы, если бы у вас было что-то вроде Union различных типов и один или несколько из них не являлись бы допустимыми типами для Pydantic. Например, такой вариант приведет к ошибке 💥: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/response_model/tutorial003_04_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/response_model/tutorial003_04.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *} ...такой код вызовет ошибку, потому что в аннотации указан неподдерживаемый Pydantic тип. А также этот тип не является классом или подклассом `Response`. @@ -351,21 +205,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма В таком случае, вы можете отключить генерацию модели ответа, указав `response_model=None`: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/response_model/tutorial003_05_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/response_model/tutorial003_05.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *} Тогда FastAPI не станет генерировать модель ответа и вы сможете сохранить такую аннотацию типа, которая вам требуется, никак не влияя на работу FastAPI. 🤓 @@ -373,29 +213,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма Модель ответа может иметь значения по умолчанию, например: -//// tab | Python 3.10+ - -```Python hl_lines="9 11-12" -{!> ../../docs_src/response_model/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11 13-14" -{!> ../../docs_src/response_model/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11 13-14" -{!> ../../docs_src/response_model/tutorial004.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *} * `description: Union[str, None] = None` (или `str | None = None` в Python 3.10), где `None` является значением по умолчанию. * `tax: float = 10.5`, где `10.5` является значением по умолчанию. @@ -409,29 +227,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма Установите для *декоратора операции пути* параметр `response_model_exclude_unset=True`: -//// tab | Python 3.10+ - -```Python hl_lines="22" -{!> ../../docs_src/response_model/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/response_model/tutorial004.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *} и тогда значения по умолчанию не будут включены в ответ. В нем будут только те поля, значения которых фактически были установлены. @@ -520,21 +316,7 @@ FastAPI достаточно умен (на самом деле, это засл /// -//// tab | Python 3.10+ - -```Python hl_lines="29 35" -{!> ../../docs_src/response_model/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="31 37" -{!> ../../docs_src/response_model/tutorial005.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *} /// tip | Подсказка @@ -548,21 +330,7 @@ FastAPI достаточно умен (на самом деле, это засл Если вы забыли про `set` и использовали структуру `list` или `tuple`, FastAPI автоматически преобразует этот объект в `set`, чтобы обеспечить корректную работу: -//// tab | Python 3.10+ - -```Python hl_lines="29 35" -{!> ../../docs_src/response_model/tutorial006_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="31 37" -{!> ../../docs_src/response_model/tutorial006.py!} -``` - -//// +{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *} ## Резюме diff --git a/docs/ru/docs/tutorial/response-status-code.md b/docs/ru/docs/tutorial/response-status-code.md index f08b15379..b46f656f3 100644 --- a/docs/ru/docs/tutorial/response-status-code.md +++ b/docs/ru/docs/tutorial/response-status-code.md @@ -8,9 +8,7 @@ * `@app.delete()` * и других. -```Python hl_lines="6" -{!../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} /// note | Примечание @@ -76,9 +74,7 @@ FastAPI знает об этом и создаст документацию Open Рассмотрим предыдущий пример еще раз: -```Python hl_lines="6" -{!../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} `201` – это код статуса "Создано". @@ -86,9 +82,7 @@ FastAPI знает об этом и создаст документацию Open Для удобства вы можете использовать переменные из `fastapi.status`. -```Python hl_lines="1 6" -{!../../docs_src/response_status_code/tutorial002.py!} -``` +{* ../../docs_src/response_status_code/tutorial002.py hl[1,6] *} Они содержат те же числовые значения, но позволяют использовать подсказки редактора для выбора кода статуса: diff --git a/docs/ru/docs/tutorial/schema-extra-example.md b/docs/ru/docs/tutorial/schema-extra-example.md index daa264afc..f17b24349 100644 --- a/docs/ru/docs/tutorial/schema-extra-example.md +++ b/docs/ru/docs/tutorial/schema-extra-example.md @@ -8,21 +8,7 @@ Вы можете объявить ключ `example` для модели Pydantic, используя класс `Config` и переменную `schema_extra`, как описано в Pydantic документации: Настройка схемы: -//// tab | Python 3.10+ - -```Python hl_lines="13-21" -{!> ../../docs_src/schema_extra_example/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15-23" -{!> ../../docs_src/schema_extra_example/tutorial001.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:21] *} Эта дополнительная информация будет включена в **JSON Schema** выходных данных для этой модели, и она будет использоваться в документации к API. @@ -40,21 +26,7 @@ Вы можете использовать это, чтобы добавить аргумент `example` для каждого поля: -//// tab | Python 3.10+ - -```Python hl_lines="2 8-11" -{!> ../../docs_src/schema_extra_example/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 10-13" -{!> ../../docs_src/schema_extra_example/tutorial002.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *} /// warning | Внимание @@ -80,57 +52,7 @@ Здесь мы передаём аргумент `example`, как пример данных ожидаемых в параметре `Body()`: -//// tab | Python 3.10+ - -```Python hl_lines="22-27" -{!> ../../docs_src/schema_extra_example/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="22-27" -{!> ../../docs_src/schema_extra_example/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="23-28" -{!> ../../docs_src/schema_extra_example/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Заметка - -Рекомендуется использовать версию с `Annotated`, если это возможно. - -/// - -```Python hl_lines="18-23" -{!> ../../docs_src/schema_extra_example/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Заметка - -Рекомендуется использовать версию с `Annotated`, если это возможно. - -/// - -```Python hl_lines="20-25" -{!> ../../docs_src/schema_extra_example/tutorial003.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:27] *} ### Аргумент "example" в UI документации @@ -151,57 +73,7 @@ * `value`: Это конкретный пример, который отображается, например, в виде типа `dict`. * `externalValue`: альтернатива параметру `value`, URL-адрес, указывающий на пример. Хотя это может не поддерживаться таким же количеством инструментов разработки и тестирования API, как параметр `value`. -//// tab | Python 3.10+ - -```Python hl_lines="23-49" -{!> ../../docs_src/schema_extra_example/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23-49" -{!> ../../docs_src/schema_extra_example/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24-50" -{!> ../../docs_src/schema_extra_example/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | Заметка - -Рекомендуется использовать версию с `Annotated`, если это возможно. - -/// - -```Python hl_lines="19-45" -{!> ../../docs_src/schema_extra_example/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | Заметка - -Рекомендуется использовать версию с `Annotated`, если это возможно. - -/// - -```Python hl_lines="21-47" -{!> ../../docs_src/schema_extra_example/tutorial004.py!} -``` - -//// +{* ../../docs_src/schema_extra_example/tutorial004_an_py310.py hl[23:49] *} ### Аргумент "examples" в UI документации diff --git a/docs/ru/docs/tutorial/security/first-steps.md b/docs/ru/docs/tutorial/security/first-steps.md index 484dfceff..e55f48b89 100644 --- a/docs/ru/docs/tutorial/security/first-steps.md +++ b/docs/ru/docs/tutorial/security/first-steps.md @@ -20,35 +20,7 @@ Скопируйте пример в файл `main.py`: -//// tab | Python 3.9+ - -```Python -{!> ../../docs_src/security/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python -{!> ../../docs_src/security/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python -{!> ../../docs_src/security/tutorial001.py!} -``` - -//// +{* ../../docs_src/security/tutorial001_an_py39.py *} ## Запуск @@ -152,35 +124,7 @@ OAuth2 был разработан для того, чтобы бэкэнд ил При создании экземпляра класса `OAuth2PasswordBearer` мы передаем в него параметр `tokenUrl`. Этот параметр содержит URL, который клиент (фронтенд, работающий в браузере пользователя) будет использовать для отправки `имени пользователя` и `пароля` с целью получения токена. -//// tab | Python 3.9+ - -```Python hl_lines="8" -{!> ../../docs_src/security/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="7" -{!> ../../docs_src/security/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="6" -{!> ../../docs_src/security/tutorial001.py!} -``` - -//// +{* ../../docs_src/security/tutorial001_an_py39.py hl[8] *} /// tip | Подсказка @@ -218,35 +162,7 @@ oauth2_scheme(some, parameters) Теперь вы можете передать ваш `oauth2_scheme` в зависимость с помощью `Depends`. -//// tab | Python 3.9+ - -```Python hl_lines="12" -{!> ../../docs_src/security/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11" -{!> ../../docs_src/security/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ без Annotated - -/// tip | Подсказка - -Предпочтительнее использовать версию с аннотацией, если это возможно. - -/// - -```Python hl_lines="10" -{!> ../../docs_src/security/tutorial001.py!} -``` - -//// +{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *} Эта зависимость будет предоставлять `строку`, которая присваивается параметру `token` в *функции операции пути*. diff --git a/docs/ru/docs/tutorial/static-files.md b/docs/ru/docs/tutorial/static-files.md index 0287fb017..c06eb858b 100644 --- a/docs/ru/docs/tutorial/static-files.md +++ b/docs/ru/docs/tutorial/static-files.md @@ -7,9 +7,7 @@ * Импортируйте `StaticFiles`. * "Примонтируйте" экземпляр `StaticFiles()` с указанием определенной директории. -```Python hl_lines="2 6" -{!../../docs_src/static_files/tutorial001.py!} -``` +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} /// note | Технические детали diff --git a/docs/ru/docs/tutorial/testing.md b/docs/ru/docs/tutorial/testing.md index 0485ef801..2c0f93d48 100644 --- a/docs/ru/docs/tutorial/testing.md +++ b/docs/ru/docs/tutorial/testing.md @@ -26,9 +26,7 @@ Напишите простое утверждение с `assert` дабы проверить истинность Python-выражения (это тоже стандарт `pytest`). -```Python hl_lines="2 12 15-18" -{!../../docs_src/app_testing/tutorial001.py!} -``` +{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *} /// tip | Подсказка @@ -74,9 +72,7 @@ Здесь файл `main.py` является "точкой входа" в Ваше приложение и содержит инициализацию Вашего приложения **FastAPI**: -```Python -{!../../docs_src/app_testing/main.py!} -``` +{* ../../docs_src/app_testing/main.py *} ### Файл тестов @@ -92,9 +88,8 @@ Так как оба файла находятся в одной директории, для импорта объекта приложения из файла `main` в файл `test_main` Вы можете использовать относительный импорт: -```Python hl_lines="3" -{!../../docs_src/app_testing/test_main.py!} -``` +{* ../../docs_src/app_testing/test_main.py hl[3] *} + ...и писать дальше тесты, как и раньше. @@ -178,9 +173,8 @@ Теперь обновим файл `test_main.py`, добавив в него тестов: -```Python -{!> ../../docs_src/app_testing/app_b/test_main.py!} -``` +{* ../../docs_src/app_testing/app_b/test_main.py *} + Если Вы не знаете, как передать информацию в запросе, можете воспользоваться поисковиком (погуглить) и задать вопрос: "Как передать информацию в запросе с помощью `httpx`", можно даже спросить: "Как передать информацию в запросе с помощью `requests`", поскольку дизайн HTTPX основан на дизайне Requests. diff --git a/docs/tr/docs/advanced/testing-websockets.md b/docs/tr/docs/advanced/testing-websockets.md index 12b6ab60f..ddacca449 100644 --- a/docs/tr/docs/advanced/testing-websockets.md +++ b/docs/tr/docs/advanced/testing-websockets.md @@ -4,9 +4,7 @@ WebSockets testi yapmak için `TestClient`'ı kullanabilirsiniz. Bu işlem için, `TestClient`'ı bir `with` ifadesinde kullanarak WebSocket'e bağlanabilirsiniz: -```Python hl_lines="27-31" -{!../../docs_src/app_testing/tutorial002.py!} -``` +{* ../../docs_src/app_testing/tutorial002.py hl[27:31] *} /// note | Not diff --git a/docs/tr/docs/advanced/wsgi.md b/docs/tr/docs/advanced/wsgi.md index bc8da16df..00815a4b2 100644 --- a/docs/tr/docs/advanced/wsgi.md +++ b/docs/tr/docs/advanced/wsgi.md @@ -12,9 +12,7 @@ Ardından WSGI (örneğin Flask) uygulamanızı middleware ile sarmalayın. Son olarak da bir yol altında bağlama işlemini gerçekleştirin. -```Python hl_lines="2-3 23" -{!../../docs_src/wsgi/tutorial001.py!} -``` +{* ../../docs_src/wsgi/tutorial001.py hl[2:3,23] *} ## Kontrol Edelim diff --git a/docs/tr/docs/python-types.md b/docs/tr/docs/python-types.md index 308dfa6fb..b44aa3b9d 100644 --- a/docs/tr/docs/python-types.md +++ b/docs/tr/docs/python-types.md @@ -22,9 +22,8 @@ Python uzmanıysanız ve tip belirteçleri ilgili her şeyi zaten biliyorsanız, Basit bir örnek ile başlayalım: -```Python -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} + Programın çıktısı: @@ -38,9 +37,8 @@ Fonksiyon sırayla şunları yapar: * `title()` ile değişkenlerin ilk karakterlerini büyütür. * Değişkenleri aralarında bir boşlukla beraber Birleştirir. -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### Düzenle @@ -82,9 +80,8 @@ Bu kadar. İşte bunlar "tip belirteçleri": -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + Bu, aşağıdaki gibi varsayılan değerleri bildirmekle aynı şey değildir: @@ -112,9 +109,8 @@ Aradığınızı bulana kadar seçenekleri kaydırabilirsiniz: Bu fonksiyon, zaten tür belirteçlerine sahip: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + Editör değişkenlerin tiplerini bildiğinden, yalnızca otomatik tamamlama değil, hata kontrolleri de sağlar: @@ -122,9 +118,8 @@ Editör değişkenlerin tiplerini bildiğinden, yalnızca otomatik tamamlama de Artık `age` değişkenini `str(age)` olarak kullanmanız gerektiğini biliyorsunuz: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## Tip bildirme @@ -143,9 +138,8 @@ Yalnızca `str` değil, tüm standart Python tiplerinin bildirebilirsiniz. * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### Tip parametreleri ile Generic tipler @@ -161,9 +155,8 @@ Bu tür tip belirteçlerini desteklemek için özel olarak mevcuttur. From `typing`, import `List` (büyük harf olan `L` ile): -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[1] *} + Değişkenin tipini yine iki nokta üstüste (`:`) ile belirleyin. @@ -171,9 +164,8 @@ tip olarak `List` kullanın. Liste, bazı dahili tipleri içeren bir tür olduğundan, bunları köşeli parantez içine alırsınız: -```Python hl_lines="4" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[4] *} + /// tip | Ipucu @@ -199,9 +191,8 @@ Ve yine, editör bunun bir `str` ​​olduğunu biliyor ve bunun için destek s `Tuple` ve `set`lerin tiplerini bildirmek için de aynısını yapıyoruz: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial007.py!} -``` +{* ../../docs_src/python_types/tutorial007.py hl[1,4] *} + Bu şu anlama geliyor: @@ -216,9 +207,8 @@ Bir `dict` tanımlamak için virgülle ayrılmış iki parametre verebilirsiniz. İkinci parametre ise `dict` değerinin `value` değeri içindir: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial008.py!} -``` +{* ../../docs_src/python_types/tutorial008.py hl[1,4] *} + Bu şu anlama gelir: @@ -255,15 +245,13 @@ Bir değişkenin tipini bir sınıf ile bildirebilirsiniz. Diyelim ki `name` değerine sahip `Person` sınıfınız var: -```Python hl_lines="1-3" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + Sonra bir değişkeni 'Person' tipinde tanımlayabilirsiniz: -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + Ve yine bütün editör desteğini alırsınız: @@ -283,9 +271,8 @@ Ve ortaya çıkan nesne üzerindeki bütün editör desteğini alırsınız. Resmi Pydantic dokümanlarından alınmıştır: -```Python -{!../../docs_src/python_types/tutorial011.py!} -``` +{* ../../docs_src/python_types/tutorial011.py *} + /// info diff --git a/docs/tr/docs/tutorial/cookie-params.md b/docs/tr/docs/tutorial/cookie-params.md index 56bcc0c86..f07508c2f 100644 --- a/docs/tr/docs/tutorial/cookie-params.md +++ b/docs/tr/docs/tutorial/cookie-params.md @@ -6,57 +6,7 @@ Öncelikle, `Cookie`'yi projenize dahil edin: -//// tab | Python 3.10+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | İpucu - -Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | İpucu - -Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[3] *} ## `Cookie` Parametrelerini Tanımlayın @@ -64,57 +14,7 @@ Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. İlk değer varsayılan değerdir; tüm ekstra doğrulama veya belirteç parametrelerini kullanabilirsiniz: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/cookie_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip | İpucu - -Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | İpucu - -Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9] *} /// note | Teknik Detaylar diff --git a/docs/tr/docs/tutorial/first-steps.md b/docs/tr/docs/tutorial/first-steps.md index da9057204..2d2949b50 100644 --- a/docs/tr/docs/tutorial/first-steps.md +++ b/docs/tr/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ En sade FastAPI dosyası şu şekilde görünür: -```Python -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} Yukarıdaki içeriği bir `main.py` dosyasına kopyalayalım. @@ -133,9 +131,7 @@ Ayrıca, API'ınızla iletişim kuracak önyüz, mobil veya IoT uygulamaları gi ### Adım 1: `FastAPI`yı Projemize Dahil Edelim -```Python hl_lines="1" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI`, API'niz için tüm işlevselliği sağlayan bir Python sınıfıdır. @@ -149,9 +145,7 @@ Ayrıca, API'ınızla iletişim kuracak önyüz, mobil veya IoT uygulamaları gi ### Adım 2: Bir `FastAPI` "Örneği" Oluşturalım -```Python hl_lines="3" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[3] *} Burada `app` değişkeni `FastAPI` sınıfının bir örneği olacaktır. @@ -171,9 +165,7 @@ $ uvicorn main:app --reload Uygulamanızı aşağıdaki gibi oluşturursanız: -```Python hl_lines="3" -{!../../docs_src/first_steps/tutorial002.py!} -``` +{* ../../docs_src/first_steps/tutorial002.py hl[3] *} Ve bunu `main.py` dosyasına yerleştirirseniz eğer `uvicorn` komutunu şu şekilde çalıştırabilirsiniz: @@ -250,9 +242,7 @@ Biz de onları "**operasyonlar**" olarak adlandıracağız. #### Bir *Yol Operasyonu Dekoratörü* Tanımlayalım -```Python hl_lines="6" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[6] *} `@app.get("/")` dekoratörü, **FastAPI**'a hemen altındaki fonksiyonun aşağıdaki durumlardan sorumlu olduğunu söyler: @@ -306,9 +296,7 @@ Aşağıdaki, bizim **yol operasyonu fonksiyonumuzdur**: * **operasyon**: `get` * **fonksiyon**: "dekoratör"ün (`@app.get("/")`'in) altındaki fonksiyondur. -```Python hl_lines="7" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[7] *} Bu bir Python fonksiyonudur. @@ -320,9 +308,7 @@ Bu durumda bu fonksiyon bir `async` fonksiyondur. Bu fonksiyonu `async def` yerine normal bir fonksiyon olarak da tanımlayabilirsiniz. -```Python hl_lines="7" -{!../../docs_src/first_steps/tutorial003.py!} -``` +{* ../../docs_src/first_steps/tutorial003.py hl[7] *} /// note | Not @@ -332,9 +318,7 @@ Eğer farkı bilmiyorsanız, [Async: *"Aceleniz mi var?"*](../async.md#in-a-hurr ### Adım 5: İçeriği Geri Döndürün -```Python hl_lines="8" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[8] *} Bir `dict`, `list` veya `str`, `int` gibi tekil değerler döndürebilirsiniz. diff --git a/docs/tr/docs/tutorial/path-params.md b/docs/tr/docs/tutorial/path-params.md index c883c2f9f..e1707a5d9 100644 --- a/docs/tr/docs/tutorial/path-params.md +++ b/docs/tr/docs/tutorial/path-params.md @@ -2,9 +2,7 @@ Yol "parametrelerini" veya "değişkenlerini" Python string biçimlemede kullanılan sözdizimi ile tanımlayabilirsiniz. -```Python hl_lines="6-7" -{!../../docs_src/path_params/tutorial001.py!} -``` +{* ../../docs_src/path_params/tutorial001.py hl[6:7] *} Yol parametresi olan `item_id`'nin değeri, fonksiyonunuza `item_id` argümanı olarak aktarılacaktır. @@ -18,9 +16,7 @@ Eğer bu örneği çalıştırıp ../../docs_src/query_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial002.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *} Bu durumda, `q` fonksiyon parametresi isteğe bağlı olacak ve varsayılan değer olarak `None` alacaktır. @@ -91,21 +75,7 @@ Ayrıca, dikkatinizi çekerim ki; **FastAPI**, `item_id` parametresinin bir yol Aşağıda görüldüğü gibi dönüştürülmek üzere `bool` tipleri de tanımlayabilirsiniz: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/query_params/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/query_params/tutorial003.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *} Bu durumda, eğer şu adrese giderseniz: @@ -148,21 +118,7 @@ Ve parametreleri, herhangi bir sıraya koymanıza da gerek yoktur. İsimlerine göre belirleneceklerdir: -//// tab | Python 3.10+ - -```Python hl_lines="6 8" -{!> ../../docs_src/query_params/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8 10" -{!> ../../docs_src/query_params/tutorial004.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *} ## Zorunlu Sorgu Parametreleri @@ -172,9 +128,7 @@ Parametre için belirli bir değer atamak istemeyip parametrenin sadece isteğe Fakat, bir sorgu parametresini zorunlu yapmak istiyorsanız varsayılan bir değer atamamanız yeterli olacaktır: -```Python hl_lines="6-7" -{!../../docs_src/query_params/tutorial005.py!} -``` +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} Burada `needy` parametresi `str` tipinden oluşan zorunlu bir sorgu parametresidir. @@ -220,21 +174,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy Ve elbette, bazı parametreleri zorunlu, bazılarını varsayılan değerli ve bazılarını tamamen opsiyonel olarak tanımlayabilirsiniz: -//// tab | Python 3.10+ - -```Python hl_lines="8" -{!> ../../docs_src/query_params/tutorial006_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/query_params/tutorial006.py!} -``` - -//// +{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *} Bu durumda, 3 tane sorgu parametresi var olacaktır: diff --git a/docs/tr/docs/tutorial/request-forms.md b/docs/tr/docs/tutorial/request-forms.md index 4ed8ac021..e4e04f5f9 100644 --- a/docs/tr/docs/tutorial/request-forms.md +++ b/docs/tr/docs/tutorial/request-forms.md @@ -14,69 +14,13 @@ Formları kullanmak için öncelikle ../../docs_src/request_forms/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1" -{!> ../../docs_src/request_forms/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/request_forms/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[3] *} ## `Form` Parametrelerini Tanımlayın Form parametrelerini `Body` veya `Query` için yaptığınız gibi oluşturun: -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/request_forms/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8" -{!> ../../docs_src/request_forms/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/request_forms/tutorial001.py!} -``` - -//// +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[9] *} Örneğin, OAuth2 spesifikasyonunun kullanılabileceği ("şifre akışı" olarak adlandırılan) yollardan birinde, form alanları olarak "username" ve "password" gönderilmesi gerekir. diff --git a/docs/tr/docs/tutorial/static-files.md b/docs/tr/docs/tutorial/static-files.md index da8bed86a..db30f13bc 100644 --- a/docs/tr/docs/tutorial/static-files.md +++ b/docs/tr/docs/tutorial/static-files.md @@ -7,9 +7,7 @@ * `StaticFiles` sınıfını projenize dahil edin. * Bir `StaticFiles()` örneğini belirli bir yola bağlayın. -```Python hl_lines="2 6" -{!../../docs_src/static_files/tutorial001.py!} -``` +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} /// note | Teknik Detaylar diff --git a/docs/uk/docs/python-types.md b/docs/uk/docs/python-types.md index 573b5372c..676bafb15 100644 --- a/docs/uk/docs/python-types.md +++ b/docs/uk/docs/python-types.md @@ -22,9 +22,8 @@ Python підтримує додаткові "підказки типу" ("type Давайте почнемо з простого прикладу: -```Python -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} + Виклик цієї програми виводить: @@ -38,9 +37,8 @@ John Doe * Конвертує кожну літеру кожного слова у верхній регістр за допомогою `title()`. * Конкатенує їх разом із пробілом по середині. -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### Редагуйте це @@ -82,9 +80,8 @@ John Doe Це "type hints": -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + Це не те саме, що оголошення значень за замовчуванням, як це було б з: @@ -112,9 +109,8 @@ John Doe Перевірте цю функцію, вона вже має анотацію типу: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + Оскільки редактор знає типи змінних, ви не тільки отримаєте автозаповнення, ви також отримаєте перевірку помилок: @@ -122,9 +118,8 @@ John Doe Тепер ви знаєте, щоб виправити це, вам потрібно перетворити `age` у строку з допомогою `str(age)`: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## Оголошення типів @@ -143,9 +138,8 @@ John Doe * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### Generic-типи з параметрами типів @@ -406,15 +400,13 @@ John Doe Скажімо, у вас є клас `Person` з імʼям: -```Python hl_lines="1-3" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + Потім ви можете оголосити змінну типу `Person`: -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + І знову ж таки, ви отримуєте всю підтримку редактора: diff --git a/docs/uk/docs/tutorial/body-fields.md b/docs/uk/docs/tutorial/body-fields.md index c286744a8..7ddd9d104 100644 --- a/docs/uk/docs/tutorial/body-fields.md +++ b/docs/uk/docs/tutorial/body-fields.md @@ -6,57 +6,7 @@ Спочатку вам потрібно імпортувати це: -//// tab | Python 3.10+ - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Варто користуватись `Annotated` версією, якщо це можливо. - -/// - -```Python hl_lines="2" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Варто користуватись `Annotated` версією, якщо це можливо. - -/// - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *} /// warning @@ -68,57 +18,7 @@ Ви можете використовувати `Field` з атрибутами моделі: -//// tab | Python 3.10+ - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12-15" -{!> ../../docs_src/body_fields/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Варто користуватись `Annotated` версією, якщо це можливо.. - -/// - -```Python hl_lines="9-12" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Варто користуватись `Annotated` версією, якщо це можливо.. - -/// - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *} `Field` працює так само, як `Query`, `Path` і `Body`, у нього такі самі параметри тощо. diff --git a/docs/uk/docs/tutorial/body.md b/docs/uk/docs/tutorial/body.md index 1e4188831..38fed7bb8 100644 --- a/docs/uk/docs/tutorial/body.md +++ b/docs/uk/docs/tutorial/body.md @@ -22,21 +22,7 @@ Спочатку вам потрібно імпортувати `BaseModel` з `pydantic`: -//// tab | Python 3.8 і вище - -```Python hl_lines="4" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// - -//// tab | Python 3.10 і вище - -```Python hl_lines="2" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial001.py hl[4] *} ## Створіть свою модель даних @@ -44,21 +30,7 @@ Використовуйте стандартні типи Python для всіх атрибутів: -//// tab | Python 3.8 і вище - -```Python hl_lines="7-11" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// - -//// tab | Python 3.10 і вище - -```Python hl_lines="5-9" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial001.py hl[7:11] *} Так само, як і при оголошенні параметрів запиту, коли атрибут моделі має значення за замовчуванням, він не є обов’язковим. В іншому випадку це потрібно. Використовуйте `None`, щоб зробити його необов'язковим. @@ -86,21 +58,7 @@ Щоб додати модель даних до вашої *операції шляху*, оголосіть її так само, як ви оголосили параметри шляху та запиту: -//// tab | Python 3.8 і вище - -```Python hl_lines="18" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// - -//// tab | Python 3.10 і вище - -```Python hl_lines="16" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial001.py hl[18] *} ...і вкажіть її тип як модель, яку ви створили, `Item`. @@ -167,21 +125,7 @@ Усередині функції ви можете отримати прямий доступ до всіх атрибутів об’єкта моделі: -//// tab | Python 3.8 і вище - -```Python hl_lines="21" -{!> ../../docs_src/body/tutorial002.py!} -``` - -//// - -//// tab | Python 3.10 і вище - -```Python hl_lines="19" -{!> ../../docs_src/body/tutorial002_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial002.py hl[21] *} ## Тіло запиту + параметри шляху @@ -189,21 +133,7 @@ **FastAPI** розпізнає, що параметри функції, які відповідають параметрам шляху, мають бути **взяті з шляху**, а параметри функції, які оголошуються як моделі Pydantic, **взяті з тіла запиту**. -//// tab | Python 3.8 і вище - -```Python hl_lines="17-18" -{!> ../../docs_src/body/tutorial003.py!} -``` - -//// - -//// tab | Python 3.10 і вище - -```Python hl_lines="15-16" -{!> ../../docs_src/body/tutorial003_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial003.py hl[17:18] *} ## Тіло запиту + шлях + параметри запиту @@ -211,21 +141,7 @@ **FastAPI** розпізнає кожен з них і візьме дані з потрібного місця. -//// tab | Python 3.8 і вище - -```Python hl_lines="18" -{!> ../../docs_src/body/tutorial004.py!} -``` - -//// - -//// tab | Python 3.10 і вище - -```Python hl_lines="16" -{!> ../../docs_src/body/tutorial004_py310.py!} -``` - -//// +{* ../../docs_src/body/tutorial004.py hl[18] *} Параметри функції будуть розпізнаватися наступним чином: diff --git a/docs/uk/docs/tutorial/cookie-params.md b/docs/uk/docs/tutorial/cookie-params.md index 229f81b63..b320645cb 100644 --- a/docs/uk/docs/tutorial/cookie-params.md +++ b/docs/uk/docs/tutorial/cookie-params.md @@ -6,57 +6,7 @@ Спочатку імпортуйте `Cookie`: -//// tab | Python 3.10+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Бажано використовувати `Annotated` версію, якщо це можливо. - -/// - -```Python hl_lines="1" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Бажано використовувати `Annotated` версію, якщо це можливо. - -/// - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[3] *} ## Визначення параметрів `Cookie` @@ -64,57 +14,7 @@ Перше значення це значення за замовчуванням, ви можете також передати всі додаткові параметри валідації чи анотації: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/cookie_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Бажано використовувати `Annotated` версію, якщо це можливо. - -/// - -```Python hl_lines="7" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Бажано використовувати `Annotated` версію, якщо це можливо. - -/// - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9] *} /// note | Технічні Деталі diff --git a/docs/uk/docs/tutorial/encoder.md b/docs/uk/docs/tutorial/encoder.md index 77b0baf4d..f202c7989 100644 --- a/docs/uk/docs/tutorial/encoder.md +++ b/docs/uk/docs/tutorial/encoder.md @@ -20,21 +20,7 @@ Вона приймає об'єкт, такий як Pydantic model, і повертає його версію, сумісну з JSON: -//// tab | Python 3.10+ - -```Python hl_lines="4 21" -{!> ../../docs_src/encoder/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="5 22" -{!> ../../docs_src/encoder/tutorial001.py!} -``` - -//// +{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *} У цьому прикладі вона конвертує Pydantic model у `dict`, а `datetime` у `str`. diff --git a/docs/uk/docs/tutorial/extra-data-types.md b/docs/uk/docs/tutorial/extra-data-types.md index 5e6c364e4..5da942b6e 100644 --- a/docs/uk/docs/tutorial/extra-data-types.md +++ b/docs/uk/docs/tutorial/extra-data-types.md @@ -55,108 +55,8 @@ Ось приклад *path operation* з параметрами, використовуючи деякі з вищезазначених типів. -//// tab | Python 3.10+ - -```Python hl_lines="1 3 12-16" -{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="1 3 12-16" -{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 3 13-17" -{!> ../../docs_src/extra_data_types/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Бажано використовувати `Annotated` версію, якщо це можливо. - -/// - -```Python hl_lines="1 2 11-15" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Бажано використовувати `Annotated` версію, якщо це можливо. - -/// - -```Python hl_lines="1 2 12-16" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *} Зверніть увагу, що параметри всередині функції мають свій звичайний тип даних, і ви можете, наприклад, виконувати звичайні маніпуляції з датами, такі як: -//// tab | Python 3.10+ - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="19-20" -{!> ../../docs_src/extra_data_types/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Бажано використовувати `Annotated` версію, якщо це можливо. - -/// - -```Python hl_lines="17-18" -{!> ../../docs_src/extra_data_types/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Бажано використовувати `Annotated` версію, якщо це можливо. - -/// - -```Python hl_lines="18-19" -{!> ../../docs_src/extra_data_types/tutorial001.py!} -``` - -//// +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *} diff --git a/docs/uk/docs/tutorial/first-steps.md b/docs/uk/docs/tutorial/first-steps.md index 63fec207d..e910c4ccc 100644 --- a/docs/uk/docs/tutorial/first-steps.md +++ b/docs/uk/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ Найпростіший файл FastAPI може виглядати так: -```Python -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} Скопіюйте це до файлу `main.py`. @@ -157,9 +155,7 @@ OpenAPI описує схему для вашого API. І ця схема вк ### Крок 1: імпортуємо `FastAPI` -```Python hl_lines="1" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI` це клас у Python, який надає всю функціональність для API. @@ -173,9 +169,7 @@ OpenAPI описує схему для вашого API. І ця схема вк ### Крок 2: створюємо екземпляр `FastAPI` -```Python hl_lines="3" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[3] *} Змінна `app` є екземпляром класу `FastAPI`. Це буде головна точка для створення і взаємодії з API. @@ -242,9 +236,7 @@ https://example.com/items/foo #### Визначте декоратор операції шляху (path operation decorator) -```Python hl_lines="6" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[6] *} Декоратор `@app.get("/")` вказує **FastAPI**, що функція нижче, відповідає за обробку запитів, які надходять до неї: * шлях `/` @@ -297,9 +289,7 @@ https://example.com/items/foo * **операція**: це `get`. * **функція**: це функція, яка знаходиться нижче "декоратора" (нижче `@app.get("/")`). -```Python hl_lines="7" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[7] *} Це звичайна функція Python. @@ -311,9 +301,7 @@ FastAPI викликатиме її щоразу, коли отримає зап Ви також можете визначити її як звичайну функцію замість `async def`: -```Python hl_lines="7" -{!../../docs_src/first_steps/tutorial003.py!} -``` +{* ../../docs_src/first_steps/tutorial003.py hl[7] *} /// note | Примітка @@ -323,9 +311,7 @@ FastAPI викликатиме її щоразу, коли отримає зап ### Крок 5: поверніть результат -```Python hl_lines="8" -{!../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[8] *} Ви можете повернути `dict`, `list`, а також окремі значення `str`, `int`, ітд. diff --git a/docs/vi/docs/python-types.md b/docs/vi/docs/python-types.md index 275b0eb39..403e89930 100644 --- a/docs/vi/docs/python-types.md +++ b/docs/vi/docs/python-types.md @@ -22,9 +22,8 @@ Nếu bạn là một chuyên gia về Python, và bạn đã biết mọi thứ Hãy bắt đầu với một ví dụ đơn giản: -```Python -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} + Kết quả khi gọi chương trình này: @@ -38,9 +37,8 @@ Hàm thực hiện như sau: * Chuyển đổi kí tự đầu tiên của mỗi biến sang kiểu chữ hoa với `title()`. * Nối chúng lại với nhau bằng một kí tự trắng ở giữa. -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### Sửa đổi @@ -82,9 +80,8 @@ Chính là nó. Những thứ đó là "type hints": -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + Đó không giống như khai báo những giá trị mặc định giống như: @@ -112,9 +109,8 @@ Với cái đó, bạn có thể cuộn, nhìn thấy các lựa chọn, cho đ Kiểm tra hàm này, nó đã có gợi ý kiểu dữ liệu: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + Bởi vì trình soạn thảo biết kiểu dữ liệu của các biến, bạn không chỉ có được completion, bạn cũng được kiểm tra lỗi: @@ -122,9 +118,8 @@ Bởi vì trình soạn thảo biết kiểu dữ liệu của các biến, bạ Bây giờ bạn biết rằng bạn phải sửa nó, chuyển `age` sang một xâu với `str(age)`: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## Khai báo các kiểu dữ liệu @@ -143,9 +138,8 @@ Bạn có thể sử dụng, ví dụ: * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### Các kiểu dữ liệu tổng quát với tham số kiểu dữ liệu @@ -374,9 +368,8 @@ Nó chỉ là về các từ và tên. Nhưng những từ đó có thể ảnh Cho một ví dụ, hãy để ý hàm này: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial009c.py!} -``` +{* ../../docs_src/python_types/tutorial009c.py hl[1,4] *} + Tham số `name` được định nghĩa là `Optional[str]`, nhưng nó **không phải là tùy chọn**, bạn không thể gọi hàm mà không có tham số: @@ -392,9 +385,8 @@ say_hi(name=None) # This works, None is valid 🎉 Tin tốt là, khi bạn sử dụng Python 3.10, bạn sẽ không phải lo lắng về điều đó, bạn sẽ có thể sử dụng `|` để định nghĩa hợp của các kiểu dữ liệu một cách đơn giản: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial009c_py310.py!} -``` +{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *} + Và sau đó, bạn sẽ không phải lo rằng những cái tên như `Optional` và `Union`. 😎 @@ -457,15 +449,13 @@ Bạn cũng có thể khai báo một lớp như là kiểu dữ liệu của m Hãy nói rằng bạn muốn có một lớp `Person` với một tên: -```Python hl_lines="1-3" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + Sau đó bạn có thể khai báo một biến có kiểu là `Person`: -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + Và lại một lần nữa, bạn có được tất cả sự hỗ trợ từ trình soạn thảo: diff --git a/docs/zh/docs/advanced/additional-status-codes.md b/docs/zh/docs/advanced/additional-status-codes.md index b8f9b0837..b048a2a17 100644 --- a/docs/zh/docs/advanced/additional-status-codes.md +++ b/docs/zh/docs/advanced/additional-status-codes.md @@ -14,9 +14,7 @@ 要实现它,导入 `JSONResponse`,然后在其中直接返回你的内容,并将 `status_code` 设置为为你要的值。 -```Python hl_lines="4 25" -{!../../docs_src/additional_status_codes/tutorial001.py!} -``` +{* ../../docs_src/additional_status_codes/tutorial001.py hl[4,25] *} /// warning | 警告 diff --git a/docs/zh/docs/advanced/advanced-dependencies.md b/docs/zh/docs/advanced/advanced-dependencies.md index bd37ecebb..8375bd48e 100644 --- a/docs/zh/docs/advanced/advanced-dependencies.md +++ b/docs/zh/docs/advanced/advanced-dependencies.md @@ -18,9 +18,7 @@ Python 可以把类实例变为**可调用项**。 为此,需要声明 `__call__` 方法: -```Python hl_lines="10" -{!../../docs_src/dependencies/tutorial011.py!} -``` +{* ../../docs_src/dependencies/tutorial011.py hl[10] *} 本例中,**FastAPI** 使用 `__call__` 检查附加参数及子依赖项,稍后,还要调用它向*路径操作函数*传递值。 @@ -28,9 +26,7 @@ Python 可以把类实例变为**可调用项**。 接下来,使用 `__init__` 声明用于**参数化**依赖项的实例参数: -```Python hl_lines="7" -{!../../docs_src/dependencies/tutorial011.py!} -``` +{* ../../docs_src/dependencies/tutorial011.py hl[7] *} 本例中,**FastAPI** 不使用 `__init__`,我们要直接在代码中使用。 @@ -38,9 +34,7 @@ Python 可以把类实例变为**可调用项**。 使用以下代码创建类实例: -```Python hl_lines="16" -{!../../docs_src/dependencies/tutorial011.py!} -``` +{* ../../docs_src/dependencies/tutorial011.py hl[16] *} 这样就可以**参数化**依赖项,它包含 `checker.fixed_content` 的属性 - `"bar"`。 @@ -56,9 +50,7 @@ checker(q="somequery") ……并用*路径操作函数*的参数 `fixed_content_included` 返回依赖项的值: -```Python hl_lines="20" -{!../../docs_src/dependencies/tutorial011.py!} -``` +{* ../../docs_src/dependencies/tutorial011.py hl[20] *} /// tip | 提示 diff --git a/docs/zh/docs/advanced/behind-a-proxy.md b/docs/zh/docs/advanced/behind-a-proxy.md index 5ed6baa82..f8f61c8a3 100644 --- a/docs/zh/docs/advanced/behind-a-proxy.md +++ b/docs/zh/docs/advanced/behind-a-proxy.md @@ -92,9 +92,7 @@ ASGI 规范定义的 `root_path` 就是为了这种用例。 我们在这里的信息里包含 `roo_path` 只是为了演示。 -```Python hl_lines="8" -{!../../docs_src/behind_a_proxy/tutorial001.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial001.py hl[8] *} 然后,用以下命令启动 Uvicorn: @@ -121,9 +119,7 @@ $ uvicorn main:app --root-path /api/v1 还有一种方案,如果不能提供 `--root-path` 或等效的命令行选项,则在创建 FastAPI 应用时要设置 `root_path` 参数。 -```Python hl_lines="3" -{!../../docs_src/behind_a_proxy/tutorial002.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial002.py hl[3] *} 传递 `root_path` 给 `FastAPI` 与传递 `--root-path` 命令行选项给 Uvicorn 或 Hypercorn 一样。 @@ -303,9 +299,7 @@ $ uvicorn main:app --root-path /api/v1 例如: -```Python hl_lines="4-7" -{!../../docs_src/behind_a_proxy/tutorial003.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial003.py hl[4:7] *} 这段代码生产如下 OpenAPI 概图: @@ -352,9 +346,7 @@ API 文档与所选的服务器进行交互。 如果不想让 **FastAPI** 包含使用 `root_path` 的自动服务器,则要使用参数 `root_path_in_servers=False`: -```Python hl_lines="9" -{!../../docs_src/behind_a_proxy/tutorial004.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial004.py hl[9] *} 这样,就不会在 OpenAPI 概图中包含服务器了。 diff --git a/docs/zh/docs/advanced/custom-response.md b/docs/zh/docs/advanced/custom-response.md index 85ca1d06d..22a9b4b51 100644 --- a/docs/zh/docs/advanced/custom-response.md +++ b/docs/zh/docs/advanced/custom-response.md @@ -24,9 +24,7 @@ 导入你想要使用的 `Response` 类(子类)然后在 *路径操作装饰器* 中声明它。 -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial001b.py!} -``` +{* ../../docs_src/custom_response/tutorial001b.py hl[2,7] *} /// info | 提示 @@ -51,9 +49,7 @@ * 导入 `HTMLResponse`。 * 将 `HTMLResponse` 作为你的 *路径操作* 的 `response_class` 参数传入。 -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial002.py!} -``` +{* ../../docs_src/custom_response/tutorial002.py hl[2,7] *} /// info | 提示 @@ -71,9 +67,7 @@ 和上面一样的例子,返回一个 `HTMLResponse` 看起来可能是这样: -```Python hl_lines="2 7 19" -{!../../docs_src/custom_response/tutorial003.py!} -``` +{* ../../docs_src/custom_response/tutorial003.py hl[2,7,19] *} /// warning | 警告 @@ -97,9 +91,7 @@ 比如像这样: -```Python hl_lines="7 23 21" -{!../../docs_src/custom_response/tutorial004.py!} -``` +{* ../../docs_src/custom_response/tutorial004.py hl[7,23,21] *} 在这个例子中,函数 `generate_html_response()` 已经生成并返回 `Response` 对象而不是在 `str` 中返回 HTML。 @@ -139,9 +131,7 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它还将包含一个基于 media_type 的 Content-Type 头,并为文本类型附加一个字符集。 -```Python hl_lines="1 18" -{!../../docs_src/response_directly/tutorial002.py!} -``` +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} ### `HTMLResponse` @@ -151,9 +141,7 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它 接受文本或字节并返回纯文本响应。 -```Python hl_lines="2 7 9" -{!../../docs_src/custom_response/tutorial005.py!} -``` +{* ../../docs_src/custom_response/tutorial005.py hl[2,7,9] *} ### `JSONResponse` @@ -176,9 +164,7 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它 /// -```Python hl_lines="2 7" -{!../../docs_src/custom_response/tutorial001.py!} -``` +{* ../../docs_src/custom_response/tutorial001.py hl[2,7] *} /// tip | 小贴士 @@ -190,17 +176,13 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它 返回 HTTP 重定向。默认情况下使用 307 状态代码(临时重定向)。 -```Python hl_lines="2 9" -{!../../docs_src/custom_response/tutorial006.py!} -``` +{* ../../docs_src/custom_response/tutorial006.py hl[2,9] *} ### `StreamingResponse` 采用异步生成器或普通生成器/迭代器,然后流式传输响应主体。 -```Python hl_lines="2 14" -{!../../docs_src/custom_response/tutorial007.py!} -``` +{* ../../docs_src/custom_response/tutorial007.py hl[2,14] *} #### 对类似文件的对象使用 `StreamingResponse` @@ -208,9 +190,7 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它 包括许多与云存储,视频处理等交互的库。 -```Python hl_lines="2 10-12 14" -{!../../docs_src/custom_response/tutorial008.py!} -``` +{* ../../docs_src/custom_response/tutorial008.py hl[2,10:12,14] *} /// tip | 小贴士 @@ -231,9 +211,7 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它 文件响应将包含适当的 `Content-Length`,`Last-Modified` 和 `ETag` 的响应头。 -```Python hl_lines="2 10" -{!../../docs_src/custom_response/tutorial009.py!} -``` +{* ../../docs_src/custom_response/tutorial009.py hl[2,10] *} ## 额外文档 diff --git a/docs/zh/docs/advanced/dataclasses.md b/docs/zh/docs/advanced/dataclasses.md index 7d977a0c7..c74ce65c3 100644 --- a/docs/zh/docs/advanced/dataclasses.md +++ b/docs/zh/docs/advanced/dataclasses.md @@ -4,9 +4,7 @@ FastAPI 基于 **Pydantic** 构建,前文已经介绍过如何使用 Pydantic 但 FastAPI 还可以使用数据类(`dataclasses`): -```Python hl_lines="1 7-12 19-20" -{!../../docs_src/dataclasses/tutorial001.py!} -``` +{* ../../docs_src/dataclasses/tutorial001.py hl[1,7:12,19:20] *} 这还是借助于 **Pydantic** 及其内置的 `dataclasses`。 @@ -34,9 +32,7 @@ FastAPI 基于 **Pydantic** 构建,前文已经介绍过如何使用 Pydantic 在 `response_model` 参数中使用 `dataclasses`: -```Python hl_lines="1 7-13 19" -{!../../docs_src/dataclasses/tutorial002.py!} -``` +{* ../../docs_src/dataclasses/tutorial002.py hl[1,7:13,19] *} 本例把数据类自动转换为 Pydantic 数据类。 diff --git a/docs/zh/docs/advanced/events.md b/docs/zh/docs/advanced/events.md index a34c03f3f..66f5af2e3 100644 --- a/docs/zh/docs/advanced/events.md +++ b/docs/zh/docs/advanced/events.md @@ -14,9 +14,7 @@ 使用 `startup` 事件声明 `app` 启动前运行的函数: -```Python hl_lines="8" -{!../../docs_src/events/tutorial001.py!} -``` +{* ../../docs_src/events/tutorial001.py hl[8] *} 本例中,`startup` 事件处理器函数为项目数据库(只是**字典**)提供了一些初始值。 @@ -28,9 +26,7 @@ 使用 `shutdown` 事件声明 `app` 关闭时运行的函数: -```Python hl_lines="6" -{!../../docs_src/events/tutorial002.py!} -``` +{* ../../docs_src/events/tutorial002.py hl[6] *} 此处,`shutdown` 事件处理器函数在 `log.txt` 中写入一行文本 `Application shutdown`。 diff --git a/docs/zh/docs/advanced/generate-clients.md b/docs/zh/docs/advanced/generate-clients.md index baf131361..bcb9ba2bf 100644 --- a/docs/zh/docs/advanced/generate-clients.md +++ b/docs/zh/docs/advanced/generate-clients.md @@ -16,21 +16,7 @@ 让我们从一个简单的 FastAPI 应用开始: -//// tab | Python 3.9+ - -```Python hl_lines="7-9 12-13 16-17 21" -{!> ../../docs_src/generate_clients/tutorial001_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-11 14-15 18 19 23" -{!> ../../docs_src/generate_clients/tutorial001.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial001_py39.py hl[7:9,12:13,16:17,21] *} 请注意,*路径操作* 定义了他们所用于请求数据和回应数据的模型,所使用的模型是`Item` 和 `ResponseMessage`。 @@ -135,21 +121,7 @@ frontend-app@1.0.0 generate-client /home/user/code/frontend-app 例如,您可以有一个用 `items` 的部分和另一个用于 `users` 的部分,它们可以用标签来分隔: -//// tab | Python 3.9+ - -```Python hl_lines="21 26 34" -{!> ../../docs_src/generate_clients/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="23 28 36" -{!> ../../docs_src/generate_clients/tutorial002.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial002_py39.py hl[21,26,34] *} ### 生成带有标签的 TypeScript 客户端 @@ -196,21 +168,7 @@ FastAPI为每个*路径操作*使用一个**唯一ID**,它用于**操作ID** 然后,你可以将这个自定义函数作为 `generate_unique_id_function` 参数传递给 **FastAPI**: -//// tab | Python 3.9+ - -```Python hl_lines="6-7 10" -{!> ../../docs_src/generate_clients/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="8-9 12" -{!> ../../docs_src/generate_clients/tutorial003.py!} -``` - -//// +{* ../../docs_src/generate_clients/tutorial003_py39.py hl[6:7,10] *} ### 使用自定义操作ID生成TypeScript客户端 @@ -232,9 +190,7 @@ FastAPI为每个*路径操作*使用一个**唯一ID**,它用于**操作ID** 我们可以将 OpenAPI JSON 下载到一个名为`openapi.json`的文件中,然后使用以下脚本**删除此前缀的标签**: -```Python -{!../../docs_src/generate_clients/tutorial004.py!} -``` +{* ../../docs_src/generate_clients/tutorial004.py *} 通过这样做,操作ID将从类似于 `items-get_items` 的名称重命名为 `get_items` ,这样客户端生成器就可以生成更简洁的方法名称。 diff --git a/docs/zh/docs/advanced/middleware.md b/docs/zh/docs/advanced/middleware.md index 78a7d559c..c7b15b929 100644 --- a/docs/zh/docs/advanced/middleware.md +++ b/docs/zh/docs/advanced/middleware.md @@ -57,17 +57,13 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 任何传向 `http` 或 `ws` 的请求都会被重定向至安全方案。 -```Python hl_lines="2 6" -{!../../docs_src/advanced_middleware/tutorial001.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial001.py hl[2,6] *} ## `TrustedHostMiddleware` 强制所有传入请求都必须正确设置 `Host` 请求头,以防 HTTP 主机头攻击。 -```Python hl_lines="2 6-8" -{!../../docs_src/advanced_middleware/tutorial002.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial002.py hl[2,6:8] *} 支持以下参数: @@ -81,9 +77,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 中间件会处理标准响应与流响应。 -```Python hl_lines="2 6" -{!../../docs_src/advanced_middleware/tutorial003.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial003.py hl[2,6] *} 支持以下参数: diff --git a/docs/zh/docs/advanced/openapi-callbacks.md b/docs/zh/docs/advanced/openapi-callbacks.md index 601cbdb5d..f021eb10a 100644 --- a/docs/zh/docs/advanced/openapi-callbacks.md +++ b/docs/zh/docs/advanced/openapi-callbacks.md @@ -31,9 +31,7 @@ API 的用户 (外部开发者)要在您的 API 内使用 POST 请求创建 这部分代码很常规,您对绝大多数代码应该都比较熟悉了: -```Python hl_lines="10-14 37-54" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[10:14,37:54] *} /// tip | 提示 @@ -92,9 +90,7 @@ requests.post(callback_url, json={"description": "Invoice paid", "paid": True}) 首先,新建包含一些用于回调的 `APIRouter`。 -```Python hl_lines="5 26" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[5,26] *} ### 创建回调*路径操作* @@ -105,9 +101,7 @@ requests.post(callback_url, json={"description": "Invoice paid", "paid": True}) * 声明要接收的请求体,例如,`body: InvoiceEvent` * 还要声明要返回的响应,例如,`response_model=InvoiceEventReceived` -```Python hl_lines="17-19 22-23 29-33" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[17:19,22:23,29:33] *} 回调*路径操作*与常规*路径操作*有两点主要区别: @@ -175,9 +169,7 @@ JSON 请求体包含如下内容: 现在使用 API *路径操作装饰器*的参数 `callbacks`,从回调路由传递属性 `.routes`(实际上只是路由/路径操作的**列表**): -```Python hl_lines="36" -{!../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[36] *} /// tip | 提示 diff --git a/docs/zh/docs/advanced/path-operation-advanced-configuration.md b/docs/zh/docs/advanced/path-operation-advanced-configuration.md index 0d77dd69e..12600eddb 100644 --- a/docs/zh/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/zh/docs/advanced/path-operation-advanced-configuration.md @@ -12,9 +12,7 @@ 务必确保每个操作路径的 `operation_id` 都是唯一的。 -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial001.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *} ### 使用 *路径操作函数* 的函数名作为 operationId @@ -22,9 +20,7 @@ 你应该在添加了所有 *路径操作* 之后执行此操作。 -```Python hl_lines="2 12 13 14 15 16 17 18 19 20 21 24" -{!../../docs_src/path_operation_advanced_configuration/tutorial002.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2,12,13,14,15,16,17,18,19,20,21,24] *} /// tip @@ -44,9 +40,7 @@ 使用参数 `include_in_schema` 并将其设置为 `False` ,来从生成的 OpenAPI 方案中排除一个 *路径操作*(这样一来,就从自动化文档系统中排除掉了)。 -```Python hl_lines="6" -{!../../docs_src/path_operation_advanced_configuration/tutorial003.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *} ## docstring 的高级描述 @@ -57,6 +51,4 @@ 剩余部分不会出现在文档中,但是其他工具(比如 Sphinx)可以使用剩余部分。 -```Python hl_lines="19 20 21 22 23 24 25 26 27 28 29" -{!../../docs_src/path_operation_advanced_configuration/tutorial004.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19,20,21,22,23,24,25,26,27,28,29] *} diff --git a/docs/zh/docs/advanced/response-change-status-code.md b/docs/zh/docs/advanced/response-change-status-code.md index c38f80f1f..cc1f2a73e 100644 --- a/docs/zh/docs/advanced/response-change-status-code.md +++ b/docs/zh/docs/advanced/response-change-status-code.md @@ -20,9 +20,7 @@ 然后你可以在这个*临时*响应对象中设置`status_code`。 -```Python hl_lines="1 9 12" -{!../../docs_src/response_change_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *} 然后你可以像平常一样返回任何你需要的对象(例如一个`dict`或者一个数据库模型)。如果你声明了一个`response_model`,它仍然会被用来过滤和转换你返回的对象。 diff --git a/docs/zh/docs/advanced/response-cookies.md b/docs/zh/docs/advanced/response-cookies.md index 2d56c6e9b..d4b93d003 100644 --- a/docs/zh/docs/advanced/response-cookies.md +++ b/docs/zh/docs/advanced/response-cookies.md @@ -4,9 +4,7 @@ 你可以在 *路径函数* 中定义一个类型为 `Response`的参数,这样你就可以在这个临时响应对象中设置cookie了。 -```Python hl_lines="1 8-9" -{!../../docs_src/response_cookies/tutorial002.py!} -``` +{* ../../docs_src/response_cookies/tutorial002.py hl[1,8:9] *} 而且你还可以根据你的需要响应不同的对象,比如常用的 `dict`,数据库model等。 @@ -24,9 +22,7 @@ 然后设置Cookies,并返回: -```Python hl_lines="10-12" -{!../../docs_src/response_cookies/tutorial001.py!} -``` +{* ../../docs_src/response_cookies/tutorial001.py hl[10:12] *} /// tip diff --git a/docs/zh/docs/advanced/response-directly.md b/docs/zh/docs/advanced/response-directly.md index 934f60ef6..4d9cd53f2 100644 --- a/docs/zh/docs/advanced/response-directly.md +++ b/docs/zh/docs/advanced/response-directly.md @@ -35,9 +35,7 @@ 对于这些情况,在将数据传递给响应之前,你可以使用 `jsonable_encoder` 来转换你的数据。 -```Python hl_lines="4 6 20 21" -{!../../docs_src/response_directly/tutorial001.py!} -``` +{* ../../docs_src/response_directly/tutorial001.py hl[4,6,20,21] *} /// note | 技术细节 @@ -57,9 +55,7 @@ 你可以把你的 XML 内容放到一个字符串中,放到一个 `Response` 中,然后返回。 -```Python hl_lines="1 18" -{!../../docs_src/response_directly/tutorial002.py!} -``` +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} ## 说明 diff --git a/docs/zh/docs/advanced/response-headers.md b/docs/zh/docs/advanced/response-headers.md index e7861ad0c..fe2cb0da8 100644 --- a/docs/zh/docs/advanced/response-headers.md +++ b/docs/zh/docs/advanced/response-headers.md @@ -5,9 +5,7 @@ 你可以在你的*路径操作函数*中声明一个`Response`类型的参数(就像你可以为cookies做的那样)。 然后你可以在这个*临时*响应对象中设置头部。 -```Python hl_lines="1 7-8" -{!../../docs_src/response_headers/tutorial002.py!} -``` +{* ../../docs_src/response_headers/tutorial002.py hl[1,7:8] *} 然后你可以像平常一样返回任何你需要的对象(例如一个`dict`或者一个数据库模型)。如果你声明了一个`response_model`,它仍然会被用来过滤和转换你返回的对象。 @@ -20,9 +18,8 @@ 你也可以在直接返回`Response`时添加头部。 按照[直接返回响应](response-directly.md){.internal-link target=_blank}中所述创建响应,并将头部作为附加参数传递: -```Python hl_lines="10-12" -{!../../docs_src/response_headers/tutorial001.py!} -``` + +{* ../../docs_src/response_headers/tutorial001.py hl[10:12] *} /// note | 技术细节 diff --git a/docs/zh/docs/advanced/security/http-basic-auth.md b/docs/zh/docs/advanced/security/http-basic-auth.md index 06c6dbbab..599429f9d 100644 --- a/docs/zh/docs/advanced/security/http-basic-auth.md +++ b/docs/zh/docs/advanced/security/http-basic-auth.md @@ -20,35 +20,7 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。 * 返回类型为 `HTTPBasicCredentials` 的对象: * 包含发送的 `username` 与 `password` -//// tab | Python 3.9+ - -```Python hl_lines="4 8 12" -{!> ../../docs_src/security/tutorial006_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="2 7 11" -{!> ../../docs_src/security/tutorial006_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="2 6 10" -{!> ../../docs_src/security/tutorial006.py!} -``` - -//// +{* ../../docs_src/security/tutorial006_an_py39.py hl[4,8,12] *} 第一次打开 URL(或在 API 文档中点击 **Execute** 按钮)时,浏览器要求输入用户名与密码: @@ -68,35 +40,7 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。 然后我们可以使用 `secrets.compare_digest()` 来确保 `credentials.username` 是 `"stanleyjobson"`,且 `credentials.password` 是`"swordfish"`。 -//// tab | Python 3.9+ - -```Python hl_lines="1 12-24" -{!> ../../docs_src/security/tutorial007_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 12-24" -{!> ../../docs_src/security/tutorial007_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="1 11-21" -{!> ../../docs_src/security/tutorial007.py!} -``` - -//// +{* ../../docs_src/security/tutorial007_an_py39.py hl[1,12:24] *} 这类似于: @@ -160,32 +104,4 @@ if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": 检测到凭证不正确后,返回 `HTTPException` 及状态码 401(与无凭证时返回的内容一样),并添加请求头 `WWW-Authenticate`,让浏览器再次显示登录提示: -//// tab | Python 3.9+ - -```Python hl_lines="26-30" -{!> ../../docs_src/security/tutorial007_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="26-30" -{!> ../../docs_src/security/tutorial007_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="23-27" -{!> ../../docs_src/security/tutorial007.py!} -``` - -//// +{* ../../docs_src/security/tutorial007_an_py39.py hl[26:30] *} diff --git a/docs/zh/docs/advanced/security/oauth2-scopes.md b/docs/zh/docs/advanced/security/oauth2-scopes.md index b26522113..c3f593684 100644 --- a/docs/zh/docs/advanced/security/oauth2-scopes.md +++ b/docs/zh/docs/advanced/security/oauth2-scopes.md @@ -62,9 +62,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 首先,快速浏览一下以下代码与**用户指南**中 [OAuth2 实现密码哈希与 Bearer JWT 令牌验证](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}一章中代码的区别。以下代码使用 OAuth2 作用域: -```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 153" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[2,4,8,12,46,64,105,107:115,121:124,128:134,139,153] *} 下面,我们逐步说明修改的代码内容。 @@ -74,9 +72,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 `scopes` 参数接收**字典**,键是作用域、值是作用域的描述: -```Python hl_lines="62-65" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[62:65] *} 因为声明了作用域,所以登录或授权时会在 API 文档中显示。 @@ -102,9 +98,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 /// -```Python hl_lines="153" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[153] *} ## 在*路径操作*与依赖项中声明作用域 @@ -130,9 +124,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 /// -```Python hl_lines="4 139 166" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[4,139,166] *} /// info | 技术细节 @@ -158,9 +150,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 `SecuriScopes` 类与 `Request` 类似(`Request` 用于直接提取请求对象)。 -```Python hl_lines="8 105" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[8,105] *} ## 使用 `scopes` @@ -174,9 +164,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 该异常包含了作用域所需的(如有),以空格分割的字符串(使用 `scope_str`)。该字符串要放到包含作用域的 `WWW-Authenticate` 请求头中(这也是规范的要求)。 -```Python hl_lines="105 107-115" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[105,107:115] *} ## 校验 `username` 与数据形状 @@ -192,9 +180,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 还可以使用用户名验证用户,如果没有用户,也会触发之前创建的异常。 -```Python hl_lines="46 116-127" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[46,116:127] *} ## 校验 `scopes` @@ -202,9 +188,7 @@ OAuth2 中,**作用域**只是声明特定权限的字符串。 为此,要使用包含所有作用域**字符串列表**的 `security_scopes.scopes`, 。 -```Python hl_lines="128-134" -{!../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[128:134] *} ## 依赖项树与作用域 diff --git a/docs/zh/docs/advanced/settings.md b/docs/zh/docs/advanced/settings.md index 4d35731cb..e33da136f 100644 --- a/docs/zh/docs/advanced/settings.md +++ b/docs/zh/docs/advanced/settings.md @@ -150,9 +150,7 @@ Hello World from Python 您可以使用与 Pydantic 模型相同的验证功能和工具,比如不同的数据类型和使用 `Field()` 进行附加验证。 -```Python hl_lines="2 5-8 11" -{!../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[2,5:8,11] *} /// tip @@ -168,9 +166,7 @@ Hello World from Python 然后,您可以在应用程序中使用新的 `settings` 对象: -```Python hl_lines="18-20" -{!../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[18:20] *} ### 运行服务器 @@ -204,15 +200,11 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app 例如,您可以创建一个名为 `config.py` 的文件,其中包含以下内容: -```Python -{!../../docs_src/settings/app01/config.py!} -``` +{* ../../docs_src/settings/app01/config.py *} 然后在一个名为 `main.py` 的文件中使用它: -```Python hl_lines="3 11-13" -{!../../docs_src/settings/app01/main.py!} -``` +{* ../../docs_src/settings/app01/main.py hl[3,11:13] *} /// tip @@ -230,9 +222,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app 根据前面的示例,您的 `config.py` 文件可能如下所示: -```Python hl_lines="10" -{!../../docs_src/settings/app02/config.py!} -``` +{* ../../docs_src/settings/app02/config.py hl[10] *} 请注意,现在我们不创建默认实例 `settings = Settings()`。 @@ -240,35 +230,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app 现在我们创建一个依赖项,返回一个新的 `config.Settings()`。 -//// tab | Python 3.9+ - -```Python hl_lines="6 12-13" -{!> ../../docs_src/settings/app02_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="6 12-13" -{!> ../../docs_src/settings/app02_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ 非注解版本 - -/// tip - -如果可能,请尽量使用 `Annotated` 版本。 - -/// - -```Python hl_lines="5 11-12" -{!> ../../docs_src/settings/app02/main.py!} -``` - -//// +{* ../../docs_src/settings/app02_an_py39/main.py hl[6,12:13] *} /// tip @@ -280,43 +242,13 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app 然后,我们可以将其作为依赖项从“路径操作函数”中引入,并在需要时使用它。 -//// tab | Python 3.9+ - -```Python hl_lines="17 19-21" -{!> ../../docs_src/settings/app02_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17 19-21" -{!> ../../docs_src/settings/app02_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ 非注解版本 - -/// tip - -如果可能,请尽量使用 `Annotated` 版本。 - -/// - -```Python hl_lines="16 18-20" -{!> ../../docs_src/settings/app02/main.py!} -``` - -//// +{* ../../docs_src/settings/app02_an_py39/main.py hl[17,19:21] *} ### 设置和测试 然后,在测试期间,通过创建 `get_settings` 的依赖项覆盖,很容易提供一个不同的设置对象: -```Python hl_lines="9-10 13 21" -{!../../docs_src/settings/app02/test_main.py!} -``` +{* ../../docs_src/settings/app02/test_main.py hl[9:10,13,21] *} 在依赖项覆盖中,我们在创建新的 `Settings` 对象时为 `admin_email` 设置了一个新值,然后返回该新对象。 @@ -357,9 +289,7 @@ APP_NAME="ChimichangApp" 然后,您可以使用以下方式更新您的 `config.py`: -```Python hl_lines="9-10" -{!../../docs_src/settings/app03/config.py!} -``` +{* ../../docs_src/settings/app03/config.py hl[9:10] *} 在这里,我们在 Pydantic 的 `Settings` 类中创建了一个名为 `Config` 的类,并将 `env_file` 设置为我们想要使用的 dotenv 文件的文件名。 @@ -392,35 +322,7 @@ def get_settings(): 但是,由于我们在顶部使用了 `@lru_cache` 装饰器,因此只有在第一次调用它时,才会创建 `Settings` 对象一次。 ✔️ -//// tab | Python 3.9+ - -```Python hl_lines="1 11" -{!> ../../docs_src/settings/app03_an_py39/main.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 11" -{!> ../../docs_src/settings/app03_an/main.py!} -``` - -//// - -//// tab | Python 3.8+ 非注解版本 - -/// tip - -如果可能,请尽量使用 `Annotated` 版本。 - -/// - -```Python hl_lines="1 10" -{!> ../../docs_src/settings/app03/main.py!} -``` - -//// +{* ../../docs_src/settings/app03_an_py39/main.py hl[1,11] *} 然后,在下一次请求的依赖项中对 `get_settings()` 进行任何后续调用时,它不会执行 `get_settings()` 的内部代码并创建新的 `Settings` 对象,而是返回在第一次调用时返回的相同对象,一次又一次。 diff --git a/docs/zh/docs/advanced/sub-applications.md b/docs/zh/docs/advanced/sub-applications.md index f93ab1d24..c42be2849 100644 --- a/docs/zh/docs/advanced/sub-applications.md +++ b/docs/zh/docs/advanced/sub-applications.md @@ -10,9 +10,7 @@ 首先,创建主(顶层)**FastAPI** 应用及其*路径操作*: -```Python hl_lines="3 6-8" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[3,6:8] *} ### 子应用 @@ -20,9 +18,7 @@ 子应用只是另一个标准 FastAPI 应用,但这个应用是被**挂载**的应用: -```Python hl_lines="11 14-16" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11,14:16] *} ### 挂载子应用 @@ -30,9 +26,7 @@ 本例的子应用挂载在 `/subapi` 路径下: -```Python hl_lines="11 19" -{!../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11,19] *} ### 查看文档 diff --git a/docs/zh/docs/advanced/templates.md b/docs/zh/docs/advanced/templates.md index 7692aa47b..8b7019ede 100644 --- a/docs/zh/docs/advanced/templates.md +++ b/docs/zh/docs/advanced/templates.md @@ -27,9 +27,7 @@ $ pip install jinja2 * 在返回模板的*路径操作*中声明 `Request` 参数 * 使用 `templates` 渲染并返回 `TemplateResponse`, 传递模板的名称、request对象以及一个包含多个键值对(用于Jinja2模板)的"context"字典, -```Python hl_lines="4 11 15-16" -{!../../docs_src/templates/tutorial001.py!} -``` +{* ../../docs_src/templates/tutorial001.py hl[4,11,15:16] *} /// note | 笔记 diff --git a/docs/zh/docs/advanced/testing-dependencies.md b/docs/zh/docs/advanced/testing-dependencies.md index b4b5b32df..620539fd1 100644 --- a/docs/zh/docs/advanced/testing-dependencies.md +++ b/docs/zh/docs/advanced/testing-dependencies.md @@ -28,9 +28,7 @@ 这样一来,**FastAPI** 就会调用覆盖依赖项,不再调用原依赖项。 -```Python hl_lines="26-27 30" -{!../../docs_src/dependency_testing/tutorial001.py!} -``` +{* ../../docs_src/dependency_testing/tutorial001.py hl[26:27,30] *} /// tip | 提示 diff --git a/docs/zh/docs/advanced/testing-events.md b/docs/zh/docs/advanced/testing-events.md index 00e661cd2..71b3739c3 100644 --- a/docs/zh/docs/advanced/testing-events.md +++ b/docs/zh/docs/advanced/testing-events.md @@ -2,6 +2,4 @@ 使用 `TestClient` 和 `with` 语句,在测试中运行事件处理器(`startup` 与 `shutdown`)。 -```Python hl_lines="9-12 20-24" -{!../../docs_src/app_testing/tutorial003.py!} -``` +{* ../../docs_src/app_testing/tutorial003.py hl[9:12,20:24] *} diff --git a/docs/zh/docs/advanced/testing-websockets.md b/docs/zh/docs/advanced/testing-websockets.md index b30939b97..5d713d5f7 100644 --- a/docs/zh/docs/advanced/testing-websockets.md +++ b/docs/zh/docs/advanced/testing-websockets.md @@ -4,9 +4,7 @@ 为此,要在 `with` 语句中使用 `TestClient` 连接 WebSocket。 -```Python hl_lines="27-31" -{!../../docs_src/app_testing/tutorial002.py!} -``` +{* ../../docs_src/app_testing/tutorial002.py hl[27:31] *} /// note | 笔记 diff --git a/docs/zh/docs/advanced/using-request-directly.md b/docs/zh/docs/advanced/using-request-directly.md index f01644de6..db0fcafdf 100644 --- a/docs/zh/docs/advanced/using-request-directly.md +++ b/docs/zh/docs/advanced/using-request-directly.md @@ -29,9 +29,7 @@ 此时,需要直接访问请求。 -```Python hl_lines="1 7-8" -{!../../docs_src/using_request_directly/tutorial001.py!} -``` +{* ../../docs_src/using_request_directly/tutorial001.py hl[1,7:8] *} 把*路径操作函数*的参数类型声明为 `Request`,**FastAPI** 就能把 `Request` 传递到参数里。 diff --git a/docs/zh/docs/advanced/websockets.md b/docs/zh/docs/advanced/websockets.md index dcd4cd5a9..d91aacc03 100644 --- a/docs/zh/docs/advanced/websockets.md +++ b/docs/zh/docs/advanced/websockets.md @@ -34,17 +34,13 @@ $ pip install websockets 但这是一种专注于 WebSockets 的服务器端并提供一个工作示例的最简单方式: -```Python hl_lines="2 6-38 41-43" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[2,6:38,41:43] *} ## 创建 `websocket` 在您的 **FastAPI** 应用程序中,创建一个 `websocket`: -```Python hl_lines="1 46-47" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[1,46:47] *} /// note | 技术细节 @@ -58,9 +54,7 @@ $ pip install websockets 在您的 WebSocket 路由中,您可以使用 `await` 等待消息并发送消息。 -```Python hl_lines="48-52" -{!../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[48:52] *} 您可以接收和发送二进制、文本和 JSON 数据。 @@ -109,57 +103,7 @@ $ uvicorn main:app --reload 它们的工作方式与其他 FastAPI 端点/ *路径操作* 相同: -//// tab | Python 3.10+ - -```Python hl_lines="68-69 82" -{!> ../../docs_src/websockets/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="68-69 82" -{!> ../../docs_src/websockets/tutorial002_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="69-70 83" -{!> ../../docs_src/websockets/tutorial002_an.py!} -``` - -//// - -//// tab | Python 3.10+ 非带注解版本 - -/// tip - -如果可能,请尽量使用 `Annotated` 版本。 - -/// - -```Python hl_lines="66-67 79" -{!> ../../docs_src/websockets/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ 非带注解版本 - -/// tip - -如果可能,请尽量使用 `Annotated` 版本。 - -/// - -```Python hl_lines="68-69 81" -{!> ../../docs_src/websockets/tutorial002.py!} -``` - -//// +{* ../../docs_src/websockets/tutorial002_an_py310.py hl[68:69,82] *} /// info @@ -200,21 +144,7 @@ $ uvicorn main:app --reload 当 WebSocket 连接关闭时,`await websocket.receive_text()` 将引发 `WebSocketDisconnect` 异常,您可以捕获并处理该异常,就像本示例中的示例一样。 -//// tab | Python 3.9+ - -```Python hl_lines="79-81" -{!> ../../docs_src/websockets/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="81-83" -{!> ../../docs_src/websockets/tutorial003.py!} -``` - -//// +{* ../../docs_src/websockets/tutorial003_py39.py hl[79:81] *} 尝试以下操作: diff --git a/docs/zh/docs/advanced/wsgi.md b/docs/zh/docs/advanced/wsgi.md index 92bd998d0..363025a34 100644 --- a/docs/zh/docs/advanced/wsgi.md +++ b/docs/zh/docs/advanced/wsgi.md @@ -12,9 +12,7 @@ 之后将其挂载到某一个路径下。 -```Python hl_lines="2-3 22" -{!../../docs_src/wsgi/tutorial001.py!} -``` +{* ../../docs_src/wsgi/tutorial001.py hl[2:3,22] *} ## 检查 diff --git a/docs/zh/docs/how-to/configure-swagger-ui.md b/docs/zh/docs/how-to/configure-swagger-ui.md index 1a2daeec1..108e0cb95 100644 --- a/docs/zh/docs/how-to/configure-swagger-ui.md +++ b/docs/zh/docs/how-to/configure-swagger-ui.md @@ -18,9 +18,7 @@ FastAPI会将这些配置转换为 **JSON**,使其与 JavaScript 兼容,因 但是你可以通过设置 `syntaxHighlight` 为 `False` 来禁用 Swagger UI 中的语法高亮: -```Python hl_lines="3" -{!../../docs_src/configure_swagger_ui/tutorial001.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial001.py hl[3] *} ...在此之后,Swagger UI 将不会高亮代码: @@ -30,9 +28,7 @@ FastAPI会将这些配置转换为 **JSON**,使其与 JavaScript 兼容,因 同样地,你也可以通过设置键 `"syntaxHighlight.theme"` 来设置语法高亮主题(注意中间有一个点): -```Python hl_lines="3" -{!../../docs_src/configure_swagger_ui/tutorial002.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial002.py hl[3] *} 这个配置会改变语法高亮主题: @@ -44,17 +40,13 @@ FastAPI 包含了一些默认配置参数,适用于大多数用例。 其包括这些默认配置参数: -```Python -{!../../fastapi/openapi/docs.py[ln:7-23]!} -``` +{* ../../fastapi/openapi/docs.py ln[7:23] *} 你可以通过在 `swagger_ui_parameters` 中设置不同的值来覆盖它们。 比如,如果要禁用 `deepLinking`,你可以像这样传递设置到 `swagger_ui_parameters` 中: -```Python hl_lines="3" -{!../../docs_src/configure_swagger_ui/tutorial003.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial003.py hl[3] *} ## 其他 Swagger UI 参数 diff --git a/docs/zh/docs/python-types.md b/docs/zh/docs/python-types.md index dab6bd4c0..5126cb847 100644 --- a/docs/zh/docs/python-types.md +++ b/docs/zh/docs/python-types.md @@ -22,9 +22,8 @@ 让我们从一个简单的例子开始: -```Python -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} + 运行这段程序将输出: @@ -38,9 +37,8 @@ John Doe * 通过 `title()` 将每个参数的第一个字母转换为大写形式。 * 中间用一个空格来拼接它们。 -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### 修改示例 @@ -82,9 +80,8 @@ John Doe 这些就是"类型提示": -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + 这和声明默认值是不同的,例如: @@ -112,9 +109,8 @@ John Doe 下面是一个已经有类型提示的函数: -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + 因为编辑器已经知道了这些变量的类型,所以不仅能对代码进行补全,还能检查其中的错误: @@ -122,9 +118,8 @@ John Doe 现在你知道了必须先修复这个问题,通过 `str(age)` 把 `age` 转换成字符串: -```Python hl_lines="2" -{!../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## 声明类型 @@ -143,9 +138,8 @@ John Doe * `bool` * `bytes` -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### 嵌套类型 @@ -161,9 +155,8 @@ John Doe 从 `typing` 模块导入 `List`(注意是大写的 `L`): -```Python hl_lines="1" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[1] *} + 同样以冒号(`:`)来声明这个变量。 @@ -171,9 +164,8 @@ John Doe 由于列表是带有"子类型"的类型,所以我们把子类型放在方括号中: -```Python hl_lines="4" -{!../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[4] *} + 这表示:"变量 `items` 是一个 `list`,并且这个列表里的每一个元素都是 `str`"。 @@ -191,9 +183,8 @@ John Doe 声明 `tuple` 和 `set` 的方法也是一样的: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial007.py!} -``` +{* ../../docs_src/python_types/tutorial007.py hl[1,4] *} + 这表示: @@ -208,9 +199,8 @@ John Doe 第二个子类型声明 `dict` 的所有值: -```Python hl_lines="1 4" -{!../../docs_src/python_types/tutorial008.py!} -``` +{* ../../docs_src/python_types/tutorial008.py hl[1,4] *} + 这表示: @@ -224,15 +214,13 @@ John Doe 假设你有一个名为 `Person` 的类,拥有 name 属性: -```Python hl_lines="1-3" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + 接下来,你可以将一个变量声明为 `Person` 类型: -```Python hl_lines="6" -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + 然后,你将再次获得所有的编辑器支持: @@ -252,9 +240,8 @@ John Doe 下面的例子来自 Pydantic 官方文档: -```Python -{!../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py *} + /// info diff --git a/docs/zh/docs/tutorial/body-fields.md b/docs/zh/docs/tutorial/body-fields.md index 9aeb481ef..4cff58bfc 100644 --- a/docs/zh/docs/tutorial/body-fields.md +++ b/docs/zh/docs/tutorial/body-fields.md @@ -6,57 +6,7 @@ 首先,从 Pydantic 中导入 `Field`: -//// tab | Python 3.10+ - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="2" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="4" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *} /// warning | 警告 @@ -68,57 +18,7 @@ 然后,使用 `Field` 定义模型的属性: -//// tab | Python 3.10+ - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="12-15" -{!> ../../docs_src/body_fields/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="9-12" -{!> ../../docs_src/body_fields/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -Prefer to use the `Annotated` version if possible. - -/// - -```Python hl_lines="11-14" -{!> ../../docs_src/body_fields/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *} `Field` 的工作方式和 `Query`、`Path`、`Body` 相同,参数也相同。 diff --git a/docs/zh/docs/tutorial/body-multiple-params.md b/docs/zh/docs/tutorial/body-multiple-params.md index c3bc0db9e..b4356fdcb 100644 --- a/docs/zh/docs/tutorial/body-multiple-params.md +++ b/docs/zh/docs/tutorial/body-multiple-params.md @@ -8,57 +8,7 @@ 你还可以通过将默认值设置为 `None` 来将请求体参数声明为可选参数: -//// tab | Python 3.10+ - -```Python hl_lines="18-20" -{!> ../../docs_src/body_multiple_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="18-20" -{!> ../../docs_src/body_multiple_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="19-21" -{!> ../../docs_src/body_multiple_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="17-19" -{!> ../../docs_src/body_multiple_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="19-21" -{!> ../../docs_src/body_multiple_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *} /// note @@ -81,21 +31,7 @@ 但是你也可以声明多个请求体参数,例如 `item` 和 `user`: -//// tab | Python 3.10+ - -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *} 在这种情况下,**FastAPI** 将注意到该函数中有多个请求体参数(两个 Pydantic 模型参数)。 @@ -137,57 +73,7 @@ 但是你可以使用 `Body` 指示 **FastAPI** 将其作为请求体的另一个键进行处理。 -//// tab | Python 3.10+ - -```Python hl_lines="23" -{!> ../../docs_src/body_multiple_params/tutorial003_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="23" -{!> ../../docs_src/body_multiple_params/tutorial003_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="24" -{!> ../../docs_src/body_multiple_params/tutorial003_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="20" -{!> ../../docs_src/body_multiple_params/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="22" -{!> ../../docs_src/body_multiple_params/tutorial003.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *} 在这种情况下,**FastAPI** 将期望像这样的请求体: @@ -222,57 +108,7 @@ q: str = None 比如: -//// tab | Python 3.10+ - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="28" -{!> ../../docs_src/body_multiple_params/tutorial004_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="25" -{!> ../../docs_src/body_multiple_params/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="27" -{!> ../../docs_src/body_multiple_params/tutorial004.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[27] *} /// info @@ -294,57 +130,7 @@ item: Item = Body(embed=True) 比如: -//// tab | Python 3.10+ - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/body_multiple_params/tutorial005_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="15" -{!> ../../docs_src/body_multiple_params/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="17" -{!> ../../docs_src/body_multiple_params/tutorial005.py!} -``` - -//// +{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *} 在这种情况下,**FastAPI** 将期望像这样的请求体: diff --git a/docs/zh/docs/tutorial/body-nested-models.md b/docs/zh/docs/tutorial/body-nested-models.md index 316ba9878..df96d96b4 100644 --- a/docs/zh/docs/tutorial/body-nested-models.md +++ b/docs/zh/docs/tutorial/body-nested-models.md @@ -6,21 +6,7 @@ 你可以将一个属性定义为拥有子元素的类型。例如 Python `list`: -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial001.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *} 这将使 `tags` 成为一个由元素组成的列表。不过它没有声明每个元素的类型。 @@ -32,9 +18,7 @@ 首先,从 Python 的标准库 `typing` 模块中导入 `List`: -```Python hl_lines="1" -{!> ../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *} ### 声明具有子类型的 List @@ -55,29 +39,7 @@ my_list: List[str] 因此,在我们的示例中,我们可以将 `tags` 明确地指定为一个「字符串列表」: -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial002_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial002.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *} ## Set 类型 @@ -87,29 +49,7 @@ Python 具有一种特殊的数据类型来保存一组唯一的元素,即 `se 然后我们可以导入 `Set` 并将 `tag` 声明为一个由 `str` 组成的 `set`: -//// tab | Python 3.10+ - -```Python hl_lines="12" -{!> ../../docs_src/body_nested_models/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="14" -{!> ../../docs_src/body_nested_models/tutorial003_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="1 14" -{!> ../../docs_src/body_nested_models/tutorial003.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *} 这样,即使你收到带有重复数据的请求,这些数据也会被转换为一组唯一项。 @@ -131,57 +71,13 @@ Pydantic 模型的每个属性都具有类型。 例如,我们可以定义一个 `Image` 模型: -//// tab | Python 3.10+ - -```Python hl_lines="7-9" -{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9-11" -{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9-11" -{!> ../../docs_src/body_nested_models/tutorial004.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *} ### 将子模型用作类型 然后我们可以将其用作一个属性的类型: -//// tab | Python 3.10+ - -```Python hl_lines="18" -{!> ../../docs_src/body_nested_models/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial004_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial004.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *} 这意味着 **FastAPI** 将期望类似于以下内容的请求体: @@ -214,29 +110,7 @@ Pydantic 模型的每个属性都具有类型。 例如,在 `Image` 模型中我们有一个 `url` 字段,我们可以把它声明为 Pydantic 的 `HttpUrl`,而不是 `str`: -//// tab | Python 3.10+ - -```Python hl_lines="2 8" -{!> ../../docs_src/body_nested_models/tutorial005_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="4 10" -{!> ../../docs_src/body_nested_models/tutorial005_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4 10" -{!> ../../docs_src/body_nested_models/tutorial005.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *} 该字符串将被检查是否为有效的 URL,并在 JSON Schema / OpenAPI 文档中进行记录。 @@ -244,29 +118,7 @@ Pydantic 模型的每个属性都具有类型。 你还可以将 Pydantic 模型用作 `list`、`set` 等的子类型: -//// tab | Python 3.10+ - -```Python hl_lines="18" -{!> ../../docs_src/body_nested_models/tutorial006_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial006_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="20" -{!> ../../docs_src/body_nested_models/tutorial006.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *} 这将期望(转换,校验,记录文档等)下面这样的 JSON 请求体: @@ -304,29 +156,7 @@ Pydantic 模型的每个属性都具有类型。 你可以定义任意深度的嵌套模型: -//// tab | Python 3.10+ - -```Python hl_lines="7 12 18 21 25" -{!> ../../docs_src/body_nested_models/tutorial007_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9 14 20 23 27" -{!> ../../docs_src/body_nested_models/tutorial007_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9 14 20 23 27" -{!> ../../docs_src/body_nested_models/tutorial007.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *} /// info @@ -344,21 +174,7 @@ images: List[Image] 例如: -//// tab | Python 3.9+ - -```Python hl_lines="13" -{!> ../../docs_src/body_nested_models/tutorial008_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="15" -{!> ../../docs_src/body_nested_models/tutorial008.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial008_py39.py hl[13] *} ## 无处不在的编辑器支持 @@ -388,21 +204,7 @@ images: List[Image] 在下面的例子中,你将接受任意键为 `int` 类型并且值为 `float` 类型的 `dict`: -//// tab | Python 3.9+ - -```Python hl_lines="7" -{!> ../../docs_src/body_nested_models/tutorial009_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/body_nested_models/tutorial009.py!} -``` - -//// +{* ../../docs_src/body_nested_models/tutorial009_py39.py hl[7] *} /// tip diff --git a/docs/zh/docs/tutorial/body-updates.md b/docs/zh/docs/tutorial/body-updates.md index 9372e1dfd..87f88f255 100644 --- a/docs/zh/docs/tutorial/body-updates.md +++ b/docs/zh/docs/tutorial/body-updates.md @@ -6,9 +6,7 @@ 把输入数据转换为以 JSON 格式存储的数据(比如,使用 NoSQL 数据库时),可以使用 `jsonable_encoder`。例如,把 `datetime` 转换为 `str`。 -```Python hl_lines="30-35" -{!../../docs_src/body_updates/tutorial001.py!} -``` +{* ../../docs_src/body_updates/tutorial001.py hl[30:35] *} `PUT` 用于接收替换现有数据的数据。 @@ -56,9 +54,7 @@ 然后再用它生成一个只含已设置(在请求中所发送)数据,且省略了默认值的 `dict`: -```Python hl_lines="34" -{!../../docs_src/body_updates/tutorial002.py!} -``` +{* ../../docs_src/body_updates/tutorial002.py hl[34] *} ### 使用 Pydantic 的 `update` 参数 @@ -66,9 +62,7 @@ 例如,`stored_item_model.copy(update=update_data)`: -```Python hl_lines="35" -{!../../docs_src/body_updates/tutorial002.py!} -``` +{* ../../docs_src/body_updates/tutorial002.py hl[35] *} ### 更新部分数据小结 @@ -85,9 +79,7 @@ * 把数据保存至数据库; * 返回更新后的模型。 -```Python hl_lines="30-37" -{!../../docs_src/body_updates/tutorial002.py!} -``` +{* ../../docs_src/body_updates/tutorial002.py hl[30:37] *} /// tip | 提示 diff --git a/docs/zh/docs/tutorial/body.md b/docs/zh/docs/tutorial/body.md index bf3117beb..3820fc747 100644 --- a/docs/zh/docs/tutorial/body.md +++ b/docs/zh/docs/tutorial/body.md @@ -22,21 +22,7 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请 从 `pydantic` 中导入 `BaseModel`: -//// tab | Python 3.10+ - -```Python hl_lines="2" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="4" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// +{* ../../docs_src/body/tutorial001_py310.py hl[2] *} ## 创建数据模型 @@ -44,21 +30,7 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请 使用 Python 标准类型声明所有属性: -//// tab | Python 3.10+ - -```Python hl_lines="5-9" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="7-11" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// +{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *} 与声明查询参数一样,包含默认值的模型属性是可选的,否则就是必选的。默认值为 `None` 的模型属性也是可选的。 @@ -86,21 +58,7 @@ API 基本上肯定要发送**响应体**,但是客户端不一定发送**请 使用与声明路径和查询参数相同的方式声明请求体,把请求体添加至*路径操作*: -//// tab | Python 3.10+ - -```Python hl_lines="16" -{!> ../../docs_src/body/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/body/tutorial001.py!} -``` - -//// +{* ../../docs_src/body/tutorial001_py310.py hl[16] *} ……此处,请求体参数的类型为 `Item` 模型。 @@ -167,21 +125,7 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 在*路径操作*函数内部直接访问模型对象的属性: -//// tab | Python 3.10+ - -```Python hl_lines="19" -{!> ../../docs_src/body/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="21" -{!> ../../docs_src/body/tutorial002.py!} -``` - -//// +{* ../../docs_src/body/tutorial002_py310.py hl[19] *} ## 请求体 + 路径参数 @@ -189,21 +133,7 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 **FastAPI** 能识别与**路径参数**匹配的函数参数,还能识别从**请求体**中获取的类型为 Pydantic 模型的函数参数。 -//// tab | Python 3.10+ - -```Python hl_lines="15-16" -{!> ../../docs_src/body/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17-18" -{!> ../../docs_src/body/tutorial003.py!} -``` - -//// +{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *} ## 请求体 + 路径参数 + 查询参数 @@ -211,21 +141,7 @@ Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文 **FastAPI** 能够正确识别这三种参数,并从正确的位置获取数据。 -//// tab | Python 3.10+ - -```Python hl_lines="16" -{!> ../../docs_src/body/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="18" -{!> ../../docs_src/body/tutorial004.py!} -``` - -//// +{* ../../docs_src/body/tutorial004_py310.py hl[16] *} 函数参数按如下规则进行识别: diff --git a/docs/zh/docs/tutorial/cookie-params.md b/docs/zh/docs/tutorial/cookie-params.md index 762dca766..495600814 100644 --- a/docs/zh/docs/tutorial/cookie-params.md +++ b/docs/zh/docs/tutorial/cookie-params.md @@ -6,57 +6,7 @@ 首先,导入 `Cookie`: -//// tab | Python 3.10+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="1" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="3" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[3] *} ## 声明 `Cookie` 参数 @@ -65,57 +15,7 @@ 第一个值是默认值,还可以传递所有验证参数或注释参数: -//// tab | Python 3.10+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py310.py!} -``` - -//// - -//// tab | Python 3.9+ - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="10" -{!> ../../docs_src/cookie_params/tutorial001_an.py!} -``` - -//// - -//// tab | Python 3.10+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="7" -{!> ../../docs_src/cookie_params/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip - -尽可能选择使用 `Annotated` 的版本。 - -/// - -```Python hl_lines="9" -{!> ../../docs_src/cookie_params/tutorial001.py!} -``` - -//// +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9] *} /// note | 技术细节 diff --git a/docs/zh/docs/tutorial/cors.md b/docs/zh/docs/tutorial/cors.md index 84c435c97..a4f15f647 100644 --- a/docs/zh/docs/tutorial/cors.md +++ b/docs/zh/docs/tutorial/cors.md @@ -46,9 +46,7 @@ * 特定的 HTTP 方法(`POST`,`PUT`)或者使用通配符 `"*"` 允许所有方法。 * 特定的 HTTP headers 或者使用通配符 `"*"` 允许所有 headers。 -```Python hl_lines="2 6-11 13-19" -{!../../docs_src/cors/tutorial001.py!} -``` +{* ../../docs_src/cors/tutorial001.py hl[2,6:11,13:19] *} 默认情况下,这个 `CORSMiddleware` 实现所使用的默认参数较为保守,所以你需要显式地启用特定的源、方法或者 headers,以便浏览器能够在跨域上下文中使用它们。 diff --git a/docs/zh/docs/tutorial/debugging.md b/docs/zh/docs/tutorial/debugging.md index a5afa1aaa..734b85565 100644 --- a/docs/zh/docs/tutorial/debugging.md +++ b/docs/zh/docs/tutorial/debugging.md @@ -6,9 +6,7 @@ 在你的 FastAPI 应用中直接导入 `uvicorn` 并运行: -```Python hl_lines="1 15" -{!../../docs_src/debugging/tutorial001.py!} -``` +{* ../../docs_src/debugging/tutorial001.py hl[1,15] *} ### 关于 `__name__ == "__main__"` diff --git a/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md index 917459d1d..f07280790 100644 --- a/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,21 +6,7 @@ 在前面的例子中, 我们从依赖项 ("可依赖对象") 中返回了一个 `dict`: -//// tab | Python 3.10+ - -```Python hl_lines="7" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_py310.py hl[7] *} 但是后面我们在路径操作函数的参数 `commons` 中得到了一个 `dict`。 @@ -83,57 +69,15 @@ fluffy = Cat(name="Mr Fluffy") 所以,我们可以将上面的依赖项 "可依赖对象" `common_parameters` 更改为类 `CommonQueryParams`: -//// tab | Python 3.10+ - -```Python hl_lines="9-13" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="11-15" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002_py310.py hl[9:13] *} 注意用于创建类实例的 `__init__` 方法: -//// tab | Python 3.10+ - -```Python hl_lines="10" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="12" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002_py310.py hl[10] *} ...它与我们以前的 `common_parameters` 具有相同的参数: -//// tab | Python 3.10+ - -```Python hl_lines="6" -{!> ../../docs_src/dependencies/tutorial001_py310.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="9" -{!> ../../docs_src/dependencies/tutorial001.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial001_py310.py hl[6] *} 这些参数就是 **FastAPI** 用来 "处理" 依赖项的。 @@ -149,21 +93,7 @@ fluffy = Cat(name="Mr Fluffy") 现在,您可以使用这个类来声明你的依赖项了。 -//// tab | Python 3.10+ - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial002_py310.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial002.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial002_py310.py hl[17] *} **FastAPI** 调用 `CommonQueryParams` 类。这将创建该类的一个 "实例",该实例将作为参数 `commons` 被传递给你的函数。 @@ -203,21 +133,7 @@ commons = Depends(CommonQueryParams) ..就像: -//// tab | Python 3.10+ - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial003_py310.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial003.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial003_py310.py hl[17] *} 但是声明类型是被鼓励的,因为那样你的编辑器就会知道将传递什么作为参数 `commons` ,然后它可以帮助你完成代码,类型检查,等等: @@ -251,21 +167,7 @@ commons: CommonQueryParams = Depends() 同样的例子看起来像这样: -//// tab | Python 3.10+ - -```Python hl_lines="17" -{!> ../../docs_src/dependencies/tutorial004_py310.py!} -``` - -//// - -//// tab | Python 3.6+ - -```Python hl_lines="19" -{!> ../../docs_src/dependencies/tutorial004.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial004_py310.py hl[17] *} ... **FastAPI** 会知道怎么处理。 diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index c202c977b..51b3e9fc3 100644 --- a/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -14,9 +14,7 @@ 该参数的值是由 `Depends()` 组成的 `list`: -```Python hl_lines="17" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[17] *} 路径操作装饰器依赖项(以下简称为**“路径装饰器依赖项”**)的执行或解析方式和普通依赖项一样,但就算这些依赖项会返回值,它们的值也不会传递给*路径操作函数*。 @@ -46,17 +44,13 @@ 路径装饰器依赖项可以声明请求的需求项(比如响应头)或其他子依赖项: -```Python hl_lines="6 11" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[6,11] *} ### 触发异常 路径装饰器依赖项与正常的依赖项一样,可以 `raise` 异常: -```Python hl_lines="8 13" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[8,13] *} ### 返回值 @@ -64,9 +58,7 @@ 因此,可以复用在其他位置使用过的、(能返回值的)普通依赖项,即使没有使用这个值,也会执行该依赖项: -```Python hl_lines="9 14" -{!../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[9,14] *} ## 为一组路径操作定义依赖项 diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md index 792b6784d..a863bb861 100644 --- a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md @@ -29,21 +29,15 @@ FastAPI支持在完成后执行一些 ../../docs_src/dependencies/tutorial008_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="17-18 25-26" -{!> ../../docs_src/dependencies/tutorial008_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | 提示 - -如果可以,请尽量使用 `Annotated` 版本。 - -/// - -```Python hl_lines="16-17 24-25" -{!> ../../docs_src/dependencies/tutorial008.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[18:19,26:27] *} 同样,你可以混合使用带有 `yield` 或 `return` 的依赖。 @@ -170,35 +106,7 @@ FastAPI支持在完成后执行一些 ../../docs_src/dependencies/tutorial008c_an_py39.py!} -``` - -//// - -//// tab | Python 3.8+ - -```Python hl_lines="14-15" -{!> ../../docs_src/dependencies/tutorial008c_an.py!} -``` - -//// - -//// tab | Python 3.8+ non-Annotated - -/// tip | 提示 - -如果可以,请尽量使用 `Annotated` 版本。 - -/// - -```Python hl_lines="13-14" -{!> ../../docs_src/dependencies/tutorial008c.py!} -``` - -//// +{* ../../docs_src/dependencies/tutorial008c_an_py39.py hl[15:16] *} 在示例代码的情况下,客户端将会收到 *HTTP 500 Internal Server Error* 的响应,因为我们没有抛出 `HTTPException` 或者类似的异常,并且服务器也 **不会有任何日志** 或者其他提示来告诉我们错误是什么。😱 @@ -244,35 +124,7 @@ FastAPI支持在完成后执行一些