-
-
Notifications
You must be signed in to change notification settings - Fork 9.5k
🌐 Add Russian translation for docs/ru/docs/tutorial/middleware.md
#13412
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
alejsdev
merged 12 commits into
fastapi:master
from
alv2017:translate-ru-tutorial-middleware
Feb 28, 2025
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
1a38854
Russian translation added: docs/ru/docs/tutorial/middleware.md
alv2017 858b7eb
🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
pre-commit-ci[bot] 85b530a
Merge branch 'master' into translate-ru-tutorial-middleware
svlandeg cf513b9
adding suggested corrections from the reviews
alv2017 574925f
adding a correction due to applied updates.
alv2017 bb4077a
adding suggestions from the reviewers
alv2017 7492555
adding recommendations from the reviewer
alv2017 2ec9c79
fixing typos
alv2017 0d581e8
Applying corrections received from the reviewers.
alv2017 b3958a1
fixing typos
alv2017 f363260
fixing text decoration
alv2017 53aaa87
Merge branch 'master' into translate-ru-tutorial-middleware
alejsdev File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| # Middleware (Промежуточный слой) | ||
|
|
||
| Вы можете добавить промежуточный слой (middleware) в **FastAPI** приложение. | ||
|
|
||
| "Middleware" это функция, которая выполняется с каждым запросом до его обработки какой-либо конкретной *операцией пути*. | ||
| А также с каждым ответом перед его возвращением. | ||
|
|
||
|
|
||
| * Она принимает каждый поступающий **запрос**. | ||
| * Может что-то сделать с этим **запросом** или выполнить любой нужный код. | ||
| * Затем передает **запрос** для последующей обработки (какой-либо *операцией пути*). | ||
| * Получает **ответ** (от *операции пути*). | ||
| * Может что-то сделать с этим **ответом** или выполнить любой нужный код. | ||
| * И возвращает **ответ**. | ||
|
|
||
| /// note | Технические детали | ||
|
|
||
| Если у вас есть зависимости с `yield`, то код выхода (код после `yield`) будет выполняться *после* middleware. | ||
|
|
||
| Если у вас имеются некие фоновые задачи (см. документацию), то они будут запущены после middleware. | ||
|
|
||
| /// | ||
|
|
||
| ## Создание middleware | ||
|
|
||
| Для создания middleware используйте декоратор `@app.middleware("http")`. | ||
|
|
||
| Функция middleware получает: | ||
|
|
||
| * `request` (объект запроса). | ||
| * Функцию `call_next`, которая получает `request` в качестве параметра. | ||
| * Эта функция передаёт `request` соответствующей *операции пути*. | ||
| * Затем она возвращает ответ `response`, сгенерированный *операцией пути*. | ||
| * Также имеется возможность видоизменить `response`, перед тем как его вернуть. | ||
|
|
||
| {* ../../docs_src/middleware/tutorial001.py hl[8:9,11,14] *} | ||
|
|
||
| /// tip | Примечание | ||
|
|
||
| Имейте в виду, что можно добавлять свои собственные заголовки <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" class="external-link" target="_blank">при помощи префикса 'X-'</a>. | ||
|
|
||
| Если же вы хотите добавить собственные заголовки, которые клиент сможет увидеть в браузере, то вам потребуется добавить их в настройки CORS ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}), используя параметр `expose_headers`, см. документацию <a href="https://www.starlette.io/middleware/#corsmiddleware" class="external-link" target="_blank">Starlette's CORS docs</a>. | ||
|
|
||
| /// | ||
|
|
||
| /// note | Технические детали | ||
|
|
||
| Вы также можете использовать `from starlette.requests import Request`. | ||
|
|
||
| **FastAPI** предоставляет такой доступ для удобства разработчиков. Но, на самом деле, это `Request` из Starlette. | ||
|
|
||
| /// | ||
|
|
||
| ### До и после `response` | ||
|
|
||
| Вы можете добавить код, использующий `request` до передачи его какой-либо *операции пути*. | ||
|
|
||
| А также после формирования `response`, до того, как вы его вернёте. | ||
|
|
||
| Например, вы можете добавить собственный заголовок `X-Process-Time`, содержащий время в секундах, необходимое для обработки запроса и генерации ответа: | ||
|
|
||
| {* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *} | ||
|
|
||
| /// tip | Примечание | ||
|
|
||
| Мы используем <a href="https://docs.python.org/3/library/time.html#time.perf_counter" class="external-link" target="_blank">`time.perf_counter()`</a> вместо `time.time()` для обеспечения большей точности наших примеров. 🤓 | ||
|
alv2017 marked this conversation as resolved.
|
||
|
|
||
| /// | ||
|
|
||
| ## Другие middleware | ||
|
|
||
| О других middleware вы можете узнать больше в разделе [Advanced User Guide: Advanced Middleware](../advanced/middleware.md){.internal-link target=_blank}. | ||
|
|
||
| В следующем разделе вы можете прочитать, как настроить <abbr title="Cross-Origin Resource Sharing">CORS</abbr> с помощью middleware. | ||
|
alv2017 marked this conversation as resolved.
|
||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.