Browse Source

Merge branch 'master' into feature_offline_docs

pull/13825/head
Robert Anthony 3 days ago
committed by GitHub
parent
commit
e0ba0adf10
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 9
      README.md
  2. 9
      docs/en/docs/index.md
  3. 15
      docs/en/docs/release-notes.md
  4. 4
      docs/en/docs/tutorial/index.md
  5. 41
      docs/ru/docs/advanced/additional-status-codes.md
  6. 65
      docs/ru/docs/advanced/response-directly.md
  7. 2
      fastapi/__init__.py
  8. 23
      pyproject.toml
  9. 2
      requirements-docs.txt

9
README.md

@ -470,15 +470,20 @@ Used by Starlette:
* <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - Required if you want to use the default template configuration.
* <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - Required if you want to support form <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>, with `request.form()`.
Used by FastAPI / Starlette:
Used by FastAPI:
* <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - for the server that loads and serves your application. This includes `uvicorn[standard]`, which includes some dependencies (e.g. `uvloop`) needed for high performance serving.
* `fastapi-cli` - to provide the `fastapi` command.
* `fastapi-cli[standard]` - to provide the `fastapi` command.
* This includes `fastapi-cloud-cli`, which allows you to deploy your FastAPI application to <a href="https://fastapicloud.com" class="external-link" target="_blank">FastAPI Cloud</a>.
### Without `standard` Dependencies
If you don't want to include the `standard` optional dependencies, you can install with `pip install fastapi` instead of `pip install "fastapi[standard]"`.
### Without `fastapi-cloud-cli`
If you want to install FastAPI with the standard dependencies but without the `fastapi-cloud-cli`, you can install with `pip install "fastapi[standard-no-fastapi-cloud-cli]"`.
### Additional Optional Dependencies
There are some additional dependencies you might want to install.

9
docs/en/docs/index.md

@ -468,15 +468,20 @@ Used by Starlette:
* <a href="https://jinja.palletsprojects.com" target="_blank"><code>jinja2</code></a> - Required if you want to use the default template configuration.
* <a href="https://github.com/Kludex/python-multipart" target="_blank"><code>python-multipart</code></a> - Required if you want to support form <abbr title="converting the string that comes from an HTTP request into Python data">"parsing"</abbr>, with `request.form()`.
Used by FastAPI / Starlette:
Used by FastAPI:
* <a href="https://www.uvicorn.org" target="_blank"><code>uvicorn</code></a> - for the server that loads and serves your application. This includes `uvicorn[standard]`, which includes some dependencies (e.g. `uvloop`) needed for high performance serving.
* `fastapi-cli` - to provide the `fastapi` command.
* `fastapi-cli[standard]` - to provide the `fastapi` command.
* This includes `fastapi-cloud-cli`, which allows you to deploy your FastAPI application to <a href="https://fastapicloud.com" class="external-link" target="_blank">FastAPI Cloud</a>.
### Without `standard` Dependencies
If you don't want to include the `standard` optional dependencies, you can install with `pip install fastapi` instead of `pip install "fastapi[standard]"`.
### Without `fastapi-cloud-cli`
If you want to install FastAPI with the standard dependencies but without the `fastapi-cloud-cli`, you can install with `pip install "fastapi[standard-no-fastapi-cloud-cli]"`.
### Additional Optional Dependencies
There are some additional dependencies you might want to install.

15
docs/en/docs/release-notes.md

