diff --git a/.github/actions/comment-docs-preview-in-pr/app/main.py b/.github/actions/comment-docs-preview-in-pr/app/main.py
index c9fb7cbbe..68914fdb9 100644
--- a/.github/actions/comment-docs-preview-in-pr/app/main.py
+++ b/.github/actions/comment-docs-preview-in-pr/app/main.py
@@ -1,7 +1,7 @@
import logging
import sys
from pathlib import Path
-from typing import Optional
+from typing import Union
import httpx
from github import Github
@@ -14,7 +14,7 @@ github_api = "https://api.github.com"
class Settings(BaseSettings):
github_repository: str
github_event_path: Path
- github_event_name: Optional[str] = None
+ github_event_name: Union[str, None] = None
input_token: SecretStr
input_deploy_url: str
@@ -42,7 +42,7 @@ if __name__ == "__main__":
except ValidationError as e:
logging.error(f"Error parsing event file: {e.errors()}")
sys.exit(0)
- use_pr: Optional[PullRequest] = None
+ use_pr: Union[PullRequest, None] = None
for pr in repo.get_pulls():
if pr.head.sha == event.workflow_run.head_commit.id:
use_pr = pr
diff --git a/.github/actions/notify-translations/app/main.py b/.github/actions/notify-translations/app/main.py
index 823685e00..d4ba0ecfc 100644
--- a/.github/actions/notify-translations/app/main.py
+++ b/.github/actions/notify-translations/app/main.py
@@ -2,7 +2,7 @@ import logging
import random
import time
from pathlib import Path
-from typing import Dict, Optional
+from typing import Dict, Union
import yaml
from github import Github
@@ -18,8 +18,8 @@ class Settings(BaseSettings):
github_repository: str
input_token: SecretStr
github_event_path: Path
- github_event_name: Optional[str] = None
- input_debug: Optional[bool] = False
+ github_event_name: Union[str, None] = None
+ input_debug: Union[bool, None] = False
class PartialGitHubEventIssue(BaseModel):
diff --git a/.github/actions/notify-translations/app/translations.yml b/.github/actions/notify-translations/app/translations.yml
index 0e5093f3a..d283ef9f7 100644
--- a/.github/actions/notify-translations/app/translations.yml
+++ b/.github/actions/notify-translations/app/translations.yml
@@ -8,10 +8,12 @@ uk: 1748
tr: 1892
fr: 1972
ko: 2017
-sq: 2041
+fa: 2041
pl: 3169
de: 3716
id: 3717
az: 3994
nl: 4701
uz: 4883
+sv: 5146
+he: 5157
diff --git a/.github/actions/people/app/main.py b/.github/actions/people/app/main.py
index 9de6fc250..cdf423b97 100644
--- a/.github/actions/people/app/main.py
+++ b/.github/actions/people/app/main.py
@@ -4,7 +4,7 @@ import sys
from collections import Counter, defaultdict
from datetime import datetime, timedelta, timezone
from pathlib import Path
-from typing import Container, DefaultDict, Dict, List, Optional, Set
+from typing import Container, DefaultDict, Dict, List, Set, Union
import httpx
import yaml
@@ -133,7 +133,7 @@ class Author(BaseModel):
class CommentsNode(BaseModel):
createdAt: datetime
- author: Optional[Author] = None
+ author: Union[Author, None] = None
class Comments(BaseModel):
@@ -142,7 +142,7 @@ class Comments(BaseModel):
class IssuesNode(BaseModel):
number: int
- author: Optional[Author] = None
+ author: Union[Author, None] = None
title: str
createdAt: datetime
state: str
@@ -179,7 +179,7 @@ class Labels(BaseModel):
class ReviewNode(BaseModel):
- author: Optional[Author] = None
+ author: Union[Author, None] = None
state: str
@@ -190,7 +190,7 @@ class Reviews(BaseModel):
class PullRequestNode(BaseModel):
number: int
labels: Labels
- author: Optional[Author] = None
+ author: Union[Author, None] = None
title: str
createdAt: datetime
state: str
@@ -260,19 +260,21 @@ class Settings(BaseSettings):
input_token: SecretStr
input_standard_token: SecretStr
github_repository: str
+ httpx_timeout: int = 30
def get_graphql_response(
- *, settings: Settings, query: str, after: Optional[str] = None
+ *, settings: Settings, query: str, after: Union[str, None] = None
):
headers = {"Authorization": f"token {settings.input_token.get_secret_value()}"}
variables = {"after": after}
response = httpx.post(
github_graphql_url,
headers=headers,
+ timeout=settings.httpx_timeout,
json={"query": query, "variables": variables, "operationName": "Q"},
)
- if not response.status_code == 200:
+ if response.status_code != 200:
logging.error(f"Response was not 200, after: {after}")
logging.error(response.text)
raise RuntimeError(response.text)
@@ -280,19 +282,19 @@ def get_graphql_response(
return data
-def get_graphql_issue_edges(*, settings: Settings, after: Optional[str] = None):
+def get_graphql_issue_edges(*, settings: Settings, after: Union[str, None] = None):
data = get_graphql_response(settings=settings, query=issues_query, after=after)
graphql_response = IssuesResponse.parse_obj(data)
return graphql_response.data.repository.issues.edges
-def get_graphql_pr_edges(*, settings: Settings, after: Optional[str] = None):
+def get_graphql_pr_edges(*, settings: Settings, after: Union[str, None] = None):
data = get_graphql_response(settings=settings, query=prs_query, after=after)
graphql_response = PRsResponse.parse_obj(data)
return graphql_response.data.repository.pullRequests.edges
-def get_graphql_sponsor_edges(*, settings: Settings, after: Optional[str] = None):
+def get_graphql_sponsor_edges(*, settings: Settings, after: Union[str, None] = None):
data = get_graphql_response(settings=settings, query=sponsors_query, after=after)
graphql_response = SponsorsResponse.parse_obj(data)
return graphql_response.data.user.sponsorshipsAsMaintainer.edges
diff --git a/.github/actions/watch-previews/app/main.py b/.github/actions/watch-previews/app/main.py
index 3b3520599..51285d02b 100644
--- a/.github/actions/watch-previews/app/main.py
+++ b/.github/actions/watch-previews/app/main.py
@@ -1,7 +1,7 @@
import logging
from datetime import datetime
from pathlib import Path
-from typing import List, Optional
+from typing import List, Union
import httpx
from github import Github
@@ -16,7 +16,7 @@ class Settings(BaseSettings):
input_token: SecretStr
github_repository: str
github_event_path: Path
- github_event_name: Optional[str] = None
+ github_event_name: Union[str, None] = None
class Artifact(BaseModel):
@@ -74,7 +74,7 @@ if __name__ == "__main__":
logging.info(f"Docs preview was notified: {notified}")
if not notified:
artifact_name = f"docs-zip-{commit}"
- use_artifact: Optional[Artifact] = None
+ use_artifact: Union[Artifact, None] = None
for artifact in artifacts_response.artifacts:
if artifact.name == artifact_name:
use_artifact = artifact
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
new file mode 100644
index 000000000..cd972a0ba
--- /dev/null
+++ b/.github/dependabot.yml
@@ -0,0 +1,16 @@
+version: 2
+updates:
+ # GitHub Actions
+ - package-ecosystem: "github-actions"
+ directory: "/"
+ schedule:
+ interval: "daily"
+ commit-message:
+ prefix: ⬆
+ # Python
+ - package-ecosystem: "pip"
+ directory: "/"
+ schedule:
+ interval: "daily"
+ commit-message:
+ prefix: ⬆
diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml
index 505d66f9f..0d666b82a 100644
--- a/.github/workflows/build-docs.yml
+++ b/.github/workflows/build-docs.yml
@@ -13,12 +13,12 @@ jobs:
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
- name: Set up Python
- uses: actions/setup-python@v2
+ uses: actions/setup-python@v4
with:
python-version: "3.7"
- - uses: actions/cache@v2
+ - uses: actions/cache@v3
id: cache
with:
path: ${{ env.pythonLocation }}
@@ -36,12 +36,12 @@ jobs:
run: python3.7 ./scripts/docs.py build-all
- name: Zip docs
run: bash ./scripts/zip-docs.sh
- - uses: actions/upload-artifact@v2
+ - uses: actions/upload-artifact@v3
with:
name: docs-zip
path: ./docs.zip
- name: Deploy to Netlify
- uses: nwtgck/actions-netlify@v1.1.5
+ uses: nwtgck/actions-netlify@v1.2.3
with:
publish-dir: './site'
production-branch: master
diff --git a/.github/workflows/latest-changes.yml b/.github/workflows/latest-changes.yml
index 5783c993a..4aa8475b6 100644
--- a/.github/workflows/latest-changes.yml
+++ b/.github/workflows/latest-changes.yml
@@ -20,7 +20,7 @@ jobs:
latest-changes:
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
with:
# To allow latest-changes to commit to master
token: ${{ secrets.ACTIONS_TOKEN }}
diff --git a/.github/workflows/notify-translations.yml b/.github/workflows/notify-translations.yml
index 7e414ab95..2fcb7595e 100644
--- a/.github/workflows/notify-translations.yml
+++ b/.github/workflows/notify-translations.yml
@@ -9,7 +9,7 @@ jobs:
notify-translations:
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
# Allow debugging with tmate
- name: Setup tmate session
uses: mxschmitt/action-tmate@v3
diff --git a/.github/workflows/people.yml b/.github/workflows/people.yml
index 2004ee7b3..4b47b4072 100644
--- a/.github/workflows/people.yml
+++ b/.github/workflows/people.yml
@@ -14,7 +14,7 @@ jobs:
fastapi-people:
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
# Allow debugging with tmate
- name: Setup tmate session
uses: mxschmitt/action-tmate@v3
diff --git a/.github/workflows/preview-docs.yml b/.github/workflows/preview-docs.yml
index 104c2677f..d42b08543 100644
--- a/.github/workflows/preview-docs.yml
+++ b/.github/workflows/preview-docs.yml
@@ -10,9 +10,9 @@ jobs:
preview-docs:
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
- name: Download Artifact Docs
- uses: dawidd6/action-download-artifact@v2.9.0
+ uses: dawidd6/action-download-artifact@v2.23.0
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
workflow: build-docs.yml
@@ -25,7 +25,7 @@ jobs:
rm -f docs.zip
- name: Deploy to Netlify
id: netlify
- uses: nwtgck/actions-netlify@v1.1.5
+ uses: nwtgck/actions-netlify@v1.2.3
with:
publish-dir: './site'
production-deploy: false
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
index 9dde4e066..02846cefd 100644
--- a/.github/workflows/publish.yml
+++ b/.github/workflows/publish.yml
@@ -13,12 +13,12 @@ jobs:
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
- name: Set up Python
- uses: actions/setup-python@v2
+ uses: actions/setup-python@v4
with:
python-version: "3.6"
- - uses: actions/cache@v2
+ - uses: actions/cache@v3
id: cache
with:
path: ${{ env.pythonLocation }}
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index f0a82344e..14dc141d9 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -16,12 +16,12 @@ jobs:
fail-fast: false
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v3
- name: Set up Python
- uses: actions/setup-python@v2
+ uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
- - uses: actions/cache@v2
+ - uses: actions/cache@v3
id: cache
with:
path: ${{ env.pythonLocation }}
@@ -38,4 +38,4 @@ jobs:
- name: Test
run: bash scripts/test.sh
- name: Upload coverage
- uses: codecov/codecov-action@v2
+ uses: codecov/codecov-action@v3
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 5c278571e..237feb083 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -2,7 +2,7 @@
# See https://pre-commit.com/hooks.html for more hooks
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
- rev: v4.2.0
+ rev: v4.3.0
hooks:
- id: check-added-large-files
- id: check-toml
@@ -12,14 +12,14 @@ repos:
- id: end-of-file-fixer
- id: trailing-whitespace
- repo: https://github.com/asottile/pyupgrade
- rev: v2.32.1
+ rev: v2.37.3
hooks:
- id: pyupgrade
args:
- --py3-plus
- --keep-runtime-typing
- repo: https://github.com/myint/autoflake
- rev: v1.4
+ rev: v1.5.1
hooks:
- id: autoflake
args:
@@ -43,7 +43,7 @@ repos:
name: isort (pyi)
types: [pyi]
- repo: https://github.com/psf/black
- rev: 22.3.0
+ rev: 22.6.0
hooks:
- id: black
ci:
diff --git a/README.md b/README.md
index 5e9e97a2a..bc00d9ed9 100644
--- a/README.md
+++ b/README.md
@@ -32,7 +32,6 @@ FastAPI is a modern, fast (high-performance), web framework for building APIs wi
The key features are:
* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance).
-
* **Fast to code**: Increase the speed to develop features by about 200% to 300%. *
* **Fewer bugs**: Reduce about 40% of human (developer) induced errors. *
* **Intuitive**: Great editor support. Completion everywhere. Less time debugging.
@@ -47,10 +46,10 @@ The key features are:
-
+
+
-
-
+
@@ -132,7 +131,7 @@ $ pip install fastapi
-You will also need an ASGI server, for production such as Uvicorn or Hypercorn.
+You will also need an ASGI server, for production such as Uvicorn or Hypercorn.
-Then it's your turn, you place your order of 2 very fancy burgers 🍔 for your crush 😍 and you.
+Then it's your turn, you place your order of 2 very fancy burgers for your crush and you. 🍔🍔
-You pay 💸.
+
-The cashier 💁 says something to the cook in the kitchen 👨🍳 so they know they have to prepare your burgers 🍔 (even though they are currently preparing the ones for the previous clients).
+The cashier says something to the cook in the kitchen so they know they have to prepare your burgers (even though they are currently preparing the ones for the previous clients).
-The cashier 💁 gives you the number of your turn.
+
-While you are waiting, you go with your crush 😍 and pick a table, you sit and talk with your crush 😍 for a long time (as your burgers are very fancy and take some time to prepare ✨🍔✨).
+You pay. 💸
-As you are sitting at the table with your crush 😍, while you wait for the burgers 🍔, you can spend that time admiring how awesome, cute and smart your crush is ✨😍✨.
+The cashier gives you the number of your turn.
-While waiting and talking to your crush 😍, from time to time, you check the number displayed on the counter to see if it's your turn already.
+
-Then at some point, it finally is your turn. You go to the counter, get your burgers 🍔 and come back to the table.
+While you are waiting, you go with your crush and pick a table, you sit and talk with your crush for a long time (as your burgers are very fancy and take some time to prepare).
-You and your crush 😍 eat the burgers 🍔 and have a nice time ✨.
+As you are sitting at the table with your crush, while you wait for the burgers, you can spend that time admiring how awesome, cute and smart your crush is ✨😍✨.
+
+
+
+While waiting and talking to your crush, from time to time, you check the number displayed on the counter to see if it's your turn already.
+
+Then at some point, it finally is your turn. You go to the counter, get your burgers and come back to the table.
+
+
+
+You and your crush eat the burgers and have a nice time. ✨
+
+
+
+!!! info
+ Beautiful illustrations by Ketrina Thompson. 🎨
---
Imagine you are the computer / program 🤖 in that story.
-While you are at the line, you are just idle 😴, waiting for your turn, not doing anything very "productive". But the line is fast because the cashier 💁 is only taking the orders (not preparing them), so that's fine.
+While you are at the line, you are just idle 😴, waiting for your turn, not doing anything very "productive". But the line is fast because the cashier is only taking the orders (not preparing them), so that's fine.
-Then, when it's your turn, you do actual "productive" work 🤓, you process the menu, decide what you want, get your crush's 😍 choice, pay 💸, check that you give the correct bill or card, check that you are charged correctly, check that the order has the correct items, etc.
+Then, when it's your turn, you do actual "productive" work, you process the menu, decide what you want, get your crush's choice, pay, check that you give the correct bill or card, check that you are charged correctly, check that the order has the correct items, etc.
-But then, even though you still don't have your burgers 🍔, your work with the cashier 💁 is "on pause" ⏸, because you have to wait 🕙 for your burgers to be ready.
+But then, even though you still don't have your burgers, your work with the cashier is "on pause" ⏸, because you have to wait 🕙 for your burgers to be ready.
-But as you go away from the counter and sit at the table with a number for your turn, you can switch 🔀 your attention to your crush 😍, and "work" ⏯ 🤓 on that. Then you are again doing something very "productive" 🤓, as is flirting with your crush 😍.
+But as you go away from the counter and sit at the table with a number for your turn, you can switch 🔀 your attention to your crush, and "work" ⏯ 🤓 on that. Then you are again doing something very "productive" as is flirting with your crush 😍.
-Then the cashier 💁 says "I'm finished with doing the burgers" 🍔 by putting your number on the counter's display, but you don't jump like crazy immediately when the displayed number changes to your turn number. You know no one will steal your burgers 🍔 because you have the number of your turn, and they have theirs.
+Then the cashier 💁 says "I'm finished with doing the burgers" by putting your number on the counter's display, but you don't jump like crazy immediately when the displayed number changes to your turn number. You know no one will steal your burgers because you have the number of your turn, and they have theirs.
-So you wait for your crush 😍 to finish the story (finish the current work ⏯ / task being processed 🤓), smile gently and say that you are going for the burgers ⏸.
+So you wait for your crush to finish the story (finish the current work ⏯ / task being processed 🤓), smile gently and say that you are going for the burgers ⏸.
-Then you go to the counter 🔀, to the initial task that is now finished ⏯, pick the burgers 🍔, say thanks and take them to the table. That finishes that step / task of interaction with the counter ⏹. That in turn, creates a new task, of "eating burgers" 🔀 ⏯, but the previous one of "getting burgers" is finished ⏹.
+Then you go to the counter 🔀, to the initial task that is now finished ⏯, pick the burgers, say thanks and take them to the table. That finishes that step / task of interaction with the counter ⏹. That in turn, creates a new task, of "eating burgers" 🔀 ⏯, but the previous one of "getting burgers" is finished ⏹.
### Parallel Burgers
Now let's imagine these aren't "Concurrent Burgers", but "Parallel Burgers".
-You go with your crush 😍 to get parallel fast food 🍔.
+You go with your crush to get parallel fast food.
-You stand in line while several (let's say 8) cashiers that at the same time are cooks 👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳 take the orders from the people in front of you.
+You stand in line while several (let's say 8) cashiers that at the same time are cooks take the orders from the people in front of you.
-Everyone before you is waiting 🕙 for their burgers 🍔 to be ready before leaving the counter because each of the 8 cashiers goes and prepares the burger right away before getting the next order.
+Everyone before you is waiting for their burgers to be ready before leaving the counter because each of the 8 cashiers goes and prepares the burger right away before getting the next order.
-Then it's finally your turn, you place your order of 2 very fancy burgers 🍔 for your crush 😍 and you.
+
+
+Then it's finally your turn, you place your order of 2 very fancy burgers for your crush and you.
You pay 💸.
-The cashier goes to the kitchen 👨🍳.
+
-You wait, standing in front of the counter 🕙, so that no one else takes your burgers 🍔 before you do, as there are no numbers for turns.
+The cashier goes to the kitchen.
-As you and your crush 😍 are busy not letting anyone get in front of you and take your burgers whenever they arrive 🕙, you cannot pay attention to your crush 😞.
+You wait, standing in front of the counter 🕙, so that no one else takes your burgers before you do, as there are no numbers for turns.
-This is "synchronous" work, you are "synchronized" with the cashier/cook 👨🍳. You have to wait 🕙 and be there at the exact moment that the cashier/cook 👨🍳 finishes the burgers 🍔 and gives them to you, or otherwise, someone else might take them.
+
-Then your cashier/cook 👨🍳 finally comes back with your burgers 🍔, after a long time waiting 🕙 there in front of the counter.
+As you and your crush are busy not letting anyone get in front of you and take your burgers whenever they arrive, you cannot pay attention to your crush. 😞
-You take your burgers 🍔 and go to the table with your crush 😍.
+This is "synchronous" work, you are "synchronized" with the cashier/cook 👨🍳. You have to wait 🕙 and be there at the exact moment that the cashier/cook 👨🍳 finishes the burgers and gives them to you, or otherwise, someone else might take them.
-You just eat them, and you are done 🍔 ⏹.
+
-There was not much talk or flirting as most of the time was spent waiting 🕙 in front of the counter 😞.
+Then your cashier/cook 👨🍳 finally comes back with your burgers, after a long time waiting 🕙 there in front of the counter.
+
+
+
+You take your burgers and go to the table with your crush.
+
+You just eat them, and you are done. ⏹
+
+
+
+There was not much talk or flirting as most of the time was spent waiting 🕙 in front of the counter. 😞
+
+!!! info
+ Beautiful illustrations by Ketrina Thompson. 🎨
---
-In this scenario of the parallel burgers, you are a computer / program 🤖 with two processors (you and your crush 😍), both waiting 🕙 and dedicating their attention ⏯ to be "waiting on the counter" 🕙 for a long time.
+In this scenario of the parallel burgers, you are a computer / program 🤖 with two processors (you and your crush), both waiting 🕙 and dedicating their attention ⏯ to be "waiting on the counter" 🕙 for a long time.
-The fast food store has 8 processors (cashiers/cooks) 👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳. While the concurrent burgers store might have had only 2 (one cashier and one cook) 💁 👨🍳.
+The fast food store has 8 processors (cashiers/cooks). While the concurrent burgers store might have had only 2 (one cashier and one cook).
-But still, the final experience is not the best 😞.
+But still, the final experience is not the best. 😞
---
-This would be the parallel equivalent story for burgers 🍔.
+This would be the parallel equivalent story for burgers. 🍔
For a more "real life" example of this, imagine a bank.
@@ -208,11 +238,7 @@ This "waiting" 🕙 is measured in microseconds, but still, summing it all, it's
That's why it makes a lot of sense to use asynchronous ⏸🔀⏯ code for web APIs.
-Most of the existing popular Python frameworks (including Flask and Django) were created before the new asynchronous features in Python existed. So, the ways they can be deployed support parallel execution and an older form of asynchronous execution that is not as powerful as the new capabilities.
-
-Even though the main specification for asynchronous web Python (ASGI) was developed at Django, to add support for WebSockets.
-
-That kind of asynchronicity is what made NodeJS popular (even though NodeJS is not parallel) and that's the strength of Go as a programming language.
+This kind of asynchronicity is what made NodeJS popular (even though NodeJS is not parallel) and that's the strength of Go as a programming language.
And that's the same level of performance you get with **FastAPI**.
@@ -238,7 +264,7 @@ You could have turns as in the burgers example, first the living room, then the
It would take the same amount of time to finish with or without turns (concurrency) and you would have done the same amount of work.
-But in this case, if you could bring the 8 ex-cashier/cooks/now-cleaners 👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳👩🍳👨🍳, and each one of them (plus you) could take a zone of the house to clean it, you could do all the work in **parallel**, with the extra help, and finish much sooner.
+But in this case, if you could bring the 8 ex-cashier/cooks/now-cleaners, and each one of them (plus you) could take a zone of the house to clean it, you could do all the work in **parallel**, with the extra help, and finish much sooner.
In this scenario, each one of the cleaners (including you) would be a processor, doing their part of the job.
@@ -371,7 +397,7 @@ All that is what powers FastAPI (through Starlette) and what makes it have such
These are very technical details of how **FastAPI** works underneath.
- If you have quite some technical knowledge (co-routines, threads, blocking, etc) and are curious about how FastAPI handles `async def` vs normal `def`, go ahead.
+ If you have quite some technical knowledge (co-routines, threads, blocking, etc.) and are curious about how FastAPI handles `async def` vs normal `def`, go ahead.
### Path operation functions
diff --git a/docs/en/docs/contributing.md b/docs/en/docs/contributing.md
index 648c472fe..ca51c6e82 100644
--- a/docs/en/docs/contributing.md
+++ b/docs/en/docs/contributing.md
@@ -84,7 +84,17 @@ To check it worked, use:
If it shows the `pip` binary at `env/bin/pip` then it worked. 🎉
+Make sure you have the latest pip version on your virtual environment to avoid errors on the next steps:
+- FastAPI framework, high performance, easy to learn, fast to code, ready for production + فریمورک FastAPI، کارایی بالا، یادگیری آسان، کدنویسی سریع، آماده برای استفاده در محیط پروداکشن
-
-
+
+
@@ -25,103 +21,99 @@
---
-**Documentation**: https://fastapi.tiangolo.com
+**مستندات**: https://fastapi.tiangolo.com
-**Source Code**: https://github.com/tiangolo/fastapi
+**کد منبع**: https://github.com/tiangolo/fastapi
---
+FastAPI یک وب فریمورک مدرن و سریع (با کارایی بالا) برای ایجاد APIهای متنوع (وب، وبسوکت و غبره) با زبان پایتون نسخه +۳.۶ است. این فریمورک با رعایت کامل راهنمای نوع داده (Type Hint) ایجاد شده است.
-FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.
+ویژگیهای کلیدی این فریمورک عبارتند از:
-The key features are:
+* **سرعت**: کارایی بسیار بالا و قابل مقایسه با **NodeJS** و **Go** (با تشکر از Starlette و Pydantic). [یکی از سریعترین فریمورکهای پایتونی موجود](#performance).
-* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance).
+* **کدنویسی سریع**: افزایش ۲۰۰ تا ۳۰۰ درصدی سرعت توسعه فابلیتهای جدید. *
+* **باگ کمتر**: کاهش ۴۰ درصدی خطاهای انسانی (برنامهنویسی). *
+* **غریزی**: پشتیبانی فوقالعاده در محیطهای توسعه یکپارچه (IDE). تکمیل در همه بخشهای کد. کاهش زمان رفع باگ.
+* **آسان**: طراحی شده برای یادگیری و استفاده آسان. کاهش زمان مورد نیاز برای مراجعه به مستندات.
+* **کوچک**: کاهش تکرار در کد. چندین قابلیت برای هر پارامتر (منظور پارامترهای ورودی تابع هندلر میباشد، به بخش خلاصه در همین صفحه مراجعه شود). باگ کمتر.
+* **استوار**: ایجاد کدی آماده برای استفاده در محیط پروداکشن و تولید خودکار مستندات تعاملی
+* **مبتنی بر استانداردها**: مبتنی بر (و منطبق با) استانداردهای متن باز مربوط به API: OpenAPI (سوگر سابق) و JSON Schema.
-* **Fast to code**: Increase the speed to develop features by about 200% to 300%. *
-* **Fewer bugs**: Reduce about 40% of human (developer) induced errors. *
-* **Intuitive**: Great editor support. Completion everywhere. Less time debugging.
-* **Easy**: Designed to be easy to use and learn. Less time reading docs.
-* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.
-* **Robust**: Get production-ready code. With automatic interactive documentation.
-* **Standards-based**: Based on (and fully compatible with) the open standards for APIs: OpenAPI (previously known as Swagger) and JSON Schema.
+* تخمینها بر اساس تستهای انجام شده در یک تیم توسعه داخلی که مشغول ایجاد برنامههای کاربردی واقعی بودند صورت گرفته است.
-* estimation based on tests on an internal development team, building production applications.
-
-## Sponsors
+## اسپانسرهای طلایی
{% if sponsors %}
{% for sponsor in sponsors.gold -%}
-
-{% endfor -%}
-{%- for sponsor in sponsors.silver -%}
-
+
{% endfor %}
{% endif %}
-Other sponsors
+دیگر اسپانسرها
-## Opinions
+## نظر دیگران در مورد FastAPI
-"_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._"
+
async def...async def... نیز استفاده کنیدuvicorn main:app --reload...uvicorn main:app --reload...ujson - for faster JSON "parsing".
-* email_validator - for email validation.
+* ujson - برای "تجزیه (parse)" سریعتر JSON .
+* email_validator - برای اعتبارسنجی آدرسهای ایمیل.
-Used by Starlette:
+استفاده شده توسط Starlette:
-* requests - Required if you want to use the `TestClient`.
-* jinja2 - Required if you want to use the default template configuration.
-* python-multipart - Required if you want to support form "parsing", with `request.form()`.
-* itsdangerous - Required for `SessionMiddleware` support.
-* pyyaml - Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI).
-* ujson - Required if you want to use `UJSONResponse`.
+* requests - در صورتی که میخواهید از `TestClient` استفاده کنید.
+* aiofiles - در صورتی که میخواهید از `FileResponse` و `StaticFiles` استفاده کنید.
+* jinja2 - در صورتی که بخواهید از پیکربندی پیشفرض برای قالبها استفاده کنید.
+* python-multipart - در صورتی که بخواهید با استفاده از `request.form()` از قابلیت "تجزیه (parse)" فرم استفاده کنید.
+* itsdangerous - در صورتی که بخواید از `SessionMiddleware` پشتیبانی کنید.
+* pyyaml - برای پشتیبانی `SchemaGenerator` در Starlet (به احتمال زیاد برای کار کردن با FastAPI به آن نیازی پیدا نمیکنید.).
+* graphene - در صورتی که از `GraphQLApp` پشتیبانی میکنید.
+* ujson - در صورتی که بخواهید از `UJSONResponse` استفاده کنید.
-Used by FastAPI / Starlette:
+استفاده شده توسط FastAPI / Starlette:
-* uvicorn - for the server that loads and serves your application.
-* orjson - Required if you want to use `ORJSONResponse`.
+* uvicorn - برای سرور اجرا کننده برنامه وب.
+* orjson - در صورتی که بخواهید از `ORJSONResponse` استفاده کنید.
-You can install all of these with `pip install "fastapi[all]"`.
+میتوان همه این موارد را با استفاده از دستور `pip install fastapi[all]`. به صورت یکجا نصب کرد.
-## License
+## لایسنس
-This project is licensed under the terms of the MIT license.
+این پروژه مشمول قوانین و مقررات لایسنس MIT است.
diff --git a/docs/fa/mkdocs.yml b/docs/fa/mkdocs.yml
index 3966a6026..7c2fe5eab 100644
--- a/docs/fa/mkdocs.yml
+++ b/docs/fa/mkdocs.yml
@@ -5,14 +5,14 @@ theme:
name: material
custom_dir: overrides
palette:
- - media: "(prefers-color-scheme: light)"
+ - media: '(prefers-color-scheme: light)'
scheme: default
primary: teal
accent: amber
toggle:
icon: material/lightbulb
name: Switch to light mode
- - media: "(prefers-color-scheme: dark)"
+ - media: '(prefers-color-scheme: dark)'
scheme: slate
primary: teal
accent: amber
@@ -44,6 +44,7 @@ nav:
- es: /es/
- fa: /fa/
- fr: /fr/
+ - he: /he/
- id: /id/
- it: /it/
- ja: /ja/
@@ -53,6 +54,7 @@ nav:
- pt: /pt/
- ru: /ru/
- sq: /sq/
+ - sv: /sv/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -73,6 +75,8 @@ markdown_extensions:
format: !!python/name:pymdownx.superfences.fence_code_format ''
- pymdownx.tabbed:
alternate_style: true
+- attr_list
+- md_in_html
extra:
analytics:
provider: google
@@ -105,6 +109,8 @@ extra:
name: fa
- link: /fr/
name: fr - français
+ - link: /he/
+ name: he
- link: /id/
name: id
- link: /it/
@@ -123,6 +129,8 @@ extra:
name: ru - русский язык
- link: /sq/
name: sq - shqip
+ - link: /sv/
+ name: sv - svenska
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/fr/docs/async.md b/docs/fr/docs/async.md
index 71c28b703..db88c4663 100644
--- a/docs/fr/docs/async.md
+++ b/docs/fr/docs/async.md
@@ -205,10 +205,6 @@ Cette "attente" 🕙 se mesure en microsecondes, mais tout de même, en cumulé
C'est pourquoi il est logique d'utiliser du code asynchrone ⏸🔀⏯ pour des APIs web.
-La plupart des frameworks Python existants (y compris Flask et Django) ont été créés avant que les nouvelles fonctionnalités asynchrones de Python n'existent. Donc, les façons dont ils peuvent être déployés supportent l'exécution parallèle et une ancienne forme d'exécution asynchrone qui n'est pas aussi puissante que les nouvelles fonctionnalités de Python.
-
-Et cela, bien que les spécifications principales du web asynchrone en Python (ou ASGI) ont été développées chez Django, pour ajouter le support des WebSockets.
-
Ce type d'asynchronicité est ce qui a rendu NodeJS populaire (bien que NodeJS ne soit pas parallèle) et c'est la force du Go en tant que langage de programmation.
Et c'est le même niveau de performance que celui obtenu avec **FastAPI**.
diff --git a/docs/fr/docs/deployment/index.md b/docs/fr/docs/deployment/index.md
new file mode 100644
index 000000000..e855adfa3
--- /dev/null
+++ b/docs/fr/docs/deployment/index.md
@@ -0,0 +1,28 @@
+# Déploiement - Intro
+
+Le déploiement d'une application **FastAPI** est relativement simple.
+
+## Que signifie le déploiement
+
+**Déployer** une application signifie effectuer les étapes nécessaires pour la rendre **disponible pour les
+utilisateurs**.
+
+Pour une **API Web**, cela implique normalement de la placer sur une **machine distante**, avec un **programme serveur**
+qui offre de bonnes performances, une bonne stabilité, _etc._, afin que vos **utilisateurs** puissent **accéder** à
+l'application efficacement et sans interruption ni problème.
+
+Ceci contraste avec les étapes de **développement**, où vous êtes constamment en train de modifier le code, de le casser
+et de le réparer, d'arrêter et de redémarrer le serveur de développement, _etc._
+
+## Stratégies de déploiement
+
+Il existe plusieurs façons de procéder, en fonction de votre cas d'utilisation spécifique et des outils que vous
+utilisez.
+
+Vous pouvez **déployer un serveur** vous-même en utilisant une combinaison d'outils, vous pouvez utiliser un **service
+cloud** qui fait une partie du travail pour vous, ou encore d'autres options possibles.
+
+Je vais vous montrer certains des principaux concepts que vous devriez probablement avoir à l'esprit lors du déploiement
+d'une application **FastAPI** (bien que la plupart de ces concepts s'appliquent à tout autre type d'application web).
+
+Vous verrez plus de détails à avoir en tête et certaines des techniques pour le faire dans les sections suivantes. ✨
diff --git a/docs/fr/docs/history-design-future.md b/docs/fr/docs/history-design-future.md
new file mode 100644
index 000000000..b77664be6
--- /dev/null
+++ b/docs/fr/docs/history-design-future.md
@@ -0,0 +1,79 @@
+# Histoire, conception et avenir
+
+Il y a quelque temps, un utilisateur de **FastAPI** a demandé :
+
+> Quelle est l'histoire de ce projet ? Il semble être sorti de nulle part et est devenu génial en quelques semaines [...].
+
+Voici un petit bout de cette histoire.
+
+## Alternatives
+
+Je crée des API avec des exigences complexes depuis plusieurs années (Machine Learning, systèmes distribués, jobs asynchrones, bases de données NoSQL, etc), en dirigeant plusieurs équipes de développeurs.
+
+Dans ce cadre, j'ai dû étudier, tester et utiliser de nombreuses alternatives.
+
+L'histoire de **FastAPI** est en grande partie l'histoire de ses prédécesseurs.
+
+Comme dit dans la section [Alternatives](alternatives.md){.internal-link target=\_blank} :
+
++ +**FastAPI** n'existerait pas sans le travail antérieur d'autres personnes. + +Il y a eu de nombreux outils créés auparavant qui ont contribué à inspirer sa création. + +J'ai évité la création d'un nouveau framework pendant plusieurs années. J'ai d'abord essayé de résoudre toutes les fonctionnalités couvertes par **FastAPI** en utilisant de nombreux frameworks, plug-ins et outils différents. + +Mais à un moment donné, il n'y avait pas d'autre option que de créer quelque chose qui offre toutes ces fonctionnalités, en prenant les meilleures idées des outils précédents, et en les combinant de la meilleure façon possible, en utilisant des fonctionnalités du langage qui n'étaient même pas disponibles auparavant (annotations de type pour Python 3.6+). + ++ +## Recherche + +En utilisant toutes les alternatives précédentes, j'ai eu la chance d'apprendre de toutes, de prendre des idées, et de les combiner de la meilleure façon que j'ai pu trouver pour moi-même et les équipes de développeurs avec lesquelles j'ai travaillé. + +Par exemple, il était clair que l'idéal était de se baser sur les annotations de type Python standard. + +De plus, la meilleure approche était d'utiliser des normes déjà existantes. + +Ainsi, avant même de commencer à coder **FastAPI**, j'ai passé plusieurs mois à étudier les spécifications d'OpenAPI, JSON Schema, OAuth2, etc. Comprendre leurs relations, leurs similarités et leurs différences. + +## Conception + +Ensuite, j'ai passé du temps à concevoir l'"API" de développeur que je voulais avoir en tant qu'utilisateur (en tant que développeur utilisant FastAPI). + +J'ai testé plusieurs idées dans les éditeurs Python les plus populaires : PyCharm, VS Code, les éditeurs basés sur Jedi. + +D'après la dernière Enquête Développeurs Python, cela couvre environ 80% des utilisateurs. + +Cela signifie que **FastAPI** a été spécifiquement testé avec les éditeurs utilisés par 80% des développeurs Python. Et comme la plupart des autres éditeurs ont tendance à fonctionner de façon similaire, tous ses avantages devraient fonctionner pour pratiquement tous les éditeurs. + +Ainsi, j'ai pu trouver les meilleurs moyens de réduire autant que possible la duplication du code, d'avoir la complétion partout, les contrôles de type et d'erreur, etc. + +Le tout de manière à offrir la meilleure expérience de développement à tous les développeurs. + +## Exigences + +Après avoir testé plusieurs alternatives, j'ai décidé que j'allais utiliser **Pydantic** pour ses avantages. + +J'y ai ensuite contribué, pour le rendre entièrement compatible avec JSON Schema, pour supporter différentes manières de définir les déclarations de contraintes, et pour améliorer le support des éditeurs (vérifications de type, autocomplétion) sur la base des tests effectués dans plusieurs éditeurs. + +Pendant le développement, j'ai également contribué à **Starlette**, l'autre exigence clé. + +## Développement + +Au moment où j'ai commencé à créer **FastAPI** lui-même, la plupart des pièces étaient déjà en place, la conception était définie, les exigences et les outils étaient prêts, et la connaissance des normes et des spécifications était claire et fraîche. + +## Futur + +À ce stade, il est déjà clair que **FastAPI** et ses idées sont utiles pour de nombreuses personnes. + +Elle a été préférée aux solutions précédentes parce qu'elle convient mieux à de nombreux cas d'utilisation. + +De nombreux développeurs et équipes dépendent déjà de **FastAPI** pour leurs projets (y compris moi et mon équipe). + +Mais il y a encore de nombreuses améliorations et fonctionnalités à venir. + +**FastAPI** a un grand avenir devant lui. + +Et [votre aide](help-fastapi.md){.internal-link target=\_blank} est grandement appréciée. diff --git a/docs/fr/docs/index.md b/docs/fr/docs/index.md index f713ee96b..1307c063b 100644 --- a/docs/fr/docs/index.md +++ b/docs/fr/docs/index.md @@ -135,7 +135,7 @@ You will also need an ASGI server, for production such as ```console -$ pip install uvicorn[standard] +$ pip install "uvicorn[standard]" ---> 100% ``` diff --git a/docs/fr/mkdocs.yml b/docs/fr/mkdocs.yml index bf0d2b21c..6bed7be73 100644 --- a/docs/fr/mkdocs.yml +++ b/docs/fr/mkdocs.yml @@ -5,14 +5,14 @@ theme: name: material custom_dir: overrides palette: - - media: "(prefers-color-scheme: light)" + - media: '(prefers-color-scheme: light)' scheme: default primary: teal accent: amber toggle: icon: material/lightbulb name: Switch to light mode - - media: "(prefers-color-scheme: dark)" + - media: '(prefers-color-scheme: dark)' scheme: slate primary: teal accent: amber @@ -44,6 +44,7 @@ nav: - es: /es/ - fa: /fa/ - fr: /fr/ + - he: /he/ - id: /id/ - it: /it/ - ja: /ja/ @@ -53,6 +54,7 @@ nav: - pt: /pt/ - ru: /ru/ - sq: /sq/ + - sv: /sv/ - tr: /tr/ - uk: /uk/ - zh: /zh/ @@ -67,9 +69,11 @@ nav: - tutorial/background-tasks.md - async.md - Déploiement: + - deployment/index.md - deployment/docker.md - project-generation.md - alternatives.md +- history-design-future.md - external-links.md markdown_extensions: - toc: @@ -88,6 +92,8 @@ markdown_extensions: format: !!python/name:pymdownx.superfences.fence_code_format '' - pymdownx.tabbed: alternate_style: true +- attr_list +- md_in_html extra: analytics: provider: google @@ -120,6 +126,8 @@ extra: name: fa - link: /fr/ name: fr - français + - link: /he/ + name: he - link: /id/ name: id - link: /it/ @@ -138,6 +146,8 @@ extra: name: ru - русский язык - link: /sq/ name: sq - shqip + - link: /sv/ + name: sv - svenska - link: /tr/ name: tr - Türkçe - link: /uk/ diff --git a/docs/he/docs/index.md b/docs/he/docs/index.md new file mode 100644 index 000000000..fa63d8cb7 --- /dev/null +++ b/docs/he/docs/index.md @@ -0,0 +1,464 @@ + +
+ תשתית FastAPI, ביצועים גבוהים, קלה ללמידה, מהירה לתכנות, מוכנה לסביבת ייצור +
+ + +--- + +**תיעוד**: https://fastapi.tiangolo.com + +**קוד**: https://github.com/tiangolo/fastapi + +--- + +FastAPI היא תשתית רשת מודרנית ומהירה (ביצועים גבוהים) לבניית ממשקי תכנות יישומים (API) עם פייתון 3.6+ בהתבסס על רמזי טיפוסים סטנדרטיים. + +תכונות המפתח הן: + +- **מהירה**: ביצועים גבוהים מאוד, בקנה אחד עם NodeJS ו - Go (תודות ל - Starlette ו - Pydantic). [אחת מתשתיות הפייתון המהירות ביותר](#performance). + +- **מהירה לתכנות**: הגבירו את מהירות פיתוח התכונות החדשות בכ - %200 עד %300. \* +- **פחות שגיאות**: מנעו כ - %40 משגיאות אנוש (מפתחים). \* +- **אינטואיטיבית**: תמיכת עורך מעולה. השלמה בכל מקום. פחות זמן ניפוי שגיאות. +- **קלה**: מתוכננת להיות קלה לשימוש וללמידה. פחות זמן קריאת תיעוד. +- **קצרה**: מזערו שכפול קוד. מספר תכונות מכל הכרזת פרמטר. פחות שגיאות. +- **חסונה**: קבלו קוד מוכן לסביבת ייצור. עם תיעוד אינטרקטיבי אוטומטי. +- **מבוססת סטנדרטים**: מבוססת על (ותואמת לחלוטין ל -) הסטדנרטים הפתוחים לממשקי תכנות יישומים: OpenAPI (ידועים לשעבר כ - Swagger) ו - JSON Schema. + +\* הערכה מבוססת על בדיקות של צוות פיתוח פנימי שבונה אפליקציות בסביבת ייצור. + +## נותני חסות + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} +async def...uvicorn main:app --reload...app = FastAPI().
+- --reload: גרמו לשרת להתאתחל לאחר שינויים בקוד. עשו זאת רק בסביבת פיתוח.
+
+/items/{item_id}.
+- שני ה _נתיבים_ מקבלים _בקשות_ `GET` (ידועות גם כ*מתודות* HTTP).
+- ה _נתיב_ /items/{item_id} כולל \*פרמטר נתיב\_ `item_id` שאמור להיות `int`.
+- ה _נתיב_ /items/{item_id} \*פרמטר שאילתא\_ אופציונלי `q`.
+
+### תיעוד API אינטרקטיבי
+
+כעת פנו לכתובת http://127.0.0.1:8000/docs.
+
+אתם תראו את התיעוד האוטומטי (מסופק על ידי Swagger UI):
+
+
+
+### תיעוד אלטרנטיבי
+
+כעת פנו לכתובת http://127.0.0.1:8000/redoc.
+
+אתם תראו תיעוד אלטרנטיבי (מסופק על ידי ReDoc):
+
+
+
+## שדרוג לדוגמא
+
+כעת ערכו את הקובץ `main.py` כך שיוכל לקבל גוף מבקשת `PUT`.
+
+הגדירו את הגוף בעזרת רמזי טיפוסים סטנדרטיים, הודות ל - `Pydantic`.
+
+```Python hl_lines="4 9-12 25-27"
+from typing import Union
+
+from fastapi import FastAPI
+from pydantic import BaseModel
+
+app = FastAPI()
+
+
+class Item(BaseModel):
+ name: str
+ price: float
+ is_offer: Union[bool, None] = None
+
+
+@app.get("/")
+def read_root():
+ return {"Hello": "World"}
+
+
+@app.get("/items/{item_id}")
+def read_item(item_id: int, q: Union[str, None] = None):
+ return {"item_id": item_id, "q": q}
+
+
+@app.put("/items/{item_id}")
+def update_item(item_id: int, item: Item):
+ return {"item_name": item.name, "item_id": item_id}
+```
+
+השרת אמול להתאתחל אוטומטית (מאחר והוספתם --reload לפקודת `uvicorn` שלמעלה).
+
+### שדרוג התיעוד האינטרקטיבי
+
+כעת פנו לכתובת http://127.0.0.1:8000/docs.
+
+- התיעוד האוטומטי יתעדכן, כולל הגוף החדש:
+
+
+
+- לחצו על הכפתור "Try it out", הוא יאפשר לכם למלא את הפרמטרים ולעבוד ישירות מול ה - API.
+
+
+
+- אחר כך לחצו על הכפתור "Execute", האתר יתקשר עם ה - API שלכם, ישלח את הפרמטרים, ישיג את התוצאות ואז יראה אותן על המסך:
+
+
+
+### שדרוג התיעוד האלטרנטיבי
+
+כעת פנו לכתובת http://127.0.0.1:8000/redoc.
+
+- התיעוד האלטרנטיבי גם יראה את פרמטר השאילתא והגוף החדשים.
+
+
+
+### סיכום
+
+לסיכום, אתם מכריזים ** פעם אחת** על טיפוסי הפרמטרים, גוף וכו' כפרמטרים לפונקציה.
+
+אתם עושים את זה עם טיפוסי פייתון מודרניים.
+
+אתם לא צריכים ללמוד תחביר חדש, מתודות או מחלקות של ספרייה ספיציפית, וכו'
+
+רק **פייתון 3.6+** סטנדרטי.
+
+לדוגמא, ל - `int`:
+
+```Python
+item_id: int
+```
+
+או למודל `Item` מורכב יותר:
+
+```Python
+item: Item
+```
+
+...ועם הכרזת הטיפוס האחת הזו אתם מקבלים:
+
+- תמיכת עורך, כולל:
+ - השלמות.
+ - בדיקת טיפוסים.
+- אימות מידע:
+ - שגיאות ברורות ואטומטיות כאשר מוכנס מידע לא חוקי .
+ - אימות אפילו לאובייקטי JSON מקוננים.
+- המרה של מידע קלט: המרה של מידע שמגיע מהרשת למידע וטיפוסים של פייתון. קורא מ:
+ - JSON.
+ - פרמטרי נתיב.
+ - פרמטרי שאילתא.
+ - עוגיות.
+ - כותרות.
+ - טפסים.
+ - קבצים.
+- המרה של מידע פלט: המרה של מידע וטיפוסים מפייתון למידע רשת (כ - JSON):
+ - המירו טיפוסי פייתון (`str`, `int`, `float`, `bool`, `list`, etc).
+ - עצמי `datetime`.
+ - עצמי `UUID`.
+ - מודלי בסיסי נתונים.
+ - ...ורבים אחרים.
+- תיעוד API אוטומטי ואינטרקטיבית כולל שתי אלטרנטיבות לממשק המשתמש:
+ - Swagger UI.
+ - ReDoc.
+
+---
+
+בחזרה לדוגמאת הקוד הקודמת, **FastAPI** ידאג:
+
+- לאמת שיש `item_id` בנתיב בבקשות `GET` ו - `PUT`.
+- לאמת שה - `item_id` הוא מטיפוס `int` בבקשות `GET` ו - `PUT`.
+ - אם הוא לא, הלקוח יראה שגיאה ברורה ושימושית.
+- לבדוק האם קיים פרמטר שאילתא בשם `q` (קרי `http://127.0.0.1:8000/items/foo?q=somequery`) לבקשות `GET`.
+ - מאחר והפרמטר `q` מוגדר עם = None, הוא אופציונלי.
+ - לולא ה - `None` הוא היה חובה (כמו הגוף במקרה של `PUT`).
+- לבקשות `PUT` לנתיב /items/{item_id}, לקרוא את גוף הבקשה כ - JSON:
+ - לאמת שהוא כולל את מאפיין החובה `name` שאמור להיות מטיפוס `str`.
+ - לאמת שהוא כולל את מאפיין החובה `price` שחייב להיות מטיפוס `float`.
+ - לבדוק האם הוא כולל את מאפיין הרשות `is_offer` שאמור להיות מטיפוס `bool`, אם הוא נמצא.
+ - כל זה יעבוד גם לאובייקט JSON מקונן.
+- להמיר מ - JSON ול- JSON אוטומטית.
+- לתעד הכל באמצעות OpenAPI, תיעוד שבו יוכלו להשתמש:
+ - מערכות תיעוד אינטרקטיביות.
+ - מערכות ייצור קוד אוטומטיות, להרבה שפות.
+- לספק ישירות שתי מערכות תיעוד רשתיות.
+
+---
+
+רק גרדנו את קצה הקרחון, אבל כבר יש לכם רעיון של איך הכל עובד.
+
+נסו לשנות את השורה:
+
+```Python
+ return {"item_name": item.name, "item_id": item_id}
+```
+
+...מ:
+
+```Python
+ ... "item_name": item.name ...
+```
+
+...ל:
+
+```Python
+ ... "item_price": item.price ...
+```
+
+...וראו איך העורך שלכם משלים את המאפיינים ויודע את הטיפוסים שלהם:
+
+
+
+לדוגמא יותר שלמה שכוללת עוד תכונות, ראו את המדריך - למשתמש.
+
+**התראת ספוילרים**: המדריך - למשתמש כולל:
+
+- הכרזה על **פרמטרים** ממקורות אחרים ושונים כגון: **כותרות**, **עוגיות**, **טפסים** ו - **קבצים**.
+- איך לקבוע **מגבלות אימות** בעזרת `maximum_length` או `regex`.
+- דרך חזקה וקלה להשתמש ב**הזרקת תלויות**.
+- אבטחה והתאמתות, כולל תמיכה ב - **OAuth2** עם **JWT** והתאמתות **HTTP Basic**.
+- טכניקות מתקדמות (אבל קלות באותה מידה) להכרזת אובייקטי JSON מקוננים (תודות ל - Pydantic).
+- אינטרקציה עם **GraphQL** דרך Strawberry וספריות אחרות.
+- תכונות נוספות רבות (תודות ל - Starlette) כגון:
+ - **WebSockets**
+ - בדיקות קלות במיוחד מבוססות על `requests` ו - `pytest`
+ - **CORS**
+ - **Cookie Sessions**
+ - ...ועוד.
+
+## ביצועים
+
+בדיקות עצמאיות של TechEmpower הראו שאפליקציות **FastAPI** שרצות תחת Uvicorn הן מתשתיות הפייתון המהירות ביותר, רק מתחת ל - Starlette ו - Uvicorn עצמן (ש - FastAPI מבוססת עליהן). (\*)
+
+כדי להבין עוד על הנושא, ראו את הפרק Benchmarks.
+
+## תלויות אופציונליות
+
+בשימוש Pydantic:
+
+- ujson - "פרסור" JSON.
+- email_validator - לאימות כתובות אימייל.
+
+בשימוש Starlette:
+
+- requests - דרוש אם ברצונכם להשתמש ב - `TestClient`.
+- jinja2 - דרוש אם ברצונכם להשתמש בברירת המחדל של תצורת הטמפלייטים.
+- python-multipart - דרוש אם ברצונכם לתמוך ב "פרסור" טפסים, באצמעות request.form().
+- itsdangerous - דרוש אם ברצונכם להשתמש ב - `SessionMiddleware`.
+- pyyaml - דרוש אם ברצונכם להשתמש ב - `SchemaGenerator` של Starlette (כנראה שאתם לא צריכים את זה עם FastAPI).
+- ujson - דרוש אם ברצונכם להשתמש ב - `UJSONResponse`.
+
+בשימוש FastAPI / Starlette:
+
+- uvicorn - לשרת שטוען ומגיש את האפליקציה שלכם.
+- orjson - דרוש אם ברצונכם להשתמש ב - `ORJSONResponse`.
+
+תוכלו להתקין את כל אלו באמצעות pip install "fastapi[all]".
+
+## רשיון
+
+הפרויקט הזה הוא תחת התנאים של רשיון MIT.
diff --git a/docs/he/mkdocs.yml b/docs/he/mkdocs.yml
new file mode 100644
index 000000000..3279099b5
--- /dev/null
+++ b/docs/he/mkdocs.yml
@@ -0,0 +1,145 @@
+site_name: FastAPI
+site_description: FastAPI framework, high performance, easy to learn, fast to code, ready for production
+site_url: https://fastapi.tiangolo.com/he/
+theme:
+ name: material
+ custom_dir: overrides
+ palette:
+ - media: '(prefers-color-scheme: light)'
+ scheme: default
+ primary: teal
+ accent: amber
+ toggle:
+ icon: material/lightbulb
+ name: Switch to light mode
+ - media: '(prefers-color-scheme: dark)'
+ scheme: slate
+ primary: teal
+ accent: amber
+ toggle:
+ icon: material/lightbulb-outline
+ name: Switch to dark mode
+ features:
+ - search.suggest
+ - search.highlight
+ - content.tabs.link
+ icon:
+ repo: fontawesome/brands/github-alt
+ logo: https://fastapi.tiangolo.com/img/icon-white.svg
+ favicon: https://fastapi.tiangolo.com/img/favicon.png
+ language: he
+repo_name: tiangolo/fastapi
+repo_url: https://github.com/tiangolo/fastapi
+edit_uri: ''
+plugins:
+- search
+- markdownextradata:
+ data: data
+nav:
+- FastAPI: index.md
+- Languages:
+ - en: /
+ - az: /az/
+ - de: /de/
+ - es: /es/
+ - fa: /fa/
+ - fr: /fr/
+ - he: /he/
+ - id: /id/
+ - it: /it/
+ - ja: /ja/
+ - ko: /ko/
+ - nl: /nl/
+ - pl: /pl/
+ - pt: /pt/
+ - ru: /ru/
+ - sq: /sq/
+ - sv: /sv/
+ - tr: /tr/
+ - uk: /uk/
+ - zh: /zh/
+markdown_extensions:
+- toc:
+ permalink: true
+- markdown.extensions.codehilite:
+ guess_lang: false
+- mdx_include:
+ base_path: docs
+- admonition
+- codehilite
+- extra
+- pymdownx.superfences:
+ custom_fences:
+ - name: mermaid
+ class: mermaid
+ format: !!python/name:pymdownx.superfences.fence_code_format ''
+- pymdownx.tabbed:
+ alternate_style: true
+- attr_list
+- md_in_html
+extra:
+ analytics:
+ provider: google
+ property: UA-133183413-1
+ social:
+ - icon: fontawesome/brands/github-alt
+ link: https://github.com/tiangolo/fastapi
+ - icon: fontawesome/brands/discord
+ link: https://discord.gg/VQjSZaeJmf
+ - icon: fontawesome/brands/twitter
+ link: https://twitter.com/fastapi
+ - icon: fontawesome/brands/linkedin
+ link: https://www.linkedin.com/in/tiangolo
+ - icon: fontawesome/brands/dev
+ link: https://dev.to/tiangolo
+ - icon: fontawesome/brands/medium
+ link: https://medium.com/@tiangolo
+ - icon: fontawesome/solid/globe
+ link: https://tiangolo.com
+ alternate:
+ - link: /
+ name: en - English
+ - link: /az/
+ name: az
+ - link: /de/
+ name: de
+ - link: /es/
+ name: es - español
+ - link: /fa/
+ name: fa
+ - link: /fr/
+ name: fr - français
+ - link: /he/
+ name: he
+ - link: /id/
+ name: id
+ - link: /it/
+ name: it - italiano
+ - link: /ja/
+ name: ja - 日本語
+ - link: /ko/
+ name: ko - 한국어
+ - link: /nl/
+ name: nl
+ - link: /pl/
+ name: pl
+ - link: /pt/
+ name: pt - português
+ - link: /ru/
+ name: ru - русский язык
+ - link: /sq/
+ name: sq - shqip
+ - link: /sv/
+ name: sv - svenska
+ - link: /tr/
+ name: tr - Türkçe
+ - link: /uk/
+ name: uk - українська мова
+ - link: /zh/
+ name: zh - 汉语
+extra_css:
+- https://fastapi.tiangolo.com/css/termynal.css
+- https://fastapi.tiangolo.com/css/custom.css
+extra_javascript:
+- https://fastapi.tiangolo.com/js/termynal.js
+- https://fastapi.tiangolo.com/js/custom.js
diff --git a/docs/he/overrides/.gitignore b/docs/he/overrides/.gitignore
new file mode 100644
index 000000000..e69de29bb
diff --git a/docs/id/docs/index.md b/docs/id/docs/index.md
index 0bb7b55e3..041e0b754 100644
--- a/docs/id/docs/index.md
+++ b/docs/id/docs/index.md
@@ -135,7 +135,7 @@ You will also need an ASGI server, for production such as
```console
-$ pip install uvicorn[standard]
+$ pip install "uvicorn[standard]"
---> 100%
```
diff --git a/docs/id/docs/tutorial/index.md b/docs/id/docs/tutorial/index.md
new file mode 100644
index 000000000..8fec3c087
--- /dev/null
+++ b/docs/id/docs/tutorial/index.md
@@ -0,0 +1,80 @@
+# Tutorial - Pedoman Pengguna - Pengenalan
+
+Tutorial ini menunjukan cara menggunakan ***FastAPI*** dengan semua fitur-fiturnya, tahap demi tahap.
+
+Setiap bagian dibangun secara bertahap dari bagian sebelumnya, tetapi terstruktur untuk memisahkan banyak topik, sehingga kamu bisa secara langsung menuju ke topik spesifik untuk menyelesaikan kebutuhan API tertentu.
+
+Ini juga dibangun untuk digunakan sebagai referensi yang akan datang.
+
+Sehingga kamu dapat kembali lagi dan mencari apa yang kamu butuhkan dengan tepat.
+
+## Jalankan kode
+
+Semua blok-blok kode dapat dicopy dan digunakan langsung (Mereka semua sebenarnya adalah file python yang sudah teruji).
+
+Untuk menjalankan setiap contoh, copy kode ke file `main.py`, dan jalankan `uvicorn` dengan:
+
+awaitを使用していないので、私たちは`async def`ではなく通常の`def`で関数を宣言する必要があります。
+
+また、Couchbaseは単一の`Bucket`オブジェクトを複数のスレッドで使用しないことを推奨していますので、単に直接Bucketを取得して関数に渡すことが出来ます。
+
+```Python hl_lines="49-53"
+{!../../../docs_src/nosql_databases/tutorial001.py!}
+```
+
+## まとめ
+
+他のサードパーティ製のNoSQLデータベースを利用する場合でも、そのデータベースの標準ライブラリを利用するだけで利用できます。
+
+他の外部ツール、システム、APIについても同じことが言えます。
diff --git a/docs/ja/docs/deployment/manually.md b/docs/ja/docs/deployment/manually.md
index dd4b568bd..67010a66f 100644
--- a/docs/ja/docs/deployment/manually.md
+++ b/docs/ja/docs/deployment/manually.md
@@ -11,7 +11,7 @@
get
+
+!!! info "`@decorator` Info"
+ Składnia `@something` jest w Pythonie nazywana "dekoratorem".
+
+ Umieszczasz to na szczycie funkcji. Jak ładną ozdobną czapkę (chyba stąd wzięła się nazwa).
+
+ "Dekorator" przyjmuje funkcję znajdującą się poniżej jego i coś z nią robi.
+
+ W naszym przypadku dekorator mówi **FastAPI**, że poniższa funkcja odpowiada **ścieżce** `/` z **operacją** `get`.
+
+ Jest to "**dekorator operacji na ścieżce**".
+
+Możesz również użyć innej operacji:
+
+* `@app.post()`
+* `@app.put()`
+* `@app.delete()`
+
+Oraz tych bardziej egzotycznych:
+
+* `@app.options()`
+* `@app.head()`
+* `@app.patch()`
+* `@app.trace()`
+
+!!! tip
+ Możesz dowolnie używać każdej operacji (metody HTTP).
+
+ **FastAPI** nie narzuca żadnego konkretnego znaczenia.
+
+ Informacje tutaj są przedstawione jako wskazówka, a nie wymóg.
+
+ Na przykład, używając GraphQL, normalnie wykonujesz wszystkie akcje używając tylko operacji `POST`.
+
+### Krok 4: zdefiniuj **funkcję obsługującą ścieżkę**
+
+To jest nasza "**funkcja obsługująca ścieżkę**":
+
+* **ścieżka**: to `/`.
+* **operacja**: to `get`.
+* **funkcja**: to funkcja poniżej "dekoratora" (poniżej `@app.get("/")`).
+
+```Python hl_lines="7"
+{!../../../docs_src/first_steps/tutorial001.py!}
+```
+
+Jest to funkcja Python.
+
+Zostanie ona wywołana przez **FastAPI** za każdym razem, gdy otrzyma żądanie do adresu URL "`/`" przy użyciu operacji `GET`.
+
+W tym przypadku jest to funkcja "asynchroniczna".
+
+---
+
+Możesz również zdefiniować to jako normalną funkcję zamiast `async def`:
+
+```Python hl_lines="7"
+{!../../../docs_src/first_steps/tutorial003.py!}
+```
+
+!!! note
+ Jeśli nie znasz różnicy, sprawdź [Async: *"In a hurry?"*](/async/#in-a-hurry){.internal-link target=_blank}.
+
+### Krok 5: zwróć zawartość
+
+```Python hl_lines="8"
+{!../../../docs_src/first_steps/tutorial001.py!}
+```
+
+Możesz zwrócić `dict`, `list`, pojedynczą wartość jako `str`, `int`, itp.
+
+Możesz również zwrócić modele Pydantic (więcej o tym później).
+
+Istnieje wiele innych obiektów i modeli, które zostaną automatycznie skonwertowane do formatu JSON (w tym ORM itp.). Spróbuj użyć swoich ulubionych, jest bardzo prawdopodobne, że są już obsługiwane.
+
+## Podsumowanie
+
+* Zaimportuj `FastAPI`.
+* Stwórz instancję `app`.
+* Dodaj **dekorator operacji na ścieżce** (taki jak `@app.get("/")`).
+* Napisz **funkcję obsługującą ścieżkę** (taką jak `def root(): ...` powyżej).
+* Uruchom serwer deweloperski (`uvicorn main:app --reload`).
diff --git a/docs/pl/mkdocs.yml b/docs/pl/mkdocs.yml
index 0c3d100e7..1cd129420 100644
--- a/docs/pl/mkdocs.yml
+++ b/docs/pl/mkdocs.yml
@@ -5,14 +5,14 @@ theme:
name: material
custom_dir: overrides
palette:
- - media: "(prefers-color-scheme: light)"
+ - media: '(prefers-color-scheme: light)'
scheme: default
primary: teal
accent: amber
toggle:
icon: material/lightbulb
name: Switch to light mode
- - media: "(prefers-color-scheme: dark)"
+ - media: '(prefers-color-scheme: dark)'
scheme: slate
primary: teal
accent: amber
@@ -44,6 +44,7 @@ nav:
- es: /es/
- fa: /fa/
- fr: /fr/
+ - he: /he/
- id: /id/
- it: /it/
- ja: /ja/
@@ -53,11 +54,13 @@ nav:
- pt: /pt/
- ru: /ru/
- sq: /sq/
+ - sv: /sv/
- tr: /tr/
- uk: /uk/
- zh: /zh/
- Samouczek:
- tutorial/index.md
+ - tutorial/first-steps.md
markdown_extensions:
- toc:
permalink: true
@@ -75,6 +78,8 @@ markdown_extensions:
format: !!python/name:pymdownx.superfences.fence_code_format ''
- pymdownx.tabbed:
alternate_style: true
+- attr_list
+- md_in_html
extra:
analytics:
provider: google
@@ -107,6 +112,8 @@ extra:
name: fa
- link: /fr/
name: fr - français
+ - link: /he/
+ name: he
- link: /id/
name: id
- link: /it/
@@ -125,6 +132,8 @@ extra:
name: ru - русский язык
- link: /sq/
name: sq - shqip
+ - link: /sv/
+ name: sv - svenska
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/pt/docs/deployment.md b/docs/pt/docs/deployment.md
index cd820cbd3..2272467fd 100644
--- a/docs/pt/docs/deployment.md
+++ b/docs/pt/docs/deployment.md
@@ -336,7 +336,7 @@ Você apenas precisa instalar um servidor ASGI compatível como:
+
+!!! marque o "botão de Autorizar!"
+ Você já tem um novo "botão de autorizar!".
+
+ E seu *path operation* tem um pequeno cadeado no canto superior direito que você pode clicar.
+
+E se você clicar, você terá um pequeno formulário de autorização para digitar o `username` e `senha` (e outros campos opcionais):
+
+
+
+!!! nota
+ Não importa o que você digita no formulário, não vai funcionar ainda. Mas nós vamos chegar lá.
+
+Claro que este não é o frontend para os usuários finais, mas é uma ótima ferramenta automática para documentar interativamente toda sua API.
+
+Pode ser usado pelo time de frontend (que pode ser você no caso).
+
+Pode ser usado por aplicações e sistemas third party (de terceiros).
+
+E também pode ser usada por você mesmo, para debugar, checar e testar a mesma aplicação.
+
+## O Fluxo da `senha`
+
+Agora vamos voltar um pouco e entender o que é isso tudo.
+
+O "fluxo" da `senha` é um dos caminhos ("fluxos") definidos no OAuth2, para lidar com a segurança e autenticação.
+
+OAuth2 foi projetado para que o backend ou a API pudesse ser independente do servidor que autentica o usuário.
+
+Mas nesse caso, a mesma aplicação **FastAPI** irá lidar com a API e a autenticação.
+
+Então, vamos rever de um ponto de vista simplificado:
+
+* O usuário digita o `username` e a `senha` no frontend e aperta `Enter`.
+* O frontend (rodando no browser do usuário) manda o `username` e a `senha` para uma URL específica na sua API (declarada com `tokenUrl="token"`).
+* A API checa aquele `username` e `senha`, e responde com um "token" (nós não implementamos nada disso ainda).
+ * Um "token" é apenas uma string com algum conteúdo que nós podemos utilizar mais tarde para verificar o usuário.
+ * Normalmente, um token é definido para expirar depois de um tempo.
+ * Então, o usuário terá que se logar de novo depois de um tempo.
+ * E se o token for roubado, o risco é menor. Não é como se fosse uma chave permanente que vai funcionar para sempre (na maioria dos casos).
+ * O frontend armazena aquele token temporariamente em algum lugar.
+ * O usuário clica no frontend para ir à outra seção daquele frontend do aplicativo web.
+ * O frontend precisa buscar mais dados daquela API.
+ * Mas precisa de autenticação para aquele endpoint em específico.
+ * Então, para autenticar com nossa API, ele manda um header de `Autorização` com o valor `Bearer` mais o token.
+ * Se o token contém `foobar`, o conteúdo do header de `Autorização` será: `Bearer foobar`.
+
+## **FastAPI**'s `OAuth2PasswordBearer`
+
+**FastAPI** fornece várias ferramentas, em diferentes níveis de abstração, para implementar esses recursos de segurança.
+
+Neste exemplo, nós vamos usar o **OAuth2** com o fluxo de **Senha**, usando um token **Bearer**. Fazemos isso usando a classe `OAuth2PasswordBearer`.
+
+!!! informação
+ Um token "bearer" não é a única opção.
+
+ Mas é a melhor no nosso caso.
+
+ E talvez seja a melhor para a maioria dos casos, a não ser que você seja um especialista em OAuth2 e saiba exatamente o porquê de existir outras opções que se adequam melhor às suas necessidades.
+
+ Nesse caso, **FastAPI** também fornece as ferramentas para construir.
+
+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!}
+```
+
+!!! dica
+ Esse `tokenUrl="token"` se refere a uma URL relativa que nós não criamos ainda. Como é uma URL relativa, é equivalente a `./token`.
+
+ Porque estamos usando uma URL relativa, se sua API estava localizada em `https://example.com/`, então irá referir-se à `https://example.com/token`. Mas se sua API estava localizada em `https://example.com/api/v1/`, então irá referir-se à `https://example.com/api/v1/token`.
+
+ Usar uma URL relativa é importante para garantir que sua aplicação continue funcionando, mesmo em um uso avançado tipo [Atrás de um Proxy](../../advanced/behind-a-proxy.md){.internal-link target=_blank}.
+
+Esse parâmetro não cria um endpoint / *path operation*, mas declara que a URL `/token` vai ser aquela que o client deve usar para obter o token. Essa informação é usada no OpenAPI, e depois na API Interativa de documentação de sistemas.
+
+Em breve também criaremos o atual path operation.
+
+!!! informação
+ Se você é um "Pythonista" muito rigoroso, você pode não gostar do estilo do nome do parâmetro `tokenUrl` em vez de `token_url`.
+
+ Isso ocorre porque está utilizando o mesmo nome que está nas especificações do OpenAPI. Então, se você precisa investigar mais sobre qualquer um desses esquemas de segurança, você pode simplesmente copiar e colar para encontrar mais informações sobre isso.
+
+A variável `oauth2_scheme` é um instância de `OAuth2PasswordBearer`, mas também é um "callable".
+
+Pode ser chamada de:
+
+```Python
+oauth2_scheme(some, parameters)
+```
+
+Então, pode ser usado com `Depends`.
+
+## Use-o
+
+Agora você pode passar aquele `oauth2_scheme` em uma dependência com `Depends`.
+
+```Python hl_lines="10"
+{!../../../docs_src/security/tutorial001.py!}
+```
+
+Esse dependência vai fornecer uma `str` que é atribuído ao parâmetro `token da *função do path operation*
+
+A **FastAPI** saberá que pode usar essa dependência para definir um "esquema de segurança" no esquema da OpenAPI (e na documentação da API automática).
+
+!!! informação "Detalhes técnicos"
+ **FastAPI** saberá que pode usar a classe `OAuth2PasswordBearer` (declarada na dependência) para definir o esquema de segurança na OpenAPI porque herda de `fastapi.security.oauth2.OAuth2`, que por sua vez herda de `fastapi.security.base.Securitybase`.
+
+ Todos os utilitários de segurança que se integram com OpenAPI (e na documentação da API automática) herdam de `SecurityBase`, é assim que **FastAPI** pode saber como integrá-los no OpenAPI.
+
+## O que ele faz
+
+Ele irá e olhará na requisição para aquele header de `Autorização`, verificará se o valor é `Bearer` mais algum token, e vai retornar o token como uma `str`
+
+Se ele não ver o header de `Autorização` ou o valor não tem um token `Bearer`, vai responder com um código de erro 401 (`UNAUTHORIZED`) diretamente.
+
+Você nem precisa verificar se o token existe para retornar um erro. Você pode ter certeza de que se a sua função for executada, ela terá um `str` nesse token.
+
+Você já pode experimentar na documentação interativa:
+
+
+
+Não estamos verificando a validade do token ainda, mas isso já é um começo
+
+## Recapitulando
+
+Então, em apenas 3 ou 4 linhas extras, você já tem alguma forma primitiva de segurança.
diff --git a/docs/pt/mkdocs.yml b/docs/pt/mkdocs.yml
index 2bb0b568d..59ee3cc88 100644
--- a/docs/pt/mkdocs.yml
+++ b/docs/pt/mkdocs.yml
@@ -5,14 +5,14 @@ theme:
name: material
custom_dir: overrides
palette:
- - media: "(prefers-color-scheme: light)"
+ - media: '(prefers-color-scheme: light)'
scheme: default
primary: teal
accent: amber
toggle:
icon: material/lightbulb
name: Switch to light mode
- - media: "(prefers-color-scheme: dark)"
+ - media: '(prefers-color-scheme: dark)'
scheme: slate
primary: teal
accent: amber
@@ -44,6 +44,7 @@ nav:
- es: /es/
- fa: /fa/
- fr: /fr/
+ - he: /he/
- id: /id/
- it: /it/
- ja: /ja/
@@ -53,6 +54,7 @@ nav:
- pt: /pt/
- ru: /ru/
- sq: /sq/
+ - sv: /sv/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -62,13 +64,17 @@ nav:
- tutorial/index.md
- tutorial/first-steps.md
- tutorial/path-params.md
+ - tutorial/query-params.md
- tutorial/body.md
- tutorial/body-fields.md
- tutorial/extra-data-types.md
- tutorial/query-params-str-validations.md
- tutorial/cookie-params.md
+ - tutorial/header-params.md
+ - tutorial/handling-errors.md
- Segurança:
- tutorial/security/index.md
+ - tutorial/background-tasks.md
- Guia de Usuário Avançado:
- advanced/index.md
- Implantação:
@@ -98,6 +104,8 @@ markdown_extensions:
format: !!python/name:pymdownx.superfences.fence_code_format ''
- pymdownx.tabbed:
alternate_style: true
+- attr_list
+- md_in_html
extra:
analytics:
provider: google
@@ -130,6 +138,8 @@ extra:
name: fa
- link: /fr/
name: fr - français
+ - link: /he/
+ name: he
- link: /id/
name: id
- link: /it/
@@ -148,6 +158,8 @@ extra:
name: ru - русский язык
- link: /sq/
name: sq - shqip
+ - link: /sv/
+ name: sv - svenska
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/ru/docs/deployment/versions.md b/docs/ru/docs/deployment/versions.md
new file mode 100644
index 000000000..91b9038e9
--- /dev/null
+++ b/docs/ru/docs/deployment/versions.md
@@ -0,0 +1,87 @@
+# О версиях FastAPI
+
+**FastAPI** уже используется в продакшене во многих приложениях и системах. Покрытие тестами поддерживается на уровне 100%. Однако его разработка все еще продолжается.
+
+Часто добавляются новые функции, регулярно исправляются баги, код продолжает постоянно совершенствоваться.
+
+По указанным причинам текущие версии до сих пор `0.x.x`. Это говорит о том, что каждая версия может содержать обратно несовместимые изменения, следуя соглашению о Семантическом Версионировании.
+
+Уже сейчас вы можете создавать приложения в продакшене, используя **FastAPI** (и скорее всего так и делаете), главное убедиться в том, что вы используете версию, которая корректно работает с вашим кодом.
+
+## Закрепите вашу версию `fastapi`
+
+Первым делом вам следует "закрепить" конкретную последнюю используемую версию **FastAPI**, которая корректно работает с вашим приложением.
+
+Например, в своём приложении вы используете версию `0.45.0`.
+
+Если вы используете файл `requirements.txt`, вы можете указать версию следующим способом:
+
+```txt
+fastapi==0.45.0
+```
+
+это означает, что вы будете использовать именно версию `0.45.0`.
+
+Или вы можете закрепить версию следующим способом:
+
+```txt
+fastapi>=0.45.0,<0.46.0
+```
+
+это значит, что вы используете версии `0.45.0` или выше, но меньше чем `0.46.0`. Например, версия `0.45.2` все еще будет подходить.
+
+Если вы используете любой другой инструмент для управления зависимостями, например Poetry, Pipenv или др., у них у всех имеется способ определения специфической версии для ваших пакетов.
+
+## Доступные версии
+
+Вы можете посмотреть доступные версии (например, проверить последнюю на данный момент) в [примечаниях к выпуску](../release-notes.md){.internal-link target=_blank}.
+
+## О версиях
+
+Следуя соглашению о Семантическом Версионировании, любые версии ниже `1.0.0` потенциально могут добавить обратно несовместимые изменения.
+
+FastAPI следует соглашению в том, что любые изменения "ПАТЧ"-версии предназначены для исправления багов и внесения обратно совместимых изменений.
+
+!!! Подсказка
+ "ПАТЧ" - это последнее число. Например, в `0.2.3`, ПАТЧ-версия - это `3`.
+
+Итак, вы можете закрепить версию следующим образом:
+
+```txt
+fastapi>=0.45.0,<0.46.0
+```
+
+Обратно несовместимые изменения и новые функции добавляются в "МИНОРНЫЕ" версии.
+
+!!! Подсказка
+ "МИНОРНАЯ" версия - это число в середине. Например, в `0.2.3` МИНОРНАЯ версия - это `2`.
+
+## Обновление версий FastAPI
+
+Вам следует добавить тесты для вашего приложения.
+
+С помощью **FastAPI** это очень просто (благодаря Starlette), см. документацию: [Тестирование](../tutorial/testing.md){.internal-link target=_blank}
+
+После создания тестов вы можете обновить свою версию **FastAPI** до более новой. После этого следует убедиться, что ваш код работает корректно, запустив тесты.
+
+Если все работает корректно, или после внесения необходимых изменений все ваши тесты проходят, только тогда вы можете закрепить вашу новую версию `fastapi`.
+
+## О Starlette
+
+Не следует закреплять версию `starlette`.
+
+Разные версии **FastAPI** будут использовать более новые версии Starlette.
+
+Так что решение об используемой версии Starlette, вы можете оставить **FastAPI**.
+
+## О Pydantic
+
+Pydantic включает свои собственные тесты для **FastAPI**, так что новые версии Pydantic (выше `1.0.0`) всегда совместимы с FastAPI.
+
+Вы можете закрепить любую версию Pydantic, которая вам подходит, выше `1.0.0` и ниже `2.0.0`.
+
+Например:
+
+```txt
+pydantic>=1.2.0,<2.0.0
+```
diff --git a/docs/ru/docs/features.md b/docs/ru/docs/features.md
new file mode 100644
index 000000000..0cec4eee2
--- /dev/null
+++ b/docs/ru/docs/features.md
@@ -0,0 +1,203 @@
+# Основные свойства
+
+## Основные свойства FastAPI
+
+**FastAPI** предлагает вам следующее:
+
+### Использование открытых стандартов
+
+* OpenAPI для создания API, включая объявления операций пути, параметров, тела запроса, безопасности и т.д.
+
+
+* Автоматическое документирование моделей данных в соответствии с JSON Schema (так как спецификация OpenAPI сама основана на JSON Schema).
+* Разработан, придерживаясь этих стандартов, после тщательного их изучения. Эти стандарты изначально включены во фреймфорк, а не являются дополнительной надстройкой.
+* Это также позволяет использовать автоматическую **генерацию клиентского кода** на многих языках.
+
+### Автоматически генерируемая документация
+
+Интерактивная документация для API и исследования пользовательских веб-интерфейсов. Поскольку этот фреймворк основан на OpenAPI, существует несколько вариантов документирования, 2 из которых включены по умолчанию.
+
+* Swagger UI, с интерактивным взаимодействием, вызывает и тестирует ваш API прямо из браузера.
+
+
+
+* Альтернативная документация API в ReDoc.
+
+
+
+### Только современный Python
+
+Все эти возможности основаны на стандартных **аннотациях типов Python 3.6** (благодаря Pydantic). Не нужно изучать новый синтаксис. Только лишь стандартный современный Python.
+
+Если вам нужно освежить знания, как использовать аннотации типов в Python (даже если вы не используете FastAPI), выделите 2 минуты и просмотрите краткое руководство: [Введение в аннотации типов Python¶
+](python-types.md){.internal-link target=_blank}.
+
+Вы пишете на стандартном Python с аннотациями типов:
+
+```Python
+from datetime import date
+
+from pydantic import BaseModel
+
+# Объявляем параметр user_id с типом `str`
+# и получаем поддержку редактора внутри функции
+def main(user_id: str):
+ return user_id
+
+
+# Модель Pydantic
+class User(BaseModel):
+ id: int
+ name: str
+ joined: date
+```
+
+Это можно использовать так:
+
+```Python
+my_user: User = User(id=3, name="John Doe", joined="2018-07-19")
+
+second_user_data = {
+ "id": 4,
+ "name": "Mary",
+ "joined": "2018-11-30",
+}
+
+my_second_user: User = User(**second_user_data)
+```
+
+!!! Информация
+ `**second_user_data` означает:
+
+ Передать ключи и значения словаря `second_user_data`, в качестве аргументов типа "ключ-значение", это эквивалентно: `User(id=4, name="Mary", joined="2018-11-30")` .
+
+### Поддержка редакторов (IDE)
+
+Весь фреймворк был продуман так, чтобы быть простым и интуитивно понятным в использовании, все решения были проверены на множестве редакторов еще до начала разработки, чтобы обеспечить наилучшие условия при написании кода.
+
+В опросе Python-разработчиков было выяснено, что наиболее часто используемой функцией редакторов, является "автодополнение".
+
+Вся структура **FastAPI** основана на удовлетворении этой возможности. Автодополнение работает везде.
+
+Вам редко нужно будет возвращаться к документации.
+
+Вот как ваш редактор может вам помочь:
+
+* в Visual Studio Code:
+
+
+
+* в PyCharm:
+
+
+
+Вы будете получать автодополнение кода даже там, где вы считали это невозможным раньше.
+Как пример, ключ `price` внутри тела JSON (который может быть вложенным), приходящего в запросе.
+
+Больше никаких неправильных имён ключей, метания по документации или прокручивания кода вверх и вниз, в попытках узнать - использовали вы ранее `username` или `user_name`.
+
+### Краткость
+FastAPI имеет продуманные значения **по умолчанию** для всего, с произвольными настройками везде. Все параметры могут быть тонко подстроены так, чтобы делать то, что вам нужно и определять необходимый вам API.
+
+Но, по умолчанию, всё это **"и так работает"**.
+
+### Проверка значений
+
+* Проверка значений для большинства (или всех?) **типов данных** Python, включая:
+ * Объекты JSON (`dict`).
+ * Массивы JSON (`list`) с установленными типами элементов.
+ * Строковые (`str`) поля с ограничением минимальной и максимальной длины.
+ * Числа (`int`, `float`) с минимальными и максимальными значениями и т.п.
+
+* Проверка для более экзотических типов, таких как:
+ * URL.
+ * Email.
+ * UUID.
+ * ...и другие.
+
+Все проверки обрабатываются хорошо зарекомендовавшим себя и надежным **Pydantic**.
+
+### Безопасность и аутентификация
+
+Встроеные функции безопасности и аутентификации. Без каких-либо компромиссов с базами данных или моделями данных.
+
+Все схемы безопасности, определённые в OpenAPI, включая:
+
+* HTTP Basic.
+* **OAuth2** (также с **токенами JWT**). Ознакомьтесь с руководством [OAuth2 с JWT](tutorial/security/oauth2-jwt.md){.internal-link target=_blank}.
+* Ключи API в:
+ * Заголовках.
+ * Параметрах запросов.
+ * Cookies и т.п.
+
+Вдобавок все функции безопасности от Starlette (включая **сессионные cookies**).
+
+Все инструменты и компоненты спроектированы для многократного использования и легко интегрируются с вашими системами, хранилищами данных, реляционными и NoSQL базами данных и т. д.
+
+### Внедрение зависимостей
+
+FastAPI включает в себя чрезвычайно простую в использовании, но чрезвычайно мощную систему Внедрения зависимостей.
+
+* Даже зависимости могут иметь зависимости, создавая иерархию или **"графы" зависимостей**.
+* Всё **автоматически обрабатывается** фреймворком.
+* Все зависимости могут запрашивать данные из запросов и **дополнять операции пути** ограничениями и автоматической документацией.
+* **Автоматическая проверка** даже для параметров *операций пути*, определенных в зависимостях.
+* Поддержка сложных систем аутентификации пользователей, **соединений с базами данных** и т.д.
+* **Никаких компромиссов** с базами данных, интерфейсами и т.д. Но легкая интеграция со всеми ними.
+
+### Нет ограничений на "Плагины"
+
+Или, другими словами, нет сложностей с ними, импортируйте и используйте нужный вам код.
+
+Любая интеграция разработана настолько простой в использовании (с зависимостями), что вы можете создать "плагин" для своего приложения в пару строк кода, используя ту же структуру и синтаксис, что и для ваших *операций пути*.
+
+### Проверен
+
+* 100% покрытие тестами.
+* 100% аннотирование типов в кодовой базе.
+* Используется в реально работающих приложениях.
+
+## Основные свойства Starlette
+
+**FastAPI** основан на Starlette и полностью совместим с ним. Так что, любой дополнительный код Starlette, который у вас есть, будет также работать.
+
+На самом деле, `FastAPI` - это класс, унаследованный от `Starlette`. Таким образом, если вы уже знаете или используете Starlette, большая часть функционала будет работать так же.
+
+С **FastAPI** вы получаете все возможности **Starlette** (так как FastAPI это всего лишь Starlette на стероидах):
+
+* Серьёзно впечатляющая производительность. Это один из самых быстрых фреймворков на Python, наравне с приложениями использующими **NodeJS** или **Go**.
+* Поддержка **WebSocket**.
+* Фоновые задачи для процессов.
+* События запуска и выключения.
+* Тестовый клиент построен на библиотеке `requests`.
+* **CORS**, GZip, статические файлы, потоковые ответы.
+* Поддержка **сессий и cookie**.
+* 100% покрытие тестами.
+* 100% аннотирование типов в кодовой базе.
+
+## Особенности и возможности Pydantic
+
+**FastAPI** основан на Pydantic и полностью совместим с ним. Так что, любой дополнительный код Pydantic, который у вас есть, будет также работать.
+
+Включая внешние библиотеки, также основанные на Pydantic, такие как: ORM'ы, ODM'ы для баз данных.
+
+Это также означает, что во многих случаях вы можете передавать тот же объект, который получили из запроса, **непосредственно в базу данных**, так как всё проверяется автоматически.
+
+И наоборот, во многих случаях вы можете просто передать объект, полученный из базы данных, **непосредственно клиенту**.
+
+С **FastAPI** вы получаете все возможности **Pydantic** (так как, FastAPI основан на Pydantic, для обработки данных):
+
+* **Никакой нервотрёпки** :
+ * Не нужно изучать новых схем в микроязыках.
+ * Если вы знаете аннотации типов в Python, вы знаете, как использовать Pydantic.
+* Прекрасно сочетается с вашими **IDE/linter/мозгом**:
+ * Потому что структуры данных pydantic - это всего лишь экземпляры классов, определённых вами. Автодополнение, проверка кода, mypy и ваша интуиция - всё будет работать с вашими проверенными данными.
+* **Быстродействие**:
+ * В тестовых замерах Pydantic быстрее, чем все другие проверенные библиотеки.
+* Проверка **сложных структур**:
+ * Использование иерархических моделей Pydantic; `List`, `Dict` и т.п. из модуля `typing` (входит в стандартную библиотеку Python).
+ * Валидаторы позволяют четко и легко определять, проверять и документировать сложные схемы данных в виде JSON Schema.
+ * У вас могут быть глубоко **вложенные объекты JSON** и все они будут проверены и аннотированы.
+* **Расширяемость**:
+ * Pydantic позволяет определять пользовательские типы данных или расширять проверку методами модели, с помощью проверочных декораторов.
+* 100% покрытие тестами.
diff --git a/docs/ru/docs/index.md b/docs/ru/docs/index.md
index 9a3957d5f..448e2c707 100644
--- a/docs/ru/docs/index.md
+++ b/docs/ru/docs/index.md
@@ -1,50 +1,48 @@
-
-{!../../../docs/missing-translation.md!}
-
-
- FastAPI framework, high performance, easy to learn, fast to code, ready for production + Готовый к внедрению высокопроизводительный фреймворк, простой в изучении и разработке.
--- -**Documentation**: https://fastapi.tiangolo.com +**Документация**: https://fastapi.tiangolo.com -**Source Code**: https://github.com/tiangolo/fastapi +**Исходный код**: https://github.com/tiangolo/fastapi --- -FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. +FastAPI — это современный, быстрый (высокопроизводительный) веб-фреймворк для создания API используя Python 3.6+, в основе которого лежит стандартная аннотация типов Python. -The key features are: +Ключевые особенности: -* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance). +* **Скорость**: Очень высокая производительность, на уровне **NodeJS** и **Go** (благодаря Starlette и Pydantic). [Один из самых быстрых фреймворков Python](#_10). +* **Быстрота разработки**: Увеличьте скорость разработки примерно на 200–300%. * +* **Меньше ошибок**: Сократите примерно на 40% количество ошибок, вызванных человеком (разработчиком). * +* **Интуитивно понятный**: Отличная поддержка редактора. Автозавершение везде. Меньше времени на отладку. +* **Лёгкость**: Разработан так, чтобы его было легко использовать и осваивать. Меньше времени на чтение документации. +* **Краткость**: Сведите к минимуму дублирование кода. Каждый объявленный параметр - определяет несколько функций. Меньше ошибок. +* **Надежность**: Получите готовый к работе код. С автоматической интерактивной документацией. +* **На основе стандартов**: Основан на открытых стандартах API и полностью совместим с ними: OpenAPI (ранее известном как Swagger) и JSON Schema. -* **Fast to code**: Increase the speed to develop features by about 200% to 300%. * -* **Fewer bugs**: Reduce about 40% of human (developer) induced errors. * -* **Intuitive**: Great editor support. Completion everywhere. Less time debugging. -* **Easy**: Designed to be easy to use and learn. Less time reading docs. -* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs. -* **Robust**: Get production-ready code. With automatic interactive documentation. -* **Standards-based**: Based on (and fully compatible with) the open standards for APIs: OpenAPI (previously known as Swagger) and JSON Schema. +* оценка на основе тестов внутренней команды разработчиков, создающих производственные приложения. -* estimation based on tests on an internal development team, building production applications. - -## Sponsors +## Спонсоры @@ -59,66 +57,66 @@ The key features are: -Other sponsors +Другие спонсоры -## Opinions +## Отзывы -"_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._" +"_В последнее время я много где использую **FastAPI**. [...] На самом деле я планирую использовать его для всех **сервисов машинного обучения моей команды в Microsoft**. Некоторые из них интегрируются в основной продукт **Windows**, а некоторые — в продукты **Office**._"async def...async def...uvicorn main:app --reload...uvicorn main:app --reload...ujson - for faster JSON "parsing".
-* email_validator - for email validation.
+* ujson - для более быстрого JSON "парсинга".
+* email_validator - для проверки электронной почты.
-Used by Starlette:
+Используется Starlette:
-* requests - Required if you want to use the `TestClient`.
-* jinja2 - Required if you want to use the default template configuration.
-* python-multipart - Required if you want to support form "parsing", with `request.form()`.
-* itsdangerous - Required for `SessionMiddleware` support.
-* pyyaml - Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI).
-* graphene - Required for `GraphQLApp` support.
-* ujson - Required if you want to use `UJSONResponse`.
+* requests - Обязательно, если вы хотите использовать `TestClient`.
+* jinja2 - Обязательно, если вы хотите использовать конфигурацию шаблона по умолчанию.
+* python-multipart - Обязательно, если вы хотите поддерживать форму "парсинга" с помощью `request.form()`.
+* itsdangerous - Обязательно, для поддержки `SessionMiddleware`.
+* pyyaml - Обязательно, для поддержки `SchemaGenerator` Starlette (возможно, вам это не нужно с FastAPI).
+* ujson - Обязательно, если вы хотите использовать `UJSONResponse`.
-Used by FastAPI / Starlette:
+Используется FastAPI / Starlette:
-* uvicorn - for the server that loads and serves your application.
-* orjson - Required if you want to use `ORJSONResponse`.
+* uvicorn - сервер, который загружает и обслуживает ваше приложение.
+* orjson - Обязательно, если вы хотите использовать `ORJSONResponse`.
-You can install all of these with `pip install fastapi[all]`.
+Вы можете установить все это с помощью `pip install "fastapi[all]"`.
-## License
+## Лицензия
-This project is licensed under the terms of the MIT license.
+Этот проект распространяется на условиях лицензии MIT.
diff --git a/docs/ru/docs/tutorial/background-tasks.md b/docs/ru/docs/tutorial/background-tasks.md
new file mode 100644
index 000000000..e608f6c8f
--- /dev/null
+++ b/docs/ru/docs/tutorial/background-tasks.md
@@ -0,0 +1,102 @@
+# Фоновые задачи
+
+Вы можете создавать фоновые задачи, которые будут выполнятся *после* возвращения ответа сервером.
+
+Это может быть полезно для функций, которые должны выполниться после получения запроса, но ожидание их выполнения необязательно для пользователя.
+
+К примеру:
+
+* Отправка писем на почту после выполнения каких-либо действий:
+ * Т.к. соединение с почтовым сервером и отправка письма идут достаточно "долго" (несколько секунд), вы можете отправить ответ пользователю, а отправку письма выполнить в фоне.
+* Обработка данных:
+ * К примеру, если вы получаете файл, который должен пройти через медленный процесс, вы можете отправить ответ "Accepted" (HTTP 202) и отправить работу с файлом в фон.
+
+## Использование класса `BackgroundTasks`
+
+Сначала импортируйте `BackgroundTasks`, потом добавьте в функцию параметр с типом `BackgroundTasks`:
+
+```Python hl_lines="1 13"
+{!../../../docs_src/background_tasks/tutorial001.py!}
+```
+
+**FastAPI** создаст объект класса `BackgroundTasks` для вас и запишет его в параметр.
+
+## Создание функции для фоновой задачи
+
+Создайте функцию, которую хотите запустить в фоне.
+
+Это совершенно обычная функция, которая может принимать параметры.
+
+Она может быть как асинхронной `async def`, так и обычной `def` функцией, **FastAPI** знает, как правильно ее выполнить.
+
+В нашем примере фоновая задача будет вести запись в файл (симулируя отправку письма).
+
+Так как операция записи не использует `async` и `await`, мы определим ее как обычную `def`:
+
+```Python hl_lines="6-9"
+{!../../../docs_src/background_tasks/tutorial001.py!}
+```
+
+## Добавление фоновой задачи
+
+Внутри функции вызовите метод `.add_task()` у объекта *background tasks* и передайте ему функцию, которую хотите выполнить в фоне:
+
+```Python hl_lines="14"
+{!../../../docs_src/background_tasks/tutorial001.py!}
+```
+
+`.add_task()` принимает следующие аргументы:
+
+* Функцию, которая будет выполнена в фоне (`write_notification`). Обратите внимание, что передается объект функции, без скобок.
+* Любое упорядоченное количество аргументов, которые принимает функция (`email`).
+* Любое количество именованных аргументов, которые принимает функция (`message="some notification"`).
+
+## Встраивание зависимостей
+
+Класс `BackgroundTasks` также работает с системой встраивания зависимостей, вы можете определить `BackgroundTasks` на разных уровнях: как параметр функции, как завимость, как подзависимость и так далее.
+
+**FastAPI** знает, что нужно сделать в каждом случае и как переиспользовать тот же объект `BackgroundTasks`, так чтобы все фоновые задачи собрались и запустились вместе в фоне:
+
+=== "Python 3.6 и выше"
+
+ ```Python hl_lines="13 15 22 25"
+ {!> ../../../docs_src/background_tasks/tutorial002.py!}
+ ```
+
+=== "Python 3.10 и выше"
+
+ ```Python hl_lines="11 13 20 23"
+ {!> ../../../docs_src/background_tasks/tutorial002_py310.py!}
+ ```
+
+В этом примере сообщения будут записаны в `log.txt` *после* того, как ответ сервера был отправлен.
+
+Если бы в запросе была очередь `q`, она бы первой записалась в `log.txt` фоновой задачей (потому что вызывается в зависимости `get_query`).
+
+После другая фоновая задача, которая была сгенерирована в функции, запишет сообщение из параметра `email`.
+
+## Технические детали
+
+Класс `BackgroundTasks` основан на `starlette.background`.
+
+Он интегрирован в FastAPI, так что вы можете импортировать его прямо из `fastapi` и избежать случайного импорта `BackgroundTask` (без `s` на конце) из `starlette.background`.
+
+При использовании `BackgroundTasks` (а не `BackgroundTask`), вам достаточно только определить параметр функции с типом `BackgroundTasks` и **FastAPI** сделает все за вас, также как при использовании объекта `Request`.
+
+Вы все равно можете использовать `BackgroundTask` из `starlette` в FastAPI, но вам придется самостоятельно создавать объект фоновой задачи и вручную обработать `Response` внутри него.
+
+Вы можете подробнее изучить его в Официальной документации Starlette для BackgroundTasks.
+
+## Предостережение
+
+Если вам нужно выполнить тяжелые вычисления в фоне, которым необязательно быть запущенными в одном процессе с приложением **FastAPI** (к примеру, вам не нужны обрабатываемые переменные или вы не хотите делиться памятью процесса и т.д.), вы можете использовать более серьезные инструменты, такие как Celery.
+
+Их тяжелее настраивать, также им нужен брокер сообщений наподобие RabbitMQ или Redis, но зато они позволяют вам запускать фоновые задачи в нескольких процессах и даже на нескольких серверах.
+
+Для примера, посмотрите [Project Generators](../project-generation.md){.internal-link target=_blank}, там есть проект с уже настроенным Celery.
+
+Но если вам нужен доступ к общим переменным и объектам вашего **FastAPI** приложения или вам нужно выполнять простые фоновые задачи (наподобие отправки письма из примера) вы можете просто использовать `BackgroundTasks`.
+
+## Резюме
+
+Для создания фоновых задач вам необходимо импортировать `BackgroundTasks` и добавить его в функцию, как параметр с типом `BackgroundTasks`.
diff --git a/docs/ru/mkdocs.yml b/docs/ru/mkdocs.yml
index bb0702489..381775ac6 100644
--- a/docs/ru/mkdocs.yml
+++ b/docs/ru/mkdocs.yml
@@ -5,14 +5,14 @@ theme:
name: material
custom_dir: overrides
palette:
- - media: "(prefers-color-scheme: light)"
+ - media: '(prefers-color-scheme: light)'
scheme: default
primary: teal
accent: amber
toggle:
icon: material/lightbulb
name: Switch to light mode
- - media: "(prefers-color-scheme: dark)"
+ - media: '(prefers-color-scheme: dark)'
scheme: slate
primary: teal
accent: amber
@@ -44,6 +44,7 @@ nav:
- es: /es/
- fa: /fa/
- fr: /fr/
+ - he: /he/
- id: /id/
- it: /it/
- ja: /ja/
@@ -53,10 +54,18 @@ nav:
- pt: /pt/
- ru: /ru/
- sq: /sq/
+ - sv: /sv/
- tr: /tr/
- uk: /uk/
- zh: /zh/
+- features.md
+- python-types.md
+- Учебник - руководство пользователя:
+ - tutorial/background-tasks.md
+- external-links.md
- async.md
+- Развёртывание:
+ - deployment/versions.md
markdown_extensions:
- toc:
permalink: true
@@ -74,6 +83,8 @@ markdown_extensions:
format: !!python/name:pymdownx.superfences.fence_code_format ''
- pymdownx.tabbed:
alternate_style: true
+- attr_list
+- md_in_html
extra:
analytics:
provider: google
@@ -106,6 +117,8 @@ extra:
name: fa
- link: /fr/
name: fr - français
+ - link: /he/
+ name: he
- link: /id/
name: id
- link: /it/
@@ -124,6 +137,8 @@ extra:
name: ru - русский язык
- link: /sq/
name: sq - shqip
+ - link: /sv/
+ name: sv - svenska
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/sq/docs/index.md b/docs/sq/docs/index.md
index 29f92e020..2b64003fe 100644
--- a/docs/sq/docs/index.md
+++ b/docs/sq/docs/index.md
@@ -135,7 +135,7 @@ You will also need an ASGI server, for production such as
```console
-$ pip install uvicorn[standard]
+$ pip install "uvicorn[standard]"
---> 100%
```
diff --git a/docs/sq/mkdocs.yml b/docs/sq/mkdocs.yml
index 8914395fe..b07f3bc63 100644
--- a/docs/sq/mkdocs.yml
+++ b/docs/sq/mkdocs.yml
@@ -5,14 +5,14 @@ theme:
name: material
custom_dir: overrides
palette:
- - media: "(prefers-color-scheme: light)"
+ - media: '(prefers-color-scheme: light)'
scheme: default
primary: teal
accent: amber
toggle:
icon: material/lightbulb
name: Switch to light mode
- - media: "(prefers-color-scheme: dark)"
+ - media: '(prefers-color-scheme: dark)'
scheme: slate
primary: teal
accent: amber
@@ -44,6 +44,7 @@ nav:
- es: /es/
- fa: /fa/
- fr: /fr/
+ - he: /he/
- id: /id/
- it: /it/
- ja: /ja/
@@ -53,6 +54,7 @@ nav:
- pt: /pt/
- ru: /ru/
- sq: /sq/
+ - sv: /sv/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -73,6 +75,8 @@ markdown_extensions:
format: !!python/name:pymdownx.superfences.fence_code_format ''
- pymdownx.tabbed:
alternate_style: true
+- attr_list
+- md_in_html
extra:
analytics:
provider: google
@@ -105,6 +109,8 @@ extra:
name: fa
- link: /fr/
name: fr - français
+ - link: /he/
+ name: he
- link: /id/
name: id
- link: /it/
@@ -123,6 +129,8 @@ extra:
name: ru - русский язык
- link: /sq/
name: sq - shqip
+ - link: /sv/
+ name: sv - svenska
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/sv/docs/index.md b/docs/sv/docs/index.md
new file mode 100644
index 000000000..fd52f994c
--- /dev/null
+++ b/docs/sv/docs/index.md
@@ -0,0 +1,468 @@
+
+{!../../../docs/missing-translation.md!}
+
+
+
++ FastAPI framework, high performance, easy to learn, fast to code, ready for production +
+ + +--- + +**Documentation**: https://fastapi.tiangolo.com + +**Source Code**: https://github.com/tiangolo/fastapi + +--- + +FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. + +The key features are: + +* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic). [One of the fastest Python frameworks available](#performance). + +* **Fast to code**: Increase the speed to develop features by about 200% to 300%. * +* **Fewer bugs**: Reduce about 40% of human (developer) induced errors. * +* **Intuitive**: Great editor support. Completion everywhere. Less time debugging. +* **Easy**: Designed to be easy to use and learn. Less time reading docs. +* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs. +* **Robust**: Get production-ready code. With automatic interactive documentation. +* **Standards-based**: Based on (and fully compatible with) the open standards for APIs: OpenAPI (previously known as Swagger) and JSON Schema. + +* estimation based on tests on an internal development team, building production applications. + +## Sponsors + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} +async def...uvicorn main:app --reload...ujson - for faster JSON "parsing".
+* email_validator - for email validation.
+
+Used by Starlette:
+
+* requests - Required if you want to use the `TestClient`.
+* jinja2 - Required if you want to use the default template configuration.
+* python-multipart - Required if you want to support form "parsing", with `request.form()`.
+* itsdangerous - Required for `SessionMiddleware` support.
+* pyyaml - Required for Starlette's `SchemaGenerator` support (you probably don't need it with FastAPI).
+* ujson - Required if you want to use `UJSONResponse`.
+
+Used by FastAPI / Starlette:
+
+* uvicorn - for the server that loads and serves your application.
+* orjson - Required if you want to use `ORJSONResponse`.
+
+You can install all of these with `pip install "fastapi[all]"`.
+
+## License
+
+This project is licensed under the terms of the MIT license.
diff --git a/docs/sv/mkdocs.yml b/docs/sv/mkdocs.yml
new file mode 100644
index 000000000..3332d232d
--- /dev/null
+++ b/docs/sv/mkdocs.yml
@@ -0,0 +1,145 @@
+site_name: FastAPI
+site_description: FastAPI framework, high performance, easy to learn, fast to code, ready for production
+site_url: https://fastapi.tiangolo.com/sv/
+theme:
+ name: material
+ custom_dir: overrides
+ palette:
+ - media: '(prefers-color-scheme: light)'
+ scheme: default
+ primary: teal
+ accent: amber
+ toggle:
+ icon: material/lightbulb
+ name: Switch to light mode
+ - media: '(prefers-color-scheme: dark)'
+ scheme: slate
+ primary: teal
+ accent: amber
+ toggle:
+ icon: material/lightbulb-outline
+ name: Switch to dark mode
+ features:
+ - search.suggest
+ - search.highlight
+ - content.tabs.link
+ icon:
+ repo: fontawesome/brands/github-alt
+ logo: https://fastapi.tiangolo.com/img/icon-white.svg
+ favicon: https://fastapi.tiangolo.com/img/favicon.png
+ language: sv
+repo_name: tiangolo/fastapi
+repo_url: https://github.com/tiangolo/fastapi
+edit_uri: ''
+plugins:
+- search
+- markdownextradata:
+ data: data
+nav:
+- FastAPI: index.md
+- Languages:
+ - en: /
+ - az: /az/
+ - de: /de/
+ - es: /es/
+ - fa: /fa/
+ - fr: /fr/
+ - he: /he/
+ - id: /id/
+ - it: /it/
+ - ja: /ja/
+ - ko: /ko/
+ - nl: /nl/
+ - pl: /pl/
+ - pt: /pt/
+ - ru: /ru/
+ - sq: /sq/
+ - sv: /sv/
+ - tr: /tr/
+ - uk: /uk/
+ - zh: /zh/
+markdown_extensions:
+- toc:
+ permalink: true
+- markdown.extensions.codehilite:
+ guess_lang: false
+- mdx_include:
+ base_path: docs
+- admonition
+- codehilite
+- extra
+- pymdownx.superfences:
+ custom_fences:
+ - name: mermaid
+ class: mermaid
+ format: !!python/name:pymdownx.superfences.fence_code_format ''
+- pymdownx.tabbed:
+ alternate_style: true
+- attr_list
+- md_in_html
+extra:
+ analytics:
+ provider: google
+ property: UA-133183413-1
+ social:
+ - icon: fontawesome/brands/github-alt
+ link: https://github.com/tiangolo/fastapi
+ - icon: fontawesome/brands/discord
+ link: https://discord.gg/VQjSZaeJmf
+ - icon: fontawesome/brands/twitter
+ link: https://twitter.com/fastapi
+ - icon: fontawesome/brands/linkedin
+ link: https://www.linkedin.com/in/tiangolo
+ - icon: fontawesome/brands/dev
+ link: https://dev.to/tiangolo
+ - icon: fontawesome/brands/medium
+ link: https://medium.com/@tiangolo
+ - icon: fontawesome/solid/globe
+ link: https://tiangolo.com
+ alternate:
+ - link: /
+ name: en - English
+ - link: /az/
+ name: az
+ - link: /de/
+ name: de
+ - link: /es/
+ name: es - español
+ - link: /fa/
+ name: fa
+ - link: /fr/
+ name: fr - français
+ - link: /he/
+ name: he
+ - link: /id/
+ name: id
+ - link: /it/
+ name: it - italiano
+ - link: /ja/
+ name: ja - 日本語
+ - link: /ko/
+ name: ko - 한국어
+ - link: /nl/
+ name: nl
+ - link: /pl/
+ name: pl
+ - link: /pt/
+ name: pt - português
+ - link: /ru/
+ name: ru - русский язык
+ - link: /sq/
+ name: sq - shqip
+ - link: /sv/
+ name: sv - svenska
+ - link: /tr/
+ name: tr - Türkçe
+ - link: /uk/
+ name: uk - українська мова
+ - link: /zh/
+ name: zh - 汉语
+extra_css:
+- https://fastapi.tiangolo.com/css/termynal.css
+- https://fastapi.tiangolo.com/css/custom.css
+extra_javascript:
+- https://fastapi.tiangolo.com/js/termynal.js
+- https://fastapi.tiangolo.com/js/custom.js
diff --git a/docs/sv/overrides/.gitignore b/docs/sv/overrides/.gitignore
new file mode 100644
index 000000000..e69de29bb
diff --git a/docs/tr/docs/index.md b/docs/tr/docs/index.md
index 5693029b5..0d5337c87 100644
--- a/docs/tr/docs/index.md
+++ b/docs/tr/docs/index.md
@@ -143,7 +143,7 @@ Uygulamanı kullanılabilir hale getirmek için
```console
-$ pip install uvicorn[standard]
+$ pip install "uvicorn[standard]"
---> 100%
```
diff --git a/docs/tr/mkdocs.yml b/docs/tr/mkdocs.yml
index 74186033c..e29d25936 100644
--- a/docs/tr/mkdocs.yml
+++ b/docs/tr/mkdocs.yml
@@ -5,14 +5,14 @@ theme:
name: material
custom_dir: overrides
palette:
- - media: "(prefers-color-scheme: light)"
+ - media: '(prefers-color-scheme: light)'
scheme: default
primary: teal
accent: amber
toggle:
icon: material/lightbulb
name: Switch to light mode
- - media: "(prefers-color-scheme: dark)"
+ - media: '(prefers-color-scheme: dark)'
scheme: slate
primary: teal
accent: amber
@@ -44,6 +44,7 @@ nav:
- es: /es/
- fa: /fa/
- fr: /fr/
+ - he: /he/
- id: /id/
- it: /it/
- ja: /ja/
@@ -53,6 +54,7 @@ nav:
- pt: /pt/
- ru: /ru/
- sq: /sq/
+ - sv: /sv/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -76,6 +78,8 @@ markdown_extensions:
format: !!python/name:pymdownx.superfences.fence_code_format ''
- pymdownx.tabbed:
alternate_style: true
+- attr_list
+- md_in_html
extra:
analytics:
provider: google
@@ -108,6 +112,8 @@ extra:
name: fa
- link: /fr/
name: fr - français
+ - link: /he/
+ name: he
- link: /id/
name: id
- link: /it/
@@ -126,6 +132,8 @@ extra:
name: ru - русский язык
- link: /sq/
name: sq - shqip
+ - link: /sv/
+ name: sv - svenska
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/uk/docs/index.md b/docs/uk/docs/index.md
index 29f92e020..2b64003fe 100644
--- a/docs/uk/docs/index.md
+++ b/docs/uk/docs/index.md
@@ -135,7 +135,7 @@ You will also need an ASGI server, for production such as
```console
-$ pip install uvicorn[standard]
+$ pip install "uvicorn[standard]"
---> 100%
```
diff --git a/docs/uk/mkdocs.yml b/docs/uk/mkdocs.yml
index ddf299d8b..711328771 100644
--- a/docs/uk/mkdocs.yml
+++ b/docs/uk/mkdocs.yml
@@ -5,14 +5,14 @@ theme:
name: material
custom_dir: overrides
palette:
- - media: "(prefers-color-scheme: light)"
+ - media: '(prefers-color-scheme: light)'
scheme: default
primary: teal
accent: amber
toggle:
icon: material/lightbulb
name: Switch to light mode
- - media: "(prefers-color-scheme: dark)"
+ - media: '(prefers-color-scheme: dark)'
scheme: slate
primary: teal
accent: amber
@@ -44,6 +44,7 @@ nav:
- es: /es/
- fa: /fa/
- fr: /fr/
+ - he: /he/
- id: /id/
- it: /it/
- ja: /ja/
@@ -53,6 +54,7 @@ nav:
- pt: /pt/
- ru: /ru/
- sq: /sq/
+ - sv: /sv/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -73,6 +75,8 @@ markdown_extensions:
format: !!python/name:pymdownx.superfences.fence_code_format ''
- pymdownx.tabbed:
alternate_style: true
+- attr_list
+- md_in_html
extra:
analytics:
provider: google
@@ -105,6 +109,8 @@ extra:
name: fa
- link: /fr/
name: fr - français
+ - link: /he/
+ name: he
- link: /id/
name: id
- link: /it/
@@ -123,6 +129,8 @@ extra:
name: ru - русский язык
- link: /sq/
name: sq - shqip
+ - link: /sv/
+ name: sv - svenska
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs/zh/docs/advanced/response-cookies.md b/docs/zh/docs/advanced/response-cookies.md
new file mode 100644
index 000000000..3e53c5319
--- /dev/null
+++ b/docs/zh/docs/advanced/response-cookies.md
@@ -0,0 +1,47 @@
+# 响应Cookies
+
+## 使用 `Response` 参数
+
+你可以在 *路径函数* 中定义一个类型为 `Response`的参数,这样你就可以在这个临时响应对象中设置cookie了。
+
+```Python hl_lines="1 8-9"
+{!../../../docs_src/response_cookies/tutorial002.py!}
+```
+
+而且你还可以根据你的需要响应不同的对象,比如常用的 `dict`,数据库model等。
+
+如果你定义了 `response_model`,程序会自动根据`response_model`来过滤和转换你响应的对象。
+
+**FastAPI** 会使用这个 *临时* 响应对象去装在这些cookies信息 (同样还有headers和状态码等信息), 最终会将这些信息和通过`response_model`转化过的数据合并到最终的响应里。
+
+你也可以在depend中定义`Response`参数,并设置cookie和header。
+
+## 直接响应 `Response`
+
+你还可以在直接响应`Response`时直接创建cookies。
+
+你可以参考[Return a Response Directly](response-directly.md){.internal-link target=_blank}来创建response
+
+然后设置Cookies,并返回:
+
+```Python hl_lines="10-12"
+{!../../../docs_src/response_cookies/tutorial001.py!}
+```
+
+!!! tip
+ 需要注意,如果你直接反馈一个response对象,而不是使用`Response`入参,FastAPI则会直接反馈你封装的response对象。
+
+ 所以你需要确保你响应数据类型的正确性,如:你可以使用`JSONResponse`来兼容JSON的场景。
+
+ 同时,你也应当仅反馈通过`response_model`过滤过的数据。
+
+### 更多信息
+
+!!! note "技术细节"
+ 你也可以使用`from starlette.responses import Response` 或者 `from starlette.responses import JSONResponse`。
+
+ 为了方便开发者,**FastAPI** 封装了相同数据类型,如`starlette.responses` 和 `fastapi.responses`。不过大部分response对象都是直接引用自Starlette。
+
+ 因为`Response`对象可以非常便捷的设置headers和cookies,所以 **FastAPI** 同时也封装了`fastapi.Response`。
+
+如果你想查看所有可用的参数和选项,可以参考 Starlette帮助文档
diff --git a/docs/zh/docs/index.md b/docs/zh/docs/index.md
index 797032c86..3898beaee 100644
--- a/docs/zh/docs/index.md
+++ b/docs/zh/docs/index.md
@@ -131,7 +131,7 @@ $ pip install fastapi
+
+!!! check "Authorize 按钮!"
+
+ 页面右上角出现了一个「**Authorize**」按钮。
+
+ *路径操作*的右上角也出现了一个可以点击的小锁图标。
+
+点击 **Authorize** 按钮,弹出授权表单,输入 `username` 与 `password` 及其它可选字段:
+
+
+
+!!! note "笔记"
+
+ 目前,在表单中输入内容不会有任何反应,后文会介绍相关内容。
+
+虽然此文档不是给前端最终用户使用的,但这个自动工具非常实用,可在文档中与所有 API 交互。
+
+前端团队(可能就是开发者本人)可以使用本工具。
+
+第三方应用与系统也可以调用本工具。
+
+开发者也可以用它来调试、检查、测试应用。
+
+## 密码流
+
+现在,我们回过头来介绍这段代码的原理。
+
+`Password` **流**是 OAuth2 定义的,用于处理安全与身份验证的方式(**流**)。
+
+OAuth2 的设计目标是为了让后端或 API 独立于服务器验证用户身份。
+
+但在本例中,**FastAPI** 应用会处理 API 与身份验证。
+
+下面,我们来看一下简化的运行流程:
+
+- 用户在前端输入 `username` 与`password`,并点击**回车**
+- (用户浏览器中运行的)前端把 `username` 与`password` 发送至 API 中指定的 URL(使用 `tokenUrl="token"` 声明)
+- API 检查 `username` 与`password`,并用令牌(`Token`) 响应(暂未实现此功能):
+ - 令牌只是用于验证用户的字符串
+ - 一般来说,令牌会在一段时间后过期
+ - 过时后,用户要再次登录
+ - 这样一来,就算令牌被人窃取,风险也较低。因为它与永久密钥不同,**在绝大多数情况下**不会长期有效
+- 前端临时将令牌存储在某个位置
+- 用户点击前端,前往前端应用的其它部件
+- 前端需要从 API 中提取更多数据:
+ - 为指定的端点(Endpoint)进行身份验证
+ - 因此,用 API 验证身份时,要发送值为 `Bearer` + 令牌的请求头 `Authorization`
+ - 假如令牌为 `foobar`,`Authorization` 请求头就是: `Bearer foobar`
+
+## **FastAPI** 的 `OAuth2PasswordBearer`
+
+**FastAPI** 提供了不同抽象级别的安全工具。
+
+本例使用 **OAuth2** 的 **Password** 流以及 **Bearer** 令牌(`Token`)。为此要使用 `OAuth2PasswordBearer` 类。
+
+!!! info "说明"
+
+ `Beare` 令牌不是唯一的选择。
+
+ 但它是最适合这个用例的方案。
+
+ 甚至可以说,它是适用于绝大多数用例的最佳方案,除非您是 OAuth2 的专家,知道为什么其它方案更合适。
+
+ 本例中,**FastAPI** 还提供了构建工具。
+
+创建 `OAuth2PasswordBearer` 的类实例时,要传递 `tokenUrl` 参数。该参数包含客户端(用户浏览器中运行的前端) 的 URL,用于发送 `username` 与 `password`,并获取令牌。
+
+```Python hl_lines="6"
+{!../../../docs_src/security/tutorial001.py!}
+```
+
+!!! tip "提示"
+
+ 在此,`tokenUrl="token"` 指向的是暂未创建的相对 URL `token`。这个相对 URL 相当于 `./token`。
+
+ 因为使用的是相对 URL,如果 API 位于 `https://example.com/`,则指向 `https://example.com/token`。但如果 API 位于 `https://example.com/api/v1/`,它指向的就是`https://example.com/api/v1/token`。
+
+ 使用相对 URL 非常重要,可以确保应用在遇到[使用代理](../../advanced/behind-a-proxy.md){.internal-link target=_blank}这样的高级用例时,也能正常运行。
+
+该参数不会创建端点或*路径操作*,但会声明客户端用来获取令牌的 URL `/token` 。此信息用于 OpenAPI 及 API 文档。
+
+接下来,学习如何创建实际的路径操作。
+
+!!! info "说明"
+
+ 严苛的 **Pythonista** 可能不喜欢用 `tokenUrl` 这种命名风格代替 `token_url`。
+
+ 这种命名方式是因为要使用与 OpenAPI 规范中相同的名字。以便在深入校验安全方案时,能通过复制粘贴查找更多相关信息。
+
+`oauth2_scheme` 变量是 `OAuth2PasswordBearer` 的实例,也是**可调用项**。
+
+以如下方式调用:
+
+```Python
+oauth2_scheme(some, parameters)
+```
+
+因此,`Depends` 可以调用 `oauth2_scheme` 变量。
+
+### 使用
+
+接下来,使用 `Depends` 把 `oauth2_scheme` 传入依赖项。
+
+```Python hl_lines="10"
+{!../../../docs_src/security/tutorial001.py!}
+```
+
+该依赖项使用字符串(`str`)接收*路径操作函数*的参数 `token` 。
+
+**FastAPI** 使用依赖项在 OpenAPI 概图(及 API 文档)中定义**安全方案**。
+
+!!! info "技术细节"
+
+ **FastAPI** 使用(在依赖项中声明的)类 `OAuth2PasswordBearer` 在 OpenAPI 中定义安全方案,这是因为它继承自 `fastapi.security.oauth2.OAuth2`,而该类又是继承自`fastapi.security.base.SecurityBase`。
+
+ 所有与 OpenAPI(及 API 文档)集成的安全工具都继承自 `SecurityBase`, 这就是为什么 **FastAPI** 能把它们集成至 OpenAPI 的原因。
+
+## 实现的操作
+
+FastAPI 校验请求中的 `Authorization` 请求头,核对请求头的值是不是由 `Bearer ` + 令牌组成, 并返回令牌字符串(`str`)。
+
+如果没有找到 `Authorization` 请求头,或请求头的值不是 `Bearer ` + 令牌。FastAPI 直接返回 401 错误状态码(`UNAUTHORIZED`)。
+
+开发者不需要检查错误信息,查看令牌是否存在,只要该函数能够执行,函数中就会包含令牌字符串。
+
+正如下图所示,API 文档已经包含了这项功能:
+
+
+
+目前,暂时还没有实现验证令牌是否有效的功能,不过后文很快就会介绍的。
+
+## 小结
+
+看到了吧,只要多写三四行代码,就可以添加基础的安全表单。
diff --git a/docs/zh/mkdocs.yml b/docs/zh/mkdocs.yml
index a72ecb657..ac8679dc0 100644
--- a/docs/zh/mkdocs.yml
+++ b/docs/zh/mkdocs.yml
@@ -5,14 +5,14 @@ theme:
name: material
custom_dir: overrides
palette:
- - media: "(prefers-color-scheme: light)"
+ - media: '(prefers-color-scheme: light)'
scheme: default
primary: teal
accent: amber
toggle:
icon: material/lightbulb
name: Switch to light mode
- - media: "(prefers-color-scheme: dark)"
+ - media: '(prefers-color-scheme: dark)'
scheme: slate
primary: teal
accent: amber
@@ -44,6 +44,7 @@ nav:
- es: /es/
- fa: /fa/
- fr: /fr/
+ - he: /he/
- id: /id/
- it: /it/
- ja: /ja/
@@ -53,6 +54,7 @@ nav:
- pt: /pt/
- ru: /ru/
- sq: /sq/
+ - sv: /sv/
- tr: /tr/
- uk: /uk/
- zh: /zh/
@@ -83,6 +85,7 @@ nav:
- tutorial/request-forms-and-files.md
- tutorial/handling-errors.md
- tutorial/path-operation-configuration.md
+ - tutorial/encoder.md
- tutorial/body-updates.md
- 依赖项:
- tutorial/dependencies/index.md
@@ -91,6 +94,7 @@ nav:
- tutorial/dependencies/global-dependencies.md
- 安全性:
- tutorial/security/index.md
+ - tutorial/security/first-steps.md
- tutorial/security/get-current-user.md
- tutorial/security/simple-oauth2.md
- tutorial/security/oauth2-jwt.md
@@ -104,6 +108,7 @@ nav:
- advanced/additional-status-codes.md
- advanced/response-directly.md
- advanced/custom-response.md
+ - advanced/response-cookies.md
- contributing.md
- help-fastapi.md
- benchmarks.md
@@ -124,6 +129,8 @@ markdown_extensions:
format: !!python/name:pymdownx.superfences.fence_code_format ''
- pymdownx.tabbed:
alternate_style: true
+- attr_list
+- md_in_html
extra:
analytics:
provider: google
@@ -156,6 +163,8 @@ extra:
name: fa
- link: /fr/
name: fr - français
+ - link: /he/
+ name: he
- link: /id/
name: id
- link: /it/
@@ -174,6 +183,8 @@ extra:
name: ru - русский язык
- link: /sq/
name: sq - shqip
+ - link: /sv/
+ name: sv - svenska
- link: /tr/
name: tr - Türkçe
- link: /uk/
diff --git a/docs_src/additional_responses/tutorial001.py b/docs_src/additional_responses/tutorial001.py
index 79dcc2efe..ffa821b91 100644
--- a/docs_src/additional_responses/tutorial001.py
+++ b/docs_src/additional_responses/tutorial001.py
@@ -19,5 +19,4 @@ app = FastAPI()
async def read_item(item_id: str):
if item_id == "foo":
return {"id": "foo", "value": "there goes my hero"}
- else:
- return JSONResponse(status_code=404, content={"message": "Item not found"})
+ return JSONResponse(status_code=404, content={"message": "Item not found"})
diff --git a/docs_src/custom_response/tutorial001b.py b/docs_src/custom_response/tutorial001b.py
index e98460372..95e6ca763 100644
--- a/docs_src/custom_response/tutorial001b.py
+++ b/docs_src/custom_response/tutorial001b.py
@@ -6,4 +6,4 @@ app = FastAPI()
@app.get("/items/", response_class=ORJSONResponse)
async def read_items():
- return [{"item_id": "Foo"}]
+ return ORJSONResponse([{"item_id": "Foo"}])
diff --git a/docs_src/custom_response/tutorial009c.py b/docs_src/custom_response/tutorial009c.py
new file mode 100644
index 000000000..de6b6688e
--- /dev/null
+++ b/docs_src/custom_response/tutorial009c.py
@@ -0,0 +1,19 @@
+from typing import Any
+
+import orjson
+from fastapi import FastAPI, Response
+
+app = FastAPI()
+
+
+class CustomORJSONResponse(Response):
+ media_type = "application/json"
+
+ def render(self, content: Any) -> bytes:
+ assert orjson is not None, "orjson must be installed"
+ return orjson.dumps(content, option=orjson.OPT_INDENT_2)
+
+
+@app.get("/", response_class=CustomORJSONResponse)
+async def main():
+ return {"message": "Hello World"}
diff --git a/docs_src/path_params/tutorial005.py b/docs_src/path_params/tutorial005.py
index 8e3767744..9a24a4963 100644
--- a/docs_src/path_params/tutorial005.py
+++ b/docs_src/path_params/tutorial005.py
@@ -14,7 +14,7 @@ app = FastAPI()
@app.get("/models/{model_name}")
async def get_model(model_name: ModelName):
- if model_name == ModelName.alexnet:
+ if model_name is ModelName.alexnet:
return {"model_name": model_name, "message": "Deep Learning FTW!"}
if model_name.value == "lenet":
diff --git a/docs_src/security/tutorial007.py b/docs_src/security/tutorial007.py
index 90b9ac054..790ee10bc 100644
--- a/docs_src/security/tutorial007.py
+++ b/docs_src/security/tutorial007.py
@@ -9,9 +9,17 @@ security = HTTPBasic()
def get_current_username(credentials: HTTPBasicCredentials = Depends(security)):
- correct_username = secrets.compare_digest(credentials.username, "stanleyjobson")
- correct_password = secrets.compare_digest(credentials.password, "swordfish")
- if not (correct_username and correct_password):
+ current_username_bytes = credentials.username.encode("utf8")
+ correct_username_bytes = b"stanleyjobson"
+ is_correct_username = secrets.compare_digest(
+ current_username_bytes, correct_username_bytes
+ )
+ current_password_bytes = credentials.password.encode("utf8")
+ correct_password_bytes = b"swordfish"
+ is_correct_password = secrets.compare_digest(
+ current_password_bytes, correct_password_bytes
+ )
+ if not (is_correct_username and is_correct_password):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect email or password",
diff --git a/fastapi/__init__.py b/fastapi/__init__.py
index 2465e2c27..c50543bf9 100644
--- a/fastapi/__init__.py
+++ b/fastapi/__init__.py
@@ -1,6 +1,6 @@
"""FastAPI framework, high performance, easy to learn, fast to code, ready for production"""
-__version__ = "0.78.0"
+__version__ = "0.82.0"
from starlette import status as status
diff --git a/fastapi/applications.py b/fastapi/applications.py
index 7530ddb9b..a242c504c 100644
--- a/fastapi/applications.py
+++ b/fastapi/applications.py
@@ -273,7 +273,7 @@ class FastAPI(Starlette):
path: str,
endpoint: Callable[..., Coroutine[Any, Any, Response]],
*,
- response_model: Optional[Type[Any]] = None,
+ response_model: Any = None,
status_code: Optional[int] = None,
tags: Optional[List[Union[str, Enum]]] = None,
dependencies: Optional[Sequence[Depends]] = None,
@@ -331,7 +331,7 @@ class FastAPI(Starlette):
self,
path: str,
*,
- response_model: Optional[Type[Any]] = None,
+ response_model: Any = None,
status_code: Optional[int] = None,
tags: Optional[List[Union[str, Enum]]] = None,
dependencies: Optional[Sequence[Depends]] = None,
@@ -434,7 +434,7 @@ class FastAPI(Starlette):
self,
path: str,
*,
- response_model: Optional[Type[Any]] = None,
+ response_model: Any = None,
status_code: Optional[int] = None,
tags: Optional[List[Union[str, Enum]]] = None,
dependencies: Optional[Sequence[Depends]] = None,
@@ -489,7 +489,7 @@ class FastAPI(Starlette):
self,
path: str,
*,
- response_model: Optional[Type[Any]] = None,
+ response_model: Any = None,
status_code: Optional[int] = None,
tags: Optional[List[Union[str, Enum]]] = None,
dependencies: Optional[Sequence[Depends]] = None,
@@ -544,7 +544,7 @@ class FastAPI(Starlette):
self,
path: str,
*,
- response_model: Optional[Type[Any]] = None,
+ response_model: Any = None,
status_code: Optional[int] = None,
tags: Optional[List[Union[str, Enum]]] = None,
dependencies: Optional[Sequence[Depends]] = None,
@@ -599,7 +599,7 @@ class FastAPI(Starlette):
self,
path: str,
*,
- response_model: Optional[Type[Any]] = None,
+ response_model: Any = None,
status_code: Optional[int] = None,
tags: Optional[List[Union[str, Enum]]] = None,
dependencies: Optional[Sequence[Depends]] = None,
@@ -635,10 +635,10 @@ class FastAPI(Starlette):
response_description=response_description,
responses=responses,
deprecated=deprecated,
+ operation_id=operation_id,
response_model_include=response_model_include,
response_model_exclude=response_model_exclude,
response_model_by_alias=response_model_by_alias,
- operation_id=operation_id,
response_model_exclude_unset=response_model_exclude_unset,
response_model_exclude_defaults=response_model_exclude_defaults,
response_model_exclude_none=response_model_exclude_none,
@@ -654,7 +654,7 @@ class FastAPI(Starlette):
self,
path: str,
*,
- response_model: Optional[Type[Any]] = None,
+ response_model: Any = None,
status_code: Optional[int] = None,
tags: Optional[List[Union[str, Enum]]] = None,
dependencies: Optional[Sequence[Depends]] = None,
@@ -709,7 +709,7 @@ class FastAPI(Starlette):
self,
path: str,
*,
- response_model: Optional[Type[Any]] = None,
+ response_model: Any = None,
status_code: Optional[int] = None,
tags: Optional[List[Union[str, Enum]]] = None,
dependencies: Optional[Sequence[Depends]] = None,
@@ -764,7 +764,7 @@ class FastAPI(Starlette):
self,
path: str,
*,
- response_model: Optional[Type[Any]] = None,
+ response_model: Any = None,
status_code: Optional[int] = None,
tags: Optional[List[Union[str, Enum]]] = None,
dependencies: Optional[Sequence[Depends]] = None,
@@ -819,7 +819,7 @@ class FastAPI(Starlette):
self,
path: str,
*,
- response_model: Optional[Type[Any]] = None,
+ response_model: Any = None,
status_code: Optional[int] = None,
tags: Optional[List[Union[str, Enum]]] = None,
dependencies: Optional[Sequence[Depends]] = None,
diff --git a/fastapi/concurrency.py b/fastapi/concurrency.py
index becac3f33..c728ec1d2 100644
--- a/fastapi/concurrency.py
+++ b/fastapi/concurrency.py
@@ -1,6 +1,8 @@
import sys
from typing import AsyncGenerator, ContextManager, TypeVar
+import anyio
+from anyio import CapacityLimiter
from starlette.concurrency import iterate_in_threadpool as iterate_in_threadpool # noqa
from starlette.concurrency import run_in_threadpool as run_in_threadpool # noqa
from starlette.concurrency import ( # noqa
@@ -22,11 +24,24 @@ _T = TypeVar("_T")
async def contextmanager_in_threadpool(
cm: ContextManager[_T],
) -> AsyncGenerator[_T, None]:
+ # blocking __exit__ from running waiting on a free thread
+ # can create race conditions/deadlocks if the context manager itself
+ # has it's own internal pool (e.g. a database connection pool)
+ # to avoid this we let __exit__ run without a capacity limit
+ # since we're creating a new limiter for each call, any non-zero limit
+ # works (1 is arbitrary)
+ exit_limiter = CapacityLimiter(1)
try:
yield await run_in_threadpool(cm.__enter__)
except Exception as e:
- ok: bool = await run_in_threadpool(cm.__exit__, type(e), e, None)
+ ok = bool(
+ await anyio.to_thread.run_sync(
+ cm.__exit__, type(e), e, None, limiter=exit_limiter
+ )
+ )
if not ok:
raise e
else:
- await run_in_threadpool(cm.__exit__, None, None, None)
+ await anyio.to_thread.run_sync(
+ cm.__exit__, None, None, None, limiter=exit_limiter
+ )
diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py
index 19ae9ad40..ee3f6f8d9 100644
--- a/fastapi/dependencies/utils.py
+++ b/fastapi/dependencies/utils.py
@@ -34,6 +34,7 @@ from pydantic import BaseModel, create_model
from pydantic.error_wrappers import ErrorWrapper
from pydantic.errors import MissingError
from pydantic.fields import (
+ SHAPE_FROZENSET,
SHAPE_LIST,
SHAPE_SEQUENCE,
SHAPE_SET,
@@ -58,6 +59,7 @@ from starlette.websockets import WebSocket
sequence_shapes = {
SHAPE_LIST,
SHAPE_SET,
+ SHAPE_FROZENSET,
SHAPE_TUPLE,
SHAPE_SEQUENCE,
SHAPE_TUPLE_ELLIPSIS,
@@ -161,7 +163,6 @@ def get_sub_dependant(
)
if security_requirement:
sub_dependant.security_requirements.append(security_requirement)
- sub_dependant.security_scopes = security_scopes
return sub_dependant
@@ -279,7 +280,13 @@ def get_dependant(
path_param_names = get_path_param_names(path)
endpoint_signature = get_typed_signature(call)
signature_params = endpoint_signature.parameters
- dependant = Dependant(call=call, name=name, path=path, use_cache=use_cache)
+ dependant = Dependant(
+ call=call,
+ name=name,
+ path=path,
+ security_scopes=security_scopes,
+ use_cache=use_cache,
+ )
for param_name, param in signature_params.items():
if isinstance(param.default, params.Depends):
sub_dependant = get_param_sub_dependant(
@@ -296,10 +303,7 @@ def get_dependant(
assert is_scalar_field(
field=param_field
), "Path params must be of one of the supported types"
- if isinstance(param.default, params.Path):
- ignore_default = False
- else:
- ignore_default = True
+ ignore_default = not isinstance(param.default, params.Path)
param_field = get_param_field(
param=param,
param_name=param_name,
@@ -496,7 +500,6 @@ async def solve_dependencies(
name=sub_dependant.name,
security_scopes=sub_dependant.security_scopes,
)
- use_sub_dependant.security_scopes = sub_dependant.security_scopes
solved_result = await solve_dependencies(
request=request,
diff --git a/fastapi/encoders.py b/fastapi/encoders.py
index 4b7ffe313..f64e4b86e 100644
--- a/fastapi/encoders.py
+++ b/fastapi/encoders.py
@@ -71,7 +71,14 @@ def jsonable_encoder(
sqlalchemy_safe=sqlalchemy_safe,
)
if dataclasses.is_dataclass(obj):
- return dataclasses.asdict(obj)
+ obj_dict = dataclasses.asdict(obj)
+ return jsonable_encoder(
+ obj_dict,
+ exclude_none=exclude_none,
+ exclude_defaults=exclude_defaults,
+ custom_encoder=custom_encoder,
+ sqlalchemy_safe=sqlalchemy_safe,
+ )
if isinstance(obj, Enum):
return obj.value
if isinstance(obj, PurePath):
@@ -80,6 +87,11 @@ def jsonable_encoder(
return obj
if isinstance(obj, dict):
encoded_dict = {}
+ allowed_keys = set(obj.keys())
+ if include is not None:
+ allowed_keys &= set(include)
+ if exclude is not None:
+ allowed_keys -= set(exclude)
for key, value in obj.items():
if (
(
@@ -88,7 +100,7 @@ def jsonable_encoder(
or (not key.startswith("_sa"))
)
and (value is not None or not exclude_none)
- and ((include and key in include) or not exclude or key not in exclude)
+ and key in allowed_keys
):
encoded_key = jsonable_encoder(
key,
@@ -132,10 +144,10 @@ def jsonable_encoder(
if isinstance(obj, classes_tuple):
return encoder(obj)
- errors: List[Exception] = []
try:
data = dict(obj)
except Exception as e:
+ errors: List[Exception] = []
errors.append(e)
try:
data = vars(obj)
@@ -144,6 +156,8 @@ def jsonable_encoder(
raise ValueError(errors)
return jsonable_encoder(
data,
+ include=include,
+ exclude=exclude,
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
diff --git a/fastapi/openapi/constants.py b/fastapi/openapi/constants.py
index 3e69e5524..1897ad750 100644
--- a/fastapi/openapi/constants.py
+++ b/fastapi/openapi/constants.py
@@ -1,3 +1,2 @@
METHODS_WITH_BODY = {"GET", "HEAD", "POST", "PUT", "DELETE", "PATCH"}
-STATUS_CODES_WITH_NO_BODY = {100, 101, 102, 103, 204, 304}
REF_PREFIX = "#/components/schemas/"
diff --git a/fastapi/openapi/docs.py b/fastapi/openapi/docs.py
index d6af17a85..bf335118f 100644
--- a/fastapi/openapi/docs.py
+++ b/fastapi/openapi/docs.py
@@ -106,6 +106,9 @@ def get_redoc_html(
+