@ -7,12 +7,27 @@ hide:
## Latest Changes
## 0.116.0
### Features
* ✨ Add support for deploying to FastAPI Cloud with `fastapi deploy`. PR [#13870](https://github.com/fastapi/fastapi/pull/13870) by [@tiangolo](https://github.com/tiangolo).
Installing `fastapi[standard]` now includes `fastapi-cloud-cli`.
This will allow you to deploy to [FastAPI Cloud](https://fastapicloud.com) with the `fastapi deploy` command.
If you want to install `fastapi` with the standard dependencies but without `fastapi-cloud-cli`, you can install instead `fastapi[standard-no-fastapi-cloud-cli]`.
### Translations
* 🌐 Add Russian translation for `docs/ru/docs/advanced/response-directly.md`. PR [#13801](https://github.com/fastapi/fastapi/pull/13801) by [@NavesSapnis](https://github.com/NavesSapnis).
* 🌐 Add Russian translation for `docs/ru/docs/advanced/additional-status-codes.md`. PR [#13799](https://github.com/fastapi/fastapi/pull/13799) by [@NavesSapnis](https://github.com/NavesSapnis).
* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/body-updates.md`. PR [#13804](https://github.com/fastapi/fastapi/pull/13804) by [@valentinDruzhinin](https://github.com/valentinDruzhinin).
### Internal
* ⬆ Bump pillow from 11.1.0 to 11.3.0. PR [#13852](https://github.com/fastapi/fastapi/pull/13852) by [@dependabot[bot]](https://github.com/apps/dependabot).
* 👥 Update FastAPI People - Sponsors. PR [#13846](https://github.com/fastapi/fastapi/pull/13846) by [@tiangolo](https://github.com/tiangolo).
* 👥 Update FastAPI GitHub topic repositories. PR [#13848](https://github.com/fastapi/fastapi/pull/13848) by [@tiangolo](https://github.com/tiangolo).
* ⬆ Bump mkdocs-material from 9.6.1 to 9.6.15. PR [#13849](https://github.com/fastapi/fastapi/pull/13849) by [@dependabot[bot]](https://github.com/apps/dependabot).

4
docs/en/docs/tutorial/index.md

@ -76,10 +76,12 @@ $ pip install "fastapi[standard]"
/// note
When you install with `pip install "fastapi[standard]"` it comes with some default optional standard dependencies.
When you install with `pip install "fastapi[standard]"` it comes with some default optional standard dependencies, including `fastapi-cloud-cli`, which allows you to deploy to <a href="https://fastapicloud.com" class="external-link" target="_blank">FastAPI Cloud</a>.
If you don't want to have those optional dependencies, you can instead install `pip install fastapi`.
If you want to install the standard dependencies but without the `fastapi-cloud-cli`, you can install with `pip install "fastapi[standard-no-fastapi-cloud-cli]"`.
///
## Advanced User Guide

41
docs/ru/docs/advanced/additional-status-codes.md

@ -0,0 +1,41 @@
# Дополнительные статус коды
По умолчанию **FastAPI** возвращает ответы, используя `JSONResponse`, помещая содержимое, которое вы возвращаете из вашей *операции пути*, внутрь этого `JSONResponse`.
Он будет использовать код статуса по умолчанию или тот, который вы укажете в вашей *операции пути*.
## Дополнительные статус коды
Если вы хотите возвращать дополнительный статус код помимо основного, вы можете сделать это, возвращая объект `Response` напрямую, как `JSONResponse`, и устанавливая нужный статус код напрямую.
Например, скажем, вы хотите создать *операцию пути*, которая позволяет обновлять элементы и возвращает HTTP-код 200 "OK" при успешном выполнении.
Но вы также хотите, чтобы она принимала новые элементы. И если элемент ранее не существовал, он создаётся, и возвращался HTTP-код 201 "Created".
Чтобы реализовать это, импортируйте `JSONResponse` и возвращайте ваш контент напрямую, устанавливая нужный `status_code`:
{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *}
/// warning | Внимание
Когда вы возвращаете объект `Response` напрямую, как в примере выше, он будет возвращён как есть.
Он не будет сериализован при помощи модели и т.д.
Убедитесь, что в нём содержатся именно те данные, которые вы хотите, и что значения являются валидным JSON (если вы используете `JSONResponse`).
///
/// note | Технические детали
Вы также можете использовать `from starlette.responses import JSONResponse`.
**FastAPI** предоставляет тот же `starlette.responses` через `fastapi.responses` просто для вашего удобства, как разработчика. Но большинство доступных Response-классов поступают напрямую из Starlette. То же самое касается и `status`.
///
## OpenAPI и документация API
Если вы возвращаете дополнительные коды статусов и ответы напрямую, они не будут включены в схему OpenAPI (документацию API), потому что FastAPI не может заранее знать, что вы собираетесь вернуть.
Но вы можете задокументировать это в вашем коде, используя: [Дополнительные ответы в OpenAPI](additional-responses.md){.internal-link target=_blank}.

65
docs/ru/docs/advanced/response-directly.md

@ -0,0 +1,65 @@
# Возврат ответа напрямую
Когда вы создаёте **FastAPI** *операцию пути*, вы можете возвращать из неё любые данные: `dict`, `list`, Pydantic-модель, модель базы данных и т.д.
По умолчанию **FastAPI** автоматически преобразует возвращаемое значение в JSON с помощью `jsonable_encoder`, как описано в [JSON кодировщик](../tutorial/encoder.md){.internal-link target=_blank}.
Затем "под капотом" эти данные, совместимые с JSON (например `dict`), помещаются в `JSONResponse`, который используется для отправки ответа клиенту.
Но вы можете возвращать `JSONResponse` напрямую из ваших *операций пути*.
Это может быть полезно, например, если нужно вернуть пользовательские заголовки или куки.
## Возврат `Response`
На самом деле, вы можете возвращать любой объект `Response` или его подкласс.
/// tip | Подсказка
`JSONResponse` сам по себе является подклассом `Response`.
///
И когда вы возвращаете `Response`, **FastAPI** передаст его напрямую.
Это не приведет к преобразованию данных с помощью Pydantic-моделей, содержимое не будет преобразовано в какой-либо тип и т.д.
Это даёт вам большую гибкость. Вы можете возвращать любые типы данных, переопределять любые объявления или валидацию данных и т.д.
## Использование `jsonable_encoder` в `Response`
Поскольку **FastAPI** не изменяет объект `Response`, который вы возвращаете, вы должны убедиться, что его содержимое готово к отправке.
Например, вы не можете поместить Pydantic-модель в `JSONResponse`, не преобразовав её сначала в `dict` с помощью преобразования всех типов данных (таких как `datetime`, `UUID` и т.д.) в совместимые с JSON типы.
В таких случаях вы можете использовать `jsonable_encoder` для преобразования данных перед передачей их в ответ:
{* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *}
/// note | Технические детали
Вы также можете использовать `from starlette.responses import JSONResponse`.
**FastAPI** предоставляет `starlette.responses` через `fastapi.responses` просто для вашего удобства, как разработчика. Но большинство доступных Response-классов поступают напрямую из Starlette.
///
## Возврат пользовательского `Response`
Пример выше показывает все необходимые части, но он пока не очень полезен, так как вы могли бы просто вернуть `item` напрямую, и **FastAPI** поместил бы его в `JSONResponse`, преобразовав в `dict` и т.д. Всё это происходит по умолчанию.
Теперь давайте посмотрим, как можно использовать это для возврата пользовательского ответа.
Допустим, вы хотите вернуть ответ в формате <a href="https://en.wikipedia.org/wiki/XML" class="external-link" target="_blank">XML</a>.
Вы можете поместить ваш XML-контент в строку, поместить её в `Response` и вернуть:
{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *}
## Примечания
Когда вы возвращаете объект `Response` напрямую, его данные не валидируются, не преобразуются (не сериализуются) и не документируются автоматически.
Но вы всё равно можете задокументировать это, как описано в [Дополнительные ответы в OpenAPI](additional-responses.md){.internal-link target=_blank}.
В следующих разделах вы увидите, как использовать/объявлять такие кастомные `Response`, при этом сохраняя автоматическое преобразование данных, документацию и т.д.

2
fastapi/__init__.py

@ -1,6 +1,6 @@
"""FastAPI framework, high performance, easy to learn, fast to code, ready for production"""
__version__ = "0.115.14"
__version__ = "0.116.0"
from starlette import status as status

23
pyproject.toml

@ -58,7 +58,26 @@ Changelog = "https://fastapi.tiangolo.com/release-notes/"
[project.optional-dependencies]
standard = [
"fastapi-cli[standard] >=0.0.5",
"fastapi-cli[standard] >=0.0.8",
# For the test client
"httpx >=0.23.0",
# For templates
"jinja2 >=3.1.5",
# For forms and file uploads
"python-multipart >=0.0.18",
# To validate email fields
"email-validator >=2.0.0",
# Uvicorn with uvloop
"uvicorn[standard] >=0.12.0",
# TODO: this should be part of some pydantic optional extra dependencies
# # Settings management
# "pydantic-settings >=2.0.0",
# # Extra Pydantic data types
# "pydantic-extra-types >=2.0.0",
]
standard-no-fastapi-cloud-cli = [
"fastapi-cli[standard-no-fastapi-cloud-cli] >=0.0.8",
# For the test client
"httpx >=0.23.0",
# For templates
@ -77,7 +96,7 @@ standard = [
]
all = [
"fastapi-cli[standard] >=0.0.5",
"fastapi-cli[standard] >=0.0.8",
# # For the test client
"httpx >=0.23.0",
# For templates

2
requirements-docs.txt

@ -8,7 +8,7 @@ pyyaml >=5.3.1,<7.0.0
# For Material for MkDocs, Chinese search
jieba==0.42.1
# For image processing by Material for MkDocs
pillow==11.1.0
pillow==11.3.0
# For image processing by Material for MkDocs
cairosvg==2.7.1
mkdocstrings[python]==0.26.1

Loading…
Cancel
Save