diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index a8f4c4de2..fd9f3b11c 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -4,13 +4,13 @@ contact_links: about: Please report security vulnerabilities to security@tiangolo.com - name: Question or Problem about: Ask a question or ask about a problem in GitHub Discussions. - url: https://github.com/tiangolo/fastapi/discussions/categories/questions + url: https://github.com/fastapi/fastapi/discussions/categories/questions - name: Feature Request about: To suggest an idea or ask about a feature, please start with a question saying what you would like to achieve. There might be a way to do it already. - url: https://github.com/tiangolo/fastapi/discussions/categories/questions + url: https://github.com/fastapi/fastapi/discussions/categories/questions - name: Show and tell about: Show what you built with FastAPI or to be used with FastAPI. - url: https://github.com/tiangolo/fastapi/discussions/categories/show-and-tell + url: https://github.com/fastapi/fastapi/discussions/categories/show-and-tell - name: Translations about: Coordinate translations in GitHub Discussions. - url: https://github.com/tiangolo/fastapi/discussions/categories/translations + url: https://github.com/fastapi/fastapi/discussions/categories/translations diff --git a/.github/ISSUE_TEMPLATE/privileged.yml b/.github/ISSUE_TEMPLATE/privileged.yml index c01e34b6d..2b85eb310 100644 --- a/.github/ISSUE_TEMPLATE/privileged.yml +++ b/.github/ISSUE_TEMPLATE/privileged.yml @@ -6,7 +6,7 @@ body: value: | Thanks for your interest in FastAPI! 🚀 - If you are not @tiangolo or he didn't ask you directly to create an issue here, please start the conversation in a [Question in GitHub Discussions](https://github.com/tiangolo/fastapi/discussions/categories/questions) instead. + If you are not @tiangolo or he didn't ask you directly to create an issue here, please start the conversation in a [Question in GitHub Discussions](https://github.com/fastapi/fastapi/discussions/categories/questions) instead. - type: checkboxes id: privileged attributes: diff --git a/.github/actions/comment-docs-preview-in-pr/Dockerfile b/.github/actions/comment-docs-preview-in-pr/Dockerfile deleted file mode 100644 index 42627fe19..000000000 --- a/.github/actions/comment-docs-preview-in-pr/Dockerfile +++ /dev/null @@ -1,9 +0,0 @@ -FROM python:3.10 - -COPY ./requirements.txt /app/requirements.txt - -RUN pip install -r /app/requirements.txt - -COPY ./app /app - -CMD ["python", "/app/main.py"] diff --git a/.github/actions/comment-docs-preview-in-pr/action.yml b/.github/actions/comment-docs-preview-in-pr/action.yml deleted file mode 100644 index 0eb64402d..000000000 --- a/.github/actions/comment-docs-preview-in-pr/action.yml +++ /dev/null @@ -1,13 +0,0 @@ -name: Comment Docs Preview in PR -description: Comment with the docs URL preview in the PR -author: Sebastián Ramírez -inputs: - token: - description: Token for the repo. Can be passed in using {{ secrets.GITHUB_TOKEN }} - required: true - deploy_url: - description: The deployment URL to comment in the PR - required: true -runs: - using: docker - image: Dockerfile diff --git a/.github/actions/comment-docs-preview-in-pr/app/main.py b/.github/actions/comment-docs-preview-in-pr/app/main.py deleted file mode 100644 index 8cc119fe0..000000000 --- a/.github/actions/comment-docs-preview-in-pr/app/main.py +++ /dev/null @@ -1,69 +0,0 @@ -import logging -import sys -from pathlib import Path -from typing import Union - -import httpx -from github import Github -from github.PullRequest import PullRequest -from pydantic import BaseModel, SecretStr, ValidationError -from pydantic_settings import BaseSettings - -github_api = "https://api.github.com" - - -class Settings(BaseSettings): - github_repository: str - github_event_path: Path - github_event_name: Union[str, None] = None - input_token: SecretStr - input_deploy_url: str - - -class PartialGithubEventHeadCommit(BaseModel): - id: str - - -class PartialGithubEventWorkflowRun(BaseModel): - head_commit: PartialGithubEventHeadCommit - - -class PartialGithubEvent(BaseModel): - workflow_run: PartialGithubEventWorkflowRun - - -if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) - settings = Settings() - logging.info(f"Using config: {settings.json()}") - g = Github(settings.input_token.get_secret_value()) - repo = g.get_repo(settings.github_repository) - try: - event = PartialGithubEvent.parse_file(settings.github_event_path) - except ValidationError as e: - logging.error(f"Error parsing event file: {e.errors()}") - sys.exit(0) - 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 - break - if not use_pr: - logging.error(f"No PR found for hash: {event.workflow_run.head_commit.id}") - sys.exit(0) - github_headers = { - "Authorization": f"token {settings.input_token.get_secret_value()}" - } - url = f"{github_api}/repos/{settings.github_repository}/issues/{use_pr.number}/comments" - logging.info(f"Using comments URL: {url}") - response = httpx.post( - url, - headers=github_headers, - json={ - "body": f"📝 Docs preview for commit {use_pr.head.sha} at: {settings.input_deploy_url}" - }, - ) - if not (200 <= response.status_code <= 300): - logging.error(f"Error posting comment: {response.text}") - sys.exit(1) - logging.info("Finished") diff --git a/.github/actions/comment-docs-preview-in-pr/requirements.txt b/.github/actions/comment-docs-preview-in-pr/requirements.txt deleted file mode 100644 index 74a3631f4..000000000 --- a/.github/actions/comment-docs-preview-in-pr/requirements.txt +++ /dev/null @@ -1,4 +0,0 @@ -PyGithub -pydantic>=2.5.3,<3.0.0 -pydantic-settings>=2.1.0,<3.0.0 -httpx diff --git a/.github/actions/notify-translations/Dockerfile b/.github/actions/notify-translations/Dockerfile deleted file mode 100644 index b68b4bb1a..000000000 --- a/.github/actions/notify-translations/Dockerfile +++ /dev/null @@ -1,7 +0,0 @@ -FROM python:3.9 - -RUN pip install httpx PyGithub "pydantic==1.5.1" "pyyaml>=5.3.1,<6.0.0" - -COPY ./app /app - -CMD ["python", "/app/main.py"] diff --git a/.github/actions/notify-translations/action.yml b/.github/actions/notify-translations/action.yml deleted file mode 100644 index c3579977c..000000000 --- a/.github/actions/notify-translations/action.yml +++ /dev/null @@ -1,10 +0,0 @@ -name: "Notify Translations" -description: "Notify in the issue for a translation when there's a new PR available" -author: "Sebastián Ramírez " -inputs: - token: - description: 'Token, to read the GitHub API. Can be passed in using {{ secrets.GITHUB_TOKEN }}' - required: true -runs: - using: 'docker' - image: 'Dockerfile' diff --git a/.github/actions/notify-translations/app/main.py b/.github/actions/notify-translations/app/main.py deleted file mode 100644 index 8ac1f233d..000000000 --- a/.github/actions/notify-translations/app/main.py +++ /dev/null @@ -1,417 +0,0 @@ -import logging -import random -import sys -import time -from pathlib import Path -from typing import Any, Dict, List, Union, cast - -import httpx -from github import Github -from pydantic import BaseModel, BaseSettings, SecretStr - -awaiting_label = "awaiting-review" -lang_all_label = "lang-all" -approved_label = "approved-2" -translations_path = Path(__file__).parent / "translations.yml" - -github_graphql_url = "https://api.github.com/graphql" -questions_translations_category_id = "DIC_kwDOCZduT84CT5P9" - -all_discussions_query = """ -query Q($category_id: ID) { - repository(name: "fastapi", owner: "tiangolo") { - discussions(categoryId: $category_id, first: 100) { - nodes { - title - id - number - labels(first: 10) { - edges { - node { - id - name - } - } - } - } - } - } -} -""" - -translation_discussion_query = """ -query Q($after: String, $discussion_number: Int!) { - repository(name: "fastapi", owner: "tiangolo") { - discussion(number: $discussion_number) { - comments(first: 100, after: $after) { - edges { - cursor - node { - id - url - body - } - } - } - } - } -} -""" - -add_comment_mutation = """ -mutation Q($discussion_id: ID!, $body: String!) { - addDiscussionComment(input: {discussionId: $discussion_id, body: $body}) { - comment { - id - url - body - } - } -} -""" - -update_comment_mutation = """ -mutation Q($comment_id: ID!, $body: String!) { - updateDiscussionComment(input: {commentId: $comment_id, body: $body}) { - comment { - id - url - body - } - } -} -""" - - -class Comment(BaseModel): - id: str - url: str - body: str - - -class UpdateDiscussionComment(BaseModel): - comment: Comment - - -class UpdateCommentData(BaseModel): - updateDiscussionComment: UpdateDiscussionComment - - -class UpdateCommentResponse(BaseModel): - data: UpdateCommentData - - -class AddDiscussionComment(BaseModel): - comment: Comment - - -class AddCommentData(BaseModel): - addDiscussionComment: AddDiscussionComment - - -class AddCommentResponse(BaseModel): - data: AddCommentData - - -class CommentsEdge(BaseModel): - node: Comment - cursor: str - - -class Comments(BaseModel): - edges: List[CommentsEdge] - - -class CommentsDiscussion(BaseModel): - comments: Comments - - -class CommentsRepository(BaseModel): - discussion: CommentsDiscussion - - -class CommentsData(BaseModel): - repository: CommentsRepository - - -class CommentsResponse(BaseModel): - data: CommentsData - - -class AllDiscussionsLabelNode(BaseModel): - id: str - name: str - - -class AllDiscussionsLabelsEdge(BaseModel): - node: AllDiscussionsLabelNode - - -class AllDiscussionsDiscussionLabels(BaseModel): - edges: List[AllDiscussionsLabelsEdge] - - -class AllDiscussionsDiscussionNode(BaseModel): - title: str - id: str - number: int - labels: AllDiscussionsDiscussionLabels - - -class AllDiscussionsDiscussions(BaseModel): - nodes: List[AllDiscussionsDiscussionNode] - - -class AllDiscussionsRepository(BaseModel): - discussions: AllDiscussionsDiscussions - - -class AllDiscussionsData(BaseModel): - repository: AllDiscussionsRepository - - -class AllDiscussionsResponse(BaseModel): - data: AllDiscussionsData - - -class Settings(BaseSettings): - github_repository: str - input_token: SecretStr - github_event_path: Path - github_event_name: Union[str, None] = None - httpx_timeout: int = 30 - input_debug: Union[bool, None] = False - - -class PartialGitHubEventIssue(BaseModel): - number: int - - -class PartialGitHubEvent(BaseModel): - pull_request: PartialGitHubEventIssue - - -def get_graphql_response( - *, - settings: Settings, - query: str, - after: Union[str, None] = None, - category_id: Union[str, None] = None, - discussion_number: Union[int, None] = None, - discussion_id: Union[str, None] = None, - comment_id: Union[str, None] = None, - body: Union[str, None] = None, -) -> Dict[str, Any]: - headers = {"Authorization": f"token {settings.input_token.get_secret_value()}"} - # some fields are only used by one query, but GraphQL allows unused variables, so - # keep them here for simplicity - variables = { - "after": after, - "category_id": category_id, - "discussion_number": discussion_number, - "discussion_id": discussion_id, - "comment_id": comment_id, - "body": body, - } - response = httpx.post( - github_graphql_url, - headers=headers, - timeout=settings.httpx_timeout, - json={"query": query, "variables": variables, "operationName": "Q"}, - ) - if response.status_code != 200: - logging.error( - f"Response was not 200, after: {after}, category_id: {category_id}" - ) - logging.error(response.text) - raise RuntimeError(response.text) - data = response.json() - if "errors" in data: - logging.error(f"Errors in response, after: {after}, category_id: {category_id}") - logging.error(response.text) - raise RuntimeError(response.text) - return cast(Dict[str, Any], data) - - -def get_graphql_translation_discussions(*, settings: Settings): - data = get_graphql_response( - settings=settings, - query=all_discussions_query, - category_id=questions_translations_category_id, - ) - graphql_response = AllDiscussionsResponse.parse_obj(data) - return graphql_response.data.repository.discussions.nodes - - -def get_graphql_translation_discussion_comments_edges( - *, settings: Settings, discussion_number: int, after: Union[str, None] = None -): - data = get_graphql_response( - settings=settings, - query=translation_discussion_query, - discussion_number=discussion_number, - after=after, - ) - graphql_response = CommentsResponse.parse_obj(data) - return graphql_response.data.repository.discussion.comments.edges - - -def get_graphql_translation_discussion_comments( - *, settings: Settings, discussion_number: int -): - comment_nodes: List[Comment] = [] - discussion_edges = get_graphql_translation_discussion_comments_edges( - settings=settings, discussion_number=discussion_number - ) - - while discussion_edges: - for discussion_edge in discussion_edges: - comment_nodes.append(discussion_edge.node) - last_edge = discussion_edges[-1] - discussion_edges = get_graphql_translation_discussion_comments_edges( - settings=settings, - discussion_number=discussion_number, - after=last_edge.cursor, - ) - return comment_nodes - - -def create_comment(*, settings: Settings, discussion_id: str, body: str): - data = get_graphql_response( - settings=settings, - query=add_comment_mutation, - discussion_id=discussion_id, - body=body, - ) - response = AddCommentResponse.parse_obj(data) - return response.data.addDiscussionComment.comment - - -def update_comment(*, settings: Settings, comment_id: str, body: str): - data = get_graphql_response( - settings=settings, - query=update_comment_mutation, - comment_id=comment_id, - body=body, - ) - response = UpdateCommentResponse.parse_obj(data) - return response.data.updateDiscussionComment.comment - - -if __name__ == "__main__": - settings = Settings() - if settings.input_debug: - logging.basicConfig(level=logging.DEBUG) - else: - logging.basicConfig(level=logging.INFO) - logging.debug(f"Using config: {settings.json()}") - g = Github(settings.input_token.get_secret_value()) - repo = g.get_repo(settings.github_repository) - if not settings.github_event_path.is_file(): - raise RuntimeError( - f"No github event file available at: {settings.github_event_path}" - ) - contents = settings.github_event_path.read_text() - github_event = PartialGitHubEvent.parse_raw(contents) - - # Avoid race conditions with multiple labels - sleep_time = random.random() * 10 # random number between 0 and 10 seconds - logging.info( - f"Sleeping for {sleep_time} seconds to avoid " - "race conditions and multiple comments" - ) - time.sleep(sleep_time) - - # Get PR - logging.debug(f"Processing PR: #{github_event.pull_request.number}") - pr = repo.get_pull(github_event.pull_request.number) - label_strs = {label.name for label in pr.get_labels()} - langs = [] - for label in label_strs: - if label.startswith("lang-") and not label == lang_all_label: - langs.append(label[5:]) - logging.info(f"PR #{pr.number} has labels: {label_strs}") - if not langs or lang_all_label not in label_strs: - logging.info(f"PR #{pr.number} doesn't seem to be a translation PR, skipping") - sys.exit(0) - - # Generate translation map, lang ID to discussion - discussions = get_graphql_translation_discussions(settings=settings) - lang_to_discussion_map: Dict[str, AllDiscussionsDiscussionNode] = {} - for discussion in discussions: - for edge in discussion.labels.edges: - label = edge.node.name - if label.startswith("lang-") and not label == lang_all_label: - lang = label[5:] - lang_to_discussion_map[lang] = discussion - logging.debug(f"Using translations map: {lang_to_discussion_map}") - - # Messages to create or check - new_translation_message = f"Good news everyone! 😉 There's a new translation PR to be reviewed: #{pr.number} by @{pr.user.login}. 🎉 This requires 2 approvals from native speakers to be merged. 🤓" - done_translation_message = f"~There's a new translation PR to be reviewed: #{pr.number} by @{pr.user.login}~ Good job! This is done. 🍰☕" - - # Normally only one language, but still - for lang in langs: - if lang not in lang_to_discussion_map: - log_message = f"Could not find discussion for language: {lang}" - logging.error(log_message) - raise RuntimeError(log_message) - discussion = lang_to_discussion_map[lang] - logging.info( - f"Found a translation discussion for language: {lang} in discussion: #{discussion.number}" - ) - - already_notified_comment: Union[Comment, None] = None - already_done_comment: Union[Comment, None] = None - - logging.info( - f"Checking current comments in discussion: #{discussion.number} to see if already notified about this PR: #{pr.number}" - ) - comments = get_graphql_translation_discussion_comments( - settings=settings, discussion_number=discussion.number - ) - for comment in comments: - if new_translation_message in comment.body: - already_notified_comment = comment - elif done_translation_message in comment.body: - already_done_comment = comment - logging.info( - f"Already notified comment: {already_notified_comment}, already done comment: {already_done_comment}" - ) - - if pr.state == "open" and awaiting_label in label_strs: - logging.info( - f"This PR seems to be a language translation and awaiting reviews: #{pr.number}" - ) - if already_notified_comment: - logging.info( - f"This PR #{pr.number} was already notified in comment: {already_notified_comment.url}" - ) - else: - logging.info( - f"Writing notification comment about PR #{pr.number} in Discussion: #{discussion.number}" - ) - comment = create_comment( - settings=settings, - discussion_id=discussion.id, - body=new_translation_message, - ) - logging.info(f"Notified in comment: {comment.url}") - elif pr.state == "closed" or approved_label in label_strs: - logging.info(f"Already approved or closed PR #{pr.number}") - if already_done_comment: - logging.info( - f"This PR #{pr.number} was already marked as done in comment: {already_done_comment.url}" - ) - elif already_notified_comment: - updated_comment = update_comment( - settings=settings, - comment_id=already_notified_comment.id, - body=done_translation_message, - ) - logging.info(f"Marked as done in comment: {updated_comment.url}") - else: - logging.info( - f"There doesn't seem to be anything to be done about PR #{pr.number}" - ) - logging.info("Finished") diff --git a/.github/actions/people/Dockerfile b/.github/actions/people/Dockerfile deleted file mode 100644 index 1455106bd..000000000 --- a/.github/actions/people/Dockerfile +++ /dev/null @@ -1,7 +0,0 @@ -FROM python:3.9 - -RUN pip install httpx PyGithub "pydantic==2.0.2" pydantic-settings "pyyaml>=5.3.1,<6.0.0" - -COPY ./app /app - -CMD ["python", "/app/main.py"] diff --git a/.github/actions/people/action.yml b/.github/actions/people/action.yml deleted file mode 100644 index 71745b874..000000000 --- a/.github/actions/people/action.yml +++ /dev/null @@ -1,10 +0,0 @@ -name: "Generate FastAPI People" -description: "Generate the data for the FastAPI People page" -author: "Sebastián Ramírez " -inputs: - token: - description: 'User token, to read the GitHub API. Can be passed in using {{ secrets.FASTAPI_PEOPLE }}' - required: true -runs: - using: 'docker' - image: 'Dockerfile' diff --git a/.github/actions/people/app/main.py b/.github/actions/people/app/main.py deleted file mode 100644 index cb6b229e8..000000000 --- a/.github/actions/people/app/main.py +++ /dev/null @@ -1,727 +0,0 @@ -import logging -import subprocess -import sys -from collections import Counter, defaultdict -from datetime import datetime, timedelta, timezone -from pathlib import Path -from typing import Any, Container, DefaultDict, Dict, List, Set, Union - -import httpx -import yaml -from github import Github -from pydantic import BaseModel, SecretStr -from pydantic_settings import BaseSettings - -github_graphql_url = "https://api.github.com/graphql" -questions_category_id = "MDE4OkRpc2N1c3Npb25DYXRlZ29yeTMyMDAxNDM0" - -discussions_query = """ -query Q($after: String, $category_id: ID) { - repository(name: "fastapi", owner: "tiangolo") { - discussions(first: 100, after: $after, categoryId: $category_id) { - edges { - cursor - node { - number - author { - login - avatarUrl - url - } - title - createdAt - comments(first: 100) { - nodes { - createdAt - author { - login - avatarUrl - url - } - isAnswer - replies(first: 10) { - nodes { - createdAt - author { - login - avatarUrl - url - } - } - } - } - } - } - } - } - } -} -""" - -issues_query = """ -query Q($after: String) { - repository(name: "fastapi", owner: "tiangolo") { - issues(first: 100, after: $after) { - edges { - cursor - node { - number - author { - login - avatarUrl - url - } - title - createdAt - state - comments(first: 100) { - nodes { - createdAt - author { - login - avatarUrl - url - } - } - } - } - } - } - } -} -""" - -prs_query = """ -query Q($after: String) { - repository(name: "fastapi", owner: "tiangolo") { - pullRequests(first: 100, after: $after) { - edges { - cursor - node { - number - labels(first: 100) { - nodes { - name - } - } - author { - login - avatarUrl - url - } - title - createdAt - state - comments(first: 100) { - nodes { - createdAt - author { - login - avatarUrl - url - } - } - } - reviews(first:100) { - nodes { - author { - login - avatarUrl - url - } - state - } - } - } - } - } - } -} -""" - -sponsors_query = """ -query Q($after: String) { - user(login: "tiangolo") { - sponsorshipsAsMaintainer(first: 100, after: $after) { - edges { - cursor - node { - sponsorEntity { - ... on Organization { - login - avatarUrl - url - } - ... on User { - login - avatarUrl - url - } - } - tier { - name - monthlyPriceInDollars - } - } - } - } - } -} -""" - - -class Author(BaseModel): - login: str - avatarUrl: str - url: str - - -# Issues and Discussions - - -class CommentsNode(BaseModel): - createdAt: datetime - author: Union[Author, None] = None - - -class Replies(BaseModel): - nodes: List[CommentsNode] - - -class DiscussionsCommentsNode(CommentsNode): - replies: Replies - - -class Comments(BaseModel): - nodes: List[CommentsNode] - - -class DiscussionsComments(BaseModel): - nodes: List[DiscussionsCommentsNode] - - -class IssuesNode(BaseModel): - number: int - author: Union[Author, None] = None - title: str - createdAt: datetime - state: str - comments: Comments - - -class DiscussionsNode(BaseModel): - number: int - author: Union[Author, None] = None - title: str - createdAt: datetime - comments: DiscussionsComments - - -class IssuesEdge(BaseModel): - cursor: str - node: IssuesNode - - -class DiscussionsEdge(BaseModel): - cursor: str - node: DiscussionsNode - - -class Issues(BaseModel): - edges: List[IssuesEdge] - - -class Discussions(BaseModel): - edges: List[DiscussionsEdge] - - -class IssuesRepository(BaseModel): - issues: Issues - - -class DiscussionsRepository(BaseModel): - discussions: Discussions - - -class IssuesResponseData(BaseModel): - repository: IssuesRepository - - -class DiscussionsResponseData(BaseModel): - repository: DiscussionsRepository - - -class IssuesResponse(BaseModel): - data: IssuesResponseData - - -class DiscussionsResponse(BaseModel): - data: DiscussionsResponseData - - -# PRs - - -class LabelNode(BaseModel): - name: str - - -class Labels(BaseModel): - nodes: List[LabelNode] - - -class ReviewNode(BaseModel): - author: Union[Author, None] = None - state: str - - -class Reviews(BaseModel): - nodes: List[ReviewNode] - - -class PullRequestNode(BaseModel): - number: int - labels: Labels - author: Union[Author, None] = None - title: str - createdAt: datetime - state: str - comments: Comments - reviews: Reviews - - -class PullRequestEdge(BaseModel): - cursor: str - node: PullRequestNode - - -class PullRequests(BaseModel): - edges: List[PullRequestEdge] - - -class PRsRepository(BaseModel): - pullRequests: PullRequests - - -class PRsResponseData(BaseModel): - repository: PRsRepository - - -class PRsResponse(BaseModel): - data: PRsResponseData - - -# Sponsors - - -class SponsorEntity(BaseModel): - login: str - avatarUrl: str - url: str - - -class Tier(BaseModel): - name: str - monthlyPriceInDollars: float - - -class SponsorshipAsMaintainerNode(BaseModel): - sponsorEntity: SponsorEntity - tier: Tier - - -class SponsorshipAsMaintainerEdge(BaseModel): - cursor: str - node: SponsorshipAsMaintainerNode - - -class SponsorshipAsMaintainer(BaseModel): - edges: List[SponsorshipAsMaintainerEdge] - - -class SponsorsUser(BaseModel): - sponsorshipsAsMaintainer: SponsorshipAsMaintainer - - -class SponsorsResponseData(BaseModel): - user: SponsorsUser - - -class SponsorsResponse(BaseModel): - data: SponsorsResponseData - - -class Settings(BaseSettings): - input_token: SecretStr - github_repository: str - httpx_timeout: int = 30 - - -def get_graphql_response( - *, - settings: Settings, - query: str, - after: Union[str, None] = None, - category_id: Union[str, None] = None, -) -> Dict[str, Any]: - headers = {"Authorization": f"token {settings.input_token.get_secret_value()}"} - # category_id is only used by one query, but GraphQL allows unused variables, so - # keep it here for simplicity - variables = {"after": after, "category_id": category_id} - response = httpx.post( - github_graphql_url, - headers=headers, - timeout=settings.httpx_timeout, - json={"query": query, "variables": variables, "operationName": "Q"}, - ) - if response.status_code != 200: - logging.error( - f"Response was not 200, after: {after}, category_id: {category_id}" - ) - logging.error(response.text) - raise RuntimeError(response.text) - data = response.json() - if "errors" in data: - logging.error(f"Errors in response, after: {after}, category_id: {category_id}") - logging.error(data["errors"]) - logging.error(response.text) - raise RuntimeError(response.text) - return data - - -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.model_validate(data) - return graphql_response.data.repository.issues.edges - - -def get_graphql_question_discussion_edges( - *, - settings: Settings, - after: Union[str, None] = None, -): - data = get_graphql_response( - settings=settings, - query=discussions_query, - after=after, - category_id=questions_category_id, - ) - graphql_response = DiscussionsResponse.model_validate(data) - return graphql_response.data.repository.discussions.edges - - -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.model_validate(data) - return graphql_response.data.repository.pullRequests.edges - - -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.model_validate(data) - return graphql_response.data.user.sponsorshipsAsMaintainer.edges - - -def get_issues_experts(settings: Settings): - issue_nodes: List[IssuesNode] = [] - issue_edges = get_graphql_issue_edges(settings=settings) - - while issue_edges: - for edge in issue_edges: - issue_nodes.append(edge.node) - last_edge = issue_edges[-1] - issue_edges = get_graphql_issue_edges(settings=settings, after=last_edge.cursor) - - commentors = Counter() - last_month_commentors = Counter() - authors: Dict[str, Author] = {} - - now = datetime.now(tz=timezone.utc) - one_month_ago = now - timedelta(days=30) - - for issue in issue_nodes: - issue_author_name = None - if issue.author: - authors[issue.author.login] = issue.author - issue_author_name = issue.author.login - issue_commentors = set() - for comment in issue.comments.nodes: - if comment.author: - authors[comment.author.login] = comment.author - if comment.author.login != issue_author_name: - issue_commentors.add(comment.author.login) - for author_name in issue_commentors: - commentors[author_name] += 1 - if issue.createdAt > one_month_ago: - last_month_commentors[author_name] += 1 - - return commentors, last_month_commentors, authors - - -def get_discussions_experts(settings: Settings): - discussion_nodes: List[DiscussionsNode] = [] - discussion_edges = get_graphql_question_discussion_edges(settings=settings) - - while discussion_edges: - for discussion_edge in discussion_edges: - discussion_nodes.append(discussion_edge.node) - last_edge = discussion_edges[-1] - discussion_edges = get_graphql_question_discussion_edges( - settings=settings, after=last_edge.cursor - ) - - commentors = Counter() - last_month_commentors = Counter() - authors: Dict[str, Author] = {} - - now = datetime.now(tz=timezone.utc) - one_month_ago = now - timedelta(days=30) - - for discussion in discussion_nodes: - discussion_author_name = None - if discussion.author: - authors[discussion.author.login] = discussion.author - discussion_author_name = discussion.author.login - discussion_commentors = set() - for comment in discussion.comments.nodes: - if comment.author: - authors[comment.author.login] = comment.author - if comment.author.login != discussion_author_name: - discussion_commentors.add(comment.author.login) - for reply in comment.replies.nodes: - if reply.author: - authors[reply.author.login] = reply.author - if reply.author.login != discussion_author_name: - discussion_commentors.add(reply.author.login) - for author_name in discussion_commentors: - commentors[author_name] += 1 - if discussion.createdAt > one_month_ago: - last_month_commentors[author_name] += 1 - return commentors, last_month_commentors, authors - - -def get_experts(settings: Settings): - # Migrated to only use GitHub Discussions - # ( - # issues_commentors, - # issues_last_month_commentors, - # issues_authors, - # ) = get_issues_experts(settings=settings) - ( - discussions_commentors, - discussions_last_month_commentors, - discussions_authors, - ) = get_discussions_experts(settings=settings) - # commentors = issues_commentors + discussions_commentors - commentors = discussions_commentors - # last_month_commentors = ( - # issues_last_month_commentors + discussions_last_month_commentors - # ) - last_month_commentors = discussions_last_month_commentors - # authors = {**issues_authors, **discussions_authors} - authors = {**discussions_authors} - return commentors, last_month_commentors, authors - - -def get_contributors(settings: Settings): - pr_nodes: List[PullRequestNode] = [] - pr_edges = get_graphql_pr_edges(settings=settings) - - while pr_edges: - for edge in pr_edges: - pr_nodes.append(edge.node) - last_edge = pr_edges[-1] - pr_edges = get_graphql_pr_edges(settings=settings, after=last_edge.cursor) - - contributors = Counter() - commentors = Counter() - reviewers = Counter() - authors: Dict[str, Author] = {} - - for pr in pr_nodes: - author_name = None - if pr.author: - authors[pr.author.login] = pr.author - author_name = pr.author.login - pr_commentors: Set[str] = set() - pr_reviewers: Set[str] = set() - for comment in pr.comments.nodes: - if comment.author: - authors[comment.author.login] = comment.author - if comment.author.login == author_name: - continue - pr_commentors.add(comment.author.login) - for author_name in pr_commentors: - commentors[author_name] += 1 - for review in pr.reviews.nodes: - if review.author: - authors[review.author.login] = review.author - pr_reviewers.add(review.author.login) - for reviewer in pr_reviewers: - reviewers[reviewer] += 1 - if pr.state == "MERGED" and pr.author: - contributors[pr.author.login] += 1 - return contributors, commentors, reviewers, authors - - -def get_individual_sponsors(settings: Settings): - nodes: List[SponsorshipAsMaintainerNode] = [] - edges = get_graphql_sponsor_edges(settings=settings) - - while edges: - for edge in edges: - nodes.append(edge.node) - last_edge = edges[-1] - edges = get_graphql_sponsor_edges(settings=settings, after=last_edge.cursor) - - tiers: DefaultDict[float, Dict[str, SponsorEntity]] = defaultdict(dict) - for node in nodes: - tiers[node.tier.monthlyPriceInDollars][ - node.sponsorEntity.login - ] = node.sponsorEntity - return tiers - - -def get_top_users( - *, - counter: Counter, - min_count: int, - authors: Dict[str, Author], - skip_users: Container[str], -): - users = [] - for commentor, count in counter.most_common(50): - if commentor in skip_users: - continue - if count >= min_count: - author = authors[commentor] - users.append( - { - "login": commentor, - "count": count, - "avatarUrl": author.avatarUrl, - "url": author.url, - } - ) - return users - - -if __name__ == "__main__": - logging.basicConfig(level=logging.INFO) - settings = Settings() - logging.info(f"Using config: {settings.model_dump_json()}") - g = Github(settings.input_token.get_secret_value()) - repo = g.get_repo(settings.github_repository) - question_commentors, question_last_month_commentors, question_authors = get_experts( - settings=settings - ) - contributors, pr_commentors, reviewers, pr_authors = get_contributors( - settings=settings - ) - authors = {**question_authors, **pr_authors} - maintainers_logins = {"tiangolo"} - bot_names = {"codecov", "github-actions", "pre-commit-ci", "dependabot"} - maintainers = [] - for login in maintainers_logins: - user = authors[login] - maintainers.append( - { - "login": login, - "answers": question_commentors[login], - "prs": contributors[login], - "avatarUrl": user.avatarUrl, - "url": user.url, - } - ) - - min_count_expert = 10 - min_count_last_month = 3 - min_count_contributor = 4 - min_count_reviewer = 4 - skip_users = maintainers_logins | bot_names - experts = get_top_users( - counter=question_commentors, - min_count=min_count_expert, - authors=authors, - skip_users=skip_users, - ) - last_month_active = get_top_users( - counter=question_last_month_commentors, - min_count=min_count_last_month, - authors=authors, - skip_users=skip_users, - ) - top_contributors = get_top_users( - counter=contributors, - min_count=min_count_contributor, - authors=authors, - skip_users=skip_users, - ) - top_reviewers = get_top_users( - counter=reviewers, - min_count=min_count_reviewer, - authors=authors, - skip_users=skip_users, - ) - - tiers = get_individual_sponsors(settings=settings) - keys = list(tiers.keys()) - keys.sort(reverse=True) - sponsors = [] - for key in keys: - sponsor_group = [] - for login, sponsor in tiers[key].items(): - sponsor_group.append( - {"login": login, "avatarUrl": sponsor.avatarUrl, "url": sponsor.url} - ) - sponsors.append(sponsor_group) - - people = { - "maintainers": maintainers, - "experts": experts, - "last_month_active": last_month_active, - "top_contributors": top_contributors, - "top_reviewers": top_reviewers, - } - github_sponsors = { - "sponsors": sponsors, - } - people_path = Path("./docs/en/data/people.yml") - github_sponsors_path = Path("./docs/en/data/github_sponsors.yml") - people_old_content = people_path.read_text(encoding="utf-8") - github_sponsors_old_content = github_sponsors_path.read_text(encoding="utf-8") - new_people_content = yaml.dump( - people, sort_keys=False, width=200, allow_unicode=True - ) - new_github_sponsors_content = yaml.dump( - github_sponsors, sort_keys=False, width=200, allow_unicode=True - ) - if ( - people_old_content == new_people_content - and github_sponsors_old_content == new_github_sponsors_content - ): - logging.info("The FastAPI People data hasn't changed, finishing.") - sys.exit(0) - people_path.write_text(new_people_content, encoding="utf-8") - github_sponsors_path.write_text(new_github_sponsors_content, encoding="utf-8") - logging.info("Setting up GitHub Actions git user") - subprocess.run(["git", "config", "user.name", "github-actions"], check=True) - subprocess.run( - ["git", "config", "user.email", "github-actions@github.com"], check=True - ) - branch_name = "fastapi-people" - logging.info(f"Creating a new branch {branch_name}") - subprocess.run(["git", "checkout", "-b", branch_name], check=True) - logging.info("Adding updated file") - subprocess.run( - ["git", "add", str(people_path), str(github_sponsors_path)], check=True - ) - logging.info("Committing updated file") - message = "👥 Update FastAPI People" - result = subprocess.run(["git", "commit", "-m", message], check=True) - logging.info("Pushing branch") - subprocess.run(["git", "push", "origin", branch_name], check=True) - logging.info("Creating PR") - pr = repo.create_pull(title=message, body=message, base="master", head=branch_name) - logging.info(f"Created PR: {pr.number}") - logging.info("Finished") diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 0a59adbd6..8979aabf8 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -12,9 +12,5 @@ updates: directory: "/" schedule: interval: "monthly" - groups: - python-packages: - patterns: - - "*" commit-message: prefix: ⬆ diff --git a/.github/labeler.yml b/.github/labeler.yml new file mode 100644 index 000000000..c5b1f84f3 --- /dev/null +++ b/.github/labeler.yml @@ -0,0 +1,38 @@ +docs: + - all: + - changed-files: + - any-glob-to-any-file: + - docs/en/docs/** + - docs_src/** + - all-globs-to-all-files: + - '!fastapi/**' + - '!pyproject.toml' + - '!docs/en/data/sponsors.yml' + - '!docs/en/overrides/main.html' + +lang-all: + - all: + - changed-files: + - any-glob-to-any-file: + - docs/*/docs/** + - all-globs-to-all-files: + - '!docs/en/docs/**' + - '!fastapi/**' + - '!pyproject.toml' + +internal: + - all: + - changed-files: + - any-glob-to-any-file: + - .github/** + - scripts/** + - .gitignore + - .pre-commit-config.yaml + - pdm_build.py + - requirements*.txt + - docs/en/data/sponsors.yml + - docs/en/overrides/main.html + - all-globs-to-all-files: + - '!docs/*/docs/**' + - '!fastapi/**' + - '!pyproject.toml' diff --git a/.github/workflows/add-to-project.yml b/.github/workflows/add-to-project.yml new file mode 100644 index 000000000..dccea83f3 --- /dev/null +++ b/.github/workflows/add-to-project.yml @@ -0,0 +1,18 @@ +name: Add to Project + +on: + pull_request_target: + issues: + types: + - opened + - reopened + +jobs: + add-to-project: + name: Add to project + runs-on: ubuntu-latest + steps: + - uses: actions/add-to-project@v1.0.2 + with: + project-url: https://github.com/orgs/fastapi/projects/2 + github-token: ${{ secrets.PROJECTS_TOKEN }} diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml index abf2b90f6..6ecdf487c 100644 --- a/.github/workflows/build-docs.yml +++ b/.github/workflows/build-docs.yml @@ -7,6 +7,10 @@ on: types: - opened - synchronize + +env: + UV_SYSTEM_PYTHON: 1 + jobs: changes: runs-on: ubuntu-latest @@ -18,8 +22,8 @@ jobs: docs: ${{ steps.filter.outputs.docs }} steps: - uses: actions/checkout@v4 - # For pull requests it's not necessary to checkout the code but for master it is - - uses: dorny/paths-filter@v2 + # For pull requests it's not necessary to checkout the code but for the main branch it is + - uses: dorny/paths-filter@v3 id: filter with: filters: | @@ -28,6 +32,12 @@ jobs: - docs/** - docs_src/** - requirements-docs.txt + - requirements-docs-insiders.txt + - pyproject.toml + - mkdocs.yml + - mkdocs.insiders.yml + - mkdocs.maybe-insiders.yml + - mkdocs.no-insiders.yml - .github/workflows/build-docs.yml - .github/workflows/deploy-docs.yml langs: @@ -42,23 +52,24 @@ jobs: uses: actions/setup-python@v5 with: python-version: "3.11" - - uses: actions/cache@v3 - id: cache + - name: Setup uv + uses: astral-sh/setup-uv@v5 with: - path: ${{ env.pythonLocation }} - key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-docs.txt', 'requirements-docs-tests.txt') }}-v06 + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml - name: Install docs extras - if: steps.cache.outputs.cache-hit != 'true' - run: pip install -r requirements-docs.txt + run: uv pip install -r requirements-docs.txt # Install MkDocs Material Insiders here just to put it in the cache for the rest of the steps - name: Install Material for MkDocs Insiders - if: ( github.event_name != 'pull_request' || github.secret_source == 'Actions' ) && steps.cache.outputs.cache-hit != 'true' - run: | - pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/squidfunk/mkdocs-material-insiders.git - pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/pawamoy-insiders/griffe-typing-deprecated.git - pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/pawamoy-insiders/mkdocstrings-python.git - - name: Verify README - run: python ./scripts/docs.py verify-readme + if: ( github.event_name != 'pull_request' || github.secret_source == 'Actions' ) + run: uv pip install -r requirements-docs-insiders.txt + env: + TOKEN: ${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }} + - name: Verify Docs + run: python ./scripts/docs.py verify-docs - name: Export Language Codes id: show-langs run: | @@ -83,32 +94,34 @@ jobs: uses: actions/setup-python@v5 with: python-version: "3.11" - - uses: actions/cache@v3 - id: cache + - name: Setup uv + uses: astral-sh/setup-uv@v5 with: - path: ${{ env.pythonLocation }} - key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml', 'requirements-docs.txt', 'requirements-docs-tests.txt') }}-v06 + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml - name: Install docs extras - if: steps.cache.outputs.cache-hit != 'true' - run: pip install -r requirements-docs.txt + run: uv pip install -r requirements-docs.txt - name: Install Material for MkDocs Insiders - if: ( github.event_name != 'pull_request' || github.secret_source != 'Actions' ) && steps.cache.outputs.cache-hit != 'true' - run: | - pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/squidfunk/mkdocs-material-insiders.git - pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/pawamoy-insiders/griffe-typing-deprecated.git - pip install git+https://${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }}@github.com/pawamoy-insiders/mkdocstrings-python.git + if: ( github.event_name != 'pull_request' || github.secret_source == 'Actions' ) + run: uv pip install -r requirements-docs-insiders.txt + env: + TOKEN: ${{ secrets.FASTAPI_MKDOCS_MATERIAL_INSIDERS }} - name: Update Languages run: python ./scripts/docs.py update-languages - - uses: actions/cache@v3 + - uses: actions/cache@v4 with: key: mkdocs-cards-${{ matrix.lang }}-${{ github.ref }} path: docs/${{ matrix.lang }}/.cache - name: Build Docs run: python ./scripts/docs.py build-lang ${{ matrix.lang }} - - uses: actions/upload-artifact@v3 + - uses: actions/upload-artifact@v4 with: - name: docs-site + name: docs-site-${{ matrix.lang }} path: ./site/** + include-hidden-files: true # https://github.com/marketplace/actions/alls-green#why docs-all-green: # This job does nothing and is only used for the branch protection diff --git a/.github/workflows/contributors.yml b/.github/workflows/contributors.yml new file mode 100644 index 000000000..87abfe3a1 --- /dev/null +++ b/.github/workflows/contributors.yml @@ -0,0 +1,53 @@ +name: FastAPI People Contributors + +on: + schedule: + - cron: "0 3 1 * *" + workflow_dispatch: + inputs: + debug_enabled: + description: "Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)" + required: false + default: "false" + +env: + UV_SYSTEM_PYTHON: 1 + +jobs: + job: + if: github.repository_owner == 'fastapi' + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - name: Dump GitHub context + env: + GITHUB_CONTEXT: ${{ toJson(github) }} + run: echo "$GITHUB_CONTEXT" + - uses: actions/checkout@v4 + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.11" + - name: Setup uv + uses: astral-sh/setup-uv@v5 + with: + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml + - name: Install Dependencies + run: uv pip install -r requirements-github-actions.txt + # Allow debugging with tmate + - name: Setup tmate session + uses: mxschmitt/action-tmate@v3 + if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }} + with: + limit-access-to-actor: true + env: + GITHUB_TOKEN: ${{ secrets.FASTAPI_PR_TOKEN }} + - name: FastAPI People Contributors + run: python ./scripts/contributors.py + env: + GITHUB_TOKEN: ${{ secrets.FASTAPI_PR_TOKEN }} diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index 2bec6682c..aec327f48 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -6,6 +6,15 @@ on: types: - completed +permissions: + deployments: write + issues: write + pull-requests: write + statuses: write + +env: + UV_SYSTEM_PYTHON: 1 + jobs: deploy-docs: runs-on: ubuntu-latest @@ -15,34 +24,54 @@ jobs: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - uses: actions/checkout@v4 + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.11" + - name: Setup uv + uses: astral-sh/setup-uv@v5 + with: + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml + - name: Install GitHub Actions dependencies + run: uv pip install -r requirements-github-actions.txt + - name: Deploy Docs Status Pending + run: python ./scripts/deploy_docs_status.py + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + COMMIT_SHA: ${{ github.event.workflow_run.head_sha }} + RUN_ID: ${{ github.run_id }} - name: Clean site run: | rm -rf ./site mkdir ./site - - name: Download Artifact Docs - id: download - uses: dawidd6/action-download-artifact@v3.0.0 + - uses: actions/download-artifact@v4 with: - if_no_artifact_found: ignore - github_token: ${{ secrets.FASTAPI_PREVIEW_DOCS_DOWNLOAD_ARTIFACTS }} - workflow: build-docs.yml - run_id: ${{ github.event.workflow_run.id }} - name: docs-site path: ./site/ + pattern: docs-site-* + merge-multiple: true + github-token: ${{ secrets.GITHUB_TOKEN }} + run-id: ${{ github.event.workflow_run.id }} - name: Deploy to Cloudflare Pages - if: steps.download.outputs.found_artifact == 'true' + # hashFiles returns an empty string if there are no files + if: hashFiles('./site/*') id: deploy - uses: cloudflare/pages-action@v1 + env: + PROJECT_NAME: fastapitiangolo + BRANCH: ${{ ( github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.head_branch == 'master' && 'main' ) || ( github.event.workflow_run.head_sha ) }} + uses: cloudflare/wrangler-action@v3 with: apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} - projectName: fastapitiangolo - directory: './site' - gitHubToken: ${{ secrets.GITHUB_TOKEN }} - branch: ${{ ( github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.head_branch == 'master' && 'main' ) || ( github.event.workflow_run.head_sha ) }} + command: pages deploy ./site --project-name=${{ env.PROJECT_NAME }} --branch=${{ env.BRANCH }} - name: Comment Deploy - if: steps.deploy.outputs.url != '' - uses: ./.github/actions/comment-docs-preview-in-pr - with: - token: ${{ secrets.FASTAPI_PREVIEW_DOCS_COMMENT_DEPLOY }} - deploy_url: "${{ steps.deploy.outputs.url }}" + run: python ./scripts/deploy_docs_status.py + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + DEPLOY_URL: ${{ steps.deploy.outputs.deployment-url }} + COMMIT_SHA: ${{ github.event.workflow_run.head_sha }} + RUN_ID: ${{ github.run_id }} + IS_DONE: "true" diff --git a/.github/workflows/issue-manager.yml b/.github/workflows/issue-manager.yml index bb967fa11..6a7e6143e 100644 --- a/.github/workflows/issue-manager.yml +++ b/.github/workflows/issue-manager.yml @@ -2,7 +2,7 @@ name: Issue Manager on: schedule: - - cron: "10 3 * * *" + - cron: "13 22 * * *" issue_comment: types: - created @@ -14,22 +14,34 @@ on: - labeled workflow_dispatch: +permissions: + issues: write + pull-requests: write + jobs: issue-manager: - if: github.repository_owner == 'tiangolo' + if: github.repository_owner == 'fastapi' runs-on: ubuntu-latest steps: - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - - uses: tiangolo/issue-manager@0.4.0 + - uses: tiangolo/issue-manager@0.5.1 with: - token: ${{ secrets.FASTAPI_ISSUE_MANAGER }} + token: ${{ secrets.GITHUB_TOKEN }} config: > { "answered": { "delay": 864000, "message": "Assuming the original need was handled, this will be automatically closed now. But feel free to add more comments or create new issues or PRs." + }, + "waiting": { + "delay": 2628000, + "message": "As this PR has been waiting for the original user for a while but seems to be inactive, it's now going to be closed. But if there's anyone interested, feel free to create a new PR." + }, + "invalid": { + "delay": 0, + "message": "This was marked as invalid and will be closed now. If this is an error, please provide additional details." } } diff --git a/.github/workflows/label-approved.yml b/.github/workflows/label-approved.yml index 62daf2608..02070146c 100644 --- a/.github/workflows/label-approved.yml +++ b/.github/workflows/label-approved.yml @@ -5,15 +5,45 @@ on: - cron: "0 12 * * *" workflow_dispatch: +permissions: + pull-requests: write + +env: + UV_SYSTEM_PYTHON: 1 + jobs: label-approved: - if: github.repository_owner == 'tiangolo' + if: github.repository_owner == 'fastapi' runs-on: ubuntu-latest steps: - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - - uses: docker://tiangolo/label-approved:0.0.4 + - uses: actions/checkout@v4 + - name: Set up Python + uses: actions/setup-python@v5 with: - token: ${{ secrets.FASTAPI_LABEL_APPROVED }} + python-version: "3.11" + - name: Setup uv + uses: astral-sh/setup-uv@v5 + with: + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml + - name: Install GitHub Actions dependencies + run: uv pip install -r requirements-github-actions.txt + - name: Label Approved + run: python ./scripts/label_approved.py + env: + TOKEN: ${{ secrets.GITHUB_TOKEN }} + CONFIG: > + { + "approved-1": + { + "number": 1, + "await_label": "awaiting-review" + } + } diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml new file mode 100644 index 000000000..e8e58015a --- /dev/null +++ b/.github/workflows/labeler.yml @@ -0,0 +1,33 @@ +name: Labels +on: + pull_request_target: + types: + - opened + - synchronize + - reopened + # For label-checker + - labeled + - unlabeled + +jobs: + labeler: + permissions: + contents: read + pull-requests: write + runs-on: ubuntu-latest + steps: + - uses: actions/labeler@v5 + if: ${{ github.event.action != 'labeled' && github.event.action != 'unlabeled' }} + - run: echo "Done adding labels" + # Run this after labeler applied labels + check-labels: + needs: + - labeler + permissions: + pull-requests: read + runs-on: ubuntu-latest + steps: + - uses: docker://agilepathway/pull-request-label-checker:latest + with: + one_of: breaking,security,feature,bug,refactor,upgrade,docs,lang-all,internal + repo_token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/latest-changes.yml b/.github/workflows/latest-changes.yml index 27e062d09..b8b5c42ee 100644 --- a/.github/workflows/latest-changes.yml +++ b/.github/workflows/latest-changes.yml @@ -34,8 +34,7 @@ jobs: if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }} with: limit-access-to-actor: true - - uses: docker://tiangolo/latest-changes:0.3.0 - # - uses: tiangolo/latest-changes@main + - uses: tiangolo/latest-changes@0.3.2 with: token: ${{ secrets.GITHUB_TOKEN }} latest_changes_file: docs/en/docs/release-notes.md diff --git a/.github/workflows/notify-translations.yml b/.github/workflows/notify-translations.yml index c0904ce48..c96992689 100644 --- a/.github/workflows/notify-translations.yml +++ b/.github/workflows/notify-translations.yml @@ -15,21 +15,45 @@ on: required: false default: 'false' +env: + UV_SYSTEM_PYTHON: 1 + jobs: - notify-translations: + job: runs-on: ubuntu-latest + permissions: + discussions: write steps: - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - uses: actions/checkout@v4 + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.11" + - name: Setup uv + uses: astral-sh/setup-uv@v5 + with: + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml + - name: Install Dependencies + run: uv pip install -r requirements-github-actions.txt # Allow debugging with tmate - name: Setup tmate session uses: mxschmitt/action-tmate@v3 if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }} with: limit-access-to-actor: true - - uses: ./.github/actions/notify-translations - with: - token: ${{ secrets.FASTAPI_NOTIFY_TRANSLATIONS }} + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Notify Translations + run: python ./scripts/notify_translations.py + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + NUMBER: ${{ github.event.inputs.number || null }} + DEBUG: ${{ github.event.inputs.debug_enabled || 'false' }} diff --git a/.github/workflows/people.yml b/.github/workflows/people.yml index b0868771d..6ec3c1ad2 100644 --- a/.github/workflows/people.yml +++ b/.github/workflows/people.yml @@ -6,29 +6,48 @@ on: workflow_dispatch: inputs: debug_enabled: - description: 'Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)' + description: Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate) required: false - default: 'false' + default: "false" + +env: + UV_SYSTEM_PYTHON: 1 jobs: - fastapi-people: - if: github.repository_owner == 'tiangolo' + job: + if: github.repository_owner == 'fastapi' runs-on: ubuntu-latest + permissions: + contents: write steps: - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - uses: actions/checkout@v4 - # Ref: https://github.com/actions/runner/issues/2033 - - name: Fix git safe.directory in container - run: mkdir -p /home/runner/work/_temp/_github_home && printf "[safe]\n\tdirectory = /github/workspace" > /home/runner/work/_temp/_github_home/.gitconfig + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.11" + - name: Setup uv + uses: astral-sh/setup-uv@v5 + with: + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml + - name: Install Dependencies + run: uv pip install -r requirements-github-actions.txt # Allow debugging with tmate - name: Setup tmate session uses: mxschmitt/action-tmate@v3 if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }} with: limit-access-to-actor: true - - uses: ./.github/actions/people - with: - token: ${{ secrets.FASTAPI_PEOPLE }} + env: + GITHUB_TOKEN: ${{ secrets.FASTAPI_PEOPLE }} + - name: FastAPI People Experts + run: python ./scripts/people.py + env: + GITHUB_TOKEN: ${{ secrets.FASTAPI_PEOPLE }} diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 8ebb28a80..bf88d59b1 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -8,6 +8,13 @@ on: jobs: publish: runs-on: ubuntu-latest + strategy: + matrix: + package: + - fastapi + - fastapi-slim + permissions: + id-token: write steps: - name: Dump GitHub context env: @@ -20,21 +27,15 @@ jobs: python-version: "3.10" # Issue ref: https://github.com/actions/setup-python/issues/436 # cache: "pip" - cache-dependency-path: pyproject.toml - - uses: actions/cache@v3 - id: cache - with: - path: ${{ env.pythonLocation }} - key: ${{ runner.os }}-python-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml') }}-publish + # cache-dependency-path: pyproject.toml - name: Install build dependencies - if: steps.cache.outputs.cache-hit != 'true' run: pip install build - name: Build distribution + env: + TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }} run: python -m build - name: Publish - uses: pypa/gh-action-pypi-publish@v1.8.11 - with: - password: ${{ secrets.PYPI_API_TOKEN }} + uses: pypa/gh-action-pypi-publish@v1.12.4 - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} diff --git a/.github/workflows/smokeshow.yml b/.github/workflows/smokeshow.yml index 10bff67ae..a0ffd55e6 100644 --- a/.github/workflows/smokeshow.yml +++ b/.github/workflows/smokeshow.yml @@ -8,6 +8,9 @@ on: permissions: statuses: write +env: + UV_SYSTEM_PYTHON: 1 + jobs: smokeshow: if: ${{ github.event.workflow_run.conclusion == 'success' }} @@ -18,23 +21,40 @@ jobs: env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" + - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: '3.9' - - - run: pip install smokeshow - - - uses: dawidd6/action-download-artifact@v3.0.0 + - name: Setup uv + uses: astral-sh/setup-uv@v5 with: - github_token: ${{ secrets.FASTAPI_SMOKESHOW_DOWNLOAD_ARTIFACTS }} - workflow: test.yml - commit: ${{ github.event.workflow_run.head_sha }} - - - run: smokeshow upload coverage-html + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml + - run: uv pip install -r requirements-github-actions.txt + - uses: actions/download-artifact@v4 + with: + name: coverage-html + path: htmlcov + github-token: ${{ secrets.GITHUB_TOKEN }} + run-id: ${{ github.event.workflow_run.id }} + # Try 5 times to upload coverage to smokeshow + - name: Upload coverage to Smokeshow + run: | + for i in 1 2 3 4 5; do + if smokeshow upload htmlcov; then + echo "Smokeshow upload success!" + break + fi + echo "Smokeshow upload error, sleep 1 sec and try again." + sleep 1 + done env: SMOKESHOW_GITHUB_STATUS_DESCRIPTION: Coverage {coverage-percentage} SMOKESHOW_GITHUB_COVERAGE_THRESHOLD: 100 SMOKESHOW_GITHUB_CONTEXT: coverage - SMOKESHOW_GITHUB_TOKEN: ${{ secrets.FASTAPI_SMOKESHOW_UPLOAD }} + SMOKESHOW_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} SMOKESHOW_GITHUB_PR_HEAD_SHA: ${{ github.event.workflow_run.head_sha }} SMOKESHOW_AUTH_KEY: ${{ secrets.SMOKESHOW_AUTH_KEY }} diff --git a/.github/workflows/sponsors.yml b/.github/workflows/sponsors.yml new file mode 100644 index 000000000..a5230c834 --- /dev/null +++ b/.github/workflows/sponsors.yml @@ -0,0 +1,52 @@ +name: FastAPI People Sponsors + +on: + schedule: + - cron: "0 6 1 * *" + workflow_dispatch: + inputs: + debug_enabled: + description: "Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)" + required: false + default: "false" + +env: + UV_SYSTEM_PYTHON: 1 + +jobs: + job: + if: github.repository_owner == 'fastapi' + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - name: Dump GitHub context + env: + GITHUB_CONTEXT: ${{ toJson(github) }} + run: echo "$GITHUB_CONTEXT" + - uses: actions/checkout@v4 + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.11" + - name: Setup uv + uses: astral-sh/setup-uv@v5 + with: + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml + - name: Install Dependencies + run: uv pip install -r requirements-github-actions.txt + # Allow debugging with tmate + - name: Setup tmate session + uses: mxschmitt/action-tmate@v3 + if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }} + with: + limit-access-to-actor: true + - name: FastAPI People Sponsors + run: python ./scripts/sponsors.py + env: + SPONSORS_TOKEN: ${{ secrets.SPONSORS_TOKEN }} + PR_TOKEN: ${{ secrets.FASTAPI_PR_TOKEN }} diff --git a/.github/workflows/test-redistribute.yml b/.github/workflows/test-redistribute.yml new file mode 100644 index 000000000..693f0c603 --- /dev/null +++ b/.github/workflows/test-redistribute.yml @@ -0,0 +1,69 @@ +name: Test Redistribute + +on: + push: + branches: + - master + pull_request: + types: + - opened + - synchronize + +jobs: + test-redistribute: + runs-on: ubuntu-latest + strategy: + matrix: + package: + - fastapi + - fastapi-slim + steps: + - name: Dump GitHub context + env: + GITHUB_CONTEXT: ${{ toJson(github) }} + run: echo "$GITHUB_CONTEXT" + - uses: actions/checkout@v4 + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.10" + - name: Install build dependencies + run: pip install build + - name: Build source distribution + env: + TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }} + run: python -m build --sdist + - name: Decompress source distribution + run: | + cd dist + tar xvf fastapi*.tar.gz + - name: Install test dependencies + run: | + cd dist/fastapi*/ + pip install -r requirements-tests.txt + env: + TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }} + - name: Run source distribution tests + run: | + cd dist/fastapi*/ + bash scripts/test.sh + - name: Build wheel distribution + run: | + cd dist + pip wheel --no-deps fastapi*.tar.gz + - name: Dump GitHub context + env: + GITHUB_CONTEXT: ${{ toJson(github) }} + run: echo "$GITHUB_CONTEXT" + + # https://github.com/marketplace/actions/alls-green#why + test-redistribute-alls-green: # This job does nothing and is only used for the branch protection + if: always() + needs: + - test-redistribute + runs-on: ubuntu-latest + steps: + - name: Decide whether the needed jobs succeeded or failed + uses: re-actors/alls-green@release/v1 + with: + jobs: ${{ toJSON(needs) }} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index b6b173685..5e8092641 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -8,6 +8,12 @@ on: types: - opened - synchronize + schedule: + # cron every week on monday + - cron: "0 0 * * 1" + +env: + UV_SYSTEM_PYTHON: 1 jobs: lint: @@ -22,19 +28,18 @@ jobs: uses: actions/setup-python@v5 with: python-version: "3.11" - # Issue ref: https://github.com/actions/setup-python/issues/436 - # cache: "pip" - # cache-dependency-path: pyproject.toml - - uses: actions/cache@v3 - id: cache + - name: Setup uv + uses: astral-sh/setup-uv@v5 with: - path: ${{ env.pythonLocation }} - key: ${{ runner.os }}-python-${{ env.pythonLocation }}-pydantic-v2-${{ hashFiles('pyproject.toml', 'requirements-tests.txt', 'requirements-docs-tests.txt') }}-test-v07 + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml - name: Install Dependencies - if: steps.cache.outputs.cache-hit != 'true' - run: pip install -r requirements-tests.txt + run: uv pip install -r requirements-tests.txt - name: Install Pydantic v2 - run: pip install "pydantic>=2.0.2,<3.0.0" + run: uv pip install --upgrade "pydantic>=2.0.2,<3.0.0" - name: Lint run: bash scripts/lint.sh @@ -43,6 +48,7 @@ jobs: strategy: matrix: python-version: + - "3.13" - "3.12" - "3.11" - "3.10" @@ -60,23 +66,26 @@ jobs: uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} - # Issue ref: https://github.com/actions/setup-python/issues/436 - # cache: "pip" - # cache-dependency-path: pyproject.toml - - uses: actions/cache@v3 - id: cache + - name: Setup uv + uses: astral-sh/setup-uv@v5 with: - path: ${{ env.pythonLocation }} - key: ${{ runner.os }}-python-${{ env.pythonLocation }}-${{ matrix.pydantic-version }}-${{ hashFiles('pyproject.toml', 'requirements-tests.txt', 'requirements-docs-tests.txt') }}-test-v07 + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml - name: Install Dependencies - if: steps.cache.outputs.cache-hit != 'true' - run: pip install -r requirements-tests.txt + run: uv pip install -r requirements-tests.txt - name: Install Pydantic v1 if: matrix.pydantic-version == 'pydantic-v1' - run: pip install "pydantic>=1.10.0,<2.0.0" + run: uv pip install "pydantic>=1.10.0,<2.0.0" - name: Install Pydantic v2 if: matrix.pydantic-version == 'pydantic-v2' - run: pip install "pydantic>=2.0.2,<3.0.0" + run: uv pip install --upgrade "pydantic>=2.0.2,<3.0.0" + # TODO: Remove this once Python 3.8 is no longer supported + - name: Install older AnyIO in Python 3.8 + if: matrix.python-version == '3.8' + run: uv pip install "anyio[trio]<4.0.0" - run: mkdir coverage - name: Test run: bash scripts/test.sh @@ -84,10 +93,11 @@ jobs: COVERAGE_FILE: coverage/.coverage.${{ runner.os }}-py${{ matrix.python-version }} CONTEXT: ${{ runner.os }}-py${{ matrix.python-version }} - name: Store coverage files - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: - name: coverage + name: coverage-${{ matrix.python-version }}-${{ matrix.pydantic-version }} path: coverage + include-hidden-files: true coverage-combine: needs: [test] @@ -101,24 +111,32 @@ jobs: - uses: actions/setup-python@v5 with: python-version: '3.8' - # Issue ref: https://github.com/actions/setup-python/issues/436 - # cache: "pip" - # cache-dependency-path: pyproject.toml + - name: Setup uv + uses: astral-sh/setup-uv@v5 + with: + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml + - name: Install Dependencies + run: uv pip install -r requirements-tests.txt - name: Get coverage files - uses: actions/download-artifact@v3 + uses: actions/download-artifact@v4 with: - name: coverage + pattern: coverage-* path: coverage - - run: pip install coverage[toml] + merge-multiple: true - run: ls -la coverage - run: coverage combine coverage - run: coverage report - - run: coverage html --show-contexts --title "Coverage for ${{ github.sha }}" + - run: coverage html --title "Coverage for ${{ github.sha }}" - name: Store coverage HTML - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: coverage-html path: htmlcov + include-hidden-files: true # https://github.com/marketplace/actions/alls-green#why check: # This job does nothing and is only used for the branch protection diff --git a/.github/workflows/topic-repos.yml b/.github/workflows/topic-repos.yml new file mode 100644 index 000000000..3c5c881f1 --- /dev/null +++ b/.github/workflows/topic-repos.yml @@ -0,0 +1,40 @@ +name: Update Topic Repos + +on: + schedule: + - cron: "0 12 1 * *" + workflow_dispatch: + +env: + UV_SYSTEM_PYTHON: 1 + +jobs: + topic-repos: + if: github.repository_owner == 'fastapi' + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - name: Dump GitHub context + env: + GITHUB_CONTEXT: ${{ toJson(github) }} + run: echo "$GITHUB_CONTEXT" + - uses: actions/checkout@v4 + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.11" + - name: Setup uv + uses: astral-sh/setup-uv@v5 + with: + version: "0.4.15" + enable-cache: true + cache-dependency-glob: | + requirements**.txt + pyproject.toml + - name: Install GitHub Actions dependencies + run: uv pip install -r requirements-github-actions.txt + - name: Update Topic Repos + run: python ./scripts/topic_repos.py + env: + GITHUB_TOKEN: ${{ secrets.FASTAPI_PR_TOKEN }} diff --git a/.gitignore b/.gitignore index 9be494cec..ef6364a9a 100644 --- a/.gitignore +++ b/.gitignore @@ -7,7 +7,7 @@ __pycache__ htmlcov dist site -.coverage +.coverage* coverage.xml .netlify test.db diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index a7f2fb3f2..767ef8d9e 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -4,7 +4,7 @@ default_language_version: python: python3.10 repos: - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.4.0 + rev: v5.0.0 hooks: - id: check-added-large-files - id: check-toml @@ -13,8 +13,8 @@ repos: - --unsafe - id: end-of-file-fixer - id: trailing-whitespace -- repo: https://github.com/charliermarsh/ruff-pre-commit - rev: v0.1.2 +- repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.7.4 hooks: - id: ruff args: diff --git a/CITATION.cff b/CITATION.cff index 9028248b1..f14700349 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -12,7 +12,7 @@ authors: family-names: Ramírez email: tiangolo@gmail.com identifiers: -repository-code: 'https://github.com/tiangolo/fastapi' +repository-code: 'https://github.com/fastapi/fastapi' url: 'https://fastapi.tiangolo.com' abstract: >- FastAPI framework, high performance, easy to learn, fast to code, diff --git a/README.md b/README.md index 2df5cba0b..9a1260b90 100644 --- a/README.md +++ b/README.md @@ -5,11 +5,11 @@ FastAPI framework, high performance, easy to learn, fast to code, ready for production

- - Test + + Test - - Coverage + + Coverage Package version @@ -23,11 +23,11 @@ **Documentation**: https://fastapi.tiangolo.com -**Source Code**: https://github.com/tiangolo/fastapi +**Source Code**: https://github.com/fastapi/fastapi --- -FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.8+ based on standard Python type hints. +FastAPI is a modern, fast (high-performance), web framework for building APIs with Python based on standard Python type hints. The key features are: @@ -46,22 +46,24 @@ The key features are: - + - - - - + + + + + + - - + - + + @@ -71,7 +73,7 @@ The key features are: "_[...] 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._" -

Kabir Khan - Microsoft (ref)
+
Kabir Khan - Microsoft (ref)
--- @@ -95,7 +97,7 @@ The key features are: "_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- @@ -123,37 +125,27 @@ If you are building a CLI app to be ## Requirements -Python 3.8+ - FastAPI stands on the shoulders of giants: * Starlette for the web parts. -* Pydantic for the data parts. +* Pydantic for the data parts. ## Installation -
- -```console -$ pip install fastapi - ----> 100% -``` - -
- -You will also need an ASGI server, for production such as Uvicorn or Hypercorn. +Create and activate a virtual environment and then install FastAPI:
```console -$ pip install "uvicorn[standard]" +$ pip install "fastapi[standard]" ---> 100% ```
+**Note**: Make sure you put `"fastapi[standard]"` in quotes to ensure it works in all terminals. + ## Example ### Create it @@ -214,11 +206,24 @@ Run the server with:
```console -$ uvicorn main:app --reload - +$ fastapi dev main.py + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + │ fastapi run │ + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -INFO: Started reloader process [28720] -INFO: Started server process [28722] +INFO: Started reloader process [2248755] using WatchFiles +INFO: Started server process [2248757] INFO: Waiting for application startup. INFO: Application startup complete. ``` @@ -226,13 +231,13 @@ INFO: Application startup complete.
-About the command uvicorn main:app --reload... +About the command fastapi dev main.py... -The command `uvicorn main:app` refers to: +The command `fastapi dev` reads your `main.py` file, detects the **FastAPI** app in it, and starts a server using Uvicorn. -* `main`: the file `main.py` (the Python "module"). -* `app`: the object created inside of `main.py` with the line `app = FastAPI()`. -* `--reload`: make the server restart after code changes. Only do this for development. +By default, `fastapi dev` will start with auto-reload enabled for local development. + +You can read more about it in the FastAPI CLI docs.
@@ -305,7 +310,7 @@ def update_item(item_id: int, item: Item): return {"item_name": item.name, "item_id": item_id} ``` -The server should reload automatically (because you added `--reload` to the `uvicorn` command above). +The `fastapi dev` server should reload automatically. ### Interactive API docs upgrade @@ -339,7 +344,7 @@ You do that with standard modern Python types. You don't have to learn a new syntax, the methods or classes of a specific library, etc. -Just standard **Python 3.8+**. +Just standard **Python**. For example, for an `int`: @@ -389,7 +394,7 @@ Coming back to the previous code example, **FastAPI** will: * Check if there is an optional query parameter named `q` (as in `http://127.0.0.1:8000/items/foo?q=somequery`) for `GET` requests. * As the `q` parameter is declared with `= None`, it is optional. * Without the `None` it would be required (as is the body in the case with `PUT`). -* For `PUT` requests to `/items/{item_id}`, Read the body as JSON: +* For `PUT` requests to `/items/{item_id}`, read the body as JSON: * Check that it has a required attribute `name` that should be a `str`. * Check that it has a required attribute `price` that has to be a `float`. * Check that it has an optional attribute `is_offer`, that should be a `bool`, if present. @@ -449,29 +454,46 @@ Independent TechEmpower benchmarks show **FastAPI** applications running under U To understand more about it, see the section Benchmarks. -## Optional Dependencies +## Dependencies + +FastAPI depends on Pydantic and Starlette. + +### `standard` Dependencies + +When you install FastAPI with `pip install "fastapi[standard]"` it comes with the `standard` group of optional dependencies: Used by Pydantic: -* email_validator - for email validation. -* pydantic-settings - for settings management. -* pydantic-extra-types - for extra types to be used with Pydantic. +* email-validator - for email validation. Used by Starlette: * httpx - 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`. +* python-multipart - Required if you want to support form "parsing", with `request.form()`. Used by FastAPI / Starlette: -* uvicorn - for the server that loads and serves your application. -* orjson - Required if you want to use `ORJSONResponse`. +* uvicorn - for the server that loads and serves your application. This includes `uvicorn[standard]`, which includes some dependencies (e.g. `uvloop`) needed for high performance serving. +* `fastapi-cli` - to provide the `fastapi` command. + +### Without `standard` Dependencies + +If you don't want to include the `standard` optional dependencies, you can install with `pip install fastapi` instead of `pip install "fastapi[standard]"`. + +### Additional Optional Dependencies + +There are some additional dependencies you might want to install. -You can install all of these with `pip install "fastapi[all]"`. +Additional optional Pydantic dependencies: + +* pydantic-settings - for settings management. +* pydantic-extra-types - for extra types to be used with Pydantic. + +Additional optional FastAPI dependencies: + +* orjson - Required if you want to use `ORJSONResponse`. +* ujson - Required if you want to use `UJSONResponse`. ## License diff --git a/docs/az/docs/index.md b/docs/az/docs/index.md new file mode 100644 index 000000000..fbbbce130 --- /dev/null +++ b/docs/az/docs/index.md @@ -0,0 +1,467 @@ +

+ FastAPI +

+

+ FastAPI framework, yüksək məshuldarlı, öyrənməsi asan, çevik kodlama, istifadəyə hazırdır +

+

+ + Test + + + Əhatə + + + Paket versiyası + + + Dəstəklənən Python versiyaları + +

+ +--- + +**Sənədlər**: https://fastapi.tiangolo.com + +**Qaynaq Kodu**: https://github.com/fastapi/fastapi + +--- + +FastAPI Python ilə API yaratmaq üçün standart Python tip məsləhətlərinə əsaslanan, müasir, sürətli (yüksək performanslı) framework-dür. + +Əsas xüsusiyyətləri bunlardır: + +* **Sürətli**: Çox yüksək performans, **NodeJS** və **Go** səviyyəsində (Starlette və Pydantic-ə təşəkkürlər). [Ən sürətli Python frameworklərindən biridir](#performans). +* **Çevik kodlama**: Funksiyanallıqları inkişaf etdirmək sürətini təxminən 200%-dən 300%-ə qədər artırın. * +* **Daha az xəta**: İnsan (developer) tərəfindən törədilən səhvlərin təxminən 40% -ni azaldın. * +* **İntuitiv**: Əla redaktor dəstəyi. Hər yerdə otomatik tamamlama. Xətaları müəyyənləşdirməyə daha az vaxt sərf edəcəksiniz. +* **Asan**: İstifadəsi və öyrənilməsi asan olması üçün nəzərdə tutulmuşdur. Sənədləri oxumaq üçün daha az vaxt ayıracaqsınız. +* **Qısa**: Kod təkrarlanmasını minimuma endirin. Hər bir parametr tərifində birdən çox xüsusiyyət ilə və daha az səhvlə qarşılaşacaqsınız. +* **Güclü**: Avtomatik və interaktiv sənədlərlə birlikdə istifadəyə hazır kod əldə edə bilərsiniz. +* **Standartlara əsaslanan**: API-lar üçün açıq standartlara əsaslanır (və tam uyğun gəlir): OpenAPI (əvvəlki adı ilə Swagger) və JSON Schema. + +* Bu fikirlər daxili development komandasının hazırladıqları məhsulların sınaqlarına əsaslanır. + +## Sponsorlar + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} + +{% endfor -%}` +{%- for sponsor in sponsors.silver -%} + +{% endfor %} +{% endif %} + + + +Digər sponsorlar + +## Rəylər + +"_[...] Son günlərdə **FastAPI**-ı çox istifadə edirəm. [...] Əslində onu komandamın bütün **Microsoftda ML sevislərində** istifadə etməyi planlayıram. Onların bəziləri **windows**-un əsas məhsuluna və bəzi **Office** məhsullarına inteqrasiya olunurlar._" + +
Kabir Khan - Microsoft (ref)
+ +--- + +"_**FastAPI** kitabxanasını **Proqnozlar** əldə etmək üçün sorğulana bilən **REST** serverini yaratmaqda istifadə etdik._" + +
Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber (ref)
+ +--- + +"_**Netflix** **böhran idarəçiliyi** orkestrləşmə framework-nün açıq qaynaqlı buraxılışını elan etməkdən məmnundur: **Dispatch**! [**FastAPI** ilə quruldu]_" + +
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (ref)
+ +--- + +"_**FastAPI** üçün həyəcanlıyam. Çox əyləncəlidir!_" + +
Brian Okken - Python Bytes podcast host (ref)
+ +--- + +"_Düzünü desəm, sizin qurduğunuz şey həqiqətən möhkəm və peşəkar görünür. Bir çox cəhətdən **Hug**-un olmasını istədiyim kimdir - kiminsə belə bir şey qurduğunu görmək həqiqətən ruhlandırıcıdır._" + +
Timothy Crosley - Hug creator (ref)
+ +--- + +"_Əgər REST API-lər yaratmaq üçün **müasir framework** öyrənmək istəyirsinizsə, **FastAPI**-a baxın [...] Sürətli, istifadəsi və öyrənməsi asandır. [...]_" + +"_**API** xidmətlərimizi **FastAPI**-a köçürdük [...] Sizin də bəyənəcəyinizi düşünürük._" + +
Ines Montani - Matthew Honnibal - Explosion AI founders - spaCy creators (ref) - (ref)
+ +--- + +"_Python ilə istifadəyə hazır API qurmaq istəyən hər kəsə **FastAPI**-ı tövsiyə edirəm. **Möhtəşəm şəkildə dizayn edilmiş**, **istifadəsi asan** və **yüksək dərəcədə genişlənə bilən**-dir, API əsaslı inkişaf strategiyamızın **əsas komponentinə** çevrilib və Virtual TAC Engineer kimi bir çox avtomatlaşdırma və servisləri idarə edir._" + +
Deon Pillsbury - Cisco (ref)
+ +--- + +## **Typer**, CLI-ların FastAPI-ı + + + +Əgər siz veb API əvəzinə terminalda istifadə ediləcək CLI proqramı qurursunuzsa, **Typer**-a baxa bilərsiniz. + +**Typer** FastAPI-ın kiçik qardaşıdır. Və o, CLI-lərin **FastAPI**-ı olmaq üçün nəzərdə tutulub. ⌨️ 🚀 + +## Tələblər + +FastAPI nəhənglərin çiyinlərində dayanır: + +* Web tərəfi üçün Starlette. +* Data tərəfi üçün Pydantic. + +## Quraşdırma + +
+ +```console +$ pip install fastapi + +---> 100% +``` + +
+ +Tətbiqimizi əlçatan etmək üçün bizə Uvicorn və ya Hypercorn kimi ASGI server lazımdır. + +
+ +```console +$ pip install "uvicorn[standard]" + +---> 100% +``` + +
+ +## Nümunə + +### Kodu yaradaq + +* `main.py` adlı fayl yaradaq və ona aşağıdakı kodu yerləşdirək: + +```Python +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@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} +``` + +
+Və ya async def... + +Əgər kodunuzda `async` və ya `await` vardırsa `async def` istifadə edə bilərik: + +```Python hl_lines="9 14" +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +async def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +async def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +**Qeyd**: + +Əgər bu mövzu haqqında məlumatınız yoxdursa `async` və `await` sənədindəki _"Tələsirsən?"_ bölməsinə baxa bilərsiniz. + +
+ +### Kodu işə salaq + +Serveri aşağıdakı əmr ilə işə salaq: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [28720] +INFO: Started server process [28722] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +
+uvicorn main:app --reload əmri haqqında... + +`uvicorn main:app` əmri aşağıdakılara instinad edir: + +* `main`: `main.py` faylı (yəni Python "modulu"). +* `app`: `main.py` faylında `app = FastAPI()` sətrində yaratdığımız `FastAPI` obyektidir. +* `--reload`: kod dəyişikliyindən sonra avtomatik olaraq serveri yenidən işə salır. Bu parametrdən yalnız development mərhələsində istifadə etməliyik. + +
+ +### İndi yoxlayaq + +Bu linki brauzerimizdə açaq http://127.0.0.1:8000/items/5?q=somequery. + +Aşağıdakı kimi bir JSON cavabı görəcəksiniz: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +Siz artıq bir API yaratmısınız, hansı ki: + +* `/` və `/items/{item_id}` _yollarında_ HTTP sorğularını qəbul edir. +* Hər iki _yolda_ `GET` əməliyyatlarını (həmçinin HTTP _metodları_ kimi bilinir) aparır. +* `/items/{item_id}` _yolu_ `item_id` adlı `int` qiyməti almalı olan _yol parametrinə_ sahibdir. +* `/items/{item_id}` _yolunun_ `q` adlı yol parametri var və bu parametr istəyə bağlı olsa da, `str` qiymətini almalıdır. + +### İnteraktiv API Sənədləri + +İndi http://127.0.0.1:8000/docs ünvanına daxil olun. + +Avtomatik interaktiv API sənədlərini görəcəksiniz (Swagger UI tərəfindən təmin edilir): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### Alternativ API sənədləri + +İndi isə http://127.0.0.1:8000/redoc ünvanına daxil olun. + +ReDoc tərəfindən təqdim edilən avtomatik sənədləri görəcəksiniz: + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## Nümunəni Yeniləyək + +İndi gəlin `main.py` faylını `PUT` sorğusu ilə birlikdə gövdə qəbul edəcək şəkildə dəyişdirək. + +Pydantic sayəsində standart Python tiplərindən istifadə edərək gövdəni müəyyən edək. + +```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} +``` +Server avtomatik olaraq yenidən işə salınmalı idi (çünki biz yuxarıda `uvicorn` əmri ilə `--reload` parametrindən istifadə etmişik). + +### İnteraktiv API sənədlərindəki dəyişikliyə baxaq + +Yenidən http://127.0.0.1:8000/docs ünvanına daxil olun. + +* İnteraktiv API sənədləri yeni gövdə də daxil olmaq ilə avtomatik olaraq yenilənəcək: + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* "Try it out" düyməsini klikləyin, bu, parametrləri doldurmağa və API ilə birbaşa əlaqə saxlamağa imkan verir: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) + +* Sonra "Execute" düyməsini klikləyin, istifadəçi interfeysi API ilə əlaqə quracaq, parametrləri göndərəcək, nəticələri əldə edəcək və onları ekranda göstərəcək: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) + +### Alternativ API Sənədlərindəki Dəyişikliyə Baxaq + +İndi isə yenidən http://127.0.0.1:8000/redoc ünvanına daxil olun. + +* Alternativ sənədlər həm də yeni sorğu parametri və gövdəsini əks etdirəcək: + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### Xülasə + +Ümumiləşdirsək, parametrlər, gövdə və s. Biz məlumat növlərini **bir dəfə** funksiya parametrləri kimi təyin edirik. + +Bunu standart müasir Python tipləri ilə edirsiniz. + +Yeni sintaksis, müəyyən bir kitabxananın metodlarını və ya siniflərini və s. öyrənmək məcburiyyətində deyilsiniz. + +Sadəcə standart **Python**. + +Məsələn, `int` üçün: + +```Python +item_id: int +``` + +və ya daha mürəkkəb `Item` modeli üçün: + +```Python +item: Item +``` + +...və yalnız parametr tipini təyin etməklə bunları əldə edirsiniz: + +* Redaktor dəstəyi ilə: + * Avtomatik tamamlama. + * Tip yoxlanması. +* Məlumatların Təsdiqlənməsi: + * Məlumat etibarsız olduqda avtomatik olaraq aydın xətalar göstərir. + * Hətta çox dərin JSON obyektlərində belə doğrulama aparır. +* Daxil olan məlumatları çevirmək üçün aşağıdakı məlumat növlərindən istifadə edilir: + * JSON. + * Yol parametrləri. + * Sorğu parametrləri. + * Çərəzlər. + * Başlıqlaq. + * Formalar. + * Fayllar. +* Daxil olan məlumatları çevirmək üçün aşağıdakı məlumat növlərindən istifadə edilir (JSON olaraq): + * Python tiplərinin (`str`, `int`, `float`, `bool`, `list`, və s) çevrilməsi. + * `datetime` obyektləri. + * `UUID` obyektləri. + * Verilənlər bazası modelləri. + * və daha çoxu... +* 2 alternativ istifadəçi interfeysi daxil olmaqla avtomatik interaktiv API sənədlərini təmin edir: + * Swagger UI. + * ReDoc. + +--- + +Gəlin əvvəlki nümunəyə qayıdaq və **FastAPI**-nin nələr edəcəyinə nəzər salaq: + +* `GET` və `PUT` sorğuları üçün `item_id`-nin yolda olub-olmadığını yoxlayacaq. +* `item_id`-nin `GET` və `PUT` sorğuları üçün növünün `int` olduğunu yoxlayacaq. + * Əgər `int` deyilsə, səbəbini göstərən bir xəta mesajı göstərəcəkdir. +* məcburi olmayan `q` parametrinin `GET` (`http://127.0.0.1:8000/items/foo?q=somequery` burdakı kimi) sorğusu içərisində olub olmadığını yoxlayacaq. + * `q` parametrini `= None` ilə yaratdığımız üçün, məcburi olmayan parametr olacaq. + * Əgər `None` olmasaydı, bu məcburi parametr olardı (`PUT` metodunun gövdəsində olduğu kimi). +* `PUT` sorğusu üçün, `/items/{item_id}` gövdəsini JSON olaraq oxuyacaq: + * `name` adında məcburi bir parametr olub olmadığını və əgər varsa, tipinin `str` olub olmadığını yoxlayacaq. + * `price` adında məcburi bir parametr olub olmadığını və əgər varsa, tipinin `float` olub olmadığını yoxlayacaq. + * `is_offer` adında məcburi olmayan bir parametr olub olmadığını və əgər varsa, tipinin `float` olub olmadığını yoxlayacaq. + * Bütün bunlar ən dərin JSON obyektlərində belə işləyəcək. +* Məlumatların JSON-a və JSON-un Python obyektinə çevrilməsi avtomatik həyata keçiriləcək. +* Hər şeyi OpenAPI ilə uyğun olacaq şəkildə avtomatik olaraq sənədləşdirəcək və onları aşağıdakı kimi istifadə edə biləcək: + * İnteraktiv sənədləşmə sistemləri. + * Bir çox proqramlaşdırma dilləri üçün avtomatlaşdırılmış müştəri kodu yaratma sistemləri. +* 2 interaktiv sənədləşmə veb interfeysini birbaşa təmin edəcək. + +--- + +Yeni başlamışıq, amma siz artıq işin məntiqini başa düşmüsünüz. + +İndi aşağıdakı sətri dəyişdirməyə çalışın: + +```Python + return {"item_name": item.name, "item_id": item_id} +``` + +...bundan: + +```Python + ... "item_name": item.name ... +``` + +...buna: + +```Python + ... "item_price": item.price ... +``` + +...və redaktorun məlumat tiplərini bildiyini və avtomatik tamaladığını görəcəksiniz: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +Daha çox funksiyaya malik daha dolğun nümunə üçün Öyrədici - İstifadəçi Təlimatı səhifəsinə baxa bilərsiniz. + +**Spoiler xəbərdarlığı**: Öyrədici - istifadəçi təlimatına bunlar daxildir: + +* **Parametrlərin**, **başlıqlar**, çərəzlər, **forma sahələri** və **fayllar** olaraq müəyyən edilməsi. +* `maximum_length` və ya `regex` kimi **doğrulama məhdudiyyətlərinin** necə təyin ediləcəyi. +* Çox güclü və istifadəsi asan **Dependency Injection** sistemi. +* Təhlükəsizlik və autentifikasiya, **JWT tokenləri** ilə **OAuth2** dəstəyi və **HTTP Basic** autentifikasiyası. +* **çox dərin JSON modellərini** müəyyən etmək üçün daha irəli səviyyə (lakin eyni dərəcədə asan) üsullar (Pydantic sayəsində). +* Strawberry və digər kitabxanalar ilə **GraphQL** inteqrasiyası. +* Digər əlavə xüsusiyyətlər (Starlette sayəsində): + * **WebSockets** + * HTTPX və `pytest` sayəsində çox asan testlər + * **CORS** + * **Cookie Sessions** + * ...və daha çoxu. + +## Performans + +Müstəqil TechEmpower meyarları göstərir ki, Uvicorn üzərində işləyən **FastAPI** proqramları ən sürətli Python kitabxanalarından biridir, yalnız Starlette və Uvicorn-un özündən yavaşdır, ki FastAPI bunların üzərinə qurulmuş bir framework-dür. (*) + +Ətraflı məlumat üçün bu bölməyə nəzər salın Müqayisələr. + +## Məcburi Olmayan Tələblər + +Pydantic tərəfindən istifadə olunanlar: + +* email-validator - e-poçtun yoxlanılması üçün. +* pydantic-settings - parametrlərin idarə edilməsi üçün. +* pydantic-extra-types - Pydantic ilə istifadə edilə bilən əlavə tiplər üçün. + +Starlette tərəfindən istifadə olunanlar: + +* httpx - Əgər `TestClient` strukturundan istifadə edəcəksinizsə, tələb olunur. +* jinja2 - Standart şablon konfiqurasiyasından istifadə etmək istəyirsinizsə, tələb olunur. +* python-multipart - `request.form()` ilə forma "çevirmə" dəstəyindən istifadə etmək istəyirsinizsə, tələb olunur. +* itsdangerous - `SessionMiddleware` dəstəyi üçün tələb olunur. +* pyyaml - `SchemaGenerator` dəstəyi üçün tələb olunur (Çox güman ki, FastAPI istifadə edərkən buna ehtiyacınız olmayacaq). +* ujson - `UJSONResponse` istifadə etmək istəyirsinizsə, tələb olunur. + +Həm FastAPI, həm də Starlette tərəfindən istifadə olunur: + +* uvicorn - Yaratdığımız proqramı servis edəcək veb server kimi fəaliyyət göstərir. +* orjson - `ORJSONResponse` istifadə edəcəksinizsə tələb olunur. + +Bütün bunları `pip install fastapi[all]` ilə quraşdıra bilərsiniz. + +## Lisenziya + +Bu layihə MIT lisenziyasının şərtlərinə əsasən lisenziyalaşdırılıb. diff --git a/docs/az/docs/learn/index.md b/docs/az/docs/learn/index.md new file mode 100644 index 000000000..cc32108bf --- /dev/null +++ b/docs/az/docs/learn/index.md @@ -0,0 +1,5 @@ +# Öyrən + +Burada **FastAPI** öyrənmək üçün giriş bölmələri və dərsliklər yer alır. + +Siz bunu kitab, kurs, FastAPI öyrənmək üçün rəsmi və tövsiyə olunan üsul hesab edə bilərsiniz. 😎 diff --git a/docs/az/mkdocs.yml b/docs/az/mkdocs.yml new file mode 100644 index 000000000..de18856f4 --- /dev/null +++ b/docs/az/mkdocs.yml @@ -0,0 +1 @@ +INHERIT: ../en/mkdocs.yml diff --git a/docs/bn/docs/index.md b/docs/bn/docs/index.md index 4f778e873..74ee230a1 100644 --- a/docs/bn/docs/index.md +++ b/docs/bn/docs/index.md @@ -5,22 +5,25 @@ FastAPI উচ্চক্ষমতা সম্পন্ন, সহজে শেখার এবং দ্রুত কোড করে প্রোডাকশনের জন্য ফ্রামওয়ার্ক।

- - Test + + Test - - Coverage + + Coverage Package version + + Supported Python versions +

--- **নির্দেশিকা নথি**: https://fastapi.tiangolo.com -**সোর্স কোড**: https://github.com/tiangolo/fastapi +**সোর্স কোড**: https://github.com/fastapi/fastapi --- @@ -61,7 +64,7 @@ FastAPI একটি আধুনিক, দ্রুত ( বেশি ক্ "_আমি আজকাল **FastAPI** ব্যবহার করছি। [...] আমরা ভাবছি মাইক্রোসফ্টে **ML সার্ভিস** এ সকল দলের জন্য এটি ব্যবহার করব। যার মধ্যে কিছু পণ্য **Windows** এ সংযোযন হয় এবং কিছু **Office** এর সাথে সংযোযন হচ্ছে।_" -
কবির খান - মাইক্রোসফ্টে (ref)
+
কবির খান - মাইক্রোসফ্টে (ref)
--- @@ -85,7 +88,7 @@ FastAPI একটি আধুনিক, দ্রুত ( বেশি ক্ "\_সত্যিই, আপনি যা তৈরি করেছেন তা খুব মজবুত এবং পরিপূর্ন৷ অনেক উপায়ে, আমি যা **Hug** এ করতে চেয়েছিলাম - তা কাউকে তৈরি করতে দেখে আমি সত্যিই অনুপ্রানিত৷\_" -
টিমোথি ক্রসলে - Hug স্রষ্টা (ref)
+
টিমোথি ক্রসলে - Hug স্রষ্টা (ref)
--- @@ -112,7 +115,7 @@ Python 3.7+ FastAPI কিছু দানবেদের কাঁধে দাঁড়িয়ে আছে: - Starlette ওয়েব অংশের জন্য. -- Pydantic ডেটা অংশগুলির জন্য. +- Pydantic ডেটা অংশগুলির জন্য. ## ইনস্টলেশন প্রক্রিয়া @@ -126,7 +129,7 @@ $ pip install fastapi -আপনার একটি ASGI সার্ভারেরও প্রয়োজন হবে, প্রোডাকশনের জন্য Uvicorn অথবা Hypercorn. +আপনার একটি ASGI সার্ভারেরও প্রয়োজন হবে, প্রোডাকশনের জন্য Uvicorn অথবা Hypercorn.
@@ -439,23 +442,22 @@ item: Item Pydantic দ্বারা ব্যবহৃত: -- ujson - দ্রুত JSON এর জন্য "parsing". -- email_validator - ইমেল যাচাইকরণের জন্য। +- email-validator - ইমেল যাচাইকরণের জন্য। স্টারলেট দ্বারা ব্যবহৃত: - httpx - আপনি যদি `TestClient` ব্যবহার করতে চান তাহলে আবশ্যক। - jinja2 - আপনি যদি প্রদত্ত টেমপ্লেট রূপরেখা ব্যবহার করতে চান তাহলে প্রয়োজন। -- python-multipart - আপনি যদি ফর্ম সহায়তা করতে চান তাহলে প্রয়োজন "parsing", `request.form()` সহ। +- python-multipart - আপনি যদি ফর্ম সহায়তা করতে চান তাহলে প্রয়োজন "parsing", `request.form()` সহ। - itsdangerous - `SessionMiddleware` সহায়তার জন্য প্রয়োজন। - pyyaml - স্টারলেটের SchemaGenerator সাপোর্ট এর জন্য প্রয়োজন (আপনার সম্ভাবত FastAPI প্রয়োজন নেই)। - graphene - `GraphQLApp` সহায়তার জন্য প্রয়োজন। -- ujson - আপনি `UJSONResponse` ব্যবহার করতে চাইলে প্রয়োজন। FastAPI / Starlette দ্বারা ব্যবহৃত: - uvicorn - সার্ভারের জন্য যা আপনার অ্যাপ্লিকেশন লোড করে এবং পরিবেশন করে। - orjson - আপনি `ORJSONResponse` ব্যবহার করতে চাইলে প্রয়োজন। +- ujson - আপনি `UJSONResponse` ব্যবহার করতে চাইলে প্রয়োজন। আপনি এই সব ইনস্টল করতে পারেন `pip install fastapi[all]` দিয়ে. diff --git a/docs/bn/docs/learn/index.md b/docs/bn/docs/learn/index.md new file mode 100644 index 000000000..4e4c62038 --- /dev/null +++ b/docs/bn/docs/learn/index.md @@ -0,0 +1,5 @@ +# শিখুন + +এখানে **FastAPI** শিখার জন্য প্রাথমিক বিভাগগুলি এবং টিউটোরিয়ালগুলি রয়েছে। + +আপনি এটিকে একটি **বই**, একটি **কোর্স**, এবং FastAPI শিখার **অফিসিয়াল** এবং প্রস্তাবিত উপায় বিবেচনা করতে পারেন। 😎 diff --git a/docs/bn/docs/python-types.md b/docs/bn/docs/python-types.md new file mode 100644 index 000000000..d98c2ec87 --- /dev/null +++ b/docs/bn/docs/python-types.md @@ -0,0 +1,586 @@ +# পাইথন এর টাইপ্স পরিচিতি + +Python-এ ঐচ্ছিক "টাইপ হিন্ট" (যা "টাইপ অ্যানোটেশন" নামেও পরিচিত) এর জন্য সাপোর্ট রয়েছে। + +এই **"টাইপ হিন্ট"** বা অ্যানোটেশনগুলি এক ধরণের বিশেষ সিনট্যাক্স যা একটি ভেরিয়েবলের টাইপ ঘোষণা করতে দেয়। + +ভেরিয়েবলগুলির জন্য টাইপ ঘোষণা করলে, এডিটর এবং টুলগুলি আপনাকে আরও ভালো সাপোর্ট দিতে পারে। + +এটি পাইথন টাইপ হিন্ট সম্পর্কে একটি দ্রুত **টিউটোরিয়াল / রিফ্রেশার** মাত্র। এটি **FastAPI** এর সাথে ব্যবহার করার জন্য শুধুমাত্র ন্যূনতম প্রয়োজনীয়তা কভার করে... যা আসলে খুব একটা বেশি না। + +**FastAPI** এই টাইপ হিন্টগুলির উপর ভিত্তি করে নির্মিত, যা এটিকে অনেক সুবিধা এবং লাভ প্রদান করে। + +তবে, আপনি যদি কখনো **FastAPI** ব্যবহার নাও করেন, তবুও এগুলি সম্পর্কে একটু শেখা আপনার উপকারে আসবে। + +/// note + +যদি আপনি একজন Python বিশেষজ্ঞ হন, এবং টাইপ হিন্ট সম্পর্কে সবকিছু জানেন, তাহলে পরবর্তী অধ্যায়ে চলে যান। + +/// + +## প্রেরণা + +চলুন একটি সাধারণ উদাহরণ দিয়ে শুরু করি: + +{* ../../docs_src/python_types/tutorial001.py *} + + +এই প্রোগ্রামটি কল করলে আউটপুট হয়: + +``` +John Doe +``` + +ফাংশনটি নিম্নলিখিত কাজ করে: + +* `first_name` এবং `last_name` নেয়। +* প্রতিটির প্রথম অক্ষরকে `title()` ব্যবহার করে বড় হাতের অক্ষরে রূপান্তর করে। +* তাদেরকে মাঝখানে একটি স্পেস দিয়ে concatenate করে। + +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + + +### এটি সম্পাদনা করুন + +এটি একটি খুব সাধারণ প্রোগ্রাম। + +কিন্তু এখন কল্পনা করুন যে আপনি এটি শুরু থেকে লিখছিলেন। + +এক পর্যায়ে আপনি ফাংশনের সংজ্ঞা শুরু করেছিলেন, আপনার প্যারামিটারগুলি প্রস্তুত ছিল... + +কিন্তু তারপর আপনাকে "সেই method কল করতে হবে যা প্রথম অক্ষরকে বড় হাতের অক্ষরে রূপান্তর করে"। + +এটা কি `upper` ছিল? নাকি `uppercase`? `first_uppercase`? `capitalize`? + +তারপর, আপনি পুরোনো প্রোগ্রামারের বন্ধু, এডিটর অটোকমপ্লিশনের সাহায্যে নেওয়ার চেষ্টা করেন। + +আপনি ফাংশনের প্রথম প্যারামিটার `first_name` টাইপ করেন, তারপর একটি ডট (`.`) টাইপ করেন এবং `Ctrl+Space` চাপেন অটোকমপ্লিশন ট্রিগার করার জন্য। + +কিন্তু, দুর্ভাগ্যবশত, আপনি কিছুই উপযোগী পান না: + + + +### টাইপ যোগ করুন + +আসুন আগের সংস্করণ থেকে একটি লাইন পরিবর্তন করি। + +আমরা ঠিক এই অংশটি পরিবর্তন করব অর্থাৎ ফাংশনের প্যারামিটারগুলি, এইগুলি: + +```Python + first_name, last_name +``` + +থেকে এইগুলি: + +```Python + first_name: str, last_name: str +``` + +ব্যাস। + +এগুলিই "টাইপ হিন্ট": + +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + + +এটি ডিফল্ট ভ্যালু ঘোষণা করার মত নয় যেমন: + +```Python + first_name="john", last_name="doe" +``` + +এটি একটি ভিন্ন জিনিস। + +আমরা সমান (`=`) নয়, কোলন (`:`) ব্যবহার করছি। + +এবং টাইপ হিন্ট যোগ করা সাধারণত তেমন কিছু পরিবর্তন করে না যা টাইপ হিন্ট ছাড়াই ঘটত। + +কিন্তু এখন, কল্পনা করুন আপনি আবার সেই ফাংশন তৈরির মাঝখানে আছেন, কিন্তু টাইপ হিন্ট সহ। + +একই পর্যায়ে, আপনি অটোকমপ্লিট ট্রিগার করতে `Ctrl+Space` চাপেন এবং আপনি দেখতে পান: + + + +এর সাথে, আপনি অপশনগুলি দেখে, স্ক্রল করতে পারেন, যতক্ষণ না আপনি এমন একটি অপশন খুঁজে পান যা কিছু মনে পরিয়ে দেয়: + + + +## আরও প্রেরণা + +এই ফাংশনটি দেখুন, এটিতে ইতিমধ্যে টাইপ হিন্ট রয়েছে: + +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + + +এডিটর ভেরিয়েবলগুলির টাইপ জানার কারণে, আপনি শুধুমাত্র অটোকমপ্লিশনই পান না, আপনি এরর চেকও পান: + + + +এখন আপনি জানেন যে আপনাকে এটি ঠিক করতে হবে, `age`-কে একটি স্ট্রিং হিসেবে রূপান্তর করতে `str(age)` ব্যবহার করতে হবে: + +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + + +## টাইপ ঘোষণা + +আপনি এতক্ষন টাইপ হিন্ট ঘোষণা করার মূল স্থানটি দেখে ফেলেছেন-- ফাংশন প্যারামিটার হিসেবে। + +সাধারণত এটি **FastAPI** এর ক্ষেত্রেও একই। + +### সিম্পল টাইপ + +আপনি `str` ছাড়াও সমস্ত স্ট্যান্ডার্ড পাইথন টাইপ ঘোষণা করতে পারেন। + +উদাহরণস্বরূপ, আপনি এগুলো ব্যবহার করতে পারেন: + +* `int` +* `float` +* `bool` +* `bytes` + +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + + +### টাইপ প্যারামিটার সহ জেনেরিক টাইপ + +কিছু ডাটা স্ট্রাকচার অন্যান্য মান ধারণ করতে পারে, যেমন `dict`, `list`, `set` এবং `tuple`। এবং অভ্যন্তরীণ মানগুলোরও নিজেদের টাইপ থাকতে পারে। + +এই ধরনের টাইপগুলিকে বলা হয় "**জেনেরিক**" টাইপ এবং এগুলিকে তাদের অভ্যন্তরীণ টাইপগুলি সহ ঘোষণা করা সম্ভব। + +এই টাইপগুলি এবং অভ্যন্তরীণ টাইপগুলি ঘোষণা করতে, আপনি Python মডিউল `typing` ব্যবহার করতে পারেন। এটি বিশেষভাবে এই টাইপ হিন্টগুলি সমর্থন করার জন্য রয়েছে। + +#### Python এর নতুন সংস্করণ + +`typing` ব্যবহার করা সিনট্যাক্সটি Python 3.6 থেকে সর্বশেষ সংস্করণগুলি পর্যন্ত, অর্থাৎ Python 3.9, Python 3.10 ইত্যাদি সহ সকল সংস্করণের সাথে **সামঞ্জস্যপূর্ণ**। + +Python যত এগিয়ে যাচ্ছে, **নতুন সংস্করণগুলি** এই টাইপ অ্যানোটেশনগুলির জন্য তত উন্নত সাপোর্ট নিয়ে আসছে এবং অনেক ক্ষেত্রে আপনাকে টাইপ অ্যানোটেশন ঘোষণা করতে `typing` মডিউল ইম্পোর্ট এবং ব্যবহার করার প্রয়োজন হবে না। + +যদি আপনি আপনার প্রজেক্টের জন্য Python-এর আরও সাম্প্রতিক সংস্করণ নির্বাচন করতে পারেন, তাহলে আপনি সেই অতিরিক্ত সরলতা থেকে সুবিধা নিতে পারবেন। + +ডক্সে রয়েছে Python-এর প্রতিটি সংস্করণের সাথে সামঞ্জস্যপূর্ণ উদাহরণগুলি (যখন পার্থক্য আছে)। + +উদাহরণস্বরূপ, "**Python 3.6+**" মানে এটি Python 3.6 বা তার উপরে সামঞ্জস্যপূর্ণ (যার মধ্যে 3.7, 3.8, 3.9, 3.10, ইত্যাদি অন্তর্ভুক্ত)। এবং "**Python 3.9+**" মানে এটি Python 3.9 বা তার উপরে সামঞ্জস্যপূর্ণ (যার মধ্যে 3.10, ইত্যাদি অন্তর্ভুক্ত)। + +যদি আপনি Python-এর **সর্বশেষ সংস্করণগুলি ব্যবহার করতে পারেন**, তাহলে সর্বশেষ সংস্করণের জন্য উদাহরণগুলি ব্যবহার করুন, সেগুলি আপনাকে **সর্বোত্তম এবং সহজতম সিনট্যাক্স** প্রদান করবে, যেমন, "**Python 3.10+**"। + +#### লিস্ট + +উদাহরণস্বরূপ, একটি ভেরিয়েবলকে `str`-এর একটি `list` হিসেবে সংজ্ঞায়িত করা যাক। + +//// tab | Python 3.9+ + +ভেরিয়েবলটি ঘোষণা করুন, একই কোলন (`:`) সিনট্যাক্স ব্যবহার করে। + +টাইপ হিসেবে, `list` ব্যবহার করুন। + +যেহেতু লিস্ট এমন একটি টাইপ যা অভ্যন্তরীণ টাইপগুলি ধারণ করে, আপনি তাদের স্কোয়ার ব্রাকেটের ভিতরে ব্যবহার করুন: + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial006_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +`typing` থেকে `List` (বড় হাতের `L` দিয়ে) ইমপোর্ট করুন: + +``` Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial006.py!} +``` + +ভেরিয়েবলটি ঘোষণা করুন, একই কোলন (`:`) সিনট্যাক্স ব্যবহার করে। + +টাইপ হিসেবে, `typing` থেকে আপনার ইম্পোর্ট করা `List` ব্যবহার করুন। + +যেহেতু লিস্ট এমন একটি টাইপ যা অভ্যন্তরীণ টাইপগুলি ধারণ করে, আপনি তাদের স্কোয়ার ব্রাকেটের ভিতরে করুন: + +```Python hl_lines="4" +{!> ../../docs_src/python_types/tutorial006.py!} +``` + +//// + +/// info + +স্কোয়ার ব্রাকেট এর ভিতরে ব্যবহৃত এইসব অভন্তরীন টাইপগুলোকে "ইন্টারনাল টাইপ" বলে। + +এই উদাহরণে, এটি হচ্ছে `List`(অথবা পাইথন ৩.৯ বা তার উপরের সংস্করণের ক্ষেত্রে `list`) এ পাস করা টাইপ প্যারামিটার। + +/// + +এর অর্থ হচ্ছে: "ভেরিয়েবল `items` একটি `list`, এবং এই লিস্টের প্রতিটি আইটেম একটি `str`।" + +/// tip + +যদি আপনি Python 3.9 বা তার উপরে ব্যবহার করেন, আপনার `typing` থেকে `List` আমদানি করতে হবে না, আপনি সাধারণ `list` ওই টাইপের পরিবর্তে ব্যবহার করতে পারেন। + +/// + +এর মাধ্যমে, আপনার এডিটর লিস্ট থেকে আইটেম প্রসেস করার সময় সাপোর্ট প্রদান করতে পারবে: + + + +টাইপগুলি ছাড়া, এটি করা প্রায় অসম্ভব। + +লক্ষ্য করুন যে ভেরিয়েবল `item` হল `items` লিস্টের একটি এলিমেন্ট। + +তবুও, এডিটর জানে যে এটি একটি `str`, এবং তার জন্য সাপোর্ট প্রদান করে। + +#### টাপল এবং সেট + +আপনি `tuple` এবং `set` ঘোষণা করার জন্য একই প্রক্রিয়া অনুসরণ করবেন: + +//// tab | Python 3.9+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial007_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial007.py!} +``` + +//// + +এর মানে হল: + +* ভেরিয়েবল `items_t` হল একটি `tuple` যা ৩টি আইটেম ধারণ করে, একটি `int`, অন্য একটি `int`, এবং একটি `str`। +* ভেরিয়েবল `items_s` হল একটি `set`, এবং এর প্রতিটি আইটেম হল `bytes` টাইপের। + +#### ডিক্ট + +একটি `dict` সংজ্ঞায়িত করতে, আপনি ২টি টাইপ প্যারামিটার কমা দ্বারা পৃথক করে দেবেন। + +প্রথম টাইপ প্যারামিটারটি হল `dict`-এর কীগুলির জন্য। + +দ্বিতীয় টাইপ প্যারামিটারটি হল `dict`-এর মানগুলির জন্য: + +//// tab | Python 3.9+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial008_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial008.py!} +``` + +//// + +এর মানে হল: + +* ভেরিয়েবল `prices` হল একটি `dict`: + * এই `dict`-এর কীগুলি হল `str` টাইপের (ধরা যাক, প্রতিটি আইটেমের নাম)। + * এই `dict`-এর মানগুলি হল `float` টাইপের (ধরা যাক, প্রতিটি আইটেমের দাম)। + +#### ইউনিয়ন + +আপনি একটি ভেরিয়েবলকে এমনভাবে ঘোষণা করতে পারেন যেন তা **একাধিক টাইপের** হয়, উদাহরণস্বরূপ, একটি `int` অথবা `str`। + +Python 3.6 এবং তার উপরের সংস্করণগুলিতে (Python 3.10 অন্তর্ভুক্ত) আপনি `typing` থেকে `Union` টাইপ ব্যবহার করতে পারেন এবং স্কোয়ার ব্র্যাকেটের মধ্যে গ্রহণযোগ্য টাইপগুলি রাখতে পারেন। + +Python 3.10-এ একটি **নতুন সিনট্যাক্স** আছে যেখানে আপনি সম্ভাব্য টাইপগুলিকে একটি ভার্টিকাল বার (`|`) দ্বারা পৃথক করতে পারেন। + +//// tab | Python 3.10+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial008b_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial008b.py!} +``` + +//// + +উভয় ক্ষেত্রেই এর মানে হল যে `item` হতে পারে একটি `int` অথবা `str`। + +#### সম্ভবত `None` + +আপনি এমনভাবে ঘোষণা করতে পারেন যে একটি মান হতে পারে এক টাইপের, যেমন `str`, আবার এটি `None`-ও হতে পারে। + +Python 3.6 এবং তার উপরের সংস্করণগুলিতে (Python 3.10 অনতর্ভুক্ত) আপনি `typing` মডিউল থেকে `Optional` ইমপোর্ট করে এটি ঘোষণা এবং ব্যবহার করতে পারেন। + +```Python hl_lines="1 4" +{!../../docs_src/python_types/tutorial009.py!} +``` + +`Optional[str]` ব্যবহার করা মানে হল শুধু `str` নয়, এটি হতে পারে `None`-ও, যা আপনার এডিটরকে সেই ত্রুটিগুলি শনাক্ত করতে সাহায্য করবে যেখানে আপনি ধরে নিচ্ছেন যে একটি মান সবসময় `str` হবে, অথচ এটি `None`-ও হতে পারেও। + +`Optional[Something]` মূলত `Union[Something, None]`-এর একটি শর্টকাট, এবং তারা সমতুল্য। + +এর মানে হল, Python 3.10-এ, আপনি টাইপগুলির ইউনিয়ন ঘোষণা করতে `Something | None` ব্যবহার করতে পারেন: + +//// tab | Python 3.10+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial009_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial009.py!} +``` + +//// + +//// tab | Python 3.8+ বিকল্প + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial009b.py!} +``` + +//// + +#### `Union` বা `Optional` ব্যবহার + +যদি আপনি Python 3.10-এর নীচের সংস্করণ ব্যবহার করেন, তবে এখানে আমার খুবই **ব্যক্তিগত** দৃষ্টিভঙ্গি থেকে একটি টিপস: + +* 🚨 `Optional[SomeType]` ব্যবহার এড়িয়ে চলুন। +* এর পরিবর্তে ✨ **`Union[SomeType, None]` ব্যবহার করুন** ✨। + +উভয়ই সমতুল্য এবং মূলে একই, কিন্তু আমি `Union`-এর পক্ষে সুপারিশ করব কারণ "**অপশনাল**" শব্দটি মনে হতে পারে যে মানটি ঐচ্ছিক,অথচ এটি আসলে মানে "এটি হতে পারে `None`", এমনকি যদি এটি ঐচ্ছিক না হয়েও আবশ্যিক হয়। + +আমি মনে করি `Union[SomeType, None]` এর অর্থ আরও স্পষ্টভাবে প্রকাশ করে। + +এটি কেবল শব্দ এবং নামের ব্যাপার। কিন্তু সেই শব্দগুলি আপনি এবং আপনার সহকর্মীরা কোড সম্পর্কে কীভাবে চিন্তা করেন তা প্রভাবিত করতে পারে। + +একটি উদাহরণ হিসেবে, এই ফাংশনটি নিন: + +{* ../../docs_src/python_types/tutorial009c.py hl[1,4] *} + + +`name` প্যারামিটারটি `Optional[str]` হিসেবে সংজ্ঞায়িত হয়েছে, কিন্তু এটি **অপশনাল নয়**, আপনি প্যারামিটার ছাড়া ফাংশনটি কল করতে পারবেন না: + +```Python +say_hi() # ওহ না, এটি একটি ত্রুটি নিক্ষেপ করবে! 😱 +``` + +`name` প্যারামিটারটি **এখনও আবশ্যিক** (নন-অপশনাল) কারণ এটির কোনো ডিফল্ট মান নেই। তবুও, `name` এর মান হিসেবে `None` গ্রহণযোগ্য: + +```Python +say_hi(name=None) # এটি কাজ করে, None বৈধ 🎉 +``` + +সুখবর হল, একবার আপনি Python 3.10 ব্যবহার করা শুরু করলে, আপনাকে এগুলোর ব্যাপারে আর চিন্তা করতে হবে না, যেহুতু আপনি | ব্যবহার করেই ইউনিয়ন ঘোষণা করতে পারবেন: + +{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *} + + +এবং তারপর আপনাকে নামগুলি যেমন `Optional` এবং `Union` নিয়ে আর চিন্তা করতে হবে না। 😎 + +#### জেনেরিক টাইপস + +স্কোয়ার ব্র্যাকেটে টাইপ প্যারামিটার নেওয়া এই টাইপগুলিকে **জেনেরিক টাইপ** বা **জেনেরিকস** বলা হয়, যেমন: + +//// tab | Python 3.10+ + +আপনি সেই একই বিল্টইন টাইপ জেনেরিক্স হিসেবে ব্যবহার করতে পারবেন(ভিতরে টাইপ সহ স্কয়ারে ব্রাকেট দিয়ে): + +* `list` +* `tuple` +* `set` +* `dict` + +এবং Python 3.8 এর মতোই, `typing` মডিউল থেকে: + +* `Union` +* `Optional` (Python 3.8 এর মতোই) +* ...এবং অন্যান্য। + +Python 3.10-এ, `Union` এবং `Optional` জেনেরিকস ব্যবহার করার বিকল্প হিসেবে, আপনি টাইপগুলির ইউনিয়ন ঘোষণা করতে ভার্টিকাল বার (`|`) ব্যবহার করতে পারেন, যা ওদের থেকে অনেক ভালো এবং সহজ। + +//// + +//// tab | Python 3.9+ + +আপনি সেই একই বিল্টইন টাইপ জেনেরিক্স হিসেবে ব্যবহার করতে পারবেন(ভিতরে টাইপ সহ স্কয়ারে ব্রাকেট দিয়ে): + +* `list` +* `tuple` +* `set` +* `dict` + +এবং Python 3.8 এর মতোই, `typing` মডিউল থেকে: + +* `Union` +* `Optional` +* ...এবং অন্যান্য। + +//// + +//// tab | Python 3.8+ + +* `List` +* `Tuple` +* `Set` +* `Dict` +* `Union` +* `Optional` +* ...এবং অন্যান্য। + +//// + +### ক্লাস হিসেবে টাইপস + +আপনি একটি ভেরিয়েবলের টাইপ হিসেবে একটি ক্লাস ঘোষণা করতে পারেন। + +ধরুন আপনার কাছে `Person` নামে একটি ক্লাস আছে, যার একটি নাম আছে: + +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + + +তারপর আপনি একটি ভেরিয়েবলকে `Person` টাইপের হিসেবে ঘোষণা করতে পারেন: + +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + + +এবং তারপর, আবার, আপনি এডিটর সাপোর্ট পেয়ে যাবেন: + + + +লক্ষ্য করুন যে এর মানে হল "`one_person` হল ক্লাস `Person`-এর একটি **ইন্সট্যান্স**।" + +এর মানে এটি নয় যে "`one_person` হল **ক্লাস** যাকে বলা হয় `Person`।" + +## Pydantic মডেল + +[Pydantic](https://docs.pydantic.dev/) হল একটি Python লাইব্রেরি যা ডাটা ভ্যালিডেশন সম্পাদন করে। + +আপনি ডাটার "আকার" এট্রিবিউট সহ ক্লাস হিসেবে ঘোষণা করেন। + +এবং প্রতিটি এট্রিবিউট এর একটি টাইপ থাকে। + +তারপর আপনি যদি কিছু মান দিয়ে সেই ক্লাসের একটি ইন্সট্যান্স তৈরি করেন-- এটি মানগুলিকে ভ্যালিডেট করবে, প্রয়োজন অনুযায়ী তাদেরকে উপযুক্ত টাইপে রূপান্তর করবে এবং আপনাকে সমস্ত ডাটা সহ একটি অবজেক্ট প্রদান করবে। + +এবং আপনি সেই ফলাফল অবজেক্টের সাথে এডিটর সাপোর্ট পাবেন। + +অফিসিয়াল Pydantic ডক্স থেকে একটি উদাহরণ: + +//// tab | Python 3.10+ + +```Python +{!> ../../docs_src/python_types/tutorial011_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python +{!> ../../docs_src/python_types/tutorial011_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python +{!> ../../docs_src/python_types/tutorial011.py!} +``` + +//// + +/// info + +[Pydantic সম্পর্কে আরও জানতে, এর ডকুমেন্টেশন দেখুন](https://docs.pydantic.dev/)। + +/// + +**FastAPI** মূলত Pydantic-এর উপর নির্মিত। + +আপনি এই সমস্ত কিছুর অনেক বাস্তবসম্মত উদাহরণ পাবেন [টিউটোরিয়াল - ইউজার গাইডে](https://fastapi.tiangolo.com/tutorial/)। + +/// tip + +যখন আপনি `Optional` বা `Union[Something, None]` ব্যবহার করেন এবং কোনো ডিফল্ট মান না থাকে, Pydantic-এর একটি বিশেষ আচরণ রয়েছে, আপনি Pydantic ডকুমেন্টেশনে [Required Optional fields](https://docs.pydantic.dev/latest/concepts/models/#required-optional-fields) সম্পর্কে আরও পড়তে পারেন। + +/// + +## মেটাডাটা অ্যানোটেশন সহ টাইপ হিন্টস + +Python-এ এমন একটি ফিচার আছে যা `Annotated` ব্যবহার করে এই টাইপ হিন্টগুলিতে **অতিরিক্ত মেটাডাটা** রাখতে দেয়। + +//// tab | Python 3.9+ + +Python 3.9-এ, `Annotated` স্ট্যান্ডার্ড লাইব্রেরিতে অন্তর্ভুক্ত, তাই আপনি এটি `typing` থেকে ইমপোর্ট করতে পারেন। + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial013_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +Python 3.9-এর নীচের সংস্করণগুলিতে, আপনি `Annotated`-কে `typing_extensions` থেকে ইমপোর্ট করেন। + +এটি **FastAPI** এর সাথে ইতিমদ্ধে ইনস্টল হয়ে থাকবে। + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial013.py!} +``` + +//// + +Python নিজে এই `Annotated` দিয়ে কিছুই করে না। এবং এডিটর এবং অন্যান্য টুলগুলির জন্য, টাইপটি এখনও `str`। + +কিন্তু আপনি এই `Annotated` এর মধ্যকার জায়গাটির মধ্যে **FastAPI**-এ কীভাবে আপনার অ্যাপ্লিকেশন আচরণ করুক তা সম্পর্কে অতিরিক্ত মেটাডাটা প্রদান করার জন্য ব্যবহার করতে পারেন। + +মনে রাখার গুরুত্বপূর্ণ বিষয় হল যে **প্রথম *টাইপ প্যারামিটার*** আপনি `Annotated`-এ পাস করেন সেটি হল **আসল টাইপ**। বাকি শুধুমাত্র অন্যান্য টুলগুলির জন্য মেটাডাটা। + +এখন আপনার কেবল জানা প্রয়োজন যে `Annotated` বিদ্যমান, এবং এটি স্ট্যান্ডার্ড Python। 😎 + +পরবর্তীতে আপনি দেখবেন এটি কতটা **শক্তিশালী** হতে পারে। + +/// tip + +এটি **স্ট্যান্ডার্ড Python** হওয়ার মানে হল আপনি আপনার এডিটরে, আপনি যে টুলগুলি কোড বিশ্লেষণ এবং রিফ্যাক্টর করার জন্য ব্যবহার করেন তাতে **সেরা সম্ভাব্য ডেভেলপার এক্সপেরিয়েন্স** পাবেন। ✨ + +এবং এছাড়াও আপনার কোড অন্যান্য অনেক Python টুল এবং লাইব্রেরিগুলির সাথে খুব সামঞ্জস্যপূর্ণ হবে। 🚀 + +/// + +## **FastAPI**-এ টাইপ হিন্টস + +**FastAPI** এই টাইপ হিন্টগুলি ব্যবহার করে বেশ কিছু জিনিস করে। + +**FastAPI**-এ আপনি টাইপ হিন্টগুলি সহ প্যারামিটার ঘোষণা করেন এবং আপনি পান: + +* **এডিটর সাপোর্ট**। +* **টাইপচেক**। + +...এবং **FastAPI** একই ঘোষণাগুলি ব্যবহার করে: + +* **রিকুইরেমেন্টস সংজ্ঞায়িত করে**: রিকোয়েস্ট পাথ প্যারামিটার, কুয়েরি প্যারামিটার, হেডার, বডি, ডিপেন্ডেন্সিস, ইত্যাদি থেকে। +* **ডেটা রূপান্তর করে**: রিকোয়েস্ট থেকে প্রয়োজনীয় টাইপে ডেটা। +* **ডেটা যাচাই করে**: প্রতিটি রিকোয়েস্ট থেকে আসা ডেটা: + * যখন ডেটা অবৈধ হয় তখন **স্বয়ংক্রিয় ত্রুটি** গ্রাহকের কাছে ফেরত পাঠানো। +* **API ডকুমেন্টেশন তৈরি করে**: OpenAPI ব্যবহার করে: + * যা স্বয়ংক্রিয় ইন্টার‌্যাক্টিভ ডকুমেন্টেশন ইউজার ইন্টারফেস দ্বারা ব্যবহৃত হয়। + +এই সব কিছু আপনার কাছে অস্পষ্ট মনে হতে পারে। চিন্তা করবেন না। আপনি [টিউটোরিয়াল - ইউজার গাইড](https://fastapi.tiangolo.com/tutorial/) এ এই সব কিছু প্র্যাকটিসে দেখতে পাবেন। + +গুরুত্বপূর্ণ বিষয় হল, আপনি যদি স্ট্যান্ডার্ড Python টাইপগুলি ব্যবহার করেন, তবে আরও বেশি ক্লাস, ডেকোরেটর ইত্যাদি যোগ না করেই একই স্থানে **FastAPI** আপনার অনেক কাজ করে দিবে। + +/// info + +যদি আপনি টিউটোরিয়ালের সমস্ত বিষয় পড়ে ফেলে থাকেন এবং টাইপ সম্পর্কে আরও জানতে চান, তবে একটি ভালো রিসোর্স হল [mypy এর "cheat sheet"](https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html)। এই "cheat sheet" এ আপনি Python টাইপ হিন্ট সম্পর্কে বেসিক থেকে উন্নত লেভেলের ধারণা পেতে পারেন, যা আপনার কোডে টাইপ সেফটি এবং স্পষ্টতা বাড়াতে সাহায্য করবে। + +/// diff --git a/docs/de/docs/about/index.md b/docs/de/docs/about/index.md new file mode 100644 index 000000000..4c309e02a --- /dev/null +++ b/docs/de/docs/about/index.md @@ -0,0 +1,3 @@ +# Über + +Über FastAPI, sein Design, seine Inspiration und mehr. 🤓 diff --git a/docs/de/docs/advanced/additional-responses.md b/docs/de/docs/advanced/additional-responses.md new file mode 100644 index 000000000..bf38d9795 --- /dev/null +++ b/docs/de/docs/advanced/additional-responses.md @@ -0,0 +1,247 @@ +# Zusätzliche Responses in OpenAPI + +/// warning | Achtung + +Dies ist ein eher fortgeschrittenes Thema. + +Wenn Sie mit **FastAPI** beginnen, benötigen Sie dies möglicherweise nicht. + +/// + +Sie können zusätzliche Responses mit zusätzlichen Statuscodes, Medientypen, Beschreibungen, usw. deklarieren. + +Diese zusätzlichen Responses werden in das OpenAPI-Schema aufgenommen, sodass sie auch in der API-Dokumentation erscheinen. + +Für diese zusätzlichen Responses müssen Sie jedoch sicherstellen, dass Sie eine `Response`, wie etwa `JSONResponse`, direkt zurückgeben, mit Ihrem Statuscode und Inhalt. + +## Zusätzliche Response mit `model` + +Sie können Ihren *Pfadoperation-Dekoratoren* einen Parameter `responses` übergeben. + +Der nimmt ein `dict` entgegen, die Schlüssel sind Statuscodes für jede Response, wie etwa `200`, und die Werte sind andere `dict`s mit den Informationen für jede Response. + +Jedes dieser Response-`dict`s kann einen Schlüssel `model` haben, welcher ein Pydantic-Modell enthält, genau wie `response_model`. + +**FastAPI** nimmt dieses Modell, generiert dessen JSON-Schema und fügt es an der richtigen Stelle in OpenAPI ein. + +Um beispielsweise eine weitere Response mit dem Statuscode `404` und einem Pydantic-Modell `Message` zu deklarieren, können Sie schreiben: + +{* ../../docs_src/additional_responses/tutorial001.py hl[18,22] *} + +/// note | Hinweis + +Beachten Sie, dass Sie die `JSONResponse` direkt zurückgeben müssen. + +/// + +/// info + +Der `model`-Schlüssel ist nicht Teil von OpenAPI. + +**FastAPI** nimmt das Pydantic-Modell von dort, generiert das JSON-Schema und fügt es an der richtigen Stelle ein. + +Die richtige Stelle ist: + +* Im Schlüssel `content`, der als Wert ein weiteres JSON-Objekt (`dict`) hat, welches Folgendes enthält: + * Ein Schlüssel mit dem Medientyp, z. B. `application/json`, der als Wert ein weiteres JSON-Objekt hat, welches Folgendes enthält: + * Ein Schlüssel `schema`, der als Wert das JSON-Schema aus dem Modell hat, hier ist die richtige Stelle. + * **FastAPI** fügt hier eine Referenz auf die globalen JSON-Schemas an einer anderen Stelle in Ihrer OpenAPI hinzu, anstatt es direkt einzubinden. Auf diese Weise können andere Anwendungen und Clients diese JSON-Schemas direkt verwenden, bessere Tools zur Codegenerierung bereitstellen, usw. + +/// + +Die generierten Responses in der OpenAPI für diese *Pfadoperation* lauten: + +```JSON hl_lines="3-12" +{ + "responses": { + "404": { + "description": "Additional Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Message" + } + } + } + }, + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Item" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } +} +``` + +Die Schemas werden von einer anderen Stelle innerhalb des OpenAPI-Schemas referenziert: + +```JSON hl_lines="4-16" +{ + "components": { + "schemas": { + "Message": { + "title": "Message", + "required": [ + "message" + ], + "type": "object", + "properties": { + "message": { + "title": "Message", + "type": "string" + } + } + }, + "Item": { + "title": "Item", + "required": [ + "id", + "value" + ], + "type": "object", + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "value": { + "title": "Value", + "type": "string" + } + } + }, + "ValidationError": { + "title": "ValidationError", + "required": [ + "loc", + "msg", + "type" + ], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "type": "string" + } + }, + "msg": { + "title": "Message", + "type": "string" + }, + "type": { + "title": "Error Type", + "type": "string" + } + } + }, + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": { + "$ref": "#/components/schemas/ValidationError" + } + } + } + } + } + } +} +``` + +## Zusätzliche Medientypen für die Haupt-Response + +Sie können denselben `responses`-Parameter verwenden, um verschiedene Medientypen für dieselbe Haupt-Response hinzuzufügen. + +Sie können beispielsweise einen zusätzlichen Medientyp `image/png` hinzufügen und damit deklarieren, dass Ihre *Pfadoperation* ein JSON-Objekt (mit dem Medientyp `application/json`) oder ein PNG-Bild zurückgeben kann: + +{* ../../docs_src/additional_responses/tutorial002.py hl[19:24,28] *} + +/// note | Hinweis + +Beachten Sie, dass Sie das Bild direkt mit einer `FileResponse` zurückgeben müssen. + +/// + +/// info + +Sofern Sie in Ihrem Parameter `responses` nicht explizit einen anderen Medientyp angeben, geht FastAPI davon aus, dass die Response denselben Medientyp wie die Haupt-Response-Klasse hat (Standardmäßig `application/json`). + +Wenn Sie jedoch eine benutzerdefinierte Response-Klasse mit `None` als Medientyp angegeben haben, verwendet FastAPI `application/json` für jede zusätzliche Response, die über ein zugehöriges Modell verfügt. + +/// + +## Informationen kombinieren + +Sie können auch Response-Informationen von mehreren Stellen kombinieren, einschließlich der Parameter `response_model`, `status_code` und `responses`. + +Sie können ein `response_model` deklarieren, indem Sie den Standardstatuscode `200` (oder bei Bedarf einen benutzerdefinierten) verwenden und dann zusätzliche Informationen für dieselbe Response in `responses` direkt im OpenAPI-Schema deklarieren. + +**FastAPI** behält die zusätzlichen Informationen aus `responses` und kombiniert sie mit dem JSON-Schema aus Ihrem Modell. + +Sie können beispielsweise eine Response mit dem Statuscode `404` deklarieren, die ein Pydantic-Modell verwendet und über eine benutzerdefinierte Beschreibung (`description`) verfügt. + +Und eine Response mit dem Statuscode `200`, die Ihr `response_model` verwendet, aber ein benutzerdefiniertes Beispiel (`example`) enthält: + +{* ../../docs_src/additional_responses/tutorial003.py hl[20:31] *} + +Es wird alles kombiniert und in Ihre OpenAPI eingebunden und in der API-Dokumentation angezeigt: + + + +## Vordefinierte und benutzerdefinierte Responses kombinieren + +Möglicherweise möchten Sie einige vordefinierte Responses haben, die für viele *Pfadoperationen* gelten, Sie möchten diese jedoch mit benutzerdefinierten Responses kombinieren, die für jede *Pfadoperation* erforderlich sind. + +In diesen Fällen können Sie die Python-Technik zum „Entpacken“ eines `dict`s mit `**dict_to_unpack` verwenden: + +```Python +old_dict = { + "old key": "old value", + "second old key": "second old value", +} +new_dict = {**old_dict, "new key": "new value"} +``` + +Hier wird `new_dict` alle Schlüssel-Wert-Paare von `old_dict` plus das neue Schlüssel-Wert-Paar enthalten: + +```Python +{ + "old key": "old value", + "second old key": "second old value", + "new key": "new value", +} +``` + +Mit dieser Technik können Sie einige vordefinierte Responses in Ihren *Pfadoperationen* wiederverwenden und sie mit zusätzlichen benutzerdefinierten Responses kombinieren. + +Zum Beispiel: + +{* ../../docs_src/additional_responses/tutorial004.py hl[13:17,26] *} + +## Weitere Informationen zu OpenAPI-Responses + +Um zu sehen, was genau Sie in die Responses aufnehmen können, können Sie die folgenden Abschnitte in der OpenAPI-Spezifikation überprüfen: + +* OpenAPI Responses Object, enthält das `Response Object`. +* OpenAPI Response Object, Sie können alles davon direkt in jede Response innerhalb Ihres `responses`-Parameter einfügen. Einschließlich `description`, `headers`, `content` (darin deklarieren Sie verschiedene Medientypen und JSON-Schemas) und `links`. diff --git a/docs/de/docs/advanced/additional-status-codes.md b/docs/de/docs/advanced/additional-status-codes.md new file mode 100644 index 000000000..b07bb90ab --- /dev/null +++ b/docs/de/docs/advanced/additional-status-codes.md @@ -0,0 +1,41 @@ +# Zusätzliche Statuscodes + +Standardmäßig liefert **FastAPI** die Rückgabewerte (Responses) als `JSONResponse` zurück und fügt den Inhalt der jeweiligen *Pfadoperation* in das `JSONResponse` Objekt ein. + +Es wird der Default-Statuscode oder derjenige verwendet, den Sie in Ihrer *Pfadoperation* festgelegt haben. + +## Zusätzliche Statuscodes + +Wenn Sie neben dem Hauptstatuscode weitere Statuscodes zurückgeben möchten, können Sie dies tun, indem Sie direkt eine `Response` zurückgeben, wie etwa eine `JSONResponse`, und den zusätzlichen Statuscode direkt festlegen. + +Angenommen, Sie möchten eine *Pfadoperation* haben, die das Aktualisieren von Artikeln ermöglicht und bei Erfolg den HTTP-Statuscode 200 „OK“ zurückgibt. + +Sie möchten aber auch, dass sie neue Artikel akzeptiert. Und wenn die Elemente vorher nicht vorhanden waren, werden diese Elemente erstellt und der HTTP-Statuscode 201 „Created“ zurückgegeben. + +Um dies zu erreichen, importieren Sie `JSONResponse`, und geben Sie Ihren Inhalt direkt zurück, indem Sie den gewünschten `status_code` setzen: + +{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *} + +/// warning | Achtung + +Wenn Sie eine `Response` direkt zurückgeben, wie im obigen Beispiel, wird sie direkt zurückgegeben. + +Sie wird nicht mit einem Modell usw. serialisiert. + +Stellen Sie sicher, dass sie die gewünschten Daten enthält und dass die Werte gültiges JSON sind (wenn Sie `JSONResponse` verwenden). + +/// + +/// note | Technische Details + +Sie können auch `from starlette.responses import JSONResponse` verwenden. + +**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. Das Gleiche gilt für `status`. + +/// + +## OpenAPI- und API-Dokumentation + +Wenn Sie zusätzliche Statuscodes und Responses direkt zurückgeben, werden diese nicht in das OpenAPI-Schema (die API-Dokumentation) aufgenommen, da FastAPI keine Möglichkeit hat, im Voraus zu wissen, was Sie zurückgeben werden. + +Sie können das jedoch in Ihrem Code dokumentieren, indem Sie Folgendes verwenden: [Zusätzliche Responses](additional-responses.md){.internal-link target=_blank}. diff --git a/docs/de/docs/advanced/advanced-dependencies.md b/docs/de/docs/advanced/advanced-dependencies.md new file mode 100644 index 000000000..56eb7d454 --- /dev/null +++ b/docs/de/docs/advanced/advanced-dependencies.md @@ -0,0 +1,65 @@ +# Fortgeschrittene Abhängigkeiten + +## Parametrisierte Abhängigkeiten + +Alle Abhängigkeiten, die wir bisher gesehen haben, waren festgelegte Funktionen oder Klassen. + +Es kann jedoch Fälle geben, in denen Sie Parameter für eine Abhängigkeit festlegen möchten, ohne viele verschiedene Funktionen oder Klassen zu deklarieren. + +Stellen wir uns vor, wir möchten eine Abhängigkeit haben, die prüft, ob ein Query-Parameter `q` einen vordefinierten Inhalt hat. + +Aber wir wollen diesen vordefinierten Inhalt per Parameter festlegen können. + +## Eine „aufrufbare“ Instanz + +In Python gibt es eine Möglichkeit, eine Instanz einer Klasse „aufrufbar“ („callable“) zu machen. + +Nicht die Klasse selbst (die bereits aufrufbar ist), sondern eine Instanz dieser Klasse. + +Dazu deklarieren wir eine Methode `__call__`: + +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[12] *} + +In diesem Fall ist dieses `__call__` das, was **FastAPI** verwendet, um nach zusätzlichen Parametern und Unterabhängigkeiten zu suchen, und das ist es auch, was später aufgerufen wird, um einen Wert an den Parameter in Ihrer *Pfadoperation-Funktion* zu übergeben. + +## Die Instanz parametrisieren + +Und jetzt können wir `__init__` verwenden, um die Parameter der Instanz zu deklarieren, die wir zum `Parametrisieren` der Abhängigkeit verwenden können: + +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[9] *} + +In diesem Fall wird **FastAPI** `__init__` nie berühren oder sich darum kümmern, wir werden es direkt in unserem Code verwenden. + +## Eine Instanz erstellen + +Wir könnten eine Instanz dieser Klasse erstellen mit: + +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[18] *} + +Und auf diese Weise können wir unsere Abhängigkeit „parametrisieren“, die jetzt `"bar"` enthält, als das Attribut `checker.fixed_content`. + +## Die Instanz als Abhängigkeit verwenden + +Dann könnten wir diesen `checker` in einem `Depends(checker)` anstelle von `Depends(FixedContentQueryChecker)` verwenden, da die Abhängigkeit die Instanz `checker` und nicht die Klasse selbst ist. + +Und beim Auflösen der Abhängigkeit ruft **FastAPI** diesen `checker` wie folgt auf: + +```Python +checker(q="somequery") +``` + +... und übergibt, was immer das als Wert dieser Abhängigkeit in unserer *Pfadoperation-Funktion* zurückgibt, als den Parameter `fixed_content_included`: + +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[22] *} + +/// tip | Tipp + +Das alles mag gekünstelt wirken. Und es ist möglicherweise noch nicht ganz klar, welchen Nutzen das hat. + +Diese Beispiele sind bewusst einfach gehalten, zeigen aber, wie alles funktioniert. + +In den Kapiteln zum Thema Sicherheit gibt es Hilfsfunktionen, die auf die gleiche Weise implementiert werden. + +Wenn Sie das hier alles verstanden haben, wissen Sie bereits, wie diese Sicherheits-Hilfswerkzeuge unter der Haube funktionieren. + +/// diff --git a/docs/de/docs/advanced/async-tests.md b/docs/de/docs/advanced/async-tests.md new file mode 100644 index 000000000..b82aadf00 --- /dev/null +++ b/docs/de/docs/advanced/async-tests.md @@ -0,0 +1,99 @@ +# Asynchrone Tests + +Sie haben bereits gesehen, wie Sie Ihre **FastAPI**-Anwendungen mit dem bereitgestellten `TestClient` testen. Bisher haben Sie nur gesehen, wie man synchrone Tests schreibt, ohne `async`hrone Funktionen zu verwenden. + +Die Möglichkeit, in Ihren Tests asynchrone Funktionen zu verwenden, könnte beispielsweise nützlich sein, wenn Sie Ihre Datenbank asynchron abfragen. Stellen Sie sich vor, Sie möchten das Senden von Requests an Ihre FastAPI-Anwendung testen und dann überprüfen, ob Ihr Backend die richtigen Daten erfolgreich in die Datenbank geschrieben hat, während Sie eine asynchrone Datenbankbibliothek verwenden. + +Schauen wir uns an, wie wir das machen können. + +## pytest.mark.anyio + +Wenn wir in unseren Tests asynchrone Funktionen aufrufen möchten, müssen unsere Testfunktionen asynchron sein. AnyIO stellt hierfür ein nettes Plugin zur Verfügung, mit dem wir festlegen können, dass einige Testfunktionen asynchron aufgerufen werden sollen. + +## HTTPX + +Auch wenn Ihre **FastAPI**-Anwendung normale `def`-Funktionen anstelle von `async def` verwendet, handelt es sich darunter immer noch um eine `async`hrone Anwendung. + +Der `TestClient` macht unter der Haube magisches, um die asynchrone FastAPI-Anwendung in Ihren normalen `def`-Testfunktionen, mithilfe von Standard-Pytest aufzurufen. Aber diese Magie funktioniert nicht mehr, wenn wir sie in asynchronen Funktionen verwenden. Durch die asynchrone Ausführung unserer Tests können wir den `TestClient` nicht mehr in unseren Testfunktionen verwenden. + +Der `TestClient` basiert auf HTTPX und glücklicherweise können wir ihn direkt verwenden, um die API zu testen. + +## Beispiel + +Betrachten wir als einfaches Beispiel eine Dateistruktur ähnlich der in [Größere Anwendungen](../tutorial/bigger-applications.md){.internal-link target=_blank} und [Testen](../tutorial/testing.md){.internal-link target=_blank}: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +Die Datei `main.py` hätte als Inhalt: + +{* ../../docs_src/async_tests/main.py *} + +Die Datei `test_main.py` hätte die Tests für `main.py`, das könnte jetzt so aussehen: + +{* ../../docs_src/async_tests/test_main.py *} + +## Es ausführen + +Sie können Ihre Tests wie gewohnt ausführen mit: + +
+ +```console +$ pytest + +---> 100% +``` + +
+ +## Details + +Der Marker `@pytest.mark.anyio` teilt pytest mit, dass diese Testfunktion asynchron aufgerufen werden soll: + +{* ../../docs_src/async_tests/test_main.py hl[7] *} + +/// tip | Tipp + +Beachten Sie, dass die Testfunktion jetzt `async def` ist und nicht nur `def` wie zuvor, wenn Sie den `TestClient` verwenden. + +/// + +Dann können wir einen `AsyncClient` mit der App erstellen und mit `await` asynchrone Requests an ihn senden. + +{* ../../docs_src/async_tests/test_main.py hl[9:12] *} + +Das ist das Äquivalent zu: + +```Python +response = client.get('/') +``` + +... welches wir verwendet haben, um unsere Requests mit dem `TestClient` zu machen. + +/// tip | Tipp + +Beachten Sie, dass wir async/await mit dem neuen `AsyncClient` verwenden – der Request ist asynchron. + +/// + +/// warning | Achtung + +Falls Ihre Anwendung auf Lifespan-Events angewiesen ist, der `AsyncClient` löst diese Events nicht aus. Um sicherzustellen, dass sie ausgelöst werden, verwenden Sie `LifespanManager` von florimondmanca/asgi-lifespan. + +/// + +## Andere asynchrone Funktionsaufrufe + +Da die Testfunktion jetzt asynchron ist, können Sie in Ihren Tests neben dem Senden von Requests an Ihre FastAPI-Anwendung jetzt auch andere `async`hrone Funktionen aufrufen (und `await`en), genau so, wie Sie diese an anderer Stelle in Ihrem Code aufrufen würden. + +/// tip | Tipp + +Wenn Sie einen `RuntimeError: Task attached to a different loop` erhalten, wenn Sie asynchrone Funktionsaufrufe in Ihre Tests integrieren (z. B. bei Verwendung von MongoDBs MotorClient), dann denken Sie daran, Objekte zu instanziieren, die einen Event Loop nur innerhalb asynchroner Funktionen benötigen, z. B. einen `@app.on_event("startup")`-Callback. + +/// diff --git a/docs/de/docs/advanced/behind-a-proxy.md b/docs/de/docs/advanced/behind-a-proxy.md new file mode 100644 index 000000000..9e2282280 --- /dev/null +++ b/docs/de/docs/advanced/behind-a-proxy.md @@ -0,0 +1,361 @@ +# Hinter einem Proxy + +In manchen Situationen müssen Sie möglicherweise einen **Proxy**-Server wie Traefik oder Nginx verwenden, mit einer Konfiguration, die ein zusätzliches Pfadpräfix hinzufügt, das von Ihrer Anwendung nicht gesehen wird. + +In diesen Fällen können Sie `root_path` verwenden, um Ihre Anwendung zu konfigurieren. + +Der `root_path` („Wurzelpfad“) ist ein Mechanismus, der von der ASGI-Spezifikation bereitgestellt wird (auf der FastAPI via Starlette aufbaut). + +Der `root_path` wird verwendet, um diese speziellen Fälle zu handhaben. + +Und er wird auch intern beim Mounten von Unteranwendungen verwendet. + +## Proxy mit einem abgetrennten Pfadpräfix + +Ein Proxy mit einem abgetrennten Pfadpräfix bedeutet in diesem Fall, dass Sie einen Pfad unter `/app` in Ihrem Code deklarieren könnten, dann aber, eine Ebene darüber, den Proxy hinzufügen, der Ihre **FastAPI**-Anwendung unter einem Pfad wie `/api/v1` platziert. + +In diesem Fall würde der ursprüngliche Pfad `/app` tatsächlich unter `/api/v1/app` bereitgestellt. + +Auch wenn Ihr gesamter Code unter der Annahme geschrieben ist, dass es nur `/app` gibt. + +{* ../../docs_src/behind_a_proxy/tutorial001.py hl[6] *} + +Und der Proxy würde das **Pfadpräfix** on-the-fly **"entfernen**", bevor er die Anfrage an Uvicorn übermittelt, dafür sorgend, dass Ihre Anwendung davon überzeugt ist, dass sie unter `/app` bereitgestellt wird, sodass Sie nicht Ihren gesamten Code dahingehend aktualisieren müssen, das Präfix `/api/v1` zu verwenden. + +Bis hierher würde alles wie gewohnt funktionieren. + +Wenn Sie dann jedoch die Benutzeroberfläche der integrierten Dokumentation (das Frontend) öffnen, wird angenommen, dass sich das OpenAPI-Schema unter `/openapi.json` anstelle von `/api/v1/openapi.json` befindet. + +Das Frontend (das im Browser läuft) würde also versuchen, `/openapi.json` zu erreichen und wäre nicht in der Lage, das OpenAPI-Schema abzurufen. + +Da wir für unsere Anwendung einen Proxy mit dem Pfadpräfix `/api/v1` haben, muss das Frontend das OpenAPI-Schema unter `/api/v1/openapi.json` abrufen. + +```mermaid +graph LR + +browser("Browser") +proxy["Proxy auf http://0.0.0.0:9999/api/v1/app"] +server["Server auf http://127.0.0.1:8000/app"] + +browser --> proxy +proxy --> server +``` + +/// tip | Tipp + +Die IP `0.0.0.0` wird üblicherweise verwendet, um anzudeuten, dass das Programm alle auf diesem Computer/Server verfügbaren IPs abhört. + +/// + +Die Benutzeroberfläche der Dokumentation würde benötigen, dass das OpenAPI-Schema deklariert, dass sich dieser API-`server` unter `/api/v1` (hinter dem Proxy) befindet. Zum Beispiel: + +```JSON hl_lines="4-8" +{ + "openapi": "3.1.0", + // Hier mehr Einstellungen + "servers": [ + { + "url": "/api/v1" + } + ], + "paths": { + // Hier mehr Einstellungen + } +} +``` + +In diesem Beispiel könnte der „Proxy“ etwa **Traefik** sein. Und der Server wäre so etwas wie **Uvicorn**, auf dem Ihre FastAPI-Anwendung ausgeführt wird. + +### Bereitstellung des `root_path` + +Um dies zu erreichen, können Sie die Kommandozeilenoption `--root-path` wie folgt verwenden: + +
+ +```console +$ uvicorn main:app --root-path /api/v1 + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Falls Sie Hypercorn verwenden, das hat auch die Option `--root-path`. + +/// note | Technische Details + +Die ASGI-Spezifikation definiert einen `root_path` für diesen Anwendungsfall. + +Und die Kommandozeilenoption `--root-path` stellt diesen `root_path` bereit. + +/// + +### Überprüfen des aktuellen `root_path` + +Sie können den aktuellen `root_path` abrufen, der von Ihrer Anwendung für jede Anfrage verwendet wird. Er ist Teil des `scope`-Dictionarys (das ist Teil der ASGI-Spezifikation). + +Hier fügen wir ihn, nur zu Demonstrationszwecken, in die Nachricht ein. + +{* ../../docs_src/behind_a_proxy/tutorial001.py hl[8] *} + +Wenn Sie Uvicorn dann starten mit: + +
+ +```console +$ uvicorn main:app --root-path /api/v1 + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +wäre die Response etwa: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +### Festlegen des `root_path` in der FastAPI-Anwendung + +Falls Sie keine Möglichkeit haben, eine Kommandozeilenoption wie `--root-path` oder ähnlich zu übergeben, können Sie als Alternative beim Erstellen Ihrer FastAPI-Anwendung den Parameter `root_path` setzen: + +{* ../../docs_src/behind_a_proxy/tutorial002.py hl[3] *} + +Die Übergabe des `root_path` an `FastAPI` wäre das Äquivalent zur Übergabe der `--root-path`-Kommandozeilenoption an Uvicorn oder Hypercorn. + +### Über `root_path` + +Beachten Sie, dass der Server (Uvicorn) diesen `root_path` für nichts anderes außer die Weitergabe an die Anwendung verwendet. + +Aber wenn Sie mit Ihrem Browser auf http://127.0.0.1:8000/app gehen, sehen Sie die normale Antwort: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +Es wird also nicht erwartet, dass unter `http://127.0.0.1:8000/api/v1/app` darauf zugegriffen wird. + +Uvicorn erwartet, dass der Proxy unter `http://127.0.0.1:8000/app` auf Uvicorn zugreift, und dann liegt es in der Verantwortung des Proxys, das zusätzliche `/api/v1`-Präfix darüber hinzuzufügen. + +## Über Proxys mit einem abgetrennten Pfadpräfix + +Bedenken Sie, dass ein Proxy mit abgetrennten Pfadpräfix nur eine von vielen Konfigurationsmöglichkeiten ist. + +Wahrscheinlich wird in vielen Fällen die Standardeinstellung sein, dass der Proxy kein abgetrenntes Pfadpräfix hat. + +In einem solchen Fall (ohne ein abgetrenntes Pfadpräfix) würde der Proxy auf etwas wie `https://myawesomeapp.com` lauschen, und wenn der Browser dann zu `https://myawesomeapp.com/api/v1/` wechselt, und Ihr Server (z. B. Uvicorn) auf `http://127.0.0.1:8000` lauscht, würde der Proxy (ohne ein abgetrenntes Pfadpräfix) über denselben Pfad auf Uvicorn zugreifen: `http://127.0.0.1:8000/api/v1/app`. + +## Lokal testen mit Traefik + +Sie können das Experiment mit einem abgetrennten Pfadpräfix ganz einfach lokal ausführen, indem Sie Traefik verwenden. + +Laden Sie Traefik herunter, es ist eine einzelne Binärdatei, Sie können die komprimierte Datei extrahieren und sie direkt vom Terminal aus ausführen. + +Dann erstellen Sie eine Datei `traefik.toml` mit: + +```TOML hl_lines="3" +[entryPoints] + [entryPoints.http] + address = ":9999" + +[providers] + [providers.file] + filename = "routes.toml" +``` + +Dadurch wird Traefik angewiesen, Port 9999 abzuhören und eine andere Datei `routes.toml` zu verwenden. + +/// tip | Tipp + +Wir verwenden Port 9999 anstelle des Standard-HTTP-Ports 80, damit Sie ihn nicht mit Administratorrechten (`sudo`) ausführen müssen. + +/// + +Erstellen Sie nun die andere Datei `routes.toml`: + +```TOML hl_lines="5 12 20" +[http] + [http.middlewares] + + [http.middlewares.api-stripprefix.stripPrefix] + prefixes = ["/api/v1"] + + [http.routers] + + [http.routers.app-http] + entryPoints = ["http"] + service = "app" + rule = "PathPrefix(`/api/v1`)" + middlewares = ["api-stripprefix"] + + [http.services] + + [http.services.app] + [http.services.app.loadBalancer] + [[http.services.app.loadBalancer.servers]] + url = "http://127.0.0.1:8000" +``` + +Diese Datei konfiguriert Traefik, das Pfadpräfix `/api/v1` zu verwenden. + +Und dann leitet Traefik seine Anfragen an Ihren Uvicorn weiter, der unter `http://127.0.0.1:8000` läuft. + +Starten Sie nun Traefik: + +
+ +```console +$ ./traefik --configFile=traefik.toml + +INFO[0000] Configuration loaded from file: /home/user/awesomeapi/traefik.toml +``` + +
+ +Und jetzt starten Sie Ihre Anwendung mit Uvicorn, indem Sie die Option `--root-path` verwenden: + +
+ +```console +$ uvicorn main:app --root-path /api/v1 + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +### Die Responses betrachten + +Wenn Sie nun zur URL mit dem Port für Uvicorn gehen: http://127.0.0.1:8000/app, sehen Sie die normale Response: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +/// tip | Tipp + +Beachten Sie, dass, obwohl Sie unter `http://127.0.0.1:8000/app` darauf zugreifen, als `root_path` angezeigt wird `/api/v1`, welches aus der Option `--root-path` stammt. + +/// + +Öffnen Sie nun die URL mit dem Port für Traefik, einschließlich des Pfadpräfixes: http://127.0.0.1:9999/api/v1/app. + +Wir bekommen die gleiche Response: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +Diesmal jedoch unter der URL mit dem vom Proxy bereitgestellten Präfixpfad: `/api/v1`. + +Die Idee hier ist natürlich, dass jeder über den Proxy auf die Anwendung zugreifen soll, daher ist die Version mit dem Pfadpräfix `/api/v1` die „korrekte“. + +Und die von Uvicorn direkt bereitgestellte Version ohne Pfadpräfix (`http://127.0.0.1:8000/app`) wäre ausschließlich für den Zugriff durch den _Proxy_ (Traefik) bestimmt. + +Dies demonstriert, wie der Proxy (Traefik) das Pfadpräfix verwendet und wie der Server (Uvicorn) den `root_path` aus der Option `--root-path` verwendet. + +### Es in der Dokumentationsoberfläche betrachten + +Jetzt folgt der spaßige Teil. ✨ + +Der „offizielle“ Weg, auf die Anwendung zuzugreifen, wäre über den Proxy mit dem von uns definierten Pfadpräfix. Wenn Sie also die von Uvicorn direkt bereitgestellte Dokumentationsoberfläche ohne das Pfadpräfix in der URL ausprobieren, wird es erwartungsgemäß nicht funktionieren, da erwartet wird, dass der Zugriff über den Proxy erfolgt. + +Sie können das unter http://127.0.0.1:8000/docs sehen: + + + +Wenn wir jedoch unter der „offiziellen“ URL, über den Proxy mit Port `9999`, unter `/api/v1/docs`, auf die Dokumentationsoberfläche zugreifen, funktioniert es ordnungsgemäß! 🎉 + +Sie können das unter http://127.0.0.1:9999/api/v1/docs testen: + + + +Genau so, wie wir es wollten. ✔️ + +Dies liegt daran, dass FastAPI diesen `root_path` verwendet, um den Default-`server` in OpenAPI mit der von `root_path` bereitgestellten URL zu erstellen. + +## Zusätzliche Server + +/// warning | Achtung + +Dies ist ein fortgeschrittener Anwendungsfall. Überspringen Sie das gerne. + +/// + +Standardmäßig erstellt **FastAPI** einen `server` im OpenAPI-Schema mit der URL für den `root_path`. + +Sie können aber auch andere alternative `server` bereitstellen, beispielsweise wenn Sie möchten, dass *dieselbe* Dokumentationsoberfläche mit einer Staging- und Produktionsumgebung interagiert. + +Wenn Sie eine benutzerdefinierte Liste von Servern (`servers`) übergeben und es einen `root_path` gibt (da Ihre API hinter einem Proxy läuft), fügt **FastAPI** einen „Server“ mit diesem `root_path` am Anfang der Liste ein. + +Zum Beispiel: + +{* ../../docs_src/behind_a_proxy/tutorial003.py hl[4:7] *} + +Erzeugt ein OpenAPI-Schema, wie: + +```JSON hl_lines="5-7" +{ + "openapi": "3.1.0", + // Hier mehr Einstellungen + "servers": [ + { + "url": "/api/v1" + }, + { + "url": "https://stag.example.com", + "description": "Staging environment" + }, + { + "url": "https://prod.example.com", + "description": "Production environment" + } + ], + "paths": { + // Hier mehr Einstellungen + } +} +``` + +/// tip | Tipp + +Beachten Sie den automatisch generierten Server mit dem `URL`-Wert `/api/v1`, welcher vom `root_path` stammt. + +/// + +In der Dokumentationsoberfläche unter http://127.0.0.1:9999/api/v1/docs würde es so aussehen: + + + +/// tip | Tipp + +Die Dokumentationsoberfläche interagiert mit dem von Ihnen ausgewählten Server. + +/// + +### Den automatischen Server von `root_path` deaktivieren + +Wenn Sie nicht möchten, dass **FastAPI** einen automatischen Server inkludiert, welcher `root_path` verwendet, können Sie den Parameter `root_path_in_servers=False` verwenden: + +{* ../../docs_src/behind_a_proxy/tutorial004.py hl[9] *} + +Dann wird er nicht in das OpenAPI-Schema aufgenommen. + +## Mounten einer Unteranwendung + +Wenn Sie gleichzeitig eine Unteranwendung mounten (wie beschrieben in [Unteranwendungen – Mounts](sub-applications.md){.internal-link target=_blank}) und einen Proxy mit `root_path` verwenden wollen, können Sie das normal tun, wie Sie es erwarten würden. + +FastAPI verwendet intern den `root_path` auf intelligente Weise, sodass es einfach funktioniert. ✨ diff --git a/docs/de/docs/advanced/custom-response.md b/docs/de/docs/advanced/custom-response.md new file mode 100644 index 000000000..43cb55e04 --- /dev/null +++ b/docs/de/docs/advanced/custom-response.md @@ -0,0 +1,303 @@ +# Benutzerdefinierte Response – HTML, Stream, Datei, andere + +Standardmäßig gibt **FastAPI** die Responses mittels `JSONResponse` zurück. + +Sie können das überschreiben, indem Sie direkt eine `Response` zurückgeben, wie in [Eine Response direkt zurückgeben](response-directly.md){.internal-link target=_blank} gezeigt. + +Wenn Sie jedoch direkt eine `Response` zurückgeben, werden die Daten nicht automatisch konvertiert und die Dokumentation wird nicht automatisch generiert (zum Beispiel wird der spezifische „Medientyp“, der im HTTP-Header `Content-Type` angegeben ist, nicht Teil der generierten OpenAPI). + +Sie können aber auch die `Response`, die Sie verwenden möchten, im *Pfadoperation-Dekorator* deklarieren. + +Der Inhalt, den Sie von Ihrer *Pfadoperation-Funktion* zurückgeben, wird in diese `Response` eingefügt. + +Und wenn diese `Response` einen JSON-Medientyp (`application/json`) hat, wie es bei `JSONResponse` und `UJSONResponse` der Fall ist, werden die von Ihnen zurückgegebenen Daten automatisch mit jedem Pydantic `response_model` konvertiert (und gefiltert), das Sie im *Pfadoperation-Dekorator* deklariert haben. + +/// note | Hinweis + +Wenn Sie eine Response-Klasse ohne Medientyp verwenden, erwartet FastAPI, dass Ihre Response keinen Inhalt hat, und dokumentiert daher das Format der Response nicht in deren generierter OpenAPI-Dokumentation. + +/// + +## `ORJSONResponse` verwenden + +Um beispielsweise noch etwas Leistung herauszuholen, können Sie `orjson` installieren und verwenden, und die Response als `ORJSONResponse` deklarieren. + +Importieren Sie die `Response`-Klasse (-Unterklasse), die Sie verwenden möchten, und deklarieren Sie sie im *Pfadoperation-Dekorator*. + +Bei umfangreichen Responses ist die direkte Rückgabe einer `Response` viel schneller als ein Dictionary zurückzugeben. + +Das liegt daran, dass FastAPI standardmäßig jedes enthaltene Element überprüft und sicherstellt, dass es als JSON serialisierbar ist, und zwar unter Verwendung desselben [JSON-kompatiblen Encoders](../tutorial/encoder.md){.internal-link target=_blank}, der im Tutorial erläutert wurde. Dadurch können Sie **beliebige Objekte** zurückgeben, zum Beispiel Datenbankmodelle. + +Wenn Sie jedoch sicher sind, dass der von Ihnen zurückgegebene Inhalt **mit JSON serialisierbar** ist, können Sie ihn direkt an die Response-Klasse übergeben und die zusätzliche Arbeit vermeiden, die FastAPI hätte, indem es Ihren zurückgegebenen Inhalt durch den `jsonable_encoder` leitet, bevor es ihn an die Response-Klasse übergibt. + +{* ../../docs_src/custom_response/tutorial001b.py hl[2,7] *} + +/// info + +Der Parameter `response_class` wird auch verwendet, um den „Medientyp“ der Response zu definieren. + +In diesem Fall wird der HTTP-Header `Content-Type` auf `application/json` gesetzt. + +Und er wird als solcher in OpenAPI dokumentiert. + +/// + +/// tip | Tipp + +Die `ORJSONResponse` ist derzeit nur in FastAPI verfügbar, nicht in Starlette. + +/// + +## HTML-Response + +Um eine Response mit HTML direkt von **FastAPI** zurückzugeben, verwenden Sie `HTMLResponse`. + +* Importieren Sie `HTMLResponse`. +* Übergeben Sie `HTMLResponse` als den Parameter `response_class` Ihres *Pfadoperation-Dekorators*. + +{* ../../docs_src/custom_response/tutorial002.py hl[2,7] *} + +/// info + +Der Parameter `response_class` wird auch verwendet, um den „Medientyp“ der Response zu definieren. + +In diesem Fall wird der HTTP-Header `Content-Type` auf `text/html` gesetzt. + +Und er wird als solcher in OpenAPI dokumentiert. + +/// + +### Eine `Response` zurückgeben + +Wie in [Eine Response direkt zurückgeben](response-directly.md){.internal-link target=_blank} gezeigt, können Sie die Response auch direkt in Ihrer *Pfadoperation* überschreiben, indem Sie diese zurückgeben. + +Das gleiche Beispiel von oben, das eine `HTMLResponse` zurückgibt, könnte so aussehen: + +{* ../../docs_src/custom_response/tutorial003.py hl[2,7,19] *} + +/// warning | Achtung + +Eine `Response`, die direkt von Ihrer *Pfadoperation-Funktion* zurückgegeben wird, wird in OpenAPI nicht dokumentiert (zum Beispiel wird der `Content-Type` nicht dokumentiert) und ist in der automatischen interaktiven Dokumentation nicht sichtbar. + +/// + +/// info + +Natürlich stammen der eigentliche `Content-Type`-Header, der Statuscode, usw., aus dem `Response`-Objekt, das Sie zurückgegeben haben. + +/// + +### In OpenAPI dokumentieren und `Response` überschreiben + +Wenn Sie die Response innerhalb der Funktion überschreiben und gleichzeitig den „Medientyp“ in OpenAPI dokumentieren möchten, können Sie den `response_class`-Parameter verwenden UND ein `Response`-Objekt zurückgeben. + +Die `response_class` wird dann nur zur Dokumentation der OpenAPI-Pfadoperation* verwendet, Ihre `Response` wird jedoch unverändert verwendet. + +#### Eine `HTMLResponse` direkt zurückgeben + +Es könnte zum Beispiel so etwas sein: + +{* ../../docs_src/custom_response/tutorial004.py hl[7,21,23] *} + +In diesem Beispiel generiert die Funktion `generate_html_response()` bereits eine `Response` und gibt sie zurück, anstatt das HTML in einem `str` zurückzugeben. + +Indem Sie das Ergebnis des Aufrufs von `generate_html_response()` zurückgeben, geben Sie bereits eine `Response` zurück, die das Standardverhalten von **FastAPI** überschreibt. + +Aber da Sie die `HTMLResponse` auch in der `response_class` übergeben haben, weiß **FastAPI**, dass sie in OpenAPI und der interaktiven Dokumentation als HTML mit `text/html` zu dokumentieren ist: + + + +## Verfügbare Responses + +Hier sind einige der verfügbaren Responses. + +Bedenken Sie, dass Sie `Response` verwenden können, um alles andere zurückzugeben, oder sogar eine benutzerdefinierte Unterklasse zu erstellen. + +/// note | Technische Details + +Sie können auch `from starlette.responses import HTMLResponse` verwenden. + +**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. + +/// + +### `Response` + +Die Hauptklasse `Response`, alle anderen Responses erben von ihr. + +Sie können sie direkt zurückgeben. + +Sie akzeptiert die folgenden Parameter: + +* `content` – Ein `str` oder `bytes`. +* `status_code` – Ein `int`-HTTP-Statuscode. +* `headers` – Ein `dict` von Strings. +* `media_type` – Ein `str`, der den Medientyp angibt. Z. B. `"text/html"`. + +FastAPI (eigentlich Starlette) fügt automatisch einen Content-Length-Header ein. Außerdem wird es einen Content-Type-Header einfügen, der auf dem media_type basiert, und für Texttypen einen Zeichensatz (charset) anfügen. + +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} + +### `HTMLResponse` + +Nimmt Text oder Bytes entgegen und gibt eine HTML-Response zurück, wie Sie oben gelesen haben. + +### `PlainTextResponse` + +Nimmt Text oder Bytes entgegen und gibt eine Plain-Text-Response zurück. + +{* ../../docs_src/custom_response/tutorial005.py hl[2,7,9] *} + +### `JSONResponse` + +Nimmt einige Daten entgegen und gibt eine `application/json`-codierte Response zurück. + +Dies ist die Standard-Response, die in **FastAPI** verwendet wird, wie Sie oben gelesen haben. + +### `ORJSONResponse` + +Eine schnelle alternative JSON-Response mit `orjson`, wie Sie oben gelesen haben. + +### `UJSONResponse` + +Eine alternative JSON-Response mit `ujson`. + +/// warning | Achtung + +`ujson` ist bei der Behandlung einiger Sonderfälle weniger sorgfältig als Pythons eingebaute Implementierung. + +/// + +{* ../../docs_src/custom_response/tutorial001.py hl[2,7] *} + +/// tip | Tipp + +Möglicherweise ist `ORJSONResponse` eine schnellere Alternative. + +/// + +### `RedirectResponse` + +Gibt eine HTTP-Weiterleitung (HTTP-Redirect) zurück. Verwendet standardmäßig den Statuscode 307 – Temporäre Weiterleitung (Temporary Redirect). + +Sie können eine `RedirectResponse` direkt zurückgeben: + +{* ../../docs_src/custom_response/tutorial006.py hl[2,9] *} + +--- + +Oder Sie können sie im Parameter `response_class` verwenden: + + +{* ../../docs_src/custom_response/tutorial006b.py hl[2,7,9] *} + +Wenn Sie das tun, können Sie die URL direkt von Ihrer *Pfadoperation*-Funktion zurückgeben. + +In diesem Fall ist der verwendete `status_code` der Standardcode für die `RedirectResponse`, also `307`. + +--- + +Sie können den Parameter `status_code` auch in Kombination mit dem Parameter `response_class` verwenden: + +{* ../../docs_src/custom_response/tutorial006c.py hl[2,7,9] *} + +### `StreamingResponse` + +Nimmt einen asynchronen Generator oder einen normalen Generator/Iterator und streamt den Responsebody. + +{* ../../docs_src/custom_response/tutorial007.py hl[2,14] *} + +#### Verwendung von `StreamingResponse` mit dateiähnlichen Objekten + +Wenn Sie ein dateiähnliches (file-like) Objekt haben (z. B. das von `open()` zurückgegebene Objekt), können Sie eine Generatorfunktion erstellen, um über dieses dateiähnliche Objekt zu iterieren. + +Auf diese Weise müssen Sie nicht alles zuerst in den Arbeitsspeicher lesen und können diese Generatorfunktion an `StreamingResponse` übergeben und zurückgeben. + +Das umfasst viele Bibliotheken zur Interaktion mit Cloud-Speicher, Videoverarbeitung und anderen. + +```{ .python .annotate hl_lines="2 10-12 14" } +{!../../docs_src/custom_response/tutorial008.py!} +``` + +1. Das ist die Generatorfunktion. Es handelt sich um eine „Generatorfunktion“, da sie `yield`-Anweisungen enthält. +2. Durch die Verwendung eines `with`-Blocks stellen wir sicher, dass das dateiähnliche Objekt geschlossen wird, nachdem die Generatorfunktion fertig ist. Also, nachdem sie mit dem Senden der Response fertig ist. +3. Dieses `yield from` weist die Funktion an, über das Ding namens `file_like` zu iterieren. Und dann für jeden iterierten Teil, diesen Teil so zurückzugeben, als wenn er aus dieser Generatorfunktion (`iterfile`) stammen würde. + + Es handelt sich also hier um eine Generatorfunktion, die die „generierende“ Arbeit intern auf etwas anderes überträgt. + + Auf diese Weise können wir das Ganze in einen `with`-Block einfügen und so sicherstellen, dass das dateiartige Objekt nach Abschluss geschlossen wird. + +/// tip | Tipp + +Beachten Sie, dass wir, da wir Standard-`open()` verwenden, welches `async` und `await` nicht unterstützt, hier die Pfadoperation mit normalen `def` deklarieren. + +/// + +### `FileResponse` + +Streamt eine Datei asynchron als Response. + +Nimmt zur Instanziierung einen anderen Satz von Argumenten entgegen als die anderen Response-Typen: + +* `path` – Der Dateipfad zur Datei, die gestreamt werden soll. +* `headers` – Alle benutzerdefinierten Header, die inkludiert werden sollen, als Dictionary. +* `media_type` – Ein String, der den Medientyp angibt. Wenn nicht gesetzt, wird der Dateiname oder Pfad verwendet, um auf einen Medientyp zu schließen. +* `filename` – Wenn gesetzt, wird das in der `Content-Disposition` der Response eingefügt. + +Datei-Responses enthalten die entsprechenden `Content-Length`-, `Last-Modified`- und `ETag`-Header. + +{* ../../docs_src/custom_response/tutorial009.py hl[2,10] *} + +Sie können auch den Parameter `response_class` verwenden: + +{* ../../docs_src/custom_response/tutorial009b.py hl[2,8,10] *} + +In diesem Fall können Sie den Dateipfad direkt von Ihrer *Pfadoperation*-Funktion zurückgeben. + +## Benutzerdefinierte Response-Klasse + +Sie können Ihre eigene benutzerdefinierte Response-Klasse erstellen, die von `Response` erbt und diese verwendet. + +Nehmen wir zum Beispiel an, dass Sie `orjson` verwenden möchten, aber mit einigen benutzerdefinierten Einstellungen, die in der enthaltenen `ORJSONResponse`-Klasse nicht verwendet werden. + +Sie möchten etwa, dass Ihre Response eingerücktes und formatiertes JSON zurückgibt. Dafür möchten Sie die orjson-Option `orjson.OPT_INDENT_2` verwenden. + +Sie könnten eine `CustomORJSONResponse` erstellen. Das Wichtigste, was Sie tun müssen, ist, eine `Response.render(content)`-Methode zu erstellen, die den Inhalt als `bytes` zurückgibt: + +{* ../../docs_src/custom_response/tutorial009c.py hl[9:14,17] *} + +Statt: + +```json +{"message": "Hello World"} +``` + +... wird die Response jetzt Folgendes zurückgeben: + +```json +{ + "message": "Hello World" +} +``` + +Natürlich werden Sie wahrscheinlich viel bessere Möglichkeiten finden, Vorteil daraus zu ziehen, als JSON zu formatieren. 😉 + +## Standard-Response-Klasse + +Beim Erstellen einer **FastAPI**-Klasseninstanz oder eines `APIRouter`s können Sie angeben, welche Response-Klasse standardmäßig verwendet werden soll. + +Der Parameter, der das definiert, ist `default_response_class`. + +Im folgenden Beispiel verwendet **FastAPI** standardmäßig `ORJSONResponse` in allen *Pfadoperationen*, anstelle von `JSONResponse`. + +{* ../../docs_src/custom_response/tutorial010.py hl[2,4] *} + +/// tip | Tipp + +Sie können dennoch weiterhin `response_class` in *Pfadoperationen* überschreiben, wie bisher. + +/// + +## Zusätzliche Dokumentation + +Sie können auch den Medientyp und viele andere Details in OpenAPI mit `responses` deklarieren: [Zusätzliche Responses in OpenAPI](additional-responses.md){.internal-link target=_blank}. diff --git a/docs/de/docs/advanced/dataclasses.md b/docs/de/docs/advanced/dataclasses.md new file mode 100644 index 000000000..8e537c639 --- /dev/null +++ b/docs/de/docs/advanced/dataclasses.md @@ -0,0 +1,95 @@ +# Verwendung von Datenklassen + +FastAPI basiert auf **Pydantic** und ich habe Ihnen gezeigt, wie Sie Pydantic-Modelle verwenden können, um Requests und Responses zu deklarieren. + +Aber FastAPI unterstützt auf die gleiche Weise auch die Verwendung von `dataclasses`: + +{* ../../docs_src/dataclasses/tutorial001.py hl[1,7:12,19:20] *} + +Das ist dank **Pydantic** ebenfalls möglich, da es `dataclasses` intern unterstützt. + +Auch wenn im obige Code Pydantic nicht explizit vorkommt, verwendet FastAPI Pydantic, um diese Standard-Datenklassen in Pydantics eigene Variante von Datenklassen zu konvertieren. + +Und natürlich wird das gleiche unterstützt: + +* Validierung der Daten +* Serialisierung der Daten +* Dokumentation der Daten, usw. + +Das funktioniert genauso wie mit Pydantic-Modellen. Und tatsächlich wird es unter der Haube mittels Pydantic auf die gleiche Weise bewerkstelligt. + +/// info + +Bedenken Sie, dass Datenklassen nicht alles können, was Pydantic-Modelle können. + +Daher müssen Sie möglicherweise weiterhin Pydantic-Modelle verwenden. + +Wenn Sie jedoch eine Menge Datenklassen herumliegen haben, ist dies ein guter Trick, um sie für eine Web-API mithilfe von FastAPI zu verwenden. 🤓 + +/// + +## Datenklassen als `response_model` + +Sie können `dataclasses` auch im Parameter `response_model` verwenden: + +{* ../../docs_src/dataclasses/tutorial002.py hl[1,7:13,19] *} + +Die Datenklasse wird automatisch in eine Pydantic-Datenklasse konvertiert. + +Auf diese Weise wird deren Schema in der Benutzeroberfläche der API-Dokumentation angezeigt: + + + +## Datenklassen in verschachtelten Datenstrukturen + +Sie können `dataclasses` auch mit anderen Typannotationen kombinieren, um verschachtelte Datenstrukturen zu erstellen. + +In einigen Fällen müssen Sie möglicherweise immer noch Pydantics Version von `dataclasses` verwenden. Zum Beispiel, wenn Sie Fehler in der automatisch generierten API-Dokumentation haben. + +In diesem Fall können Sie einfach die Standard-`dataclasses` durch `pydantic.dataclasses` ersetzen, was einen direkten Ersatz darstellt: + +{* ../../docs_src/dataclasses/tutorial003.py hl[1,5,8:11,14:17,23:25,28] *} + +1. Wir importieren `field` weiterhin von Standard-`dataclasses`. + +2. `pydantic.dataclasses` ist ein direkter Ersatz für `dataclasses`. + +3. Die Datenklasse `Author` enthält eine Liste von `Item`-Datenklassen. + +4. Die Datenklasse `Author` wird im `response_model`-Parameter verwendet. + +5. Sie können andere Standard-Typannotationen mit Datenklassen als Requestbody verwenden. + + In diesem Fall handelt es sich um eine Liste von `Item`-Datenklassen. + +6. Hier geben wir ein Dictionary zurück, das `items` enthält, welches eine Liste von Datenklassen ist. + + FastAPI ist weiterhin in der Lage, die Daten nach JSON zu serialisieren. + +7. Hier verwendet das `response_model` als Typannotation eine Liste von `Author`-Datenklassen. + + Auch hier können Sie `dataclasses` mit Standard-Typannotationen kombinieren. + +8. Beachten Sie, dass diese *Pfadoperation-Funktion* reguläres `def` anstelle von `async def` verwendet. + + Wie immer können Sie in FastAPI `def` und `async def` beliebig kombinieren. + + Wenn Sie eine Auffrischung darüber benötigen, wann welche Anwendung sinnvoll ist, lesen Sie den Abschnitt „In Eile?“ in der Dokumentation zu [`async` und `await`](../async.md#in-eile){.internal-link target=_blank}. + +9. Diese *Pfadoperation-Funktion* gibt keine Datenklassen zurück (obwohl dies möglich wäre), sondern eine Liste von Dictionarys mit internen Daten. + + FastAPI verwendet den Parameter `response_model` (der Datenklassen enthält), um die Response zu konvertieren. + +Sie können `dataclasses` mit anderen Typannotationen auf vielfältige Weise kombinieren, um komplexe Datenstrukturen zu bilden. + +Weitere Einzelheiten finden Sie in den Bemerkungen im Quellcode oben. + +## Mehr erfahren + +Sie können `dataclasses` auch mit anderen Pydantic-Modellen kombinieren, von ihnen erben, sie in Ihre eigenen Modelle einbinden, usw. + +Weitere Informationen finden Sie in der Pydantic-Dokumentation zu Datenklassen. + +## Version + +Dies ist verfügbar seit FastAPI-Version `0.67.0`. 🔖 diff --git a/docs/de/docs/advanced/events.md b/docs/de/docs/advanced/events.md new file mode 100644 index 000000000..65fc9e484 --- /dev/null +++ b/docs/de/docs/advanced/events.md @@ -0,0 +1,165 @@ +# Lifespan-Events + +Sie können Logik (Code) definieren, die ausgeführt werden soll, bevor die Anwendung **hochfährt**. Dies bedeutet, dass dieser Code **einmal** ausgeführt wird, **bevor** die Anwendung **beginnt, Requests entgegenzunehmen**. + +Auf die gleiche Weise können Sie Logik (Code) definieren, die ausgeführt werden soll, wenn die Anwendung **heruntergefahren** wird. In diesem Fall wird dieser Code **einmal** ausgeführt, **nachdem** möglicherweise **viele Requests** bearbeitet wurden. + +Da dieser Code ausgeführt wird, bevor die Anwendung **beginnt**, Requests entgegenzunehmen, und unmittelbar, nachdem sie die Bearbeitung von Requests **abgeschlossen hat**, deckt er die gesamte **Lebensdauer – „Lifespan“** – der Anwendung ab (das Wort „Lifespan“ wird gleich wichtig sein 😉). + +Dies kann sehr nützlich sein, um **Ressourcen** einzurichten, die Sie in der gesamten Anwendung verwenden wollen und die von Requests **gemeinsam genutzt** werden und/oder die Sie anschließend **aufräumen** müssen. Zum Beispiel ein Pool von Datenbankverbindungen oder das Laden eines gemeinsam genutzten Modells für maschinelles Lernen. + +## Anwendungsfall + +Beginnen wir mit einem Beispiel-**Anwendungsfall** und schauen uns dann an, wie wir ihn mit dieser Methode implementieren können. + +Stellen wir uns vor, Sie verfügen über einige **Modelle für maschinelles Lernen**, die Sie zur Bearbeitung von Requests verwenden möchten. 🤖 + +Die gleichen Modelle werden von den Requests gemeinsam genutzt, es handelt sich also nicht um ein Modell pro Request, pro Benutzer, oder ähnliches. + +Stellen wir uns vor, dass das Laden des Modells **eine ganze Weile dauern** kann, da viele **Daten von der Festplatte** gelesen werden müssen. Sie möchten das also nicht für jeden Request tun. + +Sie könnten das auf der obersten Ebene des Moduls/der Datei machen, aber das würde auch bedeuten, dass **das Modell geladen wird**, selbst wenn Sie nur einen einfachen automatisierten Test ausführen, dann wäre dieser Test **langsam**, weil er warten müsste, bis das Modell geladen ist, bevor er einen davon unabhängigen Teil des Codes ausführen könnte. + +Das wollen wir besser machen: Laden wir das Modell, bevor die Requests bearbeitet werden, aber unmittelbar bevor die Anwendung beginnt, Requests zu empfangen, und nicht, während der Code geladen wird. + +## Lifespan + +Sie können diese Logik beim *Hochfahren* und *Herunterfahren* mithilfe des `lifespan`-Parameters der `FastAPI`-App und eines „Kontextmanagers“ definieren (ich zeige Ihnen gleich, was das ist). + +Beginnen wir mit einem Beispiel und sehen es uns dann im Detail an. + +Wir erstellen eine asynchrone Funktion `lifespan()` mit `yield` wie folgt: + +{* ../../docs_src/events/tutorial003.py hl[16,19] *} + +Hier simulieren wir das langsame *Hochfahren*, das Laden des Modells, indem wir die (Fake-)Modellfunktion vor dem `yield` in das Dictionary mit Modellen für maschinelles Lernen einfügen. Dieser Code wird ausgeführt, **bevor** die Anwendung **beginnt, Requests entgegenzunehmen**, während des *Hochfahrens*. + +Und dann, direkt nach dem `yield`, entladen wir das Modell. Dieser Code wird unmittelbar vor dem *Herunterfahren* ausgeführt, **nachdem** die Anwendung **die Bearbeitung von Requests abgeschlossen hat**. Dadurch könnten beispielsweise Ressourcen wie Arbeitsspeicher oder eine GPU freigegeben werden. + +/// tip | Tipp + +Das *Herunterfahren* würde erfolgen, wenn Sie die Anwendung **stoppen**. + +Möglicherweise müssen Sie eine neue Version starten, oder Sie haben es einfach satt, sie auszuführen. 🤷 + +/// + +### Lifespan-Funktion + +Das Erste, was auffällt, ist, dass wir eine asynchrone Funktion mit `yield` definieren. Das ist sehr ähnlich zu Abhängigkeiten mit `yield`. + +{* ../../docs_src/events/tutorial003.py hl[14:19] *} + +Der erste Teil der Funktion, vor dem `yield`, wird ausgeführt **bevor** die Anwendung startet. + +Und der Teil nach `yield` wird ausgeführt, **nachdem** die Anwendung beendet ist. + +### Asynchroner Kontextmanager + +Wie Sie sehen, ist die Funktion mit einem `@asynccontextmanager` versehen. + +Dadurch wird die Funktion in einen sogenannten „**asynchronen Kontextmanager**“ umgewandelt. + +{* ../../docs_src/events/tutorial003.py hl[1,13] *} + +Ein **Kontextmanager** in Python ist etwas, das Sie in einer `with`-Anweisung verwenden können, zum Beispiel kann `open()` als Kontextmanager verwendet werden: + +```Python +with open("file.txt") as file: + file.read() +``` + +In neueren Versionen von Python gibt es auch einen **asynchronen Kontextmanager**. Sie würden ihn mit `async with` verwenden: + +```Python +async with lifespan(app): + await do_stuff() +``` + +Wenn Sie wie oben einen Kontextmanager oder einen asynchronen Kontextmanager erstellen, führt dieser vor dem Betreten des `with`-Blocks den Code vor dem `yield` aus, und nach dem Verlassen des `with`-Blocks wird er den Code nach dem `yield` ausführen. + +In unserem obigen Codebeispiel verwenden wir ihn nicht direkt, sondern übergeben ihn an FastAPI, damit es ihn verwenden kann. + +Der Parameter `lifespan` der `FastAPI`-App benötigt einen **asynchronen Kontextmanager**, wir können ihm also unseren neuen asynchronen Kontextmanager `lifespan` übergeben. + +{* ../../docs_src/events/tutorial003.py hl[22] *} + +## Alternative Events (deprecated) + +/// warning | Achtung + +Der empfohlene Weg, das *Hochfahren* und *Herunterfahren* zu handhaben, ist die Verwendung des `lifespan`-Parameters der `FastAPI`-App, wie oben beschrieben. Wenn Sie einen `lifespan`-Parameter übergeben, werden die `startup`- und `shutdown`-Eventhandler nicht mehr aufgerufen. Es ist entweder alles `lifespan` oder alles Events, nicht beides. + +Sie können diesen Teil wahrscheinlich überspringen. + +/// + +Es gibt eine alternative Möglichkeit, diese Logik zu definieren, sodass sie beim *Hochfahren* und beim *Herunterfahren* ausgeführt wird. + +Sie können Eventhandler (Funktionen) definieren, die ausgeführt werden sollen, bevor die Anwendung hochgefahren wird oder wenn die Anwendung heruntergefahren wird. + +Diese Funktionen können mit `async def` oder normalem `def` deklariert werden. + +### `startup`-Event + +Um eine Funktion hinzuzufügen, die vor dem Start der Anwendung ausgeführt werden soll, deklarieren Sie diese mit dem Event `startup`: + +{* ../../docs_src/events/tutorial001.py hl[8] *} + +In diesem Fall initialisiert die Eventhandler-Funktion `startup` die „Datenbank“ der Items (nur ein `dict`) mit einigen Werten. + +Sie können mehr als eine Eventhandler-Funktion hinzufügen. + +Und Ihre Anwendung empfängt erst dann Anfragen, wenn alle `startup`-Eventhandler abgeschlossen sind. + +### `shutdown`-Event + +Um eine Funktion hinzuzufügen, die beim Herunterfahren der Anwendung ausgeführt werden soll, deklarieren Sie sie mit dem Event `shutdown`: + +{* ../../docs_src/events/tutorial002.py hl[6] *} + +Hier schreibt die `shutdown`-Eventhandler-Funktion eine Textzeile `"Application shutdown"` in eine Datei `log.txt`. + +/// info + +In der Funktion `open()` bedeutet `mode="a"` „append“ („anhängen“), sodass die Zeile nach dem, was sich in dieser Datei befindet, hinzugefügt wird, ohne den vorherigen Inhalt zu überschreiben. + +/// + +/// tip | Tipp + +Beachten Sie, dass wir in diesem Fall eine Standard-Python-Funktion `open()` verwenden, die mit einer Datei interagiert. + +Es handelt sich also um I/O (Input/Output), welches „Warten“ erfordert, bis Dinge auf die Festplatte geschrieben werden. + +Aber `open()` verwendet nicht `async` und `await`. + +Daher deklarieren wir die Eventhandler-Funktion mit Standard-`def` statt mit `async def`. + +/// + +### `startup` und `shutdown` zusammen + +Es besteht eine hohe Wahrscheinlichkeit, dass die Logik für Ihr *Hochfahren* und *Herunterfahren* miteinander verknüpft ist. Vielleicht möchten Sie etwas beginnen und es dann beenden, eine Ressource laden und sie dann freigeben usw. + +Bei getrennten Funktionen, die keine gemeinsame Logik oder Variablen haben, ist dies schwieriger, da Sie Werte in globalen Variablen speichern oder ähnliche Tricks verwenden müssen. + +Aus diesem Grund wird jetzt empfohlen, stattdessen `lifespan` wie oben erläutert zu verwenden. + +## Technische Details + +Nur ein technisches Detail für die neugierigen Nerds. 🤓 + +In der technischen ASGI-Spezifikation ist dies Teil des Lifespan Protokolls und definiert Events namens `startup` und `shutdown`. + +/// info + +Weitere Informationen zu Starlettes `lifespan`-Handlern finden Sie in Starlettes Lifespan-Dokumentation. + +Einschließlich, wie man Lifespan-Zustand handhabt, der in anderen Bereichen Ihres Codes verwendet werden kann. + +/// + +## Unteranwendungen + +🚨 Beachten Sie, dass diese Lifespan-Events (Hochfahren und Herunterfahren) nur für die Hauptanwendung ausgeführt werden, nicht für [Unteranwendungen – Mounts](sub-applications.md){.internal-link target=_blank}. diff --git a/docs/de/docs/advanced/generate-clients.md b/docs/de/docs/advanced/generate-clients.md new file mode 100644 index 000000000..38a69031c --- /dev/null +++ b/docs/de/docs/advanced/generate-clients.md @@ -0,0 +1,257 @@ +# Clients generieren + +Da **FastAPI** auf der OpenAPI-Spezifikation basiert, erhalten Sie automatische Kompatibilität mit vielen Tools, einschließlich der automatischen API-Dokumentation (bereitgestellt von Swagger UI). + +Ein besonderer Vorteil, der nicht unbedingt offensichtlich ist, besteht darin, dass Sie für Ihre API **Clients generieren** können (manchmal auch **SDKs** genannt), für viele verschiedene **Programmiersprachen**. + +## OpenAPI-Client-Generatoren + +Es gibt viele Tools zum Generieren von Clients aus **OpenAPI**. + +Ein gängiges Tool ist OpenAPI Generator. + +Wenn Sie ein **Frontend** erstellen, ist openapi-ts eine sehr interessante Alternative. + +## Client- und SDK-Generatoren – Sponsor + +Es gibt auch einige **vom Unternehmen entwickelte** Client- und SDK-Generatoren, die auf OpenAPI (FastAPI) basieren. In einigen Fällen können diese Ihnen **weitere Funktionalität** zusätzlich zu qualitativ hochwertigen generierten SDKs/Clients bieten. + +Einige von diesen ✨ [**sponsern FastAPI**](../help-fastapi.md#den-autor-sponsern){.internal-link target=_blank} ✨, das gewährleistet die kontinuierliche und gesunde **Entwicklung** von FastAPI und seinem **Ökosystem**. + +Und es zeigt deren wahres Engagement für FastAPI und seine **Community** (Sie), da diese Ihnen nicht nur einen **guten Service** bieten möchten, sondern auch sicherstellen möchten, dass Sie über ein **gutes und gesundes Framework** verfügen, FastAPI. 🙇 + +Beispielsweise könnten Sie Speakeasy ausprobieren. + +Es gibt auch mehrere andere Unternehmen, welche ähnliche Dienste anbieten und die Sie online suchen und finden können. 🤓 + +## Einen TypeScript-Frontend-Client generieren + +Beginnen wir mit einer einfachen FastAPI-Anwendung: + +{* ../../docs_src/generate_clients/tutorial001_py39.py hl[7:9,12:13,16:17,21] *} + +Beachten Sie, dass die *Pfadoperationen* die Modelle definieren, welche diese für die Request- und Response-Payload verwenden, indem sie die Modelle `Item` und `ResponseMessage` verwenden. + +### API-Dokumentation + +Wenn Sie zur API-Dokumentation gehen, werden Sie sehen, dass diese die **Schemas** für die Daten enthält, welche in Requests gesendet und in Responses empfangen werden: + + + +Sie können diese Schemas sehen, da sie mit den Modellen in der Anwendung deklariert wurden. + +Diese Informationen sind im **OpenAPI-Schema** der Anwendung verfügbar und werden dann in der API-Dokumentation angezeigt (von Swagger UI). + +Und dieselben Informationen aus den Modellen, die in OpenAPI enthalten sind, können zum **Generieren des Client-Codes** verwendet werden. + +### Einen TypeScript-Client generieren + +Nachdem wir nun die Anwendung mit den Modellen haben, können wir den Client-Code für das Frontend generieren. + +#### `openapi-ts` installieren + +Sie können `openapi-ts` in Ihrem Frontend-Code installieren mit: + +
+ +```console +$ npm install @hey-api/openapi-ts --save-dev + +---> 100% +``` + +
+ +#### Client-Code generieren + +Um den Client-Code zu generieren, können Sie das Kommandozeilentool `openapi-ts` verwenden, das soeben installiert wurde. + +Da es im lokalen Projekt installiert ist, könnten Sie diesen Befehl wahrscheinlich nicht direkt aufrufen, sondern würden ihn in Ihre Datei `package.json` einfügen. + +Diese könnte so aussehen: + +```JSON hl_lines="7" +{ + "name": "frontend-app", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "generate-client": "openapi-ts --input http://localhost:8000/openapi.json --output ./src/client --client axios" + }, + "author": "", + "license": "", + "devDependencies": { + "@hey-api/openapi-ts": "^0.27.38", + "typescript": "^4.6.2" + } +} +``` + +Nachdem Sie das NPM-Skript `generate-client` dort stehen haben, können Sie es ausführen mit: + +
+ +```console +$ npm run generate-client + +frontend-app@1.0.0 generate-client /home/user/code/frontend-app +> openapi-ts --input http://localhost:8000/openapi.json --output ./src/client --client axios +``` + +
+ +Dieser Befehl generiert Code in `./src/client` und verwendet intern `axios` (die Frontend-HTTP-Bibliothek). + +### Den Client-Code ausprobieren + +Jetzt können Sie den Client-Code importieren und verwenden. Er könnte wie folgt aussehen, beachten Sie, dass Sie automatische Codevervollständigung für die Methoden erhalten: + + + +Sie erhalten außerdem automatische Vervollständigung für die zu sendende Payload: + + + +/// tip | Tipp + +Beachten Sie die automatische Vervollständigung für `name` und `price`, welche in der FastAPI-Anwendung im `Item`-Modell definiert wurden. + +/// + +Sie erhalten Inline-Fehlerberichte für die von Ihnen gesendeten Daten: + + + +Das Response-Objekt hat auch automatische Vervollständigung: + + + +## FastAPI-Anwendung mit Tags + +In vielen Fällen wird Ihre FastAPI-Anwendung größer sein und Sie werden wahrscheinlich Tags verwenden, um verschiedene Gruppen von *Pfadoperationen* zu separieren. + +Beispielsweise könnten Sie einen Abschnitt für **Items (Artikel)** und einen weiteren Abschnitt für **Users (Benutzer)** haben, und diese könnten durch Tags getrennt sein: + +{* ../../docs_src/generate_clients/tutorial002_py39.py hl[21,26,34] *} + +### Einen TypeScript-Client mit Tags generieren + +Wenn Sie unter Verwendung von Tags einen Client für eine FastAPI-Anwendung generieren, wird normalerweise auch der Client-Code anhand der Tags getrennt. + +Auf diese Weise können Sie die Dinge für den Client-Code richtig ordnen und gruppieren: + + + +In diesem Fall haben Sie: + +* `ItemsService` +* `UsersService` + +### Client-Methodennamen + +Im Moment sehen die generierten Methodennamen wie `createItemItemsPost` nicht sehr sauber aus: + +```TypeScript +ItemsService.createItemItemsPost({name: "Plumbus", price: 5}) +``` + +... das liegt daran, dass der Client-Generator für jede *Pfadoperation* die OpenAPI-interne **Operation-ID** verwendet. + +OpenAPI erfordert, dass jede Operation-ID innerhalb aller *Pfadoperationen* eindeutig ist. Daher verwendet FastAPI den **Funktionsnamen**, den **Pfad** und die **HTTP-Methode/-Operation**, um diese Operation-ID zu generieren. Denn so kann sichergestellt werden, dass die Operation-IDs eindeutig sind. + +Aber ich zeige Ihnen als nächstes, wie Sie das verbessern können. 🤓 + +## Benutzerdefinierte Operation-IDs und bessere Methodennamen + +Sie können die Art und Weise, wie diese Operation-IDs **generiert** werden, **ändern**, um sie einfacher zu machen und **einfachere Methodennamen** in den Clients zu haben. + +In diesem Fall müssen Sie auf andere Weise sicherstellen, dass jede Operation-ID **eindeutig** ist. + +Sie könnten beispielsweise sicherstellen, dass jede *Pfadoperation* einen Tag hat, und dann die Operation-ID basierend auf dem **Tag** und dem **Namen** der *Pfadoperation* (dem Funktionsnamen) generieren. + +### Funktion zum Generieren einer eindeutigen ID erstellen + +FastAPI verwendet eine **eindeutige ID** für jede *Pfadoperation*, diese wird für die **Operation-ID** und auch für die Namen aller benötigten benutzerdefinierten Modelle für Requests oder Responses verwendet. + +Sie können diese Funktion anpassen. Sie nimmt eine `APIRoute` und gibt einen String zurück. + +Hier verwendet sie beispielsweise den ersten Tag (Sie werden wahrscheinlich nur einen Tag haben) und den Namen der *Pfadoperation* (den Funktionsnamen). + +Anschließend können Sie diese benutzerdefinierte Funktion als Parameter `generate_unique_id_function` an **FastAPI** übergeben: + +{* ../../docs_src/generate_clients/tutorial003_py39.py hl[6:7,10] *} + +### Einen TypeScript-Client mit benutzerdefinierten Operation-IDs generieren + +Wenn Sie nun den Client erneut generieren, werden Sie feststellen, dass er über die verbesserten Methodennamen verfügt: + + + +Wie Sie sehen, haben die Methodennamen jetzt den Tag und dann den Funktionsnamen, aber keine Informationen aus dem URL-Pfad und der HTTP-Operation. + +### Vorab-Modifikation der OpenAPI-Spezifikation für den Client-Generator + +Der generierte Code enthält immer noch etwas **verdoppelte Information**. + +Wir wissen bereits, dass diese Methode mit den **Items** zusammenhängt, da sich dieses Wort in `ItemsService` befindet (vom Tag übernommen), aber wir haben auch immer noch den Tagnamen im Methodennamen vorangestellt. 😕 + +Wir werden das wahrscheinlich weiterhin für OpenAPI im Allgemeinen beibehalten wollen, da dadurch sichergestellt wird, dass die Operation-IDs **eindeutig** sind. + +Aber für den generierten Client könnten wir die OpenAPI-Operation-IDs direkt vor der Generierung der Clients **modifizieren**, um diese Methodennamen schöner und **sauberer** zu machen. + +Wir könnten das OpenAPI-JSON in eine Datei `openapi.json` herunterladen und dann mit einem Skript wie dem folgenden **den vorangestellten Tag entfernen**: + +{* ../../docs_src/generate_clients/tutorial004.py *} + +//// tab | Node.js + +```Javascript +{!> ../../docs_src/generate_clients/tutorial004.js!} +``` + +//// + +Damit würden die Operation-IDs von Dingen wie `items-get_items` in `get_items` umbenannt, sodass der Client-Generator einfachere Methodennamen generieren kann. + +### Einen TypeScript-Client mit der modifizierten OpenAPI generieren + +Da das Endergebnis nun in einer Datei `openapi.json` vorliegt, würden Sie die `package.json` ändern, um diese lokale Datei zu verwenden, zum Beispiel: + +```JSON hl_lines="7" +{ + "name": "frontend-app", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "generate-client": "openapi-ts --input ./openapi.json --output ./src/client --client axios" + }, + "author": "", + "license": "", + "devDependencies": { + "@hey-api/openapi-ts": "^0.27.38", + "typescript": "^4.6.2" + } +} +``` + +Nach der Generierung des neuen Clients hätten Sie nun **saubere Methodennamen** mit allen **Autovervollständigungen**, **Inline-Fehlerberichten**, usw.: + + + +## Vorteile + +Wenn Sie die automatisch generierten Clients verwenden, erhalten Sie **automatische Codevervollständigung** für: + +* Methoden. +* Request-Payloads im Body, Query-Parameter, usw. +* Response-Payloads. + +Außerdem erhalten Sie für alles **Inline-Fehlerberichte**. + +Und wann immer Sie den Backend-Code aktualisieren und das Frontend **neu generieren**, stehen alle neuen *Pfadoperationen* als Methoden zur Verfügung, die alten werden entfernt und alle anderen Änderungen werden im generierten Code reflektiert. 🤓 + +Das bedeutet auch, dass, wenn sich etwas ändert, dies automatisch im Client-Code **reflektiert** wird. Und wenn Sie den Client **erstellen**, kommt es zu einer Fehlermeldung, wenn die verwendeten Daten **nicht übereinstimmen**. + +Sie würden also sehr früh im Entwicklungszyklus **viele Fehler erkennen**, anstatt darauf warten zu müssen, dass die Fehler Ihren Endbenutzern in der Produktion angezeigt werden, und dann zu versuchen, zu debuggen, wo das Problem liegt. ✨ diff --git a/docs/de/docs/advanced/index.md b/docs/de/docs/advanced/index.md new file mode 100644 index 000000000..d93cd5fe8 --- /dev/null +++ b/docs/de/docs/advanced/index.md @@ -0,0 +1,36 @@ +# Handbuch für fortgeschrittene Benutzer + +## Zusatzfunktionen + +Das Haupt-[Tutorial – Benutzerhandbuch](../tutorial/index.md){.internal-link target=_blank} sollte ausreichen, um Ihnen einen Überblick über alle Hauptfunktionen von **FastAPI** zu geben. + +In den nächsten Abschnitten sehen Sie weitere Optionen, Konfigurationen und zusätzliche Funktionen. + +/// tip | Tipp + +Die nächsten Abschnitte sind **nicht unbedingt „fortgeschritten“**. + +Und es ist möglich, dass für Ihren Anwendungsfall die Lösung in einem davon liegt. + +/// + +## Lesen Sie zuerst das Tutorial + +Sie können immer noch die meisten Funktionen in **FastAPI** mit den Kenntnissen aus dem Haupt-[Tutorial – Benutzerhandbuch](../tutorial/index.md){.internal-link target=_blank} nutzen. + +Und in den nächsten Abschnitten wird davon ausgegangen, dass Sie es bereits gelesen haben und dass Sie diese Haupt-Ideen kennen. + +## Externe Kurse + +Obwohl das [Tutorial – Benutzerhandbuch](../tutorial/index.md){.internal-link target=_blank} und dieses **Handbuch für fortgeschrittene Benutzer** als geführtes Tutorial (wie ein Buch) geschrieben sind und für Sie ausreichen sollten, um **FastAPI zu lernen**, möchten Sie sie vielleicht durch zusätzliche Kurse ergänzen. + +Oder Sie belegen einfach lieber andere Kurse, weil diese besser zu Ihrem Lernstil passen. + +Einige Kursanbieter ✨ [**sponsern FastAPI**](../help-fastapi.md#den-autor-sponsern){.internal-link target=_blank} ✨, dies gewährleistet die kontinuierliche und gesunde **Entwicklung** von FastAPI und seinem **Ökosystem**. + +Und es zeigt deren wahres Engagement für FastAPI und seine **Gemeinschaft** (Sie), da diese Ihnen nicht nur eine **gute Lernerfahrung** bieten möchten, sondern auch sicherstellen möchten, dass Sie über ein **gutes und gesundes Framework verfügen **, FastAPI. 🙇 + +Vielleicht möchten Sie ihre Kurse ausprobieren: + +* Talk Python Training +* Test-Driven Development diff --git a/docs/de/docs/advanced/middleware.md b/docs/de/docs/advanced/middleware.md new file mode 100644 index 000000000..17b339788 --- /dev/null +++ b/docs/de/docs/advanced/middleware.md @@ -0,0 +1,95 @@ +# Fortgeschrittene Middleware + +Im Haupttutorial haben Sie gelesen, wie Sie Ihrer Anwendung [benutzerdefinierte Middleware](../tutorial/middleware.md){.internal-link target=_blank} hinzufügen können. + +Und dann auch, wie man [CORS mittels der `CORSMiddleware`](../tutorial/cors.md){.internal-link target=_blank} handhabt. + +In diesem Abschnitt werden wir sehen, wie man andere Middlewares verwendet. + +## ASGI-Middleware hinzufügen + +Da **FastAPI** auf Starlette basiert und die ASGI-Spezifikation implementiert, können Sie jede ASGI-Middleware verwenden. + +Eine Middleware muss nicht speziell für FastAPI oder Starlette gemacht sein, um zu funktionieren, solange sie der ASGI-Spezifikation genügt. + +Im Allgemeinen handelt es sich bei ASGI-Middleware um Klassen, die als erstes Argument eine ASGI-Anwendung erwarten. + +In der Dokumentation für ASGI-Middlewares von Drittanbietern wird Ihnen wahrscheinlich gesagt, etwa Folgendes zu tun: + +```Python +from unicorn import UnicornMiddleware + +app = SomeASGIApp() + +new_app = UnicornMiddleware(app, some_config="rainbow") +``` + +Aber FastAPI (eigentlich Starlette) bietet eine einfachere Möglichkeit, welche sicherstellt, dass die internen Middlewares zur Behandlung von Serverfehlern und benutzerdefinierten Exceptionhandlern ordnungsgemäß funktionieren. + +Dazu verwenden Sie `app.add_middleware()` (wie schon im Beispiel für CORS gesehen). + +```Python +from fastapi import FastAPI +from unicorn import UnicornMiddleware + +app = FastAPI() + +app.add_middleware(UnicornMiddleware, some_config="rainbow") +``` + +`app.add_middleware()` empfängt eine Middleware-Klasse als erstes Argument und dann alle weiteren Argumente, die an die Middleware übergeben werden sollen. + +## Integrierte Middleware + +**FastAPI** enthält mehrere Middlewares für gängige Anwendungsfälle. Wir werden als Nächstes sehen, wie man sie verwendet. + +/// note | Technische Details + +Für die nächsten Beispiele könnten Sie auch `from starlette.middleware.something import SomethingMiddleware` verwenden. + +**FastAPI** bietet mehrere Middlewares via `fastapi.middleware` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Middlewares kommen aber direkt von Starlette. + +/// + +## `HTTPSRedirectMiddleware` + +Erzwingt, dass alle eingehenden Requests entweder `https` oder `wss` sein müssen. + +Alle eingehenden Requests an `http` oder `ws` werden stattdessen an das sichere Schema umgeleitet. + +{* ../../docs_src/advanced_middleware/tutorial001.py hl[2,6] *} + +## `TrustedHostMiddleware` + +Erzwingt, dass alle eingehenden Requests einen korrekt gesetzten `Host`-Header haben, um sich vor HTTP-Host-Header-Angriffen zu schützen. + +{* ../../docs_src/advanced_middleware/tutorial002.py hl[2,6:8] *} + +Die folgenden Argumente werden unterstützt: + +* `allowed_hosts` – Eine Liste von Domain-Namen, die als Hostnamen zulässig sein sollten. Wildcard-Domains wie `*.example.com` werden unterstützt, um Subdomains zu matchen. Um jeden Hostnamen zu erlauben, verwenden Sie entweder `allowed_hosts=["*"]` oder lassen Sie diese Middleware weg. + +Wenn ein eingehender Request nicht korrekt validiert wird, wird eine „400“-Response gesendet. + +## `GZipMiddleware` + +Verarbeitet GZip-Responses für alle Requests, die `"gzip"` im `Accept-Encoding`-Header enthalten. + +Diese Middleware verarbeitet sowohl Standard- als auch Streaming-Responses. + +{* ../../docs_src/advanced_middleware/tutorial003.py hl[2,6] *} + +Die folgenden Argumente werden unterstützt: + +* `minimum_size` – Antworten, die kleiner als diese Mindestgröße in Bytes sind, nicht per GZip komprimieren. Der Defaultwert ist `500`. + +## Andere Middlewares + +Es gibt viele andere ASGI-Middlewares. + +Zum Beispiel: + +* Uvicorns `ProxyHeadersMiddleware` +* MessagePack + +Um mehr über weitere verfügbare Middlewares herauszufinden, besuchen Sie Starlettes Middleware-Dokumentation und die ASGI Awesome List. diff --git a/docs/de/docs/advanced/openapi-callbacks.md b/docs/de/docs/advanced/openapi-callbacks.md new file mode 100644 index 000000000..53f06e24e --- /dev/null +++ b/docs/de/docs/advanced/openapi-callbacks.md @@ -0,0 +1,186 @@ +# OpenAPI-Callbacks + +Sie könnten eine API mit einer *Pfadoperation* erstellen, die einen Request an eine *externe API* auslösen könnte, welche von jemand anderem erstellt wurde (wahrscheinlich derselbe Entwickler, der Ihre API *verwenden* würde). + +Der Vorgang, der stattfindet, wenn Ihre API-Anwendung die *externe API* aufruft, wird als „Callback“ („Rückruf“) bezeichnet. Denn die Software, die der externe Entwickler geschrieben hat, sendet einen Request an Ihre API und dann *ruft Ihre API zurück* (*calls back*) und sendet einen Request an eine *externe API* (die wahrscheinlich vom selben Entwickler erstellt wurde). + +In diesem Fall möchten Sie möglicherweise dokumentieren, wie diese externe API aussehen *sollte*. Welche *Pfadoperation* sie haben sollte, welchen Body sie erwarten sollte, welche Response sie zurückgeben sollte, usw. + +## Eine Anwendung mit Callbacks + +Sehen wir uns das alles anhand eines Beispiels an. + +Stellen Sie sich vor, Sie entwickeln eine Anwendung, mit der Sie Rechnungen erstellen können. + +Diese Rechnungen haben eine `id`, einen optionalen `title`, einen `customer` (Kunde) und ein `total` (Gesamtsumme). + +Der Benutzer Ihrer API (ein externer Entwickler) erstellt mit einem POST-Request eine Rechnung in Ihrer API. + +Dann wird Ihre API (beispielsweise): + +* die Rechnung an einen Kunden des externen Entwicklers senden. +* das Geld einsammeln. +* eine Benachrichtigung an den API-Benutzer (den externen Entwickler) zurücksenden. + * Dies erfolgt durch Senden eines POST-Requests (von *Ihrer API*) an eine *externe API*, die von diesem externen Entwickler bereitgestellt wird (das ist der „Callback“). + +## Die normale **FastAPI**-Anwendung + +Sehen wir uns zunächst an, wie die normale API-Anwendung aussehen würde, bevor wir den Callback hinzufügen. + +Sie verfügt über eine *Pfadoperation*, die einen `Invoice`-Body empfängt, und einen Query-Parameter `callback_url`, der die URL für den Callback enthält. + +Dieser Teil ist ziemlich normal, der größte Teil des Codes ist Ihnen wahrscheinlich bereits bekannt: + +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[9:13,36:53] *} + +/// tip | Tipp + +Der Query-Parameter `callback_url` verwendet einen Pydantic-Url-Typ. + +/// + +Das einzig Neue ist `callbacks=invoices_callback_router.routes` als Argument für den *Pfadoperation-Dekorator*. Wir werden als Nächstes sehen, was das ist. + +## Dokumentation des Callbacks + +Der tatsächliche Callback-Code hängt stark von Ihrer eigenen API-Anwendung ab. + +Und er wird wahrscheinlich von Anwendung zu Anwendung sehr unterschiedlich sein. + +Es könnten nur eine oder zwei Codezeilen sein, wie zum Beispiel: + +```Python +callback_url = "https://example.com/api/v1/invoices/events/" +httpx.post(callback_url, json={"description": "Invoice paid", "paid": True}) +``` + +Der möglicherweise wichtigste Teil des Callbacks besteht jedoch darin, sicherzustellen, dass Ihr API-Benutzer (der externe Entwickler) die *externe API* gemäß den Daten, die *Ihre API* im Requestbody des Callbacks senden wird, korrekt implementiert, usw. + +Als Nächstes fügen wir den Code hinzu, um zu dokumentieren, wie diese *externe API* aussehen sollte, um den Callback von *Ihrer API* zu empfangen. + +Diese Dokumentation wird in der Swagger-Oberfläche unter `/docs` in Ihrer API angezeigt und zeigt externen Entwicklern, wie diese die *externe API* erstellen sollten. + +In diesem Beispiel wird nicht der Callback selbst implementiert (das könnte nur eine Codezeile sein), sondern nur der Dokumentationsteil. + +/// tip | Tipp + +Der eigentliche Callback ist nur ein HTTP-Request. + +Wenn Sie den Callback selbst implementieren, können Sie beispielsweise HTTPX oder Requests verwenden. + +/// + +## Schreiben des Codes, der den Callback dokumentiert + +Dieser Code wird nicht in Ihrer Anwendung ausgeführt, wir benötigen ihn nur, um zu *dokumentieren*, wie diese *externe API* aussehen soll. + +Sie wissen jedoch bereits, wie Sie mit **FastAPI** ganz einfach eine automatische Dokumentation für eine API erstellen. + +Daher werden wir dasselbe Wissen nutzen, um zu dokumentieren, wie die *externe API* aussehen sollte ... indem wir die *Pfadoperation(en)* erstellen, welche die externe API implementieren soll (die, welche Ihre API aufruft). + +/// tip | Tipp + +Wenn Sie den Code zum Dokumentieren eines Callbacks schreiben, kann es hilfreich sein, sich vorzustellen, dass Sie dieser *externe Entwickler* sind. Und dass Sie derzeit die *externe API* implementieren, nicht *Ihre API*. + +Wenn Sie diese Sichtweise (des *externen Entwicklers*) vorübergehend übernehmen, wird es offensichtlicher, wo die Parameter, das Pydantic-Modell für den Body, die Response, usw. für diese *externe API* hingehören. + +/// + +### Einen Callback-`APIRouter` erstellen + +Erstellen Sie zunächst einen neuen `APIRouter`, der einen oder mehrere Callbacks enthält. + +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[3,25] *} + +### Die Callback-*Pfadoperation* erstellen + +Um die Callback-*Pfadoperation* zu erstellen, verwenden Sie denselben `APIRouter`, den Sie oben erstellt haben. + +Sie sollte wie eine normale FastAPI-*Pfadoperation* aussehen: + +* Sie sollte wahrscheinlich eine Deklaration des Bodys enthalten, die sie erhalten soll, z. B. `body: InvoiceEvent`. +* Und sie könnte auch eine Deklaration der Response enthalten, die zurückgegeben werden soll, z. B. `response_model=InvoiceEventReceived`. + +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[16:18,21:22,28:32] *} + +Es gibt zwei Hauptunterschiede zu einer normalen *Pfadoperation*: + +* Es muss kein tatsächlicher Code vorhanden sein, da Ihre Anwendung diesen Code niemals aufruft. Sie wird nur zur Dokumentation der *externen API* verwendet. Die Funktion könnte also einfach `pass` enthalten. +* Der *Pfad* kann einen OpenAPI-3-Ausdruck enthalten (mehr dazu weiter unten), wo er Variablen mit Parametern und Teilen des ursprünglichen Requests verwenden kann, der an *Ihre API* gesendet wurde. + +### Der Callback-Pfadausdruck + +Der Callback-*Pfad* kann einen OpenAPI-3-Ausdruck enthalten, welcher Teile des ursprünglichen Requests enthalten kann, der an *Ihre API* gesendet wurde. + +In diesem Fall ist es der `str`: + +```Python +"{$callback_url}/invoices/{$request.body.id}" +``` + +Wenn Ihr API-Benutzer (der externe Entwickler) also einen Request an *Ihre API* sendet, via: + +``` +https://yourapi.com/invoices/?callback_url=https://www.external.org/events +``` + +mit einem JSON-Körper: + +```JSON +{ + "id": "2expen51ve", + "customer": "Mr. Richie Rich", + "total": "9999" +} +``` + +dann verarbeitet *Ihre API* die Rechnung und sendet irgendwann später einen Callback-Request an die `callback_url` (die *externe API*): + +``` +https://www.external.org/events/invoices/2expen51ve +``` + +mit einem JSON-Body, der etwa Folgendes enthält: + +```JSON +{ + "description": "Payment celebration", + "paid": true +} +``` + +und sie würde eine Response von dieser *externen API* mit einem JSON-Body wie dem folgenden erwarten: + +```JSON +{ + "ok": true +} +``` + +/// tip | Tipp + +Beachten Sie, dass die verwendete Callback-URL die URL enthält, die als Query-Parameter in `callback_url` (`https://www.external.org/events`) empfangen wurde, und auch die Rechnungs-`id` aus dem JSON-Body (`2expen51ve`). + +/// + +### Den Callback-Router hinzufügen + +An diesem Punkt haben Sie die benötigte(n) *Callback-Pfadoperation(en)* (diejenige(n), die der *externe Entwickler* in der *externen API* implementieren sollte) im Callback-Router, den Sie oben erstellt haben. + +Verwenden Sie nun den Parameter `callbacks` im *Pfadoperation-Dekorator Ihrer API*, um das Attribut `.routes` (das ist eigentlich nur eine `list`e von Routen/*Pfadoperationen*) dieses Callback-Routers zu übergeben: + +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[35] *} + +/// tip | Tipp + +Beachten Sie, dass Sie nicht den Router selbst (`invoices_callback_router`) an `callback=` übergeben, sondern das Attribut `.routes`, wie in `invoices_callback_router.routes`. + +/// + +### Es in der Dokumentation ansehen + +Jetzt können Sie Ihre Anwendung mit Uvicorn starten und auf http://127.0.0.1:8000/docs gehen. + +Sie sehen Ihre Dokumentation, einschließlich eines Abschnitts „Callbacks“ für Ihre *Pfadoperation*, der zeigt, wie die *externe API* aussehen sollte: + + diff --git a/docs/de/docs/advanced/openapi-webhooks.md b/docs/de/docs/advanced/openapi-webhooks.md new file mode 100644 index 000000000..50b95eaf8 --- /dev/null +++ b/docs/de/docs/advanced/openapi-webhooks.md @@ -0,0 +1,55 @@ +# OpenAPI-Webhooks + +Es gibt Fälle, in denen Sie Ihren API-Benutzern mitteilen möchten, dass Ihre Anwendung mit einigen Daten *deren* Anwendung aufrufen (ein Request senden) könnte, normalerweise um über ein bestimmtes **Event** zu **benachrichtigen**. + +Das bedeutet, dass anstelle des normalen Prozesses, bei dem Benutzer Requests an Ihre API senden, **Ihre API** (oder Ihre Anwendung) **Requests an deren System** (an deren API, deren Anwendung) senden könnte. + +Das wird normalerweise als **Webhook** bezeichnet. + +## Webhooks-Schritte + +Der Prozess besteht normalerweise darin, dass **Sie in Ihrem Code definieren**, welche Nachricht Sie senden möchten, den **Body des Requests**. + +Sie definieren auch auf irgendeine Weise, zu welchen **Momenten** Ihre Anwendung diese Requests oder Events sendet. + +Und **Ihre Benutzer** definieren auf irgendeine Weise (zum Beispiel irgendwo in einem Web-Dashboard) die **URL**, an die Ihre Anwendung diese Requests senden soll. + +Die gesamte **Logik** zur Registrierung der URLs für Webhooks und der Code zum tatsächlichen Senden dieser Requests liegt bei Ihnen. Sie schreiben es so, wie Sie möchten, in **Ihrem eigenen Code**. + +## Webhooks mit **FastAPI** und OpenAPI dokumentieren + +Mit **FastAPI** können Sie mithilfe von OpenAPI die Namen dieser Webhooks, die Arten von HTTP-Operationen, die Ihre Anwendung senden kann (z. B. `POST`, `PUT`, usw.) und die Request**bodys** definieren, die Ihre Anwendung senden würde. + +Dies kann es Ihren Benutzern viel einfacher machen, **deren APIs zu implementieren**, um Ihre **Webhook**-Requests zu empfangen. Möglicherweise können diese sogar einen Teil des eigenem API-Codes automatisch generieren. + +/// info + +Webhooks sind in OpenAPI 3.1.0 und höher verfügbar und werden von FastAPI `0.99.0` und höher unterstützt. + +/// + +## Eine Anwendung mit Webhooks + +Wenn Sie eine **FastAPI**-Anwendung erstellen, gibt es ein `webhooks`-Attribut, mit dem Sie *Webhooks* definieren können, genauso wie Sie *Pfadoperationen* definieren würden, zum Beispiel mit `@app.webhooks.post()`. + +{* ../../docs_src/openapi_webhooks/tutorial001.py hl[9:13,36:53] *} + +Die von Ihnen definierten Webhooks landen im **OpenAPI**-Schema und der automatischen **Dokumentations-Oberfläche**. + +/// info + +Das `app.webhooks`-Objekt ist eigentlich nur ein `APIRouter`, derselbe Typ, den Sie verwenden würden, wenn Sie Ihre Anwendung mit mehreren Dateien strukturieren. + +/// + +Beachten Sie, dass Sie bei Webhooks tatsächlich keinen *Pfad* (wie `/items/`) deklarieren, sondern dass der Text, den Sie dort übergeben, lediglich eine **Kennzeichnung** des Webhooks (der Name des Events) ist. Zum Beispiel ist in `@app.webhooks.post("new-subscription")` der Webhook-Name `new-subscription`. + +Das liegt daran, dass erwartet wird, dass **Ihre Benutzer** den tatsächlichen **URL-Pfad**, an dem diese den Webhook-Request empfangen möchten, auf andere Weise definieren (z. B. über ein Web-Dashboard). + +### Es in der Dokumentation ansehen + +Jetzt können Sie Ihre Anwendung mit Uvicorn starten und auf http://127.0.0.1:8000/docs gehen. + +Sie werden sehen, dass Ihre Dokumentation die normalen *Pfadoperationen* und jetzt auch einige **Webhooks** enthält: + + diff --git a/docs/de/docs/advanced/path-operation-advanced-configuration.md b/docs/de/docs/advanced/path-operation-advanced-configuration.md new file mode 100644 index 000000000..b6e88d2c9 --- /dev/null +++ b/docs/de/docs/advanced/path-operation-advanced-configuration.md @@ -0,0 +1,204 @@ +# Fortgeschrittene Konfiguration der Pfadoperation + +## OpenAPI operationId + +/// warning | Achtung + +Wenn Sie kein „Experte“ für OpenAPI sind, brauchen Sie dies wahrscheinlich nicht. + +/// + +Mit dem Parameter `operation_id` können Sie die OpenAPI `operationId` festlegen, die in Ihrer *Pfadoperation* verwendet werden soll. + +Sie müssten sicherstellen, dass sie für jede Operation eindeutig ist. + +{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *} + +### Verwendung des Namens der *Pfadoperation-Funktion* als operationId + +Wenn Sie die Funktionsnamen Ihrer API als `operationId`s verwenden möchten, können Sie über alle iterieren und die `operation_id` jeder *Pfadoperation* mit deren `APIRoute.name` überschreiben. + +Sie sollten dies tun, nachdem Sie alle Ihre *Pfadoperationen* hinzugefügt haben. + +{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2,12:21,24] *} + +/// tip | Tipp + +Wenn Sie `app.openapi()` manuell aufrufen, sollten Sie vorher die `operationId`s aktualisiert haben. + +/// + +/// warning | Achtung + +Wenn Sie dies tun, müssen Sie sicherstellen, dass jede Ihrer *Pfadoperation-Funktionen* einen eindeutigen Namen hat. + +Auch wenn diese sich in unterschiedlichen Modulen (Python-Dateien) befinden. + +/// + +## Von OpenAPI ausschließen + +Um eine *Pfadoperation* aus dem generierten OpenAPI-Schema (und damit aus den automatischen Dokumentationssystemen) auszuschließen, verwenden Sie den Parameter `include_in_schema` und setzen Sie ihn auf `False`: + +{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *} + +## Fortgeschrittene Beschreibung mittels Docstring + +Sie können die verwendeten Zeilen aus dem Docstring einer *Pfadoperation-Funktion* einschränken, die für OpenAPI verwendet werden. + +Das Hinzufügen eines `\f` (ein maskiertes „Form Feed“-Zeichen) führt dazu, dass **FastAPI** die für OpenAPI verwendete Ausgabe an dieser Stelle abschneidet. + +Sie wird nicht in der Dokumentation angezeigt, aber andere Tools (z. B. Sphinx) können den Rest verwenden. + +{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19:29] *} + +## Zusätzliche Responses + +Sie haben wahrscheinlich gesehen, wie man das `response_model` und den `status_code` für eine *Pfadoperation* deklariert. + +Das definiert die Metadaten der Haupt-Response einer *Pfadoperation*. + +Sie können auch zusätzliche Responses mit deren Modellen, Statuscodes usw. deklarieren. + +Es gibt hier in der Dokumentation ein ganzes Kapitel darüber, Sie können es unter [Zusätzliche Responses in OpenAPI](additional-responses.md){.internal-link target=_blank} lesen. + +## OpenAPI-Extra + +Wenn Sie in Ihrer Anwendung eine *Pfadoperation* deklarieren, generiert **FastAPI** automatisch die relevanten Metadaten dieser *Pfadoperation*, die in das OpenAPI-Schema aufgenommen werden sollen. + +/// note | Technische Details + +In der OpenAPI-Spezifikation wird das Operationsobjekt genannt. + +/// + +Es hat alle Informationen zur *Pfadoperation* und wird zur Erstellung der automatischen Dokumentation verwendet. + +Es enthält `tags`, `parameters`, `requestBody`, `responses`, usw. + +Dieses *Pfadoperation*-spezifische OpenAPI-Schema wird normalerweise automatisch von **FastAPI** generiert, Sie können es aber auch erweitern. + +/// tip | Tipp + +Dies ist ein Low-Level Erweiterungspunkt. + +Wenn Sie nur zusätzliche Responses deklarieren müssen, können Sie dies bequemer mit [Zusätzliche Responses in OpenAPI](additional-responses.md){.internal-link target=_blank} tun. + +/// + +Sie können das OpenAPI-Schema für eine *Pfadoperation* erweitern, indem Sie den Parameter `openapi_extra` verwenden. + +### OpenAPI-Erweiterungen + +Dieses `openapi_extra` kann beispielsweise hilfreich sein, um OpenAPI-Erweiterungen zu deklarieren: + +{* ../../docs_src/path_operation_advanced_configuration/tutorial005.py hl[6] *} + +Wenn Sie die automatische API-Dokumentation öffnen, wird Ihre Erweiterung am Ende der spezifischen *Pfadoperation* angezeigt. + + + +Und wenn Sie die resultierende OpenAPI sehen (unter `/openapi.json` in Ihrer API), sehen Sie Ihre Erweiterung auch als Teil der spezifischen *Pfadoperation*: + +```JSON hl_lines="22" +{ + "openapi": "3.1.0", + "info": { + "title": "FastAPI", + "version": "0.1.0" + }, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + } + }, + "x-aperture-labs-portal": "blue" + } + } + } +} +``` + +### Benutzerdefiniertes OpenAPI-*Pfadoperation*-Schema + +Das Dictionary in `openapi_extra` wird mit dem automatisch generierten OpenAPI-Schema für die *Pfadoperation* zusammengeführt (mittels Deep Merge). + +Sie können dem automatisch generierten Schema also zusätzliche Daten hinzufügen. + +Sie könnten sich beispielsweise dafür entscheiden, den Request mit Ihrem eigenen Code zu lesen und zu validieren, ohne die automatischen Funktionen von FastAPI mit Pydantic zu verwenden, aber Sie könnten den Request trotzdem im OpenAPI-Schema definieren wollen. + +Das könnte man mit `openapi_extra` machen: + +{* ../../docs_src/path_operation_advanced_configuration/tutorial006.py hl[20:37,39:40] *} + +In diesem Beispiel haben wir kein Pydantic-Modell deklariert. Tatsächlich wird der Requestbody nicht einmal als JSON geparst, sondern direkt als `bytes` gelesen und die Funktion `magic_data_reader ()` wäre dafür verantwortlich, ihn in irgendeiner Weise zu parsen. + +Dennoch können wir das zu erwartende Schema für den Requestbody deklarieren. + +### Benutzerdefinierter OpenAPI-Content-Type + +Mit demselben Trick könnten Sie ein Pydantic-Modell verwenden, um das JSON-Schema zu definieren, das dann im benutzerdefinierten Abschnitt des OpenAPI-Schemas für die *Pfadoperation* enthalten ist. + +Und Sie könnten dies auch tun, wenn der Datentyp in der Anfrage nicht JSON ist. + +In der folgenden Anwendung verwenden wir beispielsweise weder die integrierte Funktionalität von FastAPI zum Extrahieren des JSON-Schemas aus Pydantic-Modellen noch die automatische Validierung für JSON. Tatsächlich deklarieren wir den Request-Content-Type als YAML und nicht als JSON: + +//// tab | Pydantic v2 + +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[17:22,24] *} + +//// + +//// tab | Pydantic v1 + +{* ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py hl[17:22,24] *} + +//// + +/// info + +In Pydantic Version 1 hieß die Methode zum Abrufen des JSON-Schemas für ein Modell `Item.schema()`, in Pydantic Version 2 heißt die Methode `Item.model_json_schema()`. + +/// + +Obwohl wir nicht die standardmäßig integrierte Funktionalität verwenden, verwenden wir dennoch ein Pydantic-Modell, um das JSON-Schema für die Daten, die wir in YAML empfangen möchten, manuell zu generieren. + +Dann verwenden wir den Request direkt und extrahieren den Body als `bytes`. Das bedeutet, dass FastAPI nicht einmal versucht, den Request-Payload als JSON zu parsen. + +Und dann parsen wir in unserem Code diesen YAML-Inhalt direkt und verwenden dann wieder dasselbe Pydantic-Modell, um den YAML-Inhalt zu validieren: + +//// tab | Pydantic v2 + +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[26:33] *} + +//// + +//// tab | Pydantic v1 + +{* ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py hl[26:33] *} + +//// + +/// info + +In Pydantic Version 1 war die Methode zum Parsen und Validieren eines Objekts `Item.parse_obj()`, in Pydantic Version 2 heißt die Methode `Item.model_validate()`. + +/// + +/// tip | Tipp + +Hier verwenden wir dasselbe Pydantic-Modell wieder. + +Aber genauso hätten wir es auch auf andere Weise validieren können. + +/// diff --git a/docs/de/docs/advanced/response-change-status-code.md b/docs/de/docs/advanced/response-change-status-code.md new file mode 100644 index 000000000..0aac32f4e --- /dev/null +++ b/docs/de/docs/advanced/response-change-status-code.md @@ -0,0 +1,31 @@ +# Response – Statuscode ändern + +Sie haben wahrscheinlich schon vorher gelesen, dass Sie einen Standard-[Response-Statuscode](../tutorial/response-status-code.md){.internal-link target=_blank} festlegen können. + +In manchen Fällen müssen Sie jedoch einen anderen als den Standard-Statuscode zurückgeben. + +## Anwendungsfall + +Stellen Sie sich zum Beispiel vor, Sie möchten standardmäßig den HTTP-Statuscode „OK“ `200` zurückgeben. + +Wenn die Daten jedoch nicht vorhanden waren, möchten Sie diese erstellen und den HTTP-Statuscode „CREATED“ `201` zurückgeben. + +Sie möchten aber dennoch in der Lage sein, die von Ihnen zurückgegebenen Daten mit einem `response_model` zu filtern und zu konvertieren. + +In diesen Fällen können Sie einen `Response`-Parameter verwenden. + +## Einen `Response`-Parameter verwenden + +Sie können einen Parameter vom Typ `Response` in Ihrer *Pfadoperation-Funktion* deklarieren (wie Sie es auch für Cookies und Header tun können). + +Anschließend können Sie den `status_code` in diesem *vorübergehenden* Response-Objekt festlegen. + +{* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *} + +Und dann können Sie wie gewohnt jedes benötigte Objekt zurückgeben (ein `dict`, ein Datenbankmodell usw.). + +Und wenn Sie ein `response_model` deklariert haben, wird es weiterhin zum Filtern und Konvertieren des von Ihnen zurückgegebenen Objekts verwendet. + +**FastAPI** verwendet diese *vorübergehende* Response, um den Statuscode (auch Cookies und Header) zu extrahieren und fügt diese in die endgültige Response ein, die den von Ihnen zurückgegebenen Wert enthält, gefiltert nach einem beliebigen `response_model`. + +Sie können den Parameter `Response` auch in Abhängigkeiten deklarieren und den Statuscode darin festlegen. Bedenken Sie jedoch, dass der gewinnt, welcher zuletzt gesetzt wird. diff --git a/docs/de/docs/advanced/response-cookies.md b/docs/de/docs/advanced/response-cookies.md new file mode 100644 index 000000000..5fe2cf7e3 --- /dev/null +++ b/docs/de/docs/advanced/response-cookies.md @@ -0,0 +1,51 @@ +# Response-Cookies + +## Einen `Response`-Parameter verwenden + +Sie können einen Parameter vom Typ `Response` in Ihrer *Pfadoperation-Funktion* deklarieren. + +Und dann können Sie Cookies in diesem *vorübergehenden* Response-Objekt setzen. + +{* ../../docs_src/response_cookies/tutorial002.py hl[1,8:9] *} + +Anschließend können Sie wie gewohnt jedes gewünschte Objekt zurückgeben (ein `dict`, ein Datenbankmodell, usw.). + +Und wenn Sie ein `response_model` deklariert haben, wird es weiterhin zum Filtern und Konvertieren des von Ihnen zurückgegebenen Objekts verwendet. + +**FastAPI** verwendet diese *vorübergehende* Response, um die Cookies (auch Header und Statuscode) zu extrahieren und fügt diese in die endgültige Response ein, die den von Ihnen zurückgegebenen Wert enthält, gefiltert nach einem beliebigen `response_model`. + +Sie können den `Response`-Parameter auch in Abhängigkeiten deklarieren und darin Cookies (und Header) setzen. + +## Eine `Response` direkt zurückgeben + +Sie können Cookies auch erstellen, wenn Sie eine `Response` direkt in Ihrem Code zurückgeben. + +Dazu können Sie eine Response erstellen, wie unter [Eine Response direkt zurückgeben](response-directly.md){.internal-link target=_blank} beschrieben. + +Setzen Sie dann Cookies darin und geben Sie sie dann zurück: + +{* ../../docs_src/response_cookies/tutorial001.py hl[10:12] *} + +/// tip | Tipp + +Beachten Sie, dass, wenn Sie eine Response direkt zurückgeben, anstatt den `Response`-Parameter zu verwenden, FastAPI diese direkt zurückgibt. + +Sie müssen also sicherstellen, dass Ihre Daten vom richtigen Typ sind. Z. B. sollten diese mit JSON kompatibel sein, wenn Sie eine `JSONResponse` zurückgeben. + +Und auch, dass Sie keine Daten senden, die durch ein `response_model` hätten gefiltert werden sollen. + +/// + +### Mehr Informationen + +/// note | Technische Details + +Sie können auch `from starlette.responses import Response` oder `from starlette.responses import JSONResponse` verwenden. + +**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. + +Und da die `Response` häufig zum Setzen von Headern und Cookies verwendet wird, stellt **FastAPI** diese auch unter `fastapi.Response` bereit. + +/// + +Um alle verfügbaren Parameter und Optionen anzuzeigen, sehen Sie sich deren Dokumentation in Starlette an. diff --git a/docs/de/docs/advanced/response-directly.md b/docs/de/docs/advanced/response-directly.md new file mode 100644 index 000000000..b84aa8ab9 --- /dev/null +++ b/docs/de/docs/advanced/response-directly.md @@ -0,0 +1,65 @@ +# Eine Response direkt zurückgeben + +Wenn Sie eine **FastAPI** *Pfadoperation* erstellen, können Sie normalerweise beliebige Daten davon zurückgeben: ein `dict`, eine `list`e, ein Pydantic-Modell, ein Datenbankmodell, usw. + +Standardmäßig konvertiert **FastAPI** diesen Rückgabewert automatisch nach JSON, mithilfe des `jsonable_encoder`, der in [JSON-kompatibler Encoder](../tutorial/encoder.md){.internal-link target=_blank} erläutert wird. + +Dann würde es hinter den Kulissen diese JSON-kompatiblen Daten (z. B. ein `dict`) in eine `JSONResponse` einfügen, die zum Senden der Response an den Client verwendet würde. + +Sie können jedoch direkt eine `JSONResponse` von Ihren *Pfadoperationen* zurückgeben. + +Das kann beispielsweise nützlich sein, um benutzerdefinierte Header oder Cookies zurückzugeben. + +## Eine `Response` zurückgeben + +Tatsächlich können Sie jede `Response` oder jede Unterklasse davon zurückgeben. + +/// tip | Tipp + +`JSONResponse` selbst ist eine Unterklasse von `Response`. + +/// + +Und wenn Sie eine `Response` zurückgeben, wird **FastAPI** diese direkt weiterleiten. + +Es wird keine Datenkonvertierung mit Pydantic-Modellen durchführen, es wird den Inhalt nicht in irgendeinen Typ konvertieren, usw. + +Dadurch haben Sie viel Flexibilität. Sie können jeden Datentyp zurückgeben, jede Datendeklaration oder -validierung überschreiben, usw. + +## Verwendung des `jsonable_encoder` in einer `Response` + +Da **FastAPI** keine Änderungen an einer von Ihnen zurückgegebenen `Response` vornimmt, müssen Sie sicherstellen, dass deren Inhalt dafür bereit ist. + +Sie können beispielsweise kein Pydantic-Modell in eine `JSONResponse` einfügen, ohne es zuvor in ein `dict` zu konvertieren, bei dem alle Datentypen (wie `datetime`, `UUID`, usw.) in JSON-kompatible Typen konvertiert wurden. + +In diesen Fällen können Sie den `jsonable_encoder` verwenden, um Ihre Daten zu konvertieren, bevor Sie sie an eine Response übergeben: + +{* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *} + +/// note | Technische Details + +Sie können auch `from starlette.responses import JSONResponse` verwenden. + +**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. + +/// + +## Eine benutzerdefinierte `Response` zurückgeben + +Das obige Beispiel zeigt alle Teile, die Sie benötigen, ist aber noch nicht sehr nützlich, da Sie das `item` einfach direkt hätten zurückgeben können, und **FastAPI** würde es für Sie in eine `JSONResponse` einfügen, es in ein `dict` konvertieren, usw. All das standardmäßig. + +Sehen wir uns nun an, wie Sie damit eine benutzerdefinierte Response zurückgeben können. + +Nehmen wir an, Sie möchten eine XML-Response zurückgeben. + +Sie könnten Ihren XML-Inhalt als String in eine `Response` einfügen und sie zurückgeben: + +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} + +## Anmerkungen + +Wenn Sie eine `Response` direkt zurücksenden, werden deren Daten weder validiert, konvertiert (serialisiert), noch automatisch dokumentiert. + +Sie können sie aber trotzdem wie unter [Zusätzliche Responses in OpenAPI](additional-responses.md){.internal-link target=_blank} beschrieben dokumentieren. + +In späteren Abschnitten erfahren Sie, wie Sie diese benutzerdefinierten `Response`s verwenden/deklarieren und gleichzeitig über automatische Datenkonvertierung, Dokumentation, usw. verfügen. diff --git a/docs/de/docs/advanced/response-headers.md b/docs/de/docs/advanced/response-headers.md new file mode 100644 index 000000000..bf0bd7296 --- /dev/null +++ b/docs/de/docs/advanced/response-headers.md @@ -0,0 +1,41 @@ +# Response-Header + +## Verwenden Sie einen `Response`-Parameter + +Sie können einen Parameter vom Typ `Response` in Ihrer *Pfadoperation-Funktion* deklarieren (wie Sie es auch für Cookies tun können). + +Und dann können Sie Header in diesem *vorübergehenden* Response-Objekt festlegen. + +{* ../../docs_src/response_headers/tutorial002.py hl[1,7:8] *} + +Anschließend können Sie wie gewohnt jedes gewünschte Objekt zurückgeben (ein `dict`, ein Datenbankmodell, usw.). + +Und wenn Sie ein `response_model` deklariert haben, wird es weiterhin zum Filtern und Konvertieren des von Ihnen zurückgegebenen Objekts verwendet. + +**FastAPI** verwendet diese *vorübergehende* Response, um die Header (auch Cookies und Statuscode) zu extrahieren und fügt diese in die endgültige Response ein, die den von Ihnen zurückgegebenen Wert enthält, gefiltert nach einem beliebigen `response_model`. + +Sie können den Parameter `Response` auch in Abhängigkeiten deklarieren und darin Header (und Cookies) festlegen. + +## Eine `Response` direkt zurückgeben + +Sie können auch Header hinzufügen, wenn Sie eine `Response` direkt zurückgeben. + +Erstellen Sie eine Response wie in [Eine Response direkt zurückgeben](response-directly.md){.internal-link target=_blank} beschrieben und übergeben Sie die Header als zusätzlichen Parameter: + +{* ../../docs_src/response_headers/tutorial001.py hl[10:12] *} + +/// note | Technische Details + +Sie können auch `from starlette.responses import Response` oder `from starlette.responses import JSONResponse` verwenden. + +**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. + +Und da die `Response` häufig zum Setzen von Headern und Cookies verwendet wird, stellt **FastAPI** diese auch unter `fastapi.Response` bereit. + +/// + +## Benutzerdefinierte Header + +Beachten Sie, dass benutzerdefinierte proprietäre Header mittels des Präfix 'X-' hinzugefügt werden können. + +Wenn Sie jedoch benutzerdefinierte Header haben, die ein Client in einem Browser sehen können soll, müssen Sie diese zu Ihren CORS-Konfigurationen hinzufügen (weitere Informationen finden Sie unter [CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md){.internal-link target=_blank}), unter Verwendung des Parameters `expose_headers`, dokumentiert in Starlettes CORS-Dokumentation. diff --git a/docs/de/docs/advanced/security/http-basic-auth.md b/docs/de/docs/advanced/security/http-basic-auth.md new file mode 100644 index 000000000..36498c01d --- /dev/null +++ b/docs/de/docs/advanced/security/http-basic-auth.md @@ -0,0 +1,106 @@ +# HTTP Basic Auth + +Für die einfachsten Fälle können Sie HTTP Basic Auth verwenden. + +Bei HTTP Basic Auth erwartet die Anwendung einen Header, der einen Benutzernamen und ein Passwort enthält. + +Wenn sie diesen nicht empfängt, gibt sie den HTTP-Error 401 „Unauthorized“ zurück. + +Und gibt einen Header `WWW-Authenticate` mit dem Wert `Basic` und einem optionalen `realm`-Parameter („Bereich“) zurück. + +Dadurch wird der Browser angewiesen, die integrierte Eingabeaufforderung für einen Benutzernamen und ein Passwort anzuzeigen. + +Wenn Sie dann den Benutzernamen und das Passwort eingeben, sendet der Browser diese automatisch im Header. + +## Einfaches HTTP Basic Auth + +* Importieren Sie `HTTPBasic` und `HTTPBasicCredentials`. +* Erstellen Sie mit `HTTPBasic` ein „`security`-Schema“. +* Verwenden Sie dieses `security` mit einer Abhängigkeit in Ihrer *Pfadoperation*. +* Diese gibt ein Objekt vom Typ `HTTPBasicCredentials` zurück: + * Es enthält den gesendeten `username` und das gesendete `password`. + +{* ../../docs_src/security/tutorial006_an_py39.py hl[4,8,12] *} +Wenn Sie versuchen, die URL zum ersten Mal zu öffnen (oder in der Dokumentation auf den Button „Execute“ zu klicken), wird der Browser Sie nach Ihrem Benutzernamen und Passwort fragen: + + + +## Den Benutzernamen überprüfen + +Hier ist ein vollständigeres Beispiel. + +Verwenden Sie eine Abhängigkeit, um zu überprüfen, ob Benutzername und Passwort korrekt sind. + +Verwenden Sie dazu das Python-Standardmodul `secrets`, um den Benutzernamen und das Passwort zu überprüfen. + +`secrets.compare_digest()` benötigt `bytes` oder einen `str`, welcher nur ASCII-Zeichen (solche der englischen Sprache) enthalten darf, das bedeutet, dass es nicht mit Zeichen wie `á`, wie in `Sebastián`, funktionieren würde. + +Um dies zu lösen, konvertieren wir zunächst den `username` und das `password` in UTF-8-codierte `bytes`. + +Dann können wir `secrets.compare_digest()` verwenden, um sicherzustellen, dass `credentials.username` `"stanleyjobson"` und `credentials.password` `"swordfish"` ist. + +{* ../../docs_src/security/tutorial007_an_py39.py hl[1,12:24] *} + +Dies wäre das gleiche wie: + +```Python +if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"): + # Einen Error zurückgeben + ... +``` + +Aber durch die Verwendung von `secrets.compare_digest()` ist dieser Code sicher vor einer Art von Angriffen, die „Timing-Angriffe“ genannt werden. + +### Timing-Angriffe + +Aber was ist ein „Timing-Angriff“? + +Stellen wir uns vor, dass einige Angreifer versuchen, den Benutzernamen und das Passwort zu erraten. + +Und sie senden eine Anfrage mit dem Benutzernamen `johndoe` und dem Passwort `love123`. + +Dann würde der Python-Code in Ihrer Anwendung etwa so aussehen: + +```Python +if "johndoe" == "stanleyjobson" and "love123" == "swordfish": + ... +``` + +Aber genau in dem Moment, in dem Python das erste `j` in `johndoe` mit dem ersten `s` in `stanleyjobson` vergleicht, gibt es `False` zurück, da es bereits weiß, dass diese beiden Strings nicht identisch sind, und denkt, „Es besteht keine Notwendigkeit, weitere Berechnungen mit dem Vergleich der restlichen Buchstaben zu verschwenden“. Und Ihre Anwendung wird zurückgeben „Incorrect username or password“. + +Doch dann versuchen es die Angreifer mit dem Benutzernamen `stanleyjobsox` und dem Passwort `love123`. + +Und Ihr Anwendungscode macht etwa Folgendes: + +```Python +if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": + ... +``` + +Python muss das gesamte `stanleyjobso` in `stanleyjobsox` und `stanleyjobson` vergleichen, bevor es erkennt, dass beide Zeichenfolgen nicht gleich sind. Daher wird es einige zusätzliche Mikrosekunden dauern, bis die Antwort „Incorrect username or password“ erfolgt. + +#### Die Zeit zum Antworten hilft den Angreifern + +Wenn die Angreifer zu diesem Zeitpunkt feststellen, dass der Server einige Mikrosekunden länger braucht, um die Antwort „Incorrect username or password“ zu senden, wissen sie, dass sie _etwas_ richtig gemacht haben, einige der Anfangsbuchstaben waren richtig. + +Und dann können sie es noch einmal versuchen, wohl wissend, dass es wahrscheinlich eher etwas mit `stanleyjobsox` als mit `johndoe` zu tun hat. + +#### Ein „professioneller“ Angriff + +Natürlich würden die Angreifer das alles nicht von Hand versuchen, sondern ein Programm dafür schreiben, möglicherweise mit Tausenden oder Millionen Tests pro Sekunde. Und würden jeweils nur einen zusätzlichen richtigen Buchstaben erhalten. + +Aber so hätten die Angreifer in wenigen Minuten oder Stunden mit der „Hilfe“ unserer Anwendung den richtigen Benutzernamen und das richtige Passwort erraten, indem sie die Zeitspanne zur Hilfe nehmen, die diese zur Beantwortung benötigt. + +#### Das Problem beheben mittels `secrets.compare_digest()` + +Aber in unserem Code verwenden wir tatsächlich `secrets.compare_digest()`. + +Damit wird, kurz gesagt, der Vergleich von `stanleyjobsox` mit `stanleyjobson` genauso lange dauern wie der Vergleich von `johndoe` mit `stanleyjobson`. Und das Gleiche gilt für das Passwort. + +So ist Ihr Anwendungscode, dank der Verwendung von `secrets.compare_digest()`, vor dieser ganzen Klasse von Sicherheitsangriffen geschützt. + +### Den Error zurückgeben + +Nachdem Sie festgestellt haben, dass die Anmeldeinformationen falsch sind, geben Sie eine `HTTPException` mit dem Statuscode 401 zurück (derselbe, der auch zurückgegeben wird, wenn keine Anmeldeinformationen angegeben werden) und fügen den Header `WWW-Authenticate` hinzu, damit der Browser die Anmeldeaufforderung erneut anzeigt: + +{* ../../docs_src/security/tutorial007_an_py39.py hl[26:30] *} diff --git a/docs/de/docs/advanced/security/index.md b/docs/de/docs/advanced/security/index.md new file mode 100644 index 000000000..25eeb25b5 --- /dev/null +++ b/docs/de/docs/advanced/security/index.md @@ -0,0 +1,19 @@ +# Fortgeschrittene Sicherheit + +## Zusatzfunktionen + +Neben den in [Tutorial – Benutzerhandbuch: Sicherheit](../../tutorial/security/index.md){.internal-link target=_blank} behandelten Funktionen gibt es noch einige zusätzliche Funktionen zur Handhabung der Sicherheit. + +/// tip | Tipp + +Die nächsten Abschnitte sind **nicht unbedingt „fortgeschritten“**. + +Und es ist möglich, dass für Ihren Anwendungsfall die Lösung in einem davon liegt. + +/// + +## Lesen Sie zuerst das Tutorial + +In den nächsten Abschnitten wird davon ausgegangen, dass Sie das Haupt-[Tutorial – Benutzerhandbuch: Sicherheit](../../tutorial/security/index.md){.internal-link target=_blank} bereits gelesen haben. + +Sie basieren alle auf den gleichen Konzepten, ermöglichen jedoch einige zusätzliche Funktionalitäten. diff --git a/docs/de/docs/advanced/security/oauth2-scopes.md b/docs/de/docs/advanced/security/oauth2-scopes.md new file mode 100644 index 000000000..ed8f69d18 --- /dev/null +++ b/docs/de/docs/advanced/security/oauth2-scopes.md @@ -0,0 +1,274 @@ +# OAuth2-Scopes + +Sie können OAuth2-Scopes direkt in **FastAPI** verwenden, sie sind nahtlos integriert. + +Das ermöglicht es Ihnen, ein feingranuliertes Berechtigungssystem nach dem OAuth2-Standard in Ihre OpenAPI-Anwendung (und deren API-Dokumentation) zu integrieren. + +OAuth2 mit Scopes ist der Mechanismus, der von vielen großen Authentifizierungsanbietern wie Facebook, Google, GitHub, Microsoft, Twitter usw. verwendet wird. Sie verwenden ihn, um Benutzern und Anwendungen spezifische Berechtigungen zu erteilen. + +Jedes Mal, wenn Sie sich mit Facebook, Google, GitHub, Microsoft oder Twitter anmelden („log in with“), verwendet die entsprechende Anwendung OAuth2 mit Scopes. + +In diesem Abschnitt erfahren Sie, wie Sie Authentifizierung und Autorisierung mit demselben OAuth2, mit Scopes in Ihrer **FastAPI**-Anwendung verwalten. + +/// warning | Achtung + +Dies ist ein mehr oder weniger fortgeschrittener Abschnitt. Wenn Sie gerade erst anfangen, können Sie ihn überspringen. + +Sie benötigen nicht unbedingt OAuth2-Scopes, und Sie können die Authentifizierung und Autorisierung handhaben wie Sie möchten. + +Aber OAuth2 mit Scopes kann bequem in Ihre API (mit OpenAPI) und deren API-Dokumentation integriert werden. + +Dennoch, verwenden Sie solche Scopes oder andere Sicherheits-/Autorisierungsanforderungen in Ihrem Code so wie Sie es möchten. + +In vielen Fällen kann OAuth2 mit Scopes ein Overkill sein. + +Aber wenn Sie wissen, dass Sie es brauchen oder neugierig sind, lesen Sie weiter. + +/// + +## OAuth2-Scopes und OpenAPI + +Die OAuth2-Spezifikation definiert „Scopes“ als eine Liste von durch Leerzeichen getrennten Strings. + +Der Inhalt jedes dieser Strings kann ein beliebiges Format haben, sollte jedoch keine Leerzeichen enthalten. + +Diese Scopes stellen „Berechtigungen“ dar. + +In OpenAPI (z. B. der API-Dokumentation) können Sie „Sicherheitsschemas“ definieren. + +Wenn eines dieser Sicherheitsschemas OAuth2 verwendet, können Sie auch Scopes deklarieren und verwenden. + +Jeder „Scope“ ist nur ein String (ohne Leerzeichen). + +Er wird normalerweise verwendet, um bestimmte Sicherheitsberechtigungen zu deklarieren, zum Beispiel: + +* `users:read` oder `users:write` sind gängige Beispiele. +* `instagram_basic` wird von Facebook / Instagram verwendet. +* `https://www.googleapis.com/auth/drive` wird von Google verwendet. + +/// info + +In OAuth2 ist ein „Scope“ nur ein String, der eine bestimmte erforderliche Berechtigung deklariert. + +Es spielt keine Rolle, ob er andere Zeichen wie `:` enthält oder ob es eine URL ist. + +Diese Details sind implementierungsspezifisch. + +Für OAuth2 sind es einfach nur Strings. + +/// + +## Gesamtübersicht + +Sehen wir uns zunächst kurz die Teile an, die sich gegenüber den Beispielen im Haupt-**Tutorial – Benutzerhandbuch** für [OAuth2 mit Password (und Hashing), Bearer mit JWT-Tokens](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank} ändern. Diesmal verwenden wir OAuth2-Scopes: + +{* ../../docs_src/security/tutorial005_an_py310.py hl[4,8,12,46,64,105,107:115,121:124,128:134,139,155] *} + +Sehen wir uns diese Änderungen nun Schritt für Schritt an. + +## OAuth2-Sicherheitsschema + +Die erste Änderung ist, dass wir jetzt das OAuth2-Sicherheitsschema mit zwei verfügbaren Scopes deklarieren: `me` und `items`. + +Der `scopes`-Parameter erhält ein `dict` mit jedem Scope als Schlüssel und dessen Beschreibung als Wert: + +{* ../../docs_src/security/tutorial005_an_py310.py hl[62:65] *} + +Da wir diese Scopes jetzt deklarieren, werden sie in der API-Dokumentation angezeigt, wenn Sie sich einloggen/autorisieren. + +Und Sie können auswählen, auf welche Scopes Sie Zugriff haben möchten: `me` und `items`. + +Das ist derselbe Mechanismus, der verwendet wird, wenn Sie beim Anmelden mit Facebook, Google, GitHub, usw. Berechtigungen erteilen: + + + +## JWT-Token mit Scopes + +Ändern Sie nun die Token-*Pfadoperation*, um die angeforderten Scopes zurückzugeben. + +Wir verwenden immer noch dasselbe `OAuth2PasswordRequestForm`. Es enthält eine Eigenschaft `scopes` mit einer `list`e von `str`s für jeden Scope, den es im Request erhalten hat. + +Und wir geben die Scopes als Teil des JWT-Tokens zurück. + +/// danger | Gefahr + +Der Einfachheit halber fügen wir hier die empfangenen Scopes direkt zum Token hinzu. + +Aus Sicherheitsgründen sollten Sie jedoch sicherstellen, dass Sie in Ihrer Anwendung nur die Scopes hinzufügen, die der Benutzer tatsächlich haben kann, oder die Sie vordefiniert haben. + +/// + +{* ../../docs_src/security/tutorial005_an_py310.py hl[155] *} + +## Scopes in *Pfadoperationen* und Abhängigkeiten deklarieren + +Jetzt deklarieren wir, dass die *Pfadoperation* für `/users/me/items/` den Scope `items` erfordert. + +Dazu importieren und verwenden wir `Security` von `fastapi`. + +Sie können `Security` verwenden, um Abhängigkeiten zu deklarieren (genau wie `Depends`), aber `Security` erhält auch einen Parameter `scopes` mit einer Liste von Scopes (Strings). + +In diesem Fall übergeben wir eine Abhängigkeitsfunktion `get_current_active_user` an `Security` (genauso wie wir es mit `Depends` tun würden). + +Wir übergeben aber auch eine `list`e von Scopes, in diesem Fall mit nur einem Scope: `items` (es könnten mehrere sein). + +Und die Abhängigkeitsfunktion `get_current_active_user` kann auch Unterabhängigkeiten deklarieren, nicht nur mit `Depends`, sondern auch mit `Security`. Ihre eigene Unterabhängigkeitsfunktion (`get_current_user`) und weitere Scope-Anforderungen deklarierend. + +In diesem Fall erfordert sie den Scope `me` (sie könnte mehr als einen Scope erfordern). + +/// note | Hinweis + +Sie müssen nicht unbedingt an verschiedenen Stellen verschiedene Scopes hinzufügen. + +Wir tun dies hier, um zu demonstrieren, wie **FastAPI** auf verschiedenen Ebenen deklarierte Scopes verarbeitet. + +/// + +{* ../../docs_src/security/tutorial005_an_py310.py hl[4,139,170] *} + +/// info | Technische Details + +`Security` ist tatsächlich eine Unterklasse von `Depends` und hat nur noch einen zusätzlichen Parameter, den wir später kennenlernen werden. + +Durch die Verwendung von `Security` anstelle von `Depends` weiß **FastAPI** jedoch, dass es Sicherheits-Scopes deklarieren, intern verwenden und die API mit OpenAPI dokumentieren kann. + +Wenn Sie jedoch `Query`, `Path`, `Depends`, `Security` und andere von `fastapi` importieren, handelt es sich tatsächlich um Funktionen, die spezielle Klassen zurückgeben. + +/// + +## `SecurityScopes` verwenden + +Aktualisieren Sie nun die Abhängigkeit `get_current_user`. + +Das ist diejenige, die von den oben genannten Abhängigkeiten verwendet wird. + +Hier verwenden wir dasselbe OAuth2-Schema, das wir zuvor erstellt haben, und deklarieren es als Abhängigkeit: `oauth2_scheme`. + +Da diese Abhängigkeitsfunktion selbst keine Scope-Anforderungen hat, können wir `Depends` mit `oauth2_scheme` verwenden. Wir müssen `Security` nicht verwenden, wenn wir keine Sicherheits-Scopes angeben müssen. + +Wir deklarieren auch einen speziellen Parameter vom Typ `SecurityScopes`, der aus `fastapi.security` importiert wird. + +Diese `SecurityScopes`-Klasse ähnelt `Request` (`Request` wurde verwendet, um das Request-Objekt direkt zu erhalten). + +{* ../../docs_src/security/tutorial005_an_py310.py hl[8,105] *} + +## Die `scopes` verwenden + +Der Parameter `security_scopes` wird vom Typ `SecurityScopes` sein. + +Dieses verfügt über ein Attribut `scopes` mit einer Liste, die alle von ihm selbst benötigten Scopes enthält und ferner alle Abhängigkeiten, die dieses als Unterabhängigkeit verwenden. Sprich, alle „Dependanten“ ... das mag verwirrend klingen, wird aber später noch einmal erklärt. + +Das `security_scopes`-Objekt (der Klasse `SecurityScopes`) stellt außerdem ein `scope_str`-Attribut mit einem einzelnen String bereit, der die durch Leerzeichen getrennten Scopes enthält (den werden wir verwenden). + +Wir erstellen eine `HTTPException`, die wir später an mehreren Stellen wiederverwenden (`raise`n) können. + +In diese Exception fügen wir (falls vorhanden) die erforderlichen Scopes als durch Leerzeichen getrennten String ein (unter Verwendung von `scope_str`). Wir fügen diesen String mit den Scopes in den Header `WWW-Authenticate` ein (das ist Teil der Spezifikation). + +{* ../../docs_src/security/tutorial005_an_py310.py hl[105,107:115] *} + +## Den `username` und das Format der Daten überprüfen + +Wir verifizieren, dass wir einen `username` erhalten, und extrahieren die Scopes. + +Und dann validieren wir diese Daten mit dem Pydantic-Modell (wobei wir die `ValidationError`-Exception abfangen), und wenn wir beim Lesen des JWT-Tokens oder beim Validieren der Daten mit Pydantic einen Fehler erhalten, lösen wir die zuvor erstellte `HTTPException` aus. + +Dazu aktualisieren wir das Pydantic-Modell `TokenData` mit einem neuen Attribut `scopes`. + +Durch die Validierung der Daten mit Pydantic können wir sicherstellen, dass wir beispielsweise präzise eine `list`e von `str`s mit den Scopes und einen `str` mit dem `username` haben. + +Anstelle beispielsweise eines `dict`s oder etwas anderem, was später in der Anwendung zu Fehlern führen könnte und darum ein Sicherheitsrisiko darstellt. + +Wir verifizieren auch, dass wir einen Benutzer mit diesem Benutzernamen haben, und wenn nicht, lösen wir dieselbe Exception aus, die wir zuvor erstellt haben. + +{* ../../docs_src/security/tutorial005_an_py310.py hl[46,116:127] *} + +## Die `scopes` verifizieren + +Wir überprüfen nun, ob das empfangenen Token alle Scopes enthält, die von dieser Abhängigkeit und deren Verwendern (einschließlich *Pfadoperationen*) gefordert werden. Andernfalls lösen wir eine `HTTPException` aus. + +Hierzu verwenden wir `security_scopes.scopes`, das eine `list`e mit allen diesen Scopes als `str` enthält. + +{* ../../docs_src/security/tutorial005_an_py310.py hl[128:134] *} + +## Abhängigkeitsbaum und Scopes + +Sehen wir uns diesen Abhängigkeitsbaum und die Scopes noch einmal an. + +Da die Abhängigkeit `get_current_active_user` von `get_current_user` abhängt, wird der bei `get_current_active_user` deklarierte Scope `"me"` in die Liste der erforderlichen Scopes in `security_scopes.scopes` aufgenommen, das an `get_current_user` übergeben wird. + +Die *Pfadoperation* selbst deklariert auch einen Scope, `"items"`, sodass dieser auch in der Liste der `security_scopes.scopes` enthalten ist, die an `get_current_user` übergeben wird. + +So sieht die Hierarchie der Abhängigkeiten und Scopes aus: + +* Die *Pfadoperation* `read_own_items` hat: + * Erforderliche Scopes `["items"]` mit der Abhängigkeit: + * `get_current_active_user`: + * Die Abhängigkeitsfunktion `get_current_active_user` hat: + * Erforderliche Scopes `["me"]` mit der Abhängigkeit: + * `get_current_user`: + * Die Abhängigkeitsfunktion `get_current_user` hat: + * Selbst keine erforderlichen Scopes. + * Eine Abhängigkeit, die `oauth2_scheme` verwendet. + * Einen `security_scopes`-Parameter vom Typ `SecurityScopes`: + * Dieser `security_scopes`-Parameter hat ein Attribut `scopes` mit einer `list`e, die alle oben deklarierten Scopes enthält, sprich: + * `security_scopes.scopes` enthält `["me", "items"]` für die *Pfadoperation* `read_own_items`. + * `security_scopes.scopes` enthält `["me"]` für die *Pfadoperation* `read_users_me`, da das in der Abhängigkeit `get_current_active_user` deklariert ist. + * `security_scopes.scopes` wird `[]` (nichts) für die *Pfadoperation* `read_system_status` enthalten, da diese keine `Security` mit `scopes` deklariert hat, und deren Abhängigkeit `get_current_user` ebenfalls keinerlei `scopes` deklariert. + +/// tip | Tipp + +Das Wichtige und „Magische“ hier ist, dass `get_current_user` für jede *Pfadoperation* eine andere Liste von `scopes` hat, die überprüft werden. + +Alles hängt von den „Scopes“ ab, die in jeder *Pfadoperation* und jeder Abhängigkeit im Abhängigkeitsbaum für diese bestimmte *Pfadoperation* deklariert wurden. + +/// + +## Weitere Details zu `SecurityScopes`. + +Sie können `SecurityScopes` an jeder Stelle und an mehreren Stellen verwenden, es muss sich nicht in der „Wurzel“-Abhängigkeit befinden. + +Es wird immer die Sicherheits-Scopes enthalten, die in den aktuellen `Security`-Abhängigkeiten deklariert sind und in allen Abhängigkeiten für **diese spezifische** *Pfadoperation* und **diesen spezifischen** Abhängigkeitsbaum. + +Da die `SecurityScopes` alle von den Verwendern der Abhängigkeiten deklarierten Scopes enthalten, können Sie damit überprüfen, ob ein Token in einer zentralen Abhängigkeitsfunktion über die erforderlichen Scopes verfügt, und dann unterschiedliche Scope-Anforderungen in unterschiedlichen *Pfadoperationen* deklarieren. + +Diese werden für jede *Pfadoperation* unabhängig überprüft. + +## Testen Sie es + +Wenn Sie die API-Dokumentation öffnen, können Sie sich authentisieren und angeben, welche Scopes Sie autorisieren möchten. + + + +Wenn Sie keinen Scope auswählen, werden Sie „authentifiziert“, aber wenn Sie versuchen, auf `/users/me/` oder `/users/me/items/` zuzugreifen, wird eine Fehlermeldung angezeigt, die sagt, dass Sie nicht über genügend Berechtigungen verfügen. Sie können aber auf `/status/` zugreifen. + +Und wenn Sie den Scope `me`, aber nicht den Scope `items` auswählen, können Sie auf `/users/me/` zugreifen, aber nicht auf `/users/me/items/`. + +Das würde einer Drittanbieteranwendung passieren, die versucht, auf eine dieser *Pfadoperationen* mit einem Token zuzugreifen, das von einem Benutzer bereitgestellt wurde, abhängig davon, wie viele Berechtigungen der Benutzer dieser Anwendung erteilt hat. + +## Über Integrationen von Drittanbietern + +In diesem Beispiel verwenden wir den OAuth2-Flow „Password“. + +Das ist angemessen, wenn wir uns bei unserer eigenen Anwendung anmelden, wahrscheinlich mit unserem eigenen Frontend. + +Weil wir darauf vertrauen können, dass es den `username` und das `password` erhält, welche wir kontrollieren. + +Wenn Sie jedoch eine OAuth2-Anwendung erstellen, mit der andere eine Verbindung herstellen würden (d.h. wenn Sie einen Authentifizierungsanbieter erstellen, der Facebook, Google, GitHub usw. entspricht), sollten Sie einen der anderen Flows verwenden. + +Am häufigsten ist der „Implicit“-Flow. + +Am sichersten ist der „Code“-Flow, die Implementierung ist jedoch komplexer, da mehr Schritte erforderlich sind. Da er komplexer ist, schlagen viele Anbieter letztendlich den „Implicit“-Flow vor. + +/// note | Hinweis + +Es ist üblich, dass jeder Authentifizierungsanbieter seine Flows anders benennt, um sie zu einem Teil seiner Marke zu machen. + +Aber am Ende implementieren sie denselben OAuth2-Standard. + +/// + +**FastAPI** enthält Werkzeuge für alle diese OAuth2-Authentifizierungs-Flows in `fastapi.security.oauth2`. + +## `Security` in Dekorator-`dependencies` + +Auf die gleiche Weise können Sie eine `list`e von `Depends` im Parameter `dependencies` des Dekorators definieren (wie in [Abhängigkeiten in Pfadoperation-Dekoratoren](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank} erläutert), Sie könnten auch dort `Security` mit `scopes` verwenden. diff --git a/docs/de/docs/advanced/settings.md b/docs/de/docs/advanced/settings.md new file mode 100644 index 000000000..00cc2ac37 --- /dev/null +++ b/docs/de/docs/advanced/settings.md @@ -0,0 +1,464 @@ +# Einstellungen und Umgebungsvariablen + +In vielen Fällen benötigt Ihre Anwendung möglicherweise einige externe Einstellungen oder Konfigurationen, zum Beispiel geheime Schlüssel, Datenbank-Anmeldeinformationen, Anmeldeinformationen für E-Mail-Dienste, usw. + +Die meisten dieser Einstellungen sind variabel (können sich ändern), wie z. B. Datenbank-URLs. Und vieles könnten schützenswerte, geheime Daten sein. + +Aus diesem Grund werden diese üblicherweise in Umgebungsvariablen bereitgestellt, die von der Anwendung gelesen werden. + +## Umgebungsvariablen + +/// tip | Tipp + +Wenn Sie bereits wissen, was „Umgebungsvariablen“ sind und wie man sie verwendet, können Sie gerne mit dem nächsten Abschnitt weiter unten fortfahren. + +/// + +Eine Umgebungsvariable (auch bekannt als „env var“) ist eine Variable, die sich außerhalb des Python-Codes im Betriebssystem befindet und von Ihrem Python-Code (oder auch von anderen Programmen) gelesen werden kann. + +Sie können Umgebungsvariablen in der Shell erstellen und verwenden, ohne Python zu benötigen: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// Sie könnten eine Umgebungsvariable MY_NAME erstellen mittels +$ export MY_NAME="Wade Wilson" + +// Dann könnten Sie diese mit anderen Programmen verwenden, etwa +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// Erstelle eine Umgebungsvariable MY_NAME +$ $Env:MY_NAME = "Wade Wilson" + +// Verwende sie mit anderen Programmen, etwa +$ echo "Hello $Env:MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +### Umgebungsvariablen mit Python auslesen + +Sie können Umgebungsvariablen auch außerhalb von Python im Terminal (oder mit einer anderen Methode) erstellen und diese dann mit Python auslesen. + +Sie könnten zum Beispiel eine Datei `main.py` haben mit: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// tip | Tipp + +Das zweite Argument für `os.getenv()` ist der zurückzugebende Defaultwert. + +Wenn nicht angegeben, ist er standardmäßig `None`. Hier übergeben wir `"World"` als Defaultwert. + +/// + +Dann könnten Sie dieses Python-Programm aufrufen: + +
+ +```console +// Hier legen wir die Umgebungsvariable noch nicht fest +$ python main.py + +// Da wir die Umgebungsvariable nicht festgelegt haben, erhalten wir den Standardwert + +Hello World from Python + +// Aber wenn wir zuerst eine Umgebungsvariable erstellen +$ export MY_NAME="Wade Wilson" + +// Und dann das Programm erneut aufrufen +$ python main.py + +// Kann es jetzt die Umgebungsvariable lesen + +Hello Wade Wilson from Python +``` + +
+ +Da Umgebungsvariablen außerhalb des Codes festgelegt, aber vom Code gelesen werden können und nicht zusammen mit den übrigen Dateien gespeichert (an `git` committet) werden müssen, werden sie häufig für Konfigurationen oder Einstellungen verwendet. + +Sie können eine Umgebungsvariable auch nur für einen bestimmten Programmaufruf erstellen, die nur für dieses Programm und nur für dessen Dauer verfügbar ist. + +Erstellen Sie diese dazu direkt vor dem Programm selbst, in derselben Zeile: + +
+ +```console +// Erstelle eine Umgebungsvariable MY_NAME inline für diesen Programmaufruf +$ MY_NAME="Wade Wilson" python main.py + +// main.py kann jetzt diese Umgebungsvariable lesen + +Hello Wade Wilson from Python + +// Die Umgebungsvariable existiert danach nicht mehr +$ python main.py + +Hello World from Python +``` + +
+ +/// tip | Tipp + +Weitere Informationen dazu finden Sie unter The Twelve-Factor App: Config. + +/// + +### Typen und Validierung + +Diese Umgebungsvariablen können nur Text-Zeichenketten verarbeiten, da sie außerhalb von Python liegen und mit anderen Programmen und dem Rest des Systems (und sogar mit verschiedenen Betriebssystemen wie Linux, Windows, macOS) kompatibel sein müssen. + +Das bedeutet, dass jeder in Python aus einer Umgebungsvariablen gelesene Wert ein `str` ist und jede Konvertierung in einen anderen Typ oder jede Validierung im Code erfolgen muss. + +## Pydantic `Settings` + +Glücklicherweise bietet Pydantic ein großartiges Werkzeug zur Verarbeitung dieser Einstellungen, die von Umgebungsvariablen stammen, mit Pydantic: Settings Management. + +### `pydantic-settings` installieren + +Installieren Sie zunächst das Package `pydantic-settings`: + +
+ +```console +$ pip install pydantic-settings +---> 100% +``` + +
+ +Es ist bereits enthalten, wenn Sie die `all`-Extras installiert haben, mit: + +
+ +```console +$ pip install "fastapi[all]" +---> 100% +``` + +
+ +/// info + +In Pydantic v1 war das im Hauptpackage enthalten. Jetzt wird es als unabhängiges Package verteilt, sodass Sie wählen können, ob Sie es installieren möchten oder nicht, falls Sie die Funktionalität nicht benötigen. + +/// + +### Das `Settings`-Objekt erstellen + +Importieren Sie `BaseSettings` aus Pydantic und erstellen Sie eine Unterklasse, ganz ähnlich wie bei einem Pydantic-Modell. + +Auf die gleiche Weise wie bei Pydantic-Modellen deklarieren Sie Klassenattribute mit Typannotationen und möglicherweise Defaultwerten. + +Sie können dieselben Validierungs-Funktionen und -Tools verwenden, die Sie für Pydantic-Modelle verwenden, z. B. verschiedene Datentypen und zusätzliche Validierungen mit `Field()`. + +//// tab | Pydantic v2 + +{* ../../docs_src/settings/tutorial001.py hl[2,5:8,11] *} + +//// + +//// tab | Pydantic v1 + +/// info + +In Pydantic v1 würden Sie `BaseSettings` direkt von `pydantic` statt von `pydantic_settings` importieren. + +/// + +{* ../../docs_src/settings/tutorial001_pv1.py hl[2,5:8,11] *} + +//// + +/// tip | Tipp + +Für ein schnelles Copy-and-paste verwenden Sie nicht dieses Beispiel, sondern das letzte unten. + +/// + +Wenn Sie dann eine Instanz dieser `Settings`-Klasse erstellen (in diesem Fall als `settings`-Objekt), liest Pydantic die Umgebungsvariablen ohne Berücksichtigung der Groß- und Kleinschreibung. Eine Variable `APP_NAME` in Großbuchstaben wird also als Attribut `app_name` gelesen. + +Als Nächstes werden die Daten konvertiert und validiert. Wenn Sie also dieses `settings`-Objekt verwenden, verfügen Sie über Daten mit den von Ihnen deklarierten Typen (z. B. ist `items_per_user` ein `int`). + +### `settings` verwenden + +Dann können Sie das neue `settings`-Objekt in Ihrer Anwendung verwenden: + +{* ../../docs_src/settings/tutorial001.py hl[18:20] *} + +### Den Server ausführen + +Als Nächstes würden Sie den Server ausführen und die Konfigurationen als Umgebungsvariablen übergeben. Sie könnten beispielsweise `ADMIN_EMAIL` und `APP_NAME` festlegen mit: + +
+ +```console +$ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +/// tip | Tipp + +Um mehrere Umgebungsvariablen für einen einzelnen Befehl festzulegen, trennen Sie diese einfach durch ein Leerzeichen und fügen Sie alle vor dem Befehl ein. + +/// + +Und dann würde die Einstellung `admin_email` auf `"deadpool@example.com"` gesetzt. + +Der `app_name` wäre `"ChimichangApp"`. + +Und `items_per_user` würde seinen Standardwert von `50` behalten. + +## Einstellungen in einem anderen Modul + +Sie könnten diese Einstellungen in eine andere Moduldatei einfügen, wie Sie in [Größere Anwendungen – mehrere Dateien](../tutorial/bigger-applications.md){.internal-link target=_blank} gesehen haben. + +Sie könnten beispielsweise eine Datei `config.py` haben mit: + +{* ../../docs_src/settings/app01/config.py *} + +Und dann verwenden Sie diese in einer Datei `main.py`: + +{* ../../docs_src/settings/app01/main.py hl[3,11:13] *} + +/// tip | Tipp + +Sie benötigen außerdem eine Datei `__init__.py`, wie in [Größere Anwendungen – mehrere Dateien](../tutorial/bigger-applications.md){.internal-link target=_blank} gesehen. + +/// + +## Einstellungen in einer Abhängigkeit + +In manchen Fällen kann es nützlich sein, die Einstellungen mit einer Abhängigkeit bereitzustellen, anstatt ein globales Objekt `settings` zu haben, das überall verwendet wird. + +Dies könnte besonders beim Testen nützlich sein, da es sehr einfach ist, eine Abhängigkeit mit Ihren eigenen benutzerdefinierten Einstellungen zu überschreiben. + +### Die Konfigurationsdatei + +Ausgehend vom vorherigen Beispiel könnte Ihre Datei `config.py` so aussehen: + +{* ../../docs_src/settings/app02/config.py hl[10] *} + +Beachten Sie, dass wir jetzt keine Standardinstanz `settings = Settings()` erstellen. + +### Die Haupt-Anwendungsdatei + +Jetzt erstellen wir eine Abhängigkeit, die ein neues `config.Settings()` zurückgibt. + +{* ../../docs_src/settings/app02_an_py39/main.py hl[6,12:13] *} + +/// tip | Tipp + +Wir werden das `@lru_cache` in Kürze besprechen. + +Im Moment nehmen Sie an, dass `get_settings()` eine normale Funktion ist. + +/// + +Und dann können wir das von der *Pfadoperation-Funktion* als Abhängigkeit einfordern und es überall dort verwenden, wo wir es brauchen. + +{* ../../docs_src/settings/app02_an_py39/main.py hl[17,19:21] *} + +### Einstellungen und Tests + +Dann wäre es sehr einfach, beim Testen ein anderes Einstellungsobjekt bereitzustellen, indem man eine Abhängigkeitsüberschreibung für `get_settings` erstellt: + +{* ../../docs_src/settings/app02/test_main.py hl[9:10,13,21] *} + +Bei der Abhängigkeitsüberschreibung legen wir einen neuen Wert für `admin_email` fest, wenn wir das neue `Settings`-Objekt erstellen, und geben dann dieses neue Objekt zurück. + +Dann können wir testen, ob das verwendet wird. + +## Lesen einer `.env`-Datei + +Wenn Sie viele Einstellungen haben, die sich möglicherweise oft ändern, vielleicht in verschiedenen Umgebungen, kann es nützlich sein, diese in eine Datei zu schreiben und sie dann daraus zu lesen, als wären sie Umgebungsvariablen. + +Diese Praxis ist so weit verbreitet, dass sie einen Namen hat. Diese Umgebungsvariablen werden üblicherweise in einer Datei `.env` abgelegt und die Datei wird „dotenv“ genannt. + +/// tip | Tipp + +Eine Datei, die mit einem Punkt (`.`) beginnt, ist eine versteckte Datei in Unix-ähnlichen Systemen wie Linux und macOS. + +Aber eine dotenv-Datei muss nicht unbedingt genau diesen Dateinamen haben. + +/// + +Pydantic unterstützt das Lesen dieser Dateitypen mithilfe einer externen Bibliothek. Weitere Informationen finden Sie unter Pydantic Settings: Dotenv (.env) support. + +/// tip | Tipp + +Damit das funktioniert, müssen Sie `pip install python-dotenv` ausführen. + +/// + +### Die `.env`-Datei + +Sie könnten eine `.env`-Datei haben, mit: + +```bash +ADMIN_EMAIL="deadpool@example.com" +APP_NAME="ChimichangApp" +``` + +### Einstellungen aus `.env` lesen + +Und dann aktualisieren Sie Ihre `config.py` mit: + +//// tab | Pydantic v2 + +{* ../../docs_src/settings/app03_an/config.py hl[9] *} + +/// tip | Tipp + +Das Attribut `model_config` wird nur für die Pydantic-Konfiguration verwendet. Weitere Informationen finden Sie unter Pydantic: Configuration. + +/// + +//// + +//// tab | Pydantic v1 + +{* ../../docs_src/settings/app03_an/config_pv1.py hl[9:10] *} + +/// tip | Tipp + +Die Klasse `Config` wird nur für die Pydantic-Konfiguration verwendet. Weitere Informationen finden Sie unter Pydantic Model Config. + +/// + +//// + +/// info + +In Pydantic Version 1 erfolgte die Konfiguration in einer internen Klasse `Config`, in Pydantic Version 2 erfolgt sie in einem Attribut `model_config`. Dieses Attribut akzeptiert ein `dict`. Um automatische Codevervollständigung und Inline-Fehlerberichte zu erhalten, können Sie `SettingsConfigDict` importieren und verwenden, um dieses `dict` zu definieren. + +/// + +Hier definieren wir die Konfiguration `env_file` innerhalb Ihrer Pydantic-`Settings`-Klasse und setzen den Wert auf den Dateinamen mit der dotenv-Datei, die wir verwenden möchten. + +### Die `Settings` nur einmal laden mittels `lru_cache` + +Das Lesen einer Datei von der Festplatte ist normalerweise ein kostspieliger (langsamer) Vorgang, daher möchten Sie ihn wahrscheinlich nur einmal ausführen und dann dasselbe Einstellungsobjekt erneut verwenden, anstatt es für jeden Request zu lesen. + +Aber jedes Mal, wenn wir ausführen: + +```Python +Settings() +``` + +würde ein neues `Settings`-Objekt erstellt und bei der Erstellung würde die `.env`-Datei erneut ausgelesen. + +Wenn die Abhängigkeitsfunktion wie folgt wäre: + +```Python +def get_settings(): + return Settings() +``` + +würden wir dieses Objekt für jeden Request erstellen und die `.env`-Datei für jeden Request lesen. ⚠️ + +Da wir jedoch den `@lru_cache`-Dekorator oben verwenden, wird das `Settings`-Objekt nur einmal erstellt, nämlich beim ersten Aufruf. ✔️ + +{* ../../docs_src/settings/app03_an_py39/main.py hl[1,11] *} + +Dann wird bei allen nachfolgenden Aufrufen von `get_settings()`, in den Abhängigkeiten für darauffolgende Requests, dasselbe Objekt zurückgegeben, das beim ersten Aufruf zurückgegeben wurde, anstatt den Code von `get_settings()` erneut auszuführen und ein neues `Settings`-Objekt zu erstellen. + +#### Technische Details zu `lru_cache` + +`@lru_cache` ändert die Funktion, die es dekoriert, dahingehend, denselben Wert zurückzugeben, der beim ersten Mal zurückgegeben wurde, anstatt ihn erneut zu berechnen und den Code der Funktion jedes Mal auszuführen. + +Die darunter liegende Funktion wird also für jede Argumentkombination einmal ausgeführt. Und dann werden die von jeder dieser Argumentkombinationen zurückgegebenen Werte immer wieder verwendet, wenn die Funktion mit genau derselben Argumentkombination aufgerufen wird. + +Wenn Sie beispielsweise eine Funktion haben: + +```Python +@lru_cache +def say_hi(name: str, salutation: str = "Ms."): + return f"Hello {salutation} {name}" +``` + +könnte Ihr Programm so ausgeführt werden: + +```mermaid +sequenceDiagram + +participant code as Code +participant function as say_hi() +participant execute as Funktion ausgeführt + + rect rgba(0, 255, 0, .1) + code ->> function: say_hi(name="Camila") + function ->> execute: führe Code der Funktion aus + execute ->> code: gib das Resultat zurück + end + + rect rgba(0, 255, 255, .1) + code ->> function: say_hi(name="Camila") + function ->> code: gib das gespeicherte Resultat zurück + end + + rect rgba(0, 255, 0, .1) + code ->> function: say_hi(name="Rick") + function ->> execute: führe Code der Funktion aus + execute ->> code: gib das Resultat zurück + end + + rect rgba(0, 255, 0, .1) + code ->> function: say_hi(name="Rick", salutation="Mr.") + function ->> execute: führe Code der Funktion aus + execute ->> code: gib das Resultat zurück + end + + rect rgba(0, 255, 255, .1) + code ->> function: say_hi(name="Rick") + function ->> code: gib das gespeicherte Resultat zurück + end + + rect rgba(0, 255, 255, .1) + code ->> function: say_hi(name="Camila") + function ->> code: gib das gespeicherte Resultat zurück + end +``` + +Im Fall unserer Abhängigkeit `get_settings()` akzeptiert die Funktion nicht einmal Argumente, sodass sie immer den gleichen Wert zurückgibt. + +Auf diese Weise verhält es sich fast so, als wäre es nur eine globale Variable. Da es jedoch eine Abhängigkeitsfunktion verwendet, können wir diese zu Testzwecken problemlos überschreiben. + +`@lru_cache` ist Teil von `functools`, welches Teil von Pythons Standardbibliothek ist. Weitere Informationen dazu finden Sie in der Python Dokumentation für `@lru_cache`. + +## Zusammenfassung + +Mit Pydantic Settings können Sie die Einstellungen oder Konfigurationen für Ihre Anwendung verwalten und dabei die gesamte Leistungsfähigkeit der Pydantic-Modelle nutzen. + +* Durch die Verwendung einer Abhängigkeit können Sie das Testen vereinfachen. +* Sie können `.env`-Dateien damit verwenden. +* Durch die Verwendung von `@lru_cache` können Sie vermeiden, die dotenv-Datei bei jedem Request erneut zu lesen, während Sie sie während des Testens überschreiben können. diff --git a/docs/de/docs/advanced/sub-applications.md b/docs/de/docs/advanced/sub-applications.md new file mode 100644 index 000000000..f123147b3 --- /dev/null +++ b/docs/de/docs/advanced/sub-applications.md @@ -0,0 +1,67 @@ +# Unteranwendungen – Mounts + +Wenn Sie zwei unabhängige FastAPI-Anwendungen mit deren eigenen unabhängigen OpenAPI und deren eigenen Dokumentationsoberflächen benötigen, können Sie eine Hauptanwendung haben und dann eine (oder mehrere) Unteranwendung(en) „mounten“. + +## Mounten einer **FastAPI**-Anwendung + +„Mounten“ („Einhängen“) bedeutet das Hinzufügen einer völlig „unabhängigen“ Anwendung an einem bestimmten Pfad, die sich dann um die Handhabung aller unter diesem Pfad liegenden _Pfadoperationen_ kümmert, welche in dieser Unteranwendung deklariert sind. + +### Hauptanwendung + +Erstellen Sie zunächst die Hauptanwendung **FastAPI** und deren *Pfadoperationen*: + +{* ../../docs_src/sub_applications/tutorial001.py hl[3,6:8] *} + +### Unteranwendung + +Erstellen Sie dann Ihre Unteranwendung und deren *Pfadoperationen*. + +Diese Unteranwendung ist nur eine weitere Standard-FastAPI-Anwendung, aber diese wird „gemountet“: + +{* ../../docs_src/sub_applications/tutorial001.py hl[11,14:16] *} + +### Die Unteranwendung mounten + +Mounten Sie in Ihrer Top-Level-Anwendung `app` die Unteranwendung `subapi`. + +In diesem Fall wird sie im Pfad `/subapi` gemountet: + +{* ../../docs_src/sub_applications/tutorial001.py hl[11,19] *} + +### Es in der automatischen API-Dokumentation betrachten + +Führen Sie nun `uvicorn` mit der Hauptanwendung aus. Wenn Ihre Datei `main.py` lautet, wäre das: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Und öffnen Sie die Dokumentation unter http://127.0.0.1:8000/docs. + +Sie sehen die automatische API-Dokumentation für die Hauptanwendung, welche nur deren eigene _Pfadoperationen_ anzeigt: + + + +Öffnen Sie dann die Dokumentation für die Unteranwendung unter http://127.0.0.1:8000/subapi/docs. + +Sie sehen die automatische API-Dokumentation für die Unteranwendung, welche nur deren eigene _Pfadoperationen_ anzeigt, alle unter dem korrekten Unterpfad-Präfix `/subapi`: + + + +Wenn Sie versuchen, mit einer der beiden Benutzeroberflächen zu interagieren, funktionieren diese ordnungsgemäß, da der Browser mit jeder spezifischen Anwendung oder Unteranwendung kommunizieren kann. + +### Technische Details: `root_path` + +Wenn Sie eine Unteranwendung wie oben beschrieben mounten, kümmert sich FastAPI darum, den Mount-Pfad für die Unteranwendung zu kommunizieren, mithilfe eines Mechanismus aus der ASGI-Spezifikation namens `root_path`. + +Auf diese Weise weiß die Unteranwendung, dass sie dieses Pfadpräfix für die Benutzeroberfläche der Dokumentation verwenden soll. + +Und die Unteranwendung könnte auch ihre eigenen gemounteten Unteranwendungen haben und alles würde korrekt funktionieren, da FastAPI sich um alle diese `root_path`s automatisch kümmert. + +Mehr über den `root_path` und dessen explizite Verwendung erfahren Sie im Abschnitt [Hinter einem Proxy](behind-a-proxy.md){.internal-link target=_blank}. diff --git a/docs/de/docs/advanced/templates.md b/docs/de/docs/advanced/templates.md new file mode 100644 index 000000000..136ce6027 --- /dev/null +++ b/docs/de/docs/advanced/templates.md @@ -0,0 +1,126 @@ +# Templates + +Sie können jede gewünschte Template-Engine mit **FastAPI** verwenden. + +Eine häufige Wahl ist Jinja2, dasselbe, was auch von Flask und anderen Tools verwendet wird. + +Es gibt Werkzeuge zur einfachen Konfiguration, die Sie direkt in Ihrer **FastAPI**-Anwendung verwenden können (bereitgestellt von Starlette). + +## Abhängigkeiten installieren + +Installieren Sie `jinja2`: + +
+ +```console +$ pip install jinja2 + +---> 100% +``` + +
+ +## Verwendung von `Jinja2Templates` + +* Importieren Sie `Jinja2Templates`. +* Erstellen Sie ein `templates`-Objekt, das Sie später wiederverwenden können. +* Deklarieren Sie einen `Request`-Parameter in der *Pfadoperation*, welcher ein Template zurückgibt. +* Verwenden Sie die von Ihnen erstellten `templates`, um eine `TemplateResponse` zu rendern und zurückzugeben, übergeben Sie den Namen des Templates, das Requestobjekt und ein „Kontext“-Dictionary mit Schlüssel-Wert-Paaren, die innerhalb des Jinja2-Templates verwendet werden sollen. + +{* ../../docs_src/templates/tutorial001.py hl[4,11,15:18] *} + +/// note | Hinweis + +Vor FastAPI 0.108.0 und Starlette 0.29.0 war `name` der erste Parameter. + +Außerdem wurde in früheren Versionen das `request`-Objekt als Teil der Schlüssel-Wert-Paare im Kontext für Jinja2 übergeben. + +/// + +/// tip | Tipp + +Durch die Deklaration von `response_class=HTMLResponse` kann die Dokumentationsoberfläche erkennen, dass die Response HTML sein wird. + +/// + +/// note | Technische Details + +Sie können auch `from starlette.templating import Jinja2Templates` verwenden. + +**FastAPI** bietet dasselbe `starlette.templating` auch via `fastapi.templating` an, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber direkt von Starlette. Das Gleiche gilt für `Request` und `StaticFiles`. + +/// + +## Templates erstellen + +Dann können Sie unter `templates/item.html` ein Template erstellen, mit z. B. folgendem Inhalt: + +```jinja hl_lines="7" +{!../../docs_src/templates/templates/item.html!} +``` + +### Template-Kontextwerte + +Im HTML, welches enthält: + +{% raw %} + +```jinja +Item ID: {{ id }} +``` + +{% endraw %} + +... wird die `id` angezeigt, welche dem „Kontext“-`dict` entnommen wird, welches Sie übergeben haben: + +```Python +{"id": id} +``` + +Mit beispielsweise einer ID `42` würde das wie folgt gerendert werden: + +```html +Item ID: 42 +``` + +### Template-`url_for`-Argumente + +Sie können `url_for()` auch innerhalb des Templates verwenden, es nimmt als Argumente dieselben Argumente, die von Ihrer *Pfadoperation-Funktion* verwendet werden. + +Der Abschnitt mit: + +{% raw %} + +```jinja + +``` + +{% endraw %} + +... generiert also einen Link zu derselben URL, welche von der *Pfadoperation-Funktion* `read_item(id=id)` gehandhabt werden würde. + +Mit beispielsweise der ID `42` würde dies Folgendes ergeben: + +```html + +``` + +## Templates und statische Dateien + +Sie können `url_for()` innerhalb des Templates auch beispielsweise mit den `StaticFiles` verwenden, die Sie mit `name="static"` gemountet haben. + +```jinja hl_lines="4" +{!../../docs_src/templates/templates/item.html!} +``` + +In diesem Beispiel würde das zu einer CSS-Datei unter `static/styles.css` verlinken, mit folgendem Inhalt: + +```CSS hl_lines="4" +{!../../docs_src/templates/static/styles.css!} +``` + +Und da Sie `StaticFiles` verwenden, wird diese CSS-Datei automatisch von Ihrer **FastAPI**-Anwendung unter der URL `/static/styles.css` bereitgestellt. + +## Mehr Details + +Weitere Informationen, einschließlich, wie man Templates testet, finden Sie in der Starlette Dokumentation zu Templates. diff --git a/docs/de/docs/advanced/testing-dependencies.md b/docs/de/docs/advanced/testing-dependencies.md new file mode 100644 index 000000000..8299d6dd7 --- /dev/null +++ b/docs/de/docs/advanced/testing-dependencies.md @@ -0,0 +1,53 @@ +# Testen mit Ersatz für Abhängigkeiten + +## Abhängigkeiten beim Testen überschreiben + +Es gibt einige Szenarien, in denen Sie beim Testen möglicherweise eine Abhängigkeit überschreiben möchten. + +Sie möchten nicht, dass die ursprüngliche Abhängigkeit ausgeführt wird (und auch keine der möglicherweise vorhandenen Unterabhängigkeiten). + +Stattdessen möchten Sie eine andere Abhängigkeit bereitstellen, die nur während Tests (möglicherweise nur bei einigen bestimmten Tests) verwendet wird und einen Wert bereitstellt, der dort verwendet werden kann, wo der Wert der ursprünglichen Abhängigkeit verwendet wurde. + +### Anwendungsfälle: Externer Service + +Ein Beispiel könnte sein, dass Sie einen externen Authentifizierungsanbieter haben, mit dem Sie sich verbinden müssen. + +Sie senden ihm ein Token und er gibt einen authentifizierten Benutzer zurück. + +Dieser Anbieter berechnet Ihnen möglicherweise Gebühren pro Anfrage, und der Aufruf könnte etwas länger dauern, als wenn Sie einen vordefinierten Scheinbenutzer für Tests hätten. + +Sie möchten den externen Anbieter wahrscheinlich einmal testen, ihn aber nicht unbedingt bei jedem weiteren ausgeführten Test aufrufen. + +In diesem Fall können Sie die Abhängigkeit, die diesen Anbieter aufruft, überschreiben und eine benutzerdefinierte Abhängigkeit verwenden, die einen Scheinbenutzer zurückgibt, nur für Ihre Tests. + +### Verwenden Sie das Attribut `app.dependency_overrides`. + +Für diese Fälle verfügt Ihre **FastAPI**-Anwendung über das Attribut `app.dependency_overrides`, bei diesem handelt sich um ein einfaches `dict`. + +Um eine Abhängigkeit für das Testen zu überschreiben, geben Sie als Schlüssel die ursprüngliche Abhängigkeit (eine Funktion) und als Wert Ihre Überschreibung der Abhängigkeit (eine andere Funktion) ein. + +Und dann ruft **FastAPI** diese Überschreibung anstelle der ursprünglichen Abhängigkeit auf. + +{* ../../docs_src/dependency_testing/tutorial001_an_py310.py hl[26:27,30] *} + +/// tip | Tipp + +Sie können eine Überschreibung für eine Abhängigkeit festlegen, die an einer beliebigen Stelle in Ihrer **FastAPI**-Anwendung verwendet wird. + +Die ursprüngliche Abhängigkeit könnte in einer *Pfadoperation-Funktion*, einem *Pfadoperation-Dekorator* (wenn Sie den Rückgabewert nicht verwenden), einem `.include_router()`-Aufruf, usw. verwendet werden. + +FastAPI kann sie in jedem Fall überschreiben. + +/// + +Anschließend können Sie Ihre Überschreibungen zurücksetzen (entfernen), indem Sie `app.dependency_overrides` auf ein leeres `dict` setzen: + +```Python +app.dependency_overrides = {} +``` + +/// tip | Tipp + +Wenn Sie eine Abhängigkeit nur während einiger Tests überschreiben möchten, können Sie die Überschreibung zu Beginn des Tests (innerhalb der Testfunktion) festlegen und am Ende (am Ende der Testfunktion) zurücksetzen. + +/// diff --git a/docs/de/docs/advanced/testing-events.md b/docs/de/docs/advanced/testing-events.md new file mode 100644 index 000000000..05d6bcb2b --- /dev/null +++ b/docs/de/docs/advanced/testing-events.md @@ -0,0 +1,5 @@ +# Events testen: Hochfahren – Herunterfahren + +Wenn Sie in Ihren Tests Ihre Event-Handler (`startup` und `shutdown`) ausführen wollen, können Sie den `TestClient` mit einer `with`-Anweisung verwenden: + +{* ../../docs_src/app_testing/tutorial003.py hl[9:12,20:24] *} diff --git a/docs/de/docs/advanced/testing-websockets.md b/docs/de/docs/advanced/testing-websockets.md new file mode 100644 index 000000000..5932e6d6a --- /dev/null +++ b/docs/de/docs/advanced/testing-websockets.md @@ -0,0 +1,13 @@ +# WebSockets testen + +Sie können den schon bekannten `TestClient` zum Testen von WebSockets verwenden. + +Dazu verwenden Sie den `TestClient` in einer `with`-Anweisung, eine Verbindung zum WebSocket herstellend: + +{* ../../docs_src/app_testing/tutorial002.py hl[27:31] *} + +/// note | Hinweis + +Weitere Informationen finden Sie in der Starlette-Dokumentation zum Testen von WebSockets. + +/// diff --git a/docs/de/docs/advanced/using-request-directly.md b/docs/de/docs/advanced/using-request-directly.md new file mode 100644 index 000000000..a0a5ec1ab --- /dev/null +++ b/docs/de/docs/advanced/using-request-directly.md @@ -0,0 +1,56 @@ +# Den Request direkt verwenden + +Bisher haben Sie die Teile des Requests, die Sie benötigen, mithilfe von deren Typen deklariert. + +Daten nehmend von: + +* Dem Pfad als Parameter. +* Headern. +* Cookies. +* usw. + +Und indem Sie das tun, validiert **FastAPI** diese Daten, konvertiert sie und generiert automatisch Dokumentation für Ihre API. + +Es gibt jedoch Situationen, in denen Sie möglicherweise direkt auf das `Request`-Objekt zugreifen müssen. + +## Details zum `Request`-Objekt + +Da **FastAPI** unter der Haube eigentlich **Starlette** ist, mit einer Ebene von mehreren Tools darüber, können Sie Starlette's `Request`-Objekt direkt verwenden, wenn Sie es benötigen. + +Das bedeutet allerdings auch, dass, wenn Sie Daten direkt vom `Request`-Objekt nehmen (z. B. dessen Body lesen), diese von FastAPI nicht validiert, konvertiert oder dokumentiert werden (mit OpenAPI, für die automatische API-Benutzeroberfläche). + +Obwohl jeder andere normal deklarierte Parameter (z. B. der Body, mit einem Pydantic-Modell) dennoch validiert, konvertiert, annotiert, usw. werden würde. + +Es gibt jedoch bestimmte Fälle, in denen es nützlich ist, auf das `Request`-Objekt zuzugreifen. + +## Das `Request`-Objekt direkt verwenden + +Angenommen, Sie möchten auf die IP-Adresse/den Host des Clients in Ihrer *Pfadoperation-Funktion* zugreifen. + +Dazu müssen Sie direkt auf den Request zugreifen. + +{* ../../docs_src/using_request_directly/tutorial001.py hl[1,7:8] *} + +Durch die Deklaration eines *Pfadoperation-Funktionsparameters*, dessen Typ der `Request` ist, weiß **FastAPI**, dass es den `Request` diesem Parameter übergeben soll. + +/// tip | Tipp + +Beachten Sie, dass wir in diesem Fall einen Pfad-Parameter zusätzlich zum Request-Parameter deklarieren. + +Der Pfad-Parameter wird also extrahiert, validiert, in den spezifizierten Typ konvertiert und mit OpenAPI annotiert. + +Auf die gleiche Weise können Sie wie gewohnt jeden anderen Parameter deklarieren und zusätzlich auch den `Request` erhalten. + +/// + +## `Request`-Dokumentation + +Weitere Details zum `Request`-Objekt finden Sie in der offiziellen Starlette-Dokumentation. + +/// note | Technische Details + +Sie können auch `from starlette.requests import Request` verwenden. + +**FastAPI** stellt es direkt zur Verfügung, als Komfort für Sie, den Entwickler. Es kommt aber direkt von Starlette. + +/// diff --git a/docs/de/docs/advanced/websockets.md b/docs/de/docs/advanced/websockets.md new file mode 100644 index 000000000..020c20bc0 --- /dev/null +++ b/docs/de/docs/advanced/websockets.md @@ -0,0 +1,186 @@ +# WebSockets + +Sie können WebSockets mit **FastAPI** verwenden. + +## `WebSockets` installieren + +Zuerst müssen Sie `WebSockets` installieren: + +
+ +```console +$ pip install websockets + +---> 100% +``` + +
+ +## WebSockets-Client + +### In Produktion + +In Ihrem Produktionssystem haben Sie wahrscheinlich ein Frontend, das mit einem modernen Framework wie React, Vue.js oder Angular erstellt wurde. + +Und um über WebSockets mit Ihrem Backend zu kommunizieren, würden Sie wahrscheinlich die Werkzeuge Ihres Frontends verwenden. + +Oder Sie verfügen möglicherweise über eine native Mobile-Anwendung, die direkt in nativem Code mit Ihrem WebSocket-Backend kommuniziert. + +Oder Sie haben andere Möglichkeiten, mit dem WebSocket-Endpunkt zu kommunizieren. + +--- + +Für dieses Beispiel verwenden wir jedoch ein sehr einfaches HTML-Dokument mit etwas JavaScript, alles in einem langen String. + +Das ist natürlich nicht optimal und man würde das nicht in der Produktion machen. + +In der Produktion hätten Sie eine der oben genannten Optionen. + +Aber es ist die einfachste Möglichkeit, sich auf die Serverseite von WebSockets zu konzentrieren und ein funktionierendes Beispiel zu haben: + +{* ../../docs_src/websockets/tutorial001.py hl[2,6:38,41:43] *} + +## Einen `websocket` erstellen + +Erstellen Sie in Ihrer **FastAPI**-Anwendung einen `websocket`: + +{* ../../docs_src/websockets/tutorial001.py hl[1,46:47] *} + +/// note | Technische Details + +Sie können auch `from starlette.websockets import WebSocket` verwenden. + +**FastAPI** stellt den gleichen `WebSocket` direkt zur Verfügung, als Annehmlichkeit für Sie, den Entwickler. Er kommt aber direkt von Starlette. + +/// + +## Nachrichten erwarten und Nachrichten senden + +In Ihrer WebSocket-Route können Sie Nachrichten `await`en und Nachrichten senden. + +{* ../../docs_src/websockets/tutorial001.py hl[48:52] *} + +Sie können Binär-, Text- und JSON-Daten empfangen und senden. + +## Es ausprobieren + +Wenn Ihre Datei `main.py` heißt, führen Sie Ihre Anwendung so aus: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Öffnen Sie Ihren Browser unter http://127.0.0.1:8000. + +Sie sehen eine einfache Seite wie: + + + +Sie können Nachrichten in das Eingabefeld tippen und absenden: + + + +Und Ihre **FastAPI**-Anwendung mit WebSockets antwortet: + + + +Sie können viele Nachrichten senden (und empfangen): + + + +Und alle verwenden dieselbe WebSocket-Verbindung. + +## Verwendung von `Depends` und anderen + +In WebSocket-Endpunkten können Sie Folgendes aus `fastapi` importieren und verwenden: + +* `Depends` +* `Security` +* `Cookie` +* `Header` +* `Path` +* `Query` + +Diese funktionieren auf die gleiche Weise wie für andere FastAPI-Endpunkte/*Pfadoperationen*: + +{* ../../docs_src/websockets/tutorial002_an_py310.py hl[68:69,82] *} + +/// info + +Da es sich um einen WebSocket handelt, macht es keinen Sinn, eine `HTTPException` auszulösen, stattdessen lösen wir eine `WebSocketException` aus. + +Sie können einen „Closing“-Code verwenden, aus den gültigen Codes, die in der Spezifikation definiert sind. + +/// + +### WebSockets mit Abhängigkeiten ausprobieren + +Wenn Ihre Datei `main.py` heißt, führen Sie Ihre Anwendung mit Folgendem aus: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Öffnen Sie Ihren Browser unter http://127.0.0.1:8000. + +Dort können Sie einstellen: + +* Die „Item ID“, die im Pfad verwendet wird. +* Das „Token“, das als Query-Parameter verwendet wird. + +/// tip | Tipp + +Beachten Sie, dass der Query-„Token“ von einer Abhängigkeit verarbeitet wird. + +/// + +Damit können Sie den WebSocket verbinden und dann Nachrichten senden und empfangen: + + + +## Verbindungsabbrüche und mehreren Clients handhaben + +Wenn eine WebSocket-Verbindung geschlossen wird, löst `await websocket.receive_text()` eine `WebSocketDisconnect`-Exception aus, die Sie dann wie in folgendem Beispiel abfangen und behandeln können. + +{* ../../docs_src/websockets/tutorial003_py39.py hl[79:81] *} + +Zum Ausprobieren: + +* Öffnen Sie die Anwendung mit mehreren Browser-Tabs. +* Schreiben Sie Nachrichten in den Tabs. +* Schließen Sie dann einen der Tabs. + +Das wird die Ausnahme `WebSocketDisconnect` auslösen und alle anderen Clients erhalten eine Nachricht wie: + +``` +Client #1596980209979 left the chat +``` + +/// tip | Tipp + +Die obige Anwendung ist ein minimales und einfaches Beispiel, das zeigt, wie Nachrichten verarbeitet und an mehrere WebSocket-Verbindungen gesendet werden. + +Beachten Sie jedoch, dass, da alles nur im Speicher in einer einzigen Liste verwaltet wird, es nur funktioniert, während der Prozess ausgeführt wird, und nur mit einem einzelnen Prozess. + +Wenn Sie etwas benötigen, das sich leicht in FastAPI integrieren lässt, aber robuster ist und von Redis, PostgreSQL und anderen unterstützt wird, sehen Sie sich encode/broadcaster an. + +/// + +## Mehr Informationen + +Weitere Informationen zu Optionen finden Sie in der Dokumentation von Starlette: + +* Die `WebSocket`-Klasse. +* Klassen-basierte Handhabung von WebSockets. diff --git a/docs/de/docs/advanced/wsgi.md b/docs/de/docs/advanced/wsgi.md new file mode 100644 index 000000000..c0998a621 --- /dev/null +++ b/docs/de/docs/advanced/wsgi.md @@ -0,0 +1,35 @@ +# WSGI inkludieren – Flask, Django und andere + +Sie können WSGI-Anwendungen mounten, wie Sie es in [Unteranwendungen – Mounts](sub-applications.md){.internal-link target=_blank}, [Hinter einem Proxy](behind-a-proxy.md){.internal-link target=_blank} gesehen haben. + +Dazu können Sie die `WSGIMiddleware` verwenden und damit Ihre WSGI-Anwendung wrappen, zum Beispiel Flask, Django usw. + +## `WSGIMiddleware` verwenden + +Sie müssen `WSGIMiddleware` importieren. + +Wrappen Sie dann die WSGI-Anwendung (z. B. Flask) mit der Middleware. + +Und dann mounten Sie das auf einem Pfad. + +{* ../../docs_src/wsgi/tutorial001.py hl[2:3,23] *} + +## Es ansehen + +Jetzt wird jede Anfrage unter dem Pfad `/v1/` von der Flask-Anwendung verarbeitet. + +Und der Rest wird von **FastAPI** gehandhabt. + +Wenn Sie das mit Uvicorn ausführen und auf http://localhost:8000/v1/ gehen, sehen Sie die Response von Flask: + +```txt +Hello, World from Flask! +``` + +Und wenn Sie auf http://localhost:8000/v2 gehen, sehen Sie die Response von FastAPI: + +```JSON +{ + "message": "Hello World" +} +``` diff --git a/docs/de/docs/alternatives.md b/docs/de/docs/alternatives.md new file mode 100644 index 000000000..611315501 --- /dev/null +++ b/docs/de/docs/alternatives.md @@ -0,0 +1,485 @@ +# Alternativen, Inspiration und Vergleiche + +Was hat **FastAPI** inspiriert, ein Vergleich zu Alternativen, und was FastAPI von diesen gelernt hat. + +## Einführung + +**FastAPI** würde ohne die frühere Arbeit anderer nicht existieren. + +Es wurden zuvor viele Tools entwickelt, die als Inspiration für seine Entwicklung dienten. + +Ich habe die Schaffung eines neuen Frameworks viele Jahre lang vermieden. Zuerst habe ich versucht, alle von **FastAPI** abgedeckten Funktionen mithilfe vieler verschiedener Frameworks, Plugins und Tools zu lösen. + +Aber irgendwann gab es keine andere Möglichkeit, als etwas zu schaffen, das all diese Funktionen bereitstellte, die besten Ideen früherer Tools aufnahm und diese auf die bestmögliche Weise kombinierte, wobei Sprachfunktionen verwendet wurden, die vorher noch nicht einmal verfügbar waren (Python 3.6+ Typhinweise). + +## Vorherige Tools + +### Django + +Es ist das beliebteste Python-Framework und genießt großes Vertrauen. Es wird zum Aufbau von Systemen wie Instagram verwendet. + +Ist relativ eng mit relationalen Datenbanken (wie MySQL oder PostgreSQL) gekoppelt, daher ist es nicht sehr einfach, eine NoSQL-Datenbank (wie Couchbase, MongoDB, Cassandra, usw.) als Hauptspeicherengine zu verwenden. + +Es wurde erstellt, um den HTML-Code im Backend zu generieren, nicht um APIs zu erstellen, die von einem modernen Frontend (wie React, Vue.js und Angular) oder von anderen Systemen (wie IoT-Geräten) verwendet werden, um mit ihm zu kommunizieren. + +### Django REST Framework + +Das Django REST Framework wurde als flexibles Toolkit zum Erstellen von Web-APIs unter Verwendung von Django entwickelt, um dessen API-Möglichkeiten zu verbessern. + +Es wird von vielen Unternehmen verwendet, darunter Mozilla, Red Hat und Eventbrite. + +Es war eines der ersten Beispiele für **automatische API-Dokumentation**, und dies war insbesondere eine der ersten Ideen, welche „die Suche nach“ **FastAPI** inspirierten. + +/// note | Hinweis + +Das Django REST Framework wurde von Tom Christie erstellt. Derselbe Schöpfer von Starlette und Uvicorn, auf denen **FastAPI** basiert. + +/// + +/// check | Inspirierte **FastAPI** + +Eine automatische API-Dokumentationsoberfläche zu haben. + +/// + +### Flask + +Flask ist ein „Mikroframework“, es enthält weder Datenbankintegration noch viele der Dinge, die standardmäßig in Django enthalten sind. + +Diese Einfachheit und Flexibilität ermöglichen beispielsweise die Verwendung von NoSQL-Datenbanken als Hauptdatenspeichersystem. + +Da es sehr einfach ist, ist es relativ intuitiv zu erlernen, obwohl die Dokumentation an einigen Stellen etwas technisch wird. + +Es wird auch häufig für andere Anwendungen verwendet, die nicht unbedingt eine Datenbank, Benutzerverwaltung oder eine der vielen in Django enthaltenen Funktionen benötigen. Obwohl viele dieser Funktionen mit Plugins hinzugefügt werden können. + +Diese Entkopplung der Teile und die Tatsache, dass es sich um ein „Mikroframework“ handelt, welches so erweitert werden kann, dass es genau das abdeckt, was benötigt wird, war ein Schlüsselmerkmal, das ich beibehalten wollte. + +Angesichts der Einfachheit von Flask schien es eine gute Ergänzung zum Erstellen von APIs zu sein. Als Nächstes musste ein „Django REST Framework“ für Flask gefunden werden. + +/// check | Inspirierte **FastAPI** + +Ein Mikroframework zu sein. Es einfach zu machen, die benötigten Tools und Teile zu kombinieren. + +Über ein einfaches und benutzerfreundliches Routingsystem zu verfügen. + +/// + +### Requests + +**FastAPI** ist eigentlich keine Alternative zu **Requests**. Der Umfang der beiden ist sehr unterschiedlich. + +Es wäre tatsächlich üblich, Requests *innerhalb* einer FastAPI-Anwendung zu verwenden. + +Dennoch erhielt FastAPI von Requests einiges an Inspiration. + +**Requests** ist eine Bibliothek zur *Interaktion* mit APIs (als Client), während **FastAPI** eine Bibliothek zum *Erstellen* von APIs (als Server) ist. + +Die beiden stehen mehr oder weniger an entgegengesetzten Enden und ergänzen sich. + +Requests hat ein sehr einfaches und intuitives Design, ist sehr einfach zu bedienen und verfügt über sinnvolle Standardeinstellungen. Aber gleichzeitig ist es sehr leistungsstark und anpassbar. + +Aus diesem Grund heißt es auf der offiziellen Website: + +> Requests ist eines der am häufigsten heruntergeladenen Python-Packages aller Zeiten + +Die Art und Weise, wie Sie es verwenden, ist sehr einfach. Um beispielsweise einen `GET`-Request zu machen, würden Sie schreiben: + +```Python +response = requests.get("http://example.com/some/url") +``` + +Die entsprechende *Pfadoperation* der FastAPI-API könnte wie folgt aussehen: + +```Python hl_lines="1" +@app.get("/some/url") +def read_url(): + return {"message": "Hello World"} +``` + +Sehen Sie sich die Ähnlichkeiten in `requests.get(...)` und `@app.get(...)` an. + +/// check | Inspirierte **FastAPI** + +* Über eine einfache und intuitive API zu verfügen. +* HTTP-Methodennamen (Operationen) direkt, auf einfache und intuitive Weise zu verwenden. +* Vernünftige Standardeinstellungen zu haben, aber auch mächtige Einstellungsmöglichkeiten. + +/// + +### Swagger / OpenAPI + +Die Hauptfunktion, die ich vom Django REST Framework haben wollte, war die automatische API-Dokumentation. + +Dann fand ich heraus, dass es einen Standard namens Swagger gab, zur Dokumentation von APIs unter Verwendung von JSON (oder YAML, einer Erweiterung von JSON). + +Und es gab bereits eine Web-Oberfläche für Swagger-APIs. Die Möglichkeit, Swagger-Dokumentation für eine API zu generieren, würde die automatische Nutzung dieser Web-Oberfläche ermöglichen. + +Irgendwann wurde Swagger an die Linux Foundation übergeben und in OpenAPI umbenannt. + +Aus diesem Grund spricht man bei Version 2.0 häufig von „Swagger“ und ab Version 3 von „OpenAPI“. + +/// check | Inspirierte **FastAPI** + +Einen offenen Standard für API-Spezifikationen zu übernehmen und zu verwenden, anstelle eines benutzerdefinierten Schemas. + +Und Standard-basierte Tools für die Oberfläche zu integrieren: + +* Swagger UI +* ReDoc + +Diese beiden wurden ausgewählt, weil sie ziemlich beliebt und stabil sind, aber bei einer schnellen Suche könnten Sie Dutzende alternativer Benutzeroberflächen für OpenAPI finden (welche Sie mit **FastAPI** verwenden können). + +/// + +### Flask REST Frameworks + +Es gibt mehrere Flask REST Frameworks, aber nachdem ich die Zeit und Arbeit investiert habe, sie zu untersuchen, habe ich festgestellt, dass viele nicht mehr unterstützt werden oder abgebrochen wurden und dass mehrere fortbestehende Probleme sie unpassend machten. + +### Marshmallow + +Eine der von API-Systemen benötigen Hauptfunktionen ist die Daten-„Serialisierung“, welche Daten aus dem Code (Python) entnimmt und in etwas umwandelt, was durch das Netzwerk gesendet werden kann. Beispielsweise das Konvertieren eines Objekts, welches Daten aus einer Datenbank enthält, in ein JSON-Objekt. Konvertieren von `datetime`-Objekten in Strings, usw. + +Eine weitere wichtige Funktion, benötigt von APIs, ist die Datenvalidierung, welche sicherstellt, dass die Daten unter gegebenen Umständen gültig sind. Zum Beispiel, dass ein Feld ein `int` ist und kein zufälliger String. Das ist besonders nützlich für hereinkommende Daten. + +Ohne ein Datenvalidierungssystem müssten Sie alle Prüfungen manuell im Code durchführen. + +Für diese Funktionen wurde Marshmallow entwickelt. Es ist eine großartige Bibliothek und ich habe sie schon oft genutzt. + +Aber sie wurde erstellt, bevor Typhinweise in Python existierten. Um also ein Schema zu definieren, müssen Sie bestimmte Werkzeuge und Klassen verwenden, die von Marshmallow bereitgestellt werden. + +/// check | Inspirierte **FastAPI** + +Code zu verwenden, um „Schemas“ zu definieren, welche Datentypen und Validierung automatisch bereitstellen. + +/// + +### Webargs + +Eine weitere wichtige Funktion, die von APIs benötigt wird, ist das Parsen von Daten aus eingehenden Requests. + +Webargs wurde entwickelt, um dieses für mehrere Frameworks, einschließlich Flask, bereitzustellen. + +Es verwendet unter der Haube Marshmallow, um die Datenvalidierung durchzuführen. Und es wurde von denselben Entwicklern erstellt. + +Es ist ein großartiges Tool und ich habe es auch oft verwendet, bevor ich **FastAPI** hatte. + +/// info + +Webargs wurde von denselben Marshmallow-Entwicklern erstellt. + +/// + +/// check | Inspirierte **FastAPI** + +Eingehende Requestdaten automatisch zu validieren. + +/// + +### APISpec + +Marshmallow und Webargs bieten Validierung, Parsen und Serialisierung als Plugins. + +Es fehlt jedoch noch die Dokumentation. Dann wurde APISpec erstellt. + +Es ist ein Plugin für viele Frameworks (und es gibt auch ein Plugin für Starlette). + +Die Funktionsweise besteht darin, dass Sie die Definition des Schemas im YAML-Format im Docstring jeder Funktion schreiben, die eine Route verarbeitet. + +Und es generiert OpenAPI-Schemas. + +So funktioniert es in Flask, Starlette, Responder, usw. + +Aber dann haben wir wieder das Problem einer Mikrosyntax innerhalb eines Python-Strings (eines großen YAML). + +Der Texteditor kann dabei nicht viel helfen. Und wenn wir Parameter oder Marshmallow-Schemas ändern und vergessen, auch den YAML-Docstring zu ändern, wäre das generierte Schema veraltet. + +/// info + +APISpec wurde von denselben Marshmallow-Entwicklern erstellt. + +/// + +/// check | Inspirierte **FastAPI** + +Den offenen Standard für APIs, OpenAPI, zu unterstützen. + +/// + +### Flask-apispec + +Hierbei handelt es sich um ein Flask-Plugin, welches Webargs, Marshmallow und APISpec miteinander verbindet. + +Es nutzt die Informationen von Webargs und Marshmallow, um mithilfe von APISpec automatisch OpenAPI-Schemas zu generieren. + +Ein großartiges Tool, sehr unterbewertet. Es sollte weitaus populärer als viele andere Flask-Plugins sein. Möglicherweise liegt es daran, dass die Dokumentation zu kompakt und abstrakt ist. + +Das löste das Problem, YAML (eine andere Syntax) in Python-Docstrings schreiben zu müssen. + +Diese Kombination aus Flask, Flask-apispec mit Marshmallow und Webargs war bis zur Entwicklung von **FastAPI** mein Lieblings-Backend-Stack. + +Die Verwendung führte zur Entwicklung mehrerer Flask-Full-Stack-Generatoren. Dies sind die Hauptstacks, die ich (und mehrere externe Teams) bisher verwendet haben: + +* https://github.com/tiangolo/full-stack +* https://github.com/tiangolo/full-stack-flask-couchbase +* https://github.com/tiangolo/full-stack-flask-couchdb + +Und dieselben Full-Stack-Generatoren bildeten die Basis der [**FastAPI**-Projektgeneratoren](project-generation.md){.internal-link target=_blank}. + +/// info + +Flask-apispec wurde von denselben Marshmallow-Entwicklern erstellt. + +/// + +/// check | Inspirierte **FastAPI** + +Das OpenAPI-Schema automatisch zu generieren, aus demselben Code, welcher die Serialisierung und Validierung definiert. + +/// + +### NestJS (und Angular) + +Dies ist nicht einmal Python, NestJS ist ein von Angular inspiriertes JavaScript (TypeScript) NodeJS Framework. + +Es erreicht etwas Ähnliches wie Flask-apispec. + +Es verfügt über ein integriertes Dependency Injection System, welches von Angular 2 inspiriert ist. Erfordert ein Vorab-Registrieren der „Injectables“ (wie alle anderen Dependency Injection Systeme, welche ich kenne), sodass der Code ausschweifender wird und es mehr Codeverdoppelung gibt. + +Da die Parameter mit TypeScript-Typen beschrieben werden (ähnlich den Python-Typhinweisen), ist die Editorunterstützung ziemlich gut. + +Da TypeScript-Daten jedoch nach der Kompilierung nach JavaScript nicht erhalten bleiben, können die Typen nicht gleichzeitig die Validierung, Serialisierung und Dokumentation definieren. Aus diesem Grund und aufgrund einiger Designentscheidungen ist es für die Validierung, Serialisierung und automatische Schemagenerierung erforderlich, an vielen Stellen Dekoratoren hinzuzufügen. Es wird also ziemlich ausführlich. + +Es kann nicht sehr gut mit verschachtelten Modellen umgehen. Wenn es sich beim JSON-Body in der Anfrage also um ein JSON-Objekt mit inneren Feldern handelt, die wiederum verschachtelte JSON-Objekte sind, kann er nicht richtig dokumentiert und validiert werden. + +/// check | Inspirierte **FastAPI** + +Python-Typen zu verwenden, um eine hervorragende Editorunterstützung zu erhalten. + +Über ein leistungsstarkes Dependency Injection System zu verfügen. Eine Möglichkeit zu finden, Codeverdoppelung zu minimieren. + +/// + +### Sanic + +Es war eines der ersten extrem schnellen Python-Frameworks, welches auf `asyncio` basierte. Es wurde so gestaltet, dass es Flask sehr ähnlich ist. + +/// note | Technische Details + +Es verwendete `uvloop` anstelle der standardmäßigen Python-`asyncio`-Schleife. Das hat es so schnell gemacht. + +Hat eindeutig Uvicorn und Starlette inspiriert, welche derzeit in offenen Benchmarks schneller als Sanic sind. + +/// + +/// check | Inspirierte **FastAPI** + +Einen Weg zu finden, eine hervorragende Performanz zu haben. + +Aus diesem Grund basiert **FastAPI** auf Starlette, da dieses das schnellste verfügbare Framework ist (getestet in Benchmarks von Dritten). + +/// + +### Falcon + +Falcon ist ein weiteres leistungsstarkes Python-Framework. Es ist minimalistisch konzipiert und dient als Grundlage für andere Frameworks wie Hug. + +Es ist so konzipiert, dass es über Funktionen verfügt, welche zwei Parameter empfangen, einen „Request“ und eine „Response“. Dann „lesen“ Sie Teile des Requests und „schreiben“ Teile der Response. Aufgrund dieses Designs ist es nicht möglich, Request-Parameter und -Bodys mit Standard-Python-Typhinweisen als Funktionsparameter zu deklarieren. + +Daher müssen Datenvalidierung, Serialisierung und Dokumentation im Code und nicht automatisch erfolgen. Oder sie müssen als Framework oberhalb von Falcon implementiert werden, so wie Hug. Dieselbe Unterscheidung findet auch in anderen Frameworks statt, die vom Design von Falcon inspiriert sind und ein Requestobjekt und ein Responseobjekt als Parameter haben. + +/// check | Inspirierte **FastAPI** + +Wege zu finden, eine großartige Performanz zu erzielen. + +Zusammen mit Hug (da Hug auf Falcon basiert), einen `response`-Parameter in Funktionen zu deklarieren. + +Obwohl er in FastAPI optional ist und hauptsächlich zum Festlegen von Headern, Cookies und alternativen Statuscodes verwendet wird. + +/// + +### Molten + +Ich habe Molten in den ersten Phasen der Entwicklung von **FastAPI** entdeckt. Und es hat ganz ähnliche Ideen: + +* Basierend auf Python-Typhinweisen. +* Validierung und Dokumentation aus diesen Typen. +* Dependency Injection System. + +Es verwendet keine Datenvalidierungs-, Serialisierungs- und Dokumentationsbibliothek eines Dritten wie Pydantic, sondern verfügt über eine eigene. Daher wären diese Datentyp-Definitionen nicht so einfach wiederverwendbar. + +Es erfordert eine etwas ausführlichere Konfiguration. Und da es auf WSGI (anstelle von ASGI) basiert, ist es nicht darauf ausgelegt, die hohe Leistung von Tools wie Uvicorn, Starlette und Sanic zu nutzen. + +Das Dependency Injection System erfordert eine Vorab-Registrierung der Abhängigkeiten und die Abhängigkeiten werden basierend auf den deklarierten Typen aufgelöst. Daher ist es nicht möglich, mehr als eine „Komponente“ zu deklarieren, welche einen bestimmten Typ bereitstellt. + +Routen werden an einer einzigen Stelle deklariert, indem Funktionen verwendet werden, die an anderen Stellen deklariert wurden (anstatt Dekoratoren zu verwenden, welche direkt über der Funktion platziert werden können, welche den Endpunkt verarbeitet). Dies ähnelt eher der Vorgehensweise von Django als der Vorgehensweise von Flask (und Starlette). Es trennt im Code Dinge, die relativ eng miteinander gekoppelt sind. + +/// check | Inspirierte **FastAPI** + +Zusätzliche Validierungen für Datentypen zu definieren, mithilfe des „Default“-Werts von Modellattributen. Dies verbessert die Editorunterstützung und war zuvor in Pydantic nicht verfügbar. + +Das hat tatsächlich dazu geführt, dass Teile von Pydantic aktualisiert wurden, um denselben Validierungsdeklarationsstil zu unterstützen (diese gesamte Funktionalität ist jetzt bereits in Pydantic verfügbar). + +/// + +### Hug + +Hug war eines der ersten Frameworks, welches die Deklaration von API-Parametertypen mithilfe von Python-Typhinweisen implementierte. Das war eine großartige Idee, die andere Tools dazu inspirierte, dasselbe zu tun. + +Es verwendete benutzerdefinierte Typen in seinen Deklarationen anstelle von Standard-Python-Typen, es war aber dennoch ein großer Fortschritt. + +Außerdem war es eines der ersten Frameworks, welches ein benutzerdefiniertes Schema generierte, welches die gesamte API in JSON deklarierte. + +Es basierte nicht auf einem Standard wie OpenAPI und JSON Schema. Daher wäre es nicht einfach, es in andere Tools wie Swagger UI zu integrieren. Aber, nochmal, es war eine sehr innovative Idee. + +Es verfügt über eine interessante, ungewöhnliche Funktion: Mit demselben Framework ist es möglich, APIs und auch CLIs zu erstellen. + +Da es auf dem bisherigen Standard für synchrone Python-Webframeworks (WSGI) basiert, kann es nicht mit Websockets und anderen Dingen umgehen, verfügt aber dennoch über eine hohe Performanz. + +/// info + +Hug wurde von Timothy Crosley erstellt, dem gleichen Schöpfer von `isort`, einem großartigen Tool zum automatischen Sortieren von Importen in Python-Dateien. + +/// + +/// check | Ideen, die **FastAPI** inspiriert haben + +Hug inspirierte Teile von APIStar und war eines der Tools, die ich am vielversprechendsten fand, neben APIStar. + +Hug hat dazu beigetragen, **FastAPI** dazu zu inspirieren, Python-Typhinweise zum Deklarieren von Parametern zu verwenden und ein Schema zu generieren, das die API automatisch definiert. + +Hug inspirierte **FastAPI** dazu, einen `response`-Parameter in Funktionen zu deklarieren, um Header und Cookies zu setzen. + +/// + +### APIStar (≦ 0.5) + +Kurz bevor ich mich entschied, **FastAPI** zu erstellen, fand ich den **APIStar**-Server. Er hatte fast alles, was ich suchte, und ein tolles Design. + +Er war eine der ersten Implementierungen eines Frameworks, die ich je gesehen hatte (vor NestJS und Molten), welches Python-Typhinweise zur Deklaration von Parametern und Requests verwendeten. Ich habe ihn mehr oder weniger zeitgleich mit Hug gefunden. Aber APIStar nutzte den OpenAPI-Standard. + +Er verfügte an mehreren Stellen über automatische Datenvalidierung, Datenserialisierung und OpenAPI-Schemagenerierung, basierend auf denselben Typhinweisen. + +Body-Schemadefinitionen verwendeten nicht die gleichen Python-Typhinweise wie Pydantic, er war Marshmallow etwas ähnlicher, sodass die Editorunterstützung nicht so gut war, aber dennoch war APIStar die beste verfügbare Option. + +Er hatte zu dieser Zeit die besten Leistungsbenchmarks (nur übertroffen von Starlette). + +Anfangs gab es keine Web-Oberfläche für die automatische API-Dokumentation, aber ich wusste, dass ich Swagger UI hinzufügen konnte. + +Er verfügte über ein Dependency Injection System. Es erforderte eine Vorab-Registrierung der Komponenten, wie auch bei anderen oben besprochenen Tools. Aber dennoch, es war ein tolles Feature. + +Ich konnte ihn nie in einem vollständigen Projekt verwenden, da er keine Sicherheitsintegration hatte, sodass ich nicht alle Funktionen, die ich hatte, durch die auf Flask-apispec basierenden Full-Stack-Generatoren ersetzen konnte. Ich hatte in meinem Projekte-Backlog den Eintrag, einen Pull Request zu erstellen, welcher diese Funktionalität hinzufügte. + +Doch dann verlagerte sich der Schwerpunkt des Projekts. + +Es handelte sich nicht länger um ein API-Webframework, da sich der Entwickler auf Starlette konzentrieren musste. + +Jetzt handelt es sich bei APIStar um eine Reihe von Tools zur Validierung von OpenAPI-Spezifikationen, nicht um ein Webframework. + +/// info + +APIStar wurde von Tom Christie erstellt. Derselbe, welcher Folgendes erstellt hat: + +* Django REST Framework +* Starlette (auf welchem **FastAPI** basiert) +* Uvicorn (verwendet von Starlette und **FastAPI**) + +/// + +/// check | Inspirierte **FastAPI** + +Zu existieren. + +Die Idee, mehrere Dinge (Datenvalidierung, Serialisierung und Dokumentation) mit denselben Python-Typen zu deklarieren, welche gleichzeitig eine hervorragende Editorunterstützung bieten, hielt ich für eine brillante Idee. + +Und nach einer langen Suche nach einem ähnlichen Framework und dem Testen vieler verschiedener Alternativen, war APIStar die beste verfügbare Option. + +Dann hörte APIStar auf, als Server zu existieren, und Starlette wurde geschaffen, welches eine neue, bessere Grundlage für ein solches System bildete. Das war die finale Inspiration für die Entwicklung von **FastAPI**. + +Ich betrachte **FastAPI** als einen „spirituellen Nachfolger“ von APIStar, welcher die Funktionen, das Typsystem und andere Teile verbessert und erweitert, basierend auf den Erkenntnissen aus all diesen früheren Tools. + +/// + +## Verwendet von **FastAPI** + +### Pydantic + +Pydantic ist eine Bibliothek zum Definieren von Datenvalidierung, Serialisierung und Dokumentation (unter Verwendung von JSON Schema) basierend auf Python-Typhinweisen. + +Das macht es äußerst intuitiv. + +Es ist vergleichbar mit Marshmallow. Obwohl es in Benchmarks schneller als Marshmallow ist. Und da es auf den gleichen Python-Typhinweisen basiert, ist die Editorunterstützung großartig. + +/// check | **FastAPI** verwendet es, um + +Die gesamte Datenvalidierung, Datenserialisierung und automatische Modelldokumentation (basierend auf JSON Schema) zu erledigen. + +**FastAPI** nimmt dann, abgesehen von all den anderen Dingen, die es tut, dieses JSON-Schema und fügt es in OpenAPI ein. + +/// + +### Starlette + +Starlette ist ein leichtgewichtiges ASGI-Framework/Toolkit, welches sich ideal für die Erstellung hochperformanter asynchroner Dienste eignet. + +Es ist sehr einfach und intuitiv. Es ist so konzipiert, dass es leicht erweiterbar ist und über modulare Komponenten verfügt. + +Es bietet: + +* Eine sehr beeindruckende Leistung. +* WebSocket-Unterstützung. +* Hintergrundtasks im selben Prozess. +* Events für das Hoch- und Herunterfahren. +* Testclient basierend auf HTTPX. +* CORS, GZip, statische Dateien, Streamende Responses. +* Session- und Cookie-Unterstützung. +* 100 % Testabdeckung. +* 100 % Typannotierte Codebasis. +* Wenige starke Abhängigkeiten. + +Starlette ist derzeit das schnellste getestete Python-Framework. Nur übertroffen von Uvicorn, welches kein Framework, sondern ein Server ist. + +Starlette bietet alle grundlegenden Funktionen eines Web-Microframeworks. + +Es bietet jedoch keine automatische Datenvalidierung, Serialisierung oder Dokumentation. + +Das ist eines der wichtigsten Dinge, welche **FastAPI** hinzufügt, alles basierend auf Python-Typhinweisen (mit Pydantic). Das, plus, das Dependency Injection System, Sicherheitswerkzeuge, OpenAPI-Schemagenerierung, usw. + +/// note | Technische Details + +ASGI ist ein neuer „Standard“, welcher von Mitgliedern des Django-Kernteams entwickelt wird. Es handelt sich immer noch nicht um einen „Python-Standard“ (ein PEP), obwohl sie gerade dabei sind, das zu tun. + +Dennoch wird es bereits von mehreren Tools als „Standard“ verwendet. Das verbessert die Interoperabilität erheblich, da Sie Uvicorn mit jeden anderen ASGI-Server (wie Daphne oder Hypercorn) tauschen oder ASGI-kompatible Tools wie `python-socketio` hinzufügen können. + +/// + +/// check | **FastAPI** verwendet es, um + +Alle Kern-Webaspekte zu handhaben. Und fügt Funktionen obenauf. + +Die Klasse `FastAPI` selbst erbt direkt von der Klasse `Starlette`. + +Alles, was Sie also mit Starlette machen können, können Sie direkt mit **FastAPI** machen, da es sich im Grunde um Starlette auf Steroiden handelt. + +/// + +### Uvicorn + +Uvicorn ist ein blitzschneller ASGI-Server, der auf uvloop und httptools basiert. + +Es handelt sich nicht um ein Webframework, sondern um einen Server. Beispielsweise werden keine Tools für das Routing von Pfaden bereitgestellt. Das ist etwas, was ein Framework wie Starlette (oder **FastAPI**) zusätzlich bieten würde. + +Es ist der empfohlene Server für Starlette und **FastAPI**. + +/// check | **FastAPI** empfiehlt es als + +Hauptwebserver zum Ausführen von **FastAPI**-Anwendungen. + +Sie können ihn mit Gunicorn kombinieren, um einen asynchronen Multiprozess-Server zu erhalten. + +Weitere Details finden Sie im Abschnitt [Deployment](deployment/index.md){.internal-link target=_blank}. + +/// + +## Benchmarks und Geschwindigkeit + +Um den Unterschied zwischen Uvicorn, Starlette und FastAPI zu verstehen, zu vergleichen und zu sehen, lesen Sie den Abschnitt über [Benchmarks](benchmarks.md){.internal-link target=_blank}. diff --git a/docs/de/docs/async.md b/docs/de/docs/async.md new file mode 100644 index 000000000..b5b3a4c52 --- /dev/null +++ b/docs/de/docs/async.md @@ -0,0 +1,442 @@ +# Nebenläufigkeit und async / await + +Details zur `async def`-Syntax für *Pfadoperation-Funktionen* und Hintergrundinformationen zu asynchronem Code, Nebenläufigkeit und Parallelität. + +## In Eile? + +TL;DR: + +Wenn Sie Bibliotheken von Dritten verwenden, die mit `await` aufgerufen werden müssen, wie zum Beispiel: + +```Python +results = await some_library() +``` + +Dann deklarieren Sie Ihre *Pfadoperation-Funktionen* mit `async def` wie in: + +```Python hl_lines="2" +@app.get('/') +async def read_results(): + results = await some_library() + return results +``` + +/// note + +Sie können `await` nur innerhalb von Funktionen verwenden, die mit `async def` erstellt wurden. + +/// + +--- + +Wenn Sie eine Bibliothek eines Dritten verwenden, die mit etwas kommuniziert (einer Datenbank, einer API, dem Dateisystem, usw.) und welche die Verwendung von `await` nicht unterstützt (dies ist derzeit bei den meisten Datenbankbibliotheken der Fall), dann deklarieren Sie Ihre *Pfadoperation-Funktionen* ganz normal nur mit `def`, etwa: + +```Python hl_lines="2" +@app.get('/') +def results(): + results = some_library() + return results +``` + +--- + +Wenn Ihre Anwendung (irgendwie) mit nichts anderem kommunizieren und auf dessen Antwort warten muss, verwenden Sie `async def`. + +--- + +Wenn Sie sich unsicher sind, verwenden Sie einfach `def`. + +--- + +**Hinweis**: Sie können `def` und `async def` in Ihren *Pfadoperation-Funktionen* beliebig mischen, so wie Sie es benötigen, und jede einzelne Funktion in der für Sie besten Variante erstellen. FastAPI wird damit das Richtige tun. + +Wie dem auch sei, in jedem der oben genannten Fälle wird FastAPI immer noch asynchron arbeiten und extrem schnell sein. + +Wenn Sie jedoch den oben genannten Schritten folgen, können einige Performance-Optimierungen vorgenommen werden. + +## Technische Details + +Moderne Versionen von Python unterstützen **„asynchronen Code“** unter Verwendung sogenannter **„Coroutinen“** mithilfe der Syntax **`async`** und **`await`**. + +Nehmen wir obigen Satz in den folgenden Abschnitten Schritt für Schritt unter die Lupe: + +* **Asynchroner Code** +* **`async` und `await`** +* **Coroutinen** + +## Asynchroner Code + +Asynchroner Code bedeutet lediglich, dass die Sprache 💬 eine Möglichkeit hat, dem Computersystem / Programm 🤖 mitzuteilen, dass es 🤖 an einem bestimmten Punkt im Code darauf warten muss, dass *etwas anderes* irgendwo anders fertig wird. Nehmen wir an, *etwas anderes* ist hier „Langsam-Datei“ 📝. + +Während der Zeit, die „Langsam-Datei“ 📝 benötigt, kann das System also andere Aufgaben erledigen. + +Dann kommt das System / Programm 🤖 bei jeder Gelegenheit zurück, wenn es entweder wieder wartet, oder wann immer es 🤖 die ganze Arbeit erledigt hat, die zu diesem Zeitpunkt zu tun war. Und es 🤖 wird nachschauen, ob eine der Aufgaben, auf die es gewartet hat, fertig damit ist, zu tun, was sie tun sollte. + +Dann nimmt es 🤖 die erste erledigte Aufgabe (sagen wir, unsere „Langsam-Datei“ 📝) und bearbeitet sie weiter. + +Das „Warten auf etwas anderes“ bezieht sich normalerweise auf I/O-Operationen, die relativ „langsam“ sind (im Vergleich zur Geschwindigkeit des Prozessors und des Arbeitsspeichers), wie etwa das Warten darauf, dass: + +* die Daten des Clients über das Netzwerk empfangen wurden +* die von Ihrem Programm gesendeten Daten vom Client über das Netzwerk empfangen wurden +* der Inhalt einer Datei vom System von der Festplatte gelesen und an Ihr Programm übergeben wurde +* der Inhalt, den Ihr Programm dem System übergeben hat, auf die Festplatte geschrieben wurde +* eine Remote-API-Operation beendet wurde +* Eine Datenbankoperation abgeschlossen wurde +* eine Datenbankabfrage die Ergebnisse zurückgegeben hat +* usw. + +Da die Ausführungszeit hier hauptsächlich durch das Warten auf I/O-Operationen verbraucht wird, nennt man dies auch „I/O-lastige“ („I/O bound“) Operationen. + +„Asynchron“, sagt man, weil das Computersystem / Programm nicht mit einer langsamen Aufgabe „synchronisiert“ werden muss und nicht auf den genauen Moment warten muss, in dem die Aufgabe beendet ist, ohne dabei etwas zu tun, um schließlich das Ergebnis der Aufgabe zu übernehmen und die Arbeit fortsetzen zu können. + +Da es sich stattdessen um ein „asynchrones“ System handelt, kann die Aufgabe nach Abschluss ein wenig (einige Mikrosekunden) in der Schlange warten, bis das System / Programm seine anderen Dinge erledigt hat und zurückkommt, um die Ergebnisse entgegenzunehmen und mit ihnen weiterzuarbeiten. + +Für „synchron“ (im Gegensatz zu „asynchron“) wird auch oft der Begriff „sequentiell“ verwendet, da das System / Programm alle Schritte in einer Sequenz („der Reihe nach“) ausführt, bevor es zu einer anderen Aufgabe wechselt, auch wenn diese Schritte mit Warten verbunden sind. + +### Nebenläufigkeit und Hamburger + +Diese oben beschriebene Idee von **asynchronem** Code wird manchmal auch **„Nebenläufigkeit“** genannt. Sie unterscheidet sich von **„Parallelität“**. + +**Nebenläufigkeit** und **Parallelität** beziehen sich beide auf „verschiedene Dinge, die mehr oder weniger gleichzeitig passieren“. + +Aber die Details zwischen *Nebenläufigkeit* und *Parallelität* sind ziemlich unterschiedlich. + +Um den Unterschied zu erkennen, stellen Sie sich die folgende Geschichte über Hamburger vor: + +### Nebenläufige Hamburger + +Sie gehen mit Ihrem Schwarm Fastfood holen, stehen in der Schlange, während der Kassierer die Bestellungen der Leute vor Ihnen entgegennimmt. 😍 + + + +Dann sind Sie an der Reihe und Sie bestellen zwei sehr schmackhafte Burger für Ihren Schwarm und Sie. 🍔🍔 + + + +Der Kassierer sagt etwas zum Koch in der Küche, damit dieser weiß, dass er Ihre Burger zubereiten muss (obwohl er gerade die für die vorherigen Kunden zubereitet). + + + +Sie bezahlen. 💸 + +Der Kassierer gibt Ihnen die Nummer Ihrer Bestellung. + + + +Während Sie warten, suchen Sie sich mit Ihrem Schwarm einen Tisch aus, Sie sitzen da und reden lange mit Ihrem Schwarm (da Ihre Burger sehr aufwändig sind und die Zubereitung einige Zeit dauert). + +Während Sie mit Ihrem Schwarm am Tisch sitzen und auf die Burger warten, können Sie die Zeit damit verbringen, zu bewundern, wie großartig, süß und klug Ihr Schwarm ist ✨😍✨. + + + +Während Sie warten und mit Ihrem Schwarm sprechen, überprüfen Sie von Zeit zu Zeit die auf dem Zähler angezeigte Nummer, um zu sehen, ob Sie bereits an der Reihe sind. + +Dann, irgendwann, sind Sie endlich an der Reihe. Sie gehen zur Theke, holen sich die Burger und kommen zurück an den Tisch. + + + +Sie und Ihr Schwarm essen die Burger und haben eine schöne Zeit. ✨ + + + +/// info + +Die wunderschönen Illustrationen stammen von Ketrina Thompson. 🎨 + +/// + +--- + +Stellen Sie sich vor, Sie wären das Computersystem / Programm 🤖 in dieser Geschichte. + +Während Sie an der Schlange stehen, sind Sie einfach untätig 😴, warten darauf, dass Sie an die Reihe kommen, und tun nichts sehr „Produktives“. Aber die Schlange ist schnell abgearbeitet, weil der Kassierer nur die Bestellungen entgegennimmt (und nicht zubereitet), also ist das vertretbar. + +Wenn Sie dann an der Reihe sind, erledigen Sie tatsächliche „produktive“ Arbeit, Sie gehen das Menü durch, entscheiden sich, was Sie möchten, bekunden Ihre und die Wahl Ihres Schwarms, bezahlen, prüfen, ob Sie die richtige Menge Geld oder die richtige Karte geben, prüfen, ob die Rechnung korrekt ist, prüfen, dass die Bestellung die richtigen Artikel enthält, usw. + +Aber dann, auch wenn Sie Ihre Burger noch nicht haben, ist Ihre Interaktion mit dem Kassierer erst mal „auf Pause“ ⏸, weil Sie warten müssen 🕙, bis Ihre Burger fertig sind. + +Aber wenn Sie sich von der Theke entfernt haben und mit der Nummer für die Bestellung an einem Tisch sitzen, können Sie Ihre Aufmerksamkeit auf Ihren Schwarm lenken und an dieser Aufgabe „arbeiten“ ⏯ 🤓. Sie machen wieder etwas sehr „Produktives“ und flirten mit Ihrem Schwarm 😍. + +Dann sagt der Kassierer 💁 „Ich bin mit dem Burger fertig“, indem er Ihre Nummer auf dem Display über der Theke anzeigt, aber Sie springen nicht sofort wie verrückt auf, wenn das Display auf Ihre Nummer springt. Sie wissen, dass niemand Ihnen Ihre Burger wegnimmt, denn Sie haben die Nummer Ihrer Bestellung, und andere Leute haben andere Nummern. + +Also warten Sie darauf, dass Ihr Schwarm ihre Geschichte zu Ende erzählt (die aktuelle Arbeit ⏯ / bearbeitete Aufgabe beendet 🤓), lächeln sanft und sagen, dass Sie die Burger holen ⏸. + +Dann gehen Sie zur Theke 🔀, zur ursprünglichen Aufgabe, die nun erledigt ist ⏯, nehmen die Burger auf, sagen Danke, und bringen sie zum Tisch. Damit ist dieser Schritt / diese Aufgabe der Interaktion mit der Theke abgeschlossen ⏹. Das wiederum schafft eine neue Aufgabe, „Burger essen“ 🔀 ⏯, aber die vorherige Aufgabe „Burger holen“ ist erledigt ⏹. + +### Parallele Hamburger + +Stellen wir uns jetzt vor, dass es sich hierbei nicht um „nebenläufige Hamburger“, sondern um „parallele Hamburger“ handelt. + +Sie gehen los mit Ihrem Schwarm, um paralleles Fast Food zu bekommen. + +Sie stehen in der Schlange, während mehrere (sagen wir acht) Kassierer, die gleichzeitig Köche sind, die Bestellungen der Leute vor Ihnen entgegennehmen. + +Alle vor Ihnen warten darauf, dass ihre Burger fertig sind, bevor sie die Theke verlassen, denn jeder der 8 Kassierer geht los und bereitet den Burger sofort zu, bevor er die nächste Bestellung entgegennimmt. + + + +Dann sind Sie endlich an der Reihe und bestellen zwei sehr leckere Burger für Ihren Schwarm und Sie. + +Sie zahlen 💸. + + + +Der Kassierer geht in die Küche. + +Sie warten, vor der Theke stehend 🕙, damit niemand außer Ihnen Ihre Burger entgegennimmt, da es keine Nummern für die Reihenfolge gibt. + + + +Da Sie und Ihr Schwarm damit beschäftigt sind, niemanden vor sich zu lassen, der Ihre Burger nimmt, wenn sie ankommen, können Sie Ihrem Schwarm keine Aufmerksamkeit schenken. 😞 + +Das ist „synchrone“ Arbeit, Sie sind mit dem Kassierer/Koch „synchronisiert“ 👨‍🍳. Sie müssen warten 🕙 und genau in dem Moment da sein, in dem der Kassierer/Koch 👨‍🍳 die Burger zubereitet hat und Ihnen gibt, sonst könnte jemand anderes sie nehmen. + + + +Dann kommt Ihr Kassierer/Koch 👨‍🍳 endlich mit Ihren Burgern zurück, nachdem Sie lange vor der Theke gewartet 🕙 haben. + + + +Sie nehmen Ihre Burger und gehen mit Ihrem Schwarm an den Tisch. + +Sie essen sie und sind fertig. ⏹ + + + +Es wurde nicht viel geredet oder geflirtet, da die meiste Zeit mit Warten 🕙 vor der Theke verbracht wurde. 😞 + +/// info + +Die wunderschönen Illustrationen stammen von Ketrina Thompson. 🎨 + +/// + +--- + +In diesem Szenario der parallelen Hamburger sind Sie ein Computersystem / Programm 🤖 mit zwei Prozessoren (Sie und Ihr Schwarm), die beide warten 🕙 und ihre Aufmerksamkeit darauf verwenden, „lange Zeit vor der Theke zu warten“ 🕙. + +Der Fast-Food-Laden verfügt über 8 Prozessoren (Kassierer/Köche). Während der nebenläufige Burger-Laden nur zwei hatte (einen Kassierer und einen Koch). + +Dennoch ist das schlussendliche Benutzererlebnis nicht das Beste. 😞 + +--- + +Dies wäre die parallele äquivalente Geschichte für Hamburger. 🍔 + +Für ein „realeres“ Beispiel hierfür, stellen Sie sich eine Bank vor. + +Bis vor kurzem hatten die meisten Banken mehrere Kassierer 👨‍💼👨‍💼👨‍💼👨‍💼 und eine große Warteschlange 🕙🕙🕙🕙🕙🕙🕙🕙. + +Alle Kassierer erledigen die ganze Arbeit mit einem Kunden nach dem anderen 👨‍💼⏯. + +Und man muss lange in der Schlange warten 🕙 sonst kommt man nicht an die Reihe. + +Sie würden Ihren Schwarm 😍 wahrscheinlich nicht mitnehmen wollen, um Besorgungen bei der Bank zu erledigen 🏦. + +### Hamburger Schlussfolgerung + +In diesem Szenario „Fast Food Burger mit Ihrem Schwarm“ ist es viel sinnvoller, ein nebenläufiges System zu haben ⏸🔀⏯, da viel gewartet wird 🕙. + +Das ist auch bei den meisten Webanwendungen der Fall. + +Viele, viele Benutzer, aber Ihr Server wartet 🕙 darauf, dass deren nicht so gute Internetverbindungen die Requests übermitteln. + +Und dann warten 🕙, bis die Responses zurückkommen. + +Dieses „Warten“ 🕙 wird in Mikrosekunden gemessen, aber zusammenfassend lässt sich sagen, dass am Ende eine Menge gewartet wird. + +Deshalb ist es sehr sinnvoll, asynchronen ⏸🔀⏯ Code für Web-APIs zu verwenden. + +Diese Art der Asynchronität hat NodeJS populär gemacht (auch wenn NodeJS nicht parallel ist) und darin liegt die Stärke von Go als Programmiersprache. + +Und das ist das gleiche Leistungsniveau, das Sie mit **FastAPI** erhalten. + +Und da Sie Parallelität und Asynchronität gleichzeitig haben können, erzielen Sie eine höhere Performanz als die meisten getesteten NodeJS-Frameworks und sind mit Go auf Augenhöhe, einer kompilierten Sprache, die näher an C liegt (alles dank Starlette). + +### Ist Nebenläufigkeit besser als Parallelität? + +Nein! Das ist nicht die Moral der Geschichte. + +Nebenläufigkeit unterscheidet sich von Parallelität. Und sie ist besser bei **bestimmten** Szenarien, die viel Warten erfordern. Aus diesem Grund ist sie im Allgemeinen viel besser als Parallelität für die Entwicklung von Webanwendungen. Aber das stimmt nicht für alle Anwendungen. + +Um die Dinge auszugleichen, stellen Sie sich die folgende Kurzgeschichte vor: + +> Sie müssen ein großes, schmutziges Haus aufräumen. + +*Yup, das ist die ganze Geschichte*. + +--- + +Es gibt kein Warten 🕙, nur viel Arbeit an mehreren Stellen im Haus. + +Sie könnten wie im Hamburger-Beispiel hin- und herspringen, zuerst das Wohnzimmer, dann die Küche, aber da Sie auf nichts warten 🕙, sondern nur putzen und putzen, hätte das Hin- und Herspringen keine Auswirkungen. + +Es würde mit oder ohne Hin- und Herspringen (Nebenläufigkeit) die gleiche Zeit in Anspruch nehmen, um fertig zu werden, und Sie hätten die gleiche Menge an Arbeit erledigt. + +Aber wenn Sie in diesem Fall die acht Ex-Kassierer/Köche/jetzt Reinigungskräfte mitbringen würden und jeder von ihnen (plus Sie) würde einen Bereich des Hauses reinigen, könnten Sie die ganze Arbeit **parallel** erledigen, und würden mit dieser zusätzlichen Hilfe viel schneller fertig werden. + +In diesem Szenario wäre jede einzelne Reinigungskraft (einschließlich Ihnen) ein Prozessor, der seinen Teil der Arbeit erledigt. + +Und da die meiste Ausführungszeit durch tatsächliche Arbeit (anstatt durch Warten) in Anspruch genommen wird und die Arbeit in einem Computer von einer CPU erledigt wird, werden diese Probleme als „CPU-lastig“ („CPU bound“) bezeichnet. + +--- + +Typische Beispiele für CPU-lastige Vorgänge sind Dinge, die komplexe mathematische Berechnungen erfordern. + +Zum Beispiel: + +* **Audio-** oder **Bildbearbeitung**. +* **Computer Vision**: Ein Bild besteht aus Millionen von Pixeln, jedes Pixel hat 3 Werte / Farben, die Verarbeitung erfordert normalerweise, Berechnungen mit diesen Pixeln durchzuführen, alles zur gleichen Zeit. +* **Maschinelles Lernen**: Normalerweise sind viele „Matrix“- und „Vektor“-Multiplikationen erforderlich. Stellen Sie sich eine riesige Tabelle mit Zahlen vor, in der Sie alle Zahlen gleichzeitig multiplizieren. +* **Deep Learning**: Dies ist ein Teilgebiet des maschinellen Lernens, daher gilt das Gleiche. Es ist nur so, dass es nicht eine einzige Tabelle mit Zahlen zum Multiplizieren gibt, sondern eine riesige Menge davon, und in vielen Fällen verwendet man einen speziellen Prozessor, um diese Modelle zu erstellen und / oder zu verwenden. + +### Nebenläufigkeit + Parallelität: Web + maschinelles Lernen + +Mit **FastAPI** können Sie die Vorteile der Nebenläufigkeit nutzen, die in der Webentwicklung weit verbreitet ist (derselbe Hauptvorteil von NodeJS). + +Sie können aber auch die Vorteile von Parallelität und Multiprocessing (Mehrere Prozesse werden parallel ausgeführt) für **CPU-lastige** Workloads wie in Systemen für maschinelles Lernen nutzen. + +Dies und die einfache Tatsache, dass Python die Hauptsprache für **Data Science**, maschinelles Lernen und insbesondere Deep Learning ist, machen FastAPI zu einem sehr passenden Werkzeug für Web-APIs und Anwendungen für Data Science / maschinelles Lernen (neben vielen anderen). + +Wie Sie diese Parallelität in der Produktion erreichen, erfahren Sie im Abschnitt über [Deployment](deployment/index.md){.internal-link target=_blank}. + +## `async` und `await`. + +Moderne Versionen von Python verfügen über eine sehr intuitive Möglichkeit, asynchronen Code zu schreiben. Dadurch sieht es wie normaler „sequentieller“ Code aus und übernimmt im richtigen Moment das „Warten“ für Sie. + +Wenn es einen Vorgang gibt, der erfordert, dass gewartet wird, bevor die Ergebnisse zurückgegeben werden, und der diese neue Python-Funktionalität unterstützt, können Sie ihn wie folgt schreiben: + +```Python +burgers = await get_burgers(2) +``` + +Der Schlüssel hier ist das `await`. Es teilt Python mit, dass es warten ⏸ muss, bis `get_burgers(2)` seine Aufgabe erledigt hat 🕙, bevor die Ergebnisse in `burgers` gespeichert werden. Damit weiß Python, dass es in der Zwischenzeit etwas anderes tun kann 🔀 ⏯ (z. B. einen weiteren Request empfangen). + +Damit `await` funktioniert, muss es sich in einer Funktion befinden, die diese Asynchronität unterstützt. Dazu deklarieren Sie sie einfach mit `async def`: + +```Python hl_lines="1" +async def get_burgers(number: int): + # Mach Sie hier etwas Asynchrones, um die Burger zu erstellen + return burgers +``` + +... statt mit `def`: + +```Python hl_lines="2" +# Die ist nicht asynchron +def get_sequential_burgers(number: int): + # Mach Sie hier etwas Sequentielles, um die Burger zu erstellen + return burgers +``` + +Mit `async def` weiß Python, dass es innerhalb dieser Funktion auf `await`-Ausdrücke achten muss und dass es die Ausführung dieser Funktion „anhalten“ ⏸ und etwas anderes tun kann 🔀, bevor es zurückkommt. + +Wenn Sie eine `async def`-Funktion aufrufen möchten, müssen Sie sie „erwarten“ („await“). Das folgende wird also nicht funktionieren: + +```Python +# Das funktioniert nicht, weil get_burgers definiert wurde mit: async def +burgers = get_burgers(2) +``` + +--- + +Wenn Sie also eine Bibliothek verwenden, die Ihnen sagt, dass Sie sie mit `await` aufrufen können, müssen Sie die *Pfadoperation-Funktionen*, die diese Bibliothek verwenden, mittels `async def` erstellen, wie in: + +```Python hl_lines="2-3" +@app.get('/burgers') +async def read_burgers(): + burgers = await get_burgers(2) + return burgers +``` + +### Weitere technische Details + +Ihnen ist wahrscheinlich aufgefallen, dass `await` nur innerhalb von Funktionen verwendet werden kann, die mit `async def` definiert sind. + +Gleichzeitig müssen aber mit `async def` definierte Funktionen „erwartet“ („awaited“) werden. Daher können Funktionen mit `async def` nur innerhalb von Funktionen aufgerufen werden, die auch mit `async def` definiert sind. + +Daraus resultiert das Ei-und-Huhn-Problem: Wie ruft man die erste `async` Funktion auf? + +Wenn Sie mit **FastAPI** arbeiten, müssen Sie sich darüber keine Sorgen machen, da diese „erste“ Funktion Ihre *Pfadoperation-Funktion* sein wird und FastAPI weiß, was zu tun ist. + +Wenn Sie jedoch `async` / `await` ohne FastAPI verwenden möchten, können Sie dies auch tun. + +### Schreiben Sie Ihren eigenen asynchronen Code + +Starlette (und **FastAPI**) basiert auf AnyIO, was bedeutet, es ist sowohl kompatibel mit der Python-Standardbibliothek asyncio, als auch mit Trio. + +Insbesondere können Sie AnyIO direkt verwenden für Ihre fortgeschritten nebenläufigen und parallelen Anwendungsfälle, die fortgeschrittenere Muster in Ihrem eigenen Code erfordern. + +Und selbst wenn Sie FastAPI nicht verwenden würden, könnten Sie auch Ihre eigenen asynchronen Anwendungen mit AnyIO so schreiben, dass sie hoch kompatibel sind und Sie dessen Vorteile nutzen können (z. B. *strukturierte Nebenläufigkeit*). + +### Andere Formen von asynchronem Code + +Diese Art der Verwendung von `async` und `await` ist in der Sprache relativ neu. + +Aber sie erleichtert die Arbeit mit asynchronem Code erheblich. + +Die gleiche Syntax (oder fast identisch) wurde kürzlich auch in moderne Versionen von JavaScript (im Browser und in NodeJS) aufgenommen. + +Davor war der Umgang mit asynchronem Code jedoch deutlich komplexer und schwieriger. + +In früheren Versionen von Python hätten Sie Threads oder Gevent verwenden können. Der Code ist jedoch viel komplexer zu verstehen, zu debuggen und nachzuvollziehen. + +In früheren Versionen von NodeJS / Browser JavaScript hätten Sie „Callbacks“ verwendet. Was zur Callback-Hölle führt. + +## Coroutinen + +**Coroutine** ist nur ein schicker Begriff für dasjenige, was von einer `async def`-Funktion zurückgegeben wird. Python weiß, dass es so etwas wie eine Funktion ist, die es starten kann und die irgendwann endet, aber auch dass sie pausiert ⏸ werden kann, wann immer darin ein `await` steht. + +Aber all diese Funktionalität der Verwendung von asynchronem Code mit `async` und `await` wird oft als Verwendung von „Coroutinen“ zusammengefasst. Es ist vergleichbar mit dem Hauptmerkmal von Go, den „Goroutinen“. + +## Fazit + +Sehen wir uns den gleichen Satz von oben noch mal an: + +> Moderne Versionen von Python unterstützen **„asynchronen Code“** unter Verwendung sogenannter **„Coroutinen“** mithilfe der Syntax **`async`** und **`await`**. + +Das sollte jetzt mehr Sinn ergeben. ✨ + +All das ist es, was FastAPI (via Starlette) befeuert und es eine so beeindruckende Performanz haben lässt. + +## Sehr technische Details + +/// warning | Achtung + +Das folgende können Sie wahrscheinlich überspringen. + +Dies sind sehr technische Details darüber, wie **FastAPI** unter der Haube funktioniert. + +Wenn Sie über gute technische Kenntnisse verfügen (Coroutinen, Threads, Blocking, usw.) und neugierig sind, wie FastAPI mit `async def`s im Vergleich zu normalen `def`s umgeht, fahren Sie fort. + +/// + +### Pfadoperation-Funktionen + +Wenn Sie eine *Pfadoperation-Funktion* mit normalem `def` anstelle von `async def` deklarieren, wird sie in einem externen Threadpool ausgeführt, der dann `await`et wird, anstatt direkt aufgerufen zu werden (da dies den Server blockieren würde). + +Wenn Sie von einem anderen asynchronen Framework kommen, das nicht auf die oben beschriebene Weise funktioniert, und Sie es gewohnt sind, triviale, nur-berechnende *Pfadoperation-Funktionen* mit einfachem `def` zu definieren, um einen geringfügigen Geschwindigkeitsgewinn (etwa 100 Nanosekunden) zu erzielen, beachten Sie bitte, dass der Effekt in **FastAPI** genau gegenteilig wäre. In solchen Fällen ist es besser, `async def` zu verwenden, es sei denn, Ihre *Pfadoperation-Funktionen* verwenden Code, der blockierende I/O-Operationen durchführt. + +Dennoch besteht in beiden Fällen eine gute Chance, dass **FastAPI** [immer noch schneller](index.md#performanz){.internal-link target=_blank} als Ihr bisheriges Framework (oder zumindest damit vergleichbar) ist. + +### Abhängigkeiten + +Das Gleiche gilt für [Abhängigkeiten](tutorial/dependencies/index.md){.internal-link target=_blank}. Wenn eine Abhängigkeit eine normale `def`-Funktion ist, anstelle einer `async def`-Funktion, dann wird sie im externen Threadpool ausgeführt. + +### Unterabhängigkeiten + +Sie können mehrere Abhängigkeiten und [Unterabhängigkeiten](tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} haben, die einander bedingen (als Parameter der Funktionsdefinitionen), einige davon könnten erstellt werden mit `async def` und einige mit normalem `def`. Es würde immer noch funktionieren und diejenigen, die mit normalem `def` erstellt wurden, würden in einem externen Thread (vom Threadpool stammend) aufgerufen werden, anstatt `await`et zu werden. + +### Andere Hilfsfunktionen + +Jede andere Hilfsfunktion, die Sie direkt aufrufen, kann mit normalem `def` oder `async def` erstellt werden, und FastAPI beeinflusst nicht die Art und Weise, wie Sie sie aufrufen. + +Dies steht im Gegensatz zu den Funktionen, die FastAPI für Sie aufruft: *Pfadoperation-Funktionen* und Abhängigkeiten. + +Wenn Ihre Hilfsfunktion eine normale Funktion mit `def` ist, wird sie direkt aufgerufen (so wie Sie es in Ihrem Code schreiben), nicht in einem Threadpool. Wenn die Funktion mit `async def` erstellt wurde, sollten Sie sie `await`en, wenn Sie sie in Ihrem Code aufrufen. + +--- + +Nochmal, es handelt sich hier um sehr technische Details, die Ihnen helfen, falls Sie danach gesucht haben. + +Andernfalls liegen Sie richtig, wenn Sie sich an die Richtlinien aus dem obigen Abschnitt halten: In Eile?. diff --git a/docs/de/docs/benchmarks.md b/docs/de/docs/benchmarks.md new file mode 100644 index 000000000..6efd56e83 --- /dev/null +++ b/docs/de/docs/benchmarks.md @@ -0,0 +1,34 @@ +# Benchmarks + +Unabhängige TechEmpower-Benchmarks zeigen, **FastAPI**-Anwendungen, die unter Uvicorn ausgeführt werden, gehören zu den schnellsten existierenden Python-Frameworks, nur Starlette und Uvicorn selbst (intern von FastAPI verwendet) sind schneller. + +Beim Ansehen von Benchmarks und Vergleichen sollten Sie jedoch Folgende Punkte beachten. + +## Benchmarks und Geschwindigkeit + +Wenn Sie sich die Benchmarks ansehen, werden häufig mehrere Tools mit unterschiedlichen Eigenschaften als gleichwertig verglichen. + +Konkret geht es darum, Uvicorn, Starlette und FastAPI miteinander zu vergleichen (neben vielen anderen Tools). + +Je einfacher das Problem, welches durch das Tool gelöst wird, desto besser ist die Performanz. Und die meisten Benchmarks testen nicht die zusätzlichen Funktionen, welche das Tool bietet. + +Die Hierarchie ist wie folgt: + +* **Uvicorn**: ein ASGI-Server + * **Starlette**: (verwendet Uvicorn) ein Web-Mikroframework + * **FastAPI**: (verwendet Starlette) ein API-Mikroframework mit mehreren zusätzlichen Funktionen zum Erstellen von APIs, mit Datenvalidierung, usw. + +* **Uvicorn**: + * Bietet die beste Leistung, da außer dem Server selbst nicht viel zusätzlicher Code vorhanden ist. + * Sie würden eine Anwendung nicht direkt in Uvicorn schreiben. Das würde bedeuten, dass Ihr Code zumindest mehr oder weniger den gesamten von Starlette (oder **FastAPI**) bereitgestellten Code enthalten müsste. Und wenn Sie das täten, hätte Ihre endgültige Anwendung den gleichen Overhead wie die Verwendung eines Frameworks nebst Minimierung Ihres Anwendungscodes und der Fehler. + * Wenn Sie Uvicorn vergleichen, vergleichen Sie es mit Anwendungsservern wie Daphne, Hypercorn, uWSGI, usw. +* **Starlette**: + * Wird nach Uvicorn die nächstbeste Performanz erbringen. Tatsächlich nutzt Starlette intern Uvicorn. Daher kann es wahrscheinlich nur „langsamer“ als Uvicorn sein, weil mehr Code ausgeführt wird. + * Aber es bietet Ihnen die Tools zum Erstellen einfacher Webanwendungen, mit Routing basierend auf Pfaden, usw. + * Wenn Sie Starlette vergleichen, vergleichen Sie es mit Webframeworks (oder Mikroframeworks) wie Sanic, Flask, Django, usw. +* **FastAPI**: + * So wie Starlette Uvicorn verwendet und nicht schneller als dieses sein kann, verwendet **FastAPI** Starlette, sodass es nicht schneller als dieses sein kann. + * FastAPI bietet zusätzlich zu Starlette weitere Funktionen. Funktionen, die Sie beim Erstellen von APIs fast immer benötigen, wie Datenvalidierung und Serialisierung. Und wenn Sie es verwenden, erhalten Sie kostenlos automatische Dokumentation (die automatische Dokumentation verursacht nicht einmal zusätzlichen Aufwand für laufende Anwendungen, sie wird beim Start generiert). + * Wenn Sie FastAPI nicht, und direkt Starlette (oder ein anderes Tool wie Sanic, Flask, Responder, usw.) verwenden würden, müssten Sie die gesamte Datenvalidierung und Serialisierung selbst implementieren. Ihre finale Anwendung hätte also immer noch den gleichen Overhead, als ob sie mit FastAPI erstellt worden wäre. Und in vielen Fällen ist diese Datenvalidierung und Serialisierung der größte Teil des in Anwendungen geschriebenen Codes. + * Durch die Verwendung von FastAPI sparen Sie also Entwicklungszeit, Fehler und Codezeilen und würden wahrscheinlich die gleiche Leistung (oder eine bessere) erzielen, die Sie hätten, wenn Sie es nicht verwenden würden (da Sie alles in Ihrem Code implementieren müssten). + * Wenn Sie FastAPI vergleichen, vergleichen Sie es mit einem Webanwendung-Framework (oder einer Reihe von Tools), welche Datenvalidierung, Serialisierung und Dokumentation bereitstellen, wie Flask-apispec, NestJS, Molten, usw. – Frameworks mit integrierter automatischer Datenvalidierung, Serialisierung und Dokumentation. diff --git a/docs/de/docs/deployment/cloud.md b/docs/de/docs/deployment/cloud.md new file mode 100644 index 000000000..2d70fe4e5 --- /dev/null +++ b/docs/de/docs/deployment/cloud.md @@ -0,0 +1,17 @@ +# FastAPI-Deployment bei Cloud-Anbietern + +Sie können praktisch **jeden Cloud-Anbieter** für das Deployment Ihrer FastAPI-Anwendung verwenden. + +In den meisten Fällen verfügen die Haupt-Cloud-Anbieter über Anleitungen zum Deployment von FastAPI. + +## Cloud-Anbieter – Sponsoren + +Einige Cloud-Anbieter ✨ [**sponsern FastAPI**](../help-fastapi.md#den-autor-sponsern){.internal-link target=_blank} ✨, dies gewährleistet die kontinuierliche und gesunde **Entwicklung** von FastAPI und seinem **Ökosystem**. + +Und es zeigt deren wahres Engagement für FastAPI und seine **Community** (Sie), da diese Ihnen nicht nur einen **guten Service** bieten möchten, sondern auch sicherstellen möchten, dass Sie über ein **gutes und gesundes Framework** verfügen, FastAPI. 🙇 + +Vielleicht möchten Sie deren Dienste ausprobieren und deren Anleitungen folgen: + +* Platform.sh +* Porter +* Coherence diff --git a/docs/de/docs/deployment/concepts.md b/docs/de/docs/deployment/concepts.md new file mode 100644 index 000000000..97ad854e2 --- /dev/null +++ b/docs/de/docs/deployment/concepts.md @@ -0,0 +1,323 @@ +# Deployment-Konzepte + +Bei dem Deployment – der Bereitstellung – einer **FastAPI**-Anwendung, oder eigentlich jeder Art von Web-API, gibt es mehrere Konzepte, die Sie wahrscheinlich interessieren, und mithilfe der Sie die **am besten geeignete** Methode zur **Bereitstellung Ihrer Anwendung** finden können. + +Einige wichtige Konzepte sind: + +* Sicherheit – HTTPS +* Beim Hochfahren ausführen +* Neustarts +* Replikation (die Anzahl der laufenden Prozesse) +* Arbeitsspeicher +* Schritte vor dem Start + +Wir werden sehen, wie diese sich auf das **Deployment** auswirken. + +Letztendlich besteht das ultimative Ziel darin, **Ihre API-Clients** auf **sichere** Weise zu bedienen, um **Unterbrechungen** zu vermeiden und die **Rechenressourcen** (z. B. entfernte Server/virtuelle Maschinen) so effizient wie möglich zu nutzen. 🚀 + +Ich erzähle Ihnen hier etwas mehr über diese **Konzepte**, was Ihnen hoffentlich die **Intuition** gibt, die Sie benötigen, um zu entscheiden, wie Sie Ihre API in sehr unterschiedlichen Umgebungen bereitstellen, möglicherweise sogar in **zukünftigen**, die jetzt noch nicht existieren. + +Durch die Berücksichtigung dieser Konzepte können Sie die beste Variante der Bereitstellung **Ihrer eigenen APIs** **evaluieren und konzipieren**. + +In den nächsten Kapiteln werde ich Ihnen mehr **konkrete Rezepte** für die Bereitstellung von FastAPI-Anwendungen geben. + +Aber schauen wir uns zunächst einmal diese grundlegenden **konzeptionellen Ideen** an. Diese Konzepte gelten auch für jede andere Art von Web-API. 💡 + +## Sicherheit – HTTPS + +Im [vorherigen Kapitel über HTTPS](https.md){.internal-link target=_blank} haben wir erfahren, wie HTTPS Verschlüsselung für Ihre API bereitstellt. + +Wir haben auch gesehen, dass HTTPS normalerweise von einer Komponente **außerhalb** Ihres Anwendungsservers bereitgestellt wird, einem **TLS-Terminierungsproxy**. + +Und es muss etwas geben, das für die **Erneuerung der HTTPS-Zertifikate** zuständig ist, es könnte sich um dieselbe Komponente handeln oder um etwas anderes. + +### Beispieltools für HTTPS + +Einige der Tools, die Sie als TLS-Terminierungsproxy verwenden können, sind: + +* Traefik + * Handhabt automatisch Zertifikat-Erneuerungen ✨ +* Caddy + * Handhabt automatisch Zertifikat-Erneuerungen ✨ +* Nginx + * Mit einer externen Komponente wie Certbot für Zertifikat-Erneuerungen +* HAProxy + * Mit einer externen Komponente wie Certbot für Zertifikat-Erneuerungen +* Kubernetes mit einem Ingress Controller wie Nginx + * Mit einer externen Komponente wie cert-manager für Zertifikat-Erneuerungen +* Es wird intern von einem Cloud-Anbieter als Teil seiner Dienste verwaltet (siehe unten 👇) + +Eine andere Möglichkeit besteht darin, dass Sie einen **Cloud-Dienst** verwenden, der den größten Teil der Arbeit übernimmt, einschließlich der Einrichtung von HTTPS. Er könnte einige Einschränkungen haben oder Ihnen mehr in Rechnung stellen, usw. In diesem Fall müssten Sie jedoch nicht selbst einen TLS-Terminierungsproxy einrichten. + +In den nächsten Kapiteln zeige ich Ihnen einige konkrete Beispiele. + +--- + +Die nächsten zu berücksichtigenden Konzepte drehen sich dann um das Programm, das Ihre eigentliche API ausführt (z. B. Uvicorn). + +## Programm und Prozess + +Wir werden viel über den laufenden „**Prozess**“ sprechen, daher ist es nützlich, Klarheit darüber zu haben, was das bedeutet und was der Unterschied zum Wort „**Programm**“ ist. + +### Was ist ein Programm? + +Das Wort **Programm** wird häufig zur Beschreibung vieler Dinge verwendet: + +* Der **Code**, den Sie schreiben, die **Python-Dateien**. +* Die **Datei**, die vom Betriebssystem **ausgeführt** werden kann, zum Beispiel: `python`, `python.exe` oder `uvicorn`. +* Ein bestimmtes Programm, während es auf dem Betriebssystem **läuft**, die CPU nutzt und Dinge im Arbeitsspeicher ablegt. Dies wird auch als **Prozess** bezeichnet. + +### Was ist ein Prozess? + +Das Wort **Prozess** wird normalerweise spezifischer verwendet und bezieht sich nur auf das, was im Betriebssystem ausgeführt wird (wie im letzten Punkt oben): + +* Ein bestimmtes Programm, während es auf dem Betriebssystem **ausgeführt** wird. + * Dies bezieht sich weder auf die Datei noch auf den Code, sondern **speziell** auf das, was vom Betriebssystem **ausgeführt** und verwaltet wird. +* Jedes Programm, jeder Code **kann nur dann Dinge tun**, wenn er **ausgeführt** wird, wenn also ein **Prozess läuft**. +* Der Prozess kann von Ihnen oder vom Betriebssystem **terminiert** („beendet“, „gekillt“) werden. An diesem Punkt hört es auf zu laufen/ausgeführt zu werden und kann **keine Dinge mehr tun**. +* Hinter jeder Anwendung, die Sie auf Ihrem Computer ausführen, steckt ein Prozess, jedes laufende Programm, jedes Fenster usw. Und normalerweise laufen viele Prozesse **gleichzeitig**, während ein Computer eingeschaltet ist. +* Es können **mehrere Prozesse** desselben **Programms** gleichzeitig ausgeführt werden. + +Wenn Sie sich den „Task-Manager“ oder „Systemmonitor“ (oder ähnliche Tools) in Ihrem Betriebssystem ansehen, können Sie viele dieser laufenden Prozesse sehen. + +Und Sie werden beispielsweise wahrscheinlich feststellen, dass mehrere Prozesse dasselbe Browserprogramm ausführen (Firefox, Chrome, Edge, usw.). Normalerweise führen diese einen Prozess pro Browsertab sowie einige andere zusätzliche Prozesse aus. + + + +--- + +Nachdem wir nun den Unterschied zwischen den Begriffen **Prozess** und **Programm** kennen, sprechen wir weiter über das Deployment. + +## Beim Hochfahren ausführen + +Wenn Sie eine Web-API erstellen, möchten Sie in den meisten Fällen, dass diese **immer läuft**, ununterbrochen, damit Ihre Clients immer darauf zugreifen können. Es sei denn natürlich, Sie haben einen bestimmten Grund, warum Sie möchten, dass diese nur in bestimmten Situationen ausgeführt wird. Meistens möchten Sie jedoch, dass sie ständig ausgeführt wird und **verfügbar** ist. + +### Auf einem entfernten Server + +Wenn Sie einen entfernten Server (einen Cloud-Server, eine virtuelle Maschine, usw.) einrichten, können Sie am einfachsten Uvicorn (oder ähnliches) manuell ausführen, genau wie bei der lokalen Entwicklung. + +Und es wird funktionieren und **während der Entwicklung** nützlich sein. + +Wenn Ihre Verbindung zum Server jedoch unterbrochen wird, wird der **laufende Prozess** wahrscheinlich abstürzen. + +Und wenn der Server neu gestartet wird (z. B. nach Updates oder Migrationen vom Cloud-Anbieter), werden Sie das wahrscheinlich **nicht bemerken**. Und deshalb wissen Sie nicht einmal, dass Sie den Prozess manuell neu starten müssen. Ihre API bleibt also einfach tot. 😱 + +### Beim Hochfahren automatisch ausführen + +Im Allgemeinen möchten Sie wahrscheinlich, dass das Serverprogramm (z. B. Uvicorn) beim Hochfahren des Servers automatisch gestartet wird und kein **menschliches Eingreifen** erforderlich ist, sodass immer ein Prozess mit Ihrer API ausgeführt wird (z. B. Uvicorn, welches Ihre FastAPI-Anwendung ausführt). + +### Separates Programm + +Um dies zu erreichen, haben Sie normalerweise ein **separates Programm**, welches sicherstellt, dass Ihre Anwendung beim Hochfahren ausgeführt wird. Und in vielen Fällen würde es auch sicherstellen, dass auch andere Komponenten oder Anwendungen ausgeführt werden, beispielsweise eine Datenbank. + +### Beispieltools zur Ausführung beim Hochfahren + +Einige Beispiele für Tools, die diese Aufgabe übernehmen können, sind: + +* Docker +* Kubernetes +* Docker Compose +* Docker im Schwarm-Modus +* Systemd +* Supervisor +* Es wird intern von einem Cloud-Anbieter im Rahmen seiner Dienste verwaltet +* Andere ... + +In den nächsten Kapiteln werde ich Ihnen konkretere Beispiele geben. + +## Neustart + +Ähnlich wie Sie sicherstellen möchten, dass Ihre Anwendung beim Hochfahren ausgeführt wird, möchten Sie wahrscheinlich auch sicherstellen, dass diese nach Fehlern **neu gestartet** wird. + +### Wir machen Fehler + +Wir, als Menschen, machen ständig **Fehler**. Software hat fast *immer* **Bugs**, die an verschiedenen Stellen versteckt sind. 🐛 + +Und wir als Entwickler verbessern den Code ständig, wenn wir diese Bugs finden und neue Funktionen implementieren (und möglicherweise auch neue Bugs hinzufügen 😅). + +### Kleine Fehler automatisch handhaben + +Wenn beim Erstellen von Web-APIs mit FastAPI ein Fehler in unserem Code auftritt, wird FastAPI ihn normalerweise dem einzelnen Request zurückgeben, der den Fehler ausgelöst hat. 🛡 + +Der Client erhält für diesen Request einen **500 Internal Server Error**, aber die Anwendung arbeitet bei den nächsten Requests weiter, anstatt einfach komplett abzustürzen. + +### Größere Fehler – Abstürze + +Dennoch kann es vorkommen, dass wir Code schreiben, der **die gesamte Anwendung zum Absturz bringt** und so zum Absturz von Uvicorn und Python führt. 💥 + +Und dennoch möchten Sie wahrscheinlich nicht, dass die Anwendung tot bleibt, weil an einer Stelle ein Fehler aufgetreten ist. Sie möchten wahrscheinlich, dass sie zumindest für die *Pfadoperationen*, die nicht fehlerhaft sind, **weiterläuft**. + +### Neustart nach Absturz + +Aber in den Fällen mit wirklich schwerwiegenden Fehlern, die den laufenden **Prozess** zum Absturz bringen, benötigen Sie eine externe Komponente, die den Prozess **neu startet**, zumindest ein paar Mal ... + +/// tip | Tipp + +... Obwohl es wahrscheinlich keinen Sinn macht, sie immer wieder neu zu starten, wenn die gesamte Anwendung einfach **sofort abstürzt**. Aber in diesen Fällen werden Sie es wahrscheinlich während der Entwicklung oder zumindest direkt nach dem Deployment bemerken. + +Konzentrieren wir uns also auf die Hauptfälle, in denen die Anwendung in bestimmten Fällen **in der Zukunft** völlig abstürzen könnte und es dann dennoch sinnvoll ist, sie neu zu starten. + +/// + +Sie möchten wahrscheinlich, dass eine **externe Komponente** für den Neustart Ihrer Anwendung verantwortlich ist, da zu diesem Zeitpunkt dieselbe Anwendung mit Uvicorn und Python bereits abgestürzt ist und es daher nichts im selben Code derselben Anwendung gibt, was etwas dagegen tun kann. + +### Beispieltools zum automatischen Neustart + +In den meisten Fällen wird dasselbe Tool, das zum **Ausführen des Programms beim Hochfahren** verwendet wird, auch für automatische **Neustarts** verwendet. + +Dies könnte zum Beispiel erledigt werden durch: + +* Docker +* Kubernetes +* Docker Compose +* Docker im Schwarm-Modus +* Systemd +* Supervisor +* Intern von einem Cloud-Anbieter im Rahmen seiner Dienste +* Andere ... + +## Replikation – Prozesse und Arbeitsspeicher + +Wenn Sie eine FastAPI-Anwendung verwenden und ein Serverprogramm wie Uvicorn verwenden, kann **ein einzelner Prozess** mehrere Clients gleichzeitig bedienen. + +In vielen Fällen möchten Sie jedoch mehrere Prozesse gleichzeitig ausführen. + +### Mehrere Prozesse – Worker + +Wenn Sie mehr Clients haben, als ein einzelner Prozess verarbeiten kann (z. B. wenn die virtuelle Maschine nicht sehr groß ist) und die CPU des Servers **mehrere Kerne** hat, dann könnten **mehrere Prozesse** gleichzeitig mit derselben Anwendung laufen und alle Requests unter sich verteilen. + +Wenn Sie mit **mehreren Prozessen** dasselbe API-Programm ausführen, werden diese üblicherweise als **Worker** bezeichnet. + +### Workerprozesse und Ports + +Erinnern Sie sich aus der Dokumentation [Über HTTPS](https.md){.internal-link target=_blank}, dass nur ein Prozess auf einer Kombination aus Port und IP-Adresse auf einem Server lauschen kann? + +Das ist immer noch wahr. + +Um also **mehrere Prozesse** gleichzeitig zu haben, muss es einen **einzelnen Prozess geben, der einen Port überwacht**, welcher dann die Kommunikation auf irgendeine Weise an jeden Workerprozess überträgt. + +### Arbeitsspeicher pro Prozess + +Wenn das Programm nun Dinge in den Arbeitsspeicher lädt, zum Beispiel ein Modell für maschinelles Lernen in einer Variablen oder den Inhalt einer großen Datei in einer Variablen, verbraucht das alles **einen Teil des Arbeitsspeichers (RAM – Random Access Memory)** des Servers. + +Und mehrere Prozesse teilen sich normalerweise keinen Speicher. Das bedeutet, dass jeder laufende Prozess seine eigenen Dinge, eigenen Variablen und eigenen Speicher hat. Und wenn Sie in Ihrem Code viel Speicher verbrauchen, verbraucht **jeder Prozess** die gleiche Menge Speicher. + +### Serverspeicher + +Wenn Ihr Code beispielsweise ein Machine-Learning-Modell mit **1 GB Größe** lädt und Sie einen Prozess mit Ihrer API ausführen, verbraucht dieser mindestens 1 GB RAM. Und wenn Sie **4 Prozesse** (4 Worker) starten, verbraucht jeder 1 GB RAM. Insgesamt verbraucht Ihre API also **4 GB RAM**. + +Und wenn Ihr entfernter Server oder Ihre virtuelle Maschine nur über 3 GB RAM verfügt, führt der Versuch, mehr als 4 GB RAM zu laden, zu Problemen. 🚨 + +### Mehrere Prozesse – Ein Beispiel + +Im folgenden Beispiel gibt es einen **Manager-Prozess**, welcher zwei **Workerprozesse** startet und steuert. + +Dieser Manager-Prozess wäre wahrscheinlich derjenige, welcher der IP am **Port** lauscht. Und er würde die gesamte Kommunikation an die Workerprozesse weiterleiten. + +Diese Workerprozesse würden Ihre Anwendung ausführen, sie würden die Hauptberechnungen durchführen, um einen **Request** entgegenzunehmen und eine **Response** zurückzugeben, und sie würden alles, was Sie in Variablen einfügen, in den RAM laden. + + + +Und natürlich würden auf derselben Maschine neben Ihrer Anwendung wahrscheinlich auch **andere Prozesse** laufen. + +Ein interessantes Detail ist dabei, dass der Prozentsatz der von jedem Prozess verwendeten **CPU** im Laufe der Zeit stark **variieren** kann, der **Arbeitsspeicher (RAM)** jedoch normalerweise mehr oder weniger **stabil** bleibt. + +Wenn Sie eine API haben, die jedes Mal eine vergleichbare Menge an Berechnungen durchführt, und Sie viele Clients haben, dann wird die **CPU-Auslastung** wahrscheinlich *ebenfalls stabil sein* (anstatt ständig schnell zu steigen und zu fallen). + +### Beispiele für Replikation-Tools und -Strategien + +Es gibt mehrere Ansätze, um dies zu erreichen, und ich werde Ihnen in den nächsten Kapiteln mehr über bestimmte Strategien erzählen, beispielsweise wenn es um Docker und Container geht. + +Die wichtigste zu berücksichtigende Einschränkung besteht darin, dass es eine **einzelne** Komponente geben muss, welche die **öffentliche IP** auf dem **Port** verwaltet. Und dann muss diese irgendwie die Kommunikation **weiterleiten**, an die replizierten **Prozesse/Worker**. + +Hier sind einige mögliche Kombinationen und Strategien: + +* **Gunicorn**, welches **Uvicorn-Worker** managt + * Gunicorn wäre der **Prozessmanager**, der die **IP** und den **Port** überwacht, die Replikation würde durch **mehrere Uvicorn-Workerprozesse** erfolgen +* **Uvicorn**, welches **Uvicorn-Worker** managt + * Ein Uvicorn-**Prozessmanager** würde der **IP** am **Port** lauschen, und er würde **mehrere Uvicorn-Workerprozesse** starten. +* **Kubernetes** und andere verteilte **Containersysteme** + * Etwas in der **Kubernetes**-Ebene würde die **IP** und den **Port** abhören. Die Replikation hätte **mehrere Container**, in jedem wird jeweils **ein Uvicorn-Prozess** ausgeführt. +* **Cloud-Dienste**, welche das für Sie erledigen + * Der Cloud-Dienst wird wahrscheinlich **die Replikation für Sie übernehmen**. Er würde Sie möglicherweise **einen auszuführenden Prozess** oder ein **zu verwendendes Container-Image** definieren lassen, in jedem Fall wäre es höchstwahrscheinlich **ein einzelner Uvicorn-Prozess**, und der Cloud-Dienst wäre auch verantwortlich für die Replikation. + +/// tip | Tipp + +Machen Sie sich keine Sorgen, wenn einige dieser Punkte zu **Containern**, Docker oder Kubernetes noch nicht viel Sinn ergeben. + +Ich werde Ihnen in einem zukünftigen Kapitel mehr über Container-Images, Docker, Kubernetes, usw. erzählen: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}. + +/// + +## Schritte vor dem Start + +Es gibt viele Fälle, in denen Sie, **bevor Sie Ihre Anwendung starten**, einige Schritte ausführen möchten. + +Beispielsweise möchten Sie möglicherweise **Datenbankmigrationen** ausführen. + +In den meisten Fällen möchten Sie diese Schritte jedoch nur **einmal** ausführen. + +Sie möchten also einen **einzelnen Prozess** haben, um diese **Vorab-Schritte** auszuführen, bevor Sie die Anwendung starten. + +Und Sie müssen sicherstellen, dass es sich um einen einzelnen Prozess handelt, der die Vorab-Schritte ausführt, *auch* wenn Sie anschließend **mehrere Prozesse** (mehrere Worker) für die Anwendung selbst starten. Wenn diese Schritte von **mehreren Prozessen** ausgeführt würden, würden diese die Arbeit **verdoppeln**, indem sie sie **parallel** ausführen, und wenn es sich bei den Schritten um etwas Delikates wie eine Datenbankmigration handelt, könnte das miteinander Konflikte verursachen. + +Natürlich gibt es Fälle, in denen es kein Problem darstellt, die Vorab-Schritte mehrmals auszuführen. In diesem Fall ist die Handhabung viel einfacher. + +/// tip | Tipp + +Bedenken Sie außerdem, dass Sie, abhängig von Ihrer Einrichtung, in manchen Fällen **gar keine Vorab-Schritte** benötigen, bevor Sie die Anwendung starten. + +In diesem Fall müssen Sie sich darüber keine Sorgen machen. 🤷 + +/// + +### Beispiele für Strategien für Vorab-Schritte + +Es hängt **stark** davon ab, wie Sie **Ihr System bereitstellen**, und hängt wahrscheinlich mit der Art und Weise zusammen, wie Sie Programme starten, Neustarts durchführen, usw. + +Hier sind einige mögliche Ideen: + +* Ein „Init-Container“ in Kubernetes, der vor Ihrem Anwendungs-Container ausgeführt wird +* Ein Bash-Skript, das die Vorab-Schritte ausführt und dann Ihre Anwendung startet + * Sie benötigen immer noch eine Möglichkeit, *dieses* Bash-Skript zu starten/neu zu starten, Fehler zu erkennen, usw. + +/// tip | Tipp + +Konkretere Beispiele hierfür mit Containern gebe ich Ihnen in einem späteren Kapitel: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}. + +/// + +## Ressourcennutzung + +Ihr(e) Server ist (sind) eine **Ressource**, welche Sie mit Ihren Programmen, der Rechenzeit auf den CPUs und dem verfügbaren RAM-Speicher verbrauchen oder **nutzen** können. + +Wie viele Systemressourcen möchten Sie verbrauchen/nutzen? Sie mögen „nicht viel“ denken, aber in Wirklichkeit möchten Sie tatsächlich **so viel wie möglich ohne Absturz** verwenden. + +Wenn Sie für drei Server bezahlen, aber nur wenig von deren RAM und CPU nutzen, **verschwenden Sie wahrscheinlich Geld** 💸 und wahrscheinlich **Strom für den Server** 🌎, usw. + +In diesem Fall könnte es besser sein, nur zwei Server zu haben und einen höheren Prozentsatz von deren Ressourcen zu nutzen (CPU, Arbeitsspeicher, Festplatte, Netzwerkbandbreite, usw.). + +Wenn Sie andererseits über zwei Server verfügen und **100 % ihrer CPU und ihres RAM** nutzen, wird irgendwann ein Prozess nach mehr Speicher fragen und der Server muss die Festplatte als „Speicher“ verwenden (was tausendmal langsamer sein kann) oder er könnte sogar **abstürzen**. Oder ein Prozess muss möglicherweise einige Berechnungen durchführen und müsste warten, bis die CPU wieder frei ist. + +In diesem Fall wäre es besser, **einen zusätzlichen Server** zu besorgen und einige Prozesse darauf auszuführen, damit alle über **genug RAM und CPU-Zeit** verfügen. + +Es besteht auch die Möglichkeit, dass es aus irgendeinem Grund zu **Spitzen** in der Nutzung Ihrer API kommt. Vielleicht ist diese viral gegangen, oder vielleicht haben andere Dienste oder Bots damit begonnen, sie zu nutzen. Und vielleicht möchten Sie in solchen Fällen über zusätzliche Ressourcen verfügen, um auf der sicheren Seite zu sein. + +Sie können eine **beliebige Zahl** festlegen, um beispielsweise eine Ressourcenauslastung zwischen **50 % und 90 %** anzustreben. Der Punkt ist, dass dies wahrscheinlich die wichtigen Dinge sind, die Sie messen und verwenden sollten, um Ihre Deployments zu optimieren. + +Sie können einfache Tools wie `htop` verwenden, um die in Ihrem Server verwendete CPU und den RAM oder die von jedem Prozess verwendete Menge anzuzeigen. Oder Sie können komplexere Überwachungstools verwenden, die möglicherweise auf mehrere Server usw. verteilt sind. + +## Zusammenfassung + +Sie haben hier einige der wichtigsten Konzepte gelesen, die Sie wahrscheinlich berücksichtigen müssen, wenn Sie entscheiden, wie Sie Ihre Anwendung bereitstellen: + +* Sicherheit – HTTPS +* Beim Hochfahren ausführen +* Neustarts +* Replikation (die Anzahl der laufenden Prozesse) +* Arbeitsspeicher +* Schritte vor dem Start + +Das Verständnis dieser Ideen und deren Anwendung sollte Ihnen die nötige Intuition vermitteln, um bei der Konfiguration und Optimierung Ihrer Deployments Entscheidungen zu treffen. 🤓 + +In den nächsten Abschnitten gebe ich Ihnen konkretere Beispiele für mögliche Strategien, die Sie verfolgen können. 🚀 diff --git a/docs/de/docs/deployment/docker.md b/docs/de/docs/deployment/docker.md new file mode 100644 index 000000000..a2734e068 --- /dev/null +++ b/docs/de/docs/deployment/docker.md @@ -0,0 +1,731 @@ +# FastAPI in Containern – Docker + +Beim Deployment von FastAPI-Anwendungen besteht ein gängiger Ansatz darin, ein **Linux-Containerimage** zu erstellen. Normalerweise erfolgt dies mit **Docker**. Sie können dieses Containerimage dann auf eine von mehreren möglichen Arten bereitstellen. + +Die Verwendung von Linux-Containern bietet mehrere Vorteile, darunter **Sicherheit**, **Replizierbarkeit**, **Einfachheit** und andere. + +/// tip | Tipp + +Sie haben es eilig und kennen sich bereits aus? Springen Sie zum [`Dockerfile` unten 👇](#ein-docker-image-fur-fastapi-erstellen). + +/// + +
+Dockerfile-Vorschau 👀 + +```Dockerfile +FROM python:3.9 + +WORKDIR /code + +COPY ./requirements.txt /code/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +COPY ./app /code/app + +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] + +# Wenn Sie hinter einem Proxy wie Nginx oder Traefik sind, fügen Sie --proxy-headers hinzu +# CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80", "--proxy-headers"] +``` + +
+ +## Was ist ein Container? + +Container (hauptsächlich Linux-Container) sind eine sehr **leichtgewichtige** Möglichkeit, Anwendungen einschließlich aller ihrer Abhängigkeiten und erforderlichen Dateien zu verpacken und sie gleichzeitig von anderen Containern (anderen Anwendungen oder Komponenten) im selben System isoliert zu halten. + +Linux-Container werden mit demselben Linux-Kernel des Hosts (Maschine, virtuellen Maschine, Cloud-Servers, usw.) ausgeführt. Das bedeutet einfach, dass sie sehr leichtgewichtig sind (im Vergleich zu vollständigen virtuellen Maschinen, die ein gesamtes Betriebssystem emulieren). + +Auf diese Weise verbrauchen Container **wenig Ressourcen**, eine Menge vergleichbar mit der direkten Ausführung der Prozesse (eine virtuelle Maschine würde viel mehr verbrauchen). + +Container verfügen außerdem über ihre eigenen **isoliert** laufenden Prozesse (üblicherweise nur einen Prozess), über ihr eigenes Dateisystem und ihr eigenes Netzwerk, was die Bereitstellung, Sicherheit, Entwicklung usw. vereinfacht. + +## Was ist ein Containerimage? + +Ein **Container** wird von einem **Containerimage** ausgeführt. + +Ein Containerimage ist eine **statische** Version aller Dateien, Umgebungsvariablen und des Standardbefehls/-programms, welche in einem Container vorhanden sein sollten. **Statisch** bedeutet hier, dass das Container-**Image** nicht läuft, nicht ausgeführt wird, sondern nur die gepackten Dateien und Metadaten enthält. + +Im Gegensatz zu einem „**Containerimage**“, bei dem es sich um den gespeicherten statischen Inhalt handelt, bezieht sich ein „**Container**“ normalerweise auf die laufende Instanz, das Ding, das **ausgeführt** wird. + +Wenn der **Container** gestartet und ausgeführt wird (gestartet von einem **Containerimage**), kann er Dateien, Umgebungsvariablen usw. erstellen oder ändern. Diese Änderungen sind nur in diesem Container vorhanden, nicht im zugrunde liegenden bestehen Containerimage (werden nicht auf der Festplatte gespeichert). + +Ein Containerimage ist vergleichbar mit der **Programmdatei** und ihrem Inhalt, z. B. `python` und eine Datei `main.py`. + +Und der **Container** selbst (im Gegensatz zum **Containerimage**) ist die tatsächlich laufende Instanz des Images, vergleichbar mit einem **Prozess**. Tatsächlich läuft ein Container nur, wenn er einen **laufenden Prozess** hat (und normalerweise ist es nur ein einzelner Prozess). Der Container stoppt, wenn kein Prozess darin ausgeführt wird. + +## Containerimages + +Docker ist eines der wichtigsten Tools zum Erstellen und Verwalten von **Containerimages** und **Containern**. + +Und es gibt einen öffentlichen Docker Hub mit vorgefertigten **offiziellen Containerimages** für viele Tools, Umgebungen, Datenbanken und Anwendungen. + +Beispielsweise gibt es ein offizielles Python-Image. + +Und es gibt viele andere Images für verschiedene Dinge wie Datenbanken, zum Beispiel für: + +* PostgreSQL +* MySQL +* MongoDB +* Redis, usw. + +Durch die Verwendung eines vorgefertigten Containerimages ist es sehr einfach, verschiedene Tools zu **kombinieren** und zu verwenden. Zum Beispiel, um eine neue Datenbank auszuprobieren. In den meisten Fällen können Sie die **offiziellen Images** verwenden und diese einfach mit Umgebungsvariablen konfigurieren. + +Auf diese Weise können Sie in vielen Fällen etwas über Container und Docker lernen und dieses Wissen mit vielen verschiedenen Tools und Komponenten wiederverwenden. + +Sie würden also **mehrere Container** mit unterschiedlichen Dingen ausführen, wie einer Datenbank, einer Python-Anwendung, einem Webserver mit einer React-Frontend-Anwendung, und diese über ihr internes Netzwerk miteinander verbinden. + +In alle Containerverwaltungssysteme (wie Docker oder Kubernetes) sind diese Netzwerkfunktionen integriert. + +## Container und Prozesse + +Ein **Containerimage** enthält normalerweise in seinen Metadaten das Standardprogramm oder den Standardbefehl, der ausgeführt werden soll, wenn der **Container** gestartet wird, sowie die Parameter, die an dieses Programm übergeben werden sollen. Sehr ähnlich zu dem, was wäre, wenn es über die Befehlszeile gestartet werden würde. + +Wenn ein **Container** gestartet wird, führt er diesen Befehl/dieses Programm aus (Sie können ihn jedoch überschreiben und einen anderen Befehl/ein anderes Programm ausführen lassen). + +Ein Container läuft, solange der **Hauptprozess** (Befehl oder Programm) läuft. + +Ein Container hat normalerweise einen **einzelnen Prozess**, aber es ist auch möglich, Unterprozesse vom Hauptprozess aus zu starten, und auf diese Weise haben Sie **mehrere Prozesse** im selben Container. + +Es ist jedoch nicht möglich, einen laufenden Container, ohne **mindestens einen laufenden Prozess** zu haben. Wenn der Hauptprozess stoppt, stoppt der Container. + +## Ein Docker-Image für FastAPI erstellen + +Okay, wollen wir jetzt etwas bauen! 🚀 + +Ich zeige Ihnen, wie Sie ein **Docker-Image** für FastAPI **von Grund auf** erstellen, basierend auf dem **offiziellen Python**-Image. + +Das ist, was Sie in **den meisten Fällen** tun möchten, zum Beispiel: + +* Bei Verwendung von **Kubernetes** oder ähnlichen Tools +* Beim Betrieb auf einem **Raspberry Pi** +* Bei Verwendung eines Cloud-Dienstes, der ein Containerimage für Sie ausführt, usw. + +### Paketanforderungen + +Normalerweise befinden sich die **Paketanforderungen** für Ihre Anwendung in einer Datei. + +Dies hängt hauptsächlich von dem Tool ab, mit dem Sie diese Anforderungen **installieren**. + +Die gebräuchlichste Methode besteht darin, eine Datei `requirements.txt` mit den Namen der Packages und deren Versionen zu erstellen, eine pro Zeile. + +Sie würden natürlich die gleichen Ideen verwenden, die Sie in [Über FastAPI-Versionen](versions.md){.internal-link target=_blank} gelesen haben, um die Versionsbereiche festzulegen. + +Ihre `requirements.txt` könnte beispielsweise so aussehen: + +``` +fastapi>=0.68.0,<0.69.0 +pydantic>=1.8.0,<2.0.0 +uvicorn>=0.15.0,<0.16.0 +``` + +Und normalerweise würden Sie diese Paketabhängigkeiten mit `pip` installieren, zum Beispiel: + +
+ +```console +$ pip install -r requirements.txt +---> 100% +Successfully installed fastapi pydantic uvicorn +``` + +
+ +/// info + +Es gibt andere Formate und Tools zum Definieren und Installieren von Paketabhängigkeiten. + +Ich zeige Ihnen später in einem Abschnitt unten ein Beispiel unter Verwendung von Poetry. 👇 + +/// + +### Den **FastAPI**-Code erstellen + +* Erstellen Sie ein `app`-Verzeichnis und betreten Sie es. +* Erstellen Sie eine leere Datei `__init__.py`. +* Erstellen Sie eine `main.py`-Datei mit: + +```Python +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@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} +``` + +### Dockerfile + +Erstellen Sie nun im selben Projektverzeichnis eine Datei `Dockerfile` mit: + +```{ .dockerfile .annotate } +# (1) +FROM python:3.9 + +# (2) +WORKDIR /code + +# (3) +COPY ./requirements.txt /code/requirements.txt + +# (4) +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +# (5) +COPY ./app /code/app + +# (6) +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] +``` + +1. Beginne mit dem offiziellen Python-Basisimage. + +2. Setze das aktuelle Arbeitsverzeichnis auf `/code`. + + Hier plazieren wir die Datei `requirements.txt` und das Verzeichnis `app`. + +3. Kopiere die Datei mit den Paketanforderungen in das Verzeichnis `/code`. + + Kopieren Sie zuerst **nur** die Datei mit den Anforderungen, nicht den Rest des Codes. + + Da sich diese Datei **nicht oft ändert**, erkennt Docker das und verwendet den **Cache** für diesen Schritt, wodurch der Cache auch für den nächsten Schritt aktiviert wird. + +4. Installiere die Paketabhängigkeiten aus der Anforderungsdatei. + + Die Option `--no-cache-dir` weist `pip` an, die heruntergeladenen Pakete nicht lokal zu speichern, da dies nur benötigt wird, sollte `pip` erneut ausgeführt werden, um dieselben Pakete zu installieren, aber das ist beim Arbeiten mit Containern nicht der Fall. + + /// note | Hinweis + + Das `--no-cache-dir` bezieht sich nur auf `pip`, es hat nichts mit Docker oder Containern zu tun. + + /// + + Die Option `--upgrade` weist `pip` an, die Packages zu aktualisieren, wenn sie bereits installiert sind. + + Da der vorherige Schritt des Kopierens der Datei vom **Docker-Cache** erkannt werden konnte, wird dieser Schritt auch **den Docker-Cache verwenden**, sofern verfügbar. + + Durch die Verwendung des Caches in diesem Schritt **sparen** Sie viel **Zeit**, wenn Sie das Image während der Entwicklung immer wieder erstellen, anstatt **jedes Mal** alle Abhängigkeiten **herunterzuladen und zu installieren**. + +5. Kopiere das Verzeichnis `./app` in das Verzeichnis `/code`. + + Da hier der gesamte Code enthalten ist, der sich **am häufigsten ändert**, wird der Docker-**Cache** nicht ohne weiteres für diesen oder andere **folgende Schritte** verwendet. + + Daher ist es wichtig, dies **nahe dem Ende** des `Dockerfile`s zu platzieren, um die Erstellungszeiten des Containerimages zu optimieren. + +6. Lege den **Befehl** fest, um den `uvicorn`-Server zu starten. + + `CMD` nimmt eine Liste von Zeichenfolgen entgegen. Jede dieser Zeichenfolgen entspricht dem, was Sie durch Leerzeichen getrennt in die Befehlszeile eingeben würden. + + Dieser Befehl wird aus dem **aktuellen Arbeitsverzeichnis** ausgeführt, dem gleichen `/code`-Verzeichnis, das Sie oben mit `WORKDIR /code` festgelegt haben. + + Da das Programm unter `/code` gestartet wird und sich darin das Verzeichnis `./app` mit Ihrem Code befindet, kann **Uvicorn** `app` sehen und aus `app.main` **importieren**. + +/// tip | Tipp + +Lernen Sie, was jede Zeile bewirkt, indem Sie auf die Zahlenblasen im Code klicken. 👆 + +/// + +Sie sollten jetzt eine Verzeichnisstruktur wie diese haben: + +``` +. +├── app +│   ├── __init__.py +│ └── main.py +├── Dockerfile +└── requirements.txt +``` + +#### Hinter einem TLS-Terminierungsproxy + +Wenn Sie Ihren Container hinter einem TLS-Terminierungsproxy (Load Balancer) wie Nginx oder Traefik ausführen, fügen Sie die Option `--proxy-headers` hinzu. Das sagt Uvicorn, den von diesem Proxy gesendeten Headern zu vertrauen und dass die Anwendung hinter HTTPS ausgeführt wird, usw. + +```Dockerfile +CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"] +``` + +#### Docker-Cache + +In diesem `Dockerfile` gibt es einen wichtigen Trick: Wir kopieren zuerst die **Datei nur mit den Abhängigkeiten**, nicht den Rest des Codes. Lassen Sie mich Ihnen erklären, warum. + +```Dockerfile +COPY ./requirements.txt /code/requirements.txt +``` + +Docker und andere Tools **erstellen** diese Containerimages **inkrementell**, fügen **eine Ebene über der anderen** hinzu, beginnend am Anfang des `Dockerfile`s und fügen alle durch die einzelnen Anweisungen des `Dockerfile`s erstellten Dateien hinzu. + +Docker und ähnliche Tools verwenden beim Erstellen des Images auch einen **internen Cache**. Wenn sich eine Datei seit der letzten Erstellung des Containerimages nicht geändert hat, wird **dieselbe Ebene wiederverwendet**, die beim letzten Mal erstellt wurde, anstatt die Datei erneut zu kopieren und eine neue Ebene von Grund auf zu erstellen. + +Das bloße Vermeiden des Kopierens von Dateien führt nicht unbedingt zu einer großen Verbesserung, aber da der Cache für diesen Schritt verwendet wurde, kann **der Cache für den nächsten Schritt verwendet werden**. Beispielsweise könnte der Cache verwendet werden für die Anweisung, welche die Abhängigkeiten installiert mit: + +```Dockerfile +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt +``` + +Die Datei mit den Paketanforderungen wird sich **nicht häufig ändern**. Wenn Docker also nur diese Datei kopiert, kann es für diesen Schritt **den Cache verwenden**. + +Und dann kann Docker **den Cache für den nächsten Schritt verwenden**, der diese Abhängigkeiten herunterlädt und installiert. Und hier **sparen wir viel Zeit**. ✨ ... und vermeiden die Langeweile beim Warten. 😪😆 + +Das Herunterladen und Installieren der Paketabhängigkeiten **könnte Minuten dauern**, aber die Verwendung des **Cache** würde höchstens **Sekunden** dauern. + +Und da Sie das Containerimage während der Entwicklung immer wieder erstellen würden, um zu überprüfen, ob Ihre Codeänderungen funktionieren, würde dies viel Zeit sparen. + +Dann, gegen Ende des `Dockerfile`s, kopieren wir den gesamten Code. Da sich der **am häufigsten ändert**, platzieren wir das am Ende, da fast immer alles nach diesem Schritt nicht mehr in der Lage sein wird, den Cache zu verwenden. + +```Dockerfile +COPY ./app /code/app +``` + +### Das Docker-Image erstellen + +Nachdem nun alle Dateien vorhanden sind, erstellen wir das Containerimage. + +* Gehen Sie zum Projektverzeichnis (dort, wo sich Ihr `Dockerfile` und Ihr `app`-Verzeichnis befindet). +* Erstellen Sie Ihr FastAPI-Image: + +
+ +```console +$ docker build -t myimage . + +---> 100% +``` + +
+ +/// tip | Tipp + +Beachten Sie das `.` am Ende, es entspricht `./` und teilt Docker mit, welches Verzeichnis zum Erstellen des Containerimages verwendet werden soll. + +In diesem Fall handelt es sich um dasselbe aktuelle Verzeichnis (`.`). + +/// + +### Den Docker-Container starten + +* Führen Sie einen Container basierend auf Ihrem Image aus: + +
+ +```console +$ docker run -d --name mycontainer -p 80:80 myimage +``` + +
+ +## Es überprüfen + +Sie sollten es in der URL Ihres Docker-Containers überprüfen können, zum Beispiel: http://192.168.99.100/items/5?q=somequery oder http://127.0.0.1/items/5?q=somequery (oder gleichwertig, unter Verwendung Ihres Docker-Hosts). + +Sie werden etwas sehen wie: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +## Interaktive API-Dokumentation + +Jetzt können Sie auf http://192.168.99.100/docs oder http://127.0.0.1/docs gehen (oder ähnlich, unter Verwendung Ihres Docker-Hosts). + +Sie sehen die automatische interaktive API-Dokumentation (bereitgestellt von Swagger UI): + +![Swagger-Oberfläche](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +## Alternative API-Dokumentation + +Sie können auch auf http://192.168.99.100/redoc oder http://127.0.0.1/redoc gehen (oder ähnlich, unter Verwendung Ihres Docker-Hosts). + +Sie sehen die alternative automatische Dokumentation (bereitgestellt von ReDoc): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## Ein Docker-Image mit einem Single-File-FastAPI erstellen + +Wenn Ihr FastAPI eine einzelne Datei ist, zum Beispiel `main.py` ohne ein `./app`-Verzeichnis, könnte Ihre Dateistruktur wie folgt aussehen: + +``` +. +├── Dockerfile +├── main.py +└── requirements.txt +``` + +Dann müssten Sie nur noch die entsprechenden Pfade ändern, um die Datei im `Dockerfile` zu kopieren: + +```{ .dockerfile .annotate hl_lines="10 13" } +FROM python:3.9 + +WORKDIR /code + +COPY ./requirements.txt /code/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +# (1) +COPY ./main.py /code/ + +# (2) +CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] +``` + +1. Kopiere die Datei `main.py` direkt in das Verzeichnis `/code` (ohne ein Verzeichnis `./app`). + +2. Führe Uvicorn aus und weisen es an, das `app`-Objekt von `main` zu importieren (anstatt von `app.main` zu importieren). + +Passen Sie dann den Uvicorn-Befehl an, um das neue Modul `main` anstelle von `app.main` zu verwenden, um das FastAPI-Objekt `app` zu importieren. + +## Deployment-Konzepte + +Lassen Sie uns noch einmal über einige der gleichen [Deployment-Konzepte](concepts.md){.internal-link target=_blank} in Bezug auf Container sprechen. + +Container sind hauptsächlich ein Werkzeug, um den Prozess des **Erstellens und Deployments** einer Anwendung zu vereinfachen, sie erzwingen jedoch keinen bestimmten Ansatz für die Handhabung dieser **Deployment-Konzepte**, und es gibt mehrere mögliche Strategien. + +Die **gute Nachricht** ist, dass es mit jeder unterschiedlichen Strategie eine Möglichkeit gibt, alle Deployment-Konzepte abzudecken. 🎉 + +Sehen wir uns diese **Deployment-Konzepte** im Hinblick auf Container noch einmal an: + +* Sicherheit – HTTPS +* Beim Hochfahren ausführen +* Neustarts +* Replikation (die Anzahl der laufenden Prozesse) +* Arbeitsspeicher +* Schritte vor dem Start + +## HTTPS + +Wenn wir uns nur auf das **Containerimage** für eine FastAPI-Anwendung (und später auf den laufenden **Container**) konzentrieren, würde HTTPS normalerweise **extern** von einem anderen Tool verarbeitet. + +Es könnte sich um einen anderen Container handeln, zum Beispiel mit Traefik, welcher **HTTPS** und **automatischen** Erwerb von **Zertifikaten** handhabt. + +/// tip | Tipp + +Traefik verfügt über Integrationen mit Docker, Kubernetes und anderen, sodass Sie damit ganz einfach HTTPS für Ihre Container einrichten und konfigurieren können. + +/// + +Alternativ könnte HTTPS von einem Cloud-Anbieter als einer seiner Dienste gehandhabt werden (während die Anwendung weiterhin in einem Container ausgeführt wird). + +## Beim Hochfahren ausführen und Neustarts + +Normalerweise gibt es ein anderes Tool, das für das **Starten und Ausführen** Ihres Containers zuständig ist. + +Es könnte sich um **Docker** direkt, **Docker Compose**, **Kubernetes**, einen **Cloud-Dienst**, usw. handeln. + +In den meisten (oder allen) Fällen gibt es eine einfache Option, um die Ausführung des Containers beim Hochfahren und Neustarts bei Fehlern zu ermöglichen. In Docker ist es beispielsweise die Befehlszeilenoption `--restart`. + +Ohne die Verwendung von Containern kann es umständlich und schwierig sein, Anwendungen beim Hochfahren auszuführen und neu zu starten. Bei der **Arbeit mit Containern** ist diese Funktionalität jedoch in den meisten Fällen standardmäßig enthalten. ✨ + +## Replikation – Anzahl der Prozesse + +Wenn Sie einen Cluster von Maschinen mit **Kubernetes**, Docker Swarm Mode, Nomad verwenden, oder einem anderen, ähnlich komplexen System zur Verwaltung verteilter Container auf mehreren Maschinen, möchten Sie wahrscheinlich die **Replikation auf Cluster-Ebene abwickeln**, anstatt in jedem Container einen **Prozessmanager** (wie Gunicorn mit Workern) zu verwenden. + +Diese verteilten Containerverwaltungssysteme wie Kubernetes verfügen normalerweise über eine integrierte Möglichkeit, die **Replikation von Containern** zu handhaben und gleichzeitig **Load Balancing** für die eingehenden Requests zu unterstützen. Alles auf **Cluster-Ebene**. + +In diesen Fällen möchten Sie wahrscheinlich ein **Docker-Image von Grund auf** erstellen, wie [oben erklärt](#dockerfile), Ihre Abhängigkeiten installieren und **einen einzelnen Uvicorn-Prozess** ausführen, anstatt etwas wie Gunicorn mit Uvicorn-Workern auszuführen. + +### Load Balancer + +Bei der Verwendung von Containern ist normalerweise eine Komponente vorhanden, **die am Hauptport lauscht**. Es könnte sich um einen anderen Container handeln, der auch ein **TLS-Terminierungsproxy** ist, um **HTTPS** zu verarbeiten, oder ein ähnliches Tool. + +Da diese Komponente die **Last** an Requests aufnehmen und diese (hoffentlich) **ausgewogen** auf die Worker verteilen würde, wird sie üblicherweise auch **Load Balancer** – Lastverteiler – genannt. + +/// tip | Tipp + +Die gleiche **TLS-Terminierungsproxy**-Komponente, die für HTTPS verwendet wird, wäre wahrscheinlich auch ein **Load Balancer**. + +/// + +Und wenn Sie mit Containern arbeiten, verfügt das gleiche System, mit dem Sie diese starten und verwalten, bereits über interne Tools, um die **Netzwerkkommunikation** (z. B. HTTP-Requests) von diesem **Load Balancer** (das könnte auch ein **TLS-Terminierungsproxy** sein) zu den Containern mit Ihrer Anwendung weiterzuleiten. + +### Ein Load Balancer – mehrere Workercontainer + +Bei der Arbeit mit **Kubernetes** oder ähnlichen verteilten Containerverwaltungssystemen würde die Verwendung ihrer internen Netzwerkmechanismen es dem einzelnen **Load Balancer**, der den Haupt-**Port** überwacht, ermöglichen, Kommunikation (Requests) an möglicherweise **mehrere Container** weiterzuleiten, in denen Ihre Anwendung ausgeführt wird. + +Jeder dieser Container, in denen Ihre Anwendung ausgeführt wird, verfügt normalerweise über **nur einen Prozess** (z. B. einen Uvicorn-Prozess, der Ihre FastAPI-Anwendung ausführt). Es wären alles **identische Container**, die das Gleiche ausführen, welche aber jeweils über einen eigenen Prozess, Speicher, usw. verfügen. Auf diese Weise würden Sie die **Parallelisierung** in **verschiedenen Kernen** der CPU nutzen. Oder sogar in **verschiedenen Maschinen**. + +Und das verteilte Containersystem mit dem **Load Balancer** würde **die Requests abwechselnd** an jeden einzelnen Container mit Ihrer Anwendung verteilen. Jeder Request könnte also von einem der mehreren **replizierten Container** verarbeitet werden, in denen Ihre Anwendung ausgeführt wird. + +Und normalerweise wäre dieser **Load Balancer** in der Lage, Requests zu verarbeiten, die an *andere* Anwendungen in Ihrem Cluster gerichtet sind (z. B. eine andere Domain oder unter einem anderen URL-Pfad-Präfix), und würde diese Kommunikation an die richtigen Container weiterleiten für *diese andere* Anwendung, die in Ihrem Cluster ausgeführt wird. + +### Ein Prozess pro Container + +In einem solchen Szenario möchten Sie wahrscheinlich **einen einzelnen (Uvicorn-)Prozess pro Container** haben, da Sie die Replikation bereits auf Cluster ebene durchführen würden. + +In diesem Fall möchten Sie also **nicht** einen Prozessmanager wie Gunicorn mit Uvicorn-Workern oder Uvicorn mit seinen eigenen Uvicorn-Workern haben. Sie möchten nur einen **einzelnen Uvicorn-Prozess** pro Container haben (wahrscheinlich aber mehrere Container). + +Ein weiterer Prozessmanager im Container (wie es bei Gunicorn oder Uvicorn der Fall wäre, welche Uvicorn-Worker verwalten) würde nur **unnötige Komplexität** hinzufügen, um welche Sie sich höchstwahrscheinlich bereits mit Ihrem Clustersystem kümmern. + +### Container mit mehreren Prozessen und Sonderfälle + +Natürlich gibt es **Sonderfälle**, in denen Sie **einen Container** mit einem **Gunicorn-Prozessmanager** haben möchten, welcher mehrere **Uvicorn-Workerprozesse** darin startet. + +In diesen Fällen können Sie das **offizielle Docker-Image** verwenden, welches **Gunicorn** als Prozessmanager enthält, welcher mehrere **Uvicorn-Workerprozesse** ausführt, sowie einige Standardeinstellungen, um die Anzahl der Worker basierend auf den verfügbaren CPU-Kernen automatisch anzupassen. Ich erzähle Ihnen weiter unten in [Offizielles Docker-Image mit Gunicorn – Uvicorn](#offizielles-docker-image-mit-gunicorn-uvicorn) mehr darüber. + +Hier sind einige Beispiele, wann das sinnvoll sein könnte: + +#### Eine einfache Anwendung + +Sie könnten einen Prozessmanager im Container haben wollen, wenn Ihre Anwendung **einfach genug** ist, sodass Sie die Anzahl der Prozesse nicht (zumindest noch nicht) zu stark tunen müssen und Sie einfach einen automatisierten Standard verwenden können (mit dem offiziellen Docker-Image), und Sie führen es auf einem **einzelnen Server** aus, nicht auf einem Cluster. + +#### Docker Compose + +Sie könnten das Deployment auf einem **einzelnen Server** (kein Cluster) mit **Docker Compose** durchführen, sodass Sie keine einfache Möglichkeit hätten, die Replikation von Containern (mit Docker Compose) zu verwalten und gleichzeitig das gemeinsame Netzwerk mit **Load Balancing** zu haben. + +Dann möchten Sie vielleicht **einen einzelnen Container** mit einem **Prozessmanager** haben, der darin **mehrere Workerprozesse** startet. + +#### Prometheus und andere Gründe + +Sie könnten auch **andere Gründe** haben, die es einfacher machen würden, einen **einzelnen Container** mit **mehreren Prozessen** zu haben, anstatt **mehrere Container** mit **einem einzelnen Prozess** in jedem von ihnen. + +Beispielsweise könnten Sie (abhängig von Ihrem Setup) ein Tool wie einen Prometheus-Exporter im selben Container haben, welcher Zugriff auf **jeden der eingehenden Requests** haben sollte. + +Wenn Sie in hier **mehrere Container** hätten, würde Prometheus beim **Lesen der Metriken** standardmäßig jedes Mal diejenigen für **einen einzelnen Container** abrufen (für den Container, der den spezifischen Request verarbeitet hat), anstatt die **akkumulierten Metriken** für alle replizierten Container abzurufen. + +In diesem Fall könnte einfacher sein, **einen Container** mit **mehreren Prozessen** und ein lokales Tool (z. B. einen Prometheus-Exporter) in demselben Container zu haben, welches Prometheus-Metriken für alle internen Prozesse sammelt und diese Metriken für diesen einzelnen Container offenlegt. + +--- + +Der Hauptpunkt ist, dass **keine** dieser Regeln **in Stein gemeißelt** ist, der man blind folgen muss. Sie können diese Ideen verwenden, um **Ihren eigenen Anwendungsfall zu evaluieren**, zu entscheiden, welcher Ansatz für Ihr System am besten geeignet ist und herauszufinden, wie Sie folgende Konzepte verwalten: + +* Sicherheit – HTTPS +* Beim Hochfahren ausführen +* Neustarts +* Replikation (die Anzahl der laufenden Prozesse) +* Arbeitsspeicher +* Schritte vor dem Start + +## Arbeitsspeicher + +Wenn Sie **einen einzelnen Prozess pro Container** ausführen, wird von jedem dieser Container (mehr als einer, wenn sie repliziert werden) eine mehr oder weniger klar definierte, stabile und begrenzte Menge an Arbeitsspeicher verbraucht. + +Und dann können Sie dieselben Speichergrenzen und -anforderungen in Ihren Konfigurationen für Ihr Container-Management-System festlegen (z. B. in **Kubernetes**). Auf diese Weise ist es in der Lage, die Container auf den **verfügbaren Maschinen** zu replizieren, wobei die von denen benötigte Speichermenge und die auf den Maschinen im Cluster verfügbare Menge berücksichtigt werden. + +Wenn Ihre Anwendung **einfach** ist, wird dies wahrscheinlich **kein Problem darstellen** und Sie müssen möglicherweise keine festen Speichergrenzen angeben. Wenn Sie jedoch **viel Speicher verbrauchen** (z. B. bei **Modellen für maschinelles Lernen**), sollten Sie überprüfen, wie viel Speicher Sie verbrauchen, und die **Anzahl der Container** anpassen, die in **jeder Maschine** ausgeführt werden. (und möglicherweise weitere Maschinen zu Ihrem Cluster hinzufügen). + +Wenn Sie **mehrere Prozesse pro Container** ausführen (zum Beispiel mit dem offiziellen Docker-Image), müssen Sie sicherstellen, dass die Anzahl der gestarteten Prozesse nicht **mehr Speicher verbraucht** als verfügbar ist. + +## Schritte vor dem Start und Container + +Wenn Sie Container (z. B. Docker, Kubernetes) verwenden, können Sie hauptsächlich zwei Ansätze verwenden. + +### Mehrere Container + +Wenn Sie **mehrere Container** haben, von denen wahrscheinlich jeder einen **einzelnen Prozess** ausführt (z. B. in einem **Kubernetes**-Cluster), dann möchten Sie wahrscheinlich einen **separaten Container** haben, welcher die Arbeit der **Vorab-Schritte** in einem einzelnen Container, mit einem einzelnenen Prozess ausführt, **bevor** die replizierten Workercontainer ausgeführt werden. + +/// info + +Wenn Sie Kubernetes verwenden, wäre dies wahrscheinlich ein Init-Container. + +/// + +Wenn es in Ihrem Anwendungsfall kein Problem darstellt, diese vorherigen Schritte **mehrmals parallel** auszuführen (z. B. wenn Sie keine Datenbankmigrationen ausführen, sondern nur prüfen, ob die Datenbank bereits bereit ist), können Sie sie auch einfach in jedem Container direkt vor dem Start des Hauptprozesses einfügen. + +### Einzelner Container + +Wenn Sie ein einfaches Setup mit einem **einzelnen Container** haben, welcher dann mehrere **Workerprozesse** (oder auch nur einen Prozess) startet, können Sie die Vorab-Schritte im selben Container direkt vor dem Starten des Prozesses mit der Anwendung ausführen. Das offizielle Docker-Image unterstützt das intern. + +## Offizielles Docker-Image mit Gunicorn – Uvicorn + +Es gibt ein offizielles Docker-Image, in dem Gunicorn mit Uvicorn-Workern ausgeführt wird, wie in einem vorherigen Kapitel beschrieben: [Serverworker – Gunicorn mit Uvicorn](server-workers.md){.internal-link target=_blank}. + +Dieses Image wäre vor allem in den oben beschriebenen Situationen nützlich: [Container mit mehreren Prozessen und Sonderfälle](#container-mit-mehreren-prozessen-und-sonderfalle). + +* tiangolo/uvicorn-gunicorn-fastapi. + +/// warning | Achtung + +Es besteht eine hohe Wahrscheinlichkeit, dass Sie dieses oder ein ähnliches Basisimage **nicht** benötigen und es besser wäre, wenn Sie das Image von Grund auf neu erstellen würden, wie [oben beschrieben in: Ein Docker-Image für FastAPI erstellen](#ein-docker-image-fur-fastapi-erstellen). + +/// + +Dieses Image verfügt über einen **Auto-Tuning**-Mechanismus, um die **Anzahl der Arbeitsprozesse** basierend auf den verfügbaren CPU-Kernen festzulegen. + +Es verfügt über **vernünftige Standardeinstellungen**, aber Sie können trotzdem alle Konfigurationen mit **Umgebungsvariablen** oder Konfigurationsdateien ändern und aktualisieren. + +Es unterstützt auch die Ausführung von **Vorab-Schritten vor dem Start** mit einem Skript. + +/// tip | Tipp + +Um alle Konfigurationen und Optionen anzuzeigen, gehen Sie zur Docker-Image-Seite: tiangolo/uvicorn-gunicorn-fastapi. + +/// + +### Anzahl der Prozesse auf dem offiziellen Docker-Image + +Die **Anzahl der Prozesse** auf diesem Image wird **automatisch** anhand der verfügbaren CPU-**Kerne** berechnet. + +Das bedeutet, dass versucht wird, so viel **Leistung** wie möglich aus der CPU herauszuquetschen. + +Sie können das auch in der Konfiguration anpassen, indem Sie **Umgebungsvariablen**, usw. verwenden. + +Das bedeutet aber auch, da die Anzahl der Prozesse von der CPU abhängt, welche der Container ausführt, dass die **Menge des verbrauchten Speichers** ebenfalls davon abhängt. + +Wenn Ihre Anwendung also viel Speicher verbraucht (z. B. bei Modellen für maschinelles Lernen) und Ihr Server über viele CPU-Kerne, **aber wenig Speicher** verfügt, könnte Ihr Container am Ende versuchen, mehr Speicher als vorhanden zu verwenden, was zu erheblichen Leistungseinbußen (oder sogar zum Absturz) führen kann. 🚨 + +### Ein `Dockerfile` erstellen + +So würden Sie ein `Dockerfile` basierend auf diesem Image erstellen: + +```Dockerfile +FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9 + +COPY ./requirements.txt /app/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt + +COPY ./app /app +``` + +### Größere Anwendungen + +Wenn Sie dem Abschnitt zum Erstellen von [größeren Anwendungen mit mehreren Dateien](../tutorial/bigger-applications.md){.internal-link target=_blank} gefolgt sind, könnte Ihr `Dockerfile` stattdessen wie folgt aussehen: + +```Dockerfile hl_lines="7" +FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9 + +COPY ./requirements.txt /app/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt + +COPY ./app /app/app +``` + +### Wann verwenden + +Sie sollten dieses offizielle Basisimage (oder ein ähnliches) wahrscheinlich **nicht** benutzen, wenn Sie **Kubernetes** (oder andere) verwenden und Sie bereits **Replikation** auf Cluster ebene mit mehreren **Containern** eingerichtet haben. In diesen Fällen ist es besser, **ein Image von Grund auf zu erstellen**, wie oben beschrieben: [Ein Docker-Image für FastAPI erstellen](#ein-docker-image-fur-fastapi-erstellen). + +Dieses Image wäre vor allem in den oben in [Container mit mehreren Prozessen und Sonderfälle](#container-mit-mehreren-prozessen-und-sonderfalle) beschriebenen Sonderfällen nützlich. Wenn Ihre Anwendung beispielsweise **einfach genug** ist, dass das Festlegen einer Standardanzahl von Prozessen basierend auf der CPU gut funktioniert, möchten Sie sich nicht mit der manuellen Konfiguration der Replikation auf Cluster ebene herumschlagen und führen nicht mehr als einen Container mit Ihrer Anwendung aus. Oder wenn Sie das Deployment mit **Docker Compose** durchführen und auf einem einzelnen Server laufen, usw. + +## Deployment des Containerimages + +Nachdem Sie ein Containerimage (Docker) haben, gibt es mehrere Möglichkeiten, es bereitzustellen. + +Zum Beispiel: + +* Mit **Docker Compose** auf einem einzelnen Server +* Mit einem **Kubernetes**-Cluster +* Mit einem Docker Swarm Mode-Cluster +* Mit einem anderen Tool wie Nomad +* Mit einem Cloud-Dienst, der Ihr Containerimage nimmt und es bereitstellt + +## Docker-Image mit Poetry + +Wenn Sie Poetry verwenden, um die Abhängigkeiten Ihres Projekts zu verwalten, können Sie Dockers mehrphasige Builds verwenden: + +```{ .dockerfile .annotate } +# (1) +FROM python:3.9 as requirements-stage + +# (2) +WORKDIR /tmp + +# (3) +RUN pip install poetry + +# (4) +COPY ./pyproject.toml ./poetry.lock* /tmp/ + +# (5) +RUN poetry export -f requirements.txt --output requirements.txt --without-hashes + +# (6) +FROM python:3.9 + +# (7) +WORKDIR /code + +# (8) +COPY --from=requirements-stage /tmp/requirements.txt /code/requirements.txt + +# (9) +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +# (10) +COPY ./app /code/app + +# (11) +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] +``` + +1. Dies ist die erste Phase, genannt `requirements-stage` – „Anforderungsphase“. + +2. Setze `/tmp` als aktuelles Arbeitsverzeichnis. + + Hier werden wir die Datei `requirements.txt` generieren. + +3. Installiere Poetry in dieser Docker-Phase. + +4. Kopiere die Dateien `pyproject.toml` und `poetry.lock` in das Verzeichnis `/tmp`. + + Da es `./poetry.lock*` verwendet (endet mit einem `*`), stürzt es nicht ab, wenn diese Datei noch nicht verfügbar ist. + +5. Generiere die Datei `requirements.txt`. + +6. Dies ist die letzte Phase. Alles hier bleibt im endgültigen Containerimage erhalten. + +7. Setze das aktuelle Arbeitsverzeichnis auf `/code`. + +8. Kopiere die Datei `requirements.txt` in das Verzeichnis `/code`. + + Diese Datei existiert nur in der vorherigen Docker-Phase, deshalb verwenden wir `--from-requirements-stage`, um sie zu kopieren. + +9. Installiere die Paketabhängigkeiten von der generierten Datei `requirements.txt`. + +10. Kopiere das Verzeichnis `app` in das Verzeichnis `/code`. + +11. Führe den Befehl `uvicorn` aus und weise ihn an, das aus `app.main` importierte `app`-Objekt zu verwenden. + +/// tip | Tipp + +Klicken Sie auf die Zahlenblasen, um zu sehen, was jede Zeile bewirkt. + +/// + +Eine **Docker-Phase** ist ein Teil eines `Dockerfile`s, welcher als **temporäres Containerimage** fungiert und nur zum Generieren einiger Dateien für die spätere Verwendung verwendet wird. + +Die erste Phase wird nur zur **Installation von Poetry** und zur **Generierung der `requirements.txt`** mit deren Projektabhängigkeiten aus der Datei `pyproject.toml` von Poetry verwendet. + +Diese `requirements.txt`-Datei wird später in der **nächsten Phase** mit `pip` verwendet. + +Im endgültigen Containerimage bleibt **nur die letzte Stufe** erhalten. Die vorherigen Stufen werden verworfen. + +Bei der Verwendung von Poetry wäre es sinnvoll, **mehrstufige Docker-Builds** zu verwenden, da Poetry und seine Abhängigkeiten nicht wirklich im endgültigen Containerimage installiert sein müssen, sondern Sie brauchen **nur** die Datei `requirements.txt`, um Ihre Projektabhängigkeiten zu installieren. + +Dann würden Sie im nächsten (und letzten) Schritt das Image mehr oder weniger auf die gleiche Weise wie zuvor beschrieben erstellen. + +### Hinter einem TLS-Terminierungsproxy – Poetry + +Auch hier gilt: Wenn Sie Ihren Container hinter einem TLS-Terminierungsproxy (Load Balancer) wie Nginx oder Traefik ausführen, fügen Sie dem Befehl die Option `--proxy-headers` hinzu: + +```Dockerfile +CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"] +``` + +## Zusammenfassung + +Mithilfe von Containersystemen (z. B. mit **Docker** und **Kubernetes**) ist es ziemlich einfach, alle **Deployment-Konzepte** zu handhaben: + +* HTTPS +* Beim Hochfahren ausführen +* Neustarts +* Replikation (die Anzahl der laufenden Prozesse) +* Arbeitsspeicher +* Schritte vor dem Start + +In den meisten Fällen möchten Sie wahrscheinlich kein Basisimage verwenden und stattdessen **ein Containerimage von Grund auf erstellen**, eines basierend auf dem offiziellen Python-Docker-Image. + +Indem Sie auf die **Reihenfolge** der Anweisungen im `Dockerfile` und den **Docker-Cache** achten, können Sie **die Build-Zeiten minimieren**, um Ihre Produktivität zu erhöhen (und Langeweile zu vermeiden). 😎 + +In bestimmten Sonderfällen möchten Sie möglicherweise das offizielle Docker-Image für FastAPI verwenden. 🤓 diff --git a/docs/de/docs/deployment/https.md b/docs/de/docs/deployment/https.md new file mode 100644 index 000000000..630582995 --- /dev/null +++ b/docs/de/docs/deployment/https.md @@ -0,0 +1,199 @@ +# Über HTTPS + +Es ist leicht anzunehmen, dass HTTPS etwas ist, was einfach nur „aktiviert“ wird oder nicht. + +Aber es ist viel komplexer als das. + +/// tip | Tipp + +Wenn Sie es eilig haben oder es Ihnen egal ist, fahren Sie mit den nächsten Abschnitten fort, um Schritt-für-Schritt-Anleitungen für die Einrichtung der verschiedenen Technologien zu erhalten. + +/// + +Um **die Grundlagen von HTTPS** aus Sicht des Benutzers zu erlernen, schauen Sie sich https://howhttps.works/ an. + +Aus **Sicht des Entwicklers** sollten Sie beim Nachdenken über HTTPS Folgendes beachten: + +* Für HTTPS muss **der Server** über von einem **Dritten** generierte **„Zertifikate“** verfügen. + * Diese Zertifikate werden tatsächlich vom Dritten **erworben** und nicht „generiert“. +* Zertifikate haben eine **Lebensdauer**. + * Sie **verfallen**. + * Und dann müssen sie vom Dritten **erneuert**, **erneut erworben** werden. +* Die Verschlüsselung der Verbindung erfolgt auf **TCP-Ebene**. + * Das ist eine Schicht **unter HTTP**. + * Die Handhabung von **Zertifikaten und Verschlüsselung** erfolgt also **vor HTTP**. +* **TCP weiß nichts über „Domains“**. Nur über IP-Adressen. + * Die Informationen über die angeforderte **spezifische Domain** befinden sich in den **HTTP-Daten**. +* Die **HTTPS-Zertifikate** „zertifizieren“ eine **bestimmte Domain**, aber das Protokoll und die Verschlüsselung erfolgen auf TCP-Ebene, **ohne zu wissen**, um welche Domain es sich handelt. +* **Standardmäßig** bedeutet das, dass Sie nur **ein HTTPS-Zertifikat pro IP-Adresse** haben können. + * Ganz gleich, wie groß Ihr Server ist oder wie klein die einzelnen Anwendungen darauf sind. + * Hierfür gibt es jedoch eine **Lösung**. +* Es gibt eine **Erweiterung** zum **TLS**-Protokoll (dasjenige, das die Verschlüsselung auf TCP-Ebene, vor HTTP, verwaltet) namens **SNI**. + * Mit dieser SNI-Erweiterung kann ein einzelner Server (mit einer **einzelnen IP-Adresse**) über **mehrere HTTPS-Zertifikate** verfügen und **mehrere HTTPS-Domains/Anwendungen** bedienen. + * Damit das funktioniert, muss eine **einzelne** Komponente (Programm), die auf dem Server ausgeführt wird und welche die **öffentliche IP-Adresse** überwacht, **alle HTTPS-Zertifikate** des Servers haben. +* **Nachdem** eine sichere Verbindung hergestellt wurde, ist das Kommunikationsprotokoll **immer noch HTTP**. + * Die Inhalte sind **verschlüsselt**, auch wenn sie mit dem **HTTP-Protokoll** gesendet werden. + +Es ist eine gängige Praxis, **ein Programm/HTTP-Server** auf dem Server (der Maschine, dem Host usw.) laufen zu lassen, welches **alle HTTPS-Aspekte verwaltet**: Empfangen der **verschlüsselten HTTPS-Requests**, Senden der **entschlüsselten HTTP-Requests** an die eigentliche HTTP-Anwendung die auf demselben Server läuft (in diesem Fall die **FastAPI**-Anwendung), entgegennehmen der **HTTP-Response** von der Anwendung, **verschlüsseln derselben** mithilfe des entsprechenden **HTTPS-Zertifikats** und Zurücksenden zum Client über **HTTPS**. Dieser Server wird oft als **TLS-Terminierungsproxy** bezeichnet. + +Einige der Optionen, die Sie als TLS-Terminierungsproxy verwenden können, sind: + +* Traefik (kann auch Zertifikat-Erneuerungen durchführen) +* Caddy (kann auch Zertifikat-Erneuerungen durchführen) +* Nginx +* HAProxy + +## Let's Encrypt + +Vor Let's Encrypt wurden diese **HTTPS-Zertifikate** von vertrauenswürdigen Dritten verkauft. + +Der Prozess zum Erwerb eines dieser Zertifikate war früher umständlich, erforderte viel Papierarbeit und die Zertifikate waren ziemlich teuer. + +Aber dann wurde **Let's Encrypt** geschaffen. + +Es ist ein Projekt der Linux Foundation. Es stellt **kostenlose HTTPS-Zertifikate** automatisiert zur Verfügung. Diese Zertifikate nutzen standardmäßig die gesamte kryptografische Sicherheit und sind kurzlebig (circa 3 Monate), sodass die **Sicherheit tatsächlich besser ist**, aufgrund der kürzeren Lebensdauer. + +Die Domains werden sicher verifiziert und die Zertifikate werden automatisch generiert. Das ermöglicht auch die automatische Erneuerung dieser Zertifikate. + +Die Idee besteht darin, den Erwerb und die Erneuerung der Zertifikate zu automatisieren, sodass Sie **sicheres HTTPS, kostenlos und für immer** haben können. + +## HTTPS für Entwickler + +Hier ist ein Beispiel, wie eine HTTPS-API aussehen könnte, Schritt für Schritt, wobei vor allem die für Entwickler wichtigen Ideen berücksichtigt werden. + +### Domainname + +Alles beginnt wahrscheinlich damit, dass Sie einen **Domainnamen erwerben**. Anschließend konfigurieren Sie ihn in einem DNS-Server (wahrscheinlich beim selben Cloud-Anbieter). + +Sie würden wahrscheinlich einen Cloud-Server (eine virtuelle Maschine) oder etwas Ähnliches bekommen, und dieser hätte eine feste **öffentliche IP-Adresse**. + +In dem oder den DNS-Server(n) würden Sie einen Eintrag (einen „`A record`“) konfigurieren, um mit **Ihrer Domain** auf die öffentliche **IP-Adresse Ihres Servers** zu verweisen. + +Sie würden dies wahrscheinlich nur einmal tun, beim ersten Mal, wenn Sie alles einrichten. + +/// tip | Tipp + +Dieser Domainnamen-Aspekt liegt weit vor HTTPS, aber da alles von der Domain und der IP-Adresse abhängt, lohnt es sich, das hier zu erwähnen. + +/// + +### DNS + +Konzentrieren wir uns nun auf alle tatsächlichen HTTPS-Aspekte. + +Zuerst würde der Browser mithilfe der **DNS-Server** herausfinden, welches die **IP für die Domain** ist, in diesem Fall für `someapp.example.com`. + +Die DNS-Server geben dem Browser eine bestimmte **IP-Adresse** zurück. Das wäre die von Ihrem Server verwendete öffentliche IP-Adresse, die Sie in den DNS-Servern konfiguriert haben. + + + +### TLS-Handshake-Start + +Der Browser kommuniziert dann mit dieser IP-Adresse über **Port 443** (den HTTPS-Port). + +Der erste Teil der Kommunikation besteht lediglich darin, die Verbindung zwischen dem Client und dem Server herzustellen und die zu verwendenden kryptografischen Schlüssel usw. zu vereinbaren. + + + +Diese Interaktion zwischen dem Client und dem Server zum Aufbau der TLS-Verbindung wird als **TLS-Handshake** bezeichnet. + +### TLS mit SNI-Erweiterung + +**Nur ein Prozess** im Server kann an einem bestimmten **Port** einer bestimmten **IP-Adresse** lauschen. Möglicherweise gibt es andere Prozesse, die an anderen Ports dieselbe IP-Adresse abhören, jedoch nur einen für jede Kombination aus IP-Adresse und Port. + +TLS (HTTPS) verwendet standardmäßig den spezifischen Port `443`. Das ist also der Port, den wir brauchen. + +Da an diesem Port nur ein Prozess lauschen kann, wäre der Prozess, der dies tun würde, der **TLS-Terminierungsproxy**. + +Der TLS-Terminierungsproxy hätte Zugriff auf ein oder mehrere **TLS-Zertifikate** (HTTPS-Zertifikate). + +Mithilfe der oben beschriebenen **SNI-Erweiterung** würde der TLS-Terminierungsproxy herausfinden, welches der verfügbaren TLS-Zertifikate (HTTPS) er für diese Verbindung verwenden muss, und zwar das, welches mit der vom Client erwarteten Domain übereinstimmt. + +In diesem Fall würde er das Zertifikat für `someapp.example.com` verwenden. + + + +Der Client **vertraut** bereits der Entität, die das TLS-Zertifikat generiert hat (in diesem Fall Let's Encrypt, aber wir werden später mehr darüber erfahren), sodass er **verifizieren** kann, dass das Zertifikat gültig ist. + +Mithilfe des Zertifikats entscheiden der Client und der TLS-Terminierungsproxy dann, **wie der Rest der TCP-Kommunikation verschlüsselt werden soll**. Damit ist der **TLS-Handshake** abgeschlossen. + +Danach verfügen der Client und der Server über eine **verschlüsselte TCP-Verbindung**, via TLS. Und dann können sie diese Verbindung verwenden, um die eigentliche **HTTP-Kommunikation** zu beginnen. + +Und genau das ist **HTTPS**, es ist einfach **HTTP** innerhalb einer **sicheren TLS-Verbindung**, statt einer puren (unverschlüsselten) TCP-Verbindung. + +/// tip | Tipp + +Beachten Sie, dass die Verschlüsselung der Kommunikation auf der **TCP-Ebene** und nicht auf der HTTP-Ebene erfolgt. + +/// + +### HTTPS-Request + +Da Client und Server (sprich, der Browser und der TLS-Terminierungsproxy) nun über eine **verschlüsselte TCP-Verbindung** verfügen, können sie die **HTTP-Kommunikation** starten. + +Der Client sendet also einen **HTTPS-Request**. Das ist einfach ein HTTP-Request über eine verschlüsselte TLS-Verbindung. + + + +### Den Request entschlüsseln + +Der TLS-Terminierungsproxy würde die vereinbarte Verschlüsselung zum **Entschlüsseln des Requests** verwenden und den **einfachen (entschlüsselten) HTTP-Request** an den Prozess weiterleiten, der die Anwendung ausführt (z. B. einen Prozess, bei dem Uvicorn die FastAPI-Anwendung ausführt). + + + +### HTTP-Response + +Die Anwendung würde den Request verarbeiten und eine **einfache (unverschlüsselte) HTTP-Response** an den TLS-Terminierungsproxy senden. + + + +### HTTPS-Response + +Der TLS-Terminierungsproxy würde dann die Response mithilfe der zuvor vereinbarten Kryptografie (als das Zertifikat für `someapp.example.com` verhandelt wurde) **verschlüsseln** und sie an den Browser zurücksenden. + +Als Nächstes überprüft der Browser, ob die Response gültig und mit dem richtigen kryptografischen Schlüssel usw. verschlüsselt ist. Anschließend **entschlüsselt er die Response** und verarbeitet sie. + + + +Der Client (Browser) weiß, dass die Response vom richtigen Server kommt, da dieser die Kryptografie verwendet, die zuvor mit dem **HTTPS-Zertifikat** vereinbart wurde. + +### Mehrere Anwendungen + +Auf demselben Server (oder denselben Servern) könnten sich **mehrere Anwendungen** befinden, beispielsweise andere API-Programme oder eine Datenbank. + +Nur ein Prozess kann diese spezifische IP und den Port verarbeiten (in unserem Beispiel der TLS-Terminierungsproxy), aber die anderen Anwendungen/Prozesse können auch auf dem/den Server(n) ausgeführt werden, solange sie nicht versuchen, dieselbe **Kombination aus öffentlicher IP und Port** zu verwenden. + + + +Auf diese Weise könnte der TLS-Terminierungsproxy HTTPS und Zertifikate für **mehrere Domains**, für mehrere Anwendungen, verarbeiten und die Requests dann jeweils an die richtige Anwendung weiterleiten. + +### Verlängerung des Zertifikats + +Irgendwann in der Zukunft würde jedes Zertifikat **ablaufen** (etwa 3 Monate nach dem Erwerb). + +Und dann gäbe es ein anderes Programm (in manchen Fällen ist es ein anderes Programm, in manchen Fällen ist es derselbe TLS-Terminierungsproxy), das mit Let's Encrypt kommuniziert und das/die Zertifikat(e) erneuert. + + + +Die **TLS-Zertifikate** sind **einem Domainnamen zugeordnet**, nicht einer IP-Adresse. + +Um die Zertifikate zu erneuern, muss das erneuernde Programm der Behörde (Let's Encrypt) **nachweisen**, dass es diese Domain tatsächlich **besitzt und kontrolliert**. + +Um dies zu erreichen und den unterschiedlichen Anwendungsanforderungen gerecht zu werden, gibt es mehrere Möglichkeiten. Einige beliebte Methoden sind: + +* **Einige DNS-Einträge ändern**. + * Hierfür muss das erneuernde Programm die APIs des DNS-Anbieters unterstützen. Je nachdem, welchen DNS-Anbieter Sie verwenden, kann dies eine Option sein oder auch nicht. +* **Als Server ausführen** (zumindest während des Zertifikatserwerbsvorgangs), auf der öffentlichen IP-Adresse, die der Domain zugeordnet ist. + * Wie oben erwähnt, kann nur ein Prozess eine bestimmte IP und einen bestimmten Port überwachen. + * Das ist einer der Gründe, warum es sehr nützlich ist, wenn derselbe TLS-Terminierungsproxy auch den Zertifikats-Erneuerungsprozess übernimmt. + * Andernfalls müssen Sie möglicherweise den TLS-Terminierungsproxy vorübergehend stoppen, das Programm starten, welches die neuen Zertifikate beschafft, diese dann mit dem TLS-Terminierungsproxy konfigurieren und dann den TLS-Terminierungsproxy neu starten. Das ist nicht ideal, da Ihre Anwendung(en) während der Zeit, in der der TLS-Terminierungsproxy ausgeschaltet ist, nicht erreichbar ist/sind. + +Dieser ganze Erneuerungsprozess, während die Anwendung weiterhin bereitgestellt wird, ist einer der Hauptgründe, warum Sie ein **separates System zur Verarbeitung von HTTPS** mit einem TLS-Terminierungsproxy haben möchten, anstatt einfach die TLS-Zertifikate direkt mit dem Anwendungsserver zu verwenden (z. B. Uvicorn). + +## Zusammenfassung + +**HTTPS** zu haben ist sehr wichtig und in den meisten Fällen eine **kritische Anforderung**. Die meiste Arbeit, die Sie als Entwickler in Bezug auf HTTPS aufwenden müssen, besteht lediglich darin, **diese Konzepte zu verstehen** und wie sie funktionieren. + +Sobald Sie jedoch die grundlegenden Informationen zu **HTTPS für Entwickler** kennen, können Sie verschiedene Tools problemlos kombinieren und konfigurieren, um alles auf einfache Weise zu verwalten. + +In einigen der nächsten Kapitel zeige ich Ihnen einige konkrete Beispiele für die Einrichtung von **HTTPS** für **FastAPI**-Anwendungen. 🔒 diff --git a/docs/de/docs/deployment/index.md b/docs/de/docs/deployment/index.md new file mode 100644 index 000000000..1aa131097 --- /dev/null +++ b/docs/de/docs/deployment/index.md @@ -0,0 +1,21 @@ +# Deployment + +Das Deployment einer **FastAPI**-Anwendung ist relativ einfach. + +## Was bedeutet Deployment? + +**Deployment** (Deutsch etwa: **Bereitstellen der Anwendung**) bedeutet, die notwendigen Schritte durchzuführen, um die Anwendung **für die Endbenutzer verfügbar** zu machen. + +Bei einer **Web-API** bedeutet das normalerweise, diese auf einem **entfernten Rechner** zu platzieren, mit einem **Serverprogramm**, welches gute Leistung, Stabilität, usw. bietet, damit Ihre **Benutzer** auf die Anwendung effizient und ohne Unterbrechungen oder Probleme **zugreifen** können. + +Das steht im Gegensatz zu den **Entwicklungsphasen**, in denen Sie ständig den Code ändern, kaputt machen, reparieren, den Entwicklungsserver stoppen und neu starten, usw. + +## Deployment-Strategien + +Abhängig von Ihrem spezifischen Anwendungsfall und den von Ihnen verwendeten Tools gibt es mehrere Möglichkeiten, das zu tun. + +Sie könnten mithilfe einer Kombination von Tools selbst **einen Server bereitstellen**, Sie könnten einen **Cloud-Dienst** nutzen, der einen Teil der Arbeit für Sie erledigt, oder andere mögliche Optionen. + +Ich zeige Ihnen einige der wichtigsten Konzepte, die Sie beim Deployment einer **FastAPI**-Anwendung wahrscheinlich berücksichtigen sollten (obwohl das meiste davon auch für jede andere Art von Webanwendung gilt). + +In den nächsten Abschnitten erfahren Sie mehr über die zu beachtenden Details und über die Techniken, das zu tun. ✨ diff --git a/docs/de/docs/deployment/manually.md b/docs/de/docs/deployment/manually.md new file mode 100644 index 000000000..fdb33f7fe --- /dev/null +++ b/docs/de/docs/deployment/manually.md @@ -0,0 +1,159 @@ +# Einen Server manuell ausführen – Uvicorn + +Das Wichtigste, was Sie zum Ausführen einer **FastAPI**-Anwendung auf einer entfernten Servermaschine benötigen, ist ein ASGI-Serverprogramm, wie **Uvicorn**. + +Es gibt 3 Hauptalternativen: + +* Uvicorn: ein hochperformanter ASGI-Server. +* Hypercorn: ein ASGI-Server, der unter anderem mit HTTP/2 und Trio kompatibel ist. +* Daphne: Der für Django Channels entwickelte ASGI-Server. + +## Servermaschine und Serverprogramm + +Bei den Benennungen gibt es ein kleines Detail, das Sie beachten sollten. 💡 + +Das Wort „**Server**“ bezieht sich häufig sowohl auf den entfernten-/Cloud-Computer (die physische oder virtuelle Maschine) als auch auf das Programm, das auf dieser Maschine ausgeführt wird (z. B. Uvicorn). + +Denken Sie einfach daran, wenn Sie „Server“ im Allgemeinen lesen, dass es sich auf eines dieser beiden Dinge beziehen kann. + +Wenn man sich auf die entfernte Maschine bezieht, wird sie üblicherweise als **Server**, aber auch als **Maschine**, **VM** (virtuelle Maschine) oder **Knoten** bezeichnet. Diese Begriffe beziehen sich auf irgendeine Art von entfernten Rechner, normalerweise unter Linux, auf dem Sie Programme ausführen. + +## Das Serverprogramm installieren + +Sie können einen ASGI-kompatiblen Server installieren mit: + +//// tab | Uvicorn + +* Uvicorn, ein blitzschneller ASGI-Server, basierend auf uvloop und httptools. + +
+ +```console +$ pip install "uvicorn[standard]" + +---> 100% +``` + +
+ +/// tip | Tipp + +Durch das Hinzufügen von `standard` installiert und verwendet Uvicorn einige empfohlene zusätzliche Abhängigkeiten. + +Inklusive `uvloop`, einen hochperformanten Drop-in-Ersatz für `asyncio`, welcher für einen großen Leistungsschub bei der Nebenläufigkeit sorgt. + +/// + +//// + +//// tab | Hypercorn + +* Hypercorn, ein ASGI-Server, der auch mit HTTP/2 kompatibel ist. + +
+ +```console +$ pip install hypercorn + +---> 100% +``` + +
+ +... oder jeden anderen ASGI-Server. + +//// + +## Das Serverprogramm ausführen + +Anschließend können Sie Ihre Anwendung auf die gleiche Weise ausführen, wie Sie es in den Tutorials getan haben, jedoch ohne die Option `--reload`, z. B.: + +//// tab | Uvicorn + +
+ +```console +$ uvicorn main:app --host 0.0.0.0 --port 80 + +INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) +``` + +
+ +//// + +//// tab | Hypercorn + +
+ +```console +$ hypercorn main:app --bind 0.0.0.0:80 + +Running on 0.0.0.0:8080 over http (CTRL + C to quit) +``` + +
+ +//// + +/// warning | Achtung + +Denken Sie daran, die Option `--reload` zu entfernen, wenn Sie diese verwendet haben. + +Die Option `--reload` verbraucht viel mehr Ressourcen, ist instabiler, usw. + +Sie hilft sehr während der **Entwicklung**, aber Sie sollten sie **nicht** in der **Produktion** verwenden. + +/// + +## Hypercorn mit Trio + +Starlette und **FastAPI** basieren auf AnyIO, welches diese sowohl mit der Python-Standardbibliothek asyncio, als auch mit Trio kompatibel macht. + +Dennoch ist Uvicorn derzeit nur mit asyncio kompatibel und verwendet normalerweise `uvloop`, den leistungsstarken Drop-in-Ersatz für `asyncio`. + +Wenn Sie jedoch **Trio** direkt verwenden möchten, können Sie **Hypercorn** verwenden, da dieses es unterstützt. ✨ + +### Hypercorn mit Trio installieren + +Zuerst müssen Sie Hypercorn mit Trio-Unterstützung installieren: + +
+ +```console +$ pip install "hypercorn[trio]" +---> 100% +``` + +
+ +### Mit Trio ausführen + +Dann können Sie die Befehlszeilenoption `--worker-class` mit dem Wert `trio` übergeben: + +
+ +```console +$ hypercorn main:app --worker-class trio +``` + +
+ +Und das startet Hypercorn mit Ihrer Anwendung und verwendet Trio als Backend. + +Jetzt können Sie Trio intern in Ihrer Anwendung verwenden. Oder noch besser: Sie können AnyIO verwenden, sodass Ihr Code sowohl mit Trio als auch asyncio kompatibel ist. 🎉 + +## Konzepte des Deployments + +Obige Beispiele führen das Serverprogramm (z. B. Uvicorn) aus, starten **einen einzelnen Prozess** und überwachen alle IPs (`0.0.0.0`) an einem vordefinierten Port (z. B. `80`). + +Das ist die Grundidee. Aber Sie möchten sich wahrscheinlich um einige zusätzliche Dinge kümmern, wie zum Beispiel: + +* Sicherheit – HTTPS +* Beim Hochfahren ausführen +* Neustarts +* Replikation (die Anzahl der laufenden Prozesse) +* Arbeitsspeicher +* Schritte vor dem Start + +In den nächsten Kapiteln erzähle ich Ihnen mehr über jedes dieser Konzepte, wie Sie über diese nachdenken, und gebe Ihnen einige konkrete Beispiele mit Strategien für den Umgang damit. 🚀 diff --git a/docs/de/docs/deployment/server-workers.md b/docs/de/docs/deployment/server-workers.md new file mode 100644 index 000000000..5cd282b4b --- /dev/null +++ b/docs/de/docs/deployment/server-workers.md @@ -0,0 +1,183 @@ +# Serverworker – Gunicorn mit Uvicorn + +Schauen wir uns die Deployment-Konzepte von früher noch einmal an: + +* Sicherheit – HTTPS +* Beim Hochfahren ausführen +* Neustarts +* **Replikation (die Anzahl der laufenden Prozesse)** +* Arbeitsspeicher +* Schritte vor dem Start + +Bis zu diesem Punkt, in allen Tutorials in der Dokumentation, haben Sie wahrscheinlich ein **Serverprogramm** wie Uvicorn ausgeführt, in einem **einzelnen Prozess**. + +Wenn Sie Anwendungen bereitstellen, möchten Sie wahrscheinlich eine gewisse **Replikation von Prozessen**, um **mehrere CPU-Kerne** zu nutzen und mehr Requests bearbeiten zu können. + +Wie Sie im vorherigen Kapitel über [Deployment-Konzepte](concepts.md){.internal-link target=_blank} gesehen haben, gibt es mehrere Strategien, die Sie anwenden können. + +Hier zeige ich Ihnen, wie Sie **Gunicorn** mit **Uvicorn Workerprozessen** verwenden. + +/// info + +Wenn Sie Container verwenden, beispielsweise mit Docker oder Kubernetes, erzähle ich Ihnen mehr darüber im nächsten Kapitel: [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank}. + +Insbesondere wenn die Anwendung auf **Kubernetes** läuft, werden Sie Gunicorn wahrscheinlich **nicht** verwenden wollen und stattdessen **einen einzelnen Uvicorn-Prozess pro Container** ausführen wollen, aber ich werde Ihnen später in diesem Kapitel mehr darüber erzählen. + +/// + +## Gunicorn mit Uvicorn-Workern + +**Gunicorn** ist hauptsächlich ein Anwendungsserver, der den **WSGI-Standard** verwendet. Das bedeutet, dass Gunicorn Anwendungen wie Flask und Django ausliefern kann. Gunicorn selbst ist nicht mit **FastAPI** kompatibel, da FastAPI den neuesten **ASGI-Standard** verwendet. + +Aber Gunicorn kann als **Prozessmanager** arbeiten und Benutzer können ihm mitteilen, welche bestimmte **Workerprozessklasse** verwendet werden soll. Dann würde Gunicorn einen oder mehrere **Workerprozesse** starten, diese Klasse verwendend. + +Und **Uvicorn** hat eine **Gunicorn-kompatible Workerklasse**. + +Mit dieser Kombination würde Gunicorn als **Prozessmanager** fungieren und den **Port** und die **IP** abhören. Und er würde die Kommunikation an die Workerprozesse **weiterleiten**, welche die **Uvicorn-Klasse** ausführen. + +Und dann wäre die Gunicorn-kompatible **Uvicorn-Worker**-Klasse dafür verantwortlich, die von Gunicorn gesendeten Daten in den ASGI-Standard zu konvertieren, damit FastAPI diese verwenden kann. + +## Gunicorn und Uvicorn installieren + +
+ +```console +$ pip install "uvicorn[standard]" gunicorn + +---> 100% +``` + +
+ +Dadurch wird sowohl Uvicorn mit zusätzlichen `standard`-Packages (um eine hohe Leistung zu erzielen) als auch Gunicorn installiert. + +## Gunicorn mit Uvicorn-Workern ausführen + +Dann können Sie Gunicorn ausführen mit: + +
+ +```console +$ gunicorn main:app --workers 4 --worker-class uvicorn.workers.UvicornWorker --bind 0.0.0.0:80 + +[19499] [INFO] Starting gunicorn 20.1.0 +[19499] [INFO] Listening at: http://0.0.0.0:80 (19499) +[19499] [INFO] Using worker: uvicorn.workers.UvicornWorker +[19511] [INFO] Booting worker with pid: 19511 +[19513] [INFO] Booting worker with pid: 19513 +[19514] [INFO] Booting worker with pid: 19514 +[19515] [INFO] Booting worker with pid: 19515 +[19511] [INFO] Started server process [19511] +[19511] [INFO] Waiting for application startup. +[19511] [INFO] Application startup complete. +[19513] [INFO] Started server process [19513] +[19513] [INFO] Waiting for application startup. +[19513] [INFO] Application startup complete. +[19514] [INFO] Started server process [19514] +[19514] [INFO] Waiting for application startup. +[19514] [INFO] Application startup complete. +[19515] [INFO] Started server process [19515] +[19515] [INFO] Waiting for application startup. +[19515] [INFO] Application startup complete. +``` + +
+ +Sehen wir uns an, was jede dieser Optionen bedeutet: + +* `main:app`: Das ist die gleiche Syntax, die auch von Uvicorn verwendet wird. `main` bedeutet das Python-Modul mit dem Namen `main`, also eine Datei `main.py`. Und `app` ist der Name der Variable, welche die **FastAPI**-Anwendung ist. + * Stellen Sie sich einfach vor, dass `main:app` einer Python-`import`-Anweisung wie der folgenden entspricht: + + ```Python + from main import app + ``` + + * Der Doppelpunkt in `main:app` entspricht also dem Python-`import`-Teil in `from main import app`. + +* `--workers`: Die Anzahl der zu verwendenden Workerprozesse, jeder führt einen Uvicorn-Worker aus, in diesem Fall 4 Worker. + +* `--worker-class`: Die Gunicorn-kompatible Workerklasse zur Verwendung in den Workerprozessen. + * Hier übergeben wir die Klasse, die Gunicorn etwa so importiert und verwendet: + + ```Python + import uvicorn.workers.UvicornWorker + ``` + +* `--bind`: Das teilt Gunicorn die IP und den Port mit, welche abgehört werden sollen, wobei ein Doppelpunkt (`:`) verwendet wird, um die IP und den Port zu trennen. + * Wenn Sie Uvicorn direkt ausführen würden, würden Sie anstelle von `--bind 0.0.0.0:80` (die Gunicorn-Option) stattdessen `--host 0.0.0.0` und `--port 80` verwenden. + +In der Ausgabe können Sie sehen, dass die **PID** (Prozess-ID) jedes Prozesses angezeigt wird (es ist nur eine Zahl). + +Sie können sehen, dass: + +* Der Gunicorn **Prozessmanager** beginnt, mit der PID `19499` (in Ihrem Fall ist es eine andere Nummer). +* Dann beginnt er zu lauschen: `Listening at: http://0.0.0.0:80`. +* Dann erkennt er, dass er die Workerklasse `uvicorn.workers.UvicornWorker` verwenden muss. +* Und dann werden **4 Worker** gestartet, jeder mit seiner eigenen PID: `19511`, `19513`, `19514` und `19515`. + +Gunicorn würde sich bei Bedarf auch um die Verwaltung **beendeter Prozesse** und den **Neustart** von Prozessen kümmern, um die Anzahl der Worker aufrechtzuerhalten. Das hilft also teilweise beim **Neustarts**-Konzept aus der obigen Liste. + +Dennoch möchten Sie wahrscheinlich auch etwas außerhalb haben, um sicherzustellen, dass Gunicorn bei Bedarf **neu gestartet wird**, und er auch **beim Hochfahren ausgeführt wird**, usw. + +## Uvicorn mit Workern + +Uvicorn bietet ebenfalls die Möglichkeit, mehrere **Workerprozesse** zu starten und auszuführen. + +Dennoch sind die Fähigkeiten von Uvicorn zur Abwicklung von Workerprozessen derzeit eingeschränkter als die von Gunicorn. Wenn Sie also einen Prozessmanager auf dieser Ebene (auf der Python-Ebene) haben möchten, ist es vermutlich besser, es mit Gunicorn als Prozessmanager zu versuchen. + +Wie auch immer, Sie würden es so ausführen: + +
+ +```console +$ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4 +INFO: Uvicorn running on http://0.0.0.0:8080 (Press CTRL+C to quit) +INFO: Started parent process [27365] +INFO: Started server process [27368] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Started server process [27369] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Started server process [27370] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Started server process [27367] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +Die einzige neue Option hier ist `--workers`, die Uvicorn anweist, 4 Workerprozesse zu starten. + +Sie können auch sehen, dass die **PID** jedes Prozesses angezeigt wird, `27365` für den übergeordneten Prozess (dies ist der **Prozessmanager**) und eine für jeden Workerprozess: `27368`, `27369`, `27370` und `27367`. + +## Deployment-Konzepte + +Hier haben Sie gesehen, wie Sie mit **Gunicorn** (oder Uvicorn) **Uvicorn-Workerprozesse** verwalten, um die Ausführung der Anwendung zu **parallelisieren**, **mehrere Kerne** der CPU zu nutzen und in der Lage zu sein, **mehr Requests** zu bedienen. + +In der Liste der Deployment-Konzepte von oben würde die Verwendung von Workern hauptsächlich beim **Replikation**-Teil und ein wenig bei **Neustarts** helfen, aber Sie müssen sich trotzdem um die anderen kümmern: + +* **Sicherheit – HTTPS** +* **Beim Hochfahren ausführen** +* **Neustarts** +* Replikation (die Anzahl der laufenden Prozesse) +* **Arbeitsspeicher** +* **Schritte vor dem Start** + +## Container und Docker + +Im nächsten Kapitel über [FastAPI in Containern – Docker](docker.md){.internal-link target=_blank} werde ich einige Strategien erläutern, die Sie für den Umgang mit den anderen **Deployment-Konzepten** verwenden können. + +Ich zeige Ihnen auch das **offizielle Docker-Image**, welches **Gunicorn mit Uvicorn-Workern** und einige Standardkonfigurationen enthält, die für einfache Fälle nützlich sein können. + +Dort zeige ich Ihnen auch, wie Sie **Ihr eigenes Image von Grund auf erstellen**, um einen einzelnen Uvicorn-Prozess (ohne Gunicorn) auszuführen. Es ist ein einfacher Vorgang und wahrscheinlich das, was Sie tun möchten, wenn Sie ein verteiltes Containerverwaltungssystem wie **Kubernetes** verwenden. + +## Zusammenfassung + +Sie können **Gunicorn** (oder auch Uvicorn) als Prozessmanager mit Uvicorn-Workern verwenden, um **Multikern-CPUs** zu nutzen und **mehrere Prozesse parallel** auszuführen. + +Sie können diese Tools und Ideen nutzen, wenn Sie **Ihr eigenes Deployment-System** einrichten und sich dabei selbst um die anderen Deployment-Konzepte kümmern. + +Schauen Sie sich das nächste Kapitel an, um mehr über **FastAPI** mit Containern (z. B. Docker und Kubernetes) zu erfahren. Sie werden sehen, dass diese Tools auch einfache Möglichkeiten bieten, die anderen **Deployment-Konzepte** zu lösen. ✨ diff --git a/docs/de/docs/deployment/versions.md b/docs/de/docs/deployment/versions.md new file mode 100644 index 000000000..5b8c69754 --- /dev/null +++ b/docs/de/docs/deployment/versions.md @@ -0,0 +1,92 @@ +# Über FastAPI-Versionen + +**FastAPI** wird bereits in vielen Anwendungen und Systemen produktiv eingesetzt. Und die Testabdeckung wird bei 100 % gehalten. Aber seine Entwicklung geht immer noch schnell voran. + +Es werden regelmäßig neue Funktionen hinzugefügt, Fehler werden regelmäßig behoben und der Code wird weiterhin kontinuierlich verbessert. + +Aus diesem Grund sind die aktuellen Versionen immer noch `0.x.x`, was darauf hindeutet, dass jede Version möglicherweise nicht abwärtskompatible Änderungen haben könnte. Dies folgt den Konventionen der semantischen Versionierung. + +Sie können jetzt Produktionsanwendungen mit **FastAPI** erstellen (und das tun Sie wahrscheinlich schon seit einiger Zeit), Sie müssen nur sicherstellen, dass Sie eine Version verwenden, die korrekt mit dem Rest Ihres Codes funktioniert. + +## `fastapi`-Version pinnen + +Als Erstes sollten Sie die Version von **FastAPI**, die Sie verwenden, an die höchste Version „pinnen“, von der Sie wissen, dass sie für Ihre Anwendung korrekt funktioniert. + +Angenommen, Sie verwenden in Ihrer Anwendung die Version `0.45.0`. + +Wenn Sie eine `requirements.txt`-Datei verwenden, können Sie die Version wie folgt angeben: + +```txt +fastapi==0.45.0 +``` + +Das würde bedeuten, dass Sie genau die Version `0.45.0` verwenden. + +Oder Sie können sie auch anpinnen mit: + +```txt +fastapi>=0.45.0,<0.46.0 +``` + +Das würde bedeuten, dass Sie eine Version `0.45.0` oder höher verwenden würden, aber kleiner als `0.46.0`, beispielsweise würde eine Version `0.45.2` immer noch akzeptiert. + +Wenn Sie zum Verwalten Ihrer Installationen andere Tools wie Poetry, Pipenv oder andere verwenden, sie verfügen alle über eine Möglichkeit, bestimmte Versionen für Ihre Packages zu definieren. + +## Verfügbare Versionen + +Die verfügbaren Versionen können Sie in den [Release Notes](../release-notes.md){.internal-link target=_blank} einsehen (z. B. um zu überprüfen, welches die neueste Version ist). + +## Über Versionen + +Gemäß den Konventionen zur semantischen Versionierung könnte jede Version unter `1.0.0` potenziell nicht abwärtskompatible Änderungen hinzufügen. + +FastAPI folgt auch der Konvention, dass jede „PATCH“-Versionsänderung für Bugfixes und abwärtskompatible Änderungen gedacht ist. + +/// tip | Tipp + +Der „PATCH“ ist die letzte Zahl, zum Beispiel ist in `0.2.3` die PATCH-Version `3`. + +/// + +Sie sollten also in der Lage sein, eine Version wie folgt anzupinnen: + +```txt +fastapi>=0.45.0,<0.46.0 +``` + +Nicht abwärtskompatible Änderungen und neue Funktionen werden in „MINOR“-Versionen hinzugefügt. + +/// tip | Tipp + +„MINOR“ ist die Zahl in der Mitte, zum Beispiel ist in `0.2.3` die MINOR-Version `2`. + +/// + +## Upgrade der FastAPI-Versionen + +Sie sollten Tests für Ihre Anwendung hinzufügen. + +Mit **FastAPI** ist das sehr einfach (dank Starlette), schauen Sie sich die Dokumentation an: [Testen](../tutorial/testing.md){.internal-link target=_blank} + +Nachdem Sie Tests erstellt haben, können Sie die **FastAPI**-Version auf eine neuere Version aktualisieren und sicherstellen, dass Ihr gesamter Code ordnungsgemäß funktioniert, indem Sie Ihre Tests ausführen. + +Wenn alles funktioniert oder nachdem Sie die erforderlichen Änderungen vorgenommen haben und alle Ihre Tests bestehen, können Sie Ihr `fastapi` an die neue aktuelle Version pinnen. + +## Über Starlette + +Sie sollten die Version von `starlette` nicht pinnen. + +Verschiedene Versionen von **FastAPI** verwenden eine bestimmte neuere Version von Starlette. + +Sie können **FastAPI** also einfach die korrekte Starlette-Version verwenden lassen. + +## Über Pydantic + +Pydantic integriert die Tests für **FastAPI** in seine eigenen Tests, sodass neue Versionen von Pydantic (über `1.0.0`) immer mit FastAPI kompatibel sind. + +Sie können Pydantic an jede für Sie geeignete Version über `1.0.0` und unter `2.0.0` anpinnen. + +Zum Beispiel: +```txt +pydantic>=1.2.0,<2.0.0 +``` diff --git a/docs/de/docs/features.md b/docs/de/docs/features.md index 64fa8092d..8fdf42622 100644 --- a/docs/de/docs/features.md +++ b/docs/de/docs/features.md @@ -2,20 +2,20 @@ ## FastAPI Merkmale -**FastAPI** ermöglicht Ihnen folgendes: +**FastAPI** ermöglicht Ihnen Folgendes: ### Basiert auf offenen Standards -* OpenAPI für API-Erstellung, zusammen mit Deklarationen von Pfad Operationen, Parameter, Nachrichtenrumpf-Anfragen (englisch: body request), Sicherheit, etc. -* Automatische Dokumentation der Datenentitäten mit dem JSON Schema (OpenAPI basiert selber auf dem JSON Schema). -* Entworfen auf Grundlage dieser Standards nach einer sorgfältigen Studie, statt einer nachträglichen Schicht über diesen Standards. -* Dies ermöglicht automatische **Quellcode-Generierung auf Benutzerebene** in vielen Sprachen. +* OpenAPI für die Erstellung von APIs, inklusive Deklarationen von Pfad-Operationen, Parametern, Requestbodys, Sicherheit, usw. +* Automatische Dokumentation der Datenmodelle mit JSON Schema (da OpenAPI selbst auf JSON Schema basiert). +* Um diese Standards herum entworfen, nach sorgfältigem Studium. Statt einer nachträglichen Schicht darüber. +* Dies ermöglicht auch automatische **Client-Code-Generierung** in vielen Sprachen. ### Automatische Dokumentation -Mit einer interaktiven API-Dokumentation und explorativen webbasierten Benutzerschnittstellen. Da FastAPI auf OpenAPI basiert, gibt es hierzu mehrere Optionen, wobei zwei standardmäßig vorhanden sind. +Interaktive API-Dokumentation und erkundbare Web-Benutzeroberflächen. Da das Framework auf OpenAPI basiert, gibt es mehrere Optionen, zwei sind standardmäßig vorhanden. -* Swagger UI, bietet interaktive Exploration: testen und rufen Sie ihre API direkt vom Webbrowser auf. +* Swagger UI, bietet interaktive Erkundung, testen und rufen Sie ihre API direkt im Webbrowser auf. ![Swagger UI Interaktion](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) @@ -27,11 +27,9 @@ Mit einer interaktiven API-Dokumentation und explorativen webbasierten Benutzers Alles basiert auf **Python 3.8 Typ**-Deklarationen (dank Pydantic). Es muss keine neue Syntax gelernt werden, nur standardisiertes modernes Python. +Wenn Sie eine zweiminütige Auffrischung benötigen, wie man Python-Typen verwendet (auch wenn Sie FastAPI nicht benutzen), schauen Sie sich das kurze Tutorial an: [Einführung in Python-Typen](python-types.md){.internal-link target=_blank}. - -Wenn Sie eine kurze, zweiminütige, Auffrischung in der Benutzung von Python Typ-Deklarationen benötigen (auch wenn Sie FastAPI nicht nutzen), schauen Sie sich diese kurze Einführung an (Englisch): Python Types{.internal-link target=_blank}. - -Sie schreiben Standard-Python mit Typ-Deklarationen: +Sie schreiben Standard-Python mit Typen: ```Python from typing import List, Dict @@ -39,20 +37,20 @@ from datetime import date from pydantic import BaseModel -# Deklariere eine Variable als str -# und bekomme Editor-Unterstütung innerhalb der Funktion +# Deklarieren Sie eine Variable als ein `str` +# und bekommen Sie Editor-Unterstütung innerhalb der Funktion def main(user_id: str): return user_id -# Ein Pydantic model +# Ein Pydantic-Modell class User(BaseModel): id: int name: str joined: date ``` -Dies kann nun wiefolgt benutzt werden: +Das kann nun wie folgt verwendet werden: ```Python my_user: User = User(id=3, name="John Doe", joined="2018-07-19") @@ -66,138 +64,139 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` bedeutet: +/// info + +`**second_user_data` bedeutet: + +Nimm die Schlüssel-Wert-Paare des `second_user_data` Dicts und übergib sie direkt als Schlüsselwort-Argumente. Äquivalent zu: `User(id=4, name="Mary", joined="2018-11-30")`. - Übergebe die Schlüssel und die zugehörigen Werte des `second_user_data` Datenwörterbuches direkt als Schlüssel-Wert Argumente, äquivalent zu: `User(id=4, name="Mary", joined="2018-11-30")` +/// ### Editor Unterstützung -FastAPI wurde so entworfen, dass es einfach und intuitiv zu benutzen ist; alle Entscheidungen wurden auf mehreren Editoren getestet (sogar vor der eigentlichen Implementierung), um so eine best mögliche Entwicklererfahrung zu gewährleisten. +Das ganze Framework wurde so entworfen, dass es einfach und intuitiv zu benutzen ist; alle Entscheidungen wurden auf mehreren Editoren getestet, sogar vor der Implementierung, um die bestmögliche Entwicklererfahrung zu gewährleisten. -In der letzen Python Entwickler Umfrage stellte sich heraus, dass die meist genutzte Funktion die "Autovervollständigung" ist. +In der letzten Python-Entwickler-Umfrage wurde klar, dass die meist genutzte Funktion die „Autovervollständigung“ ist. -Die gesamte Struktur von **FastAPI** soll dem gerecht werden. Autovervollständigung funktioniert überall. +Das gesamte **FastAPI**-Framework ist darauf ausgelegt, das zu erfüllen. Autovervollständigung funktioniert überall. -Sie müssen selten in die Dokumentation schauen. +Sie werden selten noch mal in der Dokumentation nachschauen müssen. So kann ihr Editor Sie unterstützen: * in Visual Studio Code: -![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) +![Editor Unterstützung](https://fastapi.tiangolo.com/img/vscode-completion.png) * in PyCharm: -![editor support](https://fastapi.tiangolo.com/img/pycharm-completion.png) +![Editor Unterstützung](https://fastapi.tiangolo.com/img/pycharm-completion.png) -Sie bekommen Autovervollständigung an Stellen, an denen Sie dies vorher nicht für möglich gehalten hätten. Zum Beispiel der `price` Schlüssel aus einem JSON Datensatz (dieser könnte auch verschachtelt sein) aus einer Anfrage. +Sie bekommen sogar Autovervollständigung an Stellen, an denen Sie dies vorher nicht für möglich gehalten hätten. Zum Beispiel der `price` Schlüssel in einem JSON Datensatz (dieser könnte auch verschachtelt sein), der aus einer Anfrage kommt. -Hierdurch werden Sie nie wieder einen falschen Schlüsselnamen benutzen und sparen sich lästiges Suchen in der Dokumentation, um beispielsweise herauszufinden ob Sie `username` oder `user_name` als Schlüssel verwenden. +Nie wieder falsche Schlüsselnamen tippen, Hin und Herhüpfen zwischen der Dokumentation, Hoch- und Runterscrollen, um herauszufinden, ob es `username` oder `user_name` war. ### Kompakt -FastAPI nutzt für alles sensible **Standard-Einstellungen**, welche optional überall konfiguriert werden können. Alle Parameter können ganz genau an Ihre Bedürfnisse angepasst werden, sodass sie genau die API definieren können, die sie brauchen. +Es gibt für alles sensible **Defaultwerte**, mit optionaler Konfiguration überall. Alle Parameter können feinjustiert werden, damit sie tun, was Sie benötigen, und die API definieren, die Sie brauchen. -Aber standardmäßig, **"funktioniert einfach"** alles. +Aber standardmäßig **„funktioniert einfach alles“**. ### Validierung -* Validierung für die meisten (oder alle?) Python **Datentypen**, hierzu gehören: +* Validierung für die meisten (oder alle?) Python-**Datentypen**, hierzu gehören: * JSON Objekte (`dict`). * JSON Listen (`list`), die den Typ ihrer Elemente definieren. - * Zeichenketten (`str`), mit definierter minimaler und maximaler Länge. - * Zahlen (`int`, `float`) mit minimaler und maximaler Größe, usw. + * Strings (`str`) mit definierter minimaler und maximaler Länge. + * Zahlen (`int`, `float`) mit Mindest- und Maximal-Werten, usw. -* Validierung für ungewöhnliche Typen, wie: +* Validierung für mehr exotische Typen, wie: * URL. - * Email. + * E-Mail. * UUID. * ... und andere. -Die gesamte Validierung übernimmt das etablierte und robuste **Pydantic**. +Die gesamte Validierung übernimmt das gut etablierte und robuste **Pydantic**. ### Sicherheit und Authentifizierung -Integrierte Sicherheit und Authentifizierung. Ohne Kompromisse bei Datenbanken oder Datenmodellen. +Sicherheit und Authentifizierung ist integriert. Ohne Kompromisse bei Datenbanken oder Datenmodellen. -Unterstützt werden alle von OpenAPI definierten Sicherheitsschemata, hierzu gehören: +Alle in OpenAPI definierten Sicherheitsschemas, inklusive: -* HTTP Basis Authentifizierung. -* **OAuth2** (auch mit **JWT Zugriffstokens**). Schauen Sie sich hierzu dieses Tutorial an: [OAuth2 mit JWT](tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. +* HTTP Basic Authentifizierung. +* **OAuth2** (auch mit **JWT Tokens**). Siehe dazu das Tutorial zu [OAuth2 mit JWT](tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. * API Schlüssel in: - * Kopfzeile (HTTP Header). + * Header-Feldern. * Anfrageparametern. - * Cookies, etc. + * Cookies, usw. -Zusätzlich gibt es alle Sicherheitsfunktionen von Starlette (auch **session cookies**). +Zusätzlich alle Sicherheitsfunktionen von Starlette (inklusive **Session Cookies**). -Alles wurde als wiederverwendbare Werkzeuge und Komponenten geschaffen, die einfach in ihre Systeme, Datenablagen, relationale und nicht-relationale Datenbanken, ..., integriert werden können. +Alles als wiederverwendbare Tools und Komponenten gebaut, die einfach in ihre Systeme, Datenspeicher, relationalen und nicht-relationalen Datenbanken, usw., integriert werden können. -### Einbringen von Abhängigkeiten (meist: Dependency Injection) +### Einbringen von Abhängigkeiten (Dependency Injection) -FastAPI enthält ein extrem einfaches, aber extrem mächtiges Dependency Injection System. +FastAPI enthält ein extrem einfach zu verwendendes, aber extrem mächtiges Dependency Injection System. -* Selbst Abhängigkeiten können Abhängigkeiten haben, woraus eine Hierachie oder ein **"Graph" von Abhängigkeiten** entsteht. -* **Automatische Umsetzung** durch FastAPI. -* Alle abhängigen Komponenten könnten Daten von Anfragen, **Erweiterungen der Pfadoperations-**Einschränkungen und der automatisierten Dokumentation benötigen. -* **Automatische Validierung** selbst für *Pfadoperationen*-Parameter, die in den Abhängigkeiten definiert wurden. -* Unterstützt komplexe Benutzerauthentifizierungssysteme, **Datenbankverbindungen**, usw. -* **Keine Kompromisse** bei Datenbanken, Eingabemasken, usw. Sondern einfache Integration von allen. +* Selbst Abhängigkeiten können Abhängigkeiten haben, woraus eine Hierarchie oder ein **„Graph“ von Abhängigkeiten** entsteht. +* Alles **automatisch gehandhabt** durch das Framework. +* Alle Abhängigkeiten können Daten von Anfragen anfordern und das Verhalten von **Pfadoperationen** und der automatisierten Dokumentation **modifizieren**. +* **Automatische Validierung** selbst für solche Parameter von *Pfadoperationen*, welche in Abhängigkeiten definiert sind. +* Unterstützung für komplexe Authentifizierungssysteme, **Datenbankverbindungen**, usw. +* **Keine Kompromisse** bei Datenbanken, Frontends, usw., sondern einfache Integration mit allen. ### Unbegrenzte Erweiterungen -Oder mit anderen Worten, sie werden nicht benötigt. Importieren und nutzen Sie Quellcode nach Bedarf. +Oder mit anderen Worten, sie werden nicht benötigt. Importieren und nutzen Sie den Code, den Sie brauchen. -Jede Integration wurde so entworfen, dass sie einfach zu nutzen ist (mit Abhängigkeiten), sodass Sie eine Erweiterung für Ihre Anwendung mit nur zwei Zeilen an Quellcode implementieren können. Hierbei nutzen Sie die selbe Struktur und Syntax, wie bei Pfadoperationen. +Jede Integration wurde so entworfen, dass sie so einfach zu nutzen ist (mit Abhängigkeiten), dass Sie eine Erweiterung für Ihre Anwendung mit nur zwei Zeilen Code erstellen können. Hierbei nutzen Sie die gleiche Struktur und Syntax, wie bei *Pfadoperationen*. ### Getestet -* 100% Testabdeckung. -* 100% Typen annotiert. +* 100 % Testabdeckung. +* 100 % Typen annotiert. * Verwendet in Produktionsanwendungen. ## Starlette's Merkmale -**FastAPI** ist vollkommen kompatibel (und basiert auf) Starlette. Das bedeutet, auch ihr eigener Starlette Quellcode funktioniert. +**FastAPI** ist vollkommen kompatibel (und basiert auf) Starlette. Das bedeutet, wenn Sie eigenen Starlette Quellcode haben, funktioniert der. -`FastAPI` ist eigentlich eine Unterklasse von `Starlette`. Wenn Sie also bereits Starlette kennen oder benutzen, können Sie das meiste Ihres Wissens direkt anwenden. +`FastAPI` ist tatsächlich eine Unterklasse von `Starlette`. Wenn Sie also bereits Starlette kennen oder benutzen, das meiste funktioniert genau so. -Mit **FastAPI** bekommen Sie viele von **Starlette**'s Funktionen (da FastAPI nur Starlette auf Steroiden ist): +Mit **FastAPI** bekommen Sie alles von **Starlette** (da FastAPI nur Starlette auf Steroiden ist): -* Stark beeindruckende Performanz. Es ist eines der schnellsten Python Frameworks, auf Augenhöhe mit **NodeJS** und **Go**. +* Schwer beeindruckende Performanz. Es ist eines der schnellsten Python-Frameworks, auf Augenhöhe mit **NodeJS** und **Go**. * **WebSocket**-Unterstützung. * Hintergrundaufgaben im selben Prozess. -* Ereignisse für das Starten und Herunterfahren. -* Testclient basierend auf HTTPX. -* **CORS**, GZip, statische Dateien, Antwortfluss. -* **Sitzungs und Cookie** Unterstützung. -* 100% Testabdeckung. -* 100% Typen annotiert. +* Ereignisse beim Starten und Herunterfahren. +* Testclient baut auf HTTPX auf. +* **CORS**, GZip, statische Dateien, Responses streamen. +* **Sitzungs- und Cookie**-Unterstützung. +* 100 % Testabdeckung. +* 100 % Typen annotierte Codebasis. ## Pydantic's Merkmale -**FastAPI** ist vollkommen kompatibel (und basiert auf) Pydantic. Das bedeutet, auch jeder zusätzliche Pydantic Quellcode funktioniert. +**FastAPI** ist vollkommen kompatibel (und basiert auf) Pydantic. Das bedeutet, wenn Sie eigenen Pydantic Quellcode haben, funktioniert der. -Verfügbar sind ebenso externe auf Pydantic basierende Bibliotheken, wie ORMs, ODMs für Datenbanken. +Inklusive externer Bibliotheken, die auf Pydantic basieren, wie ORMs, ODMs für Datenbanken. Daher können Sie in vielen Fällen das Objekt einer Anfrage **direkt zur Datenbank** schicken, weil alles automatisch validiert wird. -Das selbe gilt auch für die andere Richtung: Sie können jedes Objekt aus der Datenbank **direkt zum Klienten** schicken. +Das gleiche gilt auch für die andere Richtung: Sie können in vielen Fällen das Objekt aus der Datenbank **direkt zum Client** schicken. Mit **FastAPI** bekommen Sie alle Funktionen von **Pydantic** (da FastAPI für die gesamte Datenverarbeitung Pydantic nutzt): * **Kein Kopfzerbrechen**: - * Sie müssen keine neue Schemadefinitionssprache lernen. - * Wenn Sie mit Python's Typisierung arbeiten können, können Sie auch mit Pydantic arbeiten. -* Gutes Zusammenspiel mit Ihrer/Ihrem **IDE/linter/Gehirn**: - * Weil Datenstrukturen von Pydantic einfach nur Instanzen ihrer definierten Klassen sind, sollten Autovervollständigung, Linting, mypy und ihre Intuition einwandfrei funktionieren. -* **Schnell**: - * In Vergleichen ist Pydantic schneller als jede andere getestete Bibliothek. + * Keine neue Schemadefinition-Mikrosprache zu lernen. + * Wenn Sie Pythons Typen kennen, wissen Sie, wie man Pydantic verwendet. +* Gutes Zusammenspiel mit Ihrer/Ihrem **IDE/Linter/Gehirn**: + * Weil Pydantics Datenstrukturen einfach nur Instanzen ihrer definierten Klassen sind; Autovervollständigung, Linting, mypy und ihre Intuition sollten alle einwandfrei mit ihren validierten Daten funktionieren. * Validierung von **komplexen Strukturen**: - * Benutzung von hierachischen Pydantic Schemata, Python `typing`’s `List` und `Dict`, etc. - * Validierungen erlauben eine klare und einfache Datenschemadefinition, überprüft und dokumentiert als JSON Schema. - * Sie können stark **verschachtelte JSON** Objekte haben und diese sind trotzdem validiert und annotiert. + * Benutzung von hierarchischen Pydantic-Modellen, Python-`typing`s `List` und `Dict`, etc. + * Die Validierer erlauben es, komplexe Datenschemen klar und einfach zu definieren, überprüft und dokumentiert als JSON Schema. + * Sie können tief **verschachtelte JSON** Objekte haben, die alle validiert und annotiert sind. * **Erweiterbar**: - * Pydantic erlaubt die Definition von eigenen Datentypen oder sie können die Validierung mit einer `validator` dekorierten Methode erweitern. -* 100% Testabdeckung. + * Pydantic erlaubt die Definition von eigenen Datentypen oder sie können die Validierung mit einer `validator`-dekorierten Methode im Modell erweitern. +* 100 % Testabdeckung. diff --git a/docs/de/docs/help-fastapi.md b/docs/de/docs/help-fastapi.md new file mode 100644 index 000000000..0b9c52316 --- /dev/null +++ b/docs/de/docs/help-fastapi.md @@ -0,0 +1,268 @@ +# FastAPI helfen – Hilfe erhalten + +Gefällt Ihnen **FastAPI**? + +Möchten Sie FastAPI, anderen Benutzern und dem Autor helfen? + +Oder möchten Sie Hilfe zu **FastAPI** erhalten? + +Es gibt sehr einfache Möglichkeiten zu helfen (manche erfordern nur ein oder zwei Klicks). + +Und es gibt auch viele Möglichkeiten, Hilfe zu bekommen. + +## Newsletter abonnieren + +Sie können den (unregelmäßig erscheinenden) [**FastAPI and Friends**-Newsletter](newsletter.md){.internal-link target=_blank} abonnieren, um auf dem Laufenden zu bleiben: + +* Neuigkeiten über FastAPI and Friends 🚀 +* Anleitungen 📝 +* Funktionen ✨ +* Breaking Changes 🚨 +* Tipps und Tricks ✅ +## FastAPI auf Twitter folgen + +Folgen Sie @fastapi auf **Twitter**, um die neuesten Nachrichten über **FastAPI** zu erhalten. 🐦 + +## **FastAPI** auf GitHub einen Stern geben + +Sie können FastAPI auf GitHub „starren“ (durch Klicken auf den Stern-Button oben rechts): https://github.com/fastapi/fastapi. ⭐️ + +Durch das Hinzufügen eines Sterns können andere Benutzer es leichter finden und sehen, dass es für andere bereits nützlich war. + +## Das GitHub-Repository auf Releases beobachten + +Sie können FastAPI in GitHub beobachten (Klicken Sie oben rechts auf den Button „watch“): https://github.com/fastapi/fastapi. 👀 + +Dort können Sie „Releases only“ auswählen. + +Auf diese Weise erhalten Sie Benachrichtigungen (per E-Mail), wenn es einen neuen Release (eine neue Version) von **FastAPI** mit Fehlerbehebungen und neuen Funktionen gibt. + +## Mit dem Autor vernetzen + +Sie können sich mit mir (Sebastián Ramírez / `tiangolo`), dem Autor, verbinden. + +Insbesondere: + +* Folgen Sie mir auf **GitHub**. + * Finden Sie andere Open-Source-Projekte, die ich erstellt habe und die Ihnen helfen könnten. + * Folgen Sie mir, um mitzubekommen, wenn ich ein neues Open-Source-Projekt erstelle. +* Folgen Sie mir auf **Twitter** oder Mastodon. + * Berichten Sie mir, wie Sie FastAPI verwenden (das höre ich gerne). + * Bekommen Sie mit, wenn ich Ankündigungen mache oder neue Tools veröffentliche. + * Sie können auch @fastapi auf Twitter folgen (ein separates Konto). +* Folgen Sie mir auf **LinkedIn**. + * Bekommen Sie mit, wenn ich Ankündigungen mache oder neue Tools veröffentliche (obwohl ich Twitter häufiger verwende 🤷‍♂). +* Lesen Sie, was ich schreibe (oder folgen Sie mir) auf **Dev.to** oder **Medium**. + * Lesen Sie andere Ideen, Artikel, und erfahren Sie mehr über die von mir erstellten Tools. + * Folgen Sie mir, um zu lesen, wenn ich etwas Neues veröffentliche. + +## Über **FastAPI** tweeten + +Tweeten Sie über **FastAPI** und teilen Sie mir und anderen mit, warum es Ihnen gefällt. 🎉 + +Ich höre gerne, wie **FastAPI** verwendet wird, was Ihnen daran gefallen hat, in welchem Projekt/Unternehmen Sie es verwenden, usw. + +## Für FastAPI abstimmen + +* Stimmen Sie für **FastAPI** auf Slant. +* Stimmen Sie für **FastAPI** auf AlternativeTo. +* Berichten Sie auf StackShare, dass Sie **FastAPI** verwenden. + +## Anderen bei Fragen auf GitHub helfen + +Sie können versuchen, anderen bei ihren Fragen zu helfen: + +* GitHub-Diskussionen +* GitHub-Issues + +In vielen Fällen kennen Sie möglicherweise bereits die Antwort auf diese Fragen. 🤓 + +Wenn Sie vielen Menschen bei ihren Fragen helfen, werden Sie offizieller [FastAPI-Experte](fastapi-people.md#experten){.internal-link target=_blank}. 🎉 + +Denken Sie aber daran, der wichtigste Punkt ist: Versuchen Sie, freundlich zu sein. Die Leute bringen ihre Frustrationen mit und fragen in vielen Fällen nicht auf die beste Art und Weise, aber versuchen Sie dennoch so gut wie möglich, freundlich zu sein. 🤗 + +Die **FastAPI**-Community soll freundlich und einladend sein. Und auch kein Mobbing oder respektloses Verhalten gegenüber anderen akzeptieren. Wir müssen uns umeinander kümmern. + +--- + +So helfen Sie anderen bei Fragen (in Diskussionen oder Problemen): + +### Die Frage verstehen + +* Fragen Sie sich, ob Sie verstehen, was das **Ziel** und der Anwendungsfall der fragenden Person ist. + +* Überprüfen Sie dann, ob die Frage (die überwiegende Mehrheit sind Fragen) **klar** ist. + +* In vielen Fällen handelt es sich bei der gestellten Frage um eine Lösung, die der Benutzer sich vorstellt, aber es könnte eine **bessere** Lösung geben. Wenn Sie das Problem und den Anwendungsfall besser verstehen, können Sie eine bessere **Alternativlösung** vorschlagen. + +* Wenn Sie die Frage nicht verstehen können, fragen Sie nach weiteren **Details**. + +### Das Problem reproduzieren + +In den meisten Fällen und bei den meisten Fragen ist etwas mit dem von der Person erstellten **eigenen Quellcode** los. + +In vielen Fällen wird nur ein Fragment des Codes gepostet, aber das reicht nicht aus, um **das Problem zu reproduzieren**. + +* Sie können die Person darum bitten, ein minimales, reproduzierbares Beispiel bereitzustellen, welches Sie **kopieren, einfügen** und lokal ausführen können, um den gleichen Fehler oder das gleiche Verhalten zu sehen, das die Person sieht, oder um ihren Anwendungsfall besser zu verstehen. + +* Wenn Sie in Geberlaune sind, können Sie versuchen, selbst ein solches Beispiel zu erstellen, nur basierend auf der Beschreibung des Problems. Denken Sie jedoch daran, dass dies viel Zeit in Anspruch nehmen kann und dass es besser sein kann, zunächst um eine Klärung des Problems zu bitten. + +### Lösungen vorschlagen + +* Nachdem Sie die Frage verstanden haben, können Sie eine mögliche **Antwort** geben. + +* In vielen Fällen ist es besser, das **zugrunde liegende Problem oder den Anwendungsfall** zu verstehen, da es möglicherweise einen besseren Weg zur Lösung gibt als das, was die Person versucht. + +### Um Schließung bitten + +Wenn die Person antwortet, besteht eine hohe Chance, dass Sie ihr Problem gelöst haben. Herzlichen Glückwunsch, **Sie sind ein Held**! 🦸 + +* Wenn es tatsächlich das Problem gelöst hat, können Sie sie darum bitten: + + * In GitHub-Diskussionen: den Kommentar als **Antwort** zu markieren. + * In GitHub-Issues: Das Issue zu **schließen**. + +## Das GitHub-Repository beobachten + +Sie können FastAPI auf GitHub „beobachten“ (Klicken Sie oben rechts auf die Schaltfläche „watch“): https://github.com/fastapi/fastapi. 👀 + +Wenn Sie dann „Watching“ statt „Releases only“ auswählen, erhalten Sie Benachrichtigungen, wenn jemand ein neues Issue eröffnet oder eine neue Frage stellt. Sie können auch spezifizieren, dass Sie nur über neue Issues, Diskussionen, PRs, usw. benachrichtigt werden möchten. + +Dann können Sie versuchen, bei der Lösung solcher Fragen zu helfen. + +## Fragen stellen + +Sie können im GitHub-Repository eine neue Frage erstellen, zum Beispiel: + +* Stellen Sie eine **Frage** oder bitten Sie um Hilfe mit einem **Problem**. +* Schlagen Sie eine neue **Funktionalität** vor. + +**Hinweis**: Wenn Sie das tun, bitte ich Sie, auch anderen zu helfen. 😉 + +## Pull Requests prüfen + +Sie können mir helfen, Pull Requests von anderen zu überprüfen (Review). + +Noch einmal, bitte versuchen Sie Ihr Bestes, freundlich zu sein. 🤗 + +--- + +Hier ist, was Sie beachten sollten und wie Sie einen Pull Request überprüfen: + +### Das Problem verstehen + +* Stellen Sie zunächst sicher, dass Sie **das Problem verstehen**, welches der Pull Request zu lösen versucht. Möglicherweise gibt es eine längere Diskussion dazu in einer GitHub-Diskussion oder einem GitHub-Issue. + +* Es besteht auch eine gute Chance, dass der Pull Request nicht wirklich benötigt wird, da das Problem auf **andere Weise** gelöst werden kann. Dann können Sie das vorschlagen oder danach fragen. + +### Der Stil ist nicht so wichtig + +* Machen Sie sich nicht zu viele Gedanken über Dinge wie den Stil von Commit-Nachrichten, ich werde den Commit manuell zusammenführen und anpassen. + +* Machen Sie sich auch keine Sorgen über Stilregeln, es gibt bereits automatisierte Tools, die das überprüfen. + +Und wenn es irgendeinen anderen Stil- oder Konsistenz-Bedarf gibt, bitte ich direkt darum oder füge zusätzliche Commits mit den erforderlichen Änderungen hinzu. + +### Den Code überprüfen + +* Prüfen und lesen Sie den Code, fragen Sie sich, ob er Sinn macht, **führen Sie ihn lokal aus** und testen Sie, ob er das Problem tatsächlich löst. + +* Schreiben Sie dann einen **Kommentar** und berichten, dass Sie das getan haben. So weiß ich, dass Sie ihn wirklich überprüft haben. + +/// info + +Leider kann ich PRs, nur weil sie von Mehreren gutgeheißen wurden, nicht einfach vertrauen. + +Es ist mehrmals passiert, dass es PRs mit drei, fünf oder mehr Zustimmungen gibt, wahrscheinlich weil die Beschreibung ansprechend ist, aber wenn ich die PRs überprüfe, sind sie tatsächlich fehlerhaft, haben einen Bug, oder lösen das Problem nicht, welches sie behaupten, zu lösen. 😅 + +Daher ist es wirklich wichtig, dass Sie den Code tatsächlich lesen und ausführen und mir in den Kommentaren mitteilen, dass Sie dies getan haben. 🤓 + +/// + +* Wenn der PR irgendwie vereinfacht werden kann, fragen Sie ruhig danach, aber seien Sie nicht zu wählerisch, es gibt viele subjektive Standpunkte (und ich habe auch meinen eigenen 🙈), also ist es besser, wenn man sich auf die wesentlichen Dinge konzentriert. + +### Tests + +* Helfen Sie mir zu überprüfen, dass der PR **Tests** hat. + +* Überprüfen Sie, dass diese Tests vor dem PR **fehlschlagen**. 🚨 + +* Überprüfen Sie, dass diese Tests nach dem PR **bestanden** werden. ✅ + +* Viele PRs haben keine Tests. Sie können den Autor daran **erinnern**, Tests hinzuzufügen, oder Sie können sogar selbst einige Tests **vorschlagen**. Das ist eines der Dinge, die die meiste Zeit in Anspruch nehmen, und dabei können Sie viel helfen. + +* Kommentieren Sie auch hier anschließend, was Sie versucht haben, sodass ich weiß, dass Sie es überprüft haben. 🤓 + +## Einen Pull Request erstellen + +Sie können zum Quellcode mit Pull Requests [beitragen](contributing.md){.internal-link target=_blank}, zum Beispiel: + +* Um einen Tippfehler zu beheben, den Sie in der Dokumentation gefunden haben. +* Um einen Artikel, ein Video oder einen Podcast über FastAPI zu teilen, den Sie erstellt oder gefunden haben, indem Sie diese Datei bearbeiten. + * Stellen Sie sicher, dass Sie Ihren Link am Anfang des entsprechenden Abschnitts einfügen. +* Um zu helfen, [die Dokumentation in Ihre Sprache zu übersetzen](contributing.md#ubersetzungen){.internal-link target=_blank}. + * Sie können auch dabei helfen, die von anderen erstellten Übersetzungen zu überprüfen (Review). +* Um neue Dokumentationsabschnitte vorzuschlagen. +* Um ein bestehendes Problem / einen bestehenden Bug zu beheben. + * Stellen Sie sicher, dass Sie Tests hinzufügen. +* Um eine neue Funktionalität hinzuzufügen. + * Stellen Sie sicher, dass Sie Tests hinzufügen. + * Stellen Sie sicher, dass Sie Dokumentation hinzufügen, falls das notwendig ist. + +## FastAPI pflegen + +Helfen Sie mir, **FastAPI** instand zu halten! 🤓 + +Es gibt viel zu tun, und das meiste davon können **SIE** tun. + +Die Hauptaufgaben, die Sie jetzt erledigen können, sind: + +* [Helfen Sie anderen bei Fragen auf GitHub](#anderen-bei-fragen-auf-github-helfen){.internal-link target=_blank} (siehe Abschnitt oben). +* [Prüfen Sie Pull Requests](#pull-requests-prufen){.internal-link target=_blank} (siehe Abschnitt oben). + +Diese beiden Dinge sind es, die **die meiste Zeit in Anspruch nehmen**. Das ist die Hauptarbeit bei der Wartung von FastAPI. + +Wenn Sie mir dabei helfen können, **helfen Sie mir, FastAPI am Laufen zu erhalten** und sorgen dafür, dass es weiterhin **schneller und besser voranschreitet**. 🚀 + +## Beim Chat mitmachen + +Treten Sie dem 👥 Discord-Chatserver 👥 bei und treffen Sie sich mit anderen Mitgliedern der FastAPI-Community. + +/// tip | Tipp + +Wenn Sie Fragen haben, stellen Sie sie bei GitHub Diskussionen, es besteht eine viel bessere Chance, dass Sie hier Hilfe von den [FastAPI-Experten](fastapi-people.md#experten){.internal-link target=_blank} erhalten. + +Nutzen Sie den Chat nur für andere allgemeine Gespräche. + +/// + +### Den Chat nicht für Fragen verwenden + +Bedenken Sie, da Chats mehr „freie Konversation“ ermöglichen, dass es verlockend ist, Fragen zu stellen, die zu allgemein und schwierig zu beantworten sind, sodass Sie möglicherweise keine Antworten erhalten. + +Auf GitHub hilft Ihnen die Vorlage dabei, die richtige Frage zu schreiben, sodass Sie leichter eine gute Antwort erhalten oder das Problem sogar selbst lösen können, noch bevor Sie fragen. Und auf GitHub kann ich sicherstellen, dass ich immer alles beantworte, auch wenn es einige Zeit dauert. Ich persönlich kann das mit den Chat-Systemen nicht machen. 😅 + +Unterhaltungen in den Chat-Systemen sind außerdem nicht so leicht durchsuchbar wie auf GitHub, sodass Fragen und Antworten möglicherweise im Gespräch verloren gehen. Und nur die auf GitHub machen einen [FastAPI-Experten](fastapi-people.md#experten){.internal-link target=_blank}, Sie werden also höchstwahrscheinlich mehr Aufmerksamkeit auf GitHub erhalten. + +Auf der anderen Seite gibt es Tausende von Benutzern in den Chat-Systemen, sodass die Wahrscheinlichkeit hoch ist, dass Sie dort fast immer jemanden zum Reden finden. 😄 + +## Den Autor sponsern + +Sie können den Autor (mich) auch über GitHub-Sponsoren finanziell unterstützen. + +Dort könnten Sie mir als Dankeschön einen Kaffee spendieren ☕️. 😄 + +Und Sie können auch Silber- oder Gold-Sponsor für FastAPI werden. 🏅🎉 + +## Die Tools sponsern, die FastAPI unterstützen + +Wie Sie in der Dokumentation gesehen haben, steht FastAPI auf den Schultern von Giganten, Starlette und Pydantic. + +Sie können auch sponsern: + +* Samuel Colvin (Pydantic) +* Encode (Starlette, Uvicorn) + +--- + +Danke! 🚀 diff --git a/docs/de/docs/history-design-future.md b/docs/de/docs/history-design-future.md new file mode 100644 index 000000000..ee917608e --- /dev/null +++ b/docs/de/docs/history-design-future.md @@ -0,0 +1,79 @@ +# Geschichte, Design und Zukunft + +Vor einiger Zeit fragte ein **FastAPI**-Benutzer: + +> Was ist die Geschichte dieses Projekts? Es scheint, als wäre es in ein paar Wochen aus dem Nichts zu etwas Großartigem geworden [...] + +Hier ist ein wenig über diese Geschichte. + +## Alternativen + +Ich habe seit mehreren Jahren APIs mit komplexen Anforderungen (maschinelles Lernen, verteilte Systeme, asynchrone Jobs, NoSQL-Datenbanken, usw.) erstellt und leitete mehrere Entwicklerteams. + +Dabei musste ich viele Alternativen untersuchen, testen und nutzen. + +Die Geschichte von **FastAPI** ist zu einem großen Teil die Geschichte seiner Vorgänger. + +Wie im Abschnitt [Alternativen](alternatives.md){.internal-link target=_blank} gesagt: + +
+ +**FastAPI** würde ohne die frühere Arbeit anderer nicht existieren. + +Es wurden zuvor viele Tools entwickelt, die als Inspiration für seine Entwicklung dienten. + +Ich habe die Schaffung eines neuen Frameworks viele Jahre lang vermieden. Zuerst habe ich versucht, alle von **FastAPI** abgedeckten Funktionen mithilfe vieler verschiedener Frameworks, Plugins und Tools zu lösen. + +Aber irgendwann gab es keine andere Möglichkeit, als etwas zu schaffen, das all diese Funktionen bereitstellte, die besten Ideen früherer Tools aufnahm und diese auf die bestmögliche Weise kombinierte, wobei Sprachfunktionen verwendet wurden, die vorher noch nicht einmal verfügbar waren (Python 3.6+ Typhinweise). + +
+ +## Investigation + +Durch die Nutzung all dieser vorherigen Alternativen hatte ich die Möglichkeit, von allen zu lernen, Ideen aufzunehmen und sie auf die beste Weise zu kombinieren, die ich für mich und die Entwicklerteams, mit denen ich zusammengearbeitet habe, finden konnte. + +Es war beispielsweise klar, dass es idealerweise auf Standard-Python-Typhinweisen basieren sollte. + +Der beste Ansatz bestand außerdem darin, bereits bestehende Standards zu nutzen. + +Bevor ich also überhaupt angefangen habe, **FastAPI** zu schreiben, habe ich mehrere Monate damit verbracht, die Spezifikationen für OpenAPI, JSON Schema, OAuth2, usw. zu studieren und deren Beziehungen, Überschneidungen und Unterschiede zu verstehen. + +## Design + +Dann habe ich einige Zeit damit verbracht, die Entwickler-„API“ zu entwerfen, die ich als Benutzer haben wollte (als Entwickler, welcher FastAPI verwendet). + +Ich habe mehrere Ideen in den beliebtesten Python-Editoren getestet: PyCharm, VS Code, Jedi-basierte Editoren. + +Laut der letzten Python-Entwickler-Umfrage, deckt das etwa 80 % der Benutzer ab. + +Das bedeutet, dass **FastAPI** speziell mit den Editoren getestet wurde, die von 80 % der Python-Entwickler verwendet werden. Und da die meisten anderen Editoren in der Regel ähnlich funktionieren, sollten alle diese Vorteile für praktisch alle Editoren funktionieren. + +Auf diese Weise konnte ich die besten Möglichkeiten finden, die Codeverdoppelung so weit wie möglich zu reduzieren, überall Autovervollständigung, Typ- und Fehlerprüfungen, usw. zu gewährleisten. + +Alles auf eine Weise, die allen Entwicklern das beste Entwicklungserlebnis bot. + +## Anforderungen + +Nachdem ich mehrere Alternativen getestet hatte, entschied ich, dass ich **Pydantic** wegen seiner Vorteile verwenden würde. + +Dann habe ich zu dessen Code beigetragen, um es vollständig mit JSON Schema kompatibel zu machen, und so verschiedene Möglichkeiten zum Definieren von einschränkenden Deklarationen (Constraints) zu unterstützen, und die Editorunterstützung (Typprüfungen, Codevervollständigung) zu verbessern, basierend auf den Tests in mehreren Editoren. + +Während der Entwicklung habe ich auch zu **Starlette** beigetragen, der anderen Schlüsselanforderung. + +## Entwicklung + +Als ich mit der Erstellung von **FastAPI** selbst begann, waren die meisten Teile bereits vorhanden, das Design definiert, die Anforderungen und Tools bereit und das Wissen über die Standards und Spezifikationen klar und frisch. + +## Zukunft + +Zu diesem Zeitpunkt ist bereits klar, dass **FastAPI** mit seinen Ideen für viele Menschen nützlich ist. + +Es wird gegenüber früheren Alternativen gewählt, da es für viele Anwendungsfälle besser geeignet ist. + +Viele Entwickler und Teams verlassen sich bei ihren Projekten bereits auf **FastAPI** (einschließlich mir und meinem Team). + +Dennoch stehen uns noch viele Verbesserungen und Funktionen bevor. + +**FastAPI** hat eine große Zukunft vor sich. + +Und [Ihre Hilfe](help-fastapi.md){.internal-link target=_blank} wird sehr geschätzt. diff --git a/docs/de/docs/how-to/conditional-openapi.md b/docs/de/docs/how-to/conditional-openapi.md new file mode 100644 index 000000000..50ae11f90 --- /dev/null +++ b/docs/de/docs/how-to/conditional-openapi.md @@ -0,0 +1,56 @@ +# Bedingte OpenAPI + +Bei Bedarf können Sie OpenAPI mithilfe von Einstellungen und Umgebungsvariablen abhängig von der Umgebung bedingt konfigurieren und sogar vollständig deaktivieren. + +## Über Sicherheit, APIs und Dokumentation + +Das Verstecken Ihrer Dokumentationsoberflächen in der Produktion *sollte nicht* die Methode sein, Ihre API zu schützen. + +Dadurch wird Ihrer API keine zusätzliche Sicherheit hinzugefügt, die *Pfadoperationen* sind weiterhin dort verfügbar, wo sie sich befinden. + +Wenn Ihr Code eine Sicherheitslücke aufweist, ist diese weiterhin vorhanden. + +Das Verstecken der Dokumentation macht es nur schwieriger zu verstehen, wie mit Ihrer API interagiert werden kann, und könnte es auch schwieriger machen, diese in der Produktion zu debuggen. Man könnte es einfach als eine Form von Security through obscurity betrachten. + +Wenn Sie Ihre API sichern möchten, gibt es mehrere bessere Dinge, die Sie tun können, zum Beispiel: + +* Stellen Sie sicher, dass Sie über gut definierte Pydantic-Modelle für Ihre Requestbodys und Responses verfügen. +* Konfigurieren Sie alle erforderlichen Berechtigungen und Rollen mithilfe von Abhängigkeiten. +* Speichern Sie niemals Klartext-Passwörter, sondern nur Passwort-Hashes. +* Implementieren und verwenden Sie gängige kryptografische Tools wie Passlib und JWT-Tokens, usw. +* Fügen Sie bei Bedarf detailliertere Berechtigungskontrollen mit OAuth2-Scopes hinzu. +* ... usw. + +Dennoch kann es sein, dass Sie einen ganz bestimmten Anwendungsfall haben, bei dem Sie die API-Dokumentation für eine bestimmte Umgebung (z. B. für die Produktion) oder abhängig von Konfigurationen aus Umgebungsvariablen wirklich deaktivieren müssen. + +## Bedingte OpenAPI aus Einstellungen und Umgebungsvariablen + +Sie können problemlos dieselben Pydantic-Einstellungen verwenden, um Ihre generierte OpenAPI und die Dokumentationsoberflächen zu konfigurieren. + +Zum Beispiel: + +{* ../../docs_src/conditional_openapi/tutorial001.py hl[6,11] *} + +Hier deklarieren wir die Einstellung `openapi_url` mit dem gleichen Defaultwert `"/openapi.json"`. + +Und dann verwenden wir das beim Erstellen der `FastAPI`-App. + +Dann könnten Sie OpenAPI (einschließlich der Dokumentationsoberflächen) deaktivieren, indem Sie die Umgebungsvariable `OPENAPI_URL` auf einen leeren String setzen, wie zum Beispiel: + +
+ +```console +$ OPENAPI_URL= uvicorn main:app + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Wenn Sie dann zu den URLs unter `/openapi.json`, `/docs` oder `/redoc` gehen, erhalten Sie lediglich einen `404 Not Found`-Fehler, wie: + +```JSON +{ + "detail": "Not Found" +} +``` diff --git a/docs/de/docs/how-to/configure-swagger-ui.md b/docs/de/docs/how-to/configure-swagger-ui.md new file mode 100644 index 000000000..1ee72d205 --- /dev/null +++ b/docs/de/docs/how-to/configure-swagger-ui.md @@ -0,0 +1,70 @@ +# Swagger-Oberfläche konfigurieren + +Sie können einige zusätzliche Parameter der Swagger-Oberfläche konfigurieren. + +Um diese zu konfigurieren, übergeben Sie das Argument `swagger_ui_parameters` beim Erstellen des `FastAPI()`-App-Objekts oder an die Funktion `get_swagger_ui_html()`. + +`swagger_ui_parameters` empfängt ein Dict mit den Konfigurationen, die direkt an die Swagger-Oberfläche übergeben werden. + +FastAPI konvertiert die Konfigurationen nach **JSON**, um diese mit JavaScript kompatibel zu machen, da die Swagger-Oberfläche das benötigt. + +## Syntaxhervorhebung deaktivieren + +Sie könnten beispielsweise die Syntaxhervorhebung in der Swagger-Oberfläche deaktivieren. + +Ohne Änderung der Einstellungen ist die Syntaxhervorhebung standardmäßig aktiviert: + + + +Sie können sie jedoch deaktivieren, indem Sie `syntaxHighlight` auf `False` setzen: + +{* ../../docs_src/configure_swagger_ui/tutorial001.py hl[3] *} + +... und dann zeigt die Swagger-Oberfläche die Syntaxhervorhebung nicht mehr an: + + + +## Das Theme ändern + +Auf die gleiche Weise könnten Sie das Theme der Syntaxhervorhebung mit dem Schlüssel `syntaxHighlight.theme` festlegen (beachten Sie, dass er einen Punkt in der Mitte hat): + +{* ../../docs_src/configure_swagger_ui/tutorial002.py hl[3] *} + +Obige Konfiguration würde das Theme für die Farbe der Syntaxhervorhebung ändern: + + + +## Defaultparameter der Swagger-Oberfläche ändern + +FastAPI enthält einige Defaultkonfigurationsparameter, die für die meisten Anwendungsfälle geeignet sind. + +Es umfasst die folgenden Defaultkonfigurationen: + +{* ../../fastapi/openapi/docs.py ln[7:23] *} + +Sie können jede davon überschreiben, indem Sie im Argument `swagger_ui_parameters` einen anderen Wert festlegen. + +Um beispielsweise `deepLinking` zu deaktivieren, könnten Sie folgende Einstellungen an `swagger_ui_parameters` übergeben: + +{* ../../docs_src/configure_swagger_ui/tutorial003.py hl[3] *} + +## Andere Parameter der Swagger-Oberfläche + +Um alle anderen möglichen Konfigurationen zu sehen, die Sie verwenden können, lesen Sie die offizielle Dokumentation für die Parameter der Swagger-Oberfläche. + +## JavaScript-basierte Einstellungen + +Die Swagger-Oberfläche erlaubt, dass andere Konfigurationen auch **JavaScript**-Objekte sein können (z. B. JavaScript-Funktionen). + +FastAPI umfasst auch diese Nur-JavaScript-`presets`-Einstellungen: + +```JavaScript +presets: [ + SwaggerUIBundle.presets.apis, + SwaggerUIBundle.SwaggerUIStandalonePreset +] +``` + +Dabei handelt es sich um **JavaScript**-Objekte, nicht um Strings, daher können Sie diese nicht direkt vom Python-Code aus übergeben. + +Wenn Sie solche JavaScript-Konfigurationen verwenden müssen, können Sie einen der früher genannten Wege verwenden. Überschreiben Sie alle *Pfadoperationen* der Swagger-Oberfläche und schreiben Sie manuell jedes benötigte JavaScript. diff --git a/docs/de/docs/how-to/custom-docs-ui-assets.md b/docs/de/docs/how-to/custom-docs-ui-assets.md new file mode 100644 index 000000000..ab8cd9f6b --- /dev/null +++ b/docs/de/docs/how-to/custom-docs-ui-assets.md @@ -0,0 +1,191 @@ +# Statische Assets der Dokumentationsoberfläche (selbst hosten) + +Die API-Dokumentation verwendet **Swagger UI** und **ReDoc**, und jede dieser Dokumentationen benötigt einige JavaScript- und CSS-Dateien. + +Standardmäßig werden diese Dateien von einem CDN bereitgestellt. + +Es ist jedoch möglich, das anzupassen, ein bestimmtes CDN festzulegen oder die Dateien selbst bereitzustellen. + +## Benutzerdefiniertes CDN für JavaScript und CSS + +Nehmen wir an, Sie möchten ein anderes CDN verwenden, zum Beispiel möchten Sie `https://unpkg.com/` verwenden. + +Das kann nützlich sein, wenn Sie beispielsweise in einem Land leben, in dem bestimmte URLs eingeschränkt sind. + +### Die automatischen Dokumentationen deaktivieren + +Der erste Schritt besteht darin, die automatischen Dokumentationen zu deaktivieren, da diese standardmäßig das Standard-CDN verwenden. + +Um diese zu deaktivieren, setzen Sie deren URLs beim Erstellen Ihrer `FastAPI`-App auf `None`: + +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[8] *} + +### Die benutzerdefinierten Dokumentationen hinzufügen + +Jetzt können Sie die *Pfadoperationen* für die benutzerdefinierten Dokumentationen erstellen. + +Sie können die internen Funktionen von FastAPI wiederverwenden, um die HTML-Seiten für die Dokumentation zu erstellen und ihnen die erforderlichen Argumente zu übergeben: + +* `openapi_url`: die URL, unter welcher die HTML-Seite für die Dokumentation das OpenAPI-Schema für Ihre API abrufen kann. Sie können hier das Attribut `app.openapi_url` verwenden. +* `title`: der Titel Ihrer API. +* `oauth2_redirect_url`: Sie können hier `app.swagger_ui_oauth2_redirect_url` verwenden, um die Standardeinstellung zu verwenden. +* `swagger_js_url`: die URL, unter welcher der HTML-Code für Ihre Swagger-UI-Dokumentation die **JavaScript**-Datei abrufen kann. Dies ist die benutzerdefinierte CDN-URL. +* `swagger_css_url`: die URL, unter welcher der HTML-Code für Ihre Swagger-UI-Dokumentation die **CSS**-Datei abrufen kann. Dies ist die benutzerdefinierte CDN-URL. + +Und genau so für ReDoc ... + +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[2:6,11:19,22:24,27:33] *} + +/// tip | Tipp + +Die *Pfadoperation* für `swagger_ui_redirect` ist ein Hilfsmittel bei der Verwendung von OAuth2. + +Wenn Sie Ihre API mit einem OAuth2-Anbieter integrieren, können Sie sich authentifizieren und mit den erworbenen Anmeldeinformationen zur API-Dokumentation zurückkehren. Und mit ihr interagieren, die echte OAuth2-Authentifizierung verwendend. + +Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „Umleitungs“-Helfer. + +/// + +### Eine *Pfadoperation* erstellen, um es zu testen + +Um nun testen zu können, ob alles funktioniert, erstellen Sie eine *Pfadoperation*: + +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[36:38] *} + +### Es ausprobieren + +Jetzt sollten Sie in der Lage sein, zu Ihrer Dokumentation auf http://127.0.0.1:8000/docs zu gehen und die Seite neu zuladen, die Assets werden nun vom neuen CDN geladen. + +## JavaScript und CSS für die Dokumentation selbst hosten + +Das Selbst Hosten von JavaScript und CSS kann nützlich sein, wenn Sie beispielsweise möchten, dass Ihre Anwendung auch offline, ohne bestehenden Internetzugang oder in einem lokalen Netzwerk weiter funktioniert. + +Hier erfahren Sie, wie Sie diese Dateien selbst in derselben FastAPI-App bereitstellen und die Dokumentation für deren Verwendung konfigurieren. + +### Projektdateistruktur + +Nehmen wir an, die Dateistruktur Ihres Projekts sieht folgendermaßen aus: + +``` +. +├── app +│ ├── __init__.py +│ ├── main.py +``` + +Erstellen Sie jetzt ein Verzeichnis zum Speichern dieser statischen Dateien. + +Ihre neue Dateistruktur könnte so aussehen: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +└── static/ +``` + +### Die Dateien herunterladen + +Laden Sie die für die Dokumentation benötigten statischen Dateien herunter und legen Sie diese im Verzeichnis `static/` ab. + +Sie können wahrscheinlich mit der rechten Maustaste auf jeden Link klicken und eine Option wie etwa `Link speichern unter...` auswählen. + +**Swagger UI** verwendet folgende Dateien: + +* `swagger-ui-bundle.js` +* `swagger-ui.css` + +Und **ReDoc** verwendet diese Datei: + +* `redoc.standalone.js` + +Danach könnte Ihre Dateistruktur wie folgt aussehen: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +└── static + ├── redoc.standalone.js + ├── swagger-ui-bundle.js + └── swagger-ui.css +``` + +### Die statischen Dateien bereitstellen + +* Importieren Sie `StaticFiles`. +* „Mounten“ Sie eine `StaticFiles()`-Instanz in einem bestimmten Pfad. + +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[7,11] *} + +### Die statischen Dateien testen + +Starten Sie Ihre Anwendung und gehen Sie auf http://127.0.0.1:8000/static/redoc.standalone.js. + +Sie sollten eine sehr lange JavaScript-Datei für **ReDoc** sehen. + +Sie könnte beginnen mit etwas wie: + +```JavaScript +/*! + * ReDoc - OpenAPI/Swagger-generated API Reference Documentation + * ------------------------------------------------------------- + * Version: "2.0.0-rc.18" + * Repo: https://github.com/Redocly/redoc + */ +!function(e,t){"object"==typeof exports&&"object"==typeof m + +... +``` + +Das zeigt, dass Sie statische Dateien aus Ihrer Anwendung bereitstellen können und dass Sie die statischen Dateien für die Dokumentation an der richtigen Stelle platziert haben. + +Jetzt können wir die Anwendung so konfigurieren, dass sie diese statischen Dateien für die Dokumentation verwendet. + +### Die automatischen Dokumentationen deaktivieren, für statische Dateien + +Wie bei der Verwendung eines benutzerdefinierten CDN besteht der erste Schritt darin, die automatischen Dokumentationen zu deaktivieren, da diese standardmäßig das CDN verwenden. + +Um diese zu deaktivieren, setzen Sie deren URLs beim Erstellen Ihrer `FastAPI`-App auf `None`: + +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[9] *} + +### Die benutzerdefinierten Dokumentationen, mit statischen Dateien, hinzufügen + +Und genau wie bei einem benutzerdefinierten CDN können Sie jetzt die *Pfadoperationen* für die benutzerdefinierten Dokumentationen erstellen. + +Auch hier können Sie die internen Funktionen von FastAPI wiederverwenden, um die HTML-Seiten für die Dokumentationen zu erstellen, und diesen die erforderlichen Argumente übergeben: + +* `openapi_url`: die URL, unter der die HTML-Seite für die Dokumentation das OpenAPI-Schema für Ihre API abrufen kann. Sie können hier das Attribut `app.openapi_url` verwenden. +* `title`: der Titel Ihrer API. +* `oauth2_redirect_url`: Sie können hier `app.swagger_ui_oauth2_redirect_url` verwenden, um die Standardeinstellung zu verwenden. +* `swagger_js_url`: die URL, unter welcher der HTML-Code für Ihre Swagger-UI-Dokumentation die **JavaScript**-Datei abrufen kann. **Das ist die, welche jetzt von Ihrer eigenen Anwendung bereitgestellt wird**. +* `swagger_css_url`: die URL, unter welcher der HTML-Code für Ihre Swagger-UI-Dokumentation die **CSS**-Datei abrufen kann. **Das ist die, welche jetzt von Ihrer eigenen Anwendung bereitgestellt wird**. + +Und genau so für ReDoc ... + +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[2:6,14:22,25:27,30:36] *} + +/// tip | Tipp + +Die *Pfadoperation* für `swagger_ui_redirect` ist ein Hilfsmittel bei der Verwendung von OAuth2. + +Wenn Sie Ihre API mit einem OAuth2-Anbieter integrieren, können Sie sich authentifizieren und mit den erworbenen Anmeldeinformationen zur API-Dokumentation zurückkehren. Und mit ihr interagieren, die echte OAuth2-Authentifizierung verwendend. + +Swagger UI erledigt das hinter den Kulissen für Sie, benötigt aber diesen „Umleitungs“-Helfer. + +/// + +### Eine *Pfadoperation* erstellen, um statische Dateien zu testen + +Um nun testen zu können, ob alles funktioniert, erstellen Sie eine *Pfadoperation*: + +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[39:41] *} + +### Benutzeroberfläche, mit statischen Dateien, testen + +Jetzt sollten Sie in der Lage sein, Ihr WLAN zu trennen, gehen Sie zu Ihrer Dokumentation unter http://127.0.0.1:8000/docs und laden Sie die Seite neu. + +Und selbst ohne Internet könnten Sie die Dokumentation für Ihre API sehen und damit interagieren. diff --git a/docs/de/docs/how-to/custom-request-and-route.md b/docs/de/docs/how-to/custom-request-and-route.md new file mode 100644 index 000000000..3e6f709b6 --- /dev/null +++ b/docs/de/docs/how-to/custom-request-and-route.md @@ -0,0 +1,109 @@ +# Benutzerdefinierte Request- und APIRoute-Klasse + +In einigen Fällen möchten Sie möglicherweise die von den Klassen `Request` und `APIRoute` verwendete Logik überschreiben. + +Das kann insbesondere eine gute Alternative zur Logik in einer Middleware sein. + +Wenn Sie beispielsweise den Requestbody lesen oder manipulieren möchten, bevor er von Ihrer Anwendung verarbeitet wird. + +/// danger | Gefahr + +Dies ist eine „fortgeschrittene“ Funktion. + +Wenn Sie gerade erst mit **FastAPI** beginnen, möchten Sie diesen Abschnitt vielleicht überspringen. + +/// + +## Anwendungsfälle + +Einige Anwendungsfälle sind: + +* Konvertieren von Nicht-JSON-Requestbodys nach JSON (z. B. `msgpack`). +* Dekomprimierung gzip-komprimierter Requestbodys. +* Automatisches Loggen aller Requestbodys. + +## Handhaben von benutzerdefinierten Requestbody-Kodierungen + +Sehen wir uns an, wie Sie eine benutzerdefinierte `Request`-Unterklasse verwenden, um gzip-Requests zu dekomprimieren. + +Und eine `APIRoute`-Unterklasse zur Verwendung dieser benutzerdefinierten Requestklasse. + +### Eine benutzerdefinierte `GzipRequest`-Klasse erstellen + +/// tip | Tipp + +Dies ist nur ein einfaches Beispiel, um zu demonstrieren, wie es funktioniert. Wenn Sie Gzip-Unterstützung benötigen, können Sie die bereitgestellte [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank} verwenden. + +/// + +Zuerst erstellen wir eine `GzipRequest`-Klasse, welche die Methode `Request.body()` überschreibt, um den Body bei Vorhandensein eines entsprechenden Headers zu dekomprimieren. + +Wenn der Header kein `gzip` enthält, wird nicht versucht, den Body zu dekomprimieren. + +Auf diese Weise kann dieselbe Routenklasse gzip-komprimierte oder unkomprimierte Requests verarbeiten. + +{* ../../docs_src/custom_request_and_route/tutorial001.py hl[8:15] *} + +### Eine benutzerdefinierte `GzipRoute`-Klasse erstellen + +Als Nächstes erstellen wir eine benutzerdefinierte Unterklasse von `fastapi.routing.APIRoute`, welche `GzipRequest` nutzt. + +Dieses Mal wird die Methode `APIRoute.get_route_handler()` überschrieben. + +Diese Methode gibt eine Funktion zurück. Und diese Funktion empfängt einen Request und gibt eine Response zurück. + +Hier verwenden wir sie, um aus dem ursprünglichen Request einen `GzipRequest` zu erstellen. + +{* ../../docs_src/custom_request_and_route/tutorial001.py hl[18:26] *} + +/// note | Technische Details + +Ein `Request` hat ein `request.scope`-Attribut, welches einfach ein Python-`dict` ist, welches die mit dem Request verbundenen Metadaten enthält. + +Ein `Request` hat auch ein `request.receive`, welches eine Funktion ist, die den Hauptteil des Requests empfängt. + +Das `scope`-`dict` und die `receive`-Funktion sind beide Teil der ASGI-Spezifikation. + +Und diese beiden Dinge, `scope` und `receive`, werden benötigt, um eine neue `Request`-Instanz zu erstellen. + +Um mehr über den `Request` zu erfahren, schauen Sie sich Starlettes Dokumentation zu Requests an. + +/// + +Das Einzige, was die von `GzipRequest.get_route_handler` zurückgegebene Funktion anders macht, ist die Konvertierung von `Request` in ein `GzipRequest`. + +Dabei kümmert sich unser `GzipRequest` um die Dekomprimierung der Daten (falls erforderlich), bevor diese an unsere *Pfadoperationen* weitergegeben werden. + +Danach ist die gesamte Verarbeitungslogik dieselbe. + +Aufgrund unserer Änderungen in `GzipRequest.body` wird der Requestbody jedoch bei Bedarf automatisch dekomprimiert, wenn er von **FastAPI** geladen wird. + +## Zugriff auf den Requestbody in einem Exceptionhandler + +/// tip | Tipp + +Um dasselbe Problem zu lösen, ist es wahrscheinlich viel einfacher, den `body` in einem benutzerdefinierten Handler für `RequestValidationError` zu verwenden ([Fehlerbehandlung](../tutorial/handling-errors.md#den-requestvalidationerror-body-verwenden){.internal-link target=_blank}). + +Dieses Beispiel ist jedoch immer noch gültig und zeigt, wie mit den internen Komponenten interagiert wird. + +/// + +Wir können denselben Ansatz auch verwenden, um in einem Exceptionhandler auf den Requestbody zuzugreifen. + +Alles, was wir tun müssen, ist, den Request innerhalb eines `try`/`except`-Blocks zu handhaben: + +{* ../../docs_src/custom_request_and_route/tutorial002.py hl[13,15] *} + +Wenn eine Exception auftritt, befindet sich die `Request`-Instanz weiterhin im Gültigkeitsbereich, sodass wir den Requestbody lesen und bei der Fehlerbehandlung verwenden können: + +{* ../../docs_src/custom_request_and_route/tutorial002.py hl[16:18] *} + +## Benutzerdefinierte `APIRoute`-Klasse in einem Router + +Sie können auch den Parameter `route_class` eines `APIRouter` festlegen: + +{* ../../docs_src/custom_request_and_route/tutorial003.py hl[26] *} + +In diesem Beispiel verwenden die *Pfadoperationen* unter dem `router` die benutzerdefinierte `TimedRoute`-Klasse und haben in der Response einen zusätzlichen `X-Response-Time`-Header mit der Zeit, die zum Generieren der Response benötigt wurde: + +{* ../../docs_src/custom_request_and_route/tutorial003.py hl[13:20] *} diff --git a/docs/de/docs/how-to/extending-openapi.md b/docs/de/docs/how-to/extending-openapi.md new file mode 100644 index 000000000..3b1459364 --- /dev/null +++ b/docs/de/docs/how-to/extending-openapi.md @@ -0,0 +1,80 @@ +# OpenAPI erweitern + +In einigen Fällen müssen Sie möglicherweise das generierte OpenAPI-Schema ändern. + +In diesem Abschnitt erfahren Sie, wie. + +## Der normale Vorgang + +Der normale (Standard-)Prozess ist wie folgt. + +Eine `FastAPI`-Anwendung (-Instanz) verfügt über eine `.openapi()`-Methode, von der erwartet wird, dass sie das OpenAPI-Schema zurückgibt. + +Als Teil der Erstellung des Anwendungsobjekts wird eine *Pfadoperation* für `/openapi.json` (oder welcher Wert für den Parameter `openapi_url` gesetzt wurde) registriert. + +Diese gibt lediglich eine JSON-Response zurück, mit dem Ergebnis der Methode `.openapi()` der Anwendung. + +Standardmäßig überprüft die Methode `.openapi()` die Eigenschaft `.openapi_schema`, um zu sehen, ob diese Inhalt hat, und gibt diesen zurück. + +Ist das nicht der Fall, wird der Inhalt mithilfe der Hilfsfunktion unter `fastapi.openapi.utils.get_openapi` generiert. + +Und diese Funktion `get_openapi()` erhält als Parameter: + +* `title`: Der OpenAPI-Titel, der in der Dokumentation angezeigt wird. +* `version`: Die Version Ihrer API, z. B. `2.5.0`. +* `openapi_version`: Die Version der verwendeten OpenAPI-Spezifikation. Standardmäßig die neueste Version: `3.1.0`. +* `summary`: Eine kurze Zusammenfassung der API. +* `description`: Die Beschreibung Ihrer API. Dies kann Markdown enthalten und wird in der Dokumentation angezeigt. +* `routes`: Eine Liste von Routen, dies sind alle registrierten *Pfadoperationen*. Sie stammen von `app.routes`. + +/// info + +Der Parameter `summary` ist in OpenAPI 3.1.0 und höher verfügbar und wird von FastAPI 0.99.0 und höher unterstützt. + +/// + +## Überschreiben der Standardeinstellungen + +Mithilfe der oben genannten Informationen können Sie dieselbe Hilfsfunktion verwenden, um das OpenAPI-Schema zu generieren und jeden benötigten Teil zu überschreiben. + +Fügen wir beispielsweise ReDocs OpenAPI-Erweiterung zum Einbinden eines benutzerdefinierten Logos hinzu. + +### Normales **FastAPI** + +Schreiben Sie zunächst wie gewohnt Ihre ganze **FastAPI**-Anwendung: + +{* ../../docs_src/extending_openapi/tutorial001.py hl[1,4,7:9] *} + +### Das OpenAPI-Schema generieren + +Verwenden Sie dann dieselbe Hilfsfunktion, um das OpenAPI-Schema innerhalb einer `custom_openapi()`-Funktion zu generieren: + +{* ../../docs_src/extending_openapi/tutorial001.py hl[2,15:21] *} + +### Das OpenAPI-Schema ändern + +Jetzt können Sie die ReDoc-Erweiterung hinzufügen und dem `info`-„Objekt“ im OpenAPI-Schema ein benutzerdefiniertes `x-logo` hinzufügen: + +{* ../../docs_src/extending_openapi/tutorial001.py hl[22:24] *} + +### Zwischenspeichern des OpenAPI-Schemas + +Sie können die Eigenschaft `.openapi_schema` als „Cache“ verwenden, um Ihr generiertes Schema zu speichern. + +Auf diese Weise muss Ihre Anwendung das Schema nicht jedes Mal generieren, wenn ein Benutzer Ihre API-Dokumentation öffnet. + +Es wird nur einmal generiert und dann wird dasselbe zwischengespeicherte Schema für die nächsten Requests verwendet. + +{* ../../docs_src/extending_openapi/tutorial001.py hl[13:14,25:26] *} + +### Die Methode überschreiben + +Jetzt können Sie die Methode `.openapi()` durch Ihre neue Funktion ersetzen. + +{* ../../docs_src/extending_openapi/tutorial001.py hl[29] *} + +### Testen + +Sobald Sie auf http://127.0.0.1:8000/redoc gehen, werden Sie sehen, dass Ihr benutzerdefiniertes Logo verwendet wird (in diesem Beispiel das Logo von **FastAPI**): + + diff --git a/docs/de/docs/how-to/general.md b/docs/de/docs/how-to/general.md new file mode 100644 index 000000000..b38b5fabf --- /dev/null +++ b/docs/de/docs/how-to/general.md @@ -0,0 +1,39 @@ +# Allgemeines – How-To – Rezepte + +Hier finden Sie mehrere Verweise auf andere Stellen in der Dokumentation, für allgemeine oder häufige Fragen. + +## Daten filtern – Sicherheit + +Um sicherzustellen, dass Sie nicht mehr Daten zurückgeben, als Sie sollten, lesen Sie die Dokumentation unter [Tutorial – Responsemodell – Rückgabetyp](../tutorial/response-model.md){.internal-link target=_blank}. + +## Dokumentations-Tags – OpenAPI + +Um Tags zu Ihren *Pfadoperationen* hinzuzufügen und diese in der Oberfläche der Dokumentation zu gruppieren, lesen Sie die Dokumentation unter [Tutorial – Pfadoperation-Konfiguration – Tags](../tutorial/path-operation-configuration.md#tags){.internal-link target=_blank}. + +## Zusammenfassung und Beschreibung in der Dokumentation – OpenAPI + +Um Ihren *Pfadoperationen* eine Zusammenfassung und Beschreibung hinzuzufügen und diese in der Oberfläche der Dokumentation anzuzeigen, lesen Sie die Dokumentation unter [Tutorial – Pfadoperation-Konfiguration – Zusammenfassung und Beschreibung](../tutorial/path-operation-configuration.md#zusammenfassung-und-beschreibung){.internal-link target=_blank}. + +## Beschreibung der Response in der Dokumentation – OpenAPI + +Um die Beschreibung der Response zu definieren, welche in der Oberfläche der Dokumentation angezeigt wird, lesen Sie die Dokumentation unter [Tutorial – Pfadoperation-Konfiguration – Beschreibung der Response](../tutorial/path-operation-configuration.md#beschreibung-der-response){.internal-link target=_blank}. + +## *Pfadoperation* in der Dokumentation deprecaten – OpenAPI + +Um eine *Pfadoperation* zu deprecaten – sie als veraltet zu markieren – und das in der Oberfläche der Dokumentation anzuzeigen, lesen Sie die Dokumentation unter [Tutorial – Pfadoperation-Konfiguration – Deprecaten](../tutorial/path-operation-configuration.md#eine-pfadoperation-deprecaten){.internal-link target=_blank}. + +## Daten in etwas JSON-kompatibles konvertieren + +Um Daten in etwas JSON-kompatibles zu konvertieren, lesen Sie die Dokumentation unter [Tutorial – JSON-kompatibler Encoder](../tutorial/encoder.md){.internal-link target=_blank}. + +## OpenAPI-Metadaten – Dokumentation + +Um Metadaten zu Ihrem OpenAPI-Schema hinzuzufügen, einschließlich einer Lizenz, Version, Kontakt, usw., lesen Sie die Dokumentation unter [Tutorial – Metadaten und URLs der Dokumentationen](../tutorial/metadata.md){.internal-link target=_blank}. + +## Benutzerdefinierte OpenAPI-URL + +Um die OpenAPI-URL anzupassen (oder zu entfernen), lesen Sie die Dokumentation unter [Tutorial – Metadaten und URLs der Dokumentationen](../tutorial/metadata.md#openapi-url){.internal-link target=_blank}. + +## URLs der OpenAPI-Dokumentationen + +Um die URLs zu aktualisieren, die für die automatisch generierten Dokumentations-Oberflächen verwendet werden, lesen Sie die Dokumentation unter [Tutorial – Metadaten und URLs der Dokumentationen](../tutorial/metadata.md#urls-der-dokumentationen){.internal-link target=_blank}. diff --git a/docs/de/docs/how-to/graphql.md b/docs/de/docs/how-to/graphql.md new file mode 100644 index 000000000..4083e66ae --- /dev/null +++ b/docs/de/docs/how-to/graphql.md @@ -0,0 +1,60 @@ +# GraphQL + +Da **FastAPI** auf dem **ASGI**-Standard basiert, ist es sehr einfach, jede **GraphQL**-Bibliothek zu integrieren, die auch mit ASGI kompatibel ist. + +Sie können normale FastAPI-*Pfadoperationen* mit GraphQL in derselben Anwendung kombinieren. + +/// tip | Tipp + +**GraphQL** löst einige sehr spezifische Anwendungsfälle. + +Es hat **Vorteile** und **Nachteile** im Vergleich zu gängigen **Web-APIs**. + +Wiegen Sie ab, ob die **Vorteile** für Ihren Anwendungsfall die **Nachteile** ausgleichen. 🤓 + +/// + +## GraphQL-Bibliotheken + +Hier sind einige der **GraphQL**-Bibliotheken, welche **ASGI** unterstützen. Diese könnten Sie mit **FastAPI** verwenden: + +* Strawberry 🍓 + * Mit Dokumentation für FastAPI +* Ariadne + * Mit Dokumentation für FastAPI +* Tartiflette + * Mit Tartiflette ASGI, für ASGI-Integration +* Graphene + * Mit starlette-graphene3 + +## GraphQL mit Strawberry + +Wenn Sie mit **GraphQL** arbeiten möchten oder müssen, ist **Strawberry** die **empfohlene** Bibliothek, da deren Design dem Design von **FastAPI** am nächsten kommt und alles auf **Typannotationen** basiert. + +Abhängig von Ihrem Anwendungsfall bevorzugen Sie vielleicht eine andere Bibliothek, aber wenn Sie mich fragen würden, würde ich Ihnen wahrscheinlich empfehlen, **Strawberry** auszuprobieren. + +Hier ist eine kleine Vorschau, wie Sie Strawberry mit FastAPI integrieren können: + +{* ../../docs_src/graphql/tutorial001.py hl[3,22,25:26] *} + +Weitere Informationen zu Strawberry finden Sie in der Strawberry-Dokumentation. + +Und auch die Dokumentation zu Strawberry mit FastAPI. + +## Ältere `GraphQLApp` von Starlette + +Frühere Versionen von Starlette enthielten eine `GraphQLApp`-Klasse zur Integration mit Graphene. + +Das wurde von Starlette deprecated, aber wenn Sie Code haben, der das verwendet, können Sie einfach zu starlette-graphene3 **migrieren**, welches denselben Anwendungsfall abdeckt und über eine **fast identische Schnittstelle** verfügt. + +/// tip | Tipp + +Wenn Sie GraphQL benötigen, würde ich Ihnen trotzdem empfehlen, sich Strawberry anzuschauen, da es auf Typannotationen basiert, statt auf benutzerdefinierten Klassen und Typen. + +/// + +## Mehr darüber lernen + +Weitere Informationen zu **GraphQL** finden Sie in der offiziellen GraphQL-Dokumentation. + +Sie können auch mehr über jede der oben beschriebenen Bibliotheken in den jeweiligen Links lesen. diff --git a/docs/de/docs/how-to/index.md b/docs/de/docs/how-to/index.md new file mode 100644 index 000000000..84a178fc8 --- /dev/null +++ b/docs/de/docs/how-to/index.md @@ -0,0 +1,13 @@ +# How-To – Rezepte + +Hier finden Sie verschiedene Rezepte und „How-To“-Anleitungen zu **verschiedenen Themen**. + +Die meisten dieser Ideen sind mehr oder weniger **unabhängig**, und in den meisten Fällen müssen Sie diese nur studieren, wenn sie direkt auf **Ihr Projekt** anwendbar sind. + +Wenn etwas für Ihr Projekt interessant und nützlich erscheint, lesen Sie es, andernfalls überspringen Sie es einfach. + +/// tip | Tipp + +Wenn Sie strukturiert **FastAPI lernen** möchten (empfohlen), lesen Sie stattdessen Kapitel für Kapitel das [Tutorial – Benutzerhandbuch](../tutorial/index.md){.internal-link target=_blank}. + +/// diff --git a/docs/de/docs/how-to/separate-openapi-schemas.md b/docs/de/docs/how-to/separate-openapi-schemas.md new file mode 100644 index 000000000..4f6911e79 --- /dev/null +++ b/docs/de/docs/how-to/separate-openapi-schemas.md @@ -0,0 +1,104 @@ +# Separate OpenAPI-Schemas für Eingabe und Ausgabe oder nicht + +Bei Verwendung von **Pydantic v2** ist die generierte OpenAPI etwas genauer und **korrekter** als zuvor. 😎 + +Tatsächlich gibt es in einigen Fällen sogar **zwei JSON-Schemas** in OpenAPI für dasselbe Pydantic-Modell für Eingabe und Ausgabe, je nachdem, ob sie **Defaultwerte** haben. + +Sehen wir uns an, wie das funktioniert und wie Sie es bei Bedarf ändern können. + +## Pydantic-Modelle für Eingabe und Ausgabe + +Nehmen wir an, Sie haben ein Pydantic-Modell mit Defaultwerten wie dieses: + +{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:7] hl[7] *} + +### Modell für Eingabe + +Wenn Sie dieses Modell wie hier als Eingabe verwenden: + +{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:15] hl[14] *} + +... dann ist das Feld `description` **nicht erforderlich**. Weil es den Defaultwert `None` hat. + +### Eingabemodell in der Dokumentation + +Sie können überprüfen, dass das Feld `description` in der Dokumentation kein **rotes Sternchen** enthält, es ist nicht als erforderlich markiert: + +
+ +
+ +### Modell für die Ausgabe + +Wenn Sie jedoch dasselbe Modell als Ausgabe verwenden, wie hier: + +{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py hl[19] *} + +... dann, weil `description` einen Defaultwert hat, wird es, wenn Sie für dieses Feld **nichts zurückgeben**, immer noch diesen **Defaultwert** haben. + +### Modell für Ausgabe-Responsedaten + +Wenn Sie mit der Dokumentation interagieren und die Response überprüfen, enthält die JSON-Response den Defaultwert (`null`), obwohl der Code nichts in eines der `description`-Felder geschrieben hat: + +
+ +
+ +Das bedeutet, dass es **immer einen Wert** hat, der Wert kann jedoch manchmal `None` sein (oder `null` in JSON). + +Das bedeutet, dass Clients, die Ihre API verwenden, nicht prüfen müssen, ob der Wert vorhanden ist oder nicht. Sie können davon ausgehen, dass das Feld immer vorhanden ist. In einigen Fällen hat es jedoch nur den Defaultwert `None`. + +Um dies in OpenAPI zu kennzeichnen, markieren Sie dieses Feld als **erforderlich**, da es immer vorhanden sein wird. + +Aus diesem Grund kann das JSON-Schema für ein Modell unterschiedlich sein, je nachdem, ob es für **Eingabe oder Ausgabe** verwendet wird: + +* für die **Eingabe** ist `description` **nicht erforderlich** +* für die **Ausgabe** ist es **erforderlich** (und möglicherweise `None` oder, in JSON-Begriffen, `null`) + +### Ausgabemodell in der Dokumentation + +Sie können das Ausgabemodell auch in der Dokumentation überprüfen. **Sowohl** `name` **als auch** `description` sind mit einem **roten Sternchen** als **erforderlich** markiert: + +
+ +
+ +### Eingabe- und Ausgabemodell in der Dokumentation + +Und wenn Sie alle verfügbaren Schemas (JSON-Schemas) in OpenAPI überprüfen, werden Sie feststellen, dass es zwei gibt, ein `Item-Input` und ein `Item-Output`. + +Für `Item-Input` ist `description` **nicht erforderlich**, es hat kein rotes Sternchen. + +Aber für `Item-Output` ist `description` **erforderlich**, es hat ein rotes Sternchen. + +
+ +
+ +Mit dieser Funktion von **Pydantic v2** ist Ihre API-Dokumentation **präziser**, und wenn Sie über automatisch generierte Clients und SDKs verfügen, sind diese auch präziser, mit einer besseren **Entwicklererfahrung** und Konsistenz. 🎉 + +## Schemas nicht trennen + +Nun gibt es einige Fälle, in denen Sie möglicherweise **dasselbe Schema für Eingabe und Ausgabe** haben möchten. + +Der Hauptanwendungsfall hierfür besteht wahrscheinlich darin, dass Sie das mal tun möchten, wenn Sie bereits über einige automatisch generierte Client-Codes/SDKs verfügen und im Moment nicht alle automatisch generierten Client-Codes/SDKs aktualisieren möchten, möglicherweise später, aber nicht jetzt. + +In diesem Fall können Sie diese Funktion in **FastAPI** mit dem Parameter `separate_input_output_schemas=False` deaktivieren. + +/// info + +Unterstützung für `separate_input_output_schemas` wurde in FastAPI `0.102.0` hinzugefügt. 🤓 + +/// + +{* ../../docs_src/separate_openapi_schemas/tutorial002_py310.py hl[10] *} + +### Gleiches Schema für Eingabe- und Ausgabemodelle in der Dokumentation + +Und jetzt wird es ein einziges Schema für die Eingabe und Ausgabe des Modells geben, nur `Item`, und es wird `description` als **nicht erforderlich** kennzeichnen: + +
+ +
+ +Dies ist das gleiche Verhalten wie in Pydantic v1. 🤓 diff --git a/docs/de/docs/index.md b/docs/de/docs/index.md new file mode 100644 index 000000000..d239f0815 --- /dev/null +++ b/docs/de/docs/index.md @@ -0,0 +1,474 @@ +# FastAPI + + + +

+ FastAPI +

+

+ FastAPI Framework, hochperformant, leicht zu erlernen, schnell zu programmieren, einsatzbereit +

+

+ + Test + + + Coverage + + + Package-Version + + + Unterstützte Python-Versionen + +

+ +--- + +**Dokumentation**: https://fastapi.tiangolo.com + +**Quellcode**: https://github.com/fastapi/fastapi + +--- + +FastAPI ist ein modernes, schnelles (hoch performantes) Webframework zur Erstellung von APIs mit Python auf Basis von Standard-Python-Typhinweisen. + +Seine Schlüssel-Merkmale sind: + +* **Schnell**: Sehr hohe Leistung, auf Augenhöhe mit **NodeJS** und **Go** (Dank Starlette und Pydantic). [Eines der schnellsten verfügbaren Python-Frameworks](#performanz). + +* **Schnell zu programmieren**: Erhöhen Sie die Geschwindigkeit bei der Entwicklung von Funktionen um etwa 200 % bis 300 %. * +* **Weniger Bugs**: Verringern Sie die von Menschen (Entwicklern) verursachten Fehler um etwa 40 %. * +* **Intuitiv**: Exzellente Editor-Unterstützung. Code-Vervollständigung überall. Weniger Debuggen. +* **Einfach**: So konzipiert, dass es einfach zu benutzen und zu erlernen ist. Weniger Zeit für das Lesen der Dokumentation. +* **Kurz**: Minimieren Sie die Verdoppelung von Code. Mehrere Funktionen aus jeder Parameterdeklaration. Weniger Bugs. +* **Robust**: Erhalten Sie produktionsreifen Code. Mit automatischer, interaktiver Dokumentation. +* **Standards-basiert**: Basierend auf (und vollständig kompatibel mit) den offenen Standards für APIs: OpenAPI (früher bekannt als Swagger) und JSON Schema. + +* Schätzung auf Basis von Tests in einem internen Entwicklungsteam, das Produktionsanwendungen erstellt. + +## Sponsoren + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} + +{% endfor -%} +{%- for sponsor in sponsors.silver -%} + +{% endfor %} +{% endif %} + + + +Andere Sponsoren + +## Meinungen + +„_[...] Ich verwende **FastAPI** heutzutage sehr oft. [...] Ich habe tatsächlich vor, es für alle **ML-Dienste meines Teams bei Microsoft** zu verwenden. Einige davon werden in das Kernprodukt **Windows** und einige **Office**-Produkte integriert._“ + +
Kabir Khan - Microsoft (Ref)
+ +--- + +„_Wir haben die **FastAPI**-Bibliothek genommen, um einen **REST**-Server zu erstellen, der abgefragt werden kann, um **Vorhersagen** zu erhalten. [für Ludwig]_“ + +
Piero Molino, Yaroslav Dudin, und Sai Sumanth Miryala - Uber (Ref)
+ +--- + +„_**Netflix** freut sich, die Open-Source-Veröffentlichung unseres **Krisenmanagement**-Orchestrierung-Frameworks bekannt zu geben: **Dispatch**! [erstellt mit **FastAPI**]_“ + +
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (Ref)
+ +--- + +„_Ich bin überglücklich mit **FastAPI**. Es macht so viel Spaß!_“ + +
Brian Okken - Host des Python Bytes Podcast (Ref)
+ +--- + +„_Ehrlich, was Du gebaut hast, sieht super solide und poliert aus. In vielerlei Hinsicht ist es so, wie ich **Hug** haben wollte – es ist wirklich inspirierend, jemanden so etwas bauen zu sehen._“ + +
Timothy Crosley - Autor von Hug (Ref)
+ +--- + +„_Wenn Sie ein **modernes Framework** zum Erstellen von REST-APIs erlernen möchten, schauen Sie sich **FastAPI** an. [...] Es ist schnell, einfach zu verwenden und leicht zu erlernen [...]_“ + +„_Wir haben zu **FastAPI** für unsere **APIs** gewechselt [...] Ich denke, es wird Ihnen gefallen [...]_“ + +
Ines Montani - Matthew Honnibal - Gründer von Explosion AI - Autoren von spaCy (Ref) - (Ref)
+ +--- + +„_Falls irgendjemand eine Produktions-Python-API erstellen möchte, kann ich **FastAPI** wärmstens empfehlen. Es ist **wunderschön konzipiert**, **einfach zu verwenden** und **hoch skalierbar**; es ist zu einer **Schlüsselkomponente** in unserer API-First-Entwicklungsstrategie geworden und treibt viele Automatisierungen und Dienste an, wie etwa unseren virtuellen TAC-Ingenieur._“ + +
Deon Pillsbury - Cisco (Ref)
+ +--- + +## **Typer**, das FastAPI der CLIs + + + +Wenn Sie eine CLI-Anwendung für das Terminal erstellen, anstelle einer Web-API, schauen Sie sich **Typer** an. + +**Typer** ist die kleine Schwester von FastAPI. Und es soll das **FastAPI der CLIs** sein. ⌨️ 🚀 + +## Anforderungen + +FastAPI steht auf den Schultern von Giganten: + +* Starlette für die Webanteile. +* Pydantic für die Datenanteile. + +## Installation + +
+ +```console +$ pip install fastapi + +---> 100% +``` + +
+ +Sie benötigen außerdem einen ASGI-Server. Für die Produktumgebung beispielsweise Uvicorn oder Hypercorn. + +
+ +```console +$ pip install "uvicorn[standard]" + +---> 100% +``` + +
+ +## Beispiel + +### Erstellung + +* Erstellen Sie eine Datei `main.py` mit: + +```Python +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@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} +``` + +
+Oder verwenden Sie async def ... + +Wenn Ihr Code `async` / `await` verwendet, benutzen Sie `async def`: + +```Python hl_lines="9 14" +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +async def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +async def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +**Anmerkung**: + +Wenn Sie das nicht kennen, schauen Sie sich den Abschnitt _„In Eile?“_ über `async` und `await` in der Dokumentation an. +
+ +### Starten + +Führen Sie den Server aus: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [28720] +INFO: Started server process [28722] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +
+Was macht der Befehl uvicorn main:app --reload ... + +Der Befehl `uvicorn main:app` bezieht sich auf: + +* `main`: die Datei `main.py` (das Python-„Modul“). +* `app`: das Objekt, das innerhalb von `main.py` mit der Zeile `app = FastAPI()` erzeugt wurde. +* `--reload`: lässt den Server nach Codeänderungen neu starten. Tun Sie das nur während der Entwicklung. + +
+ +### Testen + +Öffnen Sie Ihren Browser unter http://127.0.0.1:8000/items/5?q=somequery. + +Sie erhalten die JSON-Response: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +Damit haben Sie bereits eine API erstellt, welche: + +* HTTP-Anfragen auf den _Pfaden_ `/` und `/items/{item_id}` entgegennimmt. +* Beide _Pfade_ erhalten `GET` Operationen (auch bekannt als HTTP _Methoden_). +* Der _Pfad_ `/items/{item_id}` hat einen _Pfadparameter_ `item_id`, der ein `int` sein sollte. +* Der _Pfad_ `/items/{item_id}` hat einen optionalen `str` _Query Parameter_ `q`. + +### Interaktive API-Dokumentation + +Gehen Sie nun auf http://127.0.0.1:8000/docs. + +Sie sehen die automatische interaktive API-Dokumentation (bereitgestellt von Swagger UI): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### Alternative API-Dokumentation + +Gehen Sie jetzt auf http://127.0.0.1:8000/redoc. + +Sie sehen die alternative automatische Dokumentation (bereitgestellt von ReDoc): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## Beispiel Aktualisierung + +Ändern Sie jetzt die Datei `main.py`, um den Body einer `PUT`-Anfrage zu empfangen. + +Deklarieren Sie den Body mithilfe von Standard-Python-Typen, dank 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} +``` + +Der Server sollte automatisch neu geladen werden (weil Sie oben `--reload` zum Befehl `uvicorn` hinzugefügt haben). + +### Aktualisierung der interaktiven API-Dokumentation + +Gehen Sie jetzt auf http://127.0.0.1:8000/docs. + +* Die interaktive API-Dokumentation wird automatisch aktualisiert, einschließlich des neuen Bodys: + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* Klicken Sie auf die Taste „Try it out“, damit können Sie die Parameter ausfüllen und direkt mit der API interagieren: + +![Swagger UI Interaktion](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) + +* Klicken Sie dann auf die Taste „Execute“, die Benutzeroberfläche wird mit Ihrer API kommunizieren, sendet die Parameter, holt die Ergebnisse und zeigt sie auf dem Bildschirm an: + +![Swagger UI Interaktion](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) + +### Aktualisierung der alternativen API-Dokumentation + +Und nun gehen Sie auf http://127.0.0.1:8000/redoc. + +* Die alternative Dokumentation wird ebenfalls den neuen Abfrageparameter und -inhalt widerspiegeln: + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### Zusammenfassung + +Zusammengefasst deklarieren Sie **einmal** die Typen von Parametern, Body, etc. als Funktionsparameter. + +Das machen Sie mit modernen Standard-Python-Typen. + +Sie müssen keine neue Syntax, Methoden oder Klassen einer bestimmten Bibliothek usw. lernen. + +Nur Standard-**Python+**. + +Zum Beispiel für ein `int`: + +```Python +item_id: int +``` + +oder für ein komplexeres `Item`-Modell: + +```Python +item: Item +``` + +... und mit dieser einen Deklaration erhalten Sie: + +* Editor-Unterstützung, einschließlich: + * Code-Vervollständigung. + * Typprüfungen. +* Validierung von Daten: + * Automatische und eindeutige Fehler, wenn die Daten ungültig sind. + * Validierung auch für tief verschachtelte JSON-Objekte. +* Konvertierung von Eingabedaten: Aus dem Netzwerk kommend, zu Python-Daten und -Typen. Lesen von: + * JSON. + * Pfad-Parametern. + * Abfrage-Parametern. + * Cookies. + * Header-Feldern. + * Formularen. + * Dateien. +* Konvertierung von Ausgabedaten: Konvertierung von Python-Daten und -Typen zu Netzwerkdaten (als JSON): + * Konvertieren von Python-Typen (`str`, `int`, `float`, `bool`, `list`, usw.). + * `Datetime`-Objekte. + * `UUID`-Objekte. + * Datenbankmodelle. + * ... und viele mehr. +* Automatische interaktive API-Dokumentation, einschließlich 2 alternativer Benutzeroberflächen: + * Swagger UI. + * ReDoc. + +--- + +Um auf das vorherige Codebeispiel zurückzukommen, **FastAPI** wird: + +* Überprüfen, dass es eine `item_id` im Pfad für `GET`- und `PUT`-Anfragen gibt. +* Überprüfen, ob die `item_id` vom Typ `int` für `GET`- und `PUT`-Anfragen ist. + * Falls nicht, wird dem Client ein nützlicher, eindeutiger Fehler angezeigt. +* Prüfen, ob es einen optionalen Abfrageparameter namens `q` (wie in `http://127.0.0.1:8000/items/foo?q=somequery`) für `GET`-Anfragen gibt. + * Da der `q`-Parameter mit `= None` deklariert ist, ist er optional. + * Ohne das `None` wäre er erforderlich (wie der Body im Fall von `PUT`). +* Bei `PUT`-Anfragen an `/items/{item_id}` den Body als JSON lesen: + * Prüfen, ob er ein erforderliches Attribut `name` hat, das ein `str` sein muss. + * Prüfen, ob er ein erforderliches Attribut `price` hat, das ein `float` sein muss. + * Prüfen, ob er ein optionales Attribut `is_offer` hat, das ein `bool` sein muss, falls vorhanden. + * All dies würde auch für tief verschachtelte JSON-Objekte funktionieren. +* Automatisch von und nach JSON konvertieren. +* Alles mit OpenAPI dokumentieren, welches verwendet werden kann von: + * Interaktiven Dokumentationssystemen. + * Automatisch Client-Code generierenden Systemen für viele Sprachen. +* Zwei interaktive Dokumentation-Webschnittstellen direkt zur Verfügung stellen. + +--- + +Wir haben nur an der Oberfläche gekratzt, aber Sie bekommen schon eine Vorstellung davon, wie das Ganze funktioniert. + +Versuchen Sie, diese Zeile zu ändern: + +```Python + return {"item_name": item.name, "item_id": item_id} +``` + +... von: + +```Python + ... "item_name": item.name ... +``` + +... zu: + +```Python + ... "item_price": item.price ... +``` + +... und sehen Sie, wie Ihr Editor die Attribute automatisch ausfüllt und ihre Typen kennt: + +![Editor Unterstützung](https://fastapi.tiangolo.com/img/vscode-completion.png) + +Für ein vollständigeres Beispiel, mit weiteren Funktionen, siehe das Tutorial - Benutzerhandbuch. + +**Spoiler-Alarm**: Das Tutorial - Benutzerhandbuch enthält: + +* Deklaration von **Parametern** von anderen verschiedenen Stellen wie: **Header-Felder**, **Cookies**, **Formularfelder** und **Dateien**. +* Wie man **Validierungseinschränkungen** wie `maximum_length` oder `regex` setzt. +* Ein sehr leistungsfähiges und einfach zu bedienendes System für **Dependency Injection**. +* Sicherheit und Authentifizierung, einschließlich Unterstützung für **OAuth2** mit **JWT-Tokens** und **HTTP-Basic**-Authentifizierung. +* Fortgeschrittenere (aber ebenso einfache) Techniken zur Deklaration **tief verschachtelter JSON-Modelle** (dank Pydantic). +* **GraphQL** Integration mit Strawberry und anderen Bibliotheken. +* Viele zusätzliche Funktionen (dank Starlette) wie: + * **WebSockets** + * extrem einfache Tests auf Basis von `httpx` und `pytest` + * **CORS** + * **Cookie Sessions** + * ... und mehr. + +## Performanz + +Unabhängige TechEmpower-Benchmarks zeigen **FastAPI**-Anwendungen, die unter Uvicorn laufen, als eines der schnellsten verfügbaren Python-Frameworks, nur noch hinter Starlette und Uvicorn selbst (intern von FastAPI verwendet). + +Um mehr darüber zu erfahren, siehe den Abschnitt Benchmarks. + +## Optionale Abhängigkeiten + +Wird von Pydantic verwendet: + +* email-validator - für E-Mail-Validierung. +* pydantic-settings - für die Verwaltung von Einstellungen. +* pydantic-extra-types - für zusätzliche Typen, mit Pydantic zu verwenden. + +Wird von Starlette verwendet: + +* httpx - erforderlich, wenn Sie den `TestClient` verwenden möchten. +* jinja2 - erforderlich, wenn Sie die Standardkonfiguration für Templates verwenden möchten. +* python-multipart - erforderlich, wenn Sie Formulare mittels `request.form()` „parsen“ möchten. +* itsdangerous - erforderlich für `SessionMiddleware` Unterstützung. +* pyyaml - erforderlich für Starlette's `SchemaGenerator` Unterstützung (Sie brauchen das wahrscheinlich nicht mit FastAPI). +* ujson - erforderlich, wenn Sie `UJSONResponse` verwenden möchten. + +Wird von FastAPI / Starlette verwendet: + +* uvicorn - für den Server, der Ihre Anwendung lädt und serviert. +* orjson - erforderlich, wenn Sie `ORJSONResponse` verwenden möchten. + +Sie können diese alle mit `pip install "fastapi[all]"` installieren. + +## Lizenz + +Dieses Projekt ist unter den Bedingungen der MIT-Lizenz lizenziert. diff --git a/docs/de/docs/learn/index.md b/docs/de/docs/learn/index.md new file mode 100644 index 000000000..b5582f55b --- /dev/null +++ b/docs/de/docs/learn/index.md @@ -0,0 +1,5 @@ +# Lernen + +Hier finden Sie die einführenden Kapitel und Tutorials zum Erlernen von **FastAPI**. + +Sie könnten dies als **Buch**, als **Kurs**, als **offizielle** und empfohlene Methode zum Erlernen von FastAPI betrachten. 😎 diff --git a/docs/de/docs/project-generation.md b/docs/de/docs/project-generation.md new file mode 100644 index 000000000..c47bcb6d3 --- /dev/null +++ b/docs/de/docs/project-generation.md @@ -0,0 +1,84 @@ +# Projektgenerierung – Vorlage + +Sie können einen Projektgenerator für den Einstieg verwenden, welcher einen Großteil der Ersteinrichtung, Sicherheit, Datenbank und einige API-Endpunkte bereits für Sie erstellt. + +Ein Projektgenerator verfügt immer über ein sehr spezifisches Setup, das Sie aktualisieren und an Ihre eigenen Bedürfnisse anpassen sollten, aber es könnte ein guter Ausgangspunkt für Ihr Projekt sein. + +## Full Stack FastAPI PostgreSQL + +GitHub: https://github.com/tiangolo/full-stack-fastapi-postgresql + +### Full Stack FastAPI PostgreSQL – Funktionen + +* Vollständige **Docker**-Integration (Docker-basiert). +* Docker-Schwarmmodus-Deployment. +* **Docker Compose**-Integration und Optimierung für die lokale Entwicklung. +* **Produktionsbereit** Python-Webserver, verwendet Uvicorn und Gunicorn. +* Python **FastAPI**-Backend: + * **Schnell**: Sehr hohe Leistung, auf Augenhöhe mit **NodeJS** und **Go** (dank Starlette und Pydantic). + * **Intuitiv**: Hervorragende Editor-Unterstützung. Codevervollständigung überall. Weniger Zeitaufwand für das Debuggen. + * **Einfach**: Einfach zu bedienen und zu erlernen. Weniger Zeit für das Lesen von Dokumentationen. + * **Kurz**: Codeverdoppelung minimieren. Mehrere Funktionalitäten aus jeder Parameterdeklaration. + * **Robust**: Erhalten Sie produktionsbereiten Code. Mit automatischer, interaktiver Dokumentation. + * **Standards-basiert**: Basierend auf (und vollständig kompatibel mit) den offenen Standards für APIs: OpenAPI und JSON Schema. + * **Viele weitere Funktionen**, einschließlich automatischer Validierung, Serialisierung, interaktiver Dokumentation, Authentifizierung mit OAuth2-JWT-Tokens, usw. +* **Sicheres Passwort**-Hashing standardmäßig. +* **JWT-Token**-Authentifizierung. +* **SQLAlchemy**-Modelle (unabhängig von Flask-Erweiterungen, sodass sie direkt mit Celery-Workern verwendet werden können). +* Grundlegende Startmodelle für Benutzer (ändern und entfernen Sie nach Bedarf). +* **Alembic**-Migrationen. +* **CORS** (Cross Origin Resource Sharing). +* **Celery**-Worker, welche Modelle und Code aus dem Rest des Backends selektiv importieren und verwenden können. +* REST-Backend-Tests basierend auf **Pytest**, integriert in Docker, sodass Sie die vollständige API-Interaktion unabhängig von der Datenbank testen können. Da es in Docker ausgeführt wird, kann jedes Mal ein neuer Datenspeicher von Grund auf erstellt werden (Sie können also ElasticSearch, MongoDB, CouchDB oder was auch immer Sie möchten verwenden und einfach testen, ob die API funktioniert). +* Einfache Python-Integration mit **Jupyter-Kerneln** für Remote- oder In-Docker-Entwicklung mit Erweiterungen wie Atom Hydrogen oder Visual Studio Code Jupyter. +* **Vue**-Frontend: + * Mit Vue CLI generiert. + * Handhabung der **JWT-Authentifizierung**. + * Login-View. + * Nach der Anmeldung Hauptansicht des Dashboards. + * Haupt-Dashboard mit Benutzererstellung und -bearbeitung. + * Bearbeitung des eigenen Benutzers. + * **Vuex**. + * **Vue-Router**. + * **Vuetify** für schöne Material-Designkomponenten. + * **TypeScript**. + * Docker-Server basierend auf **Nginx** (konfiguriert, um gut mit Vue-Router zu funktionieren). + * Mehrstufigen Docker-Erstellung, sodass Sie kompilierten Code nicht speichern oder committen müssen. + * Frontend-Tests, welche zur Erstellungszeit ausgeführt werden (können auch deaktiviert werden). + * So modular wie möglich gestaltet, sodass es sofort einsatzbereit ist. Sie können es aber mit Vue CLI neu generieren oder es so wie Sie möchten erstellen und wiederverwenden, was Sie möchten. +* **PGAdmin** für die PostgreSQL-Datenbank, können Sie problemlos ändern, sodass PHPMyAdmin und MySQL verwendet wird. +* **Flower** für die Überwachung von Celery-Jobs. +* Load Balancing zwischen Frontend und Backend mit **Traefik**, sodass Sie beide unter derselben Domain haben können, getrennt durch den Pfad, aber von unterschiedlichen Containern ausgeliefert. +* Traefik-Integration, einschließlich automatischer Generierung von Let's Encrypt-**HTTPS**-Zertifikaten. +* GitLab **CI** (kontinuierliche Integration), einschließlich Frontend- und Backend-Testen. + +## Full Stack FastAPI Couchbase + +GitHub: https://github.com/tiangolo/full-stack-fastapi-couchbase + +⚠️ **WARNUNG** ⚠️ + +Wenn Sie ein neues Projekt von Grund auf starten, prüfen Sie die Alternativen hier. + +Zum Beispiel könnte der Projektgenerator Full Stack FastAPI PostgreSQL eine bessere Alternative sein, da er aktiv gepflegt und genutzt wird. Und er enthält alle neuen Funktionen und Verbesserungen. + +Es steht Ihnen weiterhin frei, den Couchbase-basierten Generator zu verwenden, wenn Sie möchten. Er sollte wahrscheinlich immer noch gut funktionieren, und wenn Sie bereits ein Projekt damit erstellt haben, ist das auch in Ordnung (und Sie haben es wahrscheinlich bereits an Ihre Bedürfnisse angepasst). + +Weitere Informationen hierzu finden Sie in der Dokumentation des Repos. + +## Full Stack FastAPI MongoDB + +... könnte später kommen, abhängig von meiner verfügbaren Zeit und anderen Faktoren. 😅 🎉 + +## Modelle für maschinelles Lernen mit spaCy und FastAPI + +GitHub: https://github.com/microsoft/cookiecutter-spacy-fastapi + +### Modelle für maschinelles Lernen mit spaCy und FastAPI – Funktionen + +* **spaCy** NER-Modellintegration. +* **Azure Cognitive Search**-Anforderungsformat integriert. +* **Produktionsbereit** Python-Webserver, verwendet Uvicorn und Gunicorn. +* **Azure DevOps** Kubernetes (AKS) CI/CD-Deployment integriert. +* **Mehrsprachig** Wählen Sie bei der Projekteinrichtung ganz einfach eine der integrierten Sprachen von spaCy aus. +* **Einfach erweiterbar** auf andere Modellframeworks (Pytorch, Tensorflow), nicht nur auf SpaCy. diff --git a/docs/de/docs/python-types.md b/docs/de/docs/python-types.md new file mode 100644 index 000000000..81d43bc5b --- /dev/null +++ b/docs/de/docs/python-types.md @@ -0,0 +1,574 @@ +# Einführung in Python-Typen + +Python hat Unterstützung für optionale „Typhinweise“ (Englisch: „Type Hints“). Auch „Typ Annotationen“ genannt. + +Diese **„Typhinweise“** oder -Annotationen sind eine spezielle Syntax, die es erlaubt, den Typ einer Variablen zu deklarieren. + +Durch das Deklarieren von Typen für Ihre Variablen können Editoren und Tools bessere Unterstützung bieten. + +Dies ist lediglich eine **schnelle Anleitung / Auffrischung** über Pythons Typhinweise. Sie deckt nur das Minimum ab, das nötig ist, um diese mit **FastAPI** zu verwenden ... was tatsächlich sehr wenig ist. + +**FastAPI** basiert vollständig auf diesen Typhinweisen, sie geben der Anwendung viele Vorteile und Möglichkeiten. + +Aber selbst wenn Sie **FastAPI** nie verwenden, wird es für Sie nützlich sein, ein wenig darüber zu lernen. + +/// note | Hinweis + +Wenn Sie ein Python-Experte sind und bereits alles über Typhinweise wissen, überspringen Sie dieses Kapitel und fahren Sie mit dem nächsten fort. + +/// + +## Motivation + +Fangen wir mit einem einfachen Beispiel an: + +{* ../../docs_src/python_types/tutorial001.py *} + +Dieses Programm gibt aus: + +``` +John Doe +``` + +Die Funktion macht Folgendes: + +* Nimmt einen `first_name` und `last_name`. +* Schreibt den ersten Buchstaben eines jeden Wortes groß, mithilfe von `title()`. +* Verkettet sie mit einem Leerzeichen in der Mitte. + +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + +### Bearbeiten Sie es + +Es ist ein sehr einfaches Programm. + +Aber nun stellen Sie sich vor, Sie würden es selbst schreiben. + +Irgendwann sind die Funktions-Parameter fertig, Sie starten mit der Definition des Körpers ... + +Aber dann müssen Sie „diese Methode aufrufen, die den ersten Buchstaben in Großbuchstaben umwandelt“. + +War es `upper`? War es `uppercase`? `first_uppercase`? `capitalize`? + +Dann versuchen Sie es mit dem langjährigen Freund des Programmierers, der Editor-Autovervollständigung. + +Sie geben den ersten Parameter der Funktion ein, `first_name`, dann einen Punkt (`.`) und drücken `Strg+Leertaste`, um die Vervollständigung auszulösen. + +Aber leider erhalten Sie nichts Nützliches: + + + +### Typen hinzufügen + +Lassen Sie uns eine einzelne Zeile aus der vorherigen Version ändern. + +Wir ändern den folgenden Teil, die Parameter der Funktion, von: + +```Python + first_name, last_name +``` + +zu: + +```Python + first_name: str, last_name: str +``` + +Das war's. + +Das sind die „Typhinweise“: + +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + +Das ist nicht das gleiche wie das Deklarieren von Defaultwerten, wie es hier der Fall ist: + +```Python + first_name="john", last_name="doe" +``` + +Das ist eine andere Sache. + +Wir verwenden Doppelpunkte (`:`), nicht Gleichheitszeichen (`=`). + +Und das Hinzufügen von Typhinweisen ändert normalerweise nichts an dem, was ohne sie passieren würde. + +Aber jetzt stellen Sie sich vor, Sie sind wieder mitten in der Erstellung dieser Funktion, aber mit Typhinweisen. + +An derselben Stelle versuchen Sie, die Autovervollständigung mit „Strg+Leertaste“ auszulösen, und Sie sehen: + + + +Hier können Sie durch die Optionen blättern, bis Sie diejenige finden, bei der es „Klick“ macht: + + + +## Mehr Motivation + +Sehen Sie sich diese Funktion an, sie hat bereits Typhinweise: + +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + +Da der Editor die Typen der Variablen kennt, erhalten Sie nicht nur Code-Vervollständigung, sondern auch eine Fehlerprüfung: + + + +Jetzt, da Sie wissen, dass Sie das reparieren müssen, konvertieren Sie `age` mittels `str(age)` in einen String: + +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + +## Deklarieren von Typen + +Sie haben gerade den Haupt-Einsatzort für die Deklaration von Typhinweisen gesehen. Als Funktionsparameter. + +Das ist auch meistens, wie sie in **FastAPI** verwendet werden. + +### Einfache Typen + +Sie können alle Standard-Python-Typen deklarieren, nicht nur `str`. + +Zum Beispiel diese: + +* `int` +* `float` +* `bool` +* `bytes` + +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + +### Generische Typen mit Typ-Parametern + +Es gibt Datenstrukturen, die andere Werte enthalten können, wie etwa `dict`, `list`, `set` und `tuple`. Die inneren Werte können auch ihren eigenen Typ haben. + +Diese Typen mit inneren Typen werden „**generische**“ Typen genannt. Es ist möglich, sie mit ihren inneren Typen zu deklarieren. + +Um diese Typen und die inneren Typen zu deklarieren, können Sie Pythons Standardmodul `typing` verwenden. Es existiert speziell für die Unterstützung dieser Typhinweise. + +#### Neuere Python-Versionen + +Die Syntax, welche `typing` verwendet, ist **kompatibel** mit allen Versionen, von Python 3.6 aufwärts zu den neuesten, inklusive Python 3.9, Python 3.10, usw. + +Mit der Weiterentwicklung von Python kommen **neuere Versionen** heraus, mit verbesserter Unterstützung für Typannotationen, und in vielen Fällen müssen Sie gar nicht mehr das `typing`-Modul importieren, um Typannotationen zu schreiben. + +Wenn Sie eine neuere Python-Version für Ihr Projekt wählen können, werden Sie aus dieser zusätzlichen Vereinfachung Nutzen ziehen können. + +In der gesamten Dokumentation gibt es Beispiele, welche kompatibel mit unterschiedlichen Python-Versionen sind (wenn es Unterschiede gibt). + +Zum Beispiel bedeutet „**Python 3.6+**“, dass das Beispiel kompatibel mit Python 3.6 oder höher ist (inklusive 3.7, 3.8, 3.9, 3.10, usw.). Und „**Python 3.9+**“ bedeutet, es ist kompatibel mit Python 3.9 oder höher (inklusive 3.10, usw.). + +Wenn Sie über die **neueste Version von Python** verfügen, verwenden Sie die Beispiele für die neueste Version, diese werden die **beste und einfachste Syntax** haben, zum Beispiel, „**Python 3.10+**“. + +#### Liste + +Definieren wir zum Beispiel eine Variable, die eine `list` von `str` – eine Liste von Strings – sein soll. + +//// tab | Python 3.9+ + +Deklarieren Sie die Variable mit der gleichen Doppelpunkt-Syntax (`:`). + +Als Typ nehmen Sie `list`. + +Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckigen Klammern umfasst: + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial006_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +Von `typing` importieren Sie `List` (mit Großbuchstaben `L`): + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial006.py!} +``` + +Deklarieren Sie die Variable mit der gleichen Doppelpunkt-Syntax (`:`). + +Als Typ nehmen Sie das `List`, das Sie von `typing` importiert haben. + +Da die Liste ein Typ ist, welcher innere Typen enthält, werden diese von eckigen Klammern umfasst: + +```Python hl_lines="4" +{!> ../../docs_src/python_types/tutorial006.py!} +``` + +//// + +/// tip | Tipp + +Die inneren Typen in den eckigen Klammern werden als „Typ-Parameter“ bezeichnet. + +In diesem Fall ist `str` der Typ-Parameter, der an `List` übergeben wird (oder `list` in Python 3.9 und darüber). + +/// + +Das bedeutet: Die Variable `items` ist eine Liste – `list` – und jedes der Elemente in dieser Liste ist ein String – `str`. + +/// tip | Tipp + +Wenn Sie Python 3.9 oder höher verwenden, müssen Sie `List` nicht von `typing` importieren, Sie können stattdessen den regulären `list`-Typ verwenden. + +/// + +Auf diese Weise kann Ihr Editor Sie auch bei der Bearbeitung von Einträgen aus der Liste unterstützen: + + + +Ohne Typen ist das fast unmöglich zu erreichen. + +Beachten Sie, dass die Variable `item` eines der Elemente in der Liste `items` ist. + +Und trotzdem weiß der Editor, dass es sich um ein `str` handelt, und bietet entsprechende Unterstützung. + +#### Tupel und Menge + +Das Gleiche gilt für die Deklaration eines Tupels – `tuple` – und einer Menge – `set`: + +//// tab | Python 3.9+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial007_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial007.py!} +``` + +//// + +Das bedeutet: + +* Die Variable `items_t` ist ein `tuple` mit 3 Elementen, einem `int`, einem weiteren `int` und einem `str`. +* Die Variable `items_s` ist ein `set`, und jedes seiner Elemente ist vom Typ `bytes`. + +#### Dict + +Um ein `dict` zu definieren, übergeben Sie zwei Typ-Parameter, getrennt durch Kommas. + +Der erste Typ-Parameter ist für die Schlüssel des `dict`. + +Der zweite Typ-Parameter ist für die Werte des `dict`: + +//// tab | Python 3.9+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial008_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial008.py!} +``` + +//// + +Das bedeutet: + +* Die Variable `prices` ist ein `dict`: + * Die Schlüssel dieses `dict` sind vom Typ `str` (z. B. die Namen der einzelnen Artikel). + * Die Werte dieses `dict` sind vom Typ `float` (z. B. der Preis jedes Artikels). + +#### Union + +Sie können deklarieren, dass eine Variable einer von **verschiedenen Typen** sein kann, zum Beispiel ein `int` oder ein `str`. + +In Python 3.6 und höher (inklusive Python 3.10) können Sie den `Union`-Typ von `typing` verwenden und die möglichen Typen innerhalb der eckigen Klammern auflisten. + +In Python 3.10 gibt es zusätzlich eine **neue Syntax**, die es erlaubt, die möglichen Typen getrennt von einem vertikalen Balken (`|`) aufzulisten. + +//// tab | Python 3.10+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial008b_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial008b.py!} +``` + +//// + +In beiden Fällen bedeutet das, dass `item` ein `int` oder ein `str` sein kann. + +#### Vielleicht `None` + +Sie können deklarieren, dass ein Wert ein `str`, aber vielleicht auch `None` sein kann. + +In Python 3.6 und darüber (inklusive Python 3.10) können Sie das deklarieren, indem Sie `Optional` vom `typing` Modul importieren und verwenden. + +{* ../../docs_src/python_types/tutorial009.py hl[1,4] *} + +Wenn Sie `Optional[str]` anstelle von nur `str` verwenden, wird Ihr Editor Ihnen dabei helfen, Fehler zu erkennen, bei denen Sie annehmen könnten, dass ein Wert immer eine String (`str`) ist, obwohl er auch `None` sein könnte. + +`Optional[Something]` ist tatsächlich eine Abkürzung für `Union[Something, None]`, diese beiden sind äquivalent. + +Das bedeutet auch, dass Sie in Python 3.10 `Something | None` verwenden können: + +//// tab | Python 3.10+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial009_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial009.py!} +``` + +//// + +//// tab | Python 3.8+ Alternative + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial009b.py!} +``` + +//// + +#### `Union` oder `Optional` verwenden? + +Wenn Sie eine Python-Version unterhalb 3.10 verwenden, hier ist mein sehr **subjektiver** Standpunkt dazu: + +* 🚨 Vermeiden Sie `Optional[SomeType]` +* Stattdessen ✨ **verwenden Sie `Union[SomeType, None]`** ✨. + +Beide sind äquivalent und im Hintergrund dasselbe, aber ich empfehle `Union` statt `Optional`, weil das Wort „**optional**“ impliziert, dass dieser Wert, zum Beispiel als Funktionsparameter, optional ist. Tatsächlich bedeutet es aber nur „Der Wert kann `None` sein“, selbst wenn der Wert nicht optional ist und benötigt wird. + +Ich denke, `Union[SomeType, None]` ist expliziter bezüglich seiner Bedeutung. + +Es geht nur um Wörter und Namen. Aber diese Worte können beeinflussen, wie Sie und Ihre Teamkollegen über den Code denken. + +Nehmen wir zum Beispiel diese Funktion: + +{* ../../docs_src/python_types/tutorial009c.py hl[1,4] *} + +Der Parameter `name` ist definiert als `Optional[str]`, aber er ist **nicht optional**, Sie können die Funktion nicht ohne diesen Parameter aufrufen: + +```Python +say_hi() # Oh, nein, das löst einen Fehler aus! 😱 +``` + +Der `name` Parameter wird **immer noch benötigt** (nicht *optional*), weil er keinen Default-Wert hat. `name` akzeptiert aber dennoch `None` als Wert: + +```Python +say_hi(name=None) # Das funktioniert, None is gültig 🎉 +``` + +Die gute Nachricht ist, dass Sie sich darüber keine Sorgen mehr machen müssen, wenn Sie Python 3.10 verwenden, da Sie einfach `|` verwenden können, um Vereinigungen von Typen zu definieren: + +{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *} + +Und dann müssen Sie sich nicht mehr um Namen wie `Optional` und `Union` kümmern. 😎 + +#### Generische Typen + +Diese Typen, die Typ-Parameter in eckigen Klammern akzeptieren, werden **generische Typen** oder **Generics** genannt. + +//// tab | Python 3.10+ + +Sie können die eingebauten Typen als Generics verwenden (mit eckigen Klammern und Typen darin): + +* `list` +* `tuple` +* `set` +* `dict` + +Verwenden Sie für den Rest, wie unter Python 3.8, das `typing`-Modul: + +* `Union` +* `Optional` (so wie unter Python 3.8) +* ... und andere. + +In Python 3.10 können Sie als Alternative zu den Generics `Union` und `Optional` den vertikalen Balken (`|`) verwenden, um Vereinigungen von Typen zu deklarieren, das ist besser und einfacher. + +//// + +//// tab | Python 3.9+ + +Sie können die eingebauten Typen als Generics verwenden (mit eckigen Klammern und Typen darin): + +* `list` +* `tuple` +* `set` +* `dict` + +Verwenden Sie für den Rest, wie unter Python 3.8, das `typing`-Modul: + +* `Union` +* `Optional` +* ... und andere. + +//// + +//// tab | Python 3.8+ + +* `List` +* `Tuple` +* `Set` +* `Dict` +* `Union` +* `Optional` +* ... und andere. + +//// + +### Klassen als Typen + +Sie können auch eine Klasse als Typ einer Variablen deklarieren. + +Nehmen wir an, Sie haben eine Klasse `Person`, mit einem Namen: + +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + +Dann können Sie eine Variable vom Typ `Person` deklarieren: + +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + +Und wiederum bekommen Sie die volle Editor-Unterstützung: + + + +Beachten Sie, das bedeutet: „`one_person` ist eine **Instanz** der Klasse `Person`“. + +Es bedeutet nicht: „`one_person` ist die **Klasse** genannt `Person`“. + +## Pydantic Modelle + +Pydantic ist eine Python-Bibliothek für die Validierung von Daten. + +Sie deklarieren die „Form“ der Daten als Klassen mit Attributen. + +Und jedes Attribut hat einen Typ. + +Dann erzeugen Sie eine Instanz dieser Klasse mit einigen Werten, und Pydantic validiert die Werte, konvertiert sie in den passenden Typ (falls notwendig) und gibt Ihnen ein Objekt mit allen Daten. + +Und Sie erhalten volle Editor-Unterstützung für dieses Objekt. + +Ein Beispiel aus der offiziellen Pydantic Dokumentation: + +//// tab | Python 3.10+ + +```Python +{!> ../../docs_src/python_types/tutorial011_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python +{!> ../../docs_src/python_types/tutorial011_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python +{!> ../../docs_src/python_types/tutorial011.py!} +``` + +//// + +/// info + +Um mehr über Pydantic zu erfahren, schauen Sie sich dessen Dokumentation an. + +/// + +**FastAPI** basiert vollständig auf Pydantic. + +Viel mehr von all dem werden Sie in praktischer Anwendung im [Tutorial - Benutzerhandbuch](tutorial/index.md){.internal-link target=_blank} sehen. + +/// tip | Tipp + +Pydantic verhält sich speziell, wenn Sie `Optional` oder `Union[Etwas, None]` ohne einen Default-Wert verwenden. Sie können darüber in der Pydantic Dokumentation unter Required fields mehr erfahren. + +/// + +## Typhinweise mit Metadaten-Annotationen + +Python bietet auch die Möglichkeit, **zusätzliche Metadaten** in Typhinweisen unterzubringen, mittels `Annotated`. + +//// tab | Python 3.9+ + +In Python 3.9 ist `Annotated` ein Teil der Standardbibliothek, Sie können es von `typing` importieren. + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial013_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +In Versionen niedriger als Python 3.9 importieren Sie `Annotated` von `typing_extensions`. + +Es wird bereits mit **FastAPI** installiert sein. + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial013.py!} +``` + +//// + +Python selbst macht nichts mit `Annotated`. Für Editoren und andere Tools ist der Typ immer noch `str`. + +Aber Sie können `Annotated` nutzen, um **FastAPI** mit Metadaten zu versorgen, die ihm sagen, wie sich ihre Anwendung verhalten soll. + +Wichtig ist, dass **der erste *Typ-Parameter***, den Sie `Annotated` übergeben, der **tatsächliche Typ** ist. Der Rest sind Metadaten für andere Tools. + +Im Moment müssen Sie nur wissen, dass `Annotated` existiert, und dass es Standard-Python ist. 😎 + +Später werden Sie sehen, wie **mächtig** es sein kann. + +/// tip | Tipp + +Der Umstand, dass es **Standard-Python** ist, bedeutet, dass Sie immer noch die **bestmögliche Entwickler-Erfahrung** in ihrem Editor haben, sowie mit den Tools, die Sie nutzen, um ihren Code zu analysieren, zu refaktorisieren, usw. ✨ + +Und ebenfalls, dass Ihr Code sehr kompatibel mit vielen anderen Python-Tools und -Bibliotheken sein wird. 🚀 + +/// + +## Typhinweise in **FastAPI** + +**FastAPI** macht sich diese Typhinweise zunutze, um mehrere Dinge zu tun. + +Mit **FastAPI** deklarieren Sie Parameter mit Typhinweisen, und Sie erhalten: + +* **Editorunterstützung**. +* **Typ-Prüfungen**. + +... und **FastAPI** verwendet dieselben Deklarationen, um: + +* **Anforderungen** zu definieren: aus Anfrage-Pfadparametern, Abfrageparametern, Header-Feldern, Bodys, Abhängigkeiten, usw. +* **Daten umzuwandeln**: aus der Anfrage in den erforderlichen Typ. +* **Daten zu validieren**: aus jeder Anfrage: + * **Automatische Fehler** generieren, die an den Client zurückgegeben werden, wenn die Daten ungültig sind. +* Die API mit OpenAPI zu **dokumentieren**: + * Die dann von den Benutzeroberflächen der automatisch generierten interaktiven Dokumentation verwendet wird. + +Das mag alles abstrakt klingen. Machen Sie sich keine Sorgen. Sie werden all das in Aktion sehen im [Tutorial - Benutzerhandbuch](tutorial/index.md){.internal-link target=_blank}. + +Das Wichtigste ist, dass **FastAPI** durch die Verwendung von Standard-Python-Typen an einer einzigen Stelle (anstatt weitere Klassen, Dekoratoren usw. hinzuzufügen) einen Großteil der Arbeit für Sie erledigt. + +/// info + +Wenn Sie bereits das ganze Tutorial durchgearbeitet haben und mehr über Typen erfahren wollen, dann ist eine gute Ressource der „Cheat Sheet“ von `mypy`. + +/// diff --git a/docs/de/docs/resources/index.md b/docs/de/docs/resources/index.md new file mode 100644 index 000000000..abf270d9f --- /dev/null +++ b/docs/de/docs/resources/index.md @@ -0,0 +1,3 @@ +# Ressourcen + +Zusätzliche Ressourcen, externe Links, Artikel und mehr. ✈️ diff --git a/docs/de/docs/tutorial/background-tasks.md b/docs/de/docs/tutorial/background-tasks.md index a7bfd55a7..05779e12c 100644 --- a/docs/de/docs/tutorial/background-tasks.md +++ b/docs/de/docs/tutorial/background-tasks.md @@ -15,9 +15,7 @@ Hierzu zählen beispielsweise: Importieren Sie zunächst `BackgroundTasks` und definieren Sie einen Parameter in Ihrer *Pfadoperation-Funktion* mit der Typdeklaration `BackgroundTasks`: -```Python hl_lines="1 13" -{!../../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *} **FastAPI** erstellt für Sie das Objekt vom Typ `BackgroundTasks` und übergibt es als diesen Parameter. @@ -33,17 +31,13 @@ In diesem Fall schreibt die Taskfunktion in eine Datei (den Versand einer E-Mail Und da der Schreibvorgang nicht `async` und `await` verwendet, definieren wir die Funktion mit normalem `def`: -```Python hl_lines="6-9" -{!../../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *} ## Den Hintergrundtask hinzufügen Übergeben Sie innerhalb Ihrer *Pfadoperation-Funktion* Ihre Taskfunktion mit der Methode `.add_task()` an das *Hintergrundtasks*-Objekt: -```Python hl_lines="14" -{!../../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[14] *} `.add_task()` erhält als Argumente: @@ -57,41 +51,7 @@ Die Verwendung von `BackgroundTasks` funktioniert auch mit dem ../../../docs_src/background_tasks/tutorial002_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="14 16 23 26" - {!> ../../../docs_src/background_tasks/tutorial002_an.py!} - ``` - -=== "Python 3.10+ nicht annotiert" - - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. - - ```Python hl_lines="11 13 20 23" - {!> ../../../docs_src/background_tasks/tutorial002_py310.py!} - ``` - -=== "Python 3.8+ nicht annotiert" - - !!! tip "Tipp" - Bevorzugen Sie die `Annotated`-Version, falls möglich. - - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002.py!} - ``` +{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13,15,22,25] *} In obigem Beispiel werden die Nachrichten, *nachdem* die Response gesendet wurde, in die Datei `log.txt` geschrieben. @@ -117,8 +77,6 @@ Wenn Sie umfangreiche Hintergrundberechnungen durchführen müssen und diese nic Sie erfordern in der Regel komplexere Konfigurationen und einen Nachrichten-/Job-Queue-Manager wie RabbitMQ oder Redis, ermöglichen Ihnen jedoch die Ausführung von Hintergrundtasks in mehreren Prozessen und insbesondere auf mehreren Servern. -Um ein Beispiel zu sehen, sehen Sie sich die [Projektgeneratoren](../project-generation.md){.internal-link target=_blank} an. Sie alle enthalten Celery, bereits konfiguriert. - Wenn Sie jedoch über dieselbe **FastAPI**-Anwendung auf Variablen und Objekte zugreifen oder kleine Hintergrundtasks ausführen müssen (z. B. das Senden einer E-Mail-Benachrichtigung), können Sie einfach `BackgroundTasks` verwenden. ## Zusammenfassung diff --git a/docs/de/docs/tutorial/bigger-applications.md b/docs/de/docs/tutorial/bigger-applications.md new file mode 100644 index 000000000..59e91bdcc --- /dev/null +++ b/docs/de/docs/tutorial/bigger-applications.md @@ -0,0 +1,557 @@ +# Größere Anwendungen – mehrere Dateien + +Wenn Sie eine Anwendung oder eine Web-API erstellen, ist es selten der Fall, dass Sie alles in einer einzigen Datei unterbringen können. + +**FastAPI** bietet ein praktisches Werkzeug zur Strukturierung Ihrer Anwendung bei gleichzeitiger Wahrung der Flexibilität. + +/// info + +Wenn Sie von Flask kommen, wäre dies das Äquivalent zu Flasks Blueprints. + +/// + +## Eine Beispiel-Dateistruktur + +Nehmen wir an, Sie haben eine Dateistruktur wie diese: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   ├── dependencies.py +│   └── routers +│   │ ├── __init__.py +│   │ ├── items.py +│   │ └── users.py +│   └── internal +│   ├── __init__.py +│   └── admin.py +``` + +/// tip | Tipp + +Es gibt mehrere `__init__.py`-Dateien: eine in jedem Verzeichnis oder Unterverzeichnis. + +Das ermöglicht den Import von Code aus einer Datei in eine andere. + +In `app/main.py` könnten Sie beispielsweise eine Zeile wie diese haben: + +``` +from app.routers import items +``` + +/// + +* Das Verzeichnis `app` enthält alles. Und es hat eine leere Datei `app/__init__.py`, es handelt sich also um ein „Python-Package“ (eine Sammlung von „Python-Modulen“): `app`. +* Es enthält eine Datei `app/main.py`. Da sie sich in einem Python-Package (einem Verzeichnis mit einer Datei `__init__.py`) befindet, ist sie ein „Modul“ dieses Packages: `app.main`. +* Es gibt auch eine Datei `app/dependencies.py`, genau wie `app/main.py` ist sie ein „Modul“: `app.dependencies`. +* Es gibt ein Unterverzeichnis `app/routers/` mit einer weiteren Datei `__init__.py`, es handelt sich also um ein „Python-Subpackage“: `app.routers`. +* Die Datei `app/routers/items.py` befindet sich in einem Package, `app/routers/`, also ist sie ein Submodul: `app.routers.items`. +* Das Gleiche gilt für `app/routers/users.py`, es ist ein weiteres Submodul: `app.routers.users`. +* Es gibt auch ein Unterverzeichnis `app/internal/` mit einer weiteren Datei `__init__.py`, es handelt sich also um ein weiteres „Python-Subpackage“: `app.internal`. +* Und die Datei `app/internal/admin.py` ist ein weiteres Submodul: `app.internal.admin`. + + + +Die gleiche Dateistruktur mit Kommentaren: + +``` +. +├── app # „app“ ist ein Python-Package +│   ├── __init__.py # diese Datei macht „app“ zu einem „Python-Package“ +│   ├── main.py # „main“-Modul, z. B. import app.main +│   ├── dependencies.py # „dependencies“-Modul, z. B. import app.dependencies +│   └── routers # „routers“ ist ein „Python-Subpackage“ +│   │ ├── __init__.py # macht „routers“ zu einem „Python-Subpackage“ +│   │ ├── items.py # „items“-Submodul, z. B. import app.routers.items +│   │ └── users.py # „users“-Submodul, z. B. import app.routers.users +│   └── internal # „internal“ ist ein „Python-Subpackage“ +│   ├── __init__.py # macht „internal“ zu einem „Python-Subpackage“ +│   └── admin.py # „admin“-Submodul, z. B. import app.internal.admin +``` + +## `APIRouter` + +Nehmen wir an, die Datei, die nur für die Verwaltung von Benutzern zuständig ist, ist das Submodul unter `/app/routers/users.py`. + +Sie möchten die *Pfadoperationen* für Ihre Benutzer vom Rest des Codes trennen, um ihn organisiert zu halten. + +Aber es ist immer noch Teil derselben **FastAPI**-Anwendung/Web-API (es ist Teil desselben „Python-Packages“). + +Sie können die *Pfadoperationen* für dieses Modul mit `APIRouter` erstellen. + +### `APIRouter` importieren + +Sie importieren ihn und erstellen eine „Instanz“ auf die gleiche Weise wie mit der Klasse `FastAPI`: + +```Python hl_lines="1 3" title="app/routers/users.py" +{!../../docs_src/bigger_applications/app/routers/users.py!} +``` + +### *Pfadoperationen* mit `APIRouter` + +Und dann verwenden Sie ihn, um Ihre *Pfadoperationen* zu deklarieren. + +Verwenden Sie ihn auf die gleiche Weise wie die Klasse `FastAPI`: + +```Python hl_lines="6 11 16" title="app/routers/users.py" +{!../../docs_src/bigger_applications/app/routers/users.py!} +``` + +Sie können sich `APIRouter` als eine „Mini-`FastAPI`“-Klasse vorstellen. + +Alle die gleichen Optionen werden unterstützt. + +Alle die gleichen `parameters`, `responses`, `dependencies`, `tags`, usw. + +/// tip | Tipp + +In diesem Beispiel heißt die Variable `router`, aber Sie können ihr einen beliebigen Namen geben. + +/// + +Wir werden diesen `APIRouter` in die Hauptanwendung `FastAPI` einbinden, aber zuerst kümmern wir uns um die Abhängigkeiten und einen anderen `APIRouter`. + +## Abhängigkeiten + +Wir sehen, dass wir einige Abhängigkeiten benötigen, die an mehreren Stellen der Anwendung verwendet werden. + +Also fügen wir sie in ihr eigenes `dependencies`-Modul (`app/dependencies.py`) ein. + +Wir werden nun eine einfache Abhängigkeit verwenden, um einen benutzerdefinierten `X-Token`-Header zu lesen: + +//// tab | Python 3.9+ + +```Python hl_lines="3 6-8" title="app/dependencies.py" +{!> ../../docs_src/bigger_applications/app_an_py39/dependencies.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 5-7" title="app/dependencies.py" +{!> ../../docs_src/bigger_applications/app_an/dependencies.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | Tipp + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="1 4-6" title="app/dependencies.py" +{!> ../../docs_src/bigger_applications/app/dependencies.py!} +``` + +//// + +/// tip | Tipp + +Um dieses Beispiel zu vereinfachen, verwenden wir einen erfundenen Header. + +Aber in der Praxis werden Sie mit den integrierten [Sicherheits-Werkzeugen](security/index.md){.internal-link target=_blank} bessere Ergebnisse erzielen. + +/// + +## Ein weiteres Modul mit `APIRouter`. + +Nehmen wir an, Sie haben im Modul unter `app/routers/items.py` auch die Endpunkte, die für die Verarbeitung von Artikeln („Items“) aus Ihrer Anwendung vorgesehen sind. + +Sie haben *Pfadoperationen* für: + +* `/items/` +* `/items/{item_id}` + +Es ist alles die gleiche Struktur wie bei `app/routers/users.py`. + +Aber wir wollen schlauer sein und den Code etwas vereinfachen. + +Wir wissen, dass alle *Pfadoperationen* in diesem Modul folgendes haben: + +* Pfad-`prefix`: `/items`. +* `tags`: (nur ein Tag: `items`). +* Zusätzliche `responses`. +* `dependencies`: Sie alle benötigen die von uns erstellte `X-Token`-Abhängigkeit. + +Anstatt also alles zu jeder *Pfadoperation* hinzuzufügen, können wir es dem `APIRouter` hinzufügen. + +```Python hl_lines="5-10 16 21" title="app/routers/items.py" +{!../../docs_src/bigger_applications/app/routers/items.py!} +``` + +Da der Pfad jeder *Pfadoperation* mit `/` beginnen muss, wie in: + +```Python hl_lines="1" +@router.get("/{item_id}") +async def read_item(item_id: str): + ... +``` + +... darf das Präfix kein abschließendes `/` enthalten. + +Das Präfix lautet in diesem Fall also `/items`. + +Wir können auch eine Liste von `tags` und zusätzliche `responses` hinzufügen, die auf alle in diesem Router enthaltenen *Pfadoperationen* angewendet werden. + +Und wir können eine Liste von `dependencies` hinzufügen, die allen *Pfadoperationen* im Router hinzugefügt und für jeden an sie gerichteten Request ausgeführt/aufgelöst werden. + +/// tip | Tipp + +Beachten Sie, dass ähnlich wie bei [Abhängigkeiten in *Pfadoperation-Dekoratoren*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank} kein Wert an Ihre *Pfadoperation-Funktion* übergeben wird. + +/// + +Das Endergebnis ist, dass die Pfade für diese Artikel jetzt wie folgt lauten: + +* `/items/` +* `/items/{item_id}` + +... wie wir es beabsichtigt hatten. + +* Sie werden mit einer Liste von Tags gekennzeichnet, die einen einzelnen String `"items"` enthält. + * Diese „Tags“ sind besonders nützlich für die automatischen interaktiven Dokumentationssysteme (unter Verwendung von OpenAPI). +* Alle enthalten die vordefinierten `responses`. +* Für alle diese *Pfadoperationen* wird die Liste der `dependencies` ausgewertet/ausgeführt, bevor sie selbst ausgeführt werden. + * Wenn Sie außerdem Abhängigkeiten in einer bestimmten *Pfadoperation* deklarieren, **werden diese ebenfalls ausgeführt**. + * Zuerst werden die Router-Abhängigkeiten ausgeführt, dann die [`dependencies` im Dekorator](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank} und dann die normalen Parameterabhängigkeiten. + * Sie können auch [`Security`-Abhängigkeiten mit `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank} hinzufügen. + +/// tip | Tipp + +`dependencies` im `APIRouter` können beispielsweise verwendet werden, um eine Authentifizierung für eine ganze Gruppe von *Pfadoperationen* zu erfordern. Selbst wenn die Abhängigkeiten nicht jeder einzeln hinzugefügt werden. + +/// + +/// check + +Die Parameter `prefix`, `tags`, `responses` und `dependencies` sind (wie in vielen anderen Fällen) nur ein Feature von **FastAPI**, um Ihnen dabei zu helfen, Codeverdoppelung zu vermeiden. + +/// + +### Die Abhängigkeiten importieren + +Der folgende Code befindet sich im Modul `app.routers.items`, also in der Datei `app/routers/items.py`. + +Und wir müssen die Abhängigkeitsfunktion aus dem Modul `app.dependencies` importieren, also aus der Datei `app/dependencies.py`. + +Daher verwenden wir einen relativen Import mit `..` für die Abhängigkeiten: + +```Python hl_lines="3" title="app/routers/items.py" +{!../../docs_src/bigger_applications/app/routers/items.py!} +``` + +#### Wie relative Importe funktionieren + +/// tip | Tipp + +Wenn Sie genau wissen, wie Importe funktionieren, fahren Sie mit dem nächsten Abschnitt unten fort. + +/// + +Ein einzelner Punkt `.`, wie in: + +```Python +from .dependencies import get_token_header +``` + +würde bedeuten: + +* Beginnend im selben Package, in dem sich dieses Modul (die Datei `app/routers/items.py`) befindet (das Verzeichnis `app/routers/`) ... +* finde das Modul `dependencies` (eine imaginäre Datei unter `app/routers/dependencies.py`) ... +* und importiere daraus die Funktion `get_token_header`. + +Aber diese Datei existiert nicht, unsere Abhängigkeiten befinden sich in einer Datei unter `app/dependencies.py`. + +Erinnern Sie sich, wie unsere Anwendungs-/Dateistruktur aussieht: + + + +--- + +Die beiden Punkte `..`, wie in: + +```Python +from ..dependencies import get_token_header +``` + +bedeuten: + +* Beginnend im selben Package, in dem sich dieses Modul (die Datei `app/routers/items.py`) befindet (das Verzeichnis `app/routers/`) ... +* gehe zum übergeordneten Package (das Verzeichnis `app/`) ... +* und finde dort das Modul `dependencies` (die Datei unter `app/dependencies.py`) ... +* und importiere daraus die Funktion `get_token_header`. + +Das funktioniert korrekt! 🎉 + +--- + +Das Gleiche gilt, wenn wir drei Punkte `...` verwendet hätten, wie in: + +```Python +from ...dependencies import get_token_header +``` + +Das würde bedeuten: + +* Beginnend im selben Package, in dem sich dieses Modul (die Datei `app/routers/items.py`) befindet (das Verzeichnis `app/routers/`) ... +* gehe zum übergeordneten Package (das Verzeichnis `app/`) ... +* gehe dann zum übergeordneten Package dieses Packages (es gibt kein übergeordnetes Package, `app` ist die oberste Ebene 😱) ... +* und finde dort das Modul `dependencies` (die Datei unter `app/dependencies.py`) ... +* und importiere daraus die Funktion `get_token_header`. + +Das würde sich auf ein Paket oberhalb von `app/` beziehen, mit seiner eigenen Datei `__init__.py`, usw. Aber das haben wir nicht. Das würde in unserem Beispiel also einen Fehler auslösen. 🚨 + +Aber jetzt wissen Sie, wie es funktioniert, sodass Sie relative Importe in Ihren eigenen Anwendungen verwenden können, egal wie komplex diese sind. 🤓 + +### Einige benutzerdefinierte `tags`, `responses`, und `dependencies` hinzufügen + +Wir fügen weder das Präfix `/items` noch `tags=["items"]` zu jeder *Pfadoperation* hinzu, da wir sie zum `APIRouter` hinzugefügt haben. + +Aber wir können immer noch _mehr_ `tags` hinzufügen, die auf eine bestimmte *Pfadoperation* angewendet werden, sowie einige zusätzliche `responses`, die speziell für diese *Pfadoperation* gelten: + +```Python hl_lines="30-31" title="app/routers/items.py" +{!../../docs_src/bigger_applications/app/routers/items.py!} +``` + +/// tip | Tipp + +Diese letzte Pfadoperation wird eine Kombination von Tags haben: `["items", "custom"]`. + +Und sie wird auch beide Responses in der Dokumentation haben, eine für `404` und eine für `403`. + +/// + +## Das Haupt-`FastAPI`. + +Sehen wir uns nun das Modul unter `app/main.py` an. + +Hier importieren und verwenden Sie die Klasse `FastAPI`. + +Dies ist die Hauptdatei Ihrer Anwendung, die alles zusammen bindet. + +Und da sich der Großteil Ihrer Logik jetzt in seinem eigenen spezifischen Modul befindet, wird die Hauptdatei recht einfach sein. + +### `FastAPI` importieren + +Sie importieren und erstellen wie gewohnt eine `FastAPI`-Klasse. + +Und wir können sogar [globale Abhängigkeiten](dependencies/global-dependencies.md){.internal-link target=_blank} deklarieren, die mit den Abhängigkeiten für jeden `APIRouter` kombiniert werden: + +```Python hl_lines="1 3 7" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +### Den `APIRouter` importieren + +Jetzt importieren wir die anderen Submodule, die `APIRouter` haben: + +```Python hl_lines="4-5" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +Da es sich bei den Dateien `app/routers/users.py` und `app/routers/items.py` um Submodule handelt, die Teil desselben Python-Packages `app` sind, können wir einen einzelnen Punkt `.` verwenden, um sie mit „relativen Imports“ zu importieren. + +### Wie das Importieren funktioniert + +Die Sektion: + +```Python +from .routers import items, users +``` + +bedeutet: + +* Beginnend im selben Package, in dem sich dieses Modul (die Datei `app/main.py`) befindet (das Verzeichnis `app/`) ... +* Suche nach dem Subpackage `routers` (das Verzeichnis unter `app/routers/`) ... +* und importiere daraus die Submodule `items` (die Datei unter `app/routers/items.py`) und `users` (die Datei unter `app/routers/users.py`) ... + +Das Modul `items` verfügt über eine Variable `router` (`items.router`). Das ist dieselbe, die wir in der Datei `app/routers/items.py` erstellt haben, es ist ein `APIRouter`-Objekt. + +Und dann machen wir das gleiche für das Modul `users`. + +Wir könnten sie auch wie folgt importieren: + +```Python +from app.routers import items, users +``` + +/// info + +Die erste Version ist ein „relativer Import“: + +```Python +from .routers import items, users +``` + +Die zweite Version ist ein „absoluter Import“: + +```Python +from app.routers import items, users +``` + +Um mehr über Python-Packages und -Module zu erfahren, lesen Sie die offizielle Python-Dokumentation über Module. + +/// + +### Namenskollisionen vermeiden + +Wir importieren das Submodul `items` direkt, anstatt nur seine Variable `router` zu importieren. + +Das liegt daran, dass wir im Submodul `users` auch eine weitere Variable namens `router` haben. + +Wenn wir eine nach der anderen importiert hätten, etwa: + +```Python +from .routers.items import router +from .routers.users import router +``` + +würde der `router` von `users` den von `items` überschreiben und wir könnten sie nicht gleichzeitig verwenden. + +Um also beide in derselben Datei verwenden zu können, importieren wir die Submodule direkt: + +```Python hl_lines="5" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + + +### Die `APIRouter` für `users` und `items` inkludieren + +Inkludieren wir nun die `router` aus diesen Submodulen `users` und `items`: + +```Python hl_lines="10-11" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +/// info + +`users.router` enthält den `APIRouter` in der Datei `app/routers/users.py`. + +Und `items.router` enthält den `APIRouter` in der Datei `app/routers/items.py`. + +/// + +Mit `app.include_router()` können wir jeden `APIRouter` zur Hauptanwendung `FastAPI` hinzufügen. + +Es wird alle Routen von diesem Router als Teil von dieser inkludieren. + +/// note | Technische Details + +Tatsächlich wird intern eine *Pfadoperation* für jede *Pfadoperation* erstellt, die im `APIRouter` deklariert wurde. + +Hinter den Kulissen wird es also tatsächlich so funktionieren, als ob alles dieselbe einzige Anwendung wäre. + +/// + +/// check + +Bei der Einbindung von Routern müssen Sie sich keine Gedanken über die Performanz machen. + +Dies dauert Mikrosekunden und geschieht nur beim Start. + +Es hat also keinen Einfluss auf die Leistung. ⚡ + +/// + +### Einen `APIRouter` mit benutzerdefinierten `prefix`, `tags`, `responses` und `dependencies` einfügen + +Stellen wir uns nun vor, dass Ihre Organisation Ihnen die Datei `app/internal/admin.py` gegeben hat. + +Sie enthält einen `APIRouter` mit einigen administrativen *Pfadoperationen*, die Ihre Organisation zwischen mehreren Projekten teilt. + +In diesem Beispiel wird es ganz einfach sein. Nehmen wir jedoch an, dass wir, da sie mit anderen Projekten in der Organisation geteilt wird, sie nicht ändern und kein `prefix`, `dependencies`, `tags`, usw. direkt zum `APIRouter` hinzufügen können: + +```Python hl_lines="3" title="app/internal/admin.py" +{!../../docs_src/bigger_applications/app/internal/admin.py!} +``` + +Aber wir möchten immer noch ein benutzerdefiniertes `prefix` festlegen, wenn wir den `APIRouter` einbinden, sodass alle seine *Pfadoperationen* mit `/admin` beginnen, wir möchten es mit den `dependencies` sichern, die wir bereits für dieses Projekt haben, und wir möchten `tags` und `responses` hinzufügen. + +Wir können das alles deklarieren, ohne den ursprünglichen `APIRouter` ändern zu müssen, indem wir diese Parameter an `app.include_router()` übergeben: + +```Python hl_lines="14-17" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +Auf diese Weise bleibt der ursprüngliche `APIRouter` unverändert, sodass wir dieselbe `app/internal/admin.py`-Datei weiterhin mit anderen Projekten in der Organisation teilen können. + +Das Ergebnis ist, dass in unserer Anwendung jede der *Pfadoperationen* aus dem Modul `admin` Folgendes haben wird: + +* Das Präfix `/admin`. +* Den Tag `admin`. +* Die Abhängigkeit `get_token_header`. +* Die Response `418`. 🍵 + +Dies wirkt sich jedoch nur auf diesen `APIRouter` in unserer Anwendung aus, nicht auf anderen Code, der ihn verwendet. + +So könnten beispielsweise andere Projekte denselben `APIRouter` mit einer anderen Authentifizierungsmethode verwenden. + +### Eine *Pfadoperation* hinzufügen + +Wir können *Pfadoperationen* auch direkt zur `FastAPI`-App hinzufügen. + +Hier machen wir es ... nur um zu zeigen, dass wir es können 🤷: + +```Python hl_lines="21-23" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +und es wird korrekt funktionieren, zusammen mit allen anderen *Pfadoperationen*, die mit `app.include_router()` hinzugefügt wurden. + +/// info | Sehr technische Details + +**Hinweis**: Dies ist ein sehr technisches Detail, das Sie wahrscheinlich **einfach überspringen** können. + +--- + +Die `APIRouter` sind nicht „gemountet“, sie sind nicht vom Rest der Anwendung isoliert. + +Das liegt daran, dass wir deren *Pfadoperationen* in das OpenAPI-Schema und die Benutzeroberflächen einbinden möchten. + +Da wir sie nicht einfach isolieren und unabhängig vom Rest „mounten“ können, werden die *Pfadoperationen* „geklont“ (neu erstellt) und nicht direkt einbezogen. + +/// + +## Es in der automatischen API-Dokumentation ansehen + +Führen Sie nun `uvicorn` aus, indem Sie das Modul `app.main` und die Variable `app` verwenden: + +
+ +```console +$ uvicorn app.main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +und öffnen Sie die Dokumentation unter http://127.0.0.1:8000/docs. + +Sie sehen die automatische API-Dokumentation, einschließlich der Pfade aller Submodule, mit den richtigen Pfaden (und Präfixen) und den richtigen Tags: + + + +## Den gleichen Router mehrmals mit unterschiedlichem `prefix` inkludieren + +Sie können `.include_router()` auch mehrmals mit *demselben* Router und unterschiedlichen Präfixen verwenden. + +Dies könnte beispielsweise nützlich sein, um dieselbe API unter verschiedenen Präfixen verfügbar zu machen, z. B. `/api/v1` und `/api/latest`. + +Dies ist eine fortgeschrittene Verwendung, die Sie möglicherweise nicht wirklich benötigen, aber für den Fall, dass Sie sie benötigen, ist sie vorhanden. + +## Einen `APIRouter` in einen anderen einfügen + +Auf die gleiche Weise, wie Sie einen `APIRouter` in eine `FastAPI`-Anwendung einbinden können, können Sie einen `APIRouter` in einen anderen `APIRouter` einbinden, indem Sie Folgendes verwenden: + +```Python +router.include_router(other_router) +``` + +Stellen Sie sicher, dass Sie dies tun, bevor Sie `router` in die `FastAPI`-App einbinden, damit auch die *Pfadoperationen* von `other_router` inkludiert werden. diff --git a/docs/de/docs/tutorial/body-fields.md b/docs/de/docs/tutorial/body-fields.md new file mode 100644 index 000000000..9fddfb1f0 --- /dev/null +++ b/docs/de/docs/tutorial/body-fields.md @@ -0,0 +1,59 @@ +# Body – Felder + +So wie Sie zusätzliche Validation und Metadaten in Parametern der **Pfadoperation-Funktion** mittels `Query`, `Path` und `Body` deklarieren, können Sie auch innerhalb von Pydantic-Modellen zusätzliche Validation und Metadaten deklarieren, mittels Pydantics `Field`. + +## `Field` importieren + +Importieren Sie es zuerst: + +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *} + +/// warning | Achtung + +Beachten Sie, dass `Field` direkt von `pydantic` importiert wird, nicht von `fastapi`, wie die anderen (`Query`, `Path`, `Body`, usw.) + +/// + +## Modellattribute deklarieren + +Dann können Sie `Field` mit Modellattributen deklarieren: + +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *} + +`Field` funktioniert genauso wie `Query`, `Path` und `Body`, es hat die gleichen Parameter, usw. + +/// note | Technische Details + +Tatsächlich erstellen `Query`, `Path` und andere, die sie kennenlernen werden, Instanzen von Unterklassen einer allgemeinen Klasse `Param`, die ihrerseits eine Unterklasse von Pydantics `FieldInfo`-Klasse ist. + +Und Pydantics `Field` gibt ebenfalls eine Instanz von `FieldInfo` zurück. + +`Body` gibt auch Instanzen einer Unterklasse von `FieldInfo` zurück. Und später werden Sie andere sehen, die Unterklassen der `Body`-Klasse sind. + +Denken Sie daran, dass `Query`, `Path` und andere von `fastapi` tatsächlich Funktionen sind, die spezielle Klassen zurückgeben. + +/// + +/// tip | Tipp + +Beachten Sie, dass jedes Modellattribut mit einem Typ, Defaultwert und `Field` die gleiche Struktur hat wie ein Parameter einer Pfadoperation-Funktion, nur mit `Field` statt `Path`, `Query`, `Body`. + +/// + +## Zusätzliche Information hinzufügen + +Sie können zusätzliche Information in `Field`, `Query`, `Body`, usw. deklarieren. Und es wird im generierten JSON-Schema untergebracht. + +Sie werden später mehr darüber lernen, wie man zusätzliche Information unterbringt, wenn Sie lernen, Beispiele zu deklarieren. + +/// warning | Achtung + +Extra-Schlüssel, die `Field` überreicht werden, werden auch im resultierenden OpenAPI-Schema Ihrer Anwendung gelistet. Da diese Schlüssel nicht notwendigerweise Teil der OpenAPI-Spezifikation sind, könnten einige OpenAPI-Tools, wie etwa [der OpenAPI-Validator](https://validator.swagger.io/), nicht mit Ihrem generierten Schema funktionieren. + +/// + +## Zusammenfassung + +Sie können Pydantics `Field` verwenden, um zusätzliche Validierungen und Metadaten für Modellattribute zu deklarieren. + +Sie können auch Extra-Schlüssel verwenden, um zusätzliche JSON-Schema-Metadaten zu überreichen. diff --git a/docs/de/docs/tutorial/body-multiple-params.md b/docs/de/docs/tutorial/body-multiple-params.md new file mode 100644 index 000000000..8a9978d34 --- /dev/null +++ b/docs/de/docs/tutorial/body-multiple-params.md @@ -0,0 +1,171 @@ +# Body – Mehrere Parameter + +Jetzt, da wir gesehen haben, wie `Path` und `Query` verwendet werden, schauen wir uns fortgeschrittenere Verwendungsmöglichkeiten von Requestbody-Deklarationen an. + +## `Path`-, `Query`- und Body-Parameter vermischen + +Zuerst einmal, Sie können `Path`-, `Query`- und Requestbody-Parameter-Deklarationen frei mischen und **FastAPI** wird wissen, was zu tun ist. + +Und Sie können auch Body-Parameter als optional kennzeichnen, indem Sie den Defaultwert auf `None` setzen: + +{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *} + +/// note | Hinweis + +Beachten Sie, dass in diesem Fall das `item`, welches vom Body genommen wird, optional ist. Da es `None` als Defaultwert hat. + +/// + +## Mehrere Body-Parameter + +Im vorherigen Beispiel erwartete die *Pfadoperation* einen JSON-Body mit den Attributen eines `Item`s, etwa: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +Aber Sie können auch mehrere Body-Parameter deklarieren, z. B. `item` und `user`: + +{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *} + +In diesem Fall wird **FastAPI** bemerken, dass es mehr als einen Body-Parameter in der Funktion gibt (zwei Parameter, die Pydantic-Modelle sind). + +Es wird deshalb die Parameternamen als Schlüssel (Feldnamen) im Body verwenden, und erwartet einen Body wie folgt: + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + } +} +``` + +/// note | Hinweis + +Beachten Sie, dass, obwohl `item` wie zuvor deklariert wurde, es nun unter einem Schlüssel `item` im Body erwartet wird. + +/// + +**FastAPI** wird die automatische Konvertierung des Requests übernehmen, sodass der Parameter `item` seinen spezifischen Inhalt bekommt, genau so wie der Parameter `user`. + +Es wird die Validierung dieser zusammengesetzten Daten übernehmen, und sie im OpenAPI-Schema und der automatischen Dokumentation dokumentieren. + +## Einzelne Werte im Body + +So wie `Query` und `Path` für Query- und Pfad-Parameter, hat **FastAPI** auch das Äquivalent `Body`, um Extra-Daten für Body-Parameter zu definieren. + +Zum Beispiel, das vorherige Modell erweiternd, könnten Sie entscheiden, dass Sie einen weiteren Schlüssel `importance` haben möchten, im selben Body, Seite an Seite mit `item` und `user`. + +Wenn Sie diesen Parameter einfach so hinzufügen, wird **FastAPI** annehmen, dass es ein Query-Parameter ist. + +Aber Sie können **FastAPI** instruieren, ihn als weiteren Body-Schlüssel zu erkennen, indem Sie `Body` verwenden: + +{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *} + +In diesem Fall erwartet **FastAPI** einen Body wie: + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + }, + "importance": 5 +} +``` + +Wiederum wird es die Daten konvertieren, validieren, dokumentieren, usw. + +## Mehrere Body-Parameter und Query-Parameter + +Natürlich können Sie auch, wann immer Sie das brauchen, weitere Query-Parameter hinzufügen, zusätzlich zu den Body-Parametern. + +Da einfache Werte standardmäßig als Query-Parameter interpretiert werden, müssen Sie `Query` nicht explizit hinzufügen, Sie können einfach schreiben: + +```Python +q: Union[str, None] = None +``` + +Oder in Python 3.10 und darüber: + +```Python +q: str | None = None +``` + +Zum Beispiel: + +{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[27] *} + +/// info + +`Body` hat die gleichen zusätzlichen Validierungs- und Metadaten-Parameter wie `Query` und `Path` und andere, die Sie später kennenlernen. + +/// + +## Einen einzelnen Body-Parameter einbetten + +Nehmen wir an, Sie haben nur einen einzelnen `item`-Body-Parameter, ein Pydantic-Modell `Item`. + +Normalerweise wird **FastAPI** dann seinen JSON-Body direkt erwarten. + +Aber wenn Sie möchten, dass es einen JSON-Body erwartet, mit einem Schlüssel `item` und darin den Inhalt des Modells, so wie es das tut, wenn Sie mehrere Body-Parameter deklarieren, dann können Sie den speziellen `Body`-Parameter `embed` setzen: + +```Python +item: Item = Body(embed=True) +``` + +so wie in: + +{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *} + +In diesem Fall erwartet **FastAPI** einen Body wie: + +```JSON hl_lines="2" +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + } +} +``` + +statt: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +## Zusammenfassung + +Sie können mehrere Body-Parameter zu ihrer *Pfadoperation-Funktion* hinzufügen, obwohl ein Request nur einen einzigen Body enthalten kann. + +**FastAPI** wird sich darum kümmern, Ihnen korrekte Daten in Ihrer Funktion zu überreichen, und das korrekte Schema in der *Pfadoperation* zu validieren und zu dokumentieren. + +Sie können auch einzelne Werte deklarieren, die als Teil des Bodys empfangen werden. + +Und Sie können **FastAPI** instruieren, den Body in einem Schlüssel unterzubringen, selbst wenn nur ein einzelner Body-Parameter deklariert ist. diff --git a/docs/de/docs/tutorial/body-nested-models.md b/docs/de/docs/tutorial/body-nested-models.md new file mode 100644 index 000000000..6287490c6 --- /dev/null +++ b/docs/de/docs/tutorial/body-nested-models.md @@ -0,0 +1,247 @@ +# Body – Verschachtelte Modelle + +Mit **FastAPI** können Sie (dank Pydantic) beliebig tief verschachtelte Modelle definieren, validieren und dokumentieren. + +## Listen als Felder + +Sie können ein Attribut als Kindtyp definieren, zum Beispiel eine Python-`list`e. + +{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *} + +Das bewirkt, dass `tags` eine Liste ist, wenngleich es nichts über den Typ der Elemente der Liste aussagt. + +## Listen mit Typ-Parametern als Felder + +Aber Python erlaubt es, Listen mit inneren Typen, auch „Typ-Parameter“ genannt, zu deklarieren. + +### `List` von `typing` importieren + +In Python 3.9 oder darüber können Sie einfach `list` verwenden, um diese Typannotationen zu deklarieren, wie wir unten sehen werden. 💡 + +In Python-Versionen vor 3.9 (3.6 und darüber), müssen Sie zuerst `List` von Pythons Standardmodul `typing` importieren. + +{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *} + +### Eine `list`e mit einem Typ-Parameter deklarieren + +Um Typen wie `list`, `dict`, `tuple` mit inneren Typ-Parametern (inneren Typen) zu deklarieren: + +* Wenn Sie eine Python-Version kleiner als 3.9 verwenden, importieren Sie das Äquivalent zum entsprechenden Typ vom `typing`-Modul +* Überreichen Sie den/die inneren Typ(en) von eckigen Klammern umschlossen, `[` und `]`, als „Typ-Parameter“ + +In Python 3.9 wäre das: + +```Python +my_list: list[str] +``` + +Und in Python-Versionen vor 3.9: + +```Python +from typing import List + +my_list: List[str] +``` + +Das ist alles Standard-Python-Syntax für Typdeklarationen. + +Verwenden Sie dieselbe Standardsyntax für Modellattribute mit inneren Typen. + +In unserem Beispiel können wir also bewirken, dass `tags` spezifisch eine „Liste von Strings“ ist: + +{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *} + +## Set-Typen + +Aber dann denken wir darüber nach und stellen fest, dass sich die Tags nicht wiederholen sollen, es sollen eindeutige Strings sein. + +Python hat einen Datentyp speziell für Mengen eindeutiger Dinge: das `set`. + +Deklarieren wir also `tags` als Set von Strings. + +{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *} + +Jetzt, selbst wenn Sie einen Request mit duplizierten Daten erhalten, werden diese zu einem Set eindeutiger Dinge konvertiert. + +Und wann immer Sie diese Daten ausgeben, selbst wenn die Quelle Duplikate hatte, wird es als Set von eindeutigen Dingen ausgegeben. + +Und es wird entsprechend annotiert/dokumentiert. + +## Verschachtelte Modelle + +Jedes Attribut eines Pydantic-Modells hat einen Typ. + +Aber dieser Typ kann selbst ein anderes Pydantic-Modell sein. + +Sie können also tief verschachtelte JSON-„Objekte“ deklarieren, mit spezifischen Attributnamen, -typen, und -validierungen. + +Alles das beliebig tief verschachtelt. + +### Ein Kindmodell definieren + +Wir können zum Beispiel ein `Image`-Modell definieren. + +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *} + +### Das Kindmodell als Typ verwenden + +Und dann können wir es als Typ eines Attributes verwenden. + +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *} + +Das würde bedeuten, dass **FastAPI** einen Body erwartet wie: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2, + "tags": ["rock", "metal", "bar"], + "image": { + "url": "http://example.com/baz.jpg", + "name": "The Foo live" + } +} +``` + +Wiederum, nur mit dieser Deklaration erhalten Sie von **FastAPI**: + +* Editor-Unterstützung (Codevervollständigung, usw.), selbst für verschachtelte Modelle +* Datenkonvertierung +* Datenvalidierung +* Automatische Dokumentation + +## Spezielle Typen und Validierungen + +Abgesehen von normalen einfachen Typen, wie `str`, `int`, `float`, usw. können Sie komplexere einfache Typen verwenden, die von `str` erben. + +Um alle Optionen kennenzulernen, die Sie haben, schauen Sie sich Pydantics Typübersicht an. Sie werden im nächsten Kapitel ein paar Beispiele kennenlernen. + +Da wir zum Beispiel im `Image`-Modell ein Feld `url` haben, können wir deklarieren, dass das eine Instanz von Pydantics `HttpUrl` sein soll, anstelle eines `str`: + +{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *} + +Es wird getestet, ob der String eine gültige URL ist, und als solche wird er in JSON Schema / OpenAPI dokumentiert. + +## Attribute mit Listen von Kindmodellen + +Sie können Pydantic-Modelle auch als Typen innerhalb von `list`, `set`, usw. verwenden: + +{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *} + +Das wird einen JSON-Body erwarten (konvertieren, validieren, dokumentieren), wie: + +```JSON hl_lines="11" +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2, + "tags": [ + "rock", + "metal", + "bar" + ], + "images": [ + { + "url": "http://example.com/baz.jpg", + "name": "The Foo live" + }, + { + "url": "http://example.com/dave.jpg", + "name": "The Baz" + } + ] +} +``` + +/// info + +Beachten Sie, dass der `images`-Schlüssel jetzt eine Liste von Bild-Objekten hat. + +/// + +## Tief verschachtelte Modelle + +Sie können beliebig tief verschachtelte Modelle definieren: + +{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *} + +/// info + +Beachten Sie, wie `Offer` eine Liste von `Item`s hat, von denen jedes seinerseits eine optionale Liste von `Image`s hat. + +/// + +## Bodys aus reinen Listen + +Wenn Sie möchten, dass das äußerste Element des JSON-Bodys ein JSON-`array` (eine Python-`list`e) ist, können Sie den Typ im Funktionsparameter deklarieren, mit der gleichen Syntax wie in Pydantic-Modellen: + +```Python +images: List[Image] +``` + +oder in Python 3.9 und darüber: + +```Python +images: list[Image] +``` + +so wie in: + +{* ../../docs_src/body_nested_models/tutorial008_py39.py hl[13] *} + +## Editor-Unterstützung überall + +Und Sie erhalten Editor-Unterstützung überall. + +Selbst für Dinge in Listen: + + + +Sie würden diese Editor-Unterstützung nicht erhalten, wenn Sie direkt mit `dict`, statt mit Pydantic-Modellen arbeiten würden. + +Aber Sie müssen sich auch nicht weiter um die Modelle kümmern, hereinkommende Dicts werden automatisch in sie konvertiert. Und was Sie zurückgeben, wird automatisch nach JSON konvertiert. + +## Bodys mit beliebigen `dict`s + +Sie können einen Body auch als `dict` deklarieren, mit Schlüsseln eines Typs und Werten eines anderen Typs. + +So brauchen Sie vorher nicht zu wissen, wie die Feld-/Attribut-Namen lauten (wie es bei Pydantic-Modellen der Fall wäre). + +Das ist nützlich, wenn Sie Schlüssel empfangen, deren Namen Sie nicht bereits kennen. + +--- + +Ein anderer nützlicher Anwendungsfall ist, wenn Sie Schlüssel eines anderen Typs haben wollen, z. B. `int`. + +Das schauen wir uns mal an. + +Im folgenden Beispiel akzeptieren Sie irgendein `dict`, solange es `int`-Schlüssel und `float`-Werte hat. + +{* ../../docs_src/body_nested_models/tutorial009_py39.py hl[7] *} + +/// tip | Tipp + +Bedenken Sie, dass JSON nur `str` als Schlüssel unterstützt. + +Aber Pydantic hat automatische Datenkonvertierung. + +Das bedeutet, dass Ihre API-Clients nur Strings senden können, aber solange diese Strings nur Zahlen enthalten, wird Pydantic sie konvertieren und validieren. + +Und das `dict` welches Sie als `weights` erhalten, wird `int`-Schlüssel und `float`-Werte haben. + +/// + +## Zusammenfassung + +Mit **FastAPI** haben Sie die maximale Flexibilität von Pydantic-Modellen, während Ihr Code einfach, kurz und elegant bleibt. + +Aber mit all den Vorzügen: + +* Editor-Unterstützung (Codevervollständigung überall) +* Datenkonvertierung (auch bekannt als Parsen, Serialisierung) +* Datenvalidierung +* Schema-Dokumentation +* Automatische Dokumentation diff --git a/docs/de/docs/tutorial/body-updates.md b/docs/de/docs/tutorial/body-updates.md new file mode 100644 index 000000000..574016c58 --- /dev/null +++ b/docs/de/docs/tutorial/body-updates.md @@ -0,0 +1,116 @@ +# Body – Aktualisierungen + +## Ersetzendes Aktualisieren mit `PUT` + +Um einen Artikel zu aktualisieren, können Sie die HTTP `PUT` Operation verwenden. + +Sie können den `jsonable_encoder` verwenden, um die empfangenen Daten in etwas zu konvertieren, das als JSON gespeichert werden kann (in z. B. einer NoSQL-Datenbank). Zum Beispiel, um ein `datetime` in einen `str` zu konvertieren. + +{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *} + +`PUT` wird verwendet, um Daten zu empfangen, die die existierenden Daten ersetzen sollen. + +### Warnung bezüglich des Ersetzens + +Das bedeutet, dass, wenn Sie den Artikel `bar` aktualisieren wollen, mittels `PUT` und folgendem Body: + +```Python +{ + "name": "Barz", + "price": 3, + "description": None, +} +``` + +das Eingabemodell nun den Defaultwert `"tax": 10.5` hat, weil Sie das bereits gespeicherte Attribut `"tax": 20.2` nicht mit übergeben haben. + +Die Daten werden darum mit einem „neuen“ `tax`-Wert von `10.5` abgespeichert. + +## Teilweises Ersetzen mit `PATCH` + +Sie können auch die HTTP `PATCH` Operation verwenden, um Daten *teilweise* zu ersetzen. + +Das bedeutet, sie senden nur die Daten, die Sie aktualisieren wollen, der Rest bleibt unverändert. + +/// note | Hinweis + +`PATCH` wird seltener verwendet und ist weniger bekannt als `PUT`. + +Und viele Teams verwenden ausschließlich `PUT`, selbst für nur Teil-Aktualisierungen. + +Es steht Ihnen **frei**, das zu verwenden, was Sie möchten, **FastAPI** legt Ihnen keine Einschränkungen auf. + +Aber dieser Leitfaden zeigt Ihnen mehr oder weniger, wie die beiden normalerweise verwendet werden. + +/// + +### Pydantics `exclude_unset`-Parameter verwenden + +Wenn Sie Teil-Aktualisierungen entgegennehmen, ist der `exclude_unset`-Parameter in der `.model_dump()`-Methode von Pydantic-Modellen sehr nützlich. + +Wie in `item.model_dump(exclude_unset=True)`. + +/// info + +In Pydantic v1 hieß diese Methode `.dict()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_dump()` umbenannt. + +Die Beispiele hier verwenden `.dict()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_dump()` verwenden, wenn Sie Pydantic v2 verwenden können. + +/// + +Das wird ein `dict` erstellen, mit nur den Daten, die gesetzt wurden als das `item`-Modell erstellt wurde, Defaultwerte ausgeschlossen. + +Sie können das verwenden, um ein `dict` zu erstellen, das nur die (im Request) gesendeten Daten enthält, ohne Defaultwerte: + +{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *} + +### Pydantics `update`-Parameter verwenden + +Jetzt können Sie eine Kopie des existierenden Modells mittels `.model_copy()` erstellen, wobei Sie dem `update`-Parameter ein `dict` mit den zu ändernden Daten übergeben. + +/// info + +In Pydantic v1 hieß diese Methode `.copy()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_copy()` umbenannt. + +Die Beispiele hier verwenden `.copy()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_copy()` verwenden, wenn Sie Pydantic v2 verwenden können. + +/// + +Wie in `stored_item_model.model_copy(update=update_data)`: + +{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *} + +### Rekapitulation zum teilweisen Ersetzen + +Zusammengefasst, um Teil-Ersetzungen vorzunehmen: + +* (Optional) verwenden Sie `PATCH` statt `PUT`. +* Lesen Sie die bereits gespeicherten Daten aus. +* Fügen Sie diese in ein Pydantic-Modell ein. +* Erzeugen Sie aus dem empfangenen Modell ein `dict` ohne Defaultwerte (mittels `exclude_unset`). + * So ersetzen Sie nur die tatsächlich vom Benutzer gesetzten Werte, statt dass bereits gespeicherte Werte mit Defaultwerten des Modells überschrieben werden. +* Erzeugen Sie eine Kopie ihres gespeicherten Modells, wobei Sie die Attribute mit den empfangenen Teil-Ersetzungen aktualisieren (mittels des `update`-Parameters). +* Konvertieren Sie das kopierte Modell zu etwas, das in ihrer Datenbank gespeichert werden kann (indem Sie beispielsweise `jsonable_encoder` verwenden). + * Das ist vergleichbar dazu, die `.model_dump()`-Methode des Modells erneut aufzurufen, aber es wird sicherstellen, dass die Werte zu Daten konvertiert werden, die ihrerseits zu JSON konvertiert werden können, zum Beispiel `datetime` zu `str`. +* Speichern Sie die Daten in Ihrer Datenbank. +* Geben Sie das aktualisierte Modell zurück. + +{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *} + +/// tip | Tipp + +Sie können tatsächlich die gleiche Technik mit einer HTTP `PUT` Operation verwenden. + +Aber dieses Beispiel verwendet `PATCH`, da dieses für solche Anwendungsfälle geschaffen wurde. + +/// + +/// note | Hinweis + +Beachten Sie, dass das hereinkommende Modell immer noch validiert wird. + +Wenn Sie also Teil-Aktualisierungen empfangen wollen, die alle Attribute auslassen können, müssen Sie ein Modell haben, dessen Attribute alle als optional gekennzeichnet sind (mit Defaultwerten oder `None`). + +Um zu unterscheiden zwischen Modellen für **Aktualisierungen**, mit lauter optionalen Werten, und solchen für die **Erzeugung**, mit benötigten Werten, können Sie die Techniken verwenden, die in [Extramodelle](extra-models.md){.internal-link target=_blank} beschrieben wurden. + +/// diff --git a/docs/de/docs/tutorial/body.md b/docs/de/docs/tutorial/body.md new file mode 100644 index 000000000..e25323786 --- /dev/null +++ b/docs/de/docs/tutorial/body.md @@ -0,0 +1,162 @@ +# Requestbody + +Wenn Sie Daten von einem Client (sagen wir, einem Browser) zu Ihrer API senden, dann senden Sie diese als einen **Requestbody** (Deutsch: Anfragekörper). + +Ein **Request**body sind Daten, die vom Client zu Ihrer API gesendet werden. Ein **Response**body (Deutsch: Antwortkörper) sind Daten, die Ihre API zum Client sendet. + +Ihre API sendet fast immer einen **Response**body. Aber Clients senden nicht unbedingt immer **Request**bodys (sondern nur Metadaten). + +Um einen **Request**body zu deklarieren, verwenden Sie Pydantic-Modelle mit allen deren Fähigkeiten und Vorzügen. + +/// info + +Um Daten zu versenden, sollten Sie eines von: `POST` (meistverwendet), `PUT`, `DELETE` oder `PATCH` verwenden. + +Senden Sie einen Body mit einem `GET`-Request, dann führt das laut Spezifikation zu undefiniertem Verhalten. Trotzdem wird es von FastAPI unterstützt, für sehr komplexe/extreme Anwendungsfälle. + +Da aber davon abgeraten wird, zeigt die interaktive Dokumentation mit Swagger-Benutzeroberfläche die Dokumentation für den Body auch nicht an, wenn `GET` verwendet wird. Dazwischengeschaltete Proxys unterstützen es möglicherweise auch nicht. + +/// + +## Importieren Sie Pydantics `BaseModel` + +Zuerst müssen Sie `BaseModel` von `pydantic` importieren: + +{* ../../docs_src/body/tutorial001_py310.py hl[2] *} + +## Erstellen Sie Ihr Datenmodell + +Dann deklarieren Sie Ihr Datenmodell als eine Klasse, die von `BaseModel` erbt. + +Verwenden Sie Standard-Python-Typen für die Klassenattribute: + +{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *} + +Wie auch bei Query-Parametern gilt, wenn ein Modellattribut einen Defaultwert hat, ist das Attribut nicht erforderlich. Ansonsten ist es erforderlich. Verwenden Sie `None`, um es als optional zu kennzeichnen. + +Zum Beispiel deklariert das obige Modell ein JSON "`object`" (oder Python-`dict`) wie dieses: + +```JSON +{ + "name": "Foo", + "description": "An optional description", + "price": 45.2, + "tax": 3.5 +} +``` + +Da `description` und `tax` optional sind (mit `None` als Defaultwert), wäre folgendes JSON "`object`" auch gültig: + +```JSON +{ + "name": "Foo", + "price": 45.2 +} +``` + +## Deklarieren Sie es als Parameter + +Um es zu Ihrer *Pfadoperation* hinzuzufügen, deklarieren Sie es auf die gleiche Weise, wie Sie Pfad- und Query-Parameter deklariert haben: + +{* ../../docs_src/body/tutorial001_py310.py hl[16] *} + +... und deklarieren Sie seinen Typ als das Modell, welches Sie erstellt haben, `Item`. + +## Resultate + +Mit nur dieser Python-Typdeklaration, wird **FastAPI**: + +* Den Requestbody als JSON lesen. +* Die entsprechenden Typen konvertieren (falls nötig). +* Diese Daten validieren. + * Wenn die Daten ungültig sind, einen klar lesbaren Fehler zurückgeben, der anzeigt, wo und was die inkorrekten Daten waren. +* Ihnen die erhaltenen Daten im Parameter `item` übergeben. + * Da Sie diesen in der Funktion als vom Typ `Item` deklariert haben, erhalten Sie die ganze Editor-Unterstützung (Autovervollständigung, usw.) für alle Attribute und deren Typen. +* Eine JSON Schema Definition für Ihr Modell generieren, welche Sie überall sonst verwenden können, wenn es für Ihr Projekt Sinn macht. +* Diese Schemas werden Teil des generierten OpenAPI-Schemas und werden von den UIs der automatischen Dokumentation verwendet. + +## Automatische Dokumentation + +Die JSON-Schemas Ihrer Modelle werden Teil ihrer OpenAPI-generierten Schemas und werden in der interaktiven API Dokumentation angezeigt: + + + +Und werden auch verwendet in der API-Dokumentation innerhalb jeder *Pfadoperation*, welche sie braucht: + + + +## Editor Unterstützung + +In Ihrem Editor, innerhalb Ihrer Funktion, erhalten Sie Typhinweise und Code-Vervollständigung überall (was nicht der Fall wäre, wenn Sie ein `dict` anstelle eines Pydantic Modells erhalten hätten): + + + +Sie bekommen auch Fehler-Meldungen für inkorrekte Typoperationen: + + + +Das ist nicht zufällig so, das ganze Framework wurde um dieses Design herum aufgebaut. + +Und es wurde in der Designphase gründlich getestet, vor der Implementierung, um sicherzustellen, dass es mit jedem Editor funktioniert. + +Es gab sogar ein paar Änderungen an Pydantic selbst, um das zu unterstützen. + +Die vorherigen Screenshots zeigten Visual Studio Code. + +Aber Sie bekommen die gleiche Editor-Unterstützung in PyCharm und in den meisten anderen Python-Editoren: + + + +/// tip | Tipp + +Wenn Sie PyCharm als Ihren Editor verwenden, probieren Sie das Pydantic PyCharm Plugin aus. + +Es verbessert die Editor-Unterstützung für Pydantic-Modelle, mit: + +* Code-Vervollständigung +* Typüberprüfungen +* Refaktorisierung +* Suchen +* Inspektionen + +/// + +## Das Modell verwenden + +Innerhalb der Funktion können Sie alle Attribute des Modells direkt verwenden: + +{* ../../docs_src/body/tutorial002_py310.py hl[19] *} + +## Requestbody- + Pfad-Parameter + +Sie können Pfad- und Requestbody-Parameter gleichzeitig deklarieren. + +**FastAPI** erkennt, dass Funktionsparameter, die mit Pfad-Parametern übereinstimmen, **vom Pfad genommen** werden sollen, und dass Funktionsparameter, welche Pydantic-Modelle sind, **vom Requestbody genommen** werden sollen. + +{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *} + +## Requestbody- + Pfad- + Query-Parameter + +Sie können auch zur gleichen Zeit **Body-**, **Pfad-** und **Query-Parameter** deklarieren. + +**FastAPI** wird jeden Parameter korrekt erkennen und die Daten vom richtigen Ort holen. + +{* ../../docs_src/body/tutorial004_py310.py hl[16] *} + +Die Funktionsparameter werden wie folgt erkannt: + +* Wenn der Parameter auch im **Pfad** deklariert wurde, wird er als Pfad-Parameter interpretiert. +* Wenn der Parameter ein **einfacher Typ** ist (wie `int`, `float`, `str`, `bool`, usw.), wird er als **Query**-Parameter interpretiert. +* Wenn der Parameter vom Typ eines **Pydantic-Modells** ist, wird er als Request**body** interpretiert. + +/// note | Hinweis + +FastAPI weiß, dass der Wert von `q` nicht erforderlich ist, wegen des definierten Defaultwertes `= None` + +Das `Union` in `Union[str, None]` wird von FastAPI nicht verwendet, aber es erlaubt Ihrem Editor, Sie besser zu unterstützen und Fehler zu erkennen. + +/// + +## Ohne Pydantic + +Wenn Sie keine Pydantic-Modelle verwenden wollen, können Sie auch **Body**-Parameter nehmen. Siehe die Dokumentation unter [Body – Mehrere Parameter: Einfache Werte im Body](body-multiple-params.md#einzelne-werte-im-body){.internal-link target=\_blank}. diff --git a/docs/de/docs/tutorial/cookie-params.md b/docs/de/docs/tutorial/cookie-params.md new file mode 100644 index 000000000..711c8c8e9 --- /dev/null +++ b/docs/de/docs/tutorial/cookie-params.md @@ -0,0 +1,35 @@ +# Cookie-Parameter + +So wie `Query`- und `Path`-Parameter können Sie auch Cookie-Parameter definieren. + +## `Cookie` importieren + +Importieren Sie zuerst `Cookie`: + +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[3] *} + +## `Cookie`-Parameter deklarieren + +Dann deklarieren Sie Ihre Cookie-Parameter, auf die gleiche Weise, wie Sie auch `Path`- und `Query`-Parameter deklarieren. + +Der erste Wert ist der Typ. Sie können `Cookie` die gehabten Extra Validierungs- und Beschreibungsparameter hinzufügen. Danach können Sie einen Defaultwert vergeben: + +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9] *} + +/// note | Technische Details + +`Cookie` ist eine Schwesterklasse von `Path` und `Query`. Sie erbt von derselben gemeinsamen `Param`-Elternklasse. + +Aber erinnern Sie sich, dass, wenn Sie `Query`, `Path`, `Cookie` und andere von `fastapi` importieren, diese tatsächlich Funktionen sind, welche spezielle Klassen zurückgeben. + +/// + +/// info + +Um Cookies zu deklarieren, müssen Sie `Cookie` verwenden, da diese Parameter sonst als Query-Parameter interpretiert werden würden. + +/// + +## Zusammenfassung + +Deklarieren Sie Cookies mittels `Cookie`, auf die gleiche Weise wie bei `Query` und `Path`. diff --git a/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md new file mode 100644 index 000000000..e9f25f786 --- /dev/null +++ b/docs/de/docs/tutorial/dependencies/classes-as-dependencies.md @@ -0,0 +1,288 @@ +# Klassen als Abhängigkeiten + +Bevor wir tiefer in das **Dependency Injection** System eintauchen, lassen Sie uns das vorherige Beispiel verbessern. + +## Ein `dict` aus dem vorherigen Beispiel + +Im vorherigen Beispiel haben wir ein `dict` von unserer Abhängigkeit („Dependable“) zurückgegeben: + +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[9] *} + +Aber dann haben wir ein `dict` im Parameter `commons` der *Pfadoperation-Funktion*. + +Und wir wissen, dass Editoren nicht viel Unterstützung (wie etwa Code-Vervollständigung) für `dict`s bieten können, weil sie ihre Schlüssel- und Werttypen nicht kennen. + +Das können wir besser machen ... + +## Was macht eine Abhängigkeit aus + +Bisher haben Sie Abhängigkeiten gesehen, die als Funktionen deklariert wurden. + +Das ist jedoch nicht die einzige Möglichkeit, Abhängigkeiten zu deklarieren (obwohl es wahrscheinlich die gebräuchlichste ist). + +Der springende Punkt ist, dass eine Abhängigkeit aufrufbar („callable“) sein sollte. + +Ein „**Callable**“ in Python ist etwas, das wie eine Funktion aufgerufen werden kann („to call“). + +Wenn Sie also ein Objekt `something` haben (das möglicherweise _keine_ Funktion ist) und Sie es wie folgt aufrufen (ausführen) können: + +```Python +something() +``` + +oder + +```Python +something(some_argument, some_keyword_argument="foo") +``` + +dann ist das ein „Callable“ (ein „Aufrufbares“). + +## Klassen als Abhängigkeiten + +Möglicherweise stellen Sie fest, dass Sie zum Erstellen einer Instanz einer Python-Klasse die gleiche Syntax verwenden. + +Zum Beispiel: + +```Python +class Cat: + def __init__(self, name: str): + self.name = name + + +fluffy = Cat(name="Mr Fluffy") +``` + +In diesem Fall ist `fluffy` eine Instanz der Klasse `Cat`. + +Und um `fluffy` zu erzeugen, rufen Sie `Cat` auf. + +Eine Python-Klasse ist also auch ein **Callable**. + +Darum können Sie in **FastAPI** auch eine Python-Klasse als Abhängigkeit verwenden. + +Was FastAPI tatsächlich prüft, ist, ob es sich um ein „Callable“ (Funktion, Klasse oder irgendetwas anderes) handelt und ob die Parameter definiert sind. + +Wenn Sie **FastAPI** ein „Callable“ als Abhängigkeit übergeben, analysiert es die Parameter dieses „Callables“ und verarbeitet sie auf die gleiche Weise wie die Parameter einer *Pfadoperation-Funktion*. Einschließlich Unterabhängigkeiten. + +Das gilt auch für Callables ohne Parameter. So wie es auch für *Pfadoperation-Funktionen* ohne Parameter gilt. + +Dann können wir das „Dependable“ `common_parameters` der Abhängigkeit von oben in die Klasse `CommonQueryParams` ändern: + +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[11:15] *} + +Achten Sie auf die Methode `__init__`, die zum Erstellen der Instanz der Klasse verwendet wird: + +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[12] *} + +... sie hat die gleichen Parameter wie unsere vorherige `common_parameters`: + +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8] *} + +Diese Parameter werden von **FastAPI** verwendet, um die Abhängigkeit „aufzulösen“. + +In beiden Fällen wird sie haben: + +* Einen optionalen `q`-Query-Parameter, der ein `str` ist. +* Einen `skip`-Query-Parameter, der ein `int` ist, mit einem Defaultwert `0`. +* Einen `limit`-Query-Parameter, der ein `int` ist, mit einem Defaultwert `100`. + +In beiden Fällen werden die Daten konvertiert, validiert, im OpenAPI-Schema dokumentiert, usw. + +## Verwendung + +Jetzt können Sie Ihre Abhängigkeit mithilfe dieser Klasse deklarieren. + +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[19] *} + +**FastAPI** ruft die Klasse `CommonQueryParams` auf. Dadurch wird eine „Instanz“ dieser Klasse erstellt und die Instanz wird als Parameter `commons` an Ihre Funktion überreicht. + +## Typannotation vs. `Depends` + +Beachten Sie, wie wir `CommonQueryParams` im obigen Code zweimal schreiben: + +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | Tipp + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// + +Das letzte `CommonQueryParams`, in: + +```Python +... Depends(CommonQueryParams) +``` + +... ist das, was **FastAPI** tatsächlich verwendet, um die Abhängigkeit zu ermitteln. + +Aus diesem extrahiert FastAPI die deklarierten Parameter, und dieses ist es, was FastAPI auch aufruft. + +--- + +In diesem Fall hat das erste `CommonQueryParams` in: + +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, ... +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | Tipp + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python +commons: CommonQueryParams ... +``` + +//// + +... keine besondere Bedeutung für **FastAPI**. FastAPI verwendet es nicht für die Datenkonvertierung, -validierung, usw. (da es dafür `Depends(CommonQueryParams)` verwendet). + +Sie könnten tatsächlich einfach schreiben: + +//// tab | Python 3.8+ + +```Python +commons: Annotated[Any, Depends(CommonQueryParams)] +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | Tipp + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python +commons = Depends(CommonQueryParams) +``` + +//// + +... wie in: + +{* ../../docs_src/dependencies/tutorial003_an_py310.py hl[19] *} + +Es wird jedoch empfohlen, den Typ zu deklarieren, da Ihr Editor so weiß, was als Parameter `commons` übergeben wird, und Ihnen dann bei der Codevervollständigung, Typprüfungen, usw. helfen kann: + + + +## Abkürzung + +Aber Sie sehen, dass wir hier etwas Codeduplizierung haben, indem wir `CommonQueryParams` zweimal schreiben: + +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | Tipp + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// + +**FastAPI** bietet eine Abkürzung für diese Fälle, wo die Abhängigkeit *speziell* eine Klasse ist, welche **FastAPI** aufruft, um eine Instanz der Klasse selbst zu erstellen. + +In diesem speziellen Fall können Sie Folgendes tun: + +Anstatt zu schreiben: + +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | Tipp + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// + +... schreiben Sie: + +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, Depends()] +``` + +//// + +//// tab | Python 3.8 nicht annotiert + +/// tip | Tipp + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python +commons: CommonQueryParams = Depends() +``` + +//// + +Sie deklarieren die Abhängigkeit als Typ des Parameters und verwenden `Depends()` ohne Parameter, anstatt die vollständige Klasse *erneut* in `Depends(CommonQueryParams)` schreiben zu müssen. + +Dasselbe Beispiel würde dann so aussehen: + +{* ../../docs_src/dependencies/tutorial004_an_py310.py hl[19] *} + +... und **FastAPI** wird wissen, was zu tun ist. + +/// tip | Tipp + +Wenn Sie das eher verwirrt, als Ihnen zu helfen, ignorieren Sie es, Sie *brauchen* es nicht. + +Es ist nur eine Abkürzung. Es geht **FastAPI** darum, Ihnen dabei zu helfen, Codeverdoppelung zu minimieren. + +/// diff --git a/docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md new file mode 100644 index 000000000..bbba1a536 --- /dev/null +++ b/docs/de/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -0,0 +1,69 @@ +# Abhängigkeiten in Pfadoperation-Dekoratoren + +Manchmal benötigen Sie den Rückgabewert einer Abhängigkeit innerhalb Ihrer *Pfadoperation-Funktion* nicht wirklich. + +Oder die Abhängigkeit gibt keinen Wert zurück. + +Aber Sie müssen Sie trotzdem ausführen/auflösen. + +In diesen Fällen können Sie, anstatt einen Parameter der *Pfadoperation-Funktion* mit `Depends` zu deklarieren, eine `list`e von `dependencies` zum *Pfadoperation-Dekorator* hinzufügen. + +## `dependencies` zum *Pfadoperation-Dekorator* hinzufügen + +Der *Pfadoperation-Dekorator* erhält ein optionales Argument `dependencies`. + +Es sollte eine `list`e von `Depends()` sein: + +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[19] *} + +Diese Abhängigkeiten werden auf die gleiche Weise wie normale Abhängigkeiten ausgeführt/aufgelöst. Aber ihr Wert (falls sie einen zurückgeben) wird nicht an Ihre *Pfadoperation-Funktion* übergeben. + +/// tip | Tipp + +Einige Editoren prüfen, ob Funktionsparameter nicht verwendet werden, und zeigen das als Fehler an. + +Wenn Sie `dependencies` im *Pfadoperation-Dekorator* verwenden, stellen Sie sicher, dass sie ausgeführt werden, während gleichzeitig Ihr Editor/Ihre Tools keine Fehlermeldungen ausgeben. + +Damit wird auch vermieden, neue Entwickler möglicherweise zu verwirren, die einen nicht verwendeten Parameter in Ihrem Code sehen und ihn für unnötig halten könnten. + +/// + +/// info + +In diesem Beispiel verwenden wir zwei erfundene benutzerdefinierte Header `X-Key` und `X-Token`. + +Aber in realen Fällen würden Sie bei der Implementierung von Sicherheit mehr Vorteile durch die Verwendung der integrierten [Sicherheits-Werkzeuge (siehe nächstes Kapitel)](../security/index.md){.internal-link target=_blank} erzielen. + +/// + +## Abhängigkeitsfehler und -Rückgabewerte + +Sie können dieselben Abhängigkeits-*Funktionen* verwenden, die Sie normalerweise verwenden. + +### Abhängigkeitsanforderungen + +Sie können Anforderungen für einen Request (wie Header) oder andere Unterabhängigkeiten deklarieren: + +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[8,13] *} + +### Exceptions auslösen + +Die Abhängigkeiten können Exceptions `raise`n, genau wie normale Abhängigkeiten: + +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[10,15] *} + +### Rückgabewerte + +Und sie können Werte zurückgeben oder nicht, die Werte werden nicht verwendet. + +Sie können also eine normale Abhängigkeit (die einen Wert zurückgibt), die Sie bereits an anderer Stelle verwenden, wiederverwenden, und auch wenn der Wert nicht verwendet wird, wird die Abhängigkeit ausgeführt: + +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[11,16] *} + +## Abhängigkeiten für eine Gruppe von *Pfadoperationen* + +Wenn Sie später lesen, wie Sie größere Anwendungen strukturieren ([Größere Anwendungen – Mehrere Dateien](../../tutorial/bigger-applications.md){.internal-link target=_blank}), möglicherweise mit mehreren Dateien, lernen Sie, wie Sie einen einzelnen `dependencies`-Parameter für eine Gruppe von *Pfadoperationen* deklarieren. + +## Globale Abhängigkeiten + +Als Nächstes werden wir sehen, wie man Abhängigkeiten zur gesamten `FastAPI`-Anwendung hinzufügt, sodass sie für jede *Pfadoperation* gelten. diff --git a/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md new file mode 100644 index 000000000..4b12f8447 --- /dev/null +++ b/docs/de/docs/tutorial/dependencies/dependencies-with-yield.md @@ -0,0 +1,248 @@ +# Abhängigkeiten mit yield + +FastAPI unterstützt Abhängigkeiten, die nach Abschluss einige zusätzliche Schritte ausführen. + +Verwenden Sie dazu `yield` statt `return` und schreiben Sie die zusätzlichen Schritte / den zusätzlichen Code danach. + +/// tip | Tipp + +Stellen Sie sicher, dass Sie `yield` nur einmal pro Abhängigkeit verwenden. + +/// + +/// note | Technische Details + +Jede Funktion, die dekoriert werden kann mit: + +* `@contextlib.contextmanager` oder +* `@contextlib.asynccontextmanager` + +kann auch als gültige **FastAPI**-Abhängigkeit verwendet werden. + +Tatsächlich verwendet FastAPI diese beiden Dekoratoren intern. + +/// + +## Eine Datenbank-Abhängigkeit mit `yield`. + +Sie könnten damit beispielsweise eine Datenbanksession erstellen und diese nach Abschluss schließen. + +Nur der Code vor und einschließlich der `yield`-Anweisung wird ausgeführt, bevor eine Response erzeugt wird: + +{* ../../docs_src/dependencies/tutorial007.py hl[2:4] *} + +Der ge`yield`ete Wert ist das, was in *Pfadoperationen* und andere Abhängigkeiten eingefügt wird: + +{* ../../docs_src/dependencies/tutorial007.py hl[4] *} + +Der auf die `yield`-Anweisung folgende Code wird ausgeführt, nachdem die Response gesendet wurde: + +{* ../../docs_src/dependencies/tutorial007.py hl[5:6] *} + +/// tip | Tipp + +Sie können `async`hrone oder reguläre Funktionen verwenden. + +**FastAPI** wird bei jeder das Richtige tun, so wie auch bei normalen Abhängigkeiten. + +/// + +## Eine Abhängigkeit mit `yield` und `try`. + +Wenn Sie einen `try`-Block in einer Abhängigkeit mit `yield` verwenden, empfangen Sie alle Exceptions, die bei Verwendung der Abhängigkeit geworfen wurden. + +Wenn beispielsweise ein Code irgendwann in der Mitte, in einer anderen Abhängigkeit oder in einer *Pfadoperation*, ein „Rollback“ einer Datenbanktransaktion oder einen anderen Fehler verursacht, empfangen Sie die resultierende Exception in Ihrer Abhängigkeit. + +Sie können also mit `except SomeException` diese bestimmte Exception innerhalb der Abhängigkeit handhaben. + +Auf die gleiche Weise können Sie `finally` verwenden, um sicherzustellen, dass die Exit-Schritte ausgeführt werden, unabhängig davon, ob eine Exception geworfen wurde oder nicht. + +{* ../../docs_src/dependencies/tutorial007.py hl[3,5] *} + +## Unterabhängigkeiten mit `yield`. + +Sie können Unterabhängigkeiten und „Bäume“ von Unterabhängigkeiten beliebiger Größe und Form haben, und einige oder alle davon können `yield` verwenden. + +**FastAPI** stellt sicher, dass der „Exit-Code“ in jeder Abhängigkeit mit `yield` in der richtigen Reihenfolge ausgeführt wird. + +Beispielsweise kann `dependency_c` von `dependency_b` und `dependency_b` von `dependency_a` abhängen: + +{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[6,14,22] *} + +Und alle können `yield` verwenden. + +In diesem Fall benötigt `dependency_c` zum Ausführen seines Exit-Codes, dass der Wert von `dependency_b` (hier `dep_b` genannt) verfügbar ist. + +Und wiederum benötigt `dependency_b` den Wert von `dependency_a` (hier `dep_a` genannt) für seinen Exit-Code. + +{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[18:19,26:27] *} + +Auf die gleiche Weise könnten Sie einige Abhängigkeiten mit `yield` und einige andere Abhängigkeiten mit `return` haben, und alle können beliebig voneinander abhängen. + +Und Sie könnten eine einzelne Abhängigkeit haben, die auf mehreren ge`yield`eten Abhängigkeiten basiert, usw. + +Sie können beliebige Kombinationen von Abhängigkeiten haben. + +**FastAPI** stellt sicher, dass alles in der richtigen Reihenfolge ausgeführt wird. + +/// note | Technische Details + +Dieses funktioniert dank Pythons Kontextmanager. + +**FastAPI** verwendet sie intern, um das zu erreichen. + +/// + +## Abhängigkeiten mit `yield` und `HTTPException`. + +Sie haben gesehen, dass Ihre Abhängigkeiten `yield` verwenden können und `try`-Blöcke haben können, die Exceptions abfangen. + +Auf die gleiche Weise könnten Sie im Exit-Code nach dem `yield` eine `HTTPException` oder ähnliches auslösen. + +/// tip | Tipp + +Dies ist eine etwas fortgeschrittene Technik, die Sie in den meisten Fällen nicht wirklich benötigen, da Sie Exceptions (einschließlich `HTTPException`) innerhalb des restlichen Anwendungscodes auslösen können, beispielsweise in der *Pfadoperation-Funktion*. + +Aber es ist für Sie da, wenn Sie es brauchen. 🤓 + +/// + +{* ../../docs_src/dependencies/tutorial008b_an_py39.py hl[18:22,31] *} + +Eine Alternative zum Abfangen von Exceptions (und möglicherweise auch zum Auslösen einer weiteren `HTTPException`) besteht darin, einen [benutzerdefinierten Exceptionhandler](../handling-errors.md#benutzerdefinierte-exceptionhandler-definieren){.internal-link target=_blank} zu erstellen. + +## Ausführung von Abhängigkeiten mit `yield` + +Die Ausführungsreihenfolge ähnelt mehr oder weniger dem folgenden Diagramm. Die Zeit verläuft von oben nach unten. Und jede Spalte ist einer der interagierenden oder Code-ausführenden Teilnehmer. + +```mermaid +sequenceDiagram + +participant client as Client +participant handler as Exceptionhandler +participant dep as Abhängigkeit mit yield +participant operation as Pfadoperation +participant tasks as Hintergrundtasks + + Note over client,operation: Kann Exceptions auslösen, inklusive HTTPException + client ->> dep: Startet den Request + Note over dep: Führt den Code bis zum yield aus + opt Löst Exception aus + dep -->> handler: Löst Exception aus + handler -->> client: HTTP-Error-Response + end + dep ->> operation: Führt Abhängigkeit aus, z. B. DB-Session + opt Löst aus + operation -->> dep: Löst Exception aus (z. B. HTTPException) + opt Handhabt + dep -->> dep: Kann Exception abfangen, eine neue HTTPException auslösen, andere Exceptions auslösen + dep -->> handler: Leitet Exception automatisch weiter + end + handler -->> client: HTTP-Error-Response + end + operation ->> client: Sendet Response an Client + Note over client,operation: Response wurde gesendet, kann nicht mehr geändert werden + opt Tasks + operation -->> tasks: Sendet Hintergrundtasks + end + opt Löst andere Exception aus + tasks -->> tasks: Handhabt Exception im Hintergrundtask-Code + end +``` + +/// info + +Es wird nur **eine Response** an den Client gesendet. Es kann eine Error-Response oder die Response der *Pfadoperation* sein. + +Nachdem eine dieser Responses gesendet wurde, kann keine weitere Response gesendet werden. + +/// + +/// tip | Tipp + +Obiges Diagramm verwendet `HTTPException`, aber Sie können auch jede andere Exception auslösen, die Sie in einer Abhängigkeit mit `yield` abfangen, oder mit einem [benutzerdefinierten Exceptionhandler](../handling-errors.md#benutzerdefinierte-exceptionhandler-definieren){.internal-link target=_blank} erstellt haben. + +Wenn Sie eine Exception auslösen, wird diese mit yield an die Abhängigkeiten übergeben, einschließlich `HTTPException`, und dann **erneut** an die Exceptionhandler. Wenn es für diese Exception keinen Exceptionhandler gibt, wird sie von der internen Default-`ServerErrorMiddleware` gehandhabt, was einen HTTP-Statuscode 500 zurückgibt, um den Client darüber zu informieren, dass ein Fehler auf dem Server aufgetreten ist. + +/// + +## Abhängigkeiten mit `yield`, `HTTPException` und Hintergrundtasks + +/// warning | Achtung + +Sie benötigen diese technischen Details höchstwahrscheinlich nicht, Sie können diesen Abschnitt überspringen und weiter unten fortfahren. + +Diese Details sind vor allem dann nützlich, wenn Sie eine Version von FastAPI vor 0.106.0 verwendet haben und Ressourcen aus Abhängigkeiten mit `yield` in Hintergrundtasks verwendet haben. + +/// + +Vor FastAPI 0.106.0 war das Auslösen von Exceptions nach `yield` nicht möglich, der Exit-Code in Abhängigkeiten mit `yield` wurde ausgeführt, *nachdem* die Response gesendet wurde, die [Exceptionhandler](../handling-errors.md#benutzerdefinierte-exceptionhandler-definieren){.internal-link target=_blank} wären also bereits ausgeführt worden. + +Dies wurde hauptsächlich so konzipiert, damit die gleichen Objekte, die durch Abhängigkeiten ge`yield`et werden, innerhalb von Hintergrundtasks verwendet werden können, da der Exit-Code ausgeführt wird, nachdem die Hintergrundtasks abgeschlossen sind. + +Da dies jedoch bedeuten würde, darauf zu warten, dass die Response durch das Netzwerk reist, während eine Ressource unnötigerweise in einer Abhängigkeit mit yield gehalten wird (z. B. eine Datenbankverbindung), wurde dies in FastAPI 0.106.0 geändert. + +/// tip | Tipp + +Darüber hinaus handelt es sich bei einem Hintergrundtask normalerweise um einen unabhängigen Satz von Logik, der separat behandelt werden sollte, mit eigenen Ressourcen (z. B. einer eigenen Datenbankverbindung). + +Auf diese Weise erhalten Sie wahrscheinlich saubereren Code. + +/// + +Wenn Sie sich früher auf dieses Verhalten verlassen haben, sollten Sie jetzt die Ressourcen für Hintergrundtasks innerhalb des Hintergrundtasks selbst erstellen und intern nur Daten verwenden, die nicht von den Ressourcen von Abhängigkeiten mit `yield` abhängen. + +Anstatt beispielsweise dieselbe Datenbanksitzung zu verwenden, würden Sie eine neue Datenbanksitzung innerhalb des Hintergrundtasks erstellen und die Objekte mithilfe dieser neuen Sitzung aus der Datenbank abrufen. Und anstatt das Objekt aus der Datenbank als Parameter an die Hintergrundtask-Funktion zu übergeben, würden Sie die ID dieses Objekts übergeben und das Objekt dann innerhalb der Hintergrundtask-Funktion erneut laden. + +## Kontextmanager + +### Was sind „Kontextmanager“ + +„Kontextmanager“ (Englisch „Context Manager“) sind bestimmte Python-Objekte, die Sie in einer `with`-Anweisung verwenden können. + +Beispielsweise können Sie `with` verwenden, um eine Datei auszulesen: + +```Python +with open("./somefile.txt") as f: + contents = f.read() + print(contents) +``` + +Im Hintergrund erstellt das `open("./somefile.txt")` ein Objekt, das als „Kontextmanager“ bezeichnet wird. + +Dieser stellt sicher dass, wenn der `with`-Block beendet ist, die Datei geschlossen wird, auch wenn Exceptions geworfen wurden. + +Wenn Sie eine Abhängigkeit mit `yield` erstellen, erstellt **FastAPI** dafür intern einen Kontextmanager und kombiniert ihn mit einigen anderen zugehörigen Tools. + +### Kontextmanager in Abhängigkeiten mit `yield` verwenden + +/// warning | Achtung + +Dies ist mehr oder weniger eine „fortgeschrittene“ Idee. + +Wenn Sie gerade erst mit **FastAPI** beginnen, möchten Sie das vielleicht vorerst überspringen. + +/// + +In Python können Sie Kontextmanager erstellen, indem Sie eine Klasse mit zwei Methoden erzeugen: `__enter__()` und `__exit__()`. + +Sie können solche auch innerhalb von **FastAPI**-Abhängigkeiten mit `yield` verwenden, indem Sie `with`- oder `async with`-Anweisungen innerhalb der Abhängigkeits-Funktion verwenden: + +{* ../../docs_src/dependencies/tutorial010.py hl[1:9,13] *} + +/// tip | Tipp + +Andere Möglichkeiten, einen Kontextmanager zu erstellen, sind: + +* `@contextlib.contextmanager` oder +* `@contextlib.asynccontextmanager` + +Verwenden Sie diese, um eine Funktion zu dekorieren, die ein einziges `yield` hat. + +Das ist es auch, was **FastAPI** intern für Abhängigkeiten mit `yield` verwendet. + +Aber Sie müssen die Dekoratoren nicht für FastAPI-Abhängigkeiten verwenden (und das sollten Sie auch nicht). + +FastAPI erledigt das intern für Sie. + +/// diff --git a/docs/de/docs/tutorial/dependencies/global-dependencies.md b/docs/de/docs/tutorial/dependencies/global-dependencies.md new file mode 100644 index 000000000..4df2b324b --- /dev/null +++ b/docs/de/docs/tutorial/dependencies/global-dependencies.md @@ -0,0 +1,15 @@ +# Globale Abhängigkeiten + +Bei einigen Anwendungstypen möchten Sie möglicherweise Abhängigkeiten zur gesamten Anwendung hinzufügen. + +Ähnlich wie Sie [`dependencies` zu den *Pfadoperation-Dekoratoren* hinzufügen](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} können, können Sie sie auch zur `FastAPI`-Anwendung hinzufügen. + +In diesem Fall werden sie auf alle *Pfadoperationen* in der Anwendung angewendet: + +{* ../../docs_src/dependencies/tutorial012_an_py39.py hl[16] *} + +Und alle Ideen aus dem Abschnitt über das [Hinzufügen von `dependencies` zu den *Pfadoperation-Dekoratoren*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} gelten weiterhin, aber in diesem Fall für alle *Pfadoperationen* in der Anwendung. + +## Abhängigkeiten für Gruppen von *Pfadoperationen* + +Wenn Sie später lesen, wie Sie größere Anwendungen strukturieren ([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md){.internal-link target=_blank}), möglicherweise mit mehreren Dateien, lernen Sie, wie Sie einen einzelnen `dependencies`-Parameter für eine Gruppe von *Pfadoperationen* deklarieren. diff --git a/docs/de/docs/tutorial/dependencies/index.md b/docs/de/docs/tutorial/dependencies/index.md new file mode 100644 index 000000000..42182d030 --- /dev/null +++ b/docs/de/docs/tutorial/dependencies/index.md @@ -0,0 +1,249 @@ +# Abhängigkeiten + +**FastAPI** hat ein sehr mächtiges, aber intuitives **Dependency Injection** System. + +Es ist so konzipiert, sehr einfach zu verwenden zu sein und es jedem Entwickler sehr leicht zu machen, andere Komponenten mit **FastAPI** zu integrieren. + +## Was ist „Dependency Injection“ + +**„Dependency Injection“** bedeutet in der Programmierung, dass es für Ihren Code (in diesem Fall Ihre *Pfadoperation-Funktionen*) eine Möglichkeit gibt, Dinge zu deklarieren, die er verwenden möchte und die er zum Funktionieren benötigt: „Abhängigkeiten“ – „Dependencies“. + +Das System (in diesem Fall **FastAPI**) kümmert sich dann darum, Ihren Code mit den erforderlichen Abhängigkeiten zu versorgen („die Abhängigkeiten einfügen“ – „inject the dependencies“). + +Das ist sehr nützlich, wenn Sie: + +* Eine gemeinsame Logik haben (die gleiche Code-Logik immer und immer wieder). +* Datenbankverbindungen teilen. +* Sicherheit, Authentifizierung, Rollenanforderungen, usw. durchsetzen. +* Und viele andere Dinge ... + +All dies, während Sie Codeverdoppelung minimieren. + +## Erste Schritte + +Sehen wir uns ein sehr einfaches Beispiel an. Es ist so einfach, dass es vorerst nicht sehr nützlich ist. + +Aber so können wir uns besser auf die Funktionsweise des **Dependency Injection** Systems konzentrieren. + +### Erstellen Sie eine Abhängigkeit („Dependable“) + +Konzentrieren wir uns zunächst auf die Abhängigkeit - die Dependency. + +Es handelt sich einfach um eine Funktion, die die gleichen Parameter entgegennimmt wie eine *Pfadoperation-Funktion*: +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *} + +Das war's schon. + +**Zwei Zeilen**. + +Und sie hat die gleiche Form und Struktur wie alle Ihre *Pfadoperation-Funktionen*. + +Sie können sie sich als *Pfadoperation-Funktion* ohne den „Dekorator“ (ohne `@app.get("/some-path")`) vorstellen. + +Und sie kann alles zurückgeben, was Sie möchten. + +In diesem Fall erwartet diese Abhängigkeit: + +* Einen optionalen Query-Parameter `q`, der ein `str` ist. +* Einen optionalen Query-Parameter `skip`, der ein `int` ist und standardmäßig `0` ist. +* Einen optionalen Query-Parameter `limit`, der ein `int` ist und standardmäßig `100` ist. + +Und dann wird einfach ein `dict` zurückgegeben, welches diese Werte enthält. + +/// info + +FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0. + +Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden. + +Bitte [aktualisieren Sie FastAPI](../../deployment/versions.md#upgrade-der-fastapi-versionen){.internal-link target=_blank} daher mindestens zu Version 0.95.1, bevor Sie `Annotated` verwenden. + +/// + +### `Depends` importieren + +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *} + +### Deklarieren der Abhängigkeit im „Dependant“ + +So wie auch `Body`, `Query`, usw., verwenden Sie `Depends` mit den Parametern Ihrer *Pfadoperation-Funktion*: + +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *} + +Obwohl Sie `Depends` in den Parametern Ihrer Funktion genauso verwenden wie `Body`, `Query`, usw., funktioniert `Depends` etwas anders. + +Sie übergeben `Depends` nur einen einzigen Parameter. + +Dieser Parameter muss so etwas wie eine Funktion sein. + +Sie **rufen diese nicht direkt auf** (fügen Sie am Ende keine Klammern hinzu), sondern übergeben sie einfach als Parameter an `Depends()`. + +Und diese Funktion akzeptiert Parameter auf die gleiche Weise wie *Pfadoperation-Funktionen*. + +/// tip | Tipp + +Im nächsten Kapitel erfahren Sie, welche anderen „Dinge“, außer Funktionen, Sie als Abhängigkeiten verwenden können. + +/// + +Immer wenn ein neuer Request eintrifft, kümmert sich **FastAPI** darum: + +* Ihre Abhängigkeitsfunktion („Dependable“) mit den richtigen Parametern aufzurufen. +* Sich das Ergebnis von dieser Funktion zu holen. +* Dieses Ergebnis dem Parameter Ihrer *Pfadoperation-Funktion* zuzuweisen. + +```mermaid +graph TB + +common_parameters(["common_parameters"]) +read_items["/items/"] +read_users["/users/"] + +common_parameters --> read_items +common_parameters --> read_users +``` + +Auf diese Weise schreiben Sie gemeinsam genutzten Code nur einmal, und **FastAPI** kümmert sich darum, ihn für Ihre *Pfadoperationen* aufzurufen. + +/// check + +Beachten Sie, dass Sie keine spezielle Klasse erstellen und diese irgendwo an **FastAPI** übergeben müssen, um sie zu „registrieren“ oder so ähnlich. + +Sie übergeben es einfach an `Depends` und **FastAPI** weiß, wie der Rest erledigt wird. + +/// + +## `Annotated`-Abhängigkeiten wiederverwenden + +In den Beispielen oben sehen Sie, dass es ein kleines bisschen **Codeverdoppelung** gibt. + +Wenn Sie die Abhängigkeit `common_parameters()` verwenden, müssen Sie den gesamten Parameter mit der Typannotation und `Depends()` schreiben: + +```Python +commons: Annotated[dict, Depends(common_parameters)] +``` + +Da wir jedoch `Annotated` verwenden, können wir diesen `Annotated`-Wert in einer Variablen speichern und an mehreren Stellen verwenden: + +{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *} + +/// tip | Tipp + +Das ist schlicht Standard-Python, es wird als „Typalias“ bezeichnet und ist eigentlich nicht **FastAPI**-spezifisch. + +Da **FastAPI** jedoch auf Standard-Python, einschließlich `Annotated`, basiert, können Sie diesen Trick in Ihrem Code verwenden. 😎 + +/// + +Die Abhängigkeiten funktionieren weiterhin wie erwartet, und das **Beste daran** ist, dass die **Typinformationen erhalten bleiben**, was bedeutet, dass Ihr Editor Ihnen weiterhin **automatische Vervollständigung**, **Inline-Fehler**, usw. bieten kann. Das Gleiche gilt für andere Tools wie `mypy`. + +Das ist besonders nützlich, wenn Sie es in einer **großen Codebasis** verwenden, in der Sie in **vielen *Pfadoperationen*** immer wieder **dieselben Abhängigkeiten** verwenden. + +## `async` oder nicht `async` + +Da Abhängigkeiten auch von **FastAPI** aufgerufen werden (so wie Ihre *Pfadoperation-Funktionen*), gelten beim Definieren Ihrer Funktionen die gleichen Regeln. + +Sie können `async def` oder einfach `def` verwenden. + +Und Sie können Abhängigkeiten mit `async def` innerhalb normaler `def`-*Pfadoperation-Funktionen* oder `def`-Abhängigkeiten innerhalb von `async def`-*Pfadoperation-Funktionen*, usw. deklarieren. + +Es spielt keine Rolle. **FastAPI** weiß, was zu tun ist. + +/// note | Hinweis + +Wenn Ihnen das nichts sagt, lesen Sie den [Async: *„In Eile?“*](../../async.md#in-eile){.internal-link target=_blank}-Abschnitt über `async` und `await` in der Dokumentation. + +/// + +## Integriert in OpenAPI + +Alle Requestdeklarationen, -validierungen und -anforderungen Ihrer Abhängigkeiten (und Unterabhängigkeiten) werden in dasselbe OpenAPI-Schema integriert. + +Die interaktive Dokumentation enthält also auch alle Informationen aus diesen Abhängigkeiten: + + + +## Einfache Verwendung + +Näher betrachtet, werden *Pfadoperation-Funktionen* deklariert, um verwendet zu werden, wann immer ein *Pfad* und eine *Operation* übereinstimmen, und dann kümmert sich **FastAPI** darum, die Funktion mit den richtigen Parametern aufzurufen, die Daten aus der Anfrage extrahierend. + +Tatsächlich funktionieren alle (oder die meisten) Webframeworks auf die gleiche Weise. + +Sie rufen diese Funktionen niemals direkt auf. Sie werden von Ihrem Framework aufgerufen (in diesem Fall **FastAPI**). + +Mit dem Dependency Injection System können Sie **FastAPI** ebenfalls mitteilen, dass Ihre *Pfadoperation-Funktion* von etwas anderem „abhängt“, das vor Ihrer *Pfadoperation-Funktion* ausgeführt werden soll, und **FastAPI** kümmert sich darum, es auszuführen und die Ergebnisse zu „injizieren“. + +Andere gebräuchliche Begriffe für dieselbe Idee der „Abhängigkeitsinjektion“ sind: + +* Ressourcen +* Provider +* Services +* Injectables +* Komponenten + +## **FastAPI**-Plugins + +Integrationen und „Plugins“ können mit dem **Dependency Injection** System erstellt werden. Aber tatsächlich besteht **keine Notwendigkeit, „Plugins“ zu erstellen**, da es durch die Verwendung von Abhängigkeiten möglich ist, eine unendliche Anzahl von Integrationen und Interaktionen zu deklarieren, die dann für Ihre *Pfadoperation-Funktionen* verfügbar sind. + +Und Abhängigkeiten können auf sehr einfache und intuitive Weise erstellt werden, sodass Sie einfach die benötigten Python-Packages importieren und sie in wenigen Codezeilen, *im wahrsten Sinne des Wortes*, mit Ihren API-Funktionen integrieren. + +Beispiele hierfür finden Sie in den nächsten Kapiteln zu relationalen und NoSQL-Datenbanken, Sicherheit usw. + +## **FastAPI**-Kompatibilität + +Die Einfachheit des Dependency Injection Systems macht **FastAPI** kompatibel mit: + +* allen relationalen Datenbanken +* NoSQL-Datenbanken +* externen Packages +* externen APIs +* Authentifizierungs- und Autorisierungssystemen +* API-Nutzungs-Überwachungssystemen +* Responsedaten-Injektionssystemen +* usw. + +## Einfach und leistungsstark + +Obwohl das hierarchische Dependency Injection System sehr einfach zu definieren und zu verwenden ist, ist es dennoch sehr mächtig. + +Sie können Abhängigkeiten definieren, die selbst wiederum Abhängigkeiten definieren können. + +Am Ende wird ein hierarchischer Baum von Abhängigkeiten erstellt, und das **Dependency Injection** System kümmert sich darum, alle diese Abhängigkeiten (und deren Unterabhängigkeiten) für Sie aufzulösen und die Ergebnisse bei jedem Schritt einzubinden (zu injizieren). + +Nehmen wir zum Beispiel an, Sie haben vier API-Endpunkte (*Pfadoperationen*): + +* `/items/public/` +* `/items/private/` +* `/users/{user_id}/activate` +* `/items/pro/` + +Dann könnten Sie für jeden davon unterschiedliche Berechtigungsanforderungen hinzufügen, nur mit Abhängigkeiten und Unterabhängigkeiten: + +```mermaid +graph TB + +current_user(["current_user"]) +active_user(["active_user"]) +admin_user(["admin_user"]) +paying_user(["paying_user"]) + +public["/items/public/"] +private["/items/private/"] +activate_user["/users/{user_id}/activate"] +pro_items["/items/pro/"] + +current_user --> active_user +active_user --> admin_user +active_user --> paying_user + +current_user --> public +active_user --> private +admin_user --> activate_user +paying_user --> pro_items +``` + +## Integriert mit **OpenAPI** + +Alle diese Abhängigkeiten, während sie ihre Anforderungen deklarieren, fügen auch Parameter, Validierungen, usw. zu Ihren *Pfadoperationen* hinzu. + +**FastAPI** kümmert sich darum, alles zum OpenAPI-Schema hinzuzufügen, damit es in den interaktiven Dokumentationssystemen angezeigt wird. diff --git a/docs/de/docs/tutorial/dependencies/sub-dependencies.md b/docs/de/docs/tutorial/dependencies/sub-dependencies.md new file mode 100644 index 000000000..66bdc7043 --- /dev/null +++ b/docs/de/docs/tutorial/dependencies/sub-dependencies.md @@ -0,0 +1,105 @@ +# Unterabhängigkeiten + +Sie können Abhängigkeiten erstellen, die **Unterabhängigkeiten** haben. + +Diese können so **tief** verschachtelt sein, wie nötig. + +**FastAPI** kümmert sich darum, sie aufzulösen. + +## Erste Abhängigkeit, „Dependable“ + +Sie könnten eine erste Abhängigkeit („Dependable“) wie folgt erstellen: + +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *} + +Diese deklariert einen optionalen Abfrageparameter `q` vom Typ `str` und gibt ihn dann einfach zurück. + +Das ist recht einfach (nicht sehr nützlich), hilft uns aber dabei, uns auf die Funktionsweise der Unterabhängigkeiten zu konzentrieren. + +## Zweite Abhängigkeit, „Dependable“ und „Dependant“ + +Dann können Sie eine weitere Abhängigkeitsfunktion (ein „Dependable“) erstellen, die gleichzeitig eine eigene Abhängigkeit deklariert (also auch ein „Dependant“ ist): + +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *} + +Betrachten wir die deklarierten Parameter: + +* Obwohl diese Funktion selbst eine Abhängigkeit ist („Dependable“, etwas hängt von ihr ab), deklariert sie auch eine andere Abhängigkeit („Dependant“, sie hängt von etwas anderem ab). + * Sie hängt von `query_extractor` ab und weist den von diesem zurückgegebenen Wert dem Parameter `q` zu. +* Sie deklariert außerdem ein optionales `last_query`-Cookie, ein `str`. + * Wenn der Benutzer keine Query `q` übermittelt hat, verwenden wir die zuletzt übermittelte Query, die wir zuvor in einem Cookie gespeichert haben. + +## Die Abhängigkeit verwenden + +Diese Abhängigkeit verwenden wir nun wie folgt: + +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *} + +/// info + +Beachten Sie, dass wir in der *Pfadoperation-Funktion* nur eine einzige Abhängigkeit deklarieren, den `query_or_cookie_extractor`. + +Aber **FastAPI** wird wissen, dass es zuerst `query_extractor` auflösen muss, um dessen Resultat `query_or_cookie_extractor` zu übergeben, wenn dieses aufgerufen wird. + +/// + +```mermaid +graph TB + +query_extractor(["query_extractor"]) +query_or_cookie_extractor(["query_or_cookie_extractor"]) + +read_query["/items/"] + +query_extractor --> query_or_cookie_extractor --> read_query +``` + +## Dieselbe Abhängigkeit mehrmals verwenden + +Wenn eine Ihrer Abhängigkeiten mehrmals für dieselbe *Pfadoperation* deklariert wird, beispielsweise wenn mehrere Abhängigkeiten eine gemeinsame Unterabhängigkeit haben, wird **FastAPI** diese Unterabhängigkeit nur einmal pro Request aufrufen. + +Und es speichert den zurückgegebenen Wert in einem „Cache“ und übergibt diesen gecachten Wert an alle „Dependanten“, die ihn in diesem spezifischen Request benötigen, anstatt die Abhängigkeit mehrmals für denselben Request aufzurufen. + +In einem fortgeschrittenen Szenario, bei dem Sie wissen, dass die Abhängigkeit bei jedem Schritt (möglicherweise mehrmals) in derselben Anfrage aufgerufen werden muss, anstatt den zwischengespeicherten Wert zu verwenden, können Sie den Parameter `use_cache=False` festlegen, wenn Sie `Depends` verwenden: + +//// tab | Python 3.8+ + +```Python hl_lines="1" +async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]): + return {"fresh_value": fresh_value} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | Tipp + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="1" +async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)): + return {"fresh_value": fresh_value} +``` + +//// + +## Zusammenfassung + +Abgesehen von all den ausgefallenen Wörtern, die hier verwendet werden, ist das **Dependency Injection**-System recht simpel. + +Einfach Funktionen, die genauso aussehen wie *Pfadoperation-Funktionen*. + +Dennoch ist es sehr mächtig und ermöglicht Ihnen die Deklaration beliebig tief verschachtelter Abhängigkeits-„Graphen“ (Bäume). + +/// tip | Tipp + +All dies scheint angesichts dieser einfachen Beispiele möglicherweise nicht so nützlich zu sein. + +Aber Sie werden in den Kapiteln über **Sicherheit** sehen, wie nützlich das ist. + +Und Sie werden auch sehen, wie viel Code Sie dadurch einsparen. + +/// diff --git a/docs/de/docs/tutorial/encoder.md b/docs/de/docs/tutorial/encoder.md new file mode 100644 index 000000000..5678d7b8f --- /dev/null +++ b/docs/de/docs/tutorial/encoder.md @@ -0,0 +1,35 @@ +# JSON-kompatibler Encoder + +Es gibt Fälle, da möchten Sie einen Datentyp (etwa ein Pydantic-Modell) in etwas konvertieren, das kompatibel mit JSON ist (etwa ein `dict`, eine `list`e, usw.). + +Zum Beispiel, wenn Sie es in einer Datenbank speichern möchten. + +Dafür bietet **FastAPI** eine Funktion `jsonable_encoder()`. + +## `jsonable_encoder` verwenden + +Stellen wir uns vor, Sie haben eine Datenbank `fake_db`, die nur JSON-kompatible Daten entgegennimmt. + +Sie akzeptiert zum Beispiel keine `datetime`-Objekte, da die nicht kompatibel mit JSON sind. + +Ein `datetime`-Objekt müsste also in einen `str` umgewandelt werden, der die Daten im ISO-Format enthält. + +Genauso würde die Datenbank kein Pydantic-Modell (ein Objekt mit Attributen) akzeptieren, sondern nur ein `dict`. + +Sie können für diese Fälle `jsonable_encoder` verwenden. + +Es nimmt ein Objekt entgegen, wie etwa ein Pydantic-Modell, und gibt eine JSON-kompatible Version zurück: + +{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *} + +In diesem Beispiel wird das Pydantic-Modell in ein `dict`, und das `datetime`-Objekt in ein `str` konvertiert. + +Das Resultat dieses Aufrufs ist etwas, das mit Pythons Standard-`json.dumps()` kodiert werden kann. + +Es wird also kein großer `str` zurückgegeben, der die Daten im JSON-Format (als String) enthält. Es wird eine Python-Standarddatenstruktur (z. B. ein `dict`) zurückgegeben, mit Werten und Unterwerten, die alle mit JSON kompatibel sind. + +/// note | Hinweis + +`jsonable_encoder` wird tatsächlich von **FastAPI** intern verwendet, um Daten zu konvertieren. Aber es ist in vielen anderen Szenarien hilfreich. + +/// diff --git a/docs/de/docs/tutorial/extra-data-types.md b/docs/de/docs/tutorial/extra-data-types.md new file mode 100644 index 000000000..334f32f7b --- /dev/null +++ b/docs/de/docs/tutorial/extra-data-types.md @@ -0,0 +1,62 @@ +# Zusätzliche Datentypen + +Bisher haben Sie gängige Datentypen verwendet, wie zum Beispiel: + +* `int` +* `float` +* `str` +* `bool` + +Sie können aber auch komplexere Datentypen verwenden. + +Und Sie haben immer noch dieselbe Funktionalität wie bisher gesehen: + +* Großartige Editor-Unterstützung. +* Datenkonvertierung bei eingehenden Requests. +* Datenkonvertierung für Response-Daten. +* Datenvalidierung. +* Automatische Annotation und Dokumentation. + +## Andere Datentypen + +Hier sind einige der zusätzlichen Datentypen, die Sie verwenden können: + +* `UUID`: + * Ein standardmäßiger „universell eindeutiger Bezeichner“ („Universally Unique Identifier“), der in vielen Datenbanken und Systemen als ID üblich ist. + * Wird in Requests und Responses als `str` dargestellt. +* `datetime.datetime`: + * Ein Python-`datetime.datetime`. + * Wird in Requests und Responses als `str` im ISO 8601-Format dargestellt, etwa: `2008-09-15T15:53:00+05:00`. +* `datetime.date`: + * Python-`datetime.date`. + * Wird in Requests und Responses als `str` im ISO 8601-Format dargestellt, etwa: `2008-09-15`. +* `datetime.time`: + * Ein Python-`datetime.time`. + * Wird in Requests und Responses als `str` im ISO 8601-Format dargestellt, etwa: `14:23:55.003`. +* `datetime.timedelta`: + * Ein Python-`datetime.timedelta`. + * Wird in Requests und Responses als `float` der Gesamtsekunden dargestellt. + * Pydantic ermöglicht auch die Darstellung als „ISO 8601 Zeitdifferenz-Kodierung“, Weitere Informationen finden Sie in der Dokumentation. +* `frozenset`: + * Wird in Requests und Responses wie ein `set` behandelt: + * Bei Requests wird eine Liste gelesen, Duplikate entfernt und in ein `set` umgewandelt. + * Bei Responses wird das `set` in eine `list`e umgewandelt. + * Das generierte Schema zeigt an, dass die `set`-Werte eindeutig sind (unter Verwendung von JSON Schemas `uniqueItems`). +* `bytes`: + * Standard-Python-`bytes`. + * In Requests und Responses werden sie als `str` behandelt. + * Das generierte Schema wird anzeigen, dass es sich um einen `str` mit `binary` „Format“ handelt. +* `Decimal`: + * Standard-Python-`Decimal`. + * In Requests und Responses wird es wie ein `float` behandelt. +* Sie können alle gültigen Pydantic-Datentypen hier überprüfen: Pydantic data types. + +## Beispiel + +Hier ist ein Beispiel für eine *Pfadoperation* mit Parametern, die einige der oben genannten Typen verwenden. + +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *} + +Beachten Sie, dass die Parameter innerhalb der Funktion ihren natürlichen Datentyp haben und Sie beispielsweise normale Datumsmanipulationen durchführen können, wie zum Beispiel: + +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *} diff --git a/docs/de/docs/tutorial/extra-models.md b/docs/de/docs/tutorial/extra-models.md new file mode 100644 index 000000000..6aad1c0f4 --- /dev/null +++ b/docs/de/docs/tutorial/extra-models.md @@ -0,0 +1,219 @@ +# Extramodelle + +Fahren wir beim letzten Beispiel fort. Es gibt normalerweise mehrere zusammengehörende Modelle. + +Insbesondere Benutzermodelle, denn: + +* Das **hereinkommende Modell** sollte ein Passwort haben können. +* Das **herausgehende Modell** sollte kein Passwort haben. +* Das **Datenbankmodell** sollte wahrscheinlich ein gehashtes Passwort haben. + +/// danger | Gefahr + +Speichern Sie niemals das Klartext-Passwort eines Benutzers. Speichern Sie immer den „sicheren Hash“, den Sie verifizieren können. + +Falls Ihnen das nichts sagt, in den [Sicherheits-Kapiteln](security/simple-oauth2.md#passwort-hashing){.internal-link target=_blank} werden Sie lernen, was ein „Passwort-Hash“ ist. + +/// + +## Mehrere Modelle + +Hier der generelle Weg, wie die Modelle mit ihren Passwort-Feldern aussehen könnten, und an welchen Orten sie verwendet werden würden. + +{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *} + +/// info + +In Pydantic v1 hieß diese Methode `.dict()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_dump()` umbenannt. + +Die Beispiele hier verwenden `.dict()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_dump()` verwenden, wenn Sie Pydantic v2 verwenden können. + +/// + +### Über `**user_in.dict()` + +#### Pydantic's `.dict()` + +`user_in` ist ein Pydantic-Modell der Klasse `UserIn`. + +Pydantic-Modelle haben eine `.dict()`-Methode, die ein `dict` mit den Daten des Modells zurückgibt. + +Wenn wir also ein Pydantic-Objekt `user_in` erstellen, etwa so: + +```Python +user_in = UserIn(username="john", password="secret", email="john.doe@example.com") +``` + +und wir rufen seine `.dict()`-Methode auf: + +```Python +user_dict = user_in.dict() +``` + +dann haben wir jetzt in der Variable `user_dict` ein `dict` mit den gleichen Daten (es ist ein `dict` statt eines Pydantic-Modellobjekts). + +Wenn wir es ausgeben: + +```Python +print(user_dict) +``` + +bekommen wir ein Python-`dict`: + +```Python +{ + 'username': 'john', + 'password': 'secret', + 'email': 'john.doe@example.com', + 'full_name': None, +} +``` + +#### Ein `dict` entpacken + +Wenn wir ein `dict` wie `user_dict` nehmen, und es einer Funktion (oder Klassenmethode) mittels `**user_dict` übergeben, wird Python es „entpacken“. Es wird die Schlüssel und Werte von `user_dict` direkt als Schlüsselwort-Argumente übergeben. + +Wenn wir also das `user_dict` von oben nehmen und schreiben: + +```Python +UserInDB(**user_dict) +``` + +dann ist das ungefähr äquivalent zu: + +```Python +UserInDB( + username="john", + password="secret", + email="john.doe@example.com", + full_name=None, +) +``` + +Oder, präziser, `user_dict` wird direkt verwendet, welche Werte es auch immer haben mag: + +```Python +UserInDB( + username = user_dict["username"], + password = user_dict["password"], + email = user_dict["email"], + full_name = user_dict["full_name"], +) +``` + +#### Ein Pydantic-Modell aus den Inhalten eines anderen erstellen. + +Da wir in obigem Beispiel `user_dict` mittels `user_in.dict()` erzeugt haben, ist dieser Code: + +```Python +user_dict = user_in.dict() +UserInDB(**user_dict) +``` + +äquivalent zu: + +```Python +UserInDB(**user_in.dict()) +``` + +... weil `user_in.dict()` ein `dict` ist, und dann lassen wir Python es „entpacken“, indem wir es `UserInDB` übergeben, mit vorangestelltem `**`. + +Wir erhalten also ein Pydantic-Modell aus den Daten eines anderen Pydantic-Modells. + +#### Ein `dict` entpacken und zusätzliche Schlüsselwort-Argumente + +Und dann fügen wir ein noch weiteres Schlüsselwort-Argument hinzu, `hashed_password=hashed_password`: + +```Python +UserInDB(**user_in.dict(), hashed_password=hashed_password) +``` + +... was am Ende ergibt: + +```Python +UserInDB( + username = user_dict["username"], + password = user_dict["password"], + email = user_dict["email"], + full_name = user_dict["full_name"], + hashed_password = hashed_password, +) +``` + +/// warning | Achtung + +Die Hilfsfunktionen `fake_password_hasher` und `fake_save_user` demonstrieren nur den möglichen Fluss der Daten und bieten natürlich keine echte Sicherheit. + +/// + +## Verdopplung vermeiden + +Reduzierung von Code-Verdoppelung ist eine der Kern-Ideen von **FastAPI**. + +Weil Verdoppelung von Code die Wahrscheinlichkeit von Fehlern, Sicherheitsproblemen, Desynchronisation (Code wird nur an einer Stelle verändert, aber nicht an einer anderen), usw. erhöht. + +Unsere Modelle teilen alle eine Menge der Daten und verdoppeln Attribut-Namen und -Typen. + +Das können wir besser machen. + +Wir deklarieren ein `UserBase`-Modell, das als Basis für unsere anderen Modelle dient. Dann können wir Unterklassen erstellen, die seine Attribute (Typdeklarationen, Validierungen, usw.) erben. + +Die ganze Datenkonvertierung, -validierung, -dokumentation, usw. wird immer noch wie gehabt funktionieren. + +Auf diese Weise beschreiben wir nur noch die Unterschiede zwischen den Modellen (mit Klartext-`password`, mit `hashed_password`, und ohne Passwort): + +{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *} + +## `Union`, oder `anyOf` + +Sie können deklarieren, dass eine Response eine `Union` mehrerer Typen ist, sprich, einer dieser Typen. + +Das wird in OpenAPI mit `anyOf` angezeigt. + +Um das zu tun, verwenden Sie Pythons Standard-Typhinweis `typing.Union`: + +/// note | Hinweis + +Listen Sie, wenn Sie eine `Union` definieren, denjenigen Typ zuerst, der am spezifischsten ist, gefolgt von den weniger spezifischen Typen. Im Beispiel oben, in `Union[PlaneItem, CarItem]` also den spezifischeren `PlaneItem` vor dem weniger spezifischen `CarItem`. + +/// + +{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *} + +### `Union` in Python 3.10 + +In diesem Beispiel übergeben wir dem Argument `response_model` den Wert `Union[PlaneItem, CarItem]`. + +Da wir es als **Wert einem Argument überreichen**, statt es als **Typannotation** zu verwenden, müssen wir `Union` verwenden, selbst in Python 3.10. + +Wenn es eine Typannotation gewesen wäre, hätten wir auch den vertikalen Trennstrich verwenden können, wie in: + +```Python +some_variable: PlaneItem | CarItem +``` + +Aber wenn wir das in der Zuweisung `response_model=PlaneItem | CarItem` machen, erhalten wir eine Fehlermeldung, da Python versucht, eine **ungültige Operation** zwischen `PlaneItem` und `CarItem` durchzuführen, statt es als Typannotation zu interpretieren. + +## Listen von Modellen + +Genauso können Sie eine Response deklarieren, die eine Liste von Objekten ist. + +Verwenden Sie dafür Pythons Standard `typing.List` (oder nur `list` in Python 3.9 und darüber): + +{* ../../docs_src/extra_models/tutorial004_py39.py hl[18] *} + +## Response mit beliebigem `dict` + +Sie könne auch eine Response deklarieren, die ein beliebiges `dict` zurückgibt, bei dem nur die Typen der Schlüssel und der Werte bekannt sind, ohne ein Pydantic-Modell zu verwenden. + +Das ist nützlich, wenn Sie die gültigen Feld-/Attribut-Namen von vorneherein nicht wissen (was für ein Pydantic-Modell notwendig ist). + +In diesem Fall können Sie `typing.Dict` verwenden (oder nur `dict` in Python 3.9 und darüber): + +{* ../../docs_src/extra_models/tutorial005_py39.py hl[6] *} + +## Zusammenfassung + +Verwenden Sie gerne mehrere Pydantic-Modelle und vererben Sie je nach Bedarf. + +Sie brauchen kein einzelnes Datenmodell pro Einheit, wenn diese Einheit verschiedene Zustände annehmen kann. So wie unsere Benutzer-„Einheit“, welche einen Zustand mit `password`, einen mit `password_hash` und einen ohne Passwort hatte. diff --git a/docs/de/docs/tutorial/first-steps.md b/docs/de/docs/tutorial/first-steps.md index 27ba3ec16..3104c8d61 100644 --- a/docs/de/docs/tutorial/first-steps.md +++ b/docs/de/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ Die einfachste FastAPI-Datei könnte wie folgt aussehen: -```Python -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} Kopieren Sie dies in eine Datei `main.py`. @@ -24,12 +22,15 @@ $ uvicorn main:app --reload
-!!! note "Hinweis" - Der Befehl `uvicorn main:app` bezieht sich auf: +/// note | Hinweis + +Der Befehl `uvicorn main:app` bezieht sich auf: + +* `main`: die Datei `main.py` (das sogenannte Python-„Modul“). +* `app`: das Objekt, welches in der Datei `main.py` mit der Zeile `app = FastAPI()` erzeugt wurde. +* `--reload`: lässt den Server nach Codeänderungen neu starten. Verwenden Sie das nur während der Entwicklung. - * `main`: die Datei `main.py` (das sogenannte Python-„Modul“). - * `app`: das Objekt, welches in der Datei `main.py` mit der Zeile `app = FastAPI()` erzeugt wurde. - * `--reload`: lässt den Server nach Codeänderungen neu starten. Verwenden Sie das nur während der Entwicklung. +/// In der Konsolenausgabe sollte es eine Zeile geben, die ungefähr so aussieht: @@ -130,22 +131,21 @@ Ebenfalls können Sie es verwenden, um automatisch Code für Clients zu generier ### Schritt 1: Importieren von `FastAPI` -```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI` ist eine Python-Klasse, die die gesamte Funktionalität für Ihre API bereitstellt. -!!! note "Technische Details" - `FastAPI` ist eine Klasse, die direkt von `Starlette` erbt. +/// note | Technische Details + +`FastAPI` ist eine Klasse, die direkt von `Starlette` erbt. - Sie können alle Starlette-Funktionalitäten auch mit `FastAPI` nutzen. +Sie können alle Starlette-Funktionalitäten auch mit `FastAPI` nutzen. + +/// ### Schritt 2: Erzeugen einer `FastAPI`-„Instanz“ -```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[3] *} In diesem Beispiel ist die Variable `app` eine „Instanz“ der Klasse `FastAPI`. @@ -165,9 +165,7 @@ $ uvicorn main:app --reload Wenn Sie Ihre Anwendung wie folgt erstellen: -```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} -``` +{* ../../docs_src/first_steps/tutorial002.py hl[3] *} Und in eine Datei `main.py` einfügen, dann würden Sie `uvicorn` wie folgt aufrufen: @@ -199,8 +197,11 @@ https://example.com/items/foo /items/foo ``` -!!! info - Ein „Pfad“ wird häufig auch als „Endpunkt“ oder „Route“ bezeichnet. +/// info + +Ein „Pfad“ wird häufig auch als „Endpunkt“ oder „Route“ bezeichnet. + +/// Bei der Erstellung einer API ist der „Pfad“ die wichtigste Möglichkeit zur Trennung von „Anliegen“ und „Ressourcen“. @@ -241,25 +242,26 @@ Wir werden sie auch „**Operationen**“ nennen. #### Definieren eines *Pfadoperation-Dekorators* -```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[6] *} Das `@app.get("/")` sagt **FastAPI**, dass die Funktion direkt darunter für die Bearbeitung von Anfragen zuständig ist, die an: * den Pfad `/` * unter der Verwendung der get-Operation gehen -!!! info "`@decorator` Information" - Diese `@something`-Syntax wird in Python „Dekorator“ genannt. +/// info | `@decorator` Information + +Diese `@something`-Syntax wird in Python „Dekorator“ genannt. + +Sie platzieren ihn über einer Funktion. Wie ein hübscher, dekorativer Hut (daher kommt wohl der Begriff). - Sie platzieren ihn über einer Funktion. Wie ein hübscher, dekorativer Hut (daher kommt wohl der Begriff). +Ein „Dekorator“ nimmt die darunter stehende Funktion und macht etwas damit. - Ein „Dekorator“ nimmt die darunter stehende Funktion und macht etwas damit. +In unserem Fall teilt dieser Dekorator **FastAPI** mit, dass die folgende Funktion mit dem **Pfad** `/` und der **Operation** `get` zusammenhängt. - In unserem Fall teilt dieser Dekorator **FastAPI** mit, dass die folgende Funktion mit dem **Pfad** `/` und der **Operation** `get` zusammenhängt. +Dies ist der „**Pfadoperation-Dekorator**“. - Dies ist der „**Pfadoperation-Dekorator**“. +/// Sie können auch die anderen Operationen verwenden: @@ -274,14 +276,17 @@ Oder die exotischeren: * `@app.patch()` * `@app.trace()` -!!! tip "Tipp" - Es steht Ihnen frei, jede Operation (HTTP-Methode) so zu verwenden, wie Sie es möchten. +/// tip | Tipp + +Es steht Ihnen frei, jede Operation (HTTP-Methode) so zu verwenden, wie Sie es möchten. + +**FastAPI** erzwingt keine bestimmte Bedeutung. - **FastAPI** erzwingt keine bestimmte Bedeutung. +Die hier aufgeführten Informationen dienen als Leitfaden und sind nicht verbindlich. - Die hier aufgeführten Informationen dienen als Leitfaden und sind nicht verbindlich. +Wenn Sie beispielsweise GraphQL verwenden, führen Sie normalerweise alle Aktionen nur mit „POST“-Operationen durch. - Wenn Sie beispielsweise GraphQL verwenden, führen Sie normalerweise alle Aktionen nur mit „POST“-Operationen durch. +/// ### Schritt 4: Definieren der **Pfadoperation-Funktion** @@ -291,9 +296,7 @@ Das ist unsere „**Pfadoperation-Funktion**“: * **Operation**: ist `get`. * **Funktion**: ist die Funktion direkt unter dem „Dekorator“ (unter `@app.get("/")`). -```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[7] *} Dies ist eine Python-Funktion. @@ -305,18 +308,17 @@ In diesem Fall handelt es sich um eine `async`-Funktion. Sie könnten sie auch als normale Funktion anstelle von `async def` definieren: -```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} -``` +{* ../../docs_src/first_steps/tutorial003.py hl[7] *} + +/// note | Hinweis -!!! note "Hinweis" - Wenn Sie den Unterschied nicht kennen, lesen Sie [Async: *„In Eile?“*](../async.md#in-eile){.internal-link target=_blank}. +Wenn Sie den Unterschied nicht kennen, lesen Sie [Async: *„In Eile?“*](../async.md#in-eile){.internal-link target=_blank}. + +/// ### Schritt 5: den Inhalt zurückgeben -```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[8] *} Sie können ein `dict`, eine `list`, einzelne Werte wie `str`, `int`, usw. zurückgeben. diff --git a/docs/de/docs/tutorial/handling-errors.md b/docs/de/docs/tutorial/handling-errors.md new file mode 100644 index 000000000..31bc6d328 --- /dev/null +++ b/docs/de/docs/tutorial/handling-errors.md @@ -0,0 +1,255 @@ +# Fehlerbehandlung + +Es gibt viele Situationen, in denen Sie einem Client, der Ihre API benutzt, einen Fehler zurückgeben müssen. + +Dieser Client könnte ein Browser mit einem Frontend, Code von jemand anderem, ein IoT-Gerät, usw., sein. + +Sie müssten beispielsweise einem Client sagen: + +* Dass er nicht die notwendigen Berechtigungen hat, eine Aktion auszuführen. +* Dass er zu einer Ressource keinen Zugriff hat. +* Dass die Ressource, auf die er zugreifen möchte, nicht existiert. +* usw. + +In diesen Fällen geben Sie normalerweise einen **HTTP-Statuscode** im Bereich **400** (400 bis 499) zurück. + +Das ist vergleichbar mit den HTTP-Statuscodes im Bereich 200 (von 200 bis 299). Diese „200“er Statuscodes bedeuten, dass der Request in einem bestimmten Aspekt ein „Success“ („Erfolg“) war. + +Die Statuscodes im 400er-Bereich bedeuten hingegen, dass es einen Fehler gab. + +Erinnern Sie sich an all diese **404 Not Found** Fehler (und Witze)? + +## `HTTPException` verwenden + +Um HTTP-Responses mit Fehlern zum Client zurückzugeben, verwenden Sie `HTTPException`. + +### `HTTPException` importieren + +{* ../../docs_src/handling_errors/tutorial001.py hl[1] *} + +### Eine `HTTPException` in Ihrem Code auslösen + +`HTTPException` ist eine normale Python-Exception mit einigen zusätzlichen Daten, die für APIs relevant sind. + +Weil es eine Python-Exception ist, geben Sie sie nicht zurück, (`return`), sondern Sie lösen sie aus (`raise`). + +Das bedeutet auch, wenn Sie in einer Hilfsfunktion sind, die Sie von ihrer *Pfadoperation-Funktion* aus aufrufen, und Sie lösen eine `HTTPException` von innerhalb dieser Hilfsfunktion aus, dann wird der Rest der *Pfadoperation-Funktion* nicht ausgeführt, sondern der Request wird sofort abgebrochen und der HTTP-Error der `HTTP-Exception` wird zum Client gesendet. + +Der Vorteil, eine Exception auszulösen (`raise`), statt sie zurückzugeben (`return`) wird im Abschnitt über Abhängigkeiten und Sicherheit klarer werden. + +Im folgenden Beispiel lösen wir, wenn der Client eine ID anfragt, die nicht existiert, eine Exception mit dem Statuscode `404` aus. + +{* ../../docs_src/handling_errors/tutorial001.py hl[11] *} + +### Die resultierende Response + +Wenn der Client `http://example.com/items/foo` anfragt (ein `item_id` `"foo"`), erhält dieser Client einen HTTP-Statuscode 200 und folgende JSON-Response: + +```JSON +{ + "item": "The Foo Wrestlers" +} +``` + +Aber wenn der Client `http://example.com/items/bar` anfragt (ein nicht-existierendes `item_id` `"bar"`), erhält er einen HTTP-Statuscode 404 (der „Not Found“-Fehler), und eine JSON-Response wie folgt: + +```JSON +{ + "detail": "Item not found" +} +``` + +/// tip | Tipp + +Wenn Sie eine `HTTPException` auslösen, können Sie dem Parameter `detail` jeden Wert übergeben, der nach JSON konvertiert werden kann, nicht nur `str`. + +Zum Beispiel ein `dict`, eine `list`, usw. + +Das wird automatisch von **FastAPI** gehandhabt und der Wert nach JSON konvertiert. + +/// + +## Benutzerdefinierte Header hinzufügen + +Es gibt Situationen, da ist es nützlich, dem HTTP-Error benutzerdefinierte Header hinzufügen zu können, etwa in einigen Sicherheitsszenarien. + +Sie müssen das wahrscheinlich nicht direkt in ihrem Code verwenden. + +Aber falls es in einem fortgeschrittenen Szenario notwendig ist, können Sie benutzerdefinierte Header wie folgt hinzufügen: + +{* ../../docs_src/handling_errors/tutorial002.py hl[14] *} + +## Benutzerdefinierte Exceptionhandler definieren + +Sie können benutzerdefinierte Exceptionhandler hinzufügen, mithilfe derselben Werkzeuge für Exceptions von Starlette. + +Nehmen wir an, Sie haben eine benutzerdefinierte Exception `UnicornException`, die Sie (oder eine Bibliothek, die Sie verwenden) `raise`n könnten. + +Und Sie möchten diese Exception global mit FastAPI handhaben. + +Sie könnten einen benutzerdefinierten Exceptionhandler mittels `@app.exception_handler()` hinzufügen: + +{* ../../docs_src/handling_errors/tutorial003.py hl[5:7,13:18,24] *} + +Wenn Sie nun `/unicorns/yolo` anfragen, `raise`d die *Pfadoperation* eine `UnicornException`. + +Aber diese wird von `unicorn_exception_handler` gehandhabt. + +Sie erhalten also einen sauberen Error mit einem Statuscode `418` und dem JSON-Inhalt: + +```JSON +{"message": "Oops! yolo did something. There goes a rainbow..."} +``` + +/// note | Technische Details + +Sie können auch `from starlette.requests import Request` und `from starlette.responses import JSONResponse` verwenden. + +**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. Das Gleiche gilt für `Request`. + +/// + +## Die Default-Exceptionhandler überschreiben + +**FastAPI** hat einige Default-Exceptionhandler. + +Diese Handler kümmern sich darum, Default-JSON-Responses zurückzugeben, wenn Sie eine `HTTPException` `raise`n, und wenn der Request ungültige Daten enthält. + +Sie können diese Exceptionhandler mit ihren eigenen überschreiben. + +### Requestvalidierung-Exceptions überschreiben + +Wenn ein Request ungültige Daten enthält, löst **FastAPI** intern einen `RequestValidationError` aus. + +Und bietet auch einen Default-Exceptionhandler dafür. + +Um diesen zu überschreiben, importieren Sie den `RequestValidationError` und verwenden Sie ihn in `@app.exception_handler(RequestValidationError)`, um Ihren Exceptionhandler zu dekorieren. + +Der Exceptionhandler wird einen `Request` und die Exception entgegennehmen. + +{* ../../docs_src/handling_errors/tutorial004.py hl[2,14:16] *} + +Wenn Sie nun `/items/foo` besuchen, erhalten Sie statt des Default-JSON-Errors: + +```JSON +{ + "detail": [ + { + "loc": [ + "path", + "item_id" + ], + "msg": "value is not a valid integer", + "type": "type_error.integer" + } + ] +} +``` + +eine Textversion: + +``` +1 validation error +path -> item_id + value is not a valid integer (type=type_error.integer) +``` + +#### `RequestValidationError` vs. `ValidationError` + +/// warning | Achtung + +Das folgende sind technische Details, die Sie überspringen können, wenn sie für Sie nicht wichtig sind. + +/// + +`RequestValidationError` ist eine Unterklasse von Pydantics `ValidationError`. + +**FastAPI** verwendet diesen, sodass Sie, wenn Sie ein Pydantic-Modell für `response_model` verwenden, und ihre Daten fehlerhaft sind, einen Fehler in ihrem Log sehen. + +Aber der Client/Benutzer sieht ihn nicht. Stattdessen erhält der Client einen „Internal Server Error“ mit einem HTTP-Statuscode `500`. + +Das ist, wie es sein sollte, denn wenn Sie einen Pydantic-`ValidationError` in Ihrer *Response* oder irgendwo sonst in ihrem Code haben (es sei denn, im *Request* des Clients), ist das tatsächlich ein Bug in ihrem Code. + +Und während Sie den Fehler beheben, sollten ihre Clients/Benutzer keinen Zugriff auf interne Informationen über den Fehler haben, da das eine Sicherheitslücke aufdecken könnte. + +### den `HTTPException`-Handler überschreiben + +Genauso können Sie den `HTTPException`-Handler überschreiben. + +Zum Beispiel könnten Sie eine Klartext-Response statt JSON für diese Fehler zurückgeben wollen: + +{* ../../docs_src/handling_errors/tutorial004.py hl[3:4,9:11,22] *} + +/// note | Technische Details + +Sie können auch `from starlette.responses import PlainTextResponse` verwenden. + +**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. + +/// + +### Den `RequestValidationError`-Body verwenden + +Der `RequestValidationError` enthält den empfangenen `body` mit den ungültigen Daten. + +Sie könnten diesen verwenden, während Sie Ihre Anwendung entwickeln, um den Body zu loggen und zu debuggen, ihn zum Benutzer zurückzugeben, usw. + +{* ../../docs_src/handling_errors/tutorial005.py hl[14] *} + +Jetzt versuchen Sie, einen ungültigen Artikel zu senden: + +```JSON +{ + "title": "towel", + "size": "XL" +} +``` + +Sie erhalten eine Response, die Ihnen sagt, dass die Daten ungültig sind, und welche den empfangenen Body enthält. + +```JSON hl_lines="12-15" +{ + "detail": [ + { + "loc": [ + "body", + "size" + ], + "msg": "value is not a valid integer", + "type": "type_error.integer" + } + ], + "body": { + "title": "towel", + "size": "XL" + } +} +``` + +#### FastAPIs `HTTPException` vs. Starlettes `HTTPException` + +**FastAPI** hat seine eigene `HTTPException`. + +Und **FastAPI**s `HTTPException`-Fehlerklasse erbt von Starlettes `HTTPException`-Fehlerklasse. + +Der einzige Unterschied besteht darin, dass **FastAPIs** `HTTPException` alles für das Feld `detail` akzeptiert, was nach JSON konvertiert werden kann, während Starlettes `HTTPException` nur Strings zulässt. + +Sie können also weiterhin **FastAPI**s `HTTPException` wie üblich in Ihrem Code auslösen. + +Aber wenn Sie einen Exceptionhandler registrieren, registrieren Sie ihn für Starlettes `HTTPException`. + +Auf diese Weise wird Ihr Handler, wenn irgendein Teil von Starlettes internem Code, oder eine Starlette-Erweiterung, oder -Plugin eine Starlette-`HTTPException` auslöst, in der Lage sein, diese zu fangen und zu handhaben. + +Damit wir in diesem Beispiel beide `HTTPException`s im selben Code haben können, benennen wir Starlettes Exception um zu `StarletteHTTPException`: + +```Python +from starlette.exceptions import HTTPException as StarletteHTTPException +``` + +### **FastAPI**s Exceptionhandler wiederverwenden + +Wenn Sie die Exception zusammen mit denselben Default-Exceptionhandlern von **FastAPI** verwenden möchten, können Sie die Default-Exceptionhandler von `fastapi.Exception_handlers` importieren und wiederverwenden: + +{* ../../docs_src/handling_errors/tutorial006.py hl[2:5,15,21] *} + +In diesem Beispiel `print`en Sie nur den Fehler mit einer sehr ausdrucksstarken Nachricht, aber Sie sehen, worauf wir hinauswollen. Sie können mit der Exception etwas machen und dann einfach die Default-Exceptionhandler wiederverwenden. diff --git a/docs/de/docs/tutorial/header-params.md b/docs/de/docs/tutorial/header-params.md new file mode 100644 index 000000000..8283cc929 --- /dev/null +++ b/docs/de/docs/tutorial/header-params.md @@ -0,0 +1,91 @@ +# Header-Parameter + +So wie `Query`-, `Path`-, und `Cookie`-Parameter können Sie auch Header-Parameter definieren. + +## `Header` importieren + +Importieren Sie zuerst `Header`: + +{* ../../docs_src/header_params/tutorial001_an_py310.py hl[3] *} + +## `Header`-Parameter deklarieren + +Dann deklarieren Sie Ihre Header-Parameter, auf die gleiche Weise, wie Sie auch `Path`-, `Query`-, und `Cookie`-Parameter deklarieren. + +Der erste Wert ist der Typ. Sie können `Header` die gehabten Extra Validierungs- und Beschreibungsparameter hinzufügen. Danach können Sie einen Defaultwert vergeben: + +{* ../../docs_src/header_params/tutorial001_an_py310.py hl[9] *} + +/// note | Technische Details + +`Header` ist eine Schwesterklasse von `Path`, `Query` und `Cookie`. Sie erbt von derselben gemeinsamen `Param`-Elternklasse. + +Aber erinnern Sie sich, dass, wenn Sie `Query`, `Path`, `Header` und andere von `fastapi` importieren, diese tatsächlich Funktionen sind, welche spezielle Klassen zurückgeben. + +/// + +/// info + +Um Header zu deklarieren, müssen Sie `Header` verwenden, da diese Parameter sonst als Query-Parameter interpretiert werden würden. + +/// + +## Automatische Konvertierung + +`Header` hat weitere Funktionalität, zusätzlich zu der, die `Path`, `Query` und `Cookie` bereitstellen. + +Die meisten Standard-Header benutzen als Trennzeichen einen Bindestrich, auch bekannt als das „Minus-Symbol“ (`-`). + +Aber eine Variable wie `user-agent` ist in Python nicht gültig. + +Darum wird `Header` standardmäßig in Parameternamen den Unterstrich (`_`) zu einem Bindestrich (`-`) konvertieren. + +HTTP-Header sind außerdem unabhängig von Groß-/Kleinschreibung, darum können Sie sie mittels der Standard-Python-Schreibweise deklarieren (auch bekannt als "snake_case"). + +Sie können also `user_agent` schreiben, wie Sie es normalerweise in Python-Code machen würden, statt etwa die ersten Buchstaben groß zu schreiben, wie in `User_Agent`. + +Wenn Sie aus irgendeinem Grund das automatische Konvertieren von Unterstrichen zu Bindestrichen abschalten möchten, setzen Sie den Parameter `convert_underscores` auf `False`. + +{* ../../docs_src/header_params/tutorial002_an_py310.py hl[10] *} + +/// warning | Achtung + +Bevor Sie `convert_underscores` auf `False` setzen, bedenken Sie, dass manche HTTP-Proxys und Server die Verwendung von Headern mit Unterstrichen nicht erlauben. + +/// + +## Doppelte Header + +Es ist möglich, doppelte Header zu empfangen. Also den gleichen Header mit unterschiedlichen Werten. + +Sie können solche Fälle deklarieren, indem Sie in der Typdeklaration eine Liste verwenden. + +Sie erhalten dann alle Werte von diesem doppelten Header als Python-`list`e. + +Um zum Beispiel einen Header `X-Token` zu deklarieren, der mehrmals vorkommen kann, schreiben Sie: + +{* ../../docs_src/header_params/tutorial003_an_py310.py hl[9] *} + +Wenn Sie mit einer *Pfadoperation* kommunizieren, die zwei HTTP-Header sendet, wie: + +``` +X-Token: foo +X-Token: bar +``` + +Dann wäre die Response: + +```JSON +{ + "X-Token values": [ + "bar", + "foo" + ] +} +``` + +## Zusammenfassung + +Deklarieren Sie Header mittels `Header`, auf die gleiche Weise wie bei `Query`, `Path` und `Cookie`. + +Machen Sie sich keine Sorgen um Unterstriche in ihren Variablen, **FastAPI** wird sich darum kümmern, diese zu konvertieren. diff --git a/docs/de/docs/tutorial/index.md b/docs/de/docs/tutorial/index.md index dd7ed43bd..3cbfe37f4 100644 --- a/docs/de/docs/tutorial/index.md +++ b/docs/de/docs/tutorial/index.md @@ -1,6 +1,6 @@ -# Tutorial - Benutzerhandbuch - Intro +# Tutorial – Benutzerhandbuch -Diese Anleitung zeigt Ihnen Schritt für Schritt, wie Sie **FastAPI** mit den meisten Funktionen nutzen können. +Dieses Tutorial zeigt Ihnen Schritt für Schritt, wie Sie **FastAPI** und die meisten seiner Funktionen verwenden können. Jeder Abschnitt baut schrittweise auf den vorhergehenden auf. Diese Abschnitte sind aber nach einzelnen Themen gegliedert, sodass Sie direkt zu einem bestimmten Thema übergehen können, um Ihre speziellen API-Anforderungen zu lösen. @@ -12,7 +12,7 @@ Dadurch können Sie jederzeit zurückkommen und sehen genau das, was Sie benöt Alle Codeblöcke können kopiert und direkt verwendet werden (da es sich um getestete Python-Dateien handelt). -Um eines der Beispiele auszuführen, kopieren Sie den Code in die Datei `main.py`, und starten Sie `uvicorn` mit: +Um eines der Beispiele auszuführen, kopieren Sie den Code in eine Datei `main.py`, und starten Sie `uvicorn` mit:
@@ -50,31 +50,34 @@ $ pip install "fastapi[all]"
-...dies beinhaltet auch `uvicorn`, das Sie als Server verwenden können, auf dem Ihr Code läuft. +... das beinhaltet auch `uvicorn`, welchen Sie als Server verwenden können, der ihren Code ausführt. -!!! Hinweis - Sie können die Installation auch in einzelnen Schritten ausführen. +/// note | Hinweis - Dies werden Sie wahrscheinlich tun, wenn Sie Ihre Anwendung produktiv einsetzen möchten: +Sie können die einzelnen Teile auch separat installieren. - ``` - pip install fastapi - ``` +Das folgende würden Sie wahrscheinlich tun, wenn Sie Ihre Anwendung in der Produktion einsetzen: - Installieren Sie auch `uvicorn`, dies arbeitet als Server: +``` +pip install fastapi +``` + +Installieren Sie auch `uvicorn` als Server: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +Das gleiche gilt für jede der optionalen Abhängigkeiten, die Sie verwenden möchten. - Dasselbe gilt für jede der optionalen Abhängigkeiten, die Sie verwenden möchten. +/// -## Erweitertes Benutzerhandbuch +## Handbuch für fortgeschrittene Benutzer -Zusätzlich gibt es ein **Erweitertes Benutzerhandbuch**, dies können Sie später nach diesem **Tutorial - Benutzerhandbuch** lesen. +Es gibt auch ein **Handbuch für fortgeschrittene Benutzer**, welches Sie später nach diesem **Tutorial – Benutzerhandbuch** lesen können. -Das **Erweiterte Benutzerhandbuch** baut auf dieses Tutorial auf, verwendet dieselben Konzepte und bringt Ihnen zusätzliche Funktionen bei. +Das **Handbuch für fortgeschrittene Benutzer** baut auf diesem Tutorial auf, verwendet dieselben Konzepte und bringt Ihnen einige zusätzliche Funktionen bei. -Allerdings sollten Sie zuerst das **Tutorial - Benutzerhandbuch** lesen (was Sie gerade lesen). +Allerdings sollten Sie zuerst das **Tutorial – Benutzerhandbuch** lesen (was Sie hier gerade tun). -Es ist so konzipiert, dass Sie nur mit dem **Tutorial - Benutzerhandbuch** eine vollständige Anwendung erstellen können und diese dann je nach Bedarf mit einigen der zusätzlichen Ideen aus dem **Erweiterten Benutzerhandbuch** erweitern können. +Die Dokumentation ist so konzipiert, dass Sie mit dem **Tutorial – Benutzerhandbuch** eine vollständige Anwendung erstellen können und diese dann je nach Bedarf mit einigen der zusätzlichen Ideen aus dem **Handbuch für fortgeschrittene Benutzer** vervollständigen können. diff --git a/docs/de/docs/tutorial/metadata.md b/docs/de/docs/tutorial/metadata.md new file mode 100644 index 000000000..4809530be --- /dev/null +++ b/docs/de/docs/tutorial/metadata.md @@ -0,0 +1,120 @@ +# Metadaten und URLs der Dokumentationen + +Sie können mehrere Metadaten-Einstellungen für Ihre **FastAPI**-Anwendung konfigurieren. + +## Metadaten für die API + +Sie können die folgenden Felder festlegen, welche in der OpenAPI-Spezifikation und den Benutzeroberflächen der automatischen API-Dokumentation verwendet werden: + +| Parameter | Typ | Beschreibung | +|------------|------|-------------| +| `title` | `str` | Der Titel der API. | +| `summary` | `str` | Eine kurze Zusammenfassung der API. Verfügbar seit OpenAPI 3.1.0, FastAPI 0.99.0. | +| `description` | `str` | Eine kurze Beschreibung der API. Kann Markdown verwenden. | +| `version` | `string` | Die Version der API. Das ist die Version Ihrer eigenen Anwendung, nicht die von OpenAPI. Zum Beispiel `2.5.0`. | +| `terms_of_service` | `str` | Eine URL zu den Nutzungsbedingungen für die API. Falls angegeben, muss es sich um eine URL handeln. | +| `contact` | `dict` | Die Kontaktinformationen für die verfügbar gemachte API. Kann mehrere Felder enthalten.
contact-Felder
ParameterTypBeschreibung
namestrDer identifizierende Name der Kontaktperson/Organisation.
urlstrDie URL, die auf die Kontaktinformationen verweist. MUSS im Format einer URL vorliegen.
emailstrDie E-Mail-Adresse der Kontaktperson/Organisation. MUSS im Format einer E-Mail-Adresse vorliegen.
| +| `license_info` | `dict` | Die Lizenzinformationen für die verfügbar gemachte API. Kann mehrere Felder enthalten.
license_info-Felder
ParameterTypBeschreibung
namestrERFORDERLICH (wenn eine license_info festgelegt ist). Der für die API verwendete Lizenzname.
identifierstrEin SPDX-Lizenzausdruck für die API. Das Feld identifier und das Feld url schließen sich gegenseitig aus. Verfügbar seit OpenAPI 3.1.0, FastAPI 0.99.0.
urlstrEine URL zur Lizenz, die für die API verwendet wird. MUSS im Format einer URL vorliegen.
| + +Sie können diese wie folgt setzen: + +{* ../../docs_src/metadata/tutorial001.py hl[3:16,19:32] *} + +/// tip | Tipp + +Sie können Markdown in das Feld `description` schreiben und es wird in der Ausgabe gerendert. + +/// + +Mit dieser Konfiguration würde die automatische API-Dokumentation wie folgt aussehen: + + + +## Lizenz-ID + +Seit OpenAPI 3.1.0 und FastAPI 0.99.0 können Sie die `license_info` auch mit einem `identifier` anstelle einer `url` festlegen. + +Zum Beispiel: + +{* ../../docs_src/metadata/tutorial001_1.py hl[31] *} + +## Metadaten für Tags + +Sie können mit dem Parameter `openapi_tags` auch zusätzliche Metadaten für die verschiedenen Tags hinzufügen, die zum Gruppieren Ihrer Pfadoperationen verwendet werden. + +Es wird eine Liste benötigt, die für jedes Tag ein Dict enthält. + +Jedes Dict kann Folgendes enthalten: + +* `name` (**erforderlich**): ein `str` mit demselben Tag-Namen, den Sie im Parameter `tags` in Ihren *Pfadoperationen* und `APIRouter`n verwenden. +* `description`: ein `str` mit einer kurzen Beschreibung für das Tag. Sie kann Markdown enthalten und wird in der Benutzeroberfläche der Dokumentation angezeigt. +* `externalDocs`: ein `dict`, das externe Dokumentation beschreibt mit: + * `description`: ein `str` mit einer kurzen Beschreibung für die externe Dokumentation. + * `url` (**erforderlich**): ein `str` mit der URL für die externe Dokumentation. + +### Metadaten für Tags erstellen + +Versuchen wir das an einem Beispiel mit Tags für `users` und `items`. + +Erstellen Sie Metadaten für Ihre Tags und übergeben Sie sie an den Parameter `openapi_tags`: + +{* ../../docs_src/metadata/tutorial004.py hl[3:16,18] *} + +Beachten Sie, dass Sie Markdown in den Beschreibungen verwenden können. Beispielsweise wird „login“ in Fettschrift (**login**) und „fancy“ in Kursivschrift (_fancy_) angezeigt. + +/// tip | Tipp + +Sie müssen nicht für alle von Ihnen verwendeten Tags Metadaten hinzufügen. + +/// + +### Ihre Tags verwenden + +Verwenden Sie den Parameter `tags` mit Ihren *Pfadoperationen* (und `APIRouter`n), um diese verschiedenen Tags zuzuweisen: + +{* ../../docs_src/metadata/tutorial004.py hl[21,26] *} + +/// info + +Lesen Sie mehr zu Tags unter [Pfadoperation-Konfiguration](path-operation-configuration.md#tags){.internal-link target=_blank}. + +/// + +### Die Dokumentation anschauen + +Wenn Sie nun die Dokumentation ansehen, werden dort alle zusätzlichen Metadaten angezeigt: + + + +### Reihenfolge der Tags + +Die Reihenfolge der Tag-Metadaten-Dicts definiert auch die Reihenfolge, in der diese in der Benutzeroberfläche der Dokumentation angezeigt werden. + +Auch wenn beispielsweise `users` im Alphabet nach `items` kommt, wird es vor diesen angezeigt, da wir seine Metadaten als erstes Dict der Liste hinzugefügt haben. + +## OpenAPI-URL + +Standardmäßig wird das OpenAPI-Schema unter `/openapi.json` bereitgestellt. + +Sie können das aber mit dem Parameter `openapi_url` konfigurieren. + +Um beispielsweise festzulegen, dass es unter `/api/v1/openapi.json` bereitgestellt wird: + +{* ../../docs_src/metadata/tutorial002.py hl[3] *} + +Wenn Sie das OpenAPI-Schema vollständig deaktivieren möchten, können Sie `openapi_url=None` festlegen, wodurch auch die Dokumentationsbenutzeroberflächen deaktiviert werden, die es verwenden. + +## URLs der Dokumentationen + +Sie können die beiden enthaltenen Dokumentationsbenutzeroberflächen konfigurieren: + +* **Swagger UI**: bereitgestellt unter `/docs`. + * Sie können deren URL mit dem Parameter `docs_url` festlegen. + * Sie können sie deaktivieren, indem Sie `docs_url=None` festlegen. +* **ReDoc**: bereitgestellt unter `/redoc`. + * Sie können deren URL mit dem Parameter `redoc_url` festlegen. + * Sie können sie deaktivieren, indem Sie `redoc_url=None` festlegen. + +Um beispielsweise Swagger UI so einzustellen, dass sie unter `/documentation` bereitgestellt wird, und ReDoc zu deaktivieren: + +{* ../../docs_src/metadata/tutorial003.py hl[3] *} diff --git a/docs/de/docs/tutorial/middleware.md b/docs/de/docs/tutorial/middleware.md new file mode 100644 index 000000000..d3699be1b --- /dev/null +++ b/docs/de/docs/tutorial/middleware.md @@ -0,0 +1,66 @@ +# Middleware + +Sie können Middleware zu **FastAPI**-Anwendungen hinzufügen. + +Eine „Middleware“ ist eine Funktion, die mit jedem **Request** arbeitet, bevor er von einer bestimmten *Pfadoperation* verarbeitet wird. Und auch mit jeder **Response**, bevor sie zurückgegeben wird. + +* Sie nimmt jeden **Request** entgegen, der an Ihre Anwendung gesendet wird. +* Sie kann dann etwas mit diesem **Request** tun oder beliebigen Code ausführen. +* Dann gibt sie den **Request** zur Verarbeitung durch den Rest der Anwendung weiter (durch eine bestimmte *Pfadoperation*). +* Sie nimmt dann die **Response** entgegen, die von der Anwendung generiert wurde (durch eine bestimmte *Pfadoperation*). +* Sie kann etwas mit dieser **Response** tun oder beliebigen Code ausführen. +* Dann gibt sie die **Response** zurück. + +/// note | Technische Details + +Wenn Sie Abhängigkeiten mit `yield` haben, wird der Exit-Code *nach* der Middleware ausgeführt. + +Wenn es Hintergrundaufgaben gab (später dokumentiert), werden sie *nach* allen Middlewares ausgeführt. + +/// + +## Erstellung einer Middleware + +Um eine Middleware zu erstellen, verwenden Sie den Dekorator `@app.middleware("http")` über einer Funktion. + +Die Middleware-Funktion erhält: + +* Den `request`. +* Eine Funktion `call_next`, die den `request` als Parameter erhält. + * Diese Funktion gibt den `request` an die entsprechende *Pfadoperation* weiter. + * Dann gibt es die von der entsprechenden *Pfadoperation* generierte `response` zurück. +* Sie können die `response` dann weiter modifizieren, bevor Sie sie zurückgeben. + +{* ../../docs_src/middleware/tutorial001.py hl[8:9,11,14] *} + +/// tip | Tipp + +Beachten Sie, dass benutzerdefinierte proprietäre Header hinzugefügt werden können. Verwenden Sie dafür das Präfix 'X-'. + +Wenn Sie jedoch benutzerdefinierte Header haben, die ein Client in einem Browser sehen soll, müssen Sie sie zu Ihrer CORS-Konfigurationen ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) hinzufügen, indem Sie den Parameter `expose_headers` verwenden, der in der Starlette-CORS-Dokumentation dokumentiert ist. + +/// + +/// note | Technische Details + +Sie könnten auch `from starlette.requests import Request` verwenden. + +**FastAPI** bietet es als Komfort für Sie, den Entwickler, an. Aber es stammt direkt von Starlette. + +/// + +### Vor und nach der `response` + +Sie können Code hinzufügen, der mit dem `request` ausgeführt wird, bevor dieser von einer beliebigen *Pfadoperation* empfangen wird. + +Und auch nachdem die `response` generiert wurde, bevor sie zurückgegeben wird. + +Sie könnten beispielsweise einen benutzerdefinierten Header `X-Process-Time` hinzufügen, der die Zeit in Sekunden enthält, die benötigt wurde, um den Request zu verarbeiten und eine Response zu generieren: + +{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *} + +## Andere Middlewares + +Sie können später mehr über andere Middlewares in [Handbuch für fortgeschrittene Benutzer: Fortgeschrittene Middleware](../advanced/middleware.md){.internal-link target=_blank} lesen. + +In der nächsten Sektion erfahren Sie, wie Sie CORS mit einer Middleware behandeln können. diff --git a/docs/de/docs/tutorial/path-operation-configuration.md b/docs/de/docs/tutorial/path-operation-configuration.md new file mode 100644 index 000000000..7473e515b --- /dev/null +++ b/docs/de/docs/tutorial/path-operation-configuration.md @@ -0,0 +1,107 @@ +# Pfadoperation-Konfiguration + +Es gibt mehrere Konfigurations-Parameter, die Sie Ihrem *Pfadoperation-Dekorator* übergeben können. + +/// warning | Achtung + +Beachten Sie, dass diese Parameter direkt dem *Pfadoperation-Dekorator* übergeben werden, nicht der *Pfadoperation-Funktion*. + +/// + +## Response-Statuscode + +Sie können den (HTTP-)`status_code` definieren, den die Response Ihrer *Pfadoperation* verwenden soll. + +Sie können direkt den `int`-Code übergeben, etwa `404`. + +Aber falls Sie sich nicht mehr erinnern, wofür jede Nummer steht, können Sie die Abkürzungs-Konstanten in `status` verwenden: + +{* ../../docs_src/path_operation_configuration/tutorial001_py310.py hl[1,15] *} + +Dieser Statuscode wird in der Response verwendet und zum OpenAPI-Schema hinzugefügt. + +/// note | Technische Details + +Sie können auch `from starlette import status` verwenden. + +**FastAPI** bietet dieselben `starlette.status`-Codes auch via `fastapi.status` an, als Annehmlichkeit für Sie, den Entwickler. Sie kommen aber direkt von Starlette. + +/// + +## Tags + +Sie können Ihrer *Pfadoperation* Tags hinzufügen, mittels des Parameters `tags`, dem eine `list`e von `str`s übergeben wird (in der Regel nur ein `str`): + +{* ../../docs_src/path_operation_configuration/tutorial002_py310.py hl[15,20,25] *} + +Diese werden zum OpenAPI-Schema hinzugefügt und von den automatischen Dokumentations-Benutzeroberflächen verwendet: + + + +### Tags mittels Enumeration + +Wenn Sie eine große Anwendung haben, können sich am Ende **viele Tags** anhäufen, und Sie möchten sicherstellen, dass Sie für verwandte *Pfadoperationen* immer den **gleichen Tag** nehmen. + +In diesem Fall macht es Sinn, die Tags in einem `Enum` zu speichern. + +**FastAPI** unterstützt diese genauso wie einfache Strings: + +{* ../../docs_src/path_operation_configuration/tutorial002b.py hl[1,8:10,13,18] *} + +## Zusammenfassung und Beschreibung + +Sie können eine Zusammenfassung (`summary`) und eine Beschreibung (`description`) hinzufügen: + +{* ../../docs_src/path_operation_configuration/tutorial003_py310.py hl[18:19] *} + +## Beschreibung mittels Docstring + +Da Beschreibungen oft mehrere Zeilen lang sind, können Sie die Beschreibung der *Pfadoperation* im Docstring der Funktion deklarieren, und **FastAPI** wird sie daraus auslesen. + +Sie können im Docstring Markdown schreiben, es wird korrekt interpretiert und angezeigt (die Einrückung des Docstring beachtend). + +{* ../../docs_src/path_operation_configuration/tutorial004_py310.py hl[17:25] *} + +In der interaktiven Dokumentation sieht das dann so aus: + + + +## Beschreibung der Response + +Die Response können Sie mit dem Parameter `response_description` beschreiben: + +{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[19] *} + +/// info + +beachten Sie, dass sich `response_description` speziell auf die Response bezieht, während `description` sich generell auf die *Pfadoperation* bezieht. + +/// + +/// check + +OpenAPI verlangt, dass jede *Pfadoperation* über eine Beschreibung der Response verfügt. + +Daher, wenn Sie keine vergeben, wird **FastAPI** automatisch eine für „Erfolgreiche Response“ erstellen. + +/// + + + +## Eine *Pfadoperation* deprecaten + +Wenn Sie eine *Pfadoperation* als deprecated kennzeichnen möchten, ohne sie zu entfernen, fügen Sie den Parameter `deprecated` hinzu: + +{* ../../docs_src/path_operation_configuration/tutorial006.py hl[16] *} + +Sie wird in der interaktiven Dokumentation gut sichtbar als deprecated markiert werden: + + + +Vergleichen Sie, wie deprecatete und nicht-deprecatete *Pfadoperationen* aussehen: + + + +## Zusammenfassung + +Sie können auf einfache Weise Metadaten für Ihre *Pfadoperationen* definieren, indem Sie den *Pfadoperation-Dekoratoren* Parameter hinzufügen. diff --git a/docs/de/docs/tutorial/path-params-numeric-validations.md b/docs/de/docs/tutorial/path-params-numeric-validations.md new file mode 100644 index 000000000..1acdd5b4e --- /dev/null +++ b/docs/de/docs/tutorial/path-params-numeric-validations.md @@ -0,0 +1,169 @@ +# Pfad-Parameter und Validierung von Zahlen + +So wie Sie mit `Query` für Query-Parameter zusätzliche Validierungen und Metadaten hinzufügen können, können Sie das mittels `Path` auch für Pfad-Parameter tun. + +## `Path` importieren + +Importieren Sie zuerst `Path` von `fastapi`, und importieren Sie `Annotated`. + +{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *} + +/// info + +FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0. + +Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden. + +Bitte [aktualisieren Sie FastAPI](../deployment/versions.md#upgrade-der-fastapi-versionen){.internal-link target=_blank} daher mindestens zu Version 0.95.1, bevor Sie `Annotated` verwenden. + +/// + +## Metadaten deklarieren + +Sie können die gleichen Parameter deklarieren wie für `Query`. + +Um zum Beispiel einen `title`-Metadaten-Wert für den Pfad-Parameter `item_id` zu deklarieren, schreiben Sie: + +{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *} + +/// note | Hinweis + +Ein Pfad-Parameter ist immer erforderlich, weil er Teil des Pfads sein muss. + +Sie sollten ihn daher mit `...` deklarieren, um ihn als erforderlich auszuzeichnen. + +Doch selbst wenn Sie ihn mit `None` deklarieren, oder einen Defaultwert setzen, bewirkt das nichts, er bleibt immer erforderlich. + +/// + +## Sortieren Sie die Parameter, wie Sie möchten + +/// tip | Tipp + +Wenn Sie `Annotated` verwenden, ist das folgende nicht so wichtig / nicht notwendig. + +/// + +Nehmen wir an, Sie möchten den Query-Parameter `q` als erforderlichen `str` deklarieren. + +Und Sie müssen sonst nichts anderes für den Parameter deklarieren, Sie brauchen also nicht wirklich `Query`. + +Aber Sie brauchen `Path` für den `item_id`-Pfad-Parameter. Und Sie möchten aus irgendeinem Grund nicht `Annotated` verwenden. + +Python wird sich beschweren, wenn Sie einen Parameter mit Defaultwert vor einen Parameter ohne Defaultwert setzen. + +Aber Sie können die Reihenfolge der Parameter ändern, den Query-Parameter ohne Defaultwert zuerst. + +Für **FastAPI** ist es nicht wichtig. Es erkennt die Parameter anhand ihres Namens, ihrer Typen, und ihrer Defaultwerte (`Query`, `Path`, usw.). Es kümmert sich nicht um die Reihenfolge. + +Sie können Ihre Funktion also so deklarieren: + +//// tab | Python 3.8 nicht annotiert + +/// tip | Tipp + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python hl_lines="7" +{!> ../../docs_src/path_params_numeric_validations/tutorial002.py!} +``` + +//// + +Aber bedenken Sie, dass Sie dieses Problem nicht haben, wenn Sie `Annotated` verwenden, da Sie nicht die Funktions-Parameter-Defaultwerte für `Query()` oder `Path()` verwenden. + +{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py hl[10] *} + +## Sortieren Sie die Parameter wie Sie möchten: Tricks + +/// tip | Tipp + +Wenn Sie `Annotated` verwenden, ist das folgende nicht so wichtig / nicht notwendig. + +/// + +Hier ein **kleiner Trick**, der nützlich sein kann, aber Sie werden ihn nicht oft brauchen. + +Wenn Sie eines der folgenden Dinge tun möchten: + +* den `q`-Parameter ohne `Query` oder irgendeinem Defaultwert deklarieren +* den Pfad-Parameter `item_id` mittels `Path` deklarieren +* die Parameter in einer unterschiedlichen Reihenfolge haben +* `Annotated` nicht verwenden + +... dann hat Python eine kleine Spezial-Syntax für Sie. + +Übergeben Sie der Funktion `*` als ersten Parameter. + +Python macht nichts mit diesem `*`, aber es wird wissen, dass alle folgenden Parameter als Keyword-Argumente (Schlüssel-Wert-Paare), auch bekannt als kwargs, verwendet werden. Selbst wenn diese keinen Defaultwert haben. + +{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *} + +### Besser mit `Annotated` + +Bedenken Sie, dass Sie, wenn Sie `Annotated` verwenden, dieses Problem nicht haben, weil Sie keine Defaultwerte für Ihre Funktionsparameter haben. Sie müssen daher wahrscheinlich auch nicht `*` verwenden. + +{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *} + +## Validierung von Zahlen: Größer oder gleich + +Mit `Query` und `Path` (und anderen, die Sie später kennenlernen), können Sie Zahlenbeschränkungen deklarieren. + +Hier, mit `ge=1`, wird festgelegt, dass `item_id` eine Ganzzahl benötigt, die größer oder gleich `1` ist (`g`reater than or `e`qual). +{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *} + +## Validierung von Zahlen: Größer und kleiner oder gleich + +Das Gleiche trifft zu auf: + +* `gt`: `g`reater `t`han – größer als +* `le`: `l`ess than or `e`qual – kleiner oder gleich + +{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *} + +## Validierung von Zahlen: Floats, größer und kleiner + +Zahlenvalidierung funktioniert auch für `float`-Werte. + +Hier wird es wichtig, in der Lage zu sein, gt zu deklarieren, und nicht nur ge, da Sie hiermit bestimmen können, dass ein Wert, zum Beispiel, größer als `0` sein muss, obwohl er kleiner als `1` ist. + +`0.5` wäre also ein gültiger Wert, aber nicht `0.0` oder `0`. + +Das gleiche gilt für lt. + +{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *} + +## Zusammenfassung + +Mit `Query` und `Path` (und anderen, die Sie noch nicht gesehen haben) können Sie Metadaten und Stringvalidierungen deklarieren, so wie in [Query-Parameter und Stringvalidierungen](query-params-str-validations.md){.internal-link target=_blank} beschrieben. + +Und Sie können auch Validierungen für Zahlen deklarieren: + +* `gt`: `g`reater `t`han – größer als +* `ge`: `g`reater than or `e`qual – größer oder gleich +* `lt`: `l`ess `t`han – kleiner als +* `le`: `l`ess than or `e`qual – kleiner oder gleich + +/// info + +`Query`, `Path`, und andere Klassen, die Sie später kennenlernen, sind Unterklassen einer allgemeinen `Param`-Klasse. + +Sie alle teilen die gleichen Parameter für zusätzliche Validierung und Metadaten, die Sie gesehen haben. + +/// + +/// note | Technische Details + +`Query`, `Path` und andere, die Sie von `fastapi` importieren, sind tatsächlich Funktionen. + +Die, wenn sie aufgerufen werden, Instanzen der Klassen mit demselben Namen zurückgeben. + +Sie importieren also `Query`, welches eine Funktion ist. Aber wenn Sie es aufrufen, gibt es eine Instanz der Klasse zurück, die auch `Query` genannt wird. + +Diese Funktionen existieren (statt die Klassen direkt zu verwenden), damit Ihr Editor keine Fehlermeldungen über ihre Typen ausgibt. + +Auf diese Weise können Sie Ihren Editor und Ihre Programmier-Tools verwenden, ohne besondere Einstellungen vornehmen zu müssen, um diese Fehlermeldungen stummzuschalten. + +/// diff --git a/docs/de/docs/tutorial/path-params.md b/docs/de/docs/tutorial/path-params.md new file mode 100644 index 000000000..123990940 --- /dev/null +++ b/docs/de/docs/tutorial/path-params.md @@ -0,0 +1,258 @@ +# Pfad-Parameter + +Sie können Pfad-„Parameter“ oder -„Variablen“ mit der gleichen Syntax deklarieren, welche in Python-Format-Strings verwendet wird: + +{* ../../docs_src/path_params/tutorial001.py hl[6:7] *} + +Der Wert des Pfad-Parameters `item_id` wird Ihrer Funktion als das Argument `item_id` übergeben. + +Wenn Sie dieses Beispiel ausführen und auf http://127.0.0.1:8000/items/foo gehen, sehen Sie als Response: + +```JSON +{"item_id":"foo"} +``` + +## Pfad-Parameter mit Typen + +Sie können den Typ eines Pfad-Parameters in der Argumentliste der Funktion deklarieren, mit Standard-Python-Typannotationen: + +{* ../../docs_src/path_params/tutorial002.py hl[7] *} + +In diesem Fall wird `item_id` als `int` deklariert, also als Ganzzahl. + +/// check + +Dadurch erhalten Sie Editor-Unterstützung innerhalb Ihrer Funktion, mit Fehlerprüfungen, Codevervollständigung, usw. + +/// + +## Daten-Konversion + +Wenn Sie dieses Beispiel ausführen und Ihren Browser unter http://127.0.0.1:8000/items/3 öffnen, sehen Sie als Response: + +```JSON +{"item_id":3} +``` + +/// check + +Beachten Sie, dass der Wert, den Ihre Funktion erhält und zurückgibt, die Zahl `3` ist, also ein `int`. Nicht der String `"3"`, also ein `str`. + +Sprich, mit dieser Typdeklaration wird **FastAPI** die Anfrage automatisch „parsen“. + +/// + +## Datenvalidierung + +Wenn Sie aber im Browser http://127.0.0.1:8000/items/foo besuchen, erhalten Sie eine hübsche HTTP-Fehlermeldung: + +```JSON +{ + "detail": [ + { + "type": "int_parsing", + "loc": [ + "path", + "item_id" + ], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "foo", + "url": "https://errors.pydantic.dev/2.1/v/int_parsing" + } + ] +} +``` + +Der Pfad-Parameter `item_id` hatte den Wert `"foo"`, was kein `int` ist. + +Die gleiche Fehlermeldung würde angezeigt werden, wenn Sie ein `float` (also eine Kommazahl) statt eines `int`s übergeben würden, wie etwa in: http://127.0.0.1:8000/items/4.2 + +/// check + +Sprich, mit der gleichen Python-Typdeklaration gibt Ihnen **FastAPI** Datenvalidierung. + +Beachten Sie, dass die Fehlermeldung auch direkt die Stelle anzeigt, wo die Validierung nicht erfolgreich war. + +Das ist unglaublich hilfreich, wenn Sie Code entwickeln und debuggen, welcher mit ihrer API interagiert. + +/// + +## Dokumentation + +Wenn Sie die Seite http://127.0.0.1:8000/docs in Ihrem Browser öffnen, sehen Sie eine automatische, interaktive API-Dokumentation: + + + +/// check + +Wiederum, mit dieser gleichen Python-Typdeklaration gibt Ihnen **FastAPI** eine automatische, interaktive Dokumentation (verwendet die Swagger-Benutzeroberfläche). + +Beachten Sie, dass der Pfad-Parameter dort als Ganzzahl deklariert ist. + +/// + +## Nützliche Standards. Alternative Dokumentation + +Und weil das generierte Schema vom OpenAPI-Standard kommt, gibt es viele kompatible Tools. + +Zum Beispiel bietet **FastAPI** selbst eine alternative API-Dokumentation (verwendet ReDoc), welche Sie unter http://127.0.0.1:8000/redoc einsehen können: + + + +Und viele weitere kompatible Tools. Inklusive Codegenerierung für viele Sprachen. + +## Pydantic + +Die ganze Datenvalidierung wird hinter den Kulissen von Pydantic durchgeführt, Sie profitieren also von dessen Vorteilen. Und Sie wissen, dass Sie in guten Händen sind. + +Sie können für Typ Deklarationen auch `str`, `float`, `bool` und viele andere komplexe Datentypen verwenden. + +Mehrere davon werden wir in den nächsten Kapiteln erkunden. + +## Die Reihenfolge ist wichtig + +Wenn Sie *Pfadoperationen* erstellen, haben Sie manchmal einen fixen Pfad. + +Etwa `/users/me`, um Daten über den aktuellen Benutzer zu erhalten. + +Und Sie haben auch einen Pfad `/users/{user_id}`, um Daten über einen spezifischen Benutzer zu erhalten, mittels einer Benutzer-ID. + +Weil *Pfadoperationen* in ihrer Reihenfolge ausgewertet werden, müssen Sie sicherstellen, dass der Pfad `/users/me` vor `/users/{user_id}` deklariert wurde: + +{* ../../docs_src/path_params/tutorial003.py hl[6,11] *} + +Ansonsten würde der Pfad für `/users/{user_id}` auch `/users/me` auswerten, und annehmen, dass ein Parameter `user_id` mit dem Wert `"me"` übergeben wurde. + +Sie können eine Pfadoperation auch nicht erneut definieren: + +{* ../../docs_src/path_params/tutorial003b.py hl[6,11] *} + +Die erste Definition wird immer verwendet werden, da ihr Pfad zuerst übereinstimmt. + +## Vordefinierte Parameterwerte + +Wenn Sie eine *Pfadoperation* haben, welche einen *Pfad-Parameter* hat, aber Sie wollen, dass dessen gültige Werte vordefiniert sind, können Sie ein Standard-Python `Enum` verwenden. + +### Erstellen Sie eine `Enum`-Klasse + +Importieren Sie `Enum` und erstellen Sie eine Unterklasse, die von `str` und `Enum` erbt. + +Indem Sie von `str` erben, weiß die API Dokumentation, dass die Werte des Enums vom Typ `str` sein müssen, und wird in der Lage sein, korrekt zu rendern. + +Erstellen Sie dann Klassen-Attribute mit festgelegten Werten, welches die erlaubten Werte sein werden: + +{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *} + +/// info + +Enumerationen (oder kurz Enums) gibt es in Python seit Version 3.4. + +/// + +/// tip | Tipp + +Falls Sie sich fragen, was „AlexNet“, „ResNet“ und „LeNet“ ist, das sind Namen von Modellen für maschinelles Lernen. + +/// + +### Deklarieren Sie einen *Pfad-Parameter* + +Dann erstellen Sie einen *Pfad-Parameter*, der als Typ die gerade erstellte Enum-Klasse hat (`ModelName`): + +{* ../../docs_src/path_params/tutorial005.py hl[16] *} + +### Testen Sie es in der API-Dokumentation + +Weil die erlaubten Werte für den *Pfad-Parameter* nun vordefiniert sind, kann die interaktive Dokumentation sie als Auswahl-Drop-Down anzeigen: + + + +### Mit Python-*Enums* arbeiten + +Der *Pfad-Parameter* wird ein *Member eines Enums* sein. + +#### *Enum-Member* vergleichen + +Sie können ihn mit einem Member Ihres Enums `ModelName` vergleichen: + +{* ../../docs_src/path_params/tutorial005.py hl[17] *} + +#### *Enum-Wert* erhalten + +Den tatsächlichen Wert (in diesem Fall ein `str`) erhalten Sie via `model_name.value`, oder generell, `ihr_enum_member.value`: + +{* ../../docs_src/path_params/tutorial005.py hl[20] *} + +/// tip | Tipp + +Sie können den Wert `"lenet"` außerdem mittels `ModelName.lenet.value` abrufen. + +/// + +#### *Enum-Member* zurückgeben + +Sie können *Enum-Member* in ihrer *Pfadoperation* zurückgeben, sogar verschachtelt in einem JSON-Body (z. B. als `dict`). + +Diese werden zu ihren entsprechenden Werten konvertiert (in diesem Fall Strings), bevor sie zum Client übertragen werden: + +{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *} + +In Ihrem Client erhalten Sie eine JSON-Response, wie etwa: + +```JSON +{ + "model_name": "alexnet", + "message": "Deep Learning FTW!" +} +``` + +## Pfad Parameter die Pfade enthalten + +Angenommen, Sie haben eine *Pfadoperation* mit einem Pfad `/files/{file_path}`. + +Aber `file_path` soll selbst einen *Pfad* enthalten, etwa `home/johndoe/myfile.txt`. + +Sprich, die URL für diese Datei wäre etwas wie: `/files/home/johndoe/myfile.txt`. + +### OpenAPI Unterstützung + +OpenAPI bietet nicht die Möglichkeit, dass ein *Pfad-Parameter* seinerseits einen *Pfad* enthalten kann, das würde zu Szenarios führen, die schwierig zu testen und zu definieren sind. + +Trotzdem können Sie das in **FastAPI** tun, indem Sie eines der internen Tools von Starlette verwenden. + +Die Dokumentation würde weiterhin funktionieren, allerdings wird nicht dokumentiert werden, dass der Parameter ein Pfad sein sollte. + +### Pfad Konverter + +Mittels einer Option direkt von Starlette können Sie einen *Pfad-Parameter* deklarieren, der einen Pfad enthalten soll, indem Sie eine URL wie folgt definieren: + +``` +/files/{file_path:path} +``` + +In diesem Fall ist der Name des Parameters `file_path`. Der letzte Teil, `:path`, sagt aus, dass der Parameter ein *Pfad* sein soll. + +Sie verwenden das also wie folgt: + +{* ../../docs_src/path_params/tutorial004.py hl[6] *} + +/// tip | Tipp + +Der Parameter könnte einen führenden Schrägstrich (`/`) haben, wie etwa in `/home/johndoe/myfile.txt`. + +In dem Fall wäre die URL: `/files//home/johndoe/myfile.txt`, mit einem doppelten Schrägstrich (`//`) zwischen `files` und `home`. + +/// + +## Zusammenfassung + +In **FastAPI** erhalten Sie mittels kurzer, intuitiver Typdeklarationen: + +* Editor-Unterstützung: Fehlerprüfungen, Codevervollständigung, usw. +* Daten "parsen" +* Datenvalidierung +* API-Annotationen und automatische Dokumentation + +Und Sie müssen sie nur einmal deklarieren. + +Das ist wahrscheinlich der sichtbarste Unterschied zwischen **FastAPI** und alternativen Frameworks (abgesehen von der reinen Performanz). diff --git a/docs/de/docs/tutorial/query-params-str-validations.md b/docs/de/docs/tutorial/query-params-str-validations.md new file mode 100644 index 000000000..de8879ce8 --- /dev/null +++ b/docs/de/docs/tutorial/query-params-str-validations.md @@ -0,0 +1,493 @@ +# Query-Parameter und Stringvalidierung + +**FastAPI** erlaubt es Ihnen, Ihre Parameter zusätzlich zu validieren, und zusätzliche Informationen hinzuzufügen. + +Nehmen wir als Beispiel die folgende Anwendung: + +{* ../../docs_src/query_params_str_validations/tutorial001_py310.py hl[7] *} + +Der Query-Parameter `q` hat den Typ `Union[str, None]` (oder `str | None` in Python 3.10), was bedeutet, er ist entweder ein `str` oder `None`. Der Defaultwert ist `None`, also weiß FastAPI, der Parameter ist nicht erforderlich. + +/// note | Hinweis + +FastAPI weiß nur dank des definierten Defaultwertes `=None`, dass der Wert von `q` nicht erforderlich ist + +`Union[str, None]` hingegen erlaubt ihren Editor, Sie besser zu unterstützen und Fehler zu erkennen. + +/// + +## Zusätzliche Validierung + +Wir werden bewirken, dass, obwohl `q` optional ist, wenn es gegeben ist, **seine Länge 50 Zeichen nicht überschreitet**. + +### `Query` und `Annotated` importieren + +Importieren Sie zuerst: + +* `Query` von `fastapi` +* `Annotated` von `typing` (oder von `typing_extensions` in Python unter 3.9) + +//// tab | Python 3.10+ + +In Python 3.9 oder darüber, ist `Annotated` Teil der Standardbibliothek, also können Sie es von `typing` importieren. + +```Python hl_lines="1 3" +{!> ../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +In Versionen unter Python 3.9 importieren Sie `Annotated` von `typing_extensions`. + +Es wird bereits mit FastAPI installiert sein. + +```Python hl_lines="3-4" +{!> ../../docs_src/query_params_str_validations/tutorial002_an.py!} +``` + +//// + +/// info + +FastAPI unterstützt (und empfiehlt die Verwendung von) `Annotated` seit Version 0.95.0. + +Wenn Sie eine ältere Version haben, werden Sie Fehler angezeigt bekommen, wenn Sie versuchen, `Annotated` zu verwenden. + +Bitte [aktualisieren Sie FastAPI](../deployment/versions.md#upgrade-der-fastapi-versionen){.internal-link target=_blank} daher mindestens zu Version 0.95.1, bevor Sie `Annotated` verwenden. + +/// + +## `Annotated` im Typ des `q`-Parameters verwenden + +Erinnern Sie sich, wie ich in [Einführung in Python-Typen](../python-types.md#typhinweise-mit-metadaten-annotationen){.internal-link target=_blank} sagte, dass Sie mittels `Annotated` Metadaten zu Ihren Parametern hinzufügen können? + +Jetzt ist es an der Zeit, das mit FastAPI auszuprobieren. 🚀 + +Wir hatten diese Typannotation: + +//// tab | Python 3.10+ + +```Python +q: str | None = None +``` + +//// + +//// tab | Python 3.8+ + +```Python +q: Union[str, None] = None +``` + +//// + +Wir wrappen das nun in `Annotated`, sodass daraus wird: + +//// tab | Python 3.10+ + +```Python +q: Annotated[str | None] = None +``` + +//// + +//// tab | Python 3.8+ + +```Python +q: Annotated[Union[str, None]] = None +``` + +//// + +Beide Versionen bedeuten dasselbe: `q` ist ein Parameter, der `str` oder `None` sein kann. Standardmäßig ist er `None`. + +Wenden wir uns jetzt den spannenden Dingen zu. 🎉 + +## `Query` zu `Annotated` im `q`-Parameter hinzufügen + +Jetzt, da wir `Annotated` für unsere Metadaten deklariert haben, fügen Sie `Query` hinzu, und setzen Sie den Parameter `max_length` auf `50`: + +{* ../../docs_src/query_params_str_validations/tutorial002_an_py310.py hl[9] *} + +Beachten Sie, dass der Defaultwert immer noch `None` ist, sodass der Parameter immer noch optional ist. + +Aber jetzt, mit `Query(max_length=50)` innerhalb von `Annotated`, sagen wir FastAPI, dass es diesen Wert aus den Query-Parametern extrahieren soll (das hätte es sowieso gemacht 🤷) und dass wir eine **zusätzliche Validierung** für diesen Wert haben wollen (darum machen wir das, um die zusätzliche Validierung zu bekommen). 😎 + +FastAPI wird nun: + +* Die Daten **validieren** und sicherstellen, dass sie nicht länger als 50 Zeichen sind +* Dem Client einen **verständlichen Fehler** anzeigen, wenn die Daten ungültig sind +* Den Parameter in der OpenAPI-Schema-*Pfadoperation* **dokumentieren** (sodass er in der **automatischen Dokumentation** angezeigt wird) + +## Alternativ (alt): `Query` als Defaultwert + +Frühere Versionen von FastAPI (vor 0.95.0) benötigten `Query` als Defaultwert des Parameters, statt es innerhalb von `Annotated` unterzubringen. Die Chance ist groß, dass Sie Quellcode sehen, der das immer noch so macht, darum erkläre ich es Ihnen. + +/// tip | Tipp + +Verwenden Sie für neuen Code, und wann immer möglich, `Annotated`, wie oben erklärt. Es gibt mehrere Vorteile (unten erläutert) und keine Nachteile. 🍰 + +/// + +So würden Sie `Query()` als Defaultwert Ihres Funktionsparameters verwenden, den Parameter `max_length` auf 50 gesetzt: + +{* ../../docs_src/query_params_str_validations/tutorial002_py310.py hl[7] *} + +Da wir in diesem Fall (ohne die Verwendung von `Annotated`) den Parameter-Defaultwert `None` mit `Query()` ersetzen, müssen wir nun dessen Defaultwert mit dem Parameter `Query(default=None)` deklarieren. Das dient demselben Zweck, `None` als Defaultwert für den Funktionsparameter zu setzen (zumindest für FastAPI). + +Sprich: + +```Python +q: Union[str, None] = Query(default=None) +``` + +... macht den Parameter optional, mit dem Defaultwert `None`, genauso wie: + +```Python +q: Union[str, None] = None +``` + +Und in Python 3.10 und darüber macht: + +```Python +q: str | None = Query(default=None) +``` + +... den Parameter optional, mit dem Defaultwert `None`, genauso wie: + +```Python +q: str | None = None +``` + +Nur, dass die `Query`-Versionen den Parameter explizit als Query-Parameter deklarieren. + +/// info + +Bedenken Sie, dass: + +```Python += None +``` + +oder: + +```Python += Query(default=None) +``` + +der wichtigste Teil ist, um einen Parameter optional zu machen, da dieses `None` der Defaultwert ist, und das ist es, was diesen Parameter **nicht erforderlich** macht. + +Der Teil mit `Union[str, None]` erlaubt es Ihrem Editor, Sie besser zu unterstützen, aber er sagt FastAPI nicht, dass dieser Parameter optional ist. + +/// + +Jetzt können wir `Query` weitere Parameter übergeben. Fangen wir mit dem `max_length` Parameter an, der auf Strings angewendet wird: + +```Python +q: Union[str, None] = Query(default=None, max_length=50) +``` + +Das wird die Daten validieren, einen verständlichen Fehler ausgeben, wenn die Daten nicht gültig sind, und den Parameter in der OpenAPI-Schema-*Pfadoperation* dokumentieren. + +### `Query` als Defaultwert oder in `Annotated` + +Bedenken Sie, dass wenn Sie `Query` innerhalb von `Annotated` benutzen, Sie den `default`-Parameter für `Query` nicht verwenden dürfen. + +Setzen Sie stattdessen den Defaultwert des Funktionsparameters, sonst wäre es inkonsistent. + +Zum Beispiel ist das nicht erlaubt: + +```Python +q: Annotated[str, Query(default="rick")] = "morty" +``` + +... denn es wird nicht klar, ob der Defaultwert `"rick"` oder `"morty"` sein soll. + +Sie würden also (bevorzugt) schreiben: + +```Python +q: Annotated[str, Query()] = "rick" +``` + +In älterem Code werden Sie auch finden: + +```Python +q: str = Query(default="rick") +``` + +### Vorzüge von `Annotated` + +**Es wird empfohlen, `Annotated` zu verwenden**, statt des Defaultwertes im Funktionsparameter, das ist aus mehreren Gründen **besser**: 🤓 + +Der **Default**wert des **Funktionsparameters** ist der **tatsächliche Default**wert, das spielt generell intuitiver mit Python zusammen. 😌 + +Sie können die Funktion ohne FastAPI an **anderen Stellen aufrufen**, und es wird **wie erwartet funktionieren**. Wenn es einen **erforderlichen** Parameter gibt (ohne Defaultwert), und Sie führen die Funktion ohne den benötigten Parameter aus, dann wird Ihr **Editor** Sie das mit einem Fehler wissen lassen, und **Python** wird sich auch beschweren. + +Wenn Sie aber nicht `Annotated` benutzen und stattdessen die **(alte) Variante mit einem Defaultwert**, dann müssen Sie, wenn Sie die Funktion ohne FastAPI an **anderen Stellen** aufrufen, sich daran **erinnern**, die Argumente der Funktion zu übergeben, damit es richtig funktioniert. Ansonsten erhalten Sie unerwartete Werte (z. B. `QueryInfo` oder etwas Ähnliches, statt `str`). Ihr Editor kann ihnen nicht helfen, und Python wird die Funktion ohne Beschwerden ausführen, es sei denn, die Operationen innerhalb lösen einen Fehler aus. + +Da `Annotated` mehrere Metadaten haben kann, können Sie dieselbe Funktion auch mit anderen Tools verwenden, wie etwa Typer. 🚀 + +## Mehr Validierungen hinzufügen + +Sie können auch einen Parameter `min_length` hinzufügen: + +{* ../../docs_src/query_params_str_validations/tutorial003_an_py310.py hl[10] *} + +## Reguläre Ausdrücke hinzufügen + +Sie können einen Regulären Ausdruck `pattern` definieren, mit dem der Parameter übereinstimmen muss: + +{* ../../docs_src/query_params_str_validations/tutorial004_an_py310.py hl[11] *} + +Dieses bestimmte reguläre Suchmuster prüft, ob der erhaltene Parameter-Wert: + +* `^`: mit den nachfolgenden Zeichen startet, keine Zeichen davor hat. +* `fixedquery`: den exakten Text `fixedquery` hat. +* `$`: danach endet, keine weiteren Zeichen hat als `fixedquery`. + +Wenn Sie sich verloren fühlen bei all diesen **„Regulärer Ausdruck“**-Konzepten, keine Sorge. Reguläre Ausdrücke sind für viele Menschen ein schwieriges Thema. Sie können auch ohne reguläre Ausdrücke eine ganze Menge machen. + +Aber wenn Sie sie brauchen und sie lernen, wissen Sie, dass Sie sie bereits direkt in **FastAPI** verwenden können. + +### Pydantic v1 `regex` statt `pattern` + +Vor Pydantic Version 2 und vor FastAPI Version 0.100.0, war der Name des Parameters `regex` statt `pattern`, aber das ist jetzt deprecated. + +Sie könnten immer noch Code sehen, der den alten Namen verwendet: + +//// tab | Pydantic v1 + +{* ../../docs_src/query_params_str_validations/tutorial004_regex_an_py310.py hl[11] *} + +//// + +Beachten Sie aber, dass das deprecated ist, und zum neuen Namen `pattern` geändert werden sollte. 🤓 + +## Defaultwerte + +Sie können natürlich andere Defaultwerte als `None` verwenden. + +Beispielsweise könnten Sie den `q` Query-Parameter so deklarieren, dass er eine `min_length` von `3` hat, und den Defaultwert `"fixedquery"`: + +{* ../../docs_src/query_params_str_validations/tutorial005_an_py39.py hl[9] *} + +/// note | Hinweis + +Ein Parameter ist optional (nicht erforderlich), wenn er irgendeinen Defaultwert, auch `None`, hat. + +/// + +## Erforderliche Parameter + +Wenn wir keine Validierungen oder Metadaten haben, können wir den `q` Query-Parameter erforderlich machen, indem wir einfach keinen Defaultwert deklarieren, wie in: + +```Python +q: str +``` + +statt: + +```Python +q: Union[str, None] = None +``` + +Aber jetzt deklarieren wir den Parameter mit `Query`, wie in: + +//// tab | Annotiert + +```Python +q: Annotated[Union[str, None], Query(min_length=3)] = None +``` + +//// + +//// tab | Nicht annotiert + +```Python +q: Union[str, None] = Query(default=None, min_length=3) +``` + +//// + +Wenn Sie einen Parameter erforderlich machen wollen, während Sie `Query` verwenden, deklarieren Sie ebenfalls einfach keinen Defaultwert: + +{* ../../docs_src/query_params_str_validations/tutorial006_an_py39.py hl[9] *} + +### Erforderlich, kann `None` sein + +Sie können deklarieren, dass ein Parameter `None` akzeptiert, aber dennoch erforderlich ist. Das zwingt Clients, den Wert zu senden, selbst wenn er `None` ist. + +Um das zu machen, deklarieren Sie, dass `None` ein gültiger Typ ist, aber verwenden Sie dennoch `...` als Default: + +{* ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py hl[9] *} + +/// tip | Tipp + +Pydantic, welches die gesamte Datenvalidierung und Serialisierung in FastAPI antreibt, hat ein spezielles Verhalten, wenn Sie `Optional` oder `Union[Something, None]` ohne Defaultwert verwenden, Sie können mehr darüber in der Pydantic-Dokumentation unter Required fields erfahren. + +/// + +/// tip | Tipp + +Denken Sie daran, dass Sie in den meisten Fällen, wenn etwas erforderlich ist, einfach den Defaultwert weglassen können. Sie müssen also normalerweise `...` nicht verwenden. + +/// + +## Query-Parameter-Liste / Mehrere Werte + +Wenn Sie einen Query-Parameter explizit mit `Query` auszeichnen, können Sie ihn auch eine Liste von Werten empfangen lassen, oder anders gesagt, mehrere Werte. + +Um zum Beispiel einen Query-Parameter `q` zu deklarieren, der mehrere Male in der URL vorkommen kann, schreiben Sie: + +{* ../../docs_src/query_params_str_validations/tutorial011_an_py310.py hl[9] *} + +Dann, mit einer URL wie: + +``` +http://localhost:8000/items/?q=foo&q=bar +``` + +bekommen Sie alle `q`-*Query-Parameter*-Werte (`foo` und `bar`) in einer Python-Liste – `list` – in ihrer *Pfadoperation-Funktion*, im Funktionsparameter `q`, überreicht. + +Die Response für diese URL wäre also: + +```JSON +{ + "q": [ + "foo", + "bar" + ] +} +``` + +/// tip | Tipp + +Um einen Query-Parameter vom Typ `list` zu deklarieren, wie im Beispiel oben, müssen Sie explizit `Query` verwenden, sonst würde der Parameter als Requestbody interpretiert werden. + +/// + +Die interaktive API-Dokumentation wird entsprechend aktualisiert und erlaubt jetzt mehrere Werte. + + + +### Query-Parameter-Liste / Mehrere Werte mit Defaults + +Und Sie können auch eine Default-`list`e von Werten definieren, wenn keine übergeben werden: + +{* ../../docs_src/query_params_str_validations/tutorial012_an_py39.py hl[9] *} + +Wenn Sie auf: + +``` +http://localhost:8000/items/ +``` + +gehen, wird der Default für `q` verwendet: `["foo", "bar"]`, und als Response erhalten Sie: + +```JSON +{ + "q": [ + "foo", + "bar" + ] +} +``` + +#### `list` alleine verwenden + +Sie können auch `list` direkt verwenden, anstelle von `List[str]` (oder `list[str]` in Python 3.9+): + +{* ../../docs_src/query_params_str_validations/tutorial013_an_py39.py hl[9] *} + +/// note | Hinweis + +Beachten Sie, dass FastAPI in diesem Fall den Inhalt der Liste nicht überprüft. + +Zum Beispiel würde `List[int]` überprüfen (und dokumentieren) dass die Liste Ganzzahlen enthält. `list` alleine macht das nicht. + +/// + +## Deklarieren von mehr Metadaten + +Sie können mehr Informationen zum Parameter hinzufügen. + +Diese Informationen werden zur generierten OpenAPI hinzugefügt, und von den Dokumentations-Oberflächen und von externen Tools verwendet. + +/// note | Hinweis + +Beachten Sie, dass verschiedene Tools OpenAPI möglicherweise unterschiedlich gut unterstützen. + +Einige könnten noch nicht alle zusätzlichen Informationen anzeigen, die Sie deklariert haben, obwohl in den meisten Fällen geplant ist, das fehlende Feature zu implementieren. + +/// + +Sie können einen Titel hinzufügen – `title`: + +{* ../../docs_src/query_params_str_validations/tutorial007_an_py310.py hl[10] *} + +Und eine Beschreibung – `description`: + +{* ../../docs_src/query_params_str_validations/tutorial008_an_py310.py hl[14] *} + +## Alias-Parameter + +Stellen Sie sich vor, der Parameter soll `item-query` sein. + +Wie in: + +``` +http://127.0.0.1:8000/items/?item-query=foobaritems +``` + +Aber `item-query` ist kein gültiger Name für eine Variable in Python. + +Am ähnlichsten wäre `item_query`. + +Aber Sie möchten dennoch exakt `item-query` verwenden. + +Dann können Sie einen `alias` deklarieren, und dieser Alias wird verwendet, um den Parameter-Wert zu finden: + +{* ../../docs_src/query_params_str_validations/tutorial009_an_py310.py hl[9] *} + +## Parameter als deprecated ausweisen + +Nehmen wir an, Sie mögen diesen Parameter nicht mehr. + +Sie müssen ihn eine Weile dort belassen, weil Clients ihn benutzen, aber Sie möchten, dass die Dokumentation klar anzeigt, dass er deprecated ist. + +In diesem Fall fügen Sie den Parameter `deprecated=True` zu `Query` hinzu. + +{* ../../docs_src/query_params_str_validations/tutorial010_an_py310.py hl[19] *} + +Die Dokumentation wird das so anzeigen: + + + +## Parameter von OpenAPI ausschließen + +Um einen Query-Parameter vom generierten OpenAPI-Schema auszuschließen (und daher von automatischen Dokumentations-Systemen), setzen Sie den Parameter `include_in_schema` in `Query` auf `False`. + +{* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *} + +## Zusammenfassung + +Sie können zusätzliche Validierungen und Metadaten zu ihren Parametern hinzufügen. + +Allgemeine Validierungen und Metadaten: + +* `alias` +* `title` +* `description` +* `deprecated` + +Validierungen spezifisch für Strings: + +* `min_length` +* `max_length` +* `pattern` + +In diesen Beispielen haben Sie gesehen, wie Sie Validierungen für Strings hinzufügen. + +In den nächsten Kapiteln sehen wir, wie man Validierungen für andere Typen hinzufügt, etwa für Zahlen. diff --git a/docs/de/docs/tutorial/query-params.md b/docs/de/docs/tutorial/query-params.md new file mode 100644 index 000000000..0b0f473e2 --- /dev/null +++ b/docs/de/docs/tutorial/query-params.md @@ -0,0 +1,188 @@ +# Query-Parameter + +Wenn Sie in ihrer Funktion Parameter deklarieren, die nicht Teil der Pfad-Parameter sind, dann werden diese automatisch als „Query“-Parameter interpretiert. + +{* ../../docs_src/query_params/tutorial001.py hl[9] *} + +Query-Parameter (Deutsch: Abfrage-Parameter) sind die Schlüssel-Wert-Paare, die nach dem `?` in einer URL aufgelistet sind, getrennt durch `&`-Zeichen. + +Zum Beispiel sind in der URL: + +``` +http://127.0.0.1:8000/items/?skip=0&limit=10 +``` + +... die Query-Parameter: + +* `skip`: mit dem Wert `0` +* `limit`: mit dem Wert `10` + +Da sie Teil der URL sind, sind sie „naturgemäß“ Strings. + +Aber wenn Sie sie mit Python-Typen deklarieren (im obigen Beispiel als `int`), werden sie zu diesem Typ konvertiert, und gegen diesen validiert. + +Die gleichen Prozesse, die für Pfad-Parameter stattfinden, werden auch auf Query-Parameter angewendet: + +* Editor Unterstützung (natürlich) +* „Parsen“ der Daten +* Datenvalidierung +* Automatische Dokumentation + +## Defaultwerte + +Da Query-Parameter nicht ein festgelegter Teil des Pfades sind, können sie optional sein und Defaultwerte haben. + +Im obigen Beispiel haben sie die Defaultwerte `skip=0` und `limit=10`. + +Wenn Sie also zur URL: + +``` +http://127.0.0.1:8000/items/ +``` + +gehen, so ist das das gleiche wie die URL: + +``` +http://127.0.0.1:8000/items/?skip=0&limit=10 +``` + +Aber wenn Sie zum Beispiel zu: + +``` +http://127.0.0.1:8000/items/?skip=20 +``` + +gehen, werden die Parameter-Werte Ihrer Funktion sein: + +* `skip=20`: da Sie das in der URL gesetzt haben +* `limit=10`: weil das der Defaultwert ist + +## Optionale Parameter + +Auf die gleiche Weise können Sie optionale Query-Parameter deklarieren, indem Sie deren Defaultwert auf `None` setzen: + +{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *} + +In diesem Fall wird der Funktionsparameter `q` optional, und standardmäßig `None` sein. + +/// check + +Beachten Sie auch, dass **FastAPI** intelligent genug ist, um zu erkennen, dass `item_id` ein Pfad-Parameter ist und `q` keiner, daher muss letzteres ein Query-Parameter sein. + +/// + +## Query-Parameter Typkonvertierung + +Sie können auch `bool`-Typen deklarieren und sie werden konvertiert: + +{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *} + +Wenn Sie nun zu: + +``` +http://127.0.0.1:8000/items/foo?short=1 +``` + +oder + +``` +http://127.0.0.1:8000/items/foo?short=True +``` + +oder + +``` +http://127.0.0.1:8000/items/foo?short=true +``` + +oder + +``` +http://127.0.0.1:8000/items/foo?short=on +``` + +oder + +``` +http://127.0.0.1:8000/items/foo?short=yes +``` + +gehen, oder zu irgendeiner anderen Variante der Groß-/Kleinschreibung (Alles groß, Anfangsbuchstabe groß, usw.), dann wird Ihre Funktion den Parameter `short` mit dem `bool`-Wert `True` sehen, ansonsten mit dem Wert `False`. + +## Mehrere Pfad- und Query-Parameter + +Sie können mehrere Pfad-Parameter und Query-Parameter gleichzeitig deklarieren, **FastAPI** weiß, was welches ist. + +Und Sie müssen sie auch nicht in einer spezifischen Reihenfolge deklarieren. + +Parameter werden anhand ihres Namens erkannt: + +{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *} + +## Erforderliche Query-Parameter + +Wenn Sie einen Defaultwert für Nicht-Pfad-Parameter deklarieren (Bis jetzt haben wir nur Query-Parameter gesehen), dann ist der Parameter nicht erforderlich. + +Wenn Sie keinen spezifischen Wert haben wollen, sondern der Parameter einfach optional sein soll, dann setzen Sie den Defaultwert auf `None`. + +Aber wenn Sie wollen, dass ein Query-Parameter erforderlich ist, vergeben Sie einfach keinen Defaultwert: + +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} + +Hier ist `needy` ein erforderlicher Query-Parameter vom Typ `str`. + +Wenn Sie in Ihrem Browser eine URL wie: + +``` +http://127.0.0.1:8000/items/foo-item +``` + +... öffnen, ohne den benötigten Parameter `needy`, dann erhalten Sie einen Fehler wie den folgenden: + +```JSON +{ + "detail": [ + { + "type": "missing", + "loc": [ + "query", + "needy" + ], + "msg": "Field required", + "input": null, + "url": "https://errors.pydantic.dev/2.1/v/missing" + } + ] +} +``` + +Da `needy` ein erforderlicher Parameter ist, müssen Sie ihn in der URL setzen: + +``` +http://127.0.0.1:8000/items/foo-item?needy=sooooneedy +``` + +... Das funktioniert: + +```JSON +{ + "item_id": "foo-item", + "needy": "sooooneedy" +} +``` + +Und natürlich können Sie einige Parameter als erforderlich, einige mit Defaultwert, und einige als vollständig optional definieren: + +{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *} + +In diesem Fall gibt es drei Query-Parameter: + +* `needy`, ein erforderlicher `str`. +* `skip`, ein `int` mit einem Defaultwert `0`. +* `limit`, ein optionales `int`. + +/// tip | Tipp + +Sie können auch `Enum`s verwenden, auf die gleiche Weise wie mit [Pfad-Parametern](path-params.md#vordefinierte-parameterwerte){.internal-link target=_blank}. + +/// diff --git a/docs/de/docs/tutorial/request-files.md b/docs/de/docs/tutorial/request-files.md new file mode 100644 index 000000000..1f01b0d1e --- /dev/null +++ b/docs/de/docs/tutorial/request-files.md @@ -0,0 +1,172 @@ +# Dateien im Request + +Mit `File` können sie vom Client hochzuladende Dateien definieren. + +/// info + +Um hochgeladene Dateien zu empfangen, installieren Sie zuerst `python-multipart`. + +Z. B. `pip install python-multipart`. + +Das, weil hochgeladene Dateien als „Formulardaten“ gesendet werden. + +/// + +## `File` importieren + +Importieren Sie `File` und `UploadFile` von `fastapi`: + +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[3] *} + +## `File`-Parameter definieren + +Erstellen Sie Datei-Parameter, so wie Sie es auch mit `Body` und `Form` machen würden: + +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[9] *} + +/// info + +`File` ist eine Klasse, die direkt von `Form` erbt. + +Aber erinnern Sie sich, dass, wenn Sie `Query`, `Path`, `File` und andere von `fastapi` importieren, diese tatsächlich Funktionen sind, welche spezielle Klassen zurückgeben + +/// + +/// tip | Tipp + +Um Dateibodys zu deklarieren, müssen Sie `File` verwenden, da diese Parameter sonst als Query-Parameter oder Body(-JSON)-Parameter interpretiert werden würden. + +/// + +Die Dateien werden als „Formulardaten“ hochgeladen. + +Wenn Sie den Typ Ihrer *Pfadoperation-Funktion* als `bytes` deklarieren, wird **FastAPI** die Datei für Sie auslesen, und Sie erhalten den Inhalt als `bytes`. + +Bedenken Sie, dass das bedeutet, dass sich der gesamte Inhalt der Datei im Arbeitsspeicher befindet. Das wird für kleinere Dateien gut funktionieren. + +Aber es gibt viele Fälle, in denen Sie davon profitieren, `UploadFile` zu verwenden. + +## Datei-Parameter mit `UploadFile` + +Definieren Sie einen Datei-Parameter mit dem Typ `UploadFile`: + +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[14] *} + +`UploadFile` zu verwenden, hat mehrere Vorzüge gegenüber `bytes`: + +* Sie müssen `File()` nicht als Parameter-Defaultwert verwenden. +* Es wird eine „Spool“-Datei verwendet: + * Eine Datei, die bis zu einem bestimmten Größen-Limit im Arbeitsspeicher behalten wird, und wenn das Limit überschritten wird, auf der Festplatte gespeichert wird. +* Das bedeutet, es wird für große Dateien wie Bilder, Videos, große Binärdateien, usw. gut funktionieren, ohne den ganzen Arbeitsspeicher aufzubrauchen. +* Sie können Metadaten aus der hochgeladenen Datei auslesen. +* Es hat eine file-like `async`hrone Schnittstelle. +* Es stellt ein tatsächliches Python-`SpooledTemporaryFile`-Objekt bereit, welches Sie direkt anderen Bibliotheken übergeben können, die ein dateiartiges Objekt erwarten. + +### `UploadFile` + +`UploadFile` hat die folgenden Attribute: + +* `filename`: Ein `str` mit dem ursprünglichen Namen der hochgeladenen Datei (z. B. `meinbild.jpg`). +* `content_type`: Ein `str` mit dem Inhaltstyp (MIME-Typ / Medientyp) (z. B. `image/jpeg`). +* `file`: Ein `SpooledTemporaryFile` (ein file-like Objekt). Das ist das tatsächliche Python-Objekt, das Sie direkt anderen Funktionen oder Bibliotheken übergeben können, welche ein „file-like“-Objekt erwarten. + +`UploadFile` hat die folgenden `async`hronen Methoden. Sie alle rufen die entsprechenden Methoden des darunterliegenden Datei-Objekts auf (wobei intern `SpooledTemporaryFile` verwendet wird). + +* `write(daten)`: Schreibt `daten` (`str` oder `bytes`) in die Datei. +* `read(anzahl)`: Liest `anzahl` (`int`) bytes/Zeichen aus der Datei. +* `seek(versatz)`: Geht zur Position `versatz` (`int`) in der Datei. + * Z. B. würde `await myfile.seek(0)` zum Anfang der Datei gehen. + * Das ist besonders dann nützlich, wenn Sie `await myfile.read()` einmal ausführen und dann diese Inhalte erneut auslesen müssen. +* `close()`: Schließt die Datei. + +Da alle diese Methoden `async`hron sind, müssen Sie sie `await`en („erwarten“). + +Zum Beispiel können Sie innerhalb einer `async` *Pfadoperation-Funktion* den Inhalt wie folgt auslesen: + +```Python +contents = await myfile.read() +``` + +Wenn Sie sich innerhalb einer normalen `def`-*Pfadoperation-Funktion* befinden, können Sie direkt auf `UploadFile.file` zugreifen, zum Beispiel: + +```Python +contents = myfile.file.read() +``` + +/// note | Technische Details zu `async` + +Wenn Sie die `async`-Methoden verwenden, führt **FastAPI** die Datei-Methoden in einem Threadpool aus und erwartet sie. + +/// + +/// note | Technische Details zu Starlette + +**FastAPI**s `UploadFile` erbt direkt von **Starlette**s `UploadFile`, fügt aber ein paar notwendige Teile hinzu, um es kompatibel mit **Pydantic** und anderen Teilen von FastAPI zu machen. + +/// + +## Was sind „Formulardaten“ + +HTML-Formulare (`
`) senden die Daten in einer „speziellen“ Kodierung zum Server, welche sich von JSON unterscheidet. + +**FastAPI** stellt sicher, dass diese Daten korrekt ausgelesen werden, statt JSON zu erwarten. + +/// note | Technische Details + +Daten aus Formularen werden, wenn es keine Dateien sind, normalerweise mit dem „media type“ `application/x-www-form-urlencoded` kodiert. + +Sollte das Formular aber Dateien enthalten, dann werden diese mit `multipart/form-data` kodiert. Wenn Sie `File` verwenden, wird **FastAPI** wissen, dass es die Dateien vom korrekten Teil des Bodys holen muss. + +Wenn Sie mehr über Formularfelder und ihre Kodierungen lesen möchten, besuchen Sie die MDN-Webdokumentation für POST. + +/// + +/// warning | Achtung + +Sie können mehrere `File`- und `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `multipart/form-data` statt `application/json` kodiert. + +Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls. + +/// + +## Optionaler Datei-Upload + +Sie können eine Datei optional machen, indem Sie Standard-Typannotationen verwenden und den Defaultwert auf `None` setzen: + +{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *} + +## `UploadFile` mit zusätzlichen Metadaten + +Sie können auch `File()` zusammen mit `UploadFile` verwenden, um zum Beispiel zusätzliche Metadaten zu setzen: + +{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *} + +## Mehrere Datei-Uploads + +Es ist auch möglich, mehrere Dateien gleichzeitig hochzuladen. + +Diese werden demselben Formularfeld zugeordnet, welches mit den Formulardaten gesendet wird. + +Um das zu machen, deklarieren Sie eine Liste von `bytes` oder `UploadFile`s: + +{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *} + +Sie erhalten, wie deklariert, eine `list`e von `bytes` oder `UploadFile`s. + +/// note | Technische Details + +Sie können auch `from starlette.responses import HTMLResponse` verwenden. + +**FastAPI** bietet dieselben `starlette.responses` auch via `fastapi.responses` an, als Annehmlichkeit für Sie, den Entwickler. Die meisten verfügbaren Responses kommen aber direkt von Starlette. + +/// + +### Mehrere Datei-Uploads mit zusätzlichen Metadaten + +Und so wie zuvor können Sie `File()` verwenden, um zusätzliche Parameter zu setzen, sogar für `UploadFile`: + +{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *} + +## Zusammenfassung + +Verwenden Sie `File`, `bytes` und `UploadFile`, um hochladbare Dateien im Request zu deklarieren, die als Formulardaten gesendet werden. diff --git a/docs/de/docs/tutorial/request-forms-and-files.md b/docs/de/docs/tutorial/request-forms-and-files.md new file mode 100644 index 000000000..3c5e11adf --- /dev/null +++ b/docs/de/docs/tutorial/request-forms-and-files.md @@ -0,0 +1,37 @@ +# Formulardaten und Dateien im Request + +Sie können gleichzeitig Dateien und Formulardaten mit `File` und `Form` definieren. + +/// info + +Um hochgeladene Dateien und/oder Formulardaten zu empfangen, installieren Sie zuerst `python-multipart`. + +Z. B. `pip install python-multipart`. + +/// + +## `File` und `Form` importieren + +{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[3] *} + +## `File` und `Form`-Parameter definieren + +Erstellen Sie Datei- und Formularparameter, so wie Sie es auch mit `Body` und `Query` machen würden: + +{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[10:12] *} + +Die Datei- und Formularfelder werden als Formulardaten hochgeladen, und Sie erhalten diese Dateien und Formularfelder. + +Und Sie können einige der Dateien als `bytes` und einige als `UploadFile` deklarieren. + +/// warning | Achtung + +Sie können mehrere `File`- und `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `multipart/form-data` statt `application/json` kodiert. + +Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls. + +/// + +## Zusammenfassung + +Verwenden Sie `File` und `Form` zusammen, wenn Sie Daten und Dateien zusammen im selben Request empfangen müssen. diff --git a/docs/de/docs/tutorial/request-forms.md b/docs/de/docs/tutorial/request-forms.md new file mode 100644 index 000000000..2f88caaba --- /dev/null +++ b/docs/de/docs/tutorial/request-forms.md @@ -0,0 +1,69 @@ +# Formulardaten + +Wenn Sie Felder aus Formularen statt JSON empfangen müssen, können Sie `Form` verwenden. + +/// info + +Um Formulare zu verwenden, installieren Sie zuerst `python-multipart`. + +Z. B. `pip install python-multipart`. + +/// + +## `Form` importieren + +Importieren Sie `Form` von `fastapi`: + +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[3] *} + +## `Form`-Parameter definieren + +Erstellen Sie Formular-Parameter, so wie Sie es auch mit `Body` und `Query` machen würden: + +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[9] *} + +Zum Beispiel stellt eine der Möglichkeiten, die OAuth2 Spezifikation zu verwenden (genannt „password flow“), die Bedingung, einen `username` und ein `password` als Formularfelder zu senden. + +Die Spec erfordert, dass die Felder exakt `username` und `password` genannt werden und als Formularfelder, nicht JSON, gesendet werden. + +Mit `Form` haben Sie die gleichen Konfigurationsmöglichkeiten wie mit `Body` (und `Query`, `Path`, `Cookie`), inklusive Validierung, Beispielen, einem Alias (z. B. `user-name` statt `username`), usw. + +/// info + +`Form` ist eine Klasse, die direkt von `Body` erbt. + +/// + +/// tip | Tipp + +Um Formularbodys zu deklarieren, verwenden Sie explizit `Form`, da diese Parameter sonst als Query-Parameter oder Body(-JSON)-Parameter interpretiert werden würden. + +/// + +## Über „Formularfelder“ + +HTML-Formulare (`
`) senden die Daten in einer „speziellen“ Kodierung zum Server, welche sich von JSON unterscheidet. + +**FastAPI** stellt sicher, dass diese Daten korrekt ausgelesen werden, statt JSON zu erwarten. + +/// note | Technische Details + +Daten aus Formularen werden normalerweise mit dem „media type“ `application/x-www-form-urlencoded` kodiert. + +Wenn das Formular stattdessen Dateien enthält, werden diese mit `multipart/form-data` kodiert. Im nächsten Kapitel erfahren Sie mehr über die Handhabung von Dateien. + +Wenn Sie mehr über Formularfelder und ihre Kodierungen lesen möchten, besuchen Sie die MDN-Webdokumentation für POST. + +/// + +/// warning | Achtung + +Sie können mehrere `Form`-Parameter in einer *Pfadoperation* deklarieren, aber Sie können nicht gleichzeitig auch `Body`-Felder deklarieren, welche Sie als JSON erwarten, da der Request den Body mittels `application/x-www-form-urlencoded` statt `application/json` kodiert. + +Das ist keine Limitation von **FastAPI**, sondern Teil des HTTP-Protokolls. + +/// + +## Zusammenfassung + +Verwenden Sie `Form`, um Eingabe-Parameter für Formulardaten zu deklarieren. diff --git a/docs/de/docs/tutorial/response-model.md b/docs/de/docs/tutorial/response-model.md new file mode 100644 index 000000000..faf9be516 --- /dev/null +++ b/docs/de/docs/tutorial/response-model.md @@ -0,0 +1,348 @@ +# Responsemodell – Rückgabetyp + +Sie können den Typ der Response deklarieren, indem Sie den **Rückgabetyp** der *Pfadoperation* annotieren. + +Hierbei können Sie **Typannotationen** genauso verwenden, wie Sie es bei Werten von Funktions-**Parametern** machen; verwenden Sie Pydantic-Modelle, Listen, Dicts und skalare Werte wie Nummern, Booleans, usw. + +{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *} + +FastAPI wird diesen Rückgabetyp verwenden, um: + +* Die zurückzugebenden Daten zu **validieren**. + * Wenn die Daten ungültig sind (Sie haben z. B. ein Feld vergessen), bedeutet das, *Ihr* Anwendungscode ist fehlerhaft, er gibt nicht zurück, was er sollte, und daher wird ein Server-Error ausgegeben, statt falscher Daten. So können Sie und ihre Clients sicher sein, dass diese die erwarteten Daten, in der richtigen Form erhalten. +* In der OpenAPI *Pfadoperation* ein **JSON-Schema** für die Response hinzuzufügen. + * Dieses wird von der **automatischen Dokumentation** verwendet. + * Es wird auch von automatisch Client-Code-generierenden Tools verwendet. + +Aber am wichtigsten: + +* Es wird die Ausgabedaten auf das **limitieren und filtern**, was im Rückgabetyp definiert ist. + * Das ist insbesondere für die **Sicherheit** wichtig, mehr dazu unten. + +## `response_model`-Parameter + +Es gibt Fälle, da möchten oder müssen Sie Daten zurückgeben, die nicht genau dem entsprechen, was der Typ deklariert. + +Zum Beispiel könnten Sie **ein Dict zurückgeben** wollen, oder ein Datenbank-Objekt, aber **es als Pydantic-Modell deklarieren**. Auf diese Weise übernimmt das Pydantic-Modell alle Datendokumentation, -validierung, usw. für das Objekt, welches Sie zurückgeben (z. B. ein Dict oder ein Datenbank-Objekt). + +Würden Sie eine hierfür eine Rückgabetyp-Annotation verwenden, dann würden Tools und Editoren (korrekterweise) Fehler ausgeben, die Ihnen sagen, dass Ihre Funktion einen Typ zurückgibt (z. B. ein Dict), der sich unterscheidet von dem, was Sie deklariert haben (z. B. ein Pydantic-Modell). + +In solchen Fällen können Sie statt des Rückgabetyps den **Pfadoperation-Dekorator**-Parameter `response_model` verwenden. + +Sie können `response_model` in jeder möglichen *Pfadoperation* verwenden: + +* `@app.get()` +* `@app.post()` +* `@app.put()` +* `@app.delete()` +* usw. + +{* ../../docs_src/response_model/tutorial001_py310.py hl[17,22,24:27] *} + +/// note | Hinweis + +Beachten Sie, dass `response_model` ein Parameter der „Dekorator“-Methode ist (`get`, `post`, usw.). Nicht der *Pfadoperation-Funktion*, so wie die anderen Parameter. + +/// + +`response_model` nimmt denselben Typ entgegen, den Sie auch für ein Pydantic-Modellfeld deklarieren würden, also etwa ein Pydantic-Modell, aber es kann auch z. B. eine `list`e von Pydantic-Modellen sein, wie etwa `List[Item]`. + +FastAPI wird dieses `response_model` nehmen, um die Daten zu dokumentieren, validieren, usw. und auch, um **die Ausgabedaten** entsprechend der Typdeklaration **zu konvertieren und filtern**. + +/// tip | Tipp + +Wenn Sie in Ihrem Editor strikte Typchecks haben, mypy, usw., können Sie den Funktions-Rückgabetyp als `Any` deklarieren. + +So sagen Sie dem Editor, dass Sie absichtlich *irgendetwas* zurückgeben. Aber FastAPI wird trotzdem die Dokumentation, Validierung, Filterung, usw. der Daten übernehmen, via `response_model`. + +/// + +### `response_model`-Priorität + +Wenn sowohl Rückgabetyp als auch `response_model` deklariert sind, hat `response_model` die Priorität und wird von FastAPI bevorzugt verwendet. + +So können Sie korrekte Typannotationen zu ihrer Funktion hinzufügen, die von ihrem Editor und Tools wie mypy verwendet werden. Und dennoch übernimmt FastAPI die Validierung und Dokumentation, usw., der Daten anhand von `response_model`. + +Sie können auch `response_model=None` verwenden, um das Erstellen eines Responsemodells für diese *Pfadoperation* zu unterbinden. Sie könnten das tun wollen, wenn sie Dinge annotieren, die nicht gültige Pydantic-Felder sind. Ein Beispiel dazu werden Sie in einer der Abschnitte unten sehen. + +## Dieselben Eingabedaten zurückgeben + +Im Folgenden deklarieren wir ein `UserIn`-Modell; es enthält ein Klartext-Passwort: + +{* ../../docs_src/response_model/tutorial002_py310.py hl[7,9] *} + +/// info + +Um `EmailStr` zu verwenden, installieren Sie zuerst `email-validator`. + +Z. B. `pip install email-validator` +oder `pip install pydantic[email]`. + +/// + +Wir verwenden dieses Modell, um sowohl unsere Eingabe- als auch Ausgabedaten zu deklarieren: + +{* ../../docs_src/response_model/tutorial002_py310.py hl[16] *} + +Immer wenn jetzt ein Browser einen Benutzer mit Passwort erzeugt, gibt die API dasselbe Passwort in der Response zurück. + +Hier ist das möglicherweise kein Problem, da es derselbe Benutzer ist, der das Passwort sendet. + +Aber wenn wir dasselbe Modell für eine andere *Pfadoperation* verwenden, könnten wir das Passwort dieses Benutzers zu jedem Client schicken. + +/// danger | Gefahr + +Speichern Sie niemals das Klartext-Passwort eines Benutzers, oder versenden Sie es in einer Response wie dieser, wenn Sie sich nicht der resultierenden Gefahren bewusst sind und nicht wissen, was Sie tun. + +/// + +## Ausgabemodell hinzufügen + +Wir können stattdessen ein Eingabemodell mit dem Klartext-Passwort, und ein Ausgabemodell ohne das Passwort erstellen: + +{* ../../docs_src/response_model/tutorial003_py310.py hl[9,11,16] *} + +Obwohl unsere *Pfadoperation-Funktion* hier denselben `user` von der Eingabe zurückgibt, der das Passwort enthält: + +{* ../../docs_src/response_model/tutorial003_py310.py hl[24] *} + +... haben wir deklariert, dass `response_model` das Modell `UserOut` ist, welches das Passwort nicht enthält: + +{* ../../docs_src/response_model/tutorial003_py310.py hl[22] *} + +Darum wird **FastAPI** sich darum kümmern, dass alle Daten, die nicht im Ausgabemodell deklariert sind, herausgefiltert werden (mittels Pydantic). + +### `response_model` oder Rückgabewert + +Da unsere zwei Modelle in diesem Fall unterschiedlich sind, würde, wenn wir den Rückgabewert der Funktion als `UserOut` deklarieren, der Editor sich beschweren, dass wir einen ungültigen Typ zurückgeben, weil das unterschiedliche Klassen sind. + +Darum müssen wir es in diesem Fall im `response_model`-Parameter deklarieren. + +... aber lesen Sie weiter, um zu sehen, wie man das anders lösen kann. + +## Rückgabewert und Datenfilterung + +Führen wir unser vorheriges Beispiel fort. Wir wollten **die Funktion mit einem Typ annotieren**, aber etwas zurückgeben, das **weniger Daten** enthält. + +Wir möchten auch, dass FastAPI die Daten weiterhin, dem Responsemodell entsprechend, **filtert**. + +Im vorherigen Beispiel mussten wir den `response_model`-Parameter verwenden, weil die Klassen unterschiedlich waren. Das bedeutet aber auch, wir bekommen keine Unterstützung vom Editor und anderen Tools, die den Funktions-Rückgabewert überprüfen. + +Aber in den meisten Fällen, wenn wir so etwas machen, wollen wir nur, dass das Modell einige der Daten **filtert/entfernt**, so wie in diesem Beispiel. + +Und in solchen Fällen können wir Klassen und Vererbung verwenden, um Vorteil aus den Typannotationen in der Funktion zu ziehen, was vom Editor und von Tools besser unterstützt wird, während wir gleichzeitig FastAPIs **Datenfilterung** behalten. + +{* ../../docs_src/response_model/tutorial003_01_py310.py hl[7:10,13:14,18] *} + +Damit erhalten wir Tool-Unterstützung, vom Editor und mypy, da dieser Code hinsichtlich der Typen korrekt ist, aber wir erhalten auch die Datenfilterung von FastAPI. + +Wie funktioniert das? Schauen wir uns das mal an. 🤓 + +### Typannotationen und Tooling + +Sehen wir uns zunächst an, wie Editor, mypy und andere Tools dies sehen würden. + +`BaseUser` verfügt über die Basis-Felder. Dann erbt `UserIn` von `BaseUser` und fügt das Feld `Passwort` hinzu, sodass dass es nun alle Felder beider Modelle hat. + +Wir annotieren den Funktionsrückgabetyp als `BaseUser`, geben aber tatsächlich eine `UserIn`-Instanz zurück. + +Für den Editor, mypy und andere Tools ist das kein Problem, da `UserIn` eine Unterklasse von `BaseUser` ist (Salopp: `UserIn` ist ein `BaseUser`). Es handelt sich um einen *gültigen* Typ, solange irgendetwas überreicht wird, das ein `BaseUser` ist. + +### FastAPI Datenfilterung + +FastAPI seinerseits wird den Rückgabetyp sehen und sicherstellen, dass das, was zurückgegeben wird, **nur** diejenigen Felder enthält, welche im Typ deklariert sind. + +FastAPI macht intern mehrere Dinge mit Pydantic, um sicherzustellen, dass obige Ähnlichkeitsregeln der Klassenvererbung nicht auf die Filterung der zurückgegebenen Daten angewendet werden, sonst könnten Sie am Ende mehr Daten zurückgeben als gewollt. + +Auf diese Weise erhalten Sie das beste beider Welten: Sowohl Typannotationen mit **Tool-Unterstützung** als auch **Datenfilterung**. + +## Anzeige in der Dokumentation + +Wenn Sie sich die automatische Dokumentation betrachten, können Sie sehen, dass Eingabe- und Ausgabemodell beide ihr eigenes JSON-Schema haben: + + + +Und beide Modelle werden auch in der interaktiven API-Dokumentation verwendet: + + + +## Andere Rückgabetyp-Annotationen + +Es kann Fälle geben, bei denen Sie etwas zurückgeben, das kein gültiges Pydantic-Feld ist, und Sie annotieren es in der Funktion nur, um Unterstützung von Tools zu erhalten (Editor, mypy, usw.). + +### Eine Response direkt zurückgeben + +Der häufigste Anwendungsfall ist, wenn Sie [eine Response direkt zurückgeben, wie es später im Handbuch für fortgeschrittene Benutzer erläutert wird](../advanced/response-directly.md){.internal-link target=_blank}. + +{* ../../docs_src/response_model/tutorial003_02.py hl[8,10:11] *} + +Dieser einfache Anwendungsfall wird automatisch von FastAPI gehandhabt, weil die Annotation des Rückgabetyps die Klasse (oder eine Unterklasse von) `Response` ist. + +Und Tools werden auch glücklich sein, weil sowohl `RedirectResponse` als auch `JSONResponse` Unterklassen von `Response` sind, die Typannotation ist daher korrekt. + +### Eine Unterklasse von Response annotieren + +Sie können auch eine Unterklasse von `Response` in der Typannotation verwenden. + +{* ../../docs_src/response_model/tutorial003_03.py hl[8:9] *} + +Das wird ebenfalls funktionieren, weil `RedirectResponse` eine Unterklasse von `Response` ist, und FastAPI sich um diesen einfachen Anwendungsfall automatisch kümmert. + +### Ungültige Rückgabetyp-Annotationen + +Aber wenn Sie ein beliebiges anderes Objekt zurückgeben, das kein gültiger Pydantic-Typ ist (z. B. ein Datenbank-Objekt), und Sie annotieren es so in der Funktion, wird FastAPI versuchen, ein Pydantic-Responsemodell von dieser Typannotation zu erstellen, und scheitern. + +Das gleiche wird passieren, wenn Sie eine Union mehrerer Typen haben, und einer oder mehrere sind nicht gültige Pydantic-Typen. Zum Beispiel funktioniert folgendes nicht 💥: + +{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *} + +... das scheitert, da die Typannotation kein Pydantic-Typ ist, und auch keine einzelne `Response`-Klasse, oder -Unterklasse, es ist eine Union (eines von beiden) von `Response` und `dict`. + +### Responsemodell deaktivieren + +Beim Beispiel oben fortsetzend, mögen Sie vielleicht die standardmäßige Datenvalidierung, -Dokumentation, -Filterung, usw., die von FastAPI durchgeführt wird, nicht haben. + +Aber Sie möchten dennoch den Rückgabetyp in der Funktion annotieren, um Unterstützung von Editoren und Typcheckern (z. B. mypy) zu erhalten. + +In diesem Fall können Sie die Generierung des Responsemodells abschalten, indem Sie `response_model=None` setzen: + +{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *} + +Das bewirkt, dass FastAPI die Generierung des Responsemodells unterlässt, und damit können Sie jede gewünschte Rückgabetyp-Annotation haben, ohne dass es Ihre FastAPI-Anwendung beeinflusst. 🤓 + +## Parameter für die Enkodierung des Responsemodells + +Ihr Responsemodell könnte Defaultwerte haben, wie: + +{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *} + +* `description: Union[str, None] = None` (oder `str | None = None` in Python 3.10) hat einen Defaultwert `None`. +* `tax: float = 10.5` hat einen Defaultwert `10.5`. +* `tags: List[str] = []` hat eine leere Liste als Defaultwert: `[]`. + +Aber Sie möchten diese vielleicht vom Resultat ausschließen, wenn Sie gar nicht gesetzt wurden. + +Wenn Sie zum Beispiel Modelle mit vielen optionalen Attributen in einer NoSQL-Datenbank haben, und Sie möchten nicht ellenlange JSON-Responses voller Defaultwerte senden. + +### Den `response_model_exclude_unset`-Parameter verwenden + +Sie können den *Pfadoperation-Dekorator*-Parameter `response_model_exclude_unset=True` setzen: + +{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *} + +Die Defaultwerte werden dann nicht in der Response enthalten sein, sondern nur die tatsächlich gesetzten Werte. + +Wenn Sie also den Artikel mit der ID `foo` bei der *Pfadoperation* anfragen, wird (ohne die Defaultwerte) die Response sein: + +```JSON +{ + "name": "Foo", + "price": 50.2 +} +``` + +/// info + +In Pydantic v1 hieß diese Methode `.dict()`, in Pydantic v2 wurde sie deprecated (aber immer noch unterstützt) und in `.model_dump()` umbenannt. + +Die Beispiele hier verwenden `.dict()` für die Kompatibilität mit Pydantic v1, Sie sollten jedoch stattdessen `.model_dump()` verwenden, wenn Sie Pydantic v2 verwenden können. + +/// + +/// info + +FastAPI verwendet `.dict()` von Pydantic Modellen, mit dessen `exclude_unset`-Parameter, um das zu erreichen. + +/// + +/// info + +Sie können auch: + +* `response_model_exclude_defaults=True` +* `response_model_exclude_none=True` + +verwenden, wie in der Pydantic Dokumentation für `exclude_defaults` und `exclude_none` beschrieben. + +/// + +#### Daten mit Werten für Felder mit Defaultwerten + +Aber wenn ihre Daten Werte für Modellfelder mit Defaultwerten haben, wie etwa der Artikel mit der ID `bar`: + +```Python hl_lines="3 5" +{ + "name": "Bar", + "description": "The bartenders", + "price": 62, + "tax": 20.2 +} +``` + +dann werden diese Werte in der Response enthalten sein. + +#### Daten mit den gleichen Werten wie die Defaultwerte + +Wenn Daten die gleichen Werte haben wie ihre Defaultwerte, wie etwa der Artikel mit der ID `baz`: + +```Python hl_lines="3 5-6" +{ + "name": "Baz", + "description": None, + "price": 50.2, + "tax": 10.5, + "tags": [] +} +``` + +dann ist FastAPI klug genug (tatsächlich ist Pydantic klug genug) zu erkennen, dass, obwohl `description`, `tax`, und `tags` die gleichen Werte haben wie ihre Defaultwerte, sie explizit gesetzt wurden (statt dass sie von den Defaultwerten genommen wurden). + +Diese Felder werden also in der JSON-Response enthalten sein. + +/// tip | Tipp + +Beachten Sie, dass Defaultwerte alles Mögliche sein können, nicht nur `None`. + +Sie können eine Liste (`[]`), ein `float` `10.5`, usw. sein. + +/// + +### `response_model_include` und `response_model_exclude` + +Sie können auch die Parameter `response_model_include` und `response_model_exclude` im **Pfadoperation-Dekorator** verwenden. + +Diese nehmen ein `set` von `str`s entgegen, welches Namen von Attributen sind, die eingeschlossen (ohne die Anderen) oder ausgeschlossen (nur die Anderen) werden sollen. + +Das kann als schnelle Abkürzung verwendet werden, wenn Sie nur ein Pydantic-Modell haben und ein paar Daten von der Ausgabe ausschließen wollen. + +/// tip | Tipp + +Es wird dennoch empfohlen, dass Sie die Ideen von oben verwenden, also mehrere Klassen statt dieser Parameter. + +Der Grund ist, dass das das generierte JSON-Schema in der OpenAPI ihrer Anwendung (und deren Dokumentation) dennoch das komplette Modell abbildet, selbst wenn Sie `response_model_include` oder `response_model_exclude` verwenden, um einige Attribute auszuschließen. + +Das trifft auch auf `response_model_by_alias` zu, welches ähnlich funktioniert. + +/// + +{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *} + +/// tip | Tipp + +Die Syntax `{"name", "description"}` erzeugt ein `set` mit diesen zwei Werten. + +Äquivalent zu `set(["name", "description"])`. + +/// + +#### `list`en statt `set`s verwenden + +Wenn Sie vergessen, ein `set` zu verwenden, und stattdessen eine `list`e oder ein `tuple` übergeben, wird FastAPI die dennoch in ein `set` konvertieren, und es wird korrekt funktionieren: + +{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *} + +## Zusammenfassung + +Verwenden Sie den Parameter `response_model` im *Pfadoperation-Dekorator*, um Responsemodelle zu definieren, und besonders, um private Daten herauszufiltern. + +Verwenden Sie `response_model_exclude_unset`, um nur explizit gesetzte Werte zurückzugeben. diff --git a/docs/de/docs/tutorial/response-status-code.md b/docs/de/docs/tutorial/response-status-code.md new file mode 100644 index 000000000..a1b388a0a --- /dev/null +++ b/docs/de/docs/tutorial/response-status-code.md @@ -0,0 +1,101 @@ +# Response-Statuscode + +So wie ein Responsemodell, können Sie auch einen HTTP-Statuscode für die Response deklarieren, mithilfe des Parameters `status_code`, und zwar in jeder der *Pfadoperationen*: + +* `@app.get()` +* `@app.post()` +* `@app.put()` +* `@app.delete()` +* usw. + +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} + +/// note | Hinweis + +Beachten Sie, dass `status_code` ein Parameter der „Dekorator“-Methode ist (`get`, `post`, usw.). Nicht der *Pfadoperation-Funktion*, so wie die anderen Parameter und der Body. + +/// + +Dem `status_code`-Parameter wird eine Zahl mit dem HTTP-Statuscode übergeben. + +/// info + +Alternativ kann `status_code` auch ein `IntEnum` erhalten, so wie Pythons `http.HTTPStatus`. + +/// + +Das wird: + +* Diesen Statuscode mit der Response zurücksenden. +* Ihn als solchen im OpenAPI-Schema dokumentieren (und somit in den Benutzeroberflächen): + + + +/// note | Hinweis + +Einige Responsecodes (siehe nächster Abschnitt) kennzeichnen, dass die Response keinen Body hat. + +FastAPI versteht das und wird in der OpenAPI-Dokumentation anzeigen, dass es keinen Responsebody gibt. + +/// + +## Über HTTP-Statuscodes + +/// note | Hinweis + +Wenn Sie bereits wissen, was HTTP-Statuscodes sind, überspringen Sie dieses Kapitel und fahren Sie mit dem nächsten fort. + +/// + +In HTTP senden Sie als Teil der Response einen aus drei Ziffern bestehenden numerischen Statuscode. + +Diese Statuscodes haben einen Namen zugeordnet, um sie besser zu erkennen, aber der wichtige Teil ist die Zahl. + +Kurz: + +* `100` und darüber stehen für „Information“. Diese verwenden Sie selten direkt. Responses mit diesen Statuscodes können keinen Body haben. +* **`200`** und darüber stehen für Responses, die „Successful“ („Erfolgreich“) waren. Diese verwenden Sie am häufigsten. + * `200` ist der Default-Statuscode, welcher bedeutet, alles ist „OK“. + * Ein anderes Beispiel ist `201`, „Created“ („Erzeugt“). Wird in der Regel verwendet, wenn ein neuer Datensatz in der Datenbank erzeugt wurde. + * Ein spezieller Fall ist `204`, „No Content“ („Kein Inhalt“). Diese Response wird verwendet, wenn es keinen Inhalt gibt, der zum Client zurückgeschickt wird, diese Response hat also keinen Body. +* **`300`** und darüber steht für „Redirection“ („Umleitung“). Responses mit diesen Statuscodes können einen oder keinen Body haben, mit Ausnahme von `304`, „Not Modified“ („Nicht verändert“), welche keinen haben darf. +* **`400`** und darüber stehen für „Client error“-Responses („Client-Fehler“). Auch diese verwenden Sie am häufigsten. + * Ein Beispiel ist `404`, für eine „Not Found“-Response („Nicht gefunden“). + * Für allgemeine Fehler beim Client können Sie einfach `400` verwenden. +* `500` und darüber stehen für Server-Fehler. Diese verwenden Sie fast nie direkt. Wenn etwas an irgendeiner Stelle in Ihrem Anwendungscode oder im Server schiefläuft, wird automatisch einer dieser Fehler-Statuscodes zurückgegeben. + +/// tip | Tipp + +Um mehr über Statuscodes zu lernen, und welcher wofür verwendet wird, lesen Sie die MDN Dokumentation über HTTP-Statuscodes. + +/// + +## Abkürzung, um die Namen zu erinnern + +Schauen wir uns das vorherige Beispiel noch einmal an: + +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} + +`201` ist der Statuscode für „Created“ („Erzeugt“). + +Aber Sie müssen sich nicht daran erinnern, welcher dieser Codes was bedeutet. + +Sie können die Hilfsvariablen von `fastapi.status` verwenden. + +{* ../../docs_src/response_status_code/tutorial002.py hl[1,6] *} + +Diese sind nur eine Annehmlichkeit und enthalten dieselbe Nummer, aber auf diese Weise können Sie die Autovervollständigung Ihres Editors verwenden, um sie zu finden: + + + +/// note | Technische Details + +Sie können auch `from starlette import status` verwenden. + +**FastAPI** bietet dieselben `starlette.status`-Codes auch via `fastapi.status` an, als Annehmlichkeit für Sie, den Entwickler. Sie kommen aber direkt von Starlette. + +/// + +## Den Defaultwert ändern + +Später sehen Sie, im [Handbuch für fortgeschrittene Benutzer](../advanced/response-change-status-code.md){.internal-link target=_blank}, wie Sie einen anderen Statuscode zurückgeben können, als den Default, den Sie hier deklarieren. diff --git a/docs/de/docs/tutorial/schema-extra-example.md b/docs/de/docs/tutorial/schema-extra-example.md new file mode 100644 index 000000000..f065ad4ca --- /dev/null +++ b/docs/de/docs/tutorial/schema-extra-example.md @@ -0,0 +1,224 @@ +# Beispiel-Request-Daten deklarieren + +Sie können Beispiele für die Daten deklarieren, die Ihre Anwendung empfangen kann. + +Hier sind mehrere Möglichkeiten, das zu tun. + +## Zusätzliche JSON-Schemadaten in Pydantic-Modellen + +Sie können `examples` („Beispiele“) für ein Pydantic-Modell deklarieren, welche dem generierten JSON-Schema hinzugefügt werden. + +//// tab | Pydantic v2 + +{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:24] *} + +//// + +//// tab | Pydantic v1 + +{* ../../docs_src/schema_extra_example/tutorial001_pv1_py310.py hl[13:23] *} + +//// + +Diese zusätzlichen Informationen werden unverändert zum für dieses Modell ausgegebenen **JSON-Schema** hinzugefügt und in der API-Dokumentation verwendet. + +//// tab | Pydantic v2 + +In Pydantic Version 2 würden Sie das Attribut `model_config` verwenden, das ein `dict` akzeptiert, wie beschrieben in Pydantic-Dokumentation: Configuration. + +Sie können `json_schema_extra` setzen, mit einem `dict`, das alle zusätzlichen Daten enthält, die im generierten JSON-Schema angezeigt werden sollen, einschließlich `examples`. + +//// + +//// tab | Pydantic v1 + +In Pydantic Version 1 würden Sie eine interne Klasse `Config` und `schema_extra` verwenden, wie beschrieben in Pydantic-Dokumentation: Schema customization. + +Sie können `schema_extra` setzen, mit einem `dict`, das alle zusätzlichen Daten enthält, die im generierten JSON-Schema angezeigt werden sollen, einschließlich `examples`. + +//// + +/// tip | Tipp + +Mit derselben Technik können Sie das JSON-Schema erweitern und Ihre eigenen benutzerdefinierten Zusatzinformationen hinzufügen. + +Sie könnten das beispielsweise verwenden, um Metadaten für eine Frontend-Benutzeroberfläche usw. hinzuzufügen. + +/// + +/// info + +OpenAPI 3.1.0 (verwendet seit FastAPI 0.99.0) hat Unterstützung für `examples` hinzugefügt, was Teil des **JSON Schema** Standards ist. + +Zuvor unterstützte es nur das Schlüsselwort `example` mit einem einzigen Beispiel. Dieses wird weiterhin von OpenAPI 3.1.0 unterstützt, ist jedoch deprecated und nicht Teil des JSON Schema Standards. Wir empfehlen Ihnen daher, von `example` nach `examples` zu migrieren. 🤓 + +Mehr erfahren Sie am Ende dieser Seite. + +/// + +## Zusätzliche Argumente für `Field` + +Wenn Sie `Field()` mit Pydantic-Modellen verwenden, können Sie ebenfalls zusätzliche `examples` deklarieren: + +{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *} + +## `examples` im JSON-Schema – OpenAPI + +Bei Verwendung von: + +* `Path()` +* `Query()` +* `Header()` +* `Cookie()` +* `Body()` +* `Form()` +* `File()` + +können Sie auch eine Gruppe von `examples` mit zusätzlichen Informationen deklarieren, die zu ihren **JSON-Schemas** innerhalb von **OpenAPI** hinzugefügt werden. + +### `Body` mit `examples` + +Hier übergeben wir `examples`, welches ein einzelnes Beispiel für die in `Body()` erwarteten Daten enthält: + +{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:29] *} + +### Beispiel in der Dokumentations-Benutzeroberfläche + +Mit jeder der oben genannten Methoden würde es in `/docs` so aussehen: + + + +### `Body` mit mehreren `examples` + +Sie können natürlich auch mehrere `examples` übergeben: + +{* ../../docs_src/schema_extra_example/tutorial004_an_py310.py hl[23:38] *} + +Wenn Sie das tun, werden die Beispiele Teil des internen **JSON-Schemas** für diese Body-Daten. + +Während dies geschrieben wird, unterstützt Swagger UI, das für die Anzeige der Dokumentations-Benutzeroberfläche zuständige Tool, jedoch nicht die Anzeige mehrerer Beispiele für die Daten in **JSON Schema**. Aber lesen Sie unten für einen Workaround weiter. + +### OpenAPI-spezifische `examples` + +Schon bevor **JSON Schema** `examples` unterstützte, unterstützte OpenAPI ein anderes Feld, das auch `examples` genannt wurde. + +Diese **OpenAPI-spezifischen** `examples` finden sich in einem anderen Abschnitt der OpenAPI-Spezifikation. Sie sind **Details für jede *Pfadoperation***, nicht für jedes JSON-Schema. + +Und Swagger UI unterstützt dieses spezielle Feld `examples` schon seit einiger Zeit. Sie können es also verwenden, um verschiedene **Beispiele in der Benutzeroberfläche der Dokumentation anzuzeigen**. + +Das Format dieses OpenAPI-spezifischen Felds `examples` ist ein `dict` mit **mehreren Beispielen** (anstelle einer `list`e), jedes mit zusätzlichen Informationen, die auch zu **OpenAPI** hinzugefügt werden. + +Dies erfolgt nicht innerhalb jedes in OpenAPI enthaltenen JSON-Schemas, sondern außerhalb, in der *Pfadoperation*. + +### Verwendung des Parameters `openapi_examples` + +Sie können die OpenAPI-spezifischen `examples` in FastAPI mit dem Parameter `openapi_examples` deklarieren, für: + +* `Path()` +* `Query()` +* `Header()` +* `Cookie()` +* `Body()` +* `Form()` +* `File()` + +Die Schlüssel des `dict` identifizieren jedes Beispiel, und jeder Wert (`"value"`) ist ein weiteres `dict`. + +Jedes spezifische Beispiel-`dict` in den `examples` kann Folgendes enthalten: + +* `summary`: Kurze Beschreibung für das Beispiel. +* `description`: Eine lange Beschreibung, die Markdown-Text enthalten kann. +* `value`: Dies ist das tatsächlich angezeigte Beispiel, z. B. ein `dict`. +* `externalValue`: Alternative zu `value`, eine URL, die auf das Beispiel verweist. Allerdings wird dies möglicherweise nicht von so vielen Tools unterstützt wie `value`. + +Sie können es so verwenden: + +{* ../../docs_src/schema_extra_example/tutorial005_an_py310.py hl[23:49] *} + +### OpenAPI-Beispiele in der Dokumentations-Benutzeroberfläche + +Wenn `openapi_examples` zu `Body()` hinzugefügt wird, würde `/docs` so aussehen: + + + +## Technische Details + +/// tip | Tipp + +Wenn Sie bereits **FastAPI** Version **0.99.0 oder höher** verwenden, können Sie diese Details wahrscheinlich **überspringen**. + +Sie sind für ältere Versionen relevanter, bevor OpenAPI 3.1.0 verfügbar war. + +Sie können dies als eine kurze **Geschichtsstunde** zu OpenAPI und JSON Schema betrachten. 🤓 + +/// + +/// warning | Achtung + +Dies sind sehr technische Details zu den Standards **JSON Schema** und **OpenAPI**. + +Wenn die oben genannten Ideen bereits für Sie funktionieren, reicht das möglicherweise aus und Sie benötigen diese Details wahrscheinlich nicht, überspringen Sie sie gerne. + +/// + +Vor OpenAPI 3.1.0 verwendete OpenAPI eine ältere und modifizierte Version von **JSON Schema**. + +JSON Schema hatte keine `examples`, daher fügte OpenAPI seiner eigenen modifizierten Version ein eigenes `example`-Feld hinzu. + +OpenAPI fügte auch die Felder `example` und `examples` zu anderen Teilen der Spezifikation hinzu: + +* `Parameter Object` (in der Spezifikation), das verwendet wurde von FastAPIs: + * `Path()` + * `Query()` + * `Header()` + * `Cookie()` +* `Request Body Object` im Feld `content` des `Media Type Object`s (in der Spezifikation), das verwendet wurde von FastAPIs: + * `Body()` + * `File()` + * `Form()` + +/// info + +Dieser alte, OpenAPI-spezifische `examples`-Parameter heißt seit FastAPI `0.103.0` jetzt `openapi_examples`. + +/// + +### JSON Schemas Feld `examples` + +Aber dann fügte JSON Schema ein `examples`-Feld zu einer neuen Version der Spezifikation hinzu. + +Und dann basierte das neue OpenAPI 3.1.0 auf der neuesten Version (JSON Schema 2020-12), die dieses neue Feld `examples` enthielt. + +Und jetzt hat dieses neue `examples`-Feld Vorrang vor dem alten (und benutzerdefinierten) `example`-Feld, im Singular, das jetzt deprecated ist. + +Dieses neue `examples`-Feld in JSON Schema ist **nur eine `list`e** von Beispielen, kein Dict mit zusätzlichen Metadaten wie an den anderen Stellen in OpenAPI (oben beschrieben). + +/// info + +Selbst, nachdem OpenAPI 3.1.0 veröffentlicht wurde, mit dieser neuen, einfacheren Integration mit JSON Schema, unterstützte Swagger UI, das Tool, das die automatische Dokumentation bereitstellt, eine Zeit lang OpenAPI 3.1.0 nicht (das tut es seit Version 5.0.0 🎉). + +Aus diesem Grund verwendeten Versionen von FastAPI vor 0.99.0 immer noch Versionen von OpenAPI vor 3.1.0. + +/// + +### Pydantic- und FastAPI-`examples` + +Wenn Sie `examples` innerhalb eines Pydantic-Modells hinzufügen, indem Sie `schema_extra` oder `Field(examples=["something"])` verwenden, wird dieses Beispiel dem **JSON-Schema** für dieses Pydantic-Modell hinzugefügt. + +Und dieses **JSON-Schema** des Pydantic-Modells ist in der **OpenAPI** Ihrer API enthalten und wird dann in der Benutzeroberfläche der Dokumentation verwendet. + +In Versionen von FastAPI vor 0.99.0 (0.99.0 und höher verwenden das neuere OpenAPI 3.1.0), wenn Sie `example` oder `examples` mit einem der anderen Werkzeuge (`Query()`, `Body()`, usw.) verwendet haben, wurden diese Beispiele nicht zum JSON-Schema hinzugefügt, das diese Daten beschreibt (nicht einmal zur OpenAPI-eigenen Version von JSON Schema), sondern direkt zur *Pfadoperation*-Deklaration in OpenAPI (außerhalb der Teile von OpenAPI, die JSON Schema verwenden). + +Aber jetzt, da FastAPI 0.99.0 und höher, OpenAPI 3.1.0 verwendet, das JSON Schema 2020-12 verwendet, und Swagger UI 5.0.0 und höher, ist alles konsistenter und die Beispiele sind in JSON Schema enthalten. + +### Swagger-Benutzeroberfläche und OpenAPI-spezifische `examples`. + +Da die Swagger-Benutzeroberfläche derzeit nicht mehrere JSON Schema Beispiele unterstützt (Stand: 26.08.2023), hatten Benutzer keine Möglichkeit, mehrere Beispiele in der Dokumentation anzuzeigen. + +Um dieses Problem zu lösen, hat FastAPI `0.103.0` **Unterstützung** für die Deklaration desselben alten **OpenAPI-spezifischen** `examples`-Felds mit dem neuen Parameter `openapi_examples` hinzugefügt. 🤓 + +### Zusammenfassung + +Ich habe immer gesagt, dass ich Geschichte nicht so sehr mag ... und jetzt schauen Sie mich an, wie ich „Technikgeschichte“-Unterricht gebe. 😅 + +Kurz gesagt: **Upgraden Sie auf FastAPI 0.99.0 oder höher**, und die Dinge sind viel **einfacher, konsistenter und intuitiver**, und Sie müssen nicht alle diese historischen Details kennen. 😎 diff --git a/docs/de/docs/tutorial/security/first-steps.md b/docs/de/docs/tutorial/security/first-steps.md new file mode 100644 index 000000000..8fa33db7e --- /dev/null +++ b/docs/de/docs/tutorial/security/first-steps.md @@ -0,0 +1,197 @@ +# Sicherheit – Erste Schritte + +Stellen wir uns vor, dass Sie Ihre **Backend**-API auf einer Domain haben. + +Und Sie haben ein **Frontend** auf einer anderen Domain oder in einem anderen Pfad derselben Domain (oder in einer mobilen Anwendung). + +Und Sie möchten eine Möglichkeit haben, dass sich das Frontend mithilfe eines **Benutzernamens** und eines **Passworts** beim Backend authentisieren kann. + +Wir können **OAuth2** verwenden, um das mit **FastAPI** zu erstellen. + +Aber ersparen wir Ihnen die Zeit, die gesamte lange Spezifikation zu lesen, nur um die kleinen Informationen zu finden, die Sie benötigen. + +Lassen Sie uns die von **FastAPI** bereitgestellten Tools verwenden, um Sicherheit zu gewährleisten. + +## Wie es aussieht + +Lassen Sie uns zunächst einfach den Code verwenden und sehen, wie er funktioniert, und dann kommen wir zurück, um zu verstehen, was passiert. + +## `main.py` erstellen + +Kopieren Sie das Beispiel in eine Datei `main.py`: + +{* ../../docs_src/security/tutorial001_an_py39.py *} + +## Ausführen + +/// info + +Um hochgeladene Dateien zu empfangen, installieren Sie zuerst `python-multipart`. + +Z. B. `pip install python-multipart`. + +Das, weil **OAuth2** „Formulardaten“ zum Senden von `username` und `password` verwendet. + +/// + +Führen Sie das Beispiel aus mit: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +## Überprüfen + +Gehen Sie zu der interaktiven Dokumentation unter: http://127.0.0.1:8000/docs. + +Sie werden etwa Folgendes sehen: + + + +/// check | Authorize-Button! + +Sie haben bereits einen glänzenden, neuen „Authorize“-Button. + +Und Ihre *Pfadoperation* hat in der oberen rechten Ecke ein kleines Schloss, auf das Sie klicken können. + +/// + +Und wenn Sie darauf klicken, erhalten Sie ein kleines Anmeldeformular zur Eingabe eines `username` und `password` (und anderer optionaler Felder): + + + +/// note | Hinweis + +Es spielt keine Rolle, was Sie in das Formular eingeben, es wird noch nicht funktionieren. Wir kommen dahin. + +/// + +Dies ist natürlich nicht das Frontend für die Endbenutzer, aber es ist ein großartiges automatisches Tool, um Ihre gesamte API interaktiv zu dokumentieren. + +Es kann vom Frontend-Team verwendet werden (das auch Sie selbst sein können). + +Es kann von Anwendungen und Systemen Dritter verwendet werden. + +Und es kann auch von Ihnen selbst verwendet werden, um dieselbe Anwendung zu debuggen, zu prüfen und zu testen. + +## Der `password`-Flow + +Lassen Sie uns nun etwas zurückgehen und verstehen, was das alles ist. + +Der `password`-„Flow“ ist eine der in OAuth2 definierten Wege („Flows“) zur Handhabung von Sicherheit und Authentifizierung. + +OAuth2 wurde so konzipiert, dass das Backend oder die API unabhängig vom Server sein kann, der den Benutzer authentifiziert. + +In diesem Fall handhabt jedoch dieselbe **FastAPI**-Anwendung sowohl die API als auch die Authentifizierung. + +Betrachten wir es also aus dieser vereinfachten Sicht: + +* Der Benutzer gibt den `username` und das `password` im Frontend ein und drückt `Enter`. +* Das Frontend (das im Browser des Benutzers läuft) sendet diesen `username` und das `password` an eine bestimmte URL in unserer API (deklariert mit `tokenUrl="token"`). +* Die API überprüft den `username` und das `password` und antwortet mit einem „Token“ (wir haben davon noch nichts implementiert). + * Ein „Token“ ist lediglich ein String mit einem Inhalt, den wir später verwenden können, um diesen Benutzer zu verifizieren. + * Normalerweise läuft ein Token nach einiger Zeit ab. + * Daher muss sich der Benutzer irgendwann später erneut anmelden. + * Und wenn der Token gestohlen wird, ist das Risiko geringer. Es handelt sich nicht um einen dauerhaften Schlüssel, der (in den meisten Fällen) für immer funktioniert. +* Das Frontend speichert diesen Token vorübergehend irgendwo. +* Der Benutzer klickt im Frontend, um zu einem anderen Abschnitt der Frontend-Web-Anwendung zu gelangen. +* Das Frontend muss weitere Daten von der API abrufen. + * Es benötigt jedoch eine Authentifizierung für diesen bestimmten Endpunkt. + * Um sich also bei unserer API zu authentifizieren, sendet es einen Header `Authorization` mit dem Wert `Bearer` plus dem Token. + * Wenn der Token `foobar` enthielte, wäre der Inhalt des `Authorization`-Headers: `Bearer foobar`. + +## **FastAPI**s `OAuth2PasswordBearer` + +**FastAPI** bietet mehrere Tools auf unterschiedlichen Abstraktionsebenen zur Implementierung dieser Sicherheitsfunktionen. + +In diesem Beispiel verwenden wir **OAuth2** mit dem **Password**-Flow und einem **Bearer**-Token. Wir machen das mit der Klasse `OAuth2PasswordBearer`. + +/// info + +Ein „Bearer“-Token ist nicht die einzige Option. + +Aber es ist die beste für unseren Anwendungsfall. + +Und es ist wahrscheinlich auch für die meisten anderen Anwendungsfälle die beste, es sei denn, Sie sind ein OAuth2-Experte und wissen genau, warum es eine andere Option gibt, die Ihren Anforderungen besser entspricht. + +In dem Fall gibt Ihnen **FastAPI** ebenfalls die Tools, die Sie zum Erstellen brauchen. + +/// + +Wenn wir eine Instanz der Klasse `OAuth2PasswordBearer` erstellen, übergeben wir den Parameter `tokenUrl`. Dieser Parameter enthält die URL, die der Client (das Frontend, das im Browser des Benutzers ausgeführt wird) verwendet, wenn er den `username` und das `password` sendet, um einen Token zu erhalten. + +{* ../../docs_src/security/tutorial001_an_py39.py hl[8] *} + +/// tip | Tipp + +Hier bezieht sich `tokenUrl="token"` auf eine relative URL `token`, die wir noch nicht erstellt haben. Da es sich um eine relative URL handelt, entspricht sie `./token`. + +Da wir eine relative URL verwenden, würde sich das, wenn sich Ihre API unter `https://example.com/` befindet, auf `https://example.com/token` beziehen. Wenn sich Ihre API jedoch unter `https://example.com/api/v1/` befände, würde es sich auf `https://example.com/api/v1/token` beziehen. + +Die Verwendung einer relativen URL ist wichtig, um sicherzustellen, dass Ihre Anwendung auch in einem fortgeschrittenen Anwendungsfall, wie [hinter einem Proxy](../../advanced/behind-a-proxy.md){.internal-link target=_blank}, weiterhin funktioniert. + +/// + +Dieser Parameter erstellt nicht diesen Endpunkt / diese *Pfadoperation*, sondern deklariert, dass die URL `/token` diejenige sein wird, die der Client verwenden soll, um den Token abzurufen. Diese Information wird in OpenAPI und dann in den interaktiven API-Dokumentationssystemen verwendet. + +Wir werden demnächst auch die eigentliche Pfadoperation erstellen. + +/// info + +Wenn Sie ein sehr strenger „Pythonista“ sind, missfällt Ihnen möglicherweise die Schreibweise des Parameternamens `tokenUrl` anstelle von `token_url`. + +Das liegt daran, dass FastAPI denselben Namen wie in der OpenAPI-Spezifikation verwendet. Sodass Sie, wenn Sie mehr über eines dieser Sicherheitsschemas herausfinden möchten, den Namen einfach kopieren und einfügen können, um weitere Informationen darüber zu erhalten. + +/// + +Die Variable `oauth2_scheme` ist eine Instanz von `OAuth2PasswordBearer`, aber auch ein „Callable“. + +Es könnte wie folgt aufgerufen werden: + +```Python +oauth2_scheme(some, parameters) +``` + +Es kann also mit `Depends` verwendet werden. + +### Verwendung + +Jetzt können Sie dieses `oauth2_scheme` als Abhängigkeit `Depends` übergeben. + +{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *} + +Diese Abhängigkeit stellt einen `str` bereit, der dem Parameter `token` der *Pfadoperation-Funktion* zugewiesen wird. + +**FastAPI** weiß, dass es diese Abhängigkeit verwenden kann, um ein „Sicherheitsschema“ im OpenAPI-Schema (und der automatischen API-Dokumentation) zu definieren. + +/// info | Technische Details + +**FastAPI** weiß, dass es die Klasse `OAuth2PasswordBearer` (deklariert in einer Abhängigkeit) verwenden kann, um das Sicherheitsschema in OpenAPI zu definieren, da es von `fastapi.security.oauth2.OAuth2` erbt, das wiederum von `fastapi.security.base.SecurityBase` erbt. + +Alle Sicherheits-Werkzeuge, die in OpenAPI integriert sind (und die automatische API-Dokumentation), erben von `SecurityBase`, so weiß **FastAPI**, wie es sie in OpenAPI integrieren muss. + +/// + +## Was es macht + +FastAPI wird im Request nach diesem `Authorization`-Header suchen, prüfen, ob der Wert `Bearer` plus ein Token ist, und den Token als `str` zurückgeben. + +Wenn es keinen `Authorization`-Header sieht, oder der Wert keinen `Bearer`-Token hat, antwortet es direkt mit einem 401-Statuscode-Error (`UNAUTHORIZED`). + +Sie müssen nicht einmal prüfen, ob der Token existiert, um einen Fehler zurückzugeben. Seien Sie sicher, dass Ihre Funktion, wenn sie ausgeführt wird, ein `str` in diesem Token enthält. + +Sie können das bereits in der interaktiven Dokumentation ausprobieren: + + + +Wir überprüfen im Moment noch nicht die Gültigkeit des Tokens, aber das ist bereits ein Anfang. + +## Zusammenfassung + +Mit nur drei oder vier zusätzlichen Zeilen haben Sie also bereits eine primitive Form der Sicherheit. diff --git a/docs/de/docs/tutorial/security/get-current-user.md b/docs/de/docs/tutorial/security/get-current-user.md new file mode 100644 index 000000000..38f7ffcbf --- /dev/null +++ b/docs/de/docs/tutorial/security/get-current-user.md @@ -0,0 +1,105 @@ +# Aktuellen Benutzer abrufen + +Im vorherigen Kapitel hat das Sicherheitssystem (das auf dem Dependency Injection System basiert) der *Pfadoperation-Funktion* einen `token` vom Typ `str` überreicht: + +{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *} + +Aber das ist immer noch nicht so nützlich. + +Lassen wir es uns den aktuellen Benutzer überreichen. + +## Ein Benutzermodell erstellen + +Erstellen wir zunächst ein Pydantic-Benutzermodell. + +So wie wir Pydantic zum Deklarieren von Bodys verwenden, können wir es auch überall sonst verwenden: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:16] *} + +## Eine `get_current_user`-Abhängigkeit erstellen + +Erstellen wir eine Abhängigkeit `get_current_user`. + +Erinnern Sie sich, dass Abhängigkeiten Unterabhängigkeiten haben können? + +`get_current_user` wird seinerseits von `oauth2_scheme` abhängen, das wir zuvor erstellt haben. + +So wie wir es zuvor in der *Pfadoperation* direkt gemacht haben, erhält unsere neue Abhängigkeit `get_current_user` von der Unterabhängigkeit `oauth2_scheme` einen `token` vom Typ `str`: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[25] *} + +## Den Benutzer holen + +`get_current_user` wird eine von uns erstellte (gefakte) Hilfsfunktion verwenden, welche einen Token vom Typ `str` entgegennimmt und unser Pydantic-`User`-Modell zurückgibt: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[19:22,26:27] *} + +## Den aktuellen Benutzer einfügen + +Und jetzt können wir wiederum `Depends` mit unserem `get_current_user` in der *Pfadoperation* verwenden: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[31] *} + +Beachten Sie, dass wir als Typ von `current_user` das Pydantic-Modell `User` deklarieren. + +Das wird uns innerhalb der Funktion bei Codevervollständigung und Typprüfungen helfen. + +/// tip | Tipp + +Sie erinnern sich vielleicht, dass Requestbodys ebenfalls mit Pydantic-Modellen deklariert werden. + +Weil Sie `Depends` verwenden, wird **FastAPI** hier aber nicht verwirrt. + +/// + +/// check + +Die Art und Weise, wie dieses System von Abhängigkeiten konzipiert ist, ermöglicht es uns, verschiedene Abhängigkeiten (verschiedene „Dependables“) zu haben, die alle ein `User`-Modell zurückgeben. + +Wir sind nicht darauf beschränkt, nur eine Abhängigkeit zu haben, die diesen Typ von Daten zurückgeben kann. + +/// + +## Andere Modelle + +Sie können jetzt den aktuellen Benutzer direkt in den *Pfadoperation-Funktionen* abrufen und die Sicherheitsmechanismen auf **Dependency Injection** Ebene handhaben, mittels `Depends`. + +Und Sie können alle Modelle und Daten für die Sicherheitsanforderungen verwenden (in diesem Fall ein Pydantic-Modell `User`). + +Sie sind jedoch nicht auf die Verwendung von bestimmten Datenmodellen, Klassen, oder Typen beschränkt. + +Möchten Sie eine `id` und eine `email` und keinen `username` in Ihrem Modell haben? Kein Problem. Sie können dieselben Tools verwenden. + +Möchten Sie nur ein `str` haben? Oder nur ein `dict`? Oder direkt eine Instanz eines Modells einer Datenbank-Klasse? Es funktioniert alles auf die gleiche Weise. + +Sie haben eigentlich keine Benutzer, die sich bei Ihrer Anwendung anmelden, sondern Roboter, Bots oder andere Systeme, die nur über einen Zugriffstoken verfügen? Auch hier funktioniert alles gleich. + +Verwenden Sie einfach jede Art von Modell, jede Art von Klasse, jede Art von Datenbank, die Sie für Ihre Anwendung benötigen. **FastAPI** deckt das alles mit seinem Dependency Injection System ab. + +## Codegröße + +Dieses Beispiel mag ausführlich erscheinen. Bedenken Sie, dass wir Sicherheit, Datenmodelle, Hilfsfunktionen und *Pfadoperationen* in derselben Datei vermischen. + +Aber hier ist der entscheidende Punkt. + +Der Code für Sicherheit und Dependency Injection wird einmal geschrieben. + +Sie können es so komplex gestalten, wie Sie möchten. Und dennoch haben Sie es nur einmal geschrieben, an einer einzigen Stelle. Mit all der Flexibilität. + +Aber Sie können Tausende von Endpunkten (*Pfadoperationen*) haben, die dasselbe Sicherheitssystem verwenden. + +Und alle (oder beliebige Teile davon) können Vorteil ziehen aus der Wiederverwendung dieser und anderer von Ihnen erstellter Abhängigkeiten. + +Und alle diese Tausenden von *Pfadoperationen* können nur drei Zeilen lang sein: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[30:32] *} + +## Zusammenfassung + +Sie können jetzt den aktuellen Benutzer direkt in Ihrer *Pfadoperation-Funktion* abrufen. + +Wir haben bereits die Hälfte geschafft. + +Wir müssen jetzt nur noch eine *Pfadoperation* hinzufügen, mittels der der Benutzer/Client tatsächlich seinen `username` und `password` senden kann. + +Das kommt als nächstes. diff --git a/docs/de/docs/tutorial/security/index.md b/docs/de/docs/tutorial/security/index.md new file mode 100644 index 000000000..b01243901 --- /dev/null +++ b/docs/de/docs/tutorial/security/index.md @@ -0,0 +1,106 @@ +# Sicherheit + +Es gibt viele Wege, Sicherheit, Authentifizierung und Autorisierung zu handhaben. + +Und normalerweise ist es ein komplexes und „schwieriges“ Thema. + +In vielen Frameworks und Systemen erfordert allein die Handhabung von Sicherheit und Authentifizierung viel Aufwand und Code (in vielen Fällen kann er 50 % oder mehr des gesamten geschriebenen Codes ausmachen). + +**FastAPI** bietet mehrere Tools, die Ihnen helfen, schnell und auf standardisierte Weise mit **Sicherheit** umzugehen, ohne alle Sicherheits-Spezifikationen studieren und erlernen zu müssen. + +Aber schauen wir uns zunächst ein paar kleine Konzepte an. + +## In Eile? + +Wenn Ihnen diese Begriffe egal sind und Sie einfach *jetzt* Sicherheit mit Authentifizierung basierend auf Benutzername und Passwort hinzufügen müssen, fahren Sie mit den nächsten Kapiteln fort. + +## OAuth2 + +OAuth2 ist eine Spezifikation, die verschiedene Möglichkeiten zur Handhabung von Authentifizierung und Autorisierung definiert. + +Es handelt sich um eine recht umfangreiche Spezifikation, und sie deckt mehrere komplexe Anwendungsfälle ab. + +Sie umfasst Möglichkeiten zur Authentifizierung mithilfe eines „Dritten“ („third party“). + +Das ist es, was alle diese „Login mit Facebook, Google, Twitter, GitHub“-Systeme unter der Haube verwenden. + +### OAuth 1 + +Es gab ein OAuth 1, das sich stark von OAuth2 unterscheidet und komplexer ist, da es direkte Spezifikationen enthält, wie die Kommunikation verschlüsselt wird. + +Heutzutage ist es nicht sehr populär und wird kaum verwendet. + +OAuth2 spezifiziert nicht, wie die Kommunikation verschlüsselt werden soll, sondern erwartet, dass Ihre Anwendung mit HTTPS bereitgestellt wird. + +/// tip | Tipp + +Im Abschnitt über **Deployment** erfahren Sie, wie Sie HTTPS mithilfe von Traefik und Let's Encrypt kostenlos einrichten. + +/// + +## OpenID Connect + +OpenID Connect ist eine weitere Spezifikation, die auf **OAuth2** basiert. + +Sie erweitert lediglich OAuth2, indem sie einige Dinge spezifiziert, die in OAuth2 relativ mehrdeutig sind, um zu versuchen, es interoperabler zu machen. + +Beispielsweise verwendet der Google Login OpenID Connect (welches seinerseits OAuth2 verwendet). + +Aber der Facebook Login unterstützt OpenID Connect nicht. Es hat seine eigene Variante von OAuth2. + +### OpenID (nicht „OpenID Connect“) + +Es gab auch eine „OpenID“-Spezifikation. Sie versuchte das Gleiche zu lösen wie **OpenID Connect**, basierte aber nicht auf OAuth2. + +Es handelte sich also um ein komplett zusätzliches System. + +Heutzutage ist es nicht sehr populär und wird kaum verwendet. + +## OpenAPI + +OpenAPI (früher bekannt als Swagger) ist die offene Spezifikation zum Erstellen von APIs (jetzt Teil der Linux Foundation). + +**FastAPI** basiert auf **OpenAPI**. + +Das ist es, was erlaubt, mehrere automatische interaktive Dokumentations-Oberflächen, Codegenerierung, usw. zu haben. + +OpenAPI bietet die Möglichkeit, mehrere Sicherheits„systeme“ zu definieren. + +Durch deren Verwendung können Sie alle diese Standards-basierten Tools nutzen, einschließlich dieser interaktiven Dokumentationssysteme. + +OpenAPI definiert die folgenden Sicherheitsschemas: + +* `apiKey`: ein anwendungsspezifischer Schlüssel, der stammen kann von: + * Einem Query-Parameter. + * Einem Header. + * Einem Cookie. +* `http`: Standard-HTTP-Authentifizierungssysteme, einschließlich: + * `bearer`: ein Header `Authorization` mit dem Wert `Bearer` plus einem Token. Dies wird von OAuth2 geerbt. + * HTTP Basic Authentication. + * HTTP Digest, usw. +* `oauth2`: Alle OAuth2-Methoden zum Umgang mit Sicherheit (genannt „Flows“). + * Mehrere dieser Flows eignen sich zum Aufbau eines OAuth 2.0-Authentifizierungsanbieters (wie Google, Facebook, Twitter, GitHub usw.): + * `implicit` + * `clientCredentials` + * `authorizationCode` + * Es gibt jedoch einen bestimmten „Flow“, der perfekt für die direkte Abwicklung der Authentifizierung in derselben Anwendung verwendet werden kann: + * `password`: Einige der nächsten Kapitel werden Beispiele dafür behandeln. +* `openIdConnect`: bietet eine Möglichkeit, zu definieren, wie OAuth2-Authentifizierungsdaten automatisch ermittelt werden können. + * Diese automatische Erkennung ist es, die in der OpenID Connect Spezifikation definiert ist. + + +/// tip | Tipp + +Auch die Integration anderer Authentifizierungs-/Autorisierungsanbieter wie Google, Facebook, Twitter, GitHub, usw. ist möglich und relativ einfach. + +Das komplexeste Problem besteht darin, einen Authentifizierungs-/Autorisierungsanbieter wie solche aufzubauen, aber **FastAPI** reicht Ihnen die Tools, das einfach zu erledigen, während Ihnen die schwere Arbeit abgenommen wird. + +/// + +## **FastAPI** Tools + +FastAPI stellt für jedes dieser Sicherheitsschemas im Modul `fastapi.security` verschiedene Tools bereit, die die Verwendung dieser Sicherheitsmechanismen vereinfachen. + +In den nächsten Kapiteln erfahren Sie, wie Sie mit diesen von **FastAPI** bereitgestellten Tools Sicherheit zu Ihrer API hinzufügen. + +Und Sie werden auch sehen, wie dies automatisch in das interaktive Dokumentationssystem integriert wird. diff --git a/docs/de/docs/tutorial/security/oauth2-jwt.md b/docs/de/docs/tutorial/security/oauth2-jwt.md new file mode 100644 index 000000000..178a95d81 --- /dev/null +++ b/docs/de/docs/tutorial/security/oauth2-jwt.md @@ -0,0 +1,275 @@ +# OAuth2 mit Password (und Hashing), Bearer mit JWT-Tokens + +Da wir nun über den gesamten Sicherheitsablauf verfügen, machen wir die Anwendung tatsächlich sicher, indem wir JWT-Tokens und sicheres Passwort-Hashing verwenden. + +Diesen Code können Sie tatsächlich in Ihrer Anwendung verwenden, die Passwort-Hashes in Ihrer Datenbank speichern, usw. + +Wir bauen auf dem vorherigen Kapitel auf. + +## Über JWT + +JWT bedeutet „JSON Web Tokens“. + +Es ist ein Standard, um ein JSON-Objekt in einem langen, kompakten String ohne Leerzeichen zu kodieren. Das sieht so aus: + +``` +eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c +``` + +Da er nicht verschlüsselt ist, kann jeder die Informationen aus dem Inhalt wiederherstellen. + +Aber er ist signiert. Wenn Sie also einen von Ihnen gesendeten Token zurückerhalten, können Sie überprüfen, ob Sie ihn tatsächlich gesendet haben. + +Auf diese Weise können Sie einen Token mit einer Gültigkeitsdauer von beispielsweise einer Woche erstellen. Und wenn der Benutzer am nächsten Tag mit dem Token zurückkommt, wissen Sie, dass der Benutzer immer noch bei Ihrem System angemeldet ist. + +Nach einer Woche läuft der Token ab und der Benutzer wird nicht autorisiert und muss sich erneut anmelden, um einen neuen Token zu erhalten. Und wenn der Benutzer (oder ein Dritter) versuchen würde, den Token zu ändern, um das Ablaufdatum zu ändern, würden Sie das entdecken, weil die Signaturen nicht übereinstimmen würden. + +Wenn Sie mit JWT-Tokens spielen und sehen möchten, wie sie funktionieren, schauen Sie sich https://jwt.io an. + +## `python-jose` installieren. + +Wir müssen `python-jose` installieren, um die JWT-Tokens in Python zu generieren und zu verifizieren: + +
+ +```console +$ pip install "python-jose[cryptography]" + +---> 100% +``` + +
+ +python-jose erfordert zusätzlich ein kryptografisches Backend. + +Hier verwenden wir das empfohlene: pyca/cryptography. + +/// tip | Tipp + +Dieses Tutorial verwendete zuvor PyJWT. + +Es wurde jedoch aktualisiert, stattdessen python-jose zu verwenden, da dieses alle Funktionen von PyJWT sowie einige Extras bietet, die Sie später möglicherweise benötigen, wenn Sie Integrationen mit anderen Tools erstellen. + +/// + +## Passwort-Hashing + +„Hashing“ bedeutet: Konvertieren eines Inhalts (in diesem Fall eines Passworts) in eine Folge von Bytes (ein schlichter String), die wie Kauderwelsch aussieht. + +Immer wenn Sie genau den gleichen Inhalt (genau das gleiche Passwort) übergeben, erhalten Sie genau den gleichen Kauderwelsch. + +Sie können jedoch nicht vom Kauderwelsch zurück zum Passwort konvertieren. + +### Warum Passwort-Hashing verwenden? + +Wenn Ihre Datenbank gestohlen wird, hat der Dieb nicht die Klartext-Passwörter Ihrer Benutzer, sondern nur die Hashes. + +Der Dieb kann also nicht versuchen, die gleichen Passwörter in einem anderen System zu verwenden (da viele Benutzer überall das gleiche Passwort verwenden, wäre dies gefährlich). + +## `passlib` installieren + +PassLib ist ein großartiges Python-Package, um Passwort-Hashes zu handhaben. + +Es unterstützt viele sichere Hashing-Algorithmen und Werkzeuge, um mit diesen zu arbeiten. + +Der empfohlene Algorithmus ist „Bcrypt“. + +Installieren Sie also PassLib mit Bcrypt: + +
+ +```console +$ pip install "passlib[bcrypt]" + +---> 100% +``` + +
+ +/// tip | Tipp + +Mit `passlib` können Sie sogar konfigurieren, Passwörter zu lesen, die von **Django**, einem **Flask**-Sicherheit-Plugin, oder vielen anderen erstellt wurden. + +So könnten Sie beispielsweise die gleichen Daten aus einer Django-Anwendung in einer Datenbank mit einer FastAPI-Anwendung teilen. Oder schrittweise eine Django-Anwendung migrieren, während Sie dieselbe Datenbank verwenden. + +Und Ihre Benutzer könnten sich gleichzeitig über Ihre Django-Anwendung oder Ihre **FastAPI**-Anwendung anmelden. + +/// + +## Die Passwörter hashen und überprüfen + +Importieren Sie die benötigten Tools aus `passlib`. + +Erstellen Sie einen PassLib-„Kontext“. Der wird für das Hashen und Verifizieren von Passwörtern verwendet. + +/// tip | Tipp + +Der PassLib-Kontext kann auch andere Hashing-Algorithmen verwenden, einschließlich deprecateter Alter, um etwa nur eine Verifizierung usw. zu ermöglichen. + +Sie könnten ihn beispielsweise verwenden, um von einem anderen System (wie Django) generierte Passwörter zu lesen und zu verifizieren, aber alle neuen Passwörter mit einem anderen Algorithmus wie Bcrypt zu hashen. + +Und mit allen gleichzeitig kompatibel sein. + +/// + +Erstellen Sie eine Hilfsfunktion, um ein vom Benutzer stammendes Passwort zu hashen. + +Und eine weitere, um zu überprüfen, ob ein empfangenes Passwort mit dem gespeicherten Hash übereinstimmt. + +Und noch eine, um einen Benutzer zu authentifizieren und zurückzugeben. + +{* ../../docs_src/security/tutorial004_an_py310.py hl[7,48,55:56,59:60,69:75] *} + +/// note | Hinweis + +Wenn Sie sich die neue (gefakte) Datenbank `fake_users_db` anschauen, sehen Sie, wie das gehashte Passwort jetzt aussieht: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`. + +/// + +## JWT-Token verarbeiten + +Importieren Sie die installierten Module. + +Erstellen Sie einen zufälligen geheimen Schlüssel, der zum Signieren der JWT-Tokens verwendet wird. + +Um einen sicheren zufälligen geheimen Schlüssel zu generieren, verwenden Sie den folgenden Befehl: + +
+ +```console +$ openssl rand -hex 32 + +09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7 +``` + +
+ +Und kopieren Sie die Ausgabe in die Variable `SECRET_KEY` (verwenden Sie nicht die im Beispiel). + +Erstellen Sie eine Variable `ALGORITHM` für den Algorithmus, der zum Signieren des JWT-Tokens verwendet wird, und setzen Sie sie auf `"HS256"`. + +Erstellen Sie eine Variable für das Ablaufdatum des Tokens. + +Definieren Sie ein Pydantic-Modell, das im Token-Endpunkt für die Response verwendet wird. + +Erstellen Sie eine Hilfsfunktion, um einen neuen Zugriffstoken zu generieren. + +{* ../../docs_src/security/tutorial004_an_py310.py hl[6,12:14,28:30,78:86] *} + +## Die Abhängigkeiten aktualisieren + +Aktualisieren Sie `get_current_user`, um den gleichen Token wie zuvor zu erhalten, dieses Mal jedoch unter Verwendung von JWT-Tokens. + +Dekodieren Sie den empfangenen Token, validieren Sie ihn und geben Sie den aktuellen Benutzer zurück. + +Wenn der Token ungültig ist, geben Sie sofort einen HTTP-Fehler zurück. + +{* ../../docs_src/security/tutorial004_an_py310.py hl[89:106] *} + +## Die *Pfadoperation* `/token` aktualisieren + +Erstellen Sie ein `timedelta` mit der Ablaufzeit des Tokens. + +Erstellen Sie einen echten JWT-Zugriffstoken und geben Sie ihn zurück. + +{* ../../docs_src/security/tutorial004_an_py310.py hl[117:132] *} + +### Technische Details zum JWT-„Subjekt“ `sub` + +Die JWT-Spezifikation besagt, dass es einen Schlüssel `sub` mit dem Subjekt des Tokens gibt. + +Die Verwendung ist optional, aber dort würden Sie die Identifikation des Benutzers speichern, daher verwenden wir das hier. + +JWT kann auch für andere Dinge verwendet werden, abgesehen davon, einen Benutzer zu identifizieren und ihm zu erlauben, Operationen direkt auf Ihrer API auszuführen. + +Sie könnten beispielsweise ein „Auto“ oder einen „Blog-Beitrag“ identifizieren. + +Anschließend könnten Sie Berechtigungen für diese Entität hinzufügen, etwa „Fahren“ (für das Auto) oder „Bearbeiten“ (für den Blog). + +Und dann könnten Sie diesen JWT-Token einem Benutzer (oder Bot) geben und dieser könnte ihn verwenden, um diese Aktionen auszuführen (das Auto fahren oder den Blog-Beitrag bearbeiten), ohne dass er überhaupt ein Konto haben müsste, einfach mit dem JWT-Token, den Ihre API dafür generiert hat. + +Mit diesen Ideen kann JWT für weitaus anspruchsvollere Szenarien verwendet werden. + +In diesen Fällen könnten mehrere dieser Entitäten die gleiche ID haben, sagen wir `foo` (ein Benutzer `foo`, ein Auto `foo` und ein Blog-Beitrag `foo`). + +Deshalb, um ID-Kollisionen zu vermeiden, könnten Sie beim Erstellen des JWT-Tokens für den Benutzer, dem Wert des `sub`-Schlüssels ein Präfix, z. B. `username:` voranstellen. In diesem Beispiel hätte der Wert von `sub` also auch `username:johndoe` sein können. + +Der wesentliche Punkt ist, dass der `sub`-Schlüssel in der gesamten Anwendung eine eindeutige Kennung haben sollte, und er sollte ein String sein. + +## Es testen + +Führen Sie den Server aus und gehen Sie zur Dokumentation: http://127.0.0.1:8000/docs. + +Die Benutzeroberfläche sieht wie folgt aus: + + + +Melden Sie sich bei der Anwendung auf die gleiche Weise wie zuvor an. + +Verwenden Sie die Anmeldeinformationen: + +Benutzername: `johndoe` +Passwort: `secret`. + +/// check + +Beachten Sie, dass im Code nirgendwo das Klartext-Passwort "`secret`" steht, wir haben nur die gehashte Version. + +/// + + + +Rufen Sie den Endpunkt `/users/me/` auf, Sie erhalten die Response: + +```JSON +{ + "username": "johndoe", + "email": "johndoe@example.com", + "full_name": "John Doe", + "disabled": false +} +``` + + + +Wenn Sie die Developer Tools öffnen, können Sie sehen, dass die gesendeten Daten nur den Token enthalten. Das Passwort wird nur bei der ersten Anfrage gesendet, um den Benutzer zu authentisieren und diesen Zugriffstoken zu erhalten, aber nicht mehr danach: + + + +/// note | Hinweis + +Beachten Sie den Header `Authorization` mit einem Wert, der mit `Bearer` beginnt. + +/// + +## Fortgeschrittene Verwendung mit `scopes` + +OAuth2 hat ein Konzept von „Scopes“. + +Sie können diese verwenden, um einem JWT-Token einen bestimmten Satz von Berechtigungen zu übergeben. + +Anschließend können Sie diesen Token einem Benutzer direkt oder einem Dritten geben, damit diese mit einer Reihe von Einschränkungen mit Ihrer API interagieren können. + +Wie Sie sie verwenden und wie sie in **FastAPI** integriert sind, erfahren Sie später im **Handbuch für fortgeschrittene Benutzer**. + +## Zusammenfassung + +Mit dem, was Sie bis hier gesehen haben, können Sie eine sichere **FastAPI**-Anwendung mithilfe von Standards wie OAuth2 und JWT einrichten. + +In fast jedem Framework wird die Handhabung der Sicherheit recht schnell zu einem ziemlich komplexen Thema. + +Viele Packages, die es stark vereinfachen, müssen viele Kompromisse beim Datenmodell, der Datenbank und den verfügbaren Funktionen eingehen. Und einige dieser Pakete, die die Dinge zu sehr vereinfachen, weisen tatsächlich Sicherheitslücken auf. + +--- + +**FastAPI** geht bei keiner Datenbank, keinem Datenmodell oder Tool Kompromisse ein. + +Es gibt Ihnen die volle Flexibilität, diejenigen auszuwählen, die am besten zu Ihrem Projekt passen. + +Und Sie können viele gut gepflegte und weit verbreitete Packages wie `passlib` und `python-jose` direkt verwenden, da **FastAPI** keine komplexen Mechanismen zur Integration externer Pakete erfordert. + +Aber es bietet Ihnen die Werkzeuge, um den Prozess so weit wie möglich zu vereinfachen, ohne Kompromisse bei Flexibilität, Robustheit oder Sicherheit einzugehen. + +Und Sie können sichere Standardprotokolle wie OAuth2 auf relativ einfache Weise verwenden und implementieren. + +Im **Handbuch für fortgeschrittene Benutzer** erfahren Sie mehr darüber, wie Sie OAuth2-„Scopes“ für ein feingranuliertes Berechtigungssystem verwenden, das denselben Standards folgt. OAuth2 mit Scopes ist der Mechanismus, der von vielen großen Authentifizierungsanbietern wie Facebook, Google, GitHub, Microsoft, Twitter, usw. verwendet wird, um Drittanbieteranwendungen zu autorisieren, im Namen ihrer Benutzer mit ihren APIs zu interagieren. diff --git a/docs/de/docs/tutorial/security/simple-oauth2.md b/docs/de/docs/tutorial/security/simple-oauth2.md new file mode 100644 index 000000000..c0c93cd26 --- /dev/null +++ b/docs/de/docs/tutorial/security/simple-oauth2.md @@ -0,0 +1,289 @@ +# Einfaches OAuth2 mit Password und Bearer + +Lassen Sie uns nun auf dem vorherigen Kapitel aufbauen und die fehlenden Teile hinzufügen, um einen vollständigen Sicherheits-Flow zu erhalten. + +## `username` und `password` entgegennehmen + +Wir werden **FastAPIs** Sicherheits-Werkzeuge verwenden, um den `username` und das `password` entgegenzunehmen. + +OAuth2 spezifiziert, dass der Client/Benutzer bei Verwendung des „Password Flow“ (den wir verwenden) die Felder `username` und `password` als Formulardaten senden muss. + +Und die Spezifikation sagt, dass die Felder so benannt werden müssen. `user-name` oder `email` würde also nicht funktionieren. + +Aber keine Sorge, Sie können sie Ihren Endbenutzern im Frontend so anzeigen, wie Sie möchten. + +Und Ihre Datenbankmodelle können beliebige andere Namen verwenden. + +Aber für die Login-*Pfadoperation* müssen wir diese Namen verwenden, um mit der Spezifikation kompatibel zu sein (und beispielsweise das integrierte API-Dokumentationssystem verwenden zu können). + +Die Spezifikation besagt auch, dass `username` und `password` als Formulardaten gesendet werden müssen (hier also kein JSON). + +### `scope` + +Ferner sagt die Spezifikation, dass der Client ein weiteres Formularfeld "`scope`" („Geltungsbereich“) senden kann. + +Der Name des Formularfelds lautet `scope` (im Singular), tatsächlich handelt es sich jedoch um einen langen String mit durch Leerzeichen getrennten „Scopes“. + +Jeder „Scope“ ist nur ein String (ohne Leerzeichen). + +Diese werden normalerweise verwendet, um bestimmte Sicherheitsberechtigungen zu deklarieren, zum Beispiel: + +* `users:read` oder `users:write` sind gängige Beispiele. +* `instagram_basic` wird von Facebook / Instagram verwendet. +* `https://www.googleapis.com/auth/drive` wird von Google verwendet. + +/// info + +In OAuth2 ist ein „Scope“ nur ein String, der eine bestimmte erforderliche Berechtigung deklariert. + +Es spielt keine Rolle, ob er andere Zeichen wie `:` enthält oder ob es eine URL ist. + +Diese Details sind implementierungsspezifisch. + +Für OAuth2 sind es einfach nur Strings. + +/// + +## Code, um `username` und `password` entgegenzunehmen. + +Lassen Sie uns nun die von **FastAPI** bereitgestellten Werkzeuge verwenden, um das zu erledigen. + +### `OAuth2PasswordRequestForm` + +Importieren Sie zunächst `OAuth2PasswordRequestForm` und verwenden Sie es als Abhängigkeit mit `Depends` in der *Pfadoperation* für `/token`: + +{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *} + +`OAuth2PasswordRequestForm` ist eine Klassenabhängigkeit, die einen Formularbody deklariert mit: + +* Dem `username`. +* Dem `password`. +* Einem optionalen `scope`-Feld als langem String, bestehend aus durch Leerzeichen getrennten Strings. +* Einem optionalen `grant_type` („Art der Anmeldung“). + +/// tip | Tipp + +Die OAuth2-Spezifikation *erfordert* tatsächlich ein Feld `grant_type` mit dem festen Wert `password`, aber `OAuth2PasswordRequestForm` erzwingt dies nicht. + +Wenn Sie es erzwingen müssen, verwenden Sie `OAuth2PasswordRequestFormStrict` anstelle von `OAuth2PasswordRequestForm`. + +/// + +* Eine optionale `client_id` (benötigen wir für unser Beispiel nicht). +* Ein optionales `client_secret` (benötigen wir für unser Beispiel nicht). + +/// info + +`OAuth2PasswordRequestForm` ist keine spezielle Klasse für **FastAPI**, so wie `OAuth2PasswordBearer`. + +`OAuth2PasswordBearer` lässt **FastAPI** wissen, dass es sich um ein Sicherheitsschema handelt. Daher wird es auf diese Weise zu OpenAPI hinzugefügt. + +Aber `OAuth2PasswordRequestForm` ist nur eine Klassenabhängigkeit, die Sie selbst hätten schreiben können, oder Sie hätten `Form`ular-Parameter direkt deklarieren können. + +Da es sich jedoch um einen häufigen Anwendungsfall handelt, wird er zur Vereinfachung direkt von **FastAPI** bereitgestellt. + +/// + +### Die Formulardaten verwenden + +/// tip | Tipp + +Die Instanz der Klassenabhängigkeit `OAuth2PasswordRequestForm` verfügt, statt eines Attributs `scope` mit dem durch Leerzeichen getrennten langen String, über das Attribut `scopes` mit einer tatsächlichen Liste von Strings, einem für jeden gesendeten Scope. + +In diesem Beispiel verwenden wir keine `scopes`, aber die Funktionalität ist vorhanden, wenn Sie sie benötigen. + +/// + +Rufen Sie nun die Benutzerdaten aus der (gefakten) Datenbank ab, für diesen `username` aus dem Formularfeld. + +Wenn es keinen solchen Benutzer gibt, geben wir die Fehlermeldung „Incorrect username or password“ zurück. + +Für den Fehler verwenden wir die Exception `HTTPException`: + +{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *} + +### Das Passwort überprüfen + +Zu diesem Zeitpunkt liegen uns die Benutzerdaten aus unserer Datenbank vor, das Passwort haben wir jedoch noch nicht überprüft. + +Lassen Sie uns diese Daten zunächst in das Pydantic-Modell `UserInDB` einfügen. + +Sie sollten niemals Klartext-Passwörter speichern, daher verwenden wir ein (gefaktes) Passwort-Hashing-System. + +Wenn die Passwörter nicht übereinstimmen, geben wir denselben Fehler zurück. + +#### Passwort-Hashing + +„Hashing“ bedeutet: Konvertieren eines Inhalts (in diesem Fall eines Passworts) in eine Folge von Bytes (ein schlichter String), die wie Kauderwelsch aussieht. + +Immer wenn Sie genau den gleichen Inhalt (genau das gleiche Passwort) übergeben, erhalten Sie genau den gleichen Kauderwelsch. + +Sie können jedoch nicht vom Kauderwelsch zurück zum Passwort konvertieren. + +##### Warum Passwort-Hashing verwenden? + +Wenn Ihre Datenbank gestohlen wird, hat der Dieb nicht die Klartext-Passwörter Ihrer Benutzer, sondern nur die Hashes. + +Der Dieb kann also nicht versuchen, die gleichen Passwörter in einem anderen System zu verwenden (da viele Benutzer überall das gleiche Passwort verwenden, wäre dies gefährlich). + +{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *} + +#### Über `**user_dict` + +`UserInDB(**user_dict)` bedeutet: + +*Übergib die Schlüssel und Werte des `user_dict` direkt als Schlüssel-Wert-Argumente, äquivalent zu:* + +```Python +UserInDB( + username = user_dict["username"], + email = user_dict["email"], + full_name = user_dict["full_name"], + disabled = user_dict["disabled"], + hashed_password = user_dict["hashed_password"], +) +``` + +/// info + +Eine ausführlichere Erklärung von `**user_dict` finden Sie in [der Dokumentation für **Extra Modelle**](../extra-models.md#uber-user_indict){.internal-link target=_blank}. + +/// + +## Den Token zurückgeben + +Die Response des `token`-Endpunkts muss ein JSON-Objekt sein. + +Es sollte einen `token_type` haben. Da wir in unserem Fall „Bearer“-Token verwenden, sollte der Token-Typ "`bearer`" sein. + +Und es sollte einen `access_token` haben, mit einem String, der unseren Zugriffstoken enthält. + +In diesem einfachen Beispiel gehen wir einfach völlig unsicher vor und geben denselben `username` wie der Token zurück. + +/// tip | Tipp + +Im nächsten Kapitel sehen Sie eine wirklich sichere Implementierung mit Passwort-Hashing und JWT-Tokens. + +Aber konzentrieren wir uns zunächst auf die spezifischen Details, die wir benötigen. + +/// + +{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *} + +/// tip | Tipp + +Gemäß der Spezifikation sollten Sie ein JSON mit einem `access_token` und einem `token_type` zurückgeben, genau wie in diesem Beispiel. + +Das müssen Sie selbst in Ihrem Code tun und sicherstellen, dass Sie diese JSON-Schlüssel verwenden. + +Es ist fast das Einzige, woran Sie denken müssen, es selbst richtigzumachen und die Spezifikationen einzuhalten. + +Den Rest erledigt **FastAPI** für Sie. + +/// + +## Die Abhängigkeiten aktualisieren + +Jetzt werden wir unsere Abhängigkeiten aktualisieren. + +Wir möchten den `current_user` *nur* erhalten, wenn dieser Benutzer aktiv ist. + +Daher erstellen wir eine zusätzliche Abhängigkeit `get_current_active_user`, die wiederum `get_current_user` als Abhängigkeit verwendet. + +Beide Abhängigkeiten geben nur dann einen HTTP-Error zurück, wenn der Benutzer nicht existiert oder inaktiv ist. + +In unserem Endpunkt erhalten wir also nur dann einen Benutzer, wenn der Benutzer existiert, korrekt authentifiziert wurde und aktiv ist: + +{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *} + +/// info + +Der zusätzliche Header `WWW-Authenticate` mit dem Wert `Bearer`, den wir hier zurückgeben, ist ebenfalls Teil der Spezifikation. + +Jeder HTTP-(Fehler-)Statuscode 401 „UNAUTHORIZED“ soll auch einen `WWW-Authenticate`-Header zurückgeben. + +Im Fall von Bearer-Tokens (in unserem Fall) sollte der Wert dieses Headers `Bearer` lauten. + +Sie können diesen zusätzlichen Header tatsächlich weglassen und es würde trotzdem funktionieren. + +Aber er wird hier bereitgestellt, um den Spezifikationen zu entsprechen. + +Außerdem gibt es möglicherweise Tools, die ihn erwarten und verwenden (jetzt oder in der Zukunft) und das könnte für Sie oder Ihre Benutzer jetzt oder in der Zukunft nützlich sein. + +Das ist der Vorteil von Standards ... + +/// + +## Es in Aktion sehen + +Öffnen Sie die interaktive Dokumentation: http://127.0.0.1:8000/docs. + +### Authentifizieren + +Klicken Sie auf den Button „Authorize“. + +Verwenden Sie die Anmeldedaten: + +Benutzer: `johndoe` + +Passwort: `secret`. + + + +Nach der Authentifizierung im System sehen Sie Folgendes: + + + +### Die eigenen Benutzerdaten ansehen + +Verwenden Sie nun die Operation `GET` mit dem Pfad `/users/me`. + +Sie erhalten Ihre Benutzerdaten: + +```JSON +{ + "username": "johndoe", + "email": "johndoe@example.com", + "full_name": "John Doe", + "disabled": false, + "hashed_password": "fakehashedsecret" +} +``` + + + +Wenn Sie auf das Schlosssymbol klicken und sich abmelden und dann den gleichen Vorgang nochmal versuchen, erhalten Sie einen HTTP 401 Error: + +```JSON +{ + "detail": "Not authenticated" +} +``` + +### Inaktiver Benutzer + +Versuchen Sie es nun mit einem inaktiven Benutzer und authentisieren Sie sich mit: + +Benutzer: `alice`. + +Passwort: `secret2`. + +Und versuchen Sie, die Operation `GET` mit dem Pfad `/users/me` zu verwenden. + +Sie erhalten die Fehlermeldung „Inactive user“: + +```JSON +{ + "detail": "Inactive user" +} +``` + +## Zusammenfassung + +Sie verfügen jetzt über die Tools, um ein vollständiges Sicherheitssystem basierend auf `username` und `password` für Ihre API zu implementieren. + +Mit diesen Tools können Sie das Sicherheitssystem mit jeder Datenbank und jedem Benutzer oder Datenmodell kompatibel machen. + +Das einzige fehlende Detail ist, dass es noch nicht wirklich „sicher“ ist. + +Im nächsten Kapitel erfahren Sie, wie Sie eine sichere Passwort-Hashing-Bibliothek und JWT-Token verwenden. diff --git a/docs/de/docs/tutorial/static-files.md b/docs/de/docs/tutorial/static-files.md new file mode 100644 index 000000000..50e86d68e --- /dev/null +++ b/docs/de/docs/tutorial/static-files.md @@ -0,0 +1,40 @@ +# Statische Dateien + +Mit `StaticFiles` können Sie statische Dateien aus einem Verzeichnis automatisch bereitstellen. + +## `StaticFiles` verwenden + +* Importieren Sie `StaticFiles`. +* „Mounten“ Sie eine `StaticFiles()`-Instanz in einem bestimmten Pfad. + +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} + +/// note | Technische Details + +Sie könnten auch `from starlette.staticfiles import StaticFiles` verwenden. + +**FastAPI** stellt dasselbe `starlette.staticfiles` auch via `fastapi.staticfiles` bereit, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber tatsächlich direkt von Starlette. + +/// + +### Was ist „Mounten“? + +„Mounten“ bedeutet das Hinzufügen einer vollständigen „unabhängigen“ Anwendung an einem bestimmten Pfad, die sich dann um die Handhabung aller Unterpfade kümmert. + +Dies unterscheidet sich von der Verwendung eines `APIRouter`, da eine gemountete Anwendung völlig unabhängig ist. Die OpenAPI und Dokumentation Ihrer Hauptanwendung enthalten nichts von der gemounteten Anwendung, usw. + +Weitere Informationen hierzu finden Sie im [Handbuch für fortgeschrittene Benutzer](../advanced/index.md){.internal-link target=_blank}. + +## Einzelheiten + +Das erste `"/static"` bezieht sich auf den Unterpfad, auf dem diese „Unteranwendung“ „gemountet“ wird. Daher wird jeder Pfad, der mit `"/static"` beginnt, von ihr verarbeitet. + +Das `directory="static"` bezieht sich auf den Namen des Verzeichnisses, das Ihre statischen Dateien enthält. + +Das `name="static"` gibt dieser Unteranwendung einen Namen, der intern von **FastAPI** verwendet werden kann. + +Alle diese Parameter können anders als "`static`" lauten, passen Sie sie an die Bedürfnisse und spezifischen Details Ihrer eigenen Anwendung an. + +## Weitere Informationen + +Weitere Details und Optionen finden Sie in der Dokumentation von Starlette zu statischen Dateien. diff --git a/docs/de/docs/tutorial/testing.md b/docs/de/docs/tutorial/testing.md new file mode 100644 index 000000000..e7c1dda95 --- /dev/null +++ b/docs/de/docs/tutorial/testing.md @@ -0,0 +1,238 @@ +# Testen + +Dank Starlette ist das Testen von **FastAPI**-Anwendungen einfach und macht Spaß. + +Es basiert auf HTTPX, welches wiederum auf der Grundlage von requests konzipiert wurde, es ist also sehr vertraut und intuitiv. + +Damit können Sie pytest direkt mit **FastAPI** verwenden. + +## Verwendung von `TestClient` + +/// info + +Um `TestClient` zu verwenden, installieren Sie zunächst `httpx`. + +Z. B. `pip install httpx`. + +/// + +Importieren Sie `TestClient`. + +Erstellen Sie einen `TestClient`, indem Sie ihm Ihre **FastAPI**-Anwendung übergeben. + +Erstellen Sie Funktionen mit einem Namen, der mit `test_` beginnt (das sind `pytest`-Konventionen). + +Verwenden Sie das `TestClient`-Objekt auf die gleiche Weise wie `httpx`. + +Schreiben Sie einfache `assert`-Anweisungen mit den Standard-Python-Ausdrücken, die Sie überprüfen müssen (wiederum, Standard-`pytest`). + +{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *} + +/// tip | Tipp + +Beachten Sie, dass die Testfunktionen normal `def` und nicht `async def` sind. + +Und die Anrufe an den Client sind ebenfalls normale Anrufe, die nicht `await` verwenden. + +Dadurch können Sie `pytest` ohne Komplikationen direkt nutzen. + +/// + +/// note | Technische Details + +Sie könnten auch `from starlette.testclient import TestClient` verwenden. + +**FastAPI** stellt denselben `starlette.testclient` auch via `fastapi.testclient` bereit, als Annehmlichkeit für Sie, den Entwickler. Es kommt aber tatsächlich direkt von Starlette. + +/// + +/// tip | Tipp + +Wenn Sie in Ihren Tests neben dem Senden von Anfragen an Ihre FastAPI-Anwendung auch `async`-Funktionen aufrufen möchten (z. B. asynchrone Datenbankfunktionen), werfen Sie einen Blick auf die [Async-Tests](../advanced/async-tests.md){.internal-link target=_blank} im Handbuch für fortgeschrittene Benutzer. + +/// + +## Tests separieren + +In einer echten Anwendung würden Sie Ihre Tests wahrscheinlich in einer anderen Datei haben. + +Und Ihre **FastAPI**-Anwendung könnte auch aus mehreren Dateien/Modulen, usw. bestehen. + +### **FastAPI** Anwendungsdatei + +Nehmen wir an, Sie haben eine Dateistruktur wie in [Größere Anwendungen](bigger-applications.md){.internal-link target=_blank} beschrieben: + +``` +. +├── app +│   ├── __init__.py +│   └── main.py +``` + +In der Datei `main.py` haben Sie Ihre **FastAPI**-Anwendung: + + +{* ../../docs_src/app_testing/main.py *} + + +### Testdatei + +Dann könnten Sie eine Datei `test_main.py` mit Ihren Tests haben. Sie könnte sich im selben Python-Package befinden (dasselbe Verzeichnis mit einer `__init__.py`-Datei): + +``` hl_lines="5" +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +Da sich diese Datei im selben Package befindet, können Sie relative Importe verwenden, um das Objekt `app` aus dem `main`-Modul (`main.py`) zu importieren: + +{* ../../docs_src/app_testing/test_main.py hl[3] *} + + +... und haben den Code für die Tests wie zuvor. + +## Testen: erweitertes Beispiel + +Nun erweitern wir dieses Beispiel und fügen weitere Details hinzu, um zu sehen, wie verschiedene Teile getestet werden. + +### Erweiterte **FastAPI**-Anwendungsdatei + +Fahren wir mit der gleichen Dateistruktur wie zuvor fort: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +Nehmen wir an, dass die Datei `main.py` mit Ihrer **FastAPI**-Anwendung jetzt einige andere **Pfadoperationen** hat. + +Sie verfügt über eine `GET`-Operation, die einen Fehler zurückgeben könnte. + +Sie verfügt über eine `POST`-Operation, die mehrere Fehler zurückgeben könnte. + +Beide *Pfadoperationen* erfordern einen `X-Token`-Header. + +//// tab | Python 3.10+ + +```Python +{!> ../../docs_src/app_testing/app_b_an_py310/main.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python +{!> ../../docs_src/app_testing/app_b_an_py39/main.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python +{!> ../../docs_src/app_testing/app_b_an/main.py!} +``` + +//// + +//// tab | Python 3.10+ nicht annotiert + +/// tip | Tipp + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python +{!> ../../docs_src/app_testing/app_b_py310/main.py!} +``` + +//// + +//// tab | Python 3.8+ nicht annotiert + +/// tip | Tipp + +Bevorzugen Sie die `Annotated`-Version, falls möglich. + +/// + +```Python +{!> ../../docs_src/app_testing/app_b/main.py!} +``` + +//// + +### Erweiterte Testdatei + +Anschließend könnten Sie `test_main.py` mit den erweiterten Tests aktualisieren: + +{* ../../docs_src/app_testing/app_b/test_main.py *} + + +Wenn Sie möchten, dass der Client Informationen im Request übergibt und Sie nicht wissen, wie das geht, können Sie suchen (googeln), wie es mit `httpx` gemacht wird, oder sogar, wie es mit `requests` gemacht wird, da das Design von HTTPX auf dem Design von Requests basiert. + +Dann machen Sie in Ihren Tests einfach das gleiche. + +Z. B.: + +* Um einen *Pfad*- oder *Query*-Parameter zu übergeben, fügen Sie ihn der URL selbst hinzu. +* Um einen JSON-Body zu übergeben, übergeben Sie ein Python-Objekt (z. B. ein `dict`) an den Parameter `json`. +* Wenn Sie *Formulardaten* anstelle von JSON senden müssen, verwenden Sie stattdessen den `data`-Parameter. +* Um *Header* zu übergeben, verwenden Sie ein `dict` im `headers`-Parameter. +* Für *Cookies* ein `dict` im `cookies`-Parameter. + +Weitere Informationen zum Übergeben von Daten an das Backend (mithilfe von `httpx` oder dem `TestClient`) finden Sie in der HTTPX-Dokumentation. + +/// info + +Beachten Sie, dass der `TestClient` Daten empfängt, die nach JSON konvertiert werden können, keine Pydantic-Modelle. + +Wenn Sie ein Pydantic-Modell in Ihrem Test haben und dessen Daten während des Testens an die Anwendung senden möchten, können Sie den `jsonable_encoder` verwenden, der in [JSON-kompatibler Encoder](encoder.md){.internal-link target=_blank} beschrieben wird. + +/// + +## Tests ausführen + +Danach müssen Sie nur noch `pytest` installieren: + +
+ +```console +$ pip install pytest + +---> 100% +``` + +
+ +Es erkennt die Dateien und Tests automatisch, führt sie aus und berichtet Ihnen die Ergebnisse. + +Führen Sie die Tests aus, mit: + +
+ +```console +$ pytest + +================ test session starts ================ +platform linux -- Python 3.6.9, pytest-5.3.5, py-1.8.1, pluggy-0.13.1 +rootdir: /home/user/code/superawesome-cli/app +plugins: forked-1.1.3, xdist-1.31.0, cov-2.8.1 +collected 6 items + +---> 100% + +test_main.py ...... [100%] + +================= 1 passed in 0.03s ================= +``` + +
diff --git a/docs/em/docs/advanced/additional-responses.md b/docs/em/docs/advanced/additional-responses.md index 26963c2e3..655fc7ab6 100644 --- a/docs/em/docs/advanced/additional-responses.md +++ b/docs/em/docs/advanced/additional-responses.md @@ -1,9 +1,12 @@ # 🌖 📨 🗄 -!!! warning - 👉 👍 🏧 ❔. +/// warning - 🚥 👆 ▶️ ⏮️ **FastAPI**, 👆 💪 🚫 💪 👉. +👉 👍 🏧 ❔. + +🚥 👆 ▶️ ⏮️ **FastAPI**, 👆 💪 🚫 💪 👉. + +/// 👆 💪 📣 🌖 📨, ⏮️ 🌖 👔 📟, 🔉 🆎, 📛, ♒️. @@ -23,24 +26,28 @@ 🖼, 📣 ➕1️⃣ 📨 ⏮️ 👔 📟 `404` & Pydantic 🏷 `Message`, 👆 💪 ✍: -```Python hl_lines="18 22" -{!../../../docs_src/additional_responses/tutorial001.py!} -``` +{* ../../docs_src/additional_responses/tutorial001.py hl[18,22] *} + +/// note + +✔️ 🤯 👈 👆 ✔️ 📨 `JSONResponse` 🔗. + +/// + +/// info -!!! note - ✔️ 🤯 👈 👆 ✔️ 📨 `JSONResponse` 🔗. +`model` 🔑 🚫 🍕 🗄. -!!! info - `model` 🔑 🚫 🍕 🗄. +**FastAPI** 🔜 ✊ Pydantic 🏷 ⚪️➡️ 📤, 🏗 `JSON Schema`, & 🚮 ⚫️ ☑ 🥉. - **FastAPI** 🔜 ✊ Pydantic 🏷 ⚪️➡️ 📤, 🏗 `JSON Schema`, & 🚮 ⚫️ ☑ 🥉. +☑ 🥉: - ☑ 🥉: +* 🔑 `content`, 👈 ✔️ 💲 ➕1️⃣ 🎻 🎚 (`dict`) 👈 🔌: + * 🔑 ⏮️ 📻 🆎, ✅ `application/json`, 👈 🔌 💲 ➕1️⃣ 🎻 🎚, 👈 🔌: + * 🔑 `schema`, 👈 ✔️ 💲 🎻 🔗 ⚪️➡️ 🏷, 📥 ☑ 🥉. + * **FastAPI** 🚮 🔗 📥 🌐 🎻 🔗 ➕1️⃣ 🥉 👆 🗄 ↩️ ✅ ⚫️ 🔗. 👉 🌌, 🎏 🈸 & 👩‍💻 💪 ⚙️ 👈 🎻 🔗 🔗, 🚚 👻 📟 ⚡ 🧰, ♒️. - * 🔑 `content`, 👈 ✔️ 💲 ➕1️⃣ 🎻 🎚 (`dict`) 👈 🔌: - * 🔑 ⏮️ 📻 🆎, ✅ `application/json`, 👈 🔌 💲 ➕1️⃣ 🎻 🎚, 👈 🔌: - * 🔑 `schema`, 👈 ✔️ 💲 🎻 🔗 ⚪️➡️ 🏷, 📥 ☑ 🥉. - * **FastAPI** 🚮 🔗 📥 🌐 🎻 🔗 ➕1️⃣ 🥉 👆 🗄 ↩️ ✅ ⚫️ 🔗. 👉 🌌, 🎏 🈸 & 👩‍💻 💪 ⚙️ 👈 🎻 🔗 🔗, 🚚 👻 📟 ⚡ 🧰, ♒️. +/// 🏗 📨 🗄 👉 *➡ 🛠️* 🔜: @@ -168,17 +175,21 @@ 🖼, 👆 💪 🚮 🌖 📻 🆎 `image/png`, 📣 👈 👆 *➡ 🛠️* 💪 📨 🎻 🎚 (⏮️ 📻 🆎 `application/json`) ⚖️ 🇩🇴 🖼: -```Python hl_lines="19-24 28" -{!../../../docs_src/additional_responses/tutorial002.py!} -``` +{* ../../docs_src/additional_responses/tutorial002.py hl[19:24,28] *} + +/// note + +👀 👈 👆 ✔️ 📨 🖼 ⚙️ `FileResponse` 🔗. + +/// -!!! note - 👀 👈 👆 ✔️ 📨 🖼 ⚙️ `FileResponse` 🔗. +/// info -!!! info - 🚥 👆 ✔ 🎏 📻 🆎 🎯 👆 `responses` 🔢, FastAPI 🔜 🤔 📨 ✔️ 🎏 📻 🆎 👑 📨 🎓 (🔢 `application/json`). +🚥 👆 ✔ 🎏 📻 🆎 🎯 👆 `responses` 🔢, FastAPI 🔜 🤔 📨 ✔️ 🎏 📻 🆎 👑 📨 🎓 (🔢 `application/json`). - ✋️ 🚥 👆 ✔️ ✔ 🛃 📨 🎓 ⏮️ `None` 🚮 📻 🆎, FastAPI 🔜 ⚙️ `application/json` 🙆 🌖 📨 👈 ✔️ 👨‍💼 🏷. +✋️ 🚥 👆 ✔️ ✔ 🛃 📨 🎓 ⏮️ `None` 🚮 📻 🆎, FastAPI 🔜 ⚙️ `application/json` 🙆 🌖 📨 👈 ✔️ 👨‍💼 🏷. + +/// ## 🌀 ℹ @@ -192,9 +203,7 @@ & 📨 ⏮️ 👔 📟 `200` 👈 ⚙️ 👆 `response_model`, ✋️ 🔌 🛃 `example`: -```Python hl_lines="20-31" -{!../../../docs_src/additional_responses/tutorial003.py!} -``` +{* ../../docs_src/additional_responses/tutorial003.py hl[20:31] *} ⚫️ 🔜 🌐 🌀 & 🔌 👆 🗄, & 🎦 🛠️ 🩺: @@ -228,9 +237,7 @@ new_dict = {**old_dict, "new key": "new value"} 🖼: -```Python hl_lines="13-17 26" -{!../../../docs_src/additional_responses/tutorial004.py!} -``` +{* ../../docs_src/additional_responses/tutorial004.py hl[13:17,26] *} ## 🌖 ℹ 🔃 🗄 📨 diff --git a/docs/em/docs/advanced/additional-status-codes.md b/docs/em/docs/advanced/additional-status-codes.md index 392579df6..907c7e68e 100644 --- a/docs/em/docs/advanced/additional-status-codes.md +++ b/docs/em/docs/advanced/additional-status-codes.md @@ -14,21 +14,25 @@ 🏆 👈, 🗄 `JSONResponse`, & 📨 👆 🎚 📤 🔗, ⚒ `status_code` 👈 👆 💚: -```Python hl_lines="4 25" -{!../../../docs_src/additional_status_codes/tutorial001.py!} -``` +{* ../../docs_src/additional_status_codes/tutorial001.py hl[4,25] *} -!!! warning - 🕐❔ 👆 📨 `Response` 🔗, 💖 🖼 🔛, ⚫️ 🔜 📨 🔗. +/// warning - ⚫️ 🏆 🚫 🎻 ⏮️ 🏷, ♒️. +🕐❔ 👆 📨 `Response` 🔗, 💖 🖼 🔛, ⚫️ 🔜 📨 🔗. - ⚒ 💭 ⚫️ ✔️ 📊 👆 💚 ⚫️ ✔️, & 👈 💲 ☑ 🎻 (🚥 👆 ⚙️ `JSONResponse`). +⚫️ 🏆 🚫 🎻 ⏮️ 🏷, ♒️. -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.responses import JSONResponse`. +⚒ 💭 ⚫️ ✔️ 📊 👆 💚 ⚫️ ✔️, & 👈 💲 ☑ 🎻 (🚥 👆 ⚙️ `JSONResponse`). - **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ `status`. +/// + +/// note | 📡 ℹ + +👆 💪 ⚙️ `from starlette.responses import JSONResponse`. + +**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ `status`. + +/// ## 🗄 & 🛠️ 🩺 diff --git a/docs/em/docs/advanced/advanced-dependencies.md b/docs/em/docs/advanced/advanced-dependencies.md index fa1554734..3404c2687 100644 --- a/docs/em/docs/advanced/advanced-dependencies.md +++ b/docs/em/docs/advanced/advanced-dependencies.md @@ -18,9 +18,7 @@ 👈, 👥 📣 👩‍🔬 `__call__`: -```Python hl_lines="10" -{!../../../docs_src/dependencies/tutorial011.py!} -``` +{* ../../docs_src/dependencies/tutorial011.py hl[10] *} 👉 💼, 👉 `__call__` ⚫️❔ **FastAPI** 🔜 ⚙️ ✅ 🌖 🔢 & 🎧-🔗, & 👉 ⚫️❔ 🔜 🤙 🚶‍♀️ 💲 🔢 👆 *➡ 🛠️ 🔢* ⏪. @@ -28,9 +26,7 @@ & 🔜, 👥 💪 ⚙️ `__init__` 📣 🔢 👐 👈 👥 💪 ⚙️ "🔗" 🔗: -```Python hl_lines="7" -{!../../../docs_src/dependencies/tutorial011.py!} -``` +{* ../../docs_src/dependencies/tutorial011.py hl[7] *} 👉 💼, **FastAPI** 🏆 🚫 ⏱ 👆 ⚖️ 💅 🔃 `__init__`, 👥 🔜 ⚙️ ⚫️ 🔗 👆 📟. @@ -38,9 +34,7 @@ 👥 💪 ✍ 👐 👉 🎓 ⏮️: -```Python hl_lines="16" -{!../../../docs_src/dependencies/tutorial011.py!} -``` +{* ../../docs_src/dependencies/tutorial011.py hl[16] *} & 👈 🌌 👥 💪 "🔗" 👆 🔗, 👈 🔜 ✔️ `"bar"` 🔘 ⚫️, 🔢 `checker.fixed_content`. @@ -56,15 +50,16 @@ checker(q="somequery") ...& 🚶‍♀️ ⚫️❔ 👈 📨 💲 🔗 👆 *➡ 🛠️ 🔢* 🔢 `fixed_content_included`: -```Python hl_lines="20" -{!../../../docs_src/dependencies/tutorial011.py!} -``` +{* ../../docs_src/dependencies/tutorial011.py hl[20] *} + +/// tip + +🌐 👉 💪 😑 🎭. & ⚫️ 💪 🚫 📶 🆑 ❔ ⚫️ ⚠. -!!! tip - 🌐 👉 💪 😑 🎭. & ⚫️ 💪 🚫 📶 🆑 ❔ ⚫️ ⚠. +👫 🖼 😫 🙅, ✋️ 🎦 ❔ ⚫️ 🌐 👷. - 👫 🖼 😫 🙅, ✋️ 🎦 ❔ ⚫️ 🌐 👷. +📃 🔃 💂‍♂, 📤 🚙 🔢 👈 🛠️ 👉 🎏 🌌. - 📃 🔃 💂‍♂, 📤 🚙 🔢 👈 🛠️ 👉 🎏 🌌. +🚥 👆 🤔 🌐 👉, 👆 ⏪ 💭 ❔ 👈 🚙 🧰 💂‍♂ 👷 🔘. - 🚥 👆 🤔 🌐 👉, 👆 ⏪ 💭 ❔ 👈 🚙 🧰 💂‍♂ 👷 🔘. +/// diff --git a/docs/em/docs/advanced/async-sql-databases.md b/docs/em/docs/advanced/async-sql-databases.md deleted file mode 100644 index 848936de1..000000000 --- a/docs/em/docs/advanced/async-sql-databases.md +++ /dev/null @@ -1,162 +0,0 @@ -# 🔁 🗄 (🔗) 💽 - -👆 💪 ⚙️ `encode/databases` ⏮️ **FastAPI** 🔗 💽 ⚙️ `async` & `await`. - -⚫️ 🔗 ⏮️: - -* ✳ -* ✳ -* 🗄 - -👉 🖼, 👥 🔜 ⚙️ **🗄**, ↩️ ⚫️ ⚙️ 👁 📁 & 🐍 ✔️ 🛠️ 🐕‍🦺. , 👆 💪 📁 👉 🖼 & 🏃 ⚫️. - -⏪, 👆 🏭 🈸, 👆 💪 💚 ⚙️ 💽 💽 💖 **✳**. - -!!! tip - 👆 💪 🛠️ 💭 ⚪️➡️ 📄 🔃 🇸🇲 🐜 ([🗄 (🔗) 💽](../tutorial/sql-databases.md){.internal-link target=_blank}), 💖 ⚙️ 🚙 🔢 🎭 🛠️ 💽, 🔬 👆 **FastAPI** 📟. - - 👉 📄 🚫 ✔ 📚 💭, 🌓 😑 💃. - -## 🗄 & ⚒ 🆙 `SQLAlchemy` - -* 🗄 `SQLAlchemy`. -* ✍ `metadata` 🎚. -* ✍ 🏓 `notes` ⚙️ `metadata` 🎚. - -```Python hl_lines="4 14 16-22" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -!!! tip - 👀 👈 🌐 👉 📟 😁 🇸🇲 🐚. - - `databases` 🚫 🔨 🕳 📥. - -## 🗄 & ⚒ 🆙 `databases` - -* 🗄 `databases`. -* ✍ `DATABASE_URL`. -* ✍ `database` 🎚. - -```Python hl_lines="3 9 12" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -!!! tip - 🚥 👆 🔗 🎏 💽 (✅ ✳), 👆 🔜 💪 🔀 `DATABASE_URL`. - -## ✍ 🏓 - -👉 💼, 👥 🏗 🏓 🎏 🐍 📁, ✋️ 🏭, 👆 🔜 🎲 💚 ✍ 👫 ⏮️ ⚗, 🛠️ ⏮️ 🛠️, ♒️. - -📥, 👉 📄 🔜 🏃 🔗, ▶️️ ⏭ ▶️ 👆 **FastAPI** 🈸. - -* ✍ `engine`. -* ✍ 🌐 🏓 ⚪️➡️ `metadata` 🎚. - -```Python hl_lines="25-28" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -## ✍ 🏷 - -✍ Pydantic 🏷: - -* 🗒 ✍ (`NoteIn`). -* 🗒 📨 (`Note`). - -```Python hl_lines="31-33 36-39" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -🏗 👫 Pydantic 🏷, 🔢 💽 🔜 ✔, 🎻 (🗜), & ✍ (📄). - -, 👆 🔜 💪 👀 ⚫️ 🌐 🎓 🛠️ 🩺. - -## 🔗 & 🔌 - -* ✍ 👆 `FastAPI` 🈸. -* ✍ 🎉 🐕‍🦺 🔗 & 🔌 ⚪️➡️ 💽. - -```Python hl_lines="42 45-47 50-52" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -## ✍ 🗒 - -✍ *➡ 🛠️ 🔢* ✍ 🗒: - -```Python hl_lines="55-58" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -!!! Note - 👀 👈 👥 🔗 ⏮️ 💽 ⚙️ `await`, *➡ 🛠️ 🔢* 📣 ⏮️ `async`. - -### 👀 `response_model=List[Note]` - -⚫️ ⚙️ `typing.List`. - -👈 📄 (& ✔, 🎻, ⛽) 🔢 💽, `list` `Note`Ⓜ. - -## ✍ 🗒 - -✍ *➡ 🛠️ 🔢* ✍ 🗒: - -```Python hl_lines="61-65" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -!!! Note - 👀 👈 👥 🔗 ⏮️ 💽 ⚙️ `await`, *➡ 🛠️ 🔢* 📣 ⏮️ `async`. - -### 🔃 `{**note.dict(), "id": last_record_id}` - -`note` Pydantic `Note` 🎚. - -`note.dict()` 📨 `dict` ⏮️ 🚮 💽, 🕳 💖: - -```Python -{ - "text": "Some note", - "completed": False, -} -``` - -✋️ ⚫️ 🚫 ✔️ `id` 🏑. - -👥 ✍ 🆕 `dict`, 👈 🔌 🔑-💲 👫 ⚪️➡️ `note.dict()` ⏮️: - -```Python -{**note.dict()} -``` - -`**note.dict()` "unpacks" the key value pairs directly, so, `{**note.dict()}` would be, more or less, a copy of `note.dict()`. - -& ⤴️, 👥 ↔ 👈 📁 `dict`, ❎ ➕1️⃣ 🔑-💲 👫: `"id": last_record_id`: - -```Python -{**note.dict(), "id": last_record_id} -``` - -, 🏁 🏁 📨 🔜 🕳 💖: - -```Python -{ - "id": 1, - "text": "Some note", - "completed": False, -} -``` - -## ✅ ⚫️ - -👆 💪 📁 👉 📟, & 👀 🩺 http://127.0.0.1:8000/docs. - -📤 👆 💪 👀 🌐 👆 🛠️ 📄 & 🔗 ⏮️ ⚫️: - - - -## 🌅 ℹ - -👆 💪 ✍ 🌅 🔃 `encode/databases` 🚮 📂 📃. diff --git a/docs/em/docs/advanced/async-tests.md b/docs/em/docs/advanced/async-tests.md index df94c6ce7..283d4aa09 100644 --- a/docs/em/docs/advanced/async-tests.md +++ b/docs/em/docs/advanced/async-tests.md @@ -32,15 +32,11 @@ 📁 `main.py` 🔜 ✔️: -```Python -{!../../../docs_src/async_tests/main.py!} -``` +{* ../../docs_src/async_tests/main.py *} 📁 `test_main.py` 🔜 ✔️ 💯 `main.py`, ⚫️ 💪 👀 💖 👉 🔜: -```Python -{!../../../docs_src/async_tests/test_main.py!} -``` +{* ../../docs_src/async_tests/test_main.py *} ## 🏃 ⚫️ @@ -60,18 +56,17 @@ $ pytest 📑 `@pytest.mark.anyio` 💬 ✳ 👈 👉 💯 🔢 🔜 🤙 🔁: -```Python hl_lines="7" -{!../../../docs_src/async_tests/test_main.py!} -``` +{* ../../docs_src/async_tests/test_main.py hl[7] *} + +/// tip -!!! tip - 🗒 👈 💯 🔢 🔜 `async def` ↩️ `def` ⏭ 🕐❔ ⚙️ `TestClient`. +🗒 👈 💯 🔢 🔜 `async def` ↩️ `def` ⏭ 🕐❔ ⚙️ `TestClient`. + +/// ⤴️ 👥 💪 ✍ `AsyncClient` ⏮️ 📱, & 📨 🔁 📨 ⚫️, ⚙️ `await`. -```Python hl_lines="9-10" -{!../../../docs_src/async_tests/test_main.py!} -``` +{* ../../docs_src/async_tests/test_main.py hl[9:12] *} 👉 🌓: @@ -81,12 +76,18 @@ response = client.get('/') ...👈 👥 ⚙️ ⚒ 👆 📨 ⏮️ `TestClient`. -!!! tip - 🗒 👈 👥 ⚙️ 🔁/⌛ ⏮️ 🆕 `AsyncClient` - 📨 🔁. +/// tip + +🗒 👈 👥 ⚙️ 🔁/⌛ ⏮️ 🆕 `AsyncClient` - 📨 🔁. + +/// ## 🎏 🔁 🔢 🤙 🔬 🔢 🔜 🔁, 👆 💪 🔜 🤙 (& `await`) 🎏 `async` 🔢 ↖️ ⚪️➡️ 📨 📨 👆 FastAPI 🈸 👆 💯, ⚫️❔ 👆 🔜 🤙 👫 🙆 🙆 👆 📟. -!!! tip - 🚥 👆 ⚔ `RuntimeError: Task attached to a different loop` 🕐❔ 🛠️ 🔁 🔢 🤙 👆 💯 (✅ 🕐❔ ⚙️ ✳ MotorClient) 💭 🔗 🎚 👈 💪 🎉 ➰ 🕴 🏞 🔁 🔢, ✅ `'@app.on_event("startup")` ⏲. +/// tip + +🚥 👆 ⚔ `RuntimeError: Task attached to a different loop` 🕐❔ 🛠️ 🔁 🔢 🤙 👆 💯 (✅ 🕐❔ ⚙️ ✳ MotorClient) 💭 🔗 🎚 👈 💪 🎉 ➰ 🕴 🏞 🔁 🔢, ✅ `'@app.on_event("startup")` ⏲. + +/// diff --git a/docs/em/docs/advanced/behind-a-proxy.md b/docs/em/docs/advanced/behind-a-proxy.md index 12afe638c..8b14152c9 100644 --- a/docs/em/docs/advanced/behind-a-proxy.md +++ b/docs/em/docs/advanced/behind-a-proxy.md @@ -39,8 +39,11 @@ browser --> proxy proxy --> server ``` -!!! tip - 📢 `0.0.0.0` 🛎 ⚙️ ⛓ 👈 📋 👂 🔛 🌐 📢 💪 👈 🎰/💽. +/// tip + +📢 `0.0.0.0` 🛎 ⚙️ ⛓ 👈 📋 👂 🔛 🌐 📢 💪 👈 🎰/💽. + +/// 🩺 🎚 🔜 💪 🗄 🔗 📣 👈 👉 🛠️ `server` 🔎 `/api/v1` (⛅ 🗳). 🖼: @@ -77,10 +80,13 @@ $ uvicorn main:app --root-path /api/v1 🚥 👆 ⚙️ Hypercorn, ⚫️ ✔️ 🎛 `--root-path`. -!!! note "📡 ℹ" - 🔫 🔧 🔬 `root_path` 👉 ⚙️ 💼. +/// note | 📡 ℹ + +🔫 🔧 🔬 `root_path` 👉 ⚙️ 💼. - & `--root-path` 📋 ⏸ 🎛 🚚 👈 `root_path`. + & `--root-path` 📋 ⏸ 🎛 🚚 👈 `root_path`. + +/// ### ✅ ⏮️ `root_path` @@ -88,9 +94,7 @@ $ uvicorn main:app --root-path /api/v1 📥 👥 ✅ ⚫️ 📧 🎦 🎯. -```Python hl_lines="8" -{!../../../docs_src/behind_a_proxy/tutorial001.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial001.py hl[8] *} ⤴️, 🚥 👆 ▶️ Uvicorn ⏮️: @@ -117,9 +121,7 @@ $ uvicorn main:app --root-path /api/v1 👐, 🚥 👆 🚫 ✔️ 🌌 🚚 📋 ⏸ 🎛 💖 `--root-path` ⚖️ 🌓, 👆 💪 ⚒ `root_path` 🔢 🕐❔ 🏗 👆 FastAPI 📱: -```Python hl_lines="3" -{!../../../docs_src/behind_a_proxy/tutorial002.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial002.py hl[3] *} 🚶‍♀️ `root_path` `FastAPI` 🔜 🌓 🚶‍♀️ `--root-path` 📋 ⏸ 🎛 Uvicorn ⚖️ Hypercorn. @@ -168,8 +170,11 @@ Uvicorn 🔜 ⌛ 🗳 🔐 Uvicorn `http://127.0.0.1:8000/app`, & ⤴️ ⚫ 👉 💬 Traefik 👂 🔛 ⛴ 9️⃣9️⃣9️⃣9️⃣ & ⚙️ ➕1️⃣ 📁 `routes.toml`. -!!! tip - 👥 ⚙️ ⛴ 9️⃣9️⃣9️⃣9️⃣ ↩️ 🐩 🇺🇸🔍 ⛴ 8️⃣0️⃣ 👈 👆 🚫 ✔️ 🏃 ⚫️ ⏮️ 📡 (`sudo`) 😌. +/// tip + +👥 ⚙️ ⛴ 9️⃣9️⃣9️⃣9️⃣ ↩️ 🐩 🇺🇸🔍 ⛴ 8️⃣0️⃣ 👈 👆 🚫 ✔️ 🏃 ⚫️ ⏮️ 📡 (`sudo`) 😌. + +/// 🔜 ✍ 👈 🎏 📁 `routes.toml`: @@ -235,8 +240,11 @@ $ uvicorn main:app --root-path /api/v1 } ``` -!!! tip - 👀 👈 ✋️ 👆 🔐 ⚫️ `http://127.0.0.1:8000/app` ⚫️ 🎦 `root_path` `/api/v1`, ✊ ⚪️➡️ 🎛 `--root-path`. +/// tip + +👀 👈 ✋️ 👆 🔐 ⚫️ `http://127.0.0.1:8000/app` ⚫️ 🎦 `root_path` `/api/v1`, ✊ ⚪️➡️ 🎛 `--root-path`. + +/// & 🔜 📂 📛 ⏮️ ⛴ Traefik, ✅ ➡ 🔡: http://127.0.0.1:9999/api/v1/app. @@ -279,8 +287,11 @@ $ uvicorn main:app --root-path /api/v1 ## 🌖 💽 -!!! warning - 👉 🌅 🏧 ⚙️ 💼. 💭 🆓 🚶 ⚫️. +/// warning + +👉 🌅 🏧 ⚙️ 💼. 💭 🆓 🚶 ⚫️. + +/// 🔢, **FastAPI** 🔜 ✍ `server` 🗄 🔗 ⏮️ 📛 `root_path`. @@ -290,9 +301,7 @@ $ uvicorn main:app --root-path /api/v1 🖼: -```Python hl_lines="4-7" -{!../../../docs_src/behind_a_proxy/tutorial003.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial003.py hl[4:7] *} 🔜 🏗 🗄 🔗 💖: @@ -319,28 +328,32 @@ $ uvicorn main:app --root-path /api/v1 } ``` -!!! tip - 👀 🚘-🏗 💽 ⏮️ `url` 💲 `/api/v1`, ✊ ⚪️➡️ `root_path`. +/// tip + +👀 🚘-🏗 💽 ⏮️ `url` 💲 `/api/v1`, ✊ ⚪️➡️ `root_path`. + +/// 🩺 🎚 http://127.0.0.1:9999/api/v1/docs ⚫️ 🔜 👀 💖: -!!! tip - 🩺 🎚 🔜 🔗 ⏮️ 💽 👈 👆 🖊. +/// tip + +🩺 🎚 🔜 🔗 ⏮️ 💽 👈 👆 🖊. + +/// ### ❎ 🏧 💽 ⚪️➡️ `root_path` 🚥 👆 🚫 💚 **FastAPI** 🔌 🏧 💽 ⚙️ `root_path`, 👆 💪 ⚙️ 🔢 `root_path_in_servers=False`: -```Python hl_lines="9" -{!../../../docs_src/behind_a_proxy/tutorial004.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial004.py hl[9] *} & ⤴️ ⚫️ 🏆 🚫 🔌 ⚫️ 🗄 🔗. ## 🗜 🎧-🈸 -🚥 👆 💪 🗻 🎧-🈸 (🔬 [🎧 🈸 - 🗻](./sub-applications.md){.internal-link target=_blank}) ⏪ ⚙️ 🗳 ⏮️ `root_path`, 👆 💪 ⚫️ 🛎, 👆 🔜 ⌛. +🚥 👆 💪 🗻 🎧-🈸 (🔬 [🎧 🈸 - 🗻](sub-applications.md){.internal-link target=_blank}) ⏪ ⚙️ 🗳 ⏮️ `root_path`, 👆 💪 ⚫️ 🛎, 👆 🔜 ⌛. FastAPI 🔜 🔘 ⚙️ `root_path` 🎆, ⚫️ 🔜 👷. 👶 diff --git a/docs/em/docs/advanced/custom-response.md b/docs/em/docs/advanced/custom-response.md index cf76c01d0..ab95b3e7b 100644 --- a/docs/em/docs/advanced/custom-response.md +++ b/docs/em/docs/advanced/custom-response.md @@ -12,8 +12,11 @@ & 🚥 👈 `Response` ✔️ 🎻 📻 🆎 (`application/json`), 💖 💼 ⏮️ `JSONResponse` & `UJSONResponse`, 💽 👆 📨 🔜 🔁 🗜 (& ⛽) ⏮️ 🙆 Pydantic `response_model` 👈 👆 📣 *➡ 🛠️ 👨‍🎨*. -!!! note - 🚥 👆 ⚙️ 📨 🎓 ⏮️ 🙅‍♂ 📻 🆎, FastAPI 🔜 ⌛ 👆 📨 ✔️ 🙅‍♂ 🎚, ⚫️ 🔜 🚫 📄 📨 📁 🚮 🏗 🗄 🩺. +/// note + +🚥 👆 ⚙️ 📨 🎓 ⏮️ 🙅‍♂ 📻 🆎, FastAPI 🔜 ⌛ 👆 📨 ✔️ 🙅‍♂ 🎚, ⚫️ 🔜 🚫 📄 📨 📁 🚮 🏗 🗄 🩺. + +/// ## ⚙️ `ORJSONResponse` @@ -27,19 +30,23 @@ ✋️ 🚥 👆 🎯 👈 🎚 👈 👆 🛬 **🎻 ⏮️ 🎻**, 👆 💪 🚶‍♀️ ⚫️ 🔗 📨 🎓 & ❎ ➕ 🌥 👈 FastAPI 🔜 ✔️ 🚶‍♀️ 👆 📨 🎚 🔘 `jsonable_encoder` ⏭ 🚶‍♀️ ⚫️ 📨 🎓. -```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial001b.py!} -``` +{* ../../docs_src/custom_response/tutorial001b.py hl[2,7] *} + +/// info + +🔢 `response_class` 🔜 ⚙️ 🔬 "📻 🆎" 📨. -!!! info - 🔢 `response_class` 🔜 ⚙️ 🔬 "📻 🆎" 📨. +👉 💼, 🇺🇸🔍 🎚 `Content-Type` 🔜 ⚒ `application/json`. - 👉 💼, 🇺🇸🔍 🎚 `Content-Type` 🔜 ⚒ `application/json`. + & ⚫️ 🔜 📄 ✅ 🗄. - & ⚫️ 🔜 📄 ✅ 🗄. +/// -!!! tip - `ORJSONResponse` ⏳ 🕴 💪 FastAPI, 🚫 💃. +/// tip + +`ORJSONResponse` ⏳ 🕴 💪 FastAPI, 🚫 💃. + +/// ## 🕸 📨 @@ -48,16 +55,17 @@ * 🗄 `HTMLResponse`. * 🚶‍♀️ `HTMLResponse` 🔢 `response_class` 👆 *➡ 🛠️ 👨‍🎨*. -```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial002.py!} -``` +{* ../../docs_src/custom_response/tutorial002.py hl[2,7] *} + +/// info + +🔢 `response_class` 🔜 ⚙️ 🔬 "📻 🆎" 📨. -!!! info - 🔢 `response_class` 🔜 ⚙️ 🔬 "📻 🆎" 📨. +👉 💼, 🇺🇸🔍 🎚 `Content-Type` 🔜 ⚒ `text/html`. - 👉 💼, 🇺🇸🔍 🎚 `Content-Type` 🔜 ⚒ `text/html`. + & ⚫️ 🔜 📄 ✅ 🗄. - & ⚫️ 🔜 📄 ✅ 🗄. +/// ### 📨 `Response` @@ -65,15 +73,19 @@ 🎏 🖼 ⚪️➡️ 🔛, 🛬 `HTMLResponse`, 💪 👀 💖: -```Python hl_lines="2 7 19" -{!../../../docs_src/custom_response/tutorial003.py!} -``` +{* ../../docs_src/custom_response/tutorial003.py hl[2,7,19] *} + +/// warning + +`Response` 📨 🔗 👆 *➡ 🛠️ 🔢* 🏆 🚫 📄 🗄 (🖼, `Content-Type` 🏆 🚫 📄) & 🏆 🚫 ⭐ 🏧 🎓 🩺. + +/// + +/// info -!!! warning - `Response` 📨 🔗 👆 *➡ 🛠️ 🔢* 🏆 🚫 📄 🗄 (🖼, `Content-Type` 🏆 🚫 📄) & 🏆 🚫 ⭐ 🏧 🎓 🩺. +↗️, ☑ `Content-Type` 🎚, 👔 📟, ♒️, 🔜 👟 ⚪️➡️ `Response` 🎚 👆 📨. -!!! info - ↗️, ☑ `Content-Type` 🎚, 👔 📟, ♒️, 🔜 👟 ⚪️➡️ `Response` 🎚 👆 📨. +/// ### 📄 🗄 & 🔐 `Response` @@ -85,9 +97,7 @@ 🖼, ⚫️ 💪 🕳 💖: -```Python hl_lines="7 21 23" -{!../../../docs_src/custom_response/tutorial004.py!} -``` +{* ../../docs_src/custom_response/tutorial004.py hl[7,21,23] *} 👉 🖼, 🔢 `generate_html_response()` ⏪ 🏗 & 📨 `Response` ↩️ 🛬 🕸 `str`. @@ -103,10 +113,13 @@ ✔️ 🤯 👈 👆 💪 ⚙️ `Response` 📨 🕳 🙆, ⚖️ ✍ 🛃 🎧-🎓. -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.responses import HTMLResponse`. +/// note | 📡 ℹ + +👆 💪 ⚙️ `from starlette.responses import HTMLResponse`. - **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. +**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. + +/// ### `Response` @@ -123,9 +136,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 🎚, ⚓️ 🔛 = & 🔁 = ✍ 🆎. -```Python hl_lines="1 18" -{!../../../docs_src/response_directly/tutorial002.py!} -``` +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} ### `HTMLResponse` @@ -135,9 +146,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 ✊ ✍ ⚖️ 🔢 & 📨 ✅ ✍ 📨. -```Python hl_lines="2 7 9" -{!../../../docs_src/custom_response/tutorial005.py!} -``` +{* ../../docs_src/custom_response/tutorial005.py hl[2,7,9] *} ### `JSONResponse` @@ -153,15 +162,19 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 🎛 🎻 📨 ⚙️ `ujson`. -!!! warning - `ujson` 🌘 💛 🌘 🐍 🏗-🛠️ ❔ ⚫️ 🍵 📐-💼. +/// warning -```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial001.py!} -``` +`ujson` 🌘 💛 🌘 🐍 🏗-🛠️ ❔ ⚫️ 🍵 📐-💼. + +/// + +{* ../../docs_src/custom_response/tutorial001.py hl[2,7] *} + +/// tip -!!! tip - ⚫️ 💪 👈 `ORJSONResponse` 💪 ⏩ 🎛. +⚫️ 💪 👈 `ORJSONResponse` 💪 ⏩ 🎛. + +/// ### `RedirectResponse` @@ -169,18 +182,14 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 👆 💪 📨 `RedirectResponse` 🔗: -```Python hl_lines="2 9" -{!../../../docs_src/custom_response/tutorial006.py!} -``` +{* ../../docs_src/custom_response/tutorial006.py hl[2,9] *} --- ⚖️ 👆 💪 ⚙️ ⚫️ `response_class` 🔢: -```Python hl_lines="2 7 9" -{!../../../docs_src/custom_response/tutorial006b.py!} -``` +{* ../../docs_src/custom_response/tutorial006b.py hl[2,7,9] *} 🚥 👆 👈, ⤴️ 👆 💪 📨 📛 🔗 ⚪️➡️ 👆 *➡ 🛠️* 🔢. @@ -190,17 +199,13 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 👆 💪 ⚙️ `status_code` 🔢 🌀 ⏮️ `response_class` 🔢: -```Python hl_lines="2 7 9" -{!../../../docs_src/custom_response/tutorial006c.py!} -``` +{* ../../docs_src/custom_response/tutorial006c.py hl[2,7,9] *} ### `StreamingResponse` ✊ 🔁 🚂 ⚖️ 😐 🚂/🎻 & 🎏 📨 💪. -```Python hl_lines="2 14" -{!../../../docs_src/custom_response/tutorial007.py!} -``` +{* ../../docs_src/custom_response/tutorial007.py hl[2,14] *} #### ⚙️ `StreamingResponse` ⏮️ 📁-💖 🎚 @@ -211,7 +216,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 👉 🔌 📚 🗃 🔗 ⏮️ ☁ 💾, 📹 🏭, & 🎏. ```{ .python .annotate hl_lines="2 10-12 14" } -{!../../../docs_src/custom_response/tutorial008.py!} +{!../../docs_src/custom_response/tutorial008.py!} ``` 1️⃣. 👉 🚂 🔢. ⚫️ "🚂 🔢" ↩️ ⚫️ 🔌 `yield` 📄 🔘. @@ -222,8 +227,11 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 🔨 ⚫️ 👉 🌌, 👥 💪 🚮 ⚫️ `with` 🍫, & 👈 🌌, 🚚 👈 ⚫️ 📪 ⏮️ 🏁. -!!! tip - 👀 👈 📥 👥 ⚙️ 🐩 `open()` 👈 🚫 🐕‍🦺 `async` & `await`, 👥 📣 ➡ 🛠️ ⏮️ 😐 `def`. +/// tip + +👀 👈 📥 👥 ⚙️ 🐩 `open()` 👈 🚫 🐕‍🦺 `async` & `await`, 👥 📣 ➡ 🛠️ ⏮️ 😐 `def`. + +/// ### `FileResponse` @@ -238,15 +246,11 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 📁 📨 🔜 🔌 ☑ `Content-Length`, `Last-Modified` & `ETag` 🎚. -```Python hl_lines="2 10" -{!../../../docs_src/custom_response/tutorial009.py!} -``` +{* ../../docs_src/custom_response/tutorial009.py hl[2,10] *} 👆 💪 ⚙️ `response_class` 🔢: -```Python hl_lines="2 8 10" -{!../../../docs_src/custom_response/tutorial009b.py!} -``` +{* ../../docs_src/custom_response/tutorial009b.py hl[2,8,10] *} 👉 💼, 👆 💪 📨 📁 ➡ 🔗 ⚪️➡️ 👆 *➡ 🛠️* 🔢. @@ -260,9 +264,7 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 👆 💪 ✍ `CustomORJSONResponse`. 👑 👜 👆 ✔️ ✍ `Response.render(content)` 👩‍🔬 👈 📨 🎚 `bytes`: -```Python hl_lines="9-14 17" -{!../../../docs_src/custom_response/tutorial009c.py!} -``` +{* ../../docs_src/custom_response/tutorial009c.py hl[9:14,17] *} 🔜 ↩️ 🛬: @@ -288,12 +290,13 @@ FastAPI (🤙 💃) 🔜 🔁 🔌 🎚-📐 🎚. ⚫️ 🔜 🔌 🎚-🆎 🖼 🔛, **FastAPI** 🔜 ⚙️ `ORJSONResponse` 🔢, 🌐 *➡ 🛠️*, ↩️ `JSONResponse`. -```Python hl_lines="2 4" -{!../../../docs_src/custom_response/tutorial010.py!} -``` +{* ../../docs_src/custom_response/tutorial010.py hl[2,4] *} + +/// tip + +👆 💪 🔐 `response_class` *➡ 🛠️* ⏭. -!!! tip - 👆 💪 🔐 `response_class` *➡ 🛠️* ⏭. +/// ## 🌖 🧾 diff --git a/docs/em/docs/advanced/dataclasses.md b/docs/em/docs/advanced/dataclasses.md index a4c287106..4dd597262 100644 --- a/docs/em/docs/advanced/dataclasses.md +++ b/docs/em/docs/advanced/dataclasses.md @@ -4,11 +4,9 @@ FastAPI 🏗 🔛 🔝 **Pydantic**, & 👤 ✔️ 🌏 👆 ❔ ⚙️ Pyda ✋️ FastAPI 🐕‍🦺 ⚙️ `dataclasses` 🎏 🌌: -```Python hl_lines="1 7-12 19-20" -{!../../../docs_src/dataclasses/tutorial001.py!} -``` +{* ../../docs_src/dataclasses/tutorial001.py hl[1,7:12,19:20] *} -👉 🐕‍🦺 👏 **Pydantic**, ⚫️ ✔️ 🔗 🐕‍🦺 `dataclasses`. +👉 🐕‍🦺 👏 **Pydantic**, ⚫️ ✔️ 🔗 🐕‍🦺 `dataclasses`. , ⏮️ 📟 🔛 👈 🚫 ⚙️ Pydantic 🎯, FastAPI ⚙️ Pydantic 🗜 📚 🐩 🎻 Pydantic 👍 🍛 🎻. @@ -20,20 +18,21 @@ FastAPI 🏗 🔛 🔝 **Pydantic**, & 👤 ✔️ 🌏 👆 ❔ ⚙️ Pyda 👉 👷 🎏 🌌 ⏮️ Pydantic 🏷. & ⚫️ 🤙 🏆 🎏 🌌 🔘, ⚙️ Pydantic. -!!! info - ✔️ 🤯 👈 🎻 💪 🚫 🌐 Pydantic 🏷 💪. +/// info + +✔️ 🤯 👈 🎻 💪 🚫 🌐 Pydantic 🏷 💪. - , 👆 5️⃣📆 💪 ⚙️ Pydantic 🏷. +, 👆 5️⃣📆 💪 ⚙️ Pydantic 🏷. - ✋️ 🚥 👆 ✔️ 📚 🎻 🤥 🤭, 👉 👌 🎱 ⚙️ 👫 🏋️ 🕸 🛠️ ⚙️ FastAPI. 👶 +✋️ 🚥 👆 ✔️ 📚 🎻 🤥 🤭, 👉 👌 🎱 ⚙️ 👫 🏋️ 🕸 🛠️ ⚙️ FastAPI. 👶 + +/// ## 🎻 `response_model` 👆 💪 ⚙️ `dataclasses` `response_model` 🔢: -```Python hl_lines="1 7-13 19" -{!../../../docs_src/dataclasses/tutorial002.py!} -``` +{* ../../docs_src/dataclasses/tutorial002.py hl[1,7:13,19] *} 🎻 🔜 🔁 🗜 Pydantic 🎻. @@ -50,7 +49,7 @@ FastAPI 🏗 🔛 🔝 **Pydantic**, & 👤 ✔️ 🌏 👆 ❔ ⚙️ Pyda 👈 💼, 👆 💪 🎯 💱 🐩 `dataclasses` ⏮️ `pydantic.dataclasses`, ❔ 💧-♻: ```{ .python .annotate hl_lines="1 5 8-11 14-17 23-25 28" } -{!../../../docs_src/dataclasses/tutorial003.py!} +{!../../docs_src/dataclasses/tutorial003.py!} ``` 1️⃣. 👥 🗄 `field` ⚪️➡️ 🐩 `dataclasses`. @@ -91,7 +90,7 @@ FastAPI 🏗 🔛 🔝 **Pydantic**, & 👤 ✔️ 🌏 👆 ❔ ⚙️ Pyda 👆 💪 🌀 `dataclasses` ⏮️ 🎏 Pydantic 🏷, 😖 ⚪️➡️ 👫, 🔌 👫 👆 👍 🏷, ♒️. -💡 🌅, ✅ Pydantic 🩺 🔃 🎻. +💡 🌅, ✅ Pydantic 🩺 🔃 🎻. ## ⏬ diff --git a/docs/em/docs/advanced/events.md b/docs/em/docs/advanced/events.md index 671e81b18..68adb6d65 100644 --- a/docs/em/docs/advanced/events.md +++ b/docs/em/docs/advanced/events.md @@ -30,26 +30,25 @@ 👥 ✍ 🔁 🔢 `lifespan()` ⏮️ `yield` 💖 👉: -```Python hl_lines="16 19" -{!../../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[16,19] *} 📥 👥 ⚖ 😥 *🕴* 🛠️ 🚚 🏷 🚮 (❌) 🏷 🔢 📖 ⏮️ 🎰 🏫 🏷 ⏭ `yield`. 👉 📟 🔜 🛠️ **⏭** 🈸 **▶️ ✊ 📨**, ⏮️ *🕴*. & ⤴️, ▶️️ ⏮️ `yield`, 👥 🚚 🏷. 👉 📟 🔜 🛠️ **⏮️** 🈸 **🏁 🚚 📨**, ▶️️ ⏭ *🤫*. 👉 💪, 🖼, 🚀 ℹ 💖 💾 ⚖️ 💻. -!!! tip - `shutdown` 🔜 🔨 🕐❔ 👆 **⛔️** 🈸. +/// tip + +`shutdown` 🔜 🔨 🕐❔ 👆 **⛔️** 🈸. - 🎲 👆 💪 ▶️ 🆕 ⏬, ⚖️ 👆 🤚 🎡 🏃 ⚫️. 🤷 +🎲 👆 💪 ▶️ 🆕 ⏬, ⚖️ 👆 🤚 🎡 🏃 ⚫️. 🤷 + +/// ### 🔆 🔢 🥇 👜 👀, 👈 👥 ⚖ 🔁 🔢 ⏮️ `yield`. 👉 📶 🎏 🔗 ⏮️ `yield`. -```Python hl_lines="14-19" -{!../../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[14:19] *} 🥇 🍕 🔢, ⏭ `yield`, 🔜 🛠️ **⏭** 🈸 ▶️. @@ -61,9 +60,7 @@ 👈 🗜 🔢 🔘 🕳 🤙 "**🔁 🔑 👨‍💼**". -```Python hl_lines="1 13" -{!../../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[1,13] *} **🔑 👨‍💼** 🐍 🕳 👈 👆 💪 ⚙️ `with` 📄, 🖼, `open()` 💪 ⚙️ 🔑 👨‍💼: @@ -85,16 +82,17 @@ async with lifespan(app): `lifespan` 🔢 `FastAPI` 📱 ✊ **🔁 🔑 👨‍💼**, 👥 💪 🚶‍♀️ 👆 🆕 `lifespan` 🔁 🔑 👨‍💼 ⚫️. -```Python hl_lines="22" -{!../../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[22] *} ## 🎛 🎉 (😢) -!!! warning - 👍 🌌 🍵 *🕴* & *🤫* ⚙️ `lifespan` 🔢 `FastAPI` 📱 🔬 🔛. +/// warning + +👍 🌌 🍵 *🕴* & *🤫* ⚙️ `lifespan` 🔢 `FastAPI` 📱 🔬 🔛. + +👆 💪 🎲 🚶 👉 🍕. - 👆 💪 🎲 🚶 👉 🍕. +/// 📤 🎛 🌌 🔬 👉 ⚛ 🛠️ ⏮️ *🕴* & ⏮️ *🤫*. @@ -106,9 +104,7 @@ async with lifespan(app): 🚮 🔢 👈 🔜 🏃 ⏭ 🈸 ▶️, 📣 ⚫️ ⏮️ 🎉 `"startup"`: -```Python hl_lines="8" -{!../../../docs_src/events/tutorial001.py!} -``` +{* ../../docs_src/events/tutorial001.py hl[8] *} 👉 💼, `startup` 🎉 🐕‍🦺 🔢 🔜 🔢 🏬 "💽" ( `dict`) ⏮️ 💲. @@ -120,26 +116,33 @@ async with lifespan(app): 🚮 🔢 👈 🔜 🏃 🕐❔ 🈸 🤫 🔽, 📣 ⚫️ ⏮️ 🎉 `"shutdown"`: -```Python hl_lines="6" -{!../../../docs_src/events/tutorial002.py!} -``` +{* ../../docs_src/events/tutorial002.py hl[6] *} 📥, `shutdown` 🎉 🐕‍🦺 🔢 🔜 ✍ ✍ ⏸ `"Application shutdown"` 📁 `log.txt`. -!!! info - `open()` 🔢, `mode="a"` ⛓ "🎻",, ⏸ 🔜 🚮 ⏮️ ⚫️❔ 🔛 👈 📁, 🍵 📁 ⏮️ 🎚. +/// info + +`open()` 🔢, `mode="a"` ⛓ "🎻",, ⏸ 🔜 🚮 ⏮️ ⚫️❔ 🔛 👈 📁, 🍵 📁 ⏮️ 🎚. + +/// + +/// tip + +👀 👈 👉 💼 👥 ⚙️ 🐩 🐍 `open()` 🔢 👈 🔗 ⏮️ 📁. + +, ⚫️ 🔌 👤/🅾 (🔢/🔢), 👈 🚚 "⌛" 👜 ✍ 💾. + +✋️ `open()` 🚫 ⚙️ `async` & `await`. -!!! tip - 👀 👈 👉 💼 👥 ⚙️ 🐩 🐍 `open()` 🔢 👈 🔗 ⏮️ 📁. +, 👥 📣 🎉 🐕‍🦺 🔢 ⏮️ 🐩 `def` ↩️ `async def`. - , ⚫️ 🔌 👤/🅾 (🔢/🔢), 👈 🚚 "⌛" 👜 ✍ 💾. +/// - ✋️ `open()` 🚫 ⚙️ `async` & `await`. +/// info - , 👥 📣 🎉 🐕‍🦺 🔢 ⏮️ 🐩 `def` ↩️ `async def`. +👆 💪 ✍ 🌅 🔃 👫 🎉 🐕‍🦺 💃 🎉' 🩺. -!!! info - 👆 💪 ✍ 🌅 🔃 👫 🎉 🐕‍🦺 💃 🎉' 🩺. +/// ### `startup` & `shutdown` 👯‍♂️ @@ -157,4 +160,4 @@ async with lifespan(app): ## 🎧 🈸 -👶 ✔️ 🤯 👈 👫 🔆 🎉 (🕴 & 🤫) 🔜 🕴 🛠️ 👑 🈸, 🚫 [🎧 🈸 - 🗻](./sub-applications.md){.internal-link target=_blank}. +👶 ✔️ 🤯 👈 👫 🔆 🎉 (🕴 & 🤫) 🔜 🕴 🛠️ 👑 🈸, 🚫 [🎧 🈸 - 🗻](sub-applications.md){.internal-link target=_blank}. diff --git a/docs/em/docs/advanced/generate-clients.md b/docs/em/docs/advanced/generate-clients.md index 30560c8c6..a680c9051 100644 --- a/docs/em/docs/advanced/generate-clients.md +++ b/docs/em/docs/advanced/generate-clients.md @@ -10,23 +10,13 @@ ⚠ 🧰 🗄 🚂. -🚥 👆 🏗 **🕸**, 📶 😌 🎛 🗄-📕-🇦🇪. +🚥 👆 🏗 **🕸**, 📶 😌 🎛 🗄-📕-🇦🇪. ## 🏗 📕 🕸 👩‍💻 ➡️ ▶️ ⏮️ 🙅 FastAPI 🈸: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="9-11 14-15 18 19 23" - {!> ../../../docs_src/generate_clients/tutorial001.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="7-9 12-13 16-17 21" - {!> ../../../docs_src/generate_clients/tutorial001_py39.py!} - ``` +{* ../../docs_src/generate_clients/tutorial001.py hl[9:11,14:15,18,19,23] *} 👀 👈 *➡ 🛠️* 🔬 🏷 👫 ⚙️ 📨 🚀 & 📨 🚀, ⚙️ 🏷 `Item` & `ResponseMessage`. @@ -46,14 +36,14 @@ 🔜 👈 👥 ✔️ 📱 ⏮️ 🏷, 👥 💪 🏗 👩‍💻 📟 🕸. -#### ❎ `openapi-typescript-codegen` +#### ❎ `openapi-ts` -👆 💪 ❎ `openapi-typescript-codegen` 👆 🕸 📟 ⏮️: +👆 💪 ❎ `openapi-ts` 👆 🕸 📟 ⏮️:
```console -$ npm install openapi-typescript-codegen --save-dev +$ npm install @hey-api/openapi-ts --save-dev ---> 100% ``` @@ -62,7 +52,7 @@ $ npm install openapi-typescript-codegen --save-dev #### 🏗 👩‍💻 📟 -🏗 👩‍💻 📟 👆 💪 ⚙️ 📋 ⏸ 🈸 `openapi` 👈 🔜 🔜 ❎. +🏗 👩‍💻 📟 👆 💪 ⚙️ 📋 ⏸ 🈸 `openapi-ts` 👈 🔜 🔜 ❎. ↩️ ⚫️ ❎ 🇧🇿 🏗, 👆 🎲 🚫🔜 💪 🤙 👈 📋 🔗, ✋️ 👆 🔜 🚮 ⚫️ 🔛 👆 `package.json` 📁. @@ -75,12 +65,12 @@ $ npm install openapi-typescript-codegen --save-dev "description": "", "main": "index.js", "scripts": { - "generate-client": "openapi --input http://localhost:8000/openapi.json --output ./src/client --client axios" + "generate-client": "openapi-ts --input http://localhost:8000/openapi.json --output ./src/client --client axios" }, "author": "", "license": "", "devDependencies": { - "openapi-typescript-codegen": "^0.20.1", + "@hey-api/openapi-ts": "^0.27.38", "typescript": "^4.6.2" } } @@ -94,7 +84,7 @@ $ npm install openapi-typescript-codegen --save-dev $ npm run generate-client frontend-app@1.0.0 generate-client /home/user/code/frontend-app -> openapi --input http://localhost:8000/openapi.json --output ./src/client --client axios +> openapi-ts --input http://localhost:8000/openapi.json --output ./src/client --client axios ```
@@ -111,8 +101,11 @@ frontend-app@1.0.0 generate-client /home/user/code/frontend-app -!!! tip - 👀 ✍ `name` & `price`, 👈 🔬 FastAPI 🈸, `Item` 🏷. +/// tip + +👀 ✍ `name` & `price`, 👈 🔬 FastAPI 🈸, `Item` 🏷. + +/// 👆 🔜 ✔️ ⏸ ❌ 📊 👈 👆 📨: @@ -129,17 +122,7 @@ frontend-app@1.0.0 generate-client /home/user/code/frontend-app 🖼, 👆 💪 ✔️ 📄 **🏬** & ➕1️⃣ 📄 **👩‍💻**, & 👫 💪 👽 🔖: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="23 28 36" - {!> ../../../docs_src/generate_clients/tutorial002.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="21 26 34" - {!> ../../../docs_src/generate_clients/tutorial002_py39.py!} - ``` +{* ../../docs_src/generate_clients/tutorial002.py hl[23,28,36] *} ### 🏗 📕 👩‍💻 ⏮️ 🔖 @@ -186,17 +169,7 @@ FastAPI ⚙️ **😍 🆔** 🔠 *➡ 🛠️*, ⚫️ ⚙️ **🛠️ 🆔** 👆 💪 ⤴️ 🚶‍♀️ 👈 🛃 🔢 **FastAPI** `generate_unique_id_function` 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="8-9 12" - {!> ../../../docs_src/generate_clients/tutorial003.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="6-7 10" - {!> ../../../docs_src/generate_clients/tutorial003_py39.py!} - ``` +{* ../../docs_src/generate_clients/tutorial003.py hl[8:9,12] *} ### 🏗 📕 👩‍💻 ⏮️ 🛃 🛠️ 🆔 @@ -218,9 +191,7 @@ FastAPI ⚙️ **😍 🆔** 🔠 *➡ 🛠️*, ⚫️ ⚙️ **🛠️ 🆔** 👥 💪 ⏬ 🗄 🎻 📁 `openapi.json` & ⤴️ 👥 💪 **❎ 👈 🔡 🔖** ⏮️ ✍ 💖 👉: -```Python -{!../../../docs_src/generate_clients/tutorial004.py!} -``` +{* ../../docs_src/generate_clients/tutorial004.py *} ⏮️ 👈, 🛠️ 🆔 🔜 📁 ⚪️➡️ 👜 💖 `items-get_items` `get_items`, 👈 🌌 👩‍💻 🚂 💪 🏗 🙅 👩‍🔬 📛. @@ -235,12 +206,12 @@ FastAPI ⚙️ **😍 🆔** 🔠 *➡ 🛠️*, ⚫️ ⚙️ **🛠️ 🆔** "description": "", "main": "index.js", "scripts": { - "generate-client": "openapi --input ./openapi.json --output ./src/client --client axios" + "generate-client": "openapi-ts --input ./openapi.json --output ./src/client --client axios" }, "author": "", "license": "", "devDependencies": { - "openapi-typescript-codegen": "^0.20.1", + "@hey-api/openapi-ts": "^0.27.38", "typescript": "^4.6.2" } } diff --git a/docs/em/docs/advanced/index.md b/docs/em/docs/advanced/index.md index abe8d357c..48ef8e46d 100644 --- a/docs/em/docs/advanced/index.md +++ b/docs/em/docs/advanced/index.md @@ -2,18 +2,21 @@ ## 🌖 ⚒ -👑 [🔰 - 👩‍💻 🦮](../tutorial/){.internal-link target=_blank} 🔜 🥃 🤝 👆 🎫 🔘 🌐 👑 ⚒ **FastAPI**. +👑 [🔰 - 👩‍💻 🦮](../tutorial/index.md){.internal-link target=_blank} 🔜 🥃 🤝 👆 🎫 🔘 🌐 👑 ⚒ **FastAPI**. ⏭ 📄 👆 🔜 👀 🎏 🎛, 📳, & 🌖 ⚒. -!!! tip - ⏭ 📄 **🚫 🎯 "🏧"**. +/// tip - & ⚫️ 💪 👈 👆 ⚙️ 💼, ⚗ 1️⃣ 👫. +⏭ 📄 **🚫 🎯 "🏧"**. + + & ⚫️ 💪 👈 👆 ⚙️ 💼, ⚗ 1️⃣ 👫. + +/// ## ✍ 🔰 🥇 -👆 💪 ⚙️ 🏆 ⚒ **FastAPI** ⏮️ 💡 ⚪️➡️ 👑 [🔰 - 👩‍💻 🦮](../tutorial/){.internal-link target=_blank}. +👆 💪 ⚙️ 🏆 ⚒ **FastAPI** ⏮️ 💡 ⚪️➡️ 👑 [🔰 - 👩‍💻 🦮](../tutorial/index.md){.internal-link target=_blank}. & ⏭ 📄 🤔 👆 ⏪ ✍ ⚫️, & 🤔 👈 👆 💭 👈 👑 💭. diff --git a/docs/em/docs/advanced/middleware.md b/docs/em/docs/advanced/middleware.md index b3e722ed0..cb04fa3fb 100644 --- a/docs/em/docs/advanced/middleware.md +++ b/docs/em/docs/advanced/middleware.md @@ -43,10 +43,13 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") **FastAPI** 🔌 📚 🛠️ ⚠ ⚙️ 💼, 👥 🔜 👀 ⏭ ❔ ⚙️ 👫. -!!! note "📡 ℹ" - ⏭ 🖼, 👆 💪 ⚙️ `from starlette.middleware.something import SomethingMiddleware`. +/// note | 📡 ℹ - **FastAPI** 🚚 📚 🛠️ `fastapi.middleware` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 🛠️ 👟 🔗 ⚪️➡️ 💃. +⏭ 🖼, 👆 💪 ⚙️ `from starlette.middleware.something import SomethingMiddleware`. + +**FastAPI** 🚚 📚 🛠️ `fastapi.middleware` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 🛠️ 👟 🔗 ⚪️➡️ 💃. + +/// ## `HTTPSRedirectMiddleware` @@ -54,17 +57,13 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 🙆 📨 📨 `http` ⚖️ `ws` 🔜 ❎ 🔐 ⚖ ↩️. -```Python hl_lines="2 6" -{!../../../docs_src/advanced_middleware/tutorial001.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial001.py hl[2,6] *} ## `TrustedHostMiddleware` 🛠️ 👈 🌐 📨 📨 ✔️ ☑ ⚒ `Host` 🎚, ✔ 💂‍♂ 🛡 🇺🇸🔍 🦠 🎚 👊. -```Python hl_lines="2 6-8" -{!../../../docs_src/advanced_middleware/tutorial002.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial002.py hl[2,6:8] *} 📄 ❌ 🐕‍🦺: @@ -78,9 +77,7 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 🛠️ 🔜 🍵 👯‍♂️ 🐩 & 🎥 📨. -```Python hl_lines="2 6" -{!../../../docs_src/advanced_middleware/tutorial003.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial003.py hl[2,6] *} 📄 ❌ 🐕‍🦺: @@ -92,7 +89,6 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") 🖼: -* 🔫 * Uvicorn `ProxyHeadersMiddleware` * 🇸🇲 diff --git a/docs/em/docs/advanced/nosql-databases.md b/docs/em/docs/advanced/nosql-databases.md deleted file mode 100644 index 9c828a909..000000000 --- a/docs/em/docs/advanced/nosql-databases.md +++ /dev/null @@ -1,156 +0,0 @@ -# ☁ (📎 / 🦏 💽) 💽 - -**FastAPI** 💪 🛠️ ⏮️ 🙆 . - -📥 👥 🔜 👀 🖼 ⚙️ **🗄**, 📄 🧢 ☁ 💽. - -👆 💪 🛠️ ⚫️ 🙆 🎏 ☁ 💽 💖: - -* **✳** -* **👸** -* **✳** -* **🇸🇲** -* **✳**, ♒️. - -!!! tip - 📤 🛂 🏗 🚂 ⏮️ **FastAPI** & **🗄**, 🌐 ⚓️ 🔛 **☁**, 🔌 🕸 & 🌖 🧰: https://github.com/tiangolo/full-stack-fastapi-couchbase - -## 🗄 🗄 🦲 - -🔜, 🚫 💸 🙋 🎂, 🕴 🗄: - -```Python hl_lines="3-5" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -## 🔬 📉 ⚙️ "📄 🆎" - -👥 🔜 ⚙️ ⚫️ ⏪ 🔧 🏑 `type` 👆 📄. - -👉 🚫 ✔ 🗄, ✋️ 👍 💡 👈 🔜 ℹ 👆 ⏮️. - -```Python hl_lines="9" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -## 🚮 🔢 🤚 `Bucket` - -**🗄**, 🥡 ⚒ 📄, 👈 💪 🎏 🆎. - -👫 🛎 🌐 🔗 🎏 🈸. - -🔑 🔗 💽 🌏 🔜 "💽" (🎯 💽, 🚫 💽 💽). - -🔑 **✳** 🔜 "🗃". - -📟, `Bucket` 🎨 👑 🇨🇻 📻 ⏮️ 💽. - -👉 🚙 🔢 🔜: - -* 🔗 **🗄** 🌑 (👈 💪 👁 🎰). - * ⚒ 🔢 ⏲. -* 🔓 🌑. -* 🤚 `Bucket` 👐. - * ⚒ 🔢 ⏲. -* 📨 ⚫️. - -```Python hl_lines="12-21" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -## ✍ Pydantic 🏷 - -**🗄** "📄" 🤙 "🎻 🎚", 👥 💪 🏷 👫 ⏮️ Pydantic. - -### `User` 🏷 - -🥇, ➡️ ✍ `User` 🏷: - -```Python hl_lines="24-28" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -👥 🔜 ⚙️ 👉 🏷 👆 *➡ 🛠️ 🔢*,, 👥 🚫 🔌 ⚫️ `hashed_password`. - -### `UserInDB` 🏷 - -🔜, ➡️ ✍ `UserInDB` 🏷. - -👉 🔜 ✔️ 💽 👈 🤙 🏪 💽. - -👥 🚫 ✍ ⚫️ 🏿 Pydantic `BaseModel` ✋️ 🏿 👆 👍 `User`, ↩️ ⚫️ 🔜 ✔️ 🌐 🔢 `User` ➕ 👩‍❤‍👨 🌅: - -```Python hl_lines="31-33" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -!!! note - 👀 👈 👥 ✔️ `hashed_password` & `type` 🏑 👈 🔜 🏪 💽. - - ✋️ ⚫️ 🚫 🍕 🏢 `User` 🏷 (1️⃣ 👥 🔜 📨 *➡ 🛠️*). - -## 🤚 👩‍💻 - -🔜 ✍ 🔢 👈 🔜: - -* ✊ 🆔. -* 🏗 📄 🆔 ⚪️➡️ ⚫️. -* 🤚 📄 ⏮️ 👈 🆔. -* 🚮 🎚 📄 `UserInDB` 🏷. - -🏗 🔢 👈 🕴 💡 🤚 👆 👩‍💻 ⚪️➡️ `username` (⚖️ 🙆 🎏 🔢) 🔬 👆 *➡ 🛠️ 🔢*, 👆 💪 🌖 💪 🏤-⚙️ ⚫️ 💗 🍕 & 🚮 ⚒ 💯 ⚫️: - -```Python hl_lines="36-42" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -### Ⓜ-🎻 - -🚥 👆 🚫 😰 ⏮️ `f"userprofile::{username}"`, ⚫️ 🐍 "Ⓜ-🎻". - -🙆 🔢 👈 🚮 🔘 `{}` Ⓜ-🎻 🔜 ↔ / 💉 🎻. - -### `dict` 🏗 - -🚥 👆 🚫 😰 ⏮️ `UserInDB(**result.value)`, ⚫️ ⚙️ `dict` "🏗". - -⚫️ 🔜 ✊ `dict` `result.value`, & ✊ 🔠 🚮 🔑 & 💲 & 🚶‍♀️ 👫 🔑-💲 `UserInDB` 🇨🇻 ❌. - -, 🚥 `dict` 🔌: - -```Python -{ - "username": "johndoe", - "hashed_password": "some_hash", -} -``` - -⚫️ 🔜 🚶‍♀️ `UserInDB` : - -```Python -UserInDB(username="johndoe", hashed_password="some_hash") -``` - -## ✍ 👆 **FastAPI** 📟 - -### ✍ `FastAPI` 📱 - -```Python hl_lines="46" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -### ✍ *➡ 🛠️ 🔢* - -👆 📟 🤙 🗄 & 👥 🚫 ⚙️ 🥼 🐍 await 🐕‍🦺, 👥 🔜 📣 👆 🔢 ⏮️ 😐 `def` ↩️ `async def`. - -, 🗄 👍 🚫 ⚙️ 👁 `Bucket` 🎚 💗 "🧵Ⓜ",, 👥 💪 🤚 🥡 🔗 & 🚶‍♀️ ⚫️ 👆 🚙 🔢: - -```Python hl_lines="49-53" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -## 🌃 - -👆 💪 🛠️ 🙆 🥉 🥳 ☁ 💽, ⚙️ 👫 🐩 📦. - -🎏 ✔ 🙆 🎏 🔢 🧰, ⚙️ ⚖️ 🛠️. diff --git a/docs/em/docs/advanced/openapi-callbacks.md b/docs/em/docs/advanced/openapi-callbacks.md index 630b75ed2..b0a821668 100644 --- a/docs/em/docs/advanced/openapi-callbacks.md +++ b/docs/em/docs/advanced/openapi-callbacks.md @@ -31,12 +31,13 @@ 👉 🍕 📶 😐, 🌅 📟 🎲 ⏪ 😰 👆: -```Python hl_lines="9-13 36-53" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[9:13,36:53] *} + +/// tip -!!! tip - `callback_url` 🔢 🔢 ⚙️ Pydantic 📛 🆎. +`callback_url` 🔢 🔢 ⚙️ Pydantic 📛 🆎. + +/// 🕴 🆕 👜 `callbacks=messages_callback_router.routes` ❌ *➡ 🛠️ 👨‍🎨*. 👥 🔜 👀 ⚫️❔ 👈 ⏭. @@ -61,10 +62,13 @@ httpx.post(callback_url, json={"description": "Invoice paid", "paid": True}) 👉 🖼 🚫 🛠️ ⏲ ⚫️ (👈 💪 ⏸ 📟), 🕴 🧾 🍕. -!!! tip - ☑ ⏲ 🇺🇸🔍 📨. +/// tip + +☑ ⏲ 🇺🇸🔍 📨. - 🕐❔ 🛠️ ⏲ 👆, 👆 💪 ⚙️ 🕳 💖 🇸🇲 ⚖️ 📨. +🕐❔ 🛠️ ⏲ 👆, 👆 💪 ⚙️ 🕳 💖 🇸🇲 ⚖️ 📨. + +/// ## ✍ ⏲ 🧾 📟 @@ -74,18 +78,19 @@ httpx.post(callback_url, json={"description": "Invoice paid", "paid": True}) 👥 🔜 ⚙️ 👈 🎏 💡 📄 ❔ *🔢 🛠️* 🔜 👀 💖... 🏗 *➡ 🛠️(Ⓜ)* 👈 🔢 🛠️ 🔜 🛠️ (🕐 👆 🛠️ 🔜 🤙). -!!! tip - 🕐❔ ✍ 📟 📄 ⏲, ⚫️ 💪 ⚠ 🌈 👈 👆 👈 *🔢 👩‍💻*. & 👈 👆 ⏳ 🛠️ *🔢 🛠️*, 🚫 *👆 🛠️*. +/// tip + +🕐❔ ✍ 📟 📄 ⏲, ⚫️ 💪 ⚠ 🌈 👈 👆 👈 *🔢 👩‍💻*. & 👈 👆 ⏳ 🛠️ *🔢 🛠️*, 🚫 *👆 🛠️*. + +🍕 🛠️ 👉 ☝ 🎑 ( *🔢 👩‍💻*) 💪 ℹ 👆 💭 💖 ⚫️ 🌅 ⭐ 🌐❔ 🚮 🔢, Pydantic 🏷 💪, 📨, ♒️. 👈 *🔢 🛠️*. - 🍕 🛠️ 👉 ☝ 🎑 ( *🔢 👩‍💻*) 💪 ℹ 👆 💭 💖 ⚫️ 🌅 ⭐ 🌐❔ 🚮 🔢, Pydantic 🏷 💪, 📨, ♒️. 👈 *🔢 🛠️*. +/// ### ✍ ⏲ `APIRouter` 🥇 ✍ 🆕 `APIRouter` 👈 🔜 🔌 1️⃣ ⚖️ 🌅 ⏲. -```Python hl_lines="3 25" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[3,25] *} ### ✍ ⏲ *➡ 🛠️* @@ -96,9 +101,7 @@ httpx.post(callback_url, json={"description": "Invoice paid", "paid": True}) * ⚫️ 🔜 🎲 ✔️ 📄 💪 ⚫️ 🔜 📨, ✅ `body: InvoiceEvent`. * & ⚫️ 💪 ✔️ 📄 📨 ⚫️ 🔜 📨, ✅ `response_model=InvoiceEventReceived`. -```Python hl_lines="16-18 21-22 28-32" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[16:18,21:22,28:32] *} 📤 2️⃣ 👑 🔺 ⚪️➡️ 😐 *➡ 🛠️*: @@ -154,8 +157,11 @@ https://www.external.org/events/invoices/2expen51ve } ``` -!!! tip - 👀 ❔ ⏲ 📛 ⚙️ 🔌 📛 📨 🔢 🔢 `callback_url` (`https://www.external.org/events`) & 🧾 `id` ⚪️➡️ 🔘 🎻 💪 (`2expen51ve`). +/// tip + +👀 ❔ ⏲ 📛 ⚙️ 🔌 📛 📨 🔢 🔢 `callback_url` (`https://www.external.org/events`) & 🧾 `id` ⚪️➡️ 🔘 🎻 💪 (`2expen51ve`). + +/// ### 🚮 ⏲ 📻 @@ -163,12 +169,13 @@ https://www.external.org/events/invoices/2expen51ve 🔜 ⚙️ 🔢 `callbacks` *👆 🛠️ ➡ 🛠️ 👨‍🎨* 🚶‍♀️ 🔢 `.routes` (👈 🤙 `list` 🛣/*➡ 🛠️*) ⚪️➡️ 👈 ⏲ 📻: -```Python hl_lines="35" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[35] *} + +/// tip + +👀 👈 👆 🚫 🚶‍♀️ 📻 ⚫️ (`invoices_callback_router`) `callback=`, ✋️ 🔢 `.routes`, `invoices_callback_router.routes`. -!!! tip - 👀 👈 👆 🚫 🚶‍♀️ 📻 ⚫️ (`invoices_callback_router`) `callback=`, ✋️ 🔢 `.routes`, `invoices_callback_router.routes`. +/// ### ✅ 🩺 diff --git a/docs/em/docs/advanced/path-operation-advanced-configuration.md b/docs/em/docs/advanced/path-operation-advanced-configuration.md index ec7231870..9d9d5fa8d 100644 --- a/docs/em/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/em/docs/advanced/path-operation-advanced-configuration.md @@ -2,16 +2,17 @@ ## 🗄 { -!!! warning - 🚥 👆 🚫 "🕴" 🗄, 👆 🎲 🚫 💪 👉. +/// warning + +🚥 👆 🚫 "🕴" 🗄, 👆 🎲 🚫 💪 👉. + +/// 👆 💪 ⚒ 🗄 `operationId` ⚙️ 👆 *➡ 🛠️* ⏮️ 🔢 `operation_id`. 👆 🔜 ✔️ ⚒ 💭 👈 ⚫️ 😍 🔠 🛠️. -```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *} ### ⚙️ *➡ 🛠️ 🔢* 📛 { @@ -19,25 +20,27 @@ 👆 🔜 ⚫️ ⏮️ ❎ 🌐 👆 *➡ 🛠️*. -```Python hl_lines="2 12-21 24" -{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2,12:21,24] *} + +/// tip -!!! tip - 🚥 👆 ❎ 🤙 `app.openapi()`, 👆 🔜 ℹ `operationId`Ⓜ ⏭ 👈. +🚥 👆 ❎ 🤙 `app.openapi()`, 👆 🔜 ℹ `operationId`Ⓜ ⏭ 👈. -!!! warning - 🚥 👆 👉, 👆 ✔️ ⚒ 💭 🔠 1️⃣ 👆 *➡ 🛠️ 🔢* ✔️ 😍 📛. +/// - 🚥 👫 🎏 🕹 (🐍 📁). +/// warning + +🚥 👆 👉, 👆 ✔️ ⚒ 💭 🔠 1️⃣ 👆 *➡ 🛠️ 🔢* ✔️ 😍 📛. + +🚥 👫 🎏 🕹 (🐍 📁). + +/// ## 🚫 ⚪️➡️ 🗄 🚫 *➡ 🛠️* ⚪️➡️ 🏗 🗄 🔗 (& ➡️, ⚪️➡️ 🏧 🧾 ⚙️), ⚙️ 🔢 `include_in_schema` & ⚒ ⚫️ `False`: -```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *} ## 🏧 📛 ⚪️➡️ #️⃣ @@ -47,9 +50,7 @@ ⚫️ 🏆 🚫 🎦 🆙 🧾, ✋️ 🎏 🧰 (✅ 🐉) 🔜 💪 ⚙️ 🎂. -```Python hl_lines="19-29" -{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19:29] *} ## 🌖 📨 @@ -59,14 +60,17 @@ 👆 💪 📣 🌖 📨 ⏮️ 👫 🏷, 👔 📟, ♒️. -📤 🎂 📃 📥 🧾 🔃 ⚫️, 👆 💪 ✍ ⚫️ [🌖 📨 🗄](./additional-responses.md){.internal-link target=_blank}. +📤 🎂 📃 📥 🧾 🔃 ⚫️, 👆 💪 ✍ ⚫️ [🌖 📨 🗄](additional-responses.md){.internal-link target=_blank}. ## 🗄 ➕ 🕐❔ 👆 📣 *➡ 🛠️* 👆 🈸, **FastAPI** 🔁 🏗 🔗 🗃 🔃 👈 *➡ 🛠️* 🔌 🗄 🔗. -!!! note "📡 ℹ" - 🗄 🔧 ⚫️ 🤙 🛠️ 🎚. +/// note | 📡 ℹ + +🗄 🔧 ⚫️ 🤙 🛠️ 🎚. + +/// ⚫️ ✔️ 🌐 ℹ 🔃 *➡ 🛠️* & ⚙️ 🏗 🏧 🧾. @@ -74,10 +78,13 @@ 👉 *➡ 🛠️*-🎯 🗄 🔗 🛎 🏗 🔁 **FastAPI**, ✋️ 👆 💪 ↔ ⚫️. -!!! tip - 👉 🔅 🎚 ↔ ☝. +/// tip + +👉 🔅 🎚 ↔ ☝. - 🚥 👆 🕴 💪 📣 🌖 📨, 🌅 🏪 🌌 ⚫️ ⏮️ [🌖 📨 🗄](./additional-responses.md){.internal-link target=_blank}. +🚥 👆 🕴 💪 📣 🌖 📨, 🌅 🏪 🌌 ⚫️ ⏮️ [🌖 📨 🗄](additional-responses.md){.internal-link target=_blank}. + +/// 👆 💪 ↔ 🗄 🔗 *➡ 🛠️* ⚙️ 🔢 `openapi_extra`. @@ -85,9 +92,7 @@ 👉 `openapi_extra` 💪 👍, 🖼, 📣 [🗄 ↔](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions): -```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial005.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial005.py hl[6] *} 🚥 👆 📂 🏧 🛠️ 🩺, 👆 ↔ 🔜 🎦 🆙 🔝 🎯 *➡ 🛠️*. @@ -134,9 +139,7 @@ 👆 💪 👈 ⏮️ `openapi_extra`: -```Python hl_lines="20-37 39-40" -{!../../../docs_src/path_operation_advanced_configuration/tutorial006.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial006.py hl[20:37,39:40] *} 👉 🖼, 👥 🚫 📣 🙆 Pydantic 🏷. 👐, 📨 💪 🚫 🎻 🎻, ⚫️ ✍ 🔗 `bytes`, & 🔢 `magic_data_reader()` 🔜 🈚 🎻 ⚫️ 🌌. @@ -150,9 +153,7 @@ 🖼, 👉 🈸 👥 🚫 ⚙️ FastAPI 🛠️ 🛠️ ⚗ 🎻 🔗 ⚪️➡️ Pydantic 🏷 🚫 🏧 🔬 🎻. 👐, 👥 📣 📨 🎚 🆎 📁, 🚫 🎻: -```Python hl_lines="17-22 24" -{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[17:22,24] *} 👐, 👐 👥 🚫 ⚙️ 🔢 🛠️ 🛠️, 👥 ⚙️ Pydantic 🏷 ❎ 🏗 🎻 🔗 💽 👈 👥 💚 📨 📁. @@ -160,11 +161,12 @@ & ⤴️ 👆 📟, 👥 🎻 👈 📁 🎚 🔗, & ⤴️ 👥 🔄 ⚙️ 🎏 Pydantic 🏷 ✔ 📁 🎚: -```Python hl_lines="26-33" -{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[26:33] *} + +/// tip + +📥 👥 🏤-⚙️ 🎏 Pydantic 🏷. -!!! tip - 📥 👥 🏤-⚙️ 🎏 Pydantic 🏷. +✋️ 🎏 🌌, 👥 💪 ✔️ ✔ ⚫️ 🎏 🌌. - ✋️ 🎏 🌌, 👥 💪 ✔️ ✔ ⚫️ 🎏 🌌. +/// diff --git a/docs/em/docs/advanced/response-change-status-code.md b/docs/em/docs/advanced/response-change-status-code.md index 156efcc16..4933484dd 100644 --- a/docs/em/docs/advanced/response-change-status-code.md +++ b/docs/em/docs/advanced/response-change-status-code.md @@ -20,9 +20,7 @@ & ⤴️ 👆 💪 ⚒ `status_code` 👈 *🔀* 📨 🎚. -```Python hl_lines="1 9 12" -{!../../../docs_src/response_change_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *} & ⤴️ 👆 💪 📨 🙆 🎚 👆 💪, 👆 🛎 🔜 ( `dict`, 💽 🏷, ♒️). diff --git a/docs/em/docs/advanced/response-cookies.md b/docs/em/docs/advanced/response-cookies.md index 23fffe1dd..d9fdbaa87 100644 --- a/docs/em/docs/advanced/response-cookies.md +++ b/docs/em/docs/advanced/response-cookies.md @@ -6,9 +6,7 @@ & ⤴️ 👆 💪 ⚒ 🍪 👈 *🔀* 📨 🎚. -```Python hl_lines="1 8-9" -{!../../../docs_src/response_cookies/tutorial002.py!} -``` +{* ../../docs_src/response_cookies/tutorial002.py hl[1,8:9] *} & ⤴️ 👆 💪 📨 🙆 🎚 👆 💪, 👆 🛎 🔜 ( `dict`, 💽 🏷, ♒️). @@ -26,24 +24,28 @@ ⤴️ ⚒ 🍪 ⚫️, & ⤴️ 📨 ⚫️: -```Python hl_lines="10-12" -{!../../../docs_src/response_cookies/tutorial001.py!} -``` +{* ../../docs_src/response_cookies/tutorial001.py hl[10:12] *} -!!! tip - ✔️ 🤯 👈 🚥 👆 📨 📨 🔗 ↩️ ⚙️ `Response` 🔢, FastAPI 🔜 📨 ⚫️ 🔗. +/// tip - , 👆 🔜 ✔️ ⚒ 💭 👆 💽 ☑ 🆎. 🤶 Ⓜ. ⚫️ 🔗 ⏮️ 🎻, 🚥 👆 🛬 `JSONResponse`. +✔️ 🤯 👈 🚥 👆 📨 📨 🔗 ↩️ ⚙️ `Response` 🔢, FastAPI 🔜 📨 ⚫️ 🔗. - & 👈 👆 🚫 📨 🙆 📊 👈 🔜 ✔️ ⛽ `response_model`. +, 👆 🔜 ✔️ ⚒ 💭 👆 💽 ☑ 🆎. 🤶 Ⓜ. ⚫️ 🔗 ⏮️ 🎻, 🚥 👆 🛬 `JSONResponse`. + + & 👈 👆 🚫 📨 🙆 📊 👈 🔜 ✔️ ⛽ `response_model`. + +/// ### 🌅 ℹ -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.responses import Response` ⚖️ `from starlette.responses import JSONResponse`. +/// note | 📡 ℹ + +👆 💪 ⚙️ `from starlette.responses import Response` ⚖️ `from starlette.responses import JSONResponse`. + +**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. - **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. + & `Response` 💪 ⚙️ 🛎 ⚒ 🎚 & 🍪, **FastAPI** 🚚 ⚫️ `fastapi.Response`. - & `Response` 💪 ⚙️ 🛎 ⚒ 🎚 & 🍪, **FastAPI** 🚚 ⚫️ `fastapi.Response`. +/// 👀 🌐 💪 🔢 & 🎛, ✅ 🧾 💃. diff --git a/docs/em/docs/advanced/response-directly.md b/docs/em/docs/advanced/response-directly.md index ba09734fb..29819a205 100644 --- a/docs/em/docs/advanced/response-directly.md +++ b/docs/em/docs/advanced/response-directly.md @@ -14,8 +14,11 @@ 👐, 👆 💪 📨 🙆 `Response` ⚖️ 🙆 🎧-🎓 ⚫️. -!!! tip - `JSONResponse` ⚫️ 🎧-🎓 `Response`. +/// tip + +`JSONResponse` ⚫️ 🎧-🎓 `Response`. + +/// & 🕐❔ 👆 📨 `Response`, **FastAPI** 🔜 🚶‍♀️ ⚫️ 🔗. @@ -31,14 +34,15 @@ 📚 💼, 👆 💪 ⚙️ `jsonable_encoder` 🗜 👆 📊 ⏭ 🚶‍♀️ ⚫️ 📨: -```Python hl_lines="6-7 21-22" -{!../../../docs_src/response_directly/tutorial001.py!} -``` +{* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *} + +/// note | 📡 ℹ + +👆 💪 ⚙️ `from starlette.responses import JSONResponse`. -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.responses import JSONResponse`. +**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. - **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. +/// ## 🛬 🛃 `Response` @@ -50,9 +54,7 @@ 👆 💪 🚮 👆 📂 🎚 🎻, 🚮 ⚫️ `Response`, & 📨 ⚫️: -```Python hl_lines="1 18" -{!../../../docs_src/response_directly/tutorial002.py!} -``` +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} ## 🗒 diff --git a/docs/em/docs/advanced/response-headers.md b/docs/em/docs/advanced/response-headers.md index de798982a..e9e1b62d2 100644 --- a/docs/em/docs/advanced/response-headers.md +++ b/docs/em/docs/advanced/response-headers.md @@ -6,9 +6,7 @@ & ⤴️ 👆 💪 ⚒ 🎚 👈 *🔀* 📨 🎚. -```Python hl_lines="1 7-8" -{!../../../docs_src/response_headers/tutorial002.py!} -``` +{* ../../docs_src/response_headers/tutorial002.py hl[1,7:8] *} & ⤴️ 👆 💪 📨 🙆 🎚 👆 💪, 👆 🛎 🔜 ( `dict`, 💽 🏷, ♒️). @@ -24,16 +22,17 @@ ✍ 📨 🔬 [📨 📨 🔗](response-directly.md){.internal-link target=_blank} & 🚶‍♀️ 🎚 🌖 🔢: -```Python hl_lines="10-12" -{!../../../docs_src/response_headers/tutorial001.py!} -``` +{* ../../docs_src/response_headers/tutorial001.py hl[10:12] *} -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.responses import Response` ⚖️ `from starlette.responses import JSONResponse`. +/// note | 📡 ℹ - **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. +👆 💪 ⚙️ `from starlette.responses import Response` ⚖️ `from starlette.responses import JSONResponse`. - & `Response` 💪 ⚙️ 🛎 ⚒ 🎚 & 🍪, **FastAPI** 🚚 ⚫️ `fastapi.Response`. +**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. + + & `Response` 💪 ⚙️ 🛎 ⚒ 🎚 & 🍪, **FastAPI** 🚚 ⚫️ `fastapi.Response`. + +/// ## 🛃 🎚 diff --git a/docs/em/docs/advanced/security/http-basic-auth.md b/docs/em/docs/advanced/security/http-basic-auth.md index 33470a726..73736f3b3 100644 --- a/docs/em/docs/advanced/security/http-basic-auth.md +++ b/docs/em/docs/advanced/security/http-basic-auth.md @@ -20,9 +20,7 @@ * ⚫️ 📨 🎚 🆎 `HTTPBasicCredentials`: * ⚫️ 🔌 `username` & `password` 📨. -```Python hl_lines="2 6 10" -{!../../../docs_src/security/tutorial006.py!} -``` +{* ../../docs_src/security/tutorial006.py hl[2,6,10] *} 🕐❔ 👆 🔄 📂 📛 🥇 🕰 (⚖️ 🖊 "🛠️" 🔼 🩺) 🖥 🔜 💭 👆 👆 🆔 & 🔐: @@ -42,9 +40,7 @@ ⤴️ 👥 💪 ⚙️ `secrets.compare_digest()` 🚚 👈 `credentials.username` `"stanleyjobson"`, & 👈 `credentials.password` `"swordfish"`. -```Python hl_lines="1 11-21" -{!../../../docs_src/security/tutorial007.py!} -``` +{* ../../docs_src/security/tutorial007.py hl[1,11:21] *} 👉 🔜 🎏: @@ -108,6 +104,4 @@ if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": ⏮️ 🔍 👈 🎓 ❌, 📨 `HTTPException` ⏮️ 👔 📟 4️⃣0️⃣1️⃣ (🎏 📨 🕐❔ 🙅‍♂ 🎓 🚚) & 🚮 🎚 `WWW-Authenticate` ⚒ 🖥 🎦 💳 📋 🔄: -```Python hl_lines="23-27" -{!../../../docs_src/security/tutorial007.py!} -``` +{* ../../docs_src/security/tutorial007.py hl[23:27] *} diff --git a/docs/em/docs/advanced/security/index.md b/docs/em/docs/advanced/security/index.md index f2bb66df4..5cdc47505 100644 --- a/docs/em/docs/advanced/security/index.md +++ b/docs/em/docs/advanced/security/index.md @@ -2,15 +2,18 @@ ## 🌖 ⚒ -📤 ➕ ⚒ 🍵 💂‍♂ ↖️ ⚪️➡️ 🕐 📔 [🔰 - 👩‍💻 🦮: 💂‍♂](../../tutorial/security/){.internal-link target=_blank}. +📤 ➕ ⚒ 🍵 💂‍♂ ↖️ ⚪️➡️ 🕐 📔 [🔰 - 👩‍💻 🦮: 💂‍♂](../../tutorial/security/index.md){.internal-link target=_blank}. -!!! tip - ⏭ 📄 **🚫 🎯 "🏧"**. +/// tip - & ⚫️ 💪 👈 👆 ⚙️ 💼, ⚗ 1️⃣ 👫. +⏭ 📄 **🚫 🎯 "🏧"**. + + & ⚫️ 💪 👈 👆 ⚙️ 💼, ⚗ 1️⃣ 👫. + +/// ## ✍ 🔰 🥇 -⏭ 📄 🤔 👆 ⏪ ✍ 👑 [🔰 - 👩‍💻 🦮: 💂‍♂](../../tutorial/security/){.internal-link target=_blank}. +⏭ 📄 🤔 👆 ⏪ ✍ 👑 [🔰 - 👩‍💻 🦮: 💂‍♂](../../tutorial/security/index.md){.internal-link target=_blank}. 👫 🌐 ⚓️ 🔛 🎏 🔧, ✋️ ✔ ➕ 🛠️. diff --git a/docs/em/docs/advanced/security/oauth2-scopes.md b/docs/em/docs/advanced/security/oauth2-scopes.md index d82fe152b..b8c49bd11 100644 --- a/docs/em/docs/advanced/security/oauth2-scopes.md +++ b/docs/em/docs/advanced/security/oauth2-scopes.md @@ -10,18 +10,21 @@ Oauth2️⃣ ⏮️ ↔ 🛠️ ⚙️ 📚 🦏 🤝 🐕‍🦺, 💖 👱📔 👉 📄 👆 🔜 👀 ❔ 🛠️ 🤝 & ✔ ⏮️ 🎏 Oauth2️⃣ ⏮️ ↔ 👆 **FastAPI** 🈸. -!!! warning - 👉 🌅 ⚖️ 🌘 🏧 📄. 🚥 👆 ▶️, 👆 💪 🚶 ⚫️. +/// warning - 👆 🚫 🎯 💪 Oauth2️⃣ ↔, & 👆 💪 🍵 🤝 & ✔ 👐 👆 💚. +👉 🌅 ⚖️ 🌘 🏧 📄. 🚥 👆 ▶️, 👆 💪 🚶 ⚫️. - ✋️ Oauth2️⃣ ⏮️ ↔ 💪 🎆 🛠️ 🔘 👆 🛠️ (⏮️ 🗄) & 👆 🛠️ 🩺. +👆 🚫 🎯 💪 Oauth2️⃣ ↔, & 👆 💪 🍵 🤝 & ✔ 👐 👆 💚. - 👐, 👆 🛠️ 📚 ↔, ⚖️ 🙆 🎏 💂‍♂/✔ 📄, 👐 👆 💪, 👆 📟. +✋️ Oauth2️⃣ ⏮️ ↔ 💪 🎆 🛠️ 🔘 👆 🛠️ (⏮️ 🗄) & 👆 🛠️ 🩺. - 📚 💼, Oauth2️⃣ ⏮️ ↔ 💪 👹. +👐, 👆 🛠️ 📚 ↔, ⚖️ 🙆 🎏 💂‍♂/✔ 📄, 👐 👆 💪, 👆 📟. - ✋️ 🚥 👆 💭 👆 💪 ⚫️, ⚖️ 👆 😟, 🚧 👂. +📚 💼, Oauth2️⃣ ⏮️ ↔ 💪 👹. + +✋️ 🚥 👆 💭 👆 💪 ⚫️, ⚖️ 👆 😟, 🚧 👂. + +/// ## Oauth2️⃣ ↔ & 🗄 @@ -43,22 +46,23 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀. * `instagram_basic` ⚙️ 👱📔 / 👱📔. * `https://www.googleapis.com/auth/drive` ⚙️ 🇺🇸🔍. -!!! info - Oauth2️⃣ "↔" 🎻 👈 📣 🎯 ✔ ✔. +/// info + +Oauth2️⃣ "↔" 🎻 👈 📣 🎯 ✔ ✔. + +⚫️ 🚫 🤔 🚥 ⚫️ ✔️ 🎏 🦹 💖 `:` ⚖️ 🚥 ⚫️ 📛. - ⚫️ 🚫 🤔 🚥 ⚫️ ✔️ 🎏 🦹 💖 `:` ⚖️ 🚥 ⚫️ 📛. +👈 ℹ 🛠️ 🎯. - 👈 ℹ 🛠️ 🎯. +Oauth2️⃣ 👫 🎻. - Oauth2️⃣ 👫 🎻. +/// ## 🌐 🎑 🥇, ➡️ 🔜 👀 🍕 👈 🔀 ⚪️➡️ 🖼 👑 **🔰 - 👩‍💻 🦮** [Oauth2️⃣ ⏮️ 🔐 (& 🔁), 📨 ⏮️ 🥙 🤝](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. 🔜 ⚙️ Oauth2️⃣ ↔: -```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" -{!../../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[2,4,8,12,46,64,105,107:115,121:124,128:134,139,155] *} 🔜 ➡️ 📄 👈 🔀 🔁 🔁. @@ -68,9 +72,7 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀. `scopes` 🔢 📨 `dict` ⏮️ 🔠 ↔ 🔑 & 📛 💲: -```Python hl_lines="62-65" -{!../../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[62:65] *} ↩️ 👥 🔜 📣 📚 ↔, 👫 🔜 🎦 🆙 🛠️ 🩺 🕐❔ 👆 🕹-/✔. @@ -88,14 +90,15 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀. & 👥 📨 ↔ 🍕 🥙 🤝. -!!! danger - 🦁, 📥 👥 ❎ ↔ 📨 🔗 🤝. +/// danger - ✋️ 👆 🈸, 💂‍♂, 👆 🔜 ⚒ 💭 👆 🕴 🚮 ↔ 👈 👩‍💻 🤙 💪 ✔️, ⚖️ 🕐 👆 ✔️ 🔁. +🦁, 📥 👥 ❎ ↔ 📨 🔗 🤝. -```Python hl_lines="155" -{!../../../docs_src/security/tutorial005.py!} -``` +✋️ 👆 🈸, 💂‍♂, 👆 🔜 ⚒ 💭 👆 🕴 🚮 ↔ 👈 👩‍💻 🤙 💪 ✔️, ⚖️ 🕐 👆 ✔️ 🔁. + +/// + +{* ../../docs_src/security/tutorial005.py hl[155] *} ## 📣 ↔ *➡ 🛠️* & 🔗 @@ -113,21 +116,25 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀. 👉 💼, ⚫️ 🚚 ↔ `me` (⚫️ 💪 🚚 🌅 🌘 1️⃣ ↔). -!!! note - 👆 🚫 🎯 💪 🚮 🎏 ↔ 🎏 🥉. +/// note + +👆 🚫 🎯 💪 🚮 🎏 ↔ 🎏 🥉. - 👥 🔨 ⚫️ 📥 🎦 ❔ **FastAPI** 🍵 ↔ 📣 🎏 🎚. +👥 🔨 ⚫️ 📥 🎦 ❔ **FastAPI** 🍵 ↔ 📣 🎏 🎚. -```Python hl_lines="4 139 168" -{!../../../docs_src/security/tutorial005.py!} -``` +/// -!!! info "📡 ℹ" - `Security` 🤙 🏿 `Depends`, & ⚫️ ✔️ 1️⃣ ➕ 🔢 👈 👥 🔜 👀 ⏪. +{* ../../docs_src/security/tutorial005.py hl[4,139,168] *} - ✋️ ⚙️ `Security` ↩️ `Depends`, **FastAPI** 🔜 💭 👈 ⚫️ 💪 📣 💂‍♂ ↔, ⚙️ 👫 🔘, & 📄 🛠️ ⏮️ 🗄. +/// info | 📡 ℹ - ✋️ 🕐❔ 👆 🗄 `Query`, `Path`, `Depends`, `Security` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. +`Security` 🤙 🏿 `Depends`, & ⚫️ ✔️ 1️⃣ ➕ 🔢 👈 👥 🔜 👀 ⏪. + +✋️ ⚙️ `Security` ↩️ `Depends`, **FastAPI** 🔜 💭 👈 ⚫️ 💪 📣 💂‍♂ ↔, ⚙️ 👫 🔘, & 📄 🛠️ ⏮️ 🗄. + +✋️ 🕐❔ 👆 🗄 `Query`, `Path`, `Depends`, `Security` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. + +/// ## ⚙️ `SecurityScopes` @@ -143,9 +150,7 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀. 👉 `SecurityScopes` 🎓 🎏 `Request` (`Request` ⚙️ 🤚 📨 🎚 🔗). -```Python hl_lines="8 105" -{!../../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[8,105] *} ## ⚙️ `scopes` @@ -159,9 +164,7 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀. 👉 ⚠, 👥 🔌 ↔ 🚚 (🚥 🙆) 🎻 👽 🚀 (⚙️ `scope_str`). 👥 🚮 👈 🎻 ⚗ ↔ `WWW-Authenticate` 🎚 (👉 🍕 🔌). -```Python hl_lines="105 107-115" -{!../../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[105,107:115] *} ## ✔ `username` & 💽 💠 @@ -177,9 +180,7 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀. 👥 ✔ 👈 👥 ✔️ 👩‍💻 ⏮️ 👈 🆔, & 🚥 🚫, 👥 🤚 👈 🎏 ⚠ 👥 ✍ ⏭. -```Python hl_lines="46 116-127" -{!../../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[46,116:127] *} ## ✔ `scopes` @@ -187,9 +188,7 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀. 👉, 👥 ⚙️ `security_scopes.scopes`, 👈 🔌 `list` ⏮️ 🌐 👫 ↔ `str`. -```Python hl_lines="128-134" -{!../../../docs_src/security/tutorial005.py!} -``` +{* ../../docs_src/security/tutorial005.py hl[128:134] *} ## 🔗 🌲 & ↔ @@ -216,10 +215,13 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀. * `security_scopes.scopes` 🔜 🔌 `["me"]` *➡ 🛠️* `read_users_me`, ↩️ ⚫️ 📣 🔗 `get_current_active_user`. * `security_scopes.scopes` 🔜 🔌 `[]` (🕳) *➡ 🛠️* `read_system_status`, ↩️ ⚫️ 🚫 📣 🙆 `Security` ⏮️ `scopes`, & 🚮 🔗, `get_current_user`, 🚫 📣 🙆 `scope` 👯‍♂️. -!!! tip - ⚠ & "🎱" 👜 📥 👈 `get_current_user` 🔜 ✔️ 🎏 📇 `scopes` ✅ 🔠 *➡ 🛠️*. +/// tip + +⚠ & "🎱" 👜 📥 👈 `get_current_user` 🔜 ✔️ 🎏 📇 `scopes` ✅ 🔠 *➡ 🛠️*. - 🌐 ⚓️ 🔛 `scopes` 📣 🔠 *➡ 🛠️* & 🔠 🔗 🔗 🌲 👈 🎯 *➡ 🛠️*. +🌐 ⚓️ 🔛 `scopes` 📣 🔠 *➡ 🛠️* & 🔠 🔗 🔗 🌲 👈 🎯 *➡ 🛠️*. + +/// ## 🌖 ℹ 🔃 `SecurityScopes` @@ -257,10 +259,13 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀. 🏆 🔐 📟 💧, ✋️ 🌖 🏗 🛠️ ⚫️ 🚚 🌅 📶. ⚫️ 🌅 🏗, 📚 🐕‍🦺 🔚 🆙 ✔ 🔑 💧. -!!! note - ⚫️ ⚠ 👈 🔠 🤝 🐕‍🦺 📛 👫 💧 🎏 🌌, ⚒ ⚫️ 🍕 👫 🏷. +/// note + +⚫️ ⚠ 👈 🔠 🤝 🐕‍🦺 📛 👫 💧 🎏 🌌, ⚒ ⚫️ 🍕 👫 🏷. + +✋️ 🔚, 👫 🛠️ 🎏 Oauth2️⃣ 🐩. - ✋️ 🔚, 👫 🛠️ 🎏 Oauth2️⃣ 🐩. +/// **FastAPI** 🔌 🚙 🌐 👫 Oauth2️⃣ 🤝 💧 `fastapi.security.oauth2`. diff --git a/docs/em/docs/advanced/settings.md b/docs/em/docs/advanced/settings.md index 2ebe8ffcb..7fdd0d68a 100644 --- a/docs/em/docs/advanced/settings.md +++ b/docs/em/docs/advanced/settings.md @@ -8,44 +8,51 @@ ## 🌐 🔢 -!!! tip - 🚥 👆 ⏪ 💭 ⚫️❔ "🌐 🔢" & ❔ ⚙️ 👫, 💭 🆓 🚶 ⏭ 📄 🔛. +/// tip + +🚥 👆 ⏪ 💭 ⚫️❔ "🌐 🔢" & ❔ ⚙️ 👫, 💭 🆓 🚶 ⏭ 📄 🔛. + +/// 🌐 🔢 (💭 "🇨🇻 {") 🔢 👈 🖖 🏞 🐍 📟, 🏃‍♂ ⚙️, & 💪 ✍ 👆 🐍 📟 (⚖️ 🎏 📋 👍). 👆 💪 ✍ & ⚙️ 🌐 🔢 🐚, 🍵 💆‍♂ 🐍: -=== "💾, 🇸🇻, 🚪 🎉" +//// tab | 💾, 🇸🇻, 🚪 🎉 -
+
- ```console - // You could create an env var MY_NAME with - $ export MY_NAME="Wade Wilson" +```console +// You could create an env var MY_NAME with +$ export MY_NAME="Wade Wilson" - // Then you could use it with other programs, like - $ echo "Hello $MY_NAME" +// Then you could use it with other programs, like +$ echo "Hello $MY_NAME" - Hello Wade Wilson - ``` +Hello Wade Wilson +``` -
+
-=== "🚪 📋" +//// -
+//// tab | 🚪 📋 - ```console - // Create an env var MY_NAME - $ $Env:MY_NAME = "Wade Wilson" +
- // Use it with other programs, like - $ echo "Hello $Env:MY_NAME" +```console +// Create an env var MY_NAME +$ $Env:MY_NAME = "Wade Wilson" - Hello Wade Wilson - ``` +// Use it with other programs, like +$ echo "Hello $Env:MY_NAME" -
+Hello Wade Wilson +``` + +
+ +//// ### ✍ 🇨🇻 {🐍 @@ -60,10 +67,13 @@ name = os.getenv("MY_NAME", "World") print(f"Hello {name} from Python") ``` -!!! tip - 🥈 ❌ `os.getenv()` 🔢 💲 📨. +/// tip + +🥈 ❌ `os.getenv()` 🔢 💲 📨. - 🚥 🚫 🚚, ⚫️ `None` 🔢, 📥 👥 🚚 `"World"` 🔢 💲 ⚙️. +🚥 🚫 🚚, ⚫️ `None` 🔢, 📥 👥 🚚 `"World"` 🔢 💲 ⚙️. + +/// ⤴️ 👆 💪 🤙 👈 🐍 📋: @@ -114,8 +124,11 @@ Hello World from Python -!!! tip - 👆 💪 ✍ 🌅 🔃 ⚫️ 1️⃣2️⃣-⚖ 📱: 📁. +/// tip + +👆 💪 ✍ 🌅 🔃 ⚫️ 1️⃣2️⃣-⚖ 📱: 📁. + +/// ### 🆎 & 🔬 @@ -125,7 +138,7 @@ Hello World from Python ## Pydantic `Settings` -👐, Pydantic 🚚 👑 🚙 🍵 👫 ⚒ 👟 ⚪️➡️ 🌐 🔢 ⏮️ Pydantic: ⚒ 🧾. +👐, Pydantic 🚚 👑 🚙 🍵 👫 ⚒ 👟 ⚪️➡️ 🌐 🔢 ⏮️ Pydantic: ⚒ 🧾. ### ✍ `Settings` 🎚 @@ -135,12 +148,13 @@ Hello World from Python 👆 💪 ⚙️ 🌐 🎏 🔬 ⚒ & 🧰 👆 ⚙️ Pydantic 🏷, 💖 🎏 📊 🆎 & 🌖 🔬 ⏮️ `Field()`. -```Python hl_lines="2 5-8 11" -{!../../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[2,5:8,11] *} + +/// tip -!!! tip - 🚥 👆 💚 🕳 ⏩ 📁 & 📋, 🚫 ⚙️ 👉 🖼, ⚙️ 🏁 1️⃣ 🔛. +🚥 👆 💚 🕳 ⏩ 📁 & 📋, 🚫 ⚙️ 👉 🖼, ⚙️ 🏁 1️⃣ 🔛. + +/// ⤴️, 🕐❔ 👆 ✍ 👐 👈 `Settings` 🎓 (👉 💼, `settings` 🎚), Pydantic 🔜 ✍ 🌐 🔢 💼-😛 🌌,, ↖-💼 🔢 `APP_NAME` 🔜 ✍ 🔢 `app_name`. @@ -150,9 +164,7 @@ Hello World from Python ⤴️ 👆 💪 ⚙️ 🆕 `settings` 🎚 👆 🈸: -```Python hl_lines="18-20" -{!../../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[18:20] *} ### 🏃 💽 @@ -168,8 +180,11 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app -!!! tip - ⚒ 💗 🇨🇻 {👁 📋 🎏 👫 ⏮️ 🚀, & 🚮 👫 🌐 ⏭ 📋. +/// tip + +⚒ 💗 🇨🇻 {👁 📋 🎏 👫 ⏮️ 🚀, & 🚮 👫 🌐 ⏭ 📋. + +/// & ⤴️ `admin_email` ⚒ 🔜 ⚒ `"deadpool@example.com"`. @@ -183,18 +198,17 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app 🖼, 👆 💪 ✔️ 📁 `config.py` ⏮️: -```Python -{!../../../docs_src/settings/app01/config.py!} -``` +{* ../../docs_src/settings/app01/config.py *} & ⤴️ ⚙️ ⚫️ 📁 `main.py`: -```Python hl_lines="3 11-13" -{!../../../docs_src/settings/app01/main.py!} -``` +{* ../../docs_src/settings/app01/main.py hl[3,11:13] *} + +/// tip -!!! tip - 👆 🔜 💪 📁 `__init__.py` 👆 👀 🔛 [🦏 🈸 - 💗 📁](../tutorial/bigger-applications.md){.internal-link target=_blank}. +👆 🔜 💪 📁 `__init__.py` 👆 👀 🔛 [🦏 🈸 - 💗 📁](../tutorial/bigger-applications.md){.internal-link target=_blank}. + +/// ## ⚒ 🔗 @@ -206,9 +220,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app 👟 ⚪️➡️ ⏮️ 🖼, 👆 `config.py` 📁 💪 👀 💖: -```Python hl_lines="10" -{!../../../docs_src/settings/app02/config.py!} -``` +{* ../../docs_src/settings/app02/config.py hl[10] *} 👀 👈 🔜 👥 🚫 ✍ 🔢 👐 `settings = Settings()`. @@ -216,28 +228,25 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app 🔜 👥 ✍ 🔗 👈 📨 🆕 `config.Settings()`. -```Python hl_lines="5 11-12" -{!../../../docs_src/settings/app02/main.py!} -``` +{* ../../docs_src/settings/app02/main.py hl[5,11:12] *} + +/// tip + +👥 🔜 🔬 `@lru_cache` 🍖. -!!! tip - 👥 🔜 🔬 `@lru_cache` 🍖. +🔜 👆 💪 🤔 `get_settings()` 😐 🔢. - 🔜 👆 💪 🤔 `get_settings()` 😐 🔢. +/// & ⤴️ 👥 💪 🚚 ⚫️ ⚪️➡️ *➡ 🛠️ 🔢* 🔗 & ⚙️ ⚫️ 🙆 👥 💪 ⚫️. -```Python hl_lines="16 18-20" -{!../../../docs_src/settings/app02/main.py!} -``` +{* ../../docs_src/settings/app02/main.py hl[16,18:20] *} ### ⚒ & 🔬 ⤴️ ⚫️ 🔜 📶 ⏩ 🚚 🎏 ⚒ 🎚 ⏮️ 🔬 🏗 🔗 🔐 `get_settings`: -```Python hl_lines="9-10 13 21" -{!../../../docs_src/settings/app02/test_main.py!} -``` +{* ../../docs_src/settings/app02/test_main.py hl[9:10,13,21] *} 🔗 🔐 👥 ⚒ 🆕 💲 `admin_email` 🕐❔ 🏗 🆕 `Settings` 🎚, & ⤴️ 👥 📨 👈 🆕 🎚. @@ -249,15 +258,21 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app 👉 💡 ⚠ 🥃 👈 ⚫️ ✔️ 📛, 👫 🌐 🔢 🛎 🥉 📁 `.env`, & 📁 🤙 "🇨🇻". -!!! tip - 📁 ▶️ ⏮️ ❣ (`.`) 🕵‍♂ 📁 🖥-💖 ⚙️, 💖 💾 & 🇸🇻. +/// tip + +📁 ▶️ ⏮️ ❣ (`.`) 🕵‍♂ 📁 🖥-💖 ⚙️, 💖 💾 & 🇸🇻. - ✋️ 🇨🇻 📁 🚫 🤙 ✔️ ✔️ 👈 ☑ 📁. +✋️ 🇨🇻 📁 🚫 🤙 ✔️ ✔️ 👈 ☑ 📁. + +/// Pydantic ✔️ 🐕‍🦺 👂 ⚪️➡️ 👉 🆎 📁 ⚙️ 🔢 🗃. 👆 💪 ✍ 🌖 Pydantic ⚒: 🇨🇻 (.🇨🇻) 🐕‍🦺. -!!! tip - 👉 👷, 👆 💪 `pip install python-dotenv`. +/// tip + +👉 👷, 👆 💪 `pip install python-dotenv`. + +/// ### `.env` 📁 @@ -272,14 +287,15 @@ APP_NAME="ChimichangApp" & ⤴️ ℹ 👆 `config.py` ⏮️: -```Python hl_lines="9-10" -{!../../../docs_src/settings/app03/config.py!} -``` +{* ../../docs_src/settings/app03/config.py hl[9:10] *} 📥 👥 ✍ 🎓 `Config` 🔘 👆 Pydantic `Settings` 🎓, & ⚒ `env_file` 📁 ⏮️ 🇨🇻 📁 👥 💚 ⚙️. -!!! tip - `Config` 🎓 ⚙️ Pydantic 📳. 👆 💪 ✍ 🌖 Pydantic 🏷 📁 +/// tip + +`Config` 🎓 ⚙️ Pydantic 📳. 👆 💪 ✍ 🌖 Pydantic 🏷 📁 + +/// ### 🏗 `Settings` 🕴 🕐 ⏮️ `lru_cache` @@ -304,9 +320,7 @@ def get_settings(): ✋️ 👥 ⚙️ `@lru_cache` 👨‍🎨 🔛 🔝, `Settings` 🎚 🔜 ✍ 🕴 🕐, 🥇 🕰 ⚫️ 🤙. 👶 👶 -```Python hl_lines="1 10" -{!../../../docs_src/settings/app03/main.py!} -``` +{* ../../docs_src/settings/app03/main.py hl[1,10] *} ⤴️ 🙆 🏁 🤙 `get_settings()` 🔗 ⏭ 📨, ↩️ 🛠️ 🔗 📟 `get_settings()` & 🏗 🆕 `Settings` 🎚, ⚫️ 🔜 📨 🎏 🎚 👈 📨 🔛 🥇 🤙, 🔄 & 🔄. diff --git a/docs/em/docs/advanced/sub-applications.md b/docs/em/docs/advanced/sub-applications.md index e0391453b..7a802cd77 100644 --- a/docs/em/docs/advanced/sub-applications.md +++ b/docs/em/docs/advanced/sub-applications.md @@ -10,9 +10,7 @@ 🥇, ✍ 👑, 🔝-🎚, **FastAPI** 🈸, & 🚮 *➡ 🛠️*: -```Python hl_lines="3 6-8" -{!../../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[3,6:8] *} ### 🎧-🈸 @@ -20,9 +18,7 @@ 👉 🎧-🈸 ➕1️⃣ 🐩 FastAPI 🈸, ✋️ 👉 1️⃣ 👈 🔜 "🗻": -```Python hl_lines="11 14-16" -{!../../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11,14:16] *} ### 🗻 🎧-🈸 @@ -30,9 +26,7 @@ 👉 💼, ⚫️ 🔜 📌 ➡ `/subapi`: -```Python hl_lines="11 19" -{!../../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11,19] *} ### ✅ 🏧 🛠️ 🩺 @@ -70,4 +64,4 @@ $ uvicorn main:app --reload & 🎧-🈸 💪 ✔️ 🚮 👍 📌 🎧-🈸 & 🌐 🔜 👷 ☑, ↩️ FastAPI 🍵 🌐 👉 `root_path`Ⓜ 🔁. -👆 🔜 💡 🌅 🔃 `root_path` & ❔ ⚙️ ⚫️ 🎯 📄 🔃 [⛅ 🗳](./behind-a-proxy.md){.internal-link target=_blank}. +👆 🔜 💡 🌅 🔃 `root_path` & ❔ ⚙️ ⚫️ 🎯 📄 🔃 [⛅ 🗳](behind-a-proxy.md){.internal-link target=_blank}. diff --git a/docs/em/docs/advanced/templates.md b/docs/em/docs/advanced/templates.md index 0a73a4f47..ad4d4fc71 100644 --- a/docs/em/docs/advanced/templates.md +++ b/docs/em/docs/advanced/templates.md @@ -27,27 +27,34 @@ $ pip install jinja2 * 📣 `Request` 🔢 *➡ 🛠️* 👈 🔜 📨 📄. * ⚙️ `templates` 👆 ✍ ✍ & 📨 `TemplateResponse`, 🚶‍♀️ `request` 1️⃣ 🔑-💲 👫 Jinja2️⃣ "🔑". -```Python hl_lines="4 11 15-18" -{!../../../docs_src/templates/tutorial001.py!} -``` +{* ../../docs_src/templates/tutorial001.py hl[4,11,15:18] *} + +/// note + +👀 👈 👆 ✔️ 🚶‍♀️ `request` 🍕 🔑-💲 👫 🔑 Jinja2️⃣. , 👆 ✔️ 📣 ⚫️ 👆 *➡ 🛠️*. + +/// + +/// tip + +📣 `response_class=HTMLResponse` 🩺 🎚 🔜 💪 💭 👈 📨 🔜 🕸. + +/// -!!! note - 👀 👈 👆 ✔️ 🚶‍♀️ `request` 🍕 🔑-💲 👫 🔑 Jinja2️⃣. , 👆 ✔️ 📣 ⚫️ 👆 *➡ 🛠️*. +/// note | 📡 ℹ -!!! tip - 📣 `response_class=HTMLResponse` 🩺 🎚 🔜 💪 💭 👈 📨 🔜 🕸. +👆 💪 ⚙️ `from starlette.templating import Jinja2Templates`. -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.templating import Jinja2Templates`. +**FastAPI** 🚚 🎏 `starlette.templating` `fastapi.templating` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ `Request` & `StaticFiles`. - **FastAPI** 🚚 🎏 `starlette.templating` `fastapi.templating` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ `Request` & `StaticFiles`. +/// ## ✍ 📄 ⤴️ 👆 💪 ✍ 📄 `templates/item.html` ⏮️: ```jinja hl_lines="7" -{!../../../docs_src/templates/templates/item.html!} +{!../../docs_src/templates/templates/item.html!} ``` ⚫️ 🔜 🎦 `id` ✊ ⚪️➡️ "🔑" `dict` 👆 🚶‍♀️: @@ -61,13 +68,13 @@ $ pip install jinja2 & 👆 💪 ⚙️ `url_for()` 🔘 📄, & ⚙️ ⚫️, 🖼, ⏮️ `StaticFiles` 👆 📌. ```jinja hl_lines="4" -{!../../../docs_src/templates/templates/item.html!} +{!../../docs_src/templates/templates/item.html!} ``` 👉 🖼, ⚫️ 🔜 🔗 🎚 📁 `static/styles.css` ⏮️: ```CSS hl_lines="4" -{!../../../docs_src/templates/static/styles.css!} +{!../../docs_src/templates/static/styles.css!} ``` & ↩️ 👆 ⚙️ `StaticFiles`, 👈 🎚 📁 🔜 🍦 🔁 👆 **FastAPI** 🈸 📛 `/static/styles.css`. diff --git a/docs/em/docs/advanced/testing-database.md b/docs/em/docs/advanced/testing-database.md deleted file mode 100644 index 93acd710e..000000000 --- a/docs/em/docs/advanced/testing-database.md +++ /dev/null @@ -1,95 +0,0 @@ -# 🔬 💽 - -👆 💪 ⚙️ 🎏 🔗 🔐 ⚪️➡️ [🔬 🔗 ⏮️ 🔐](testing-dependencies.md){.internal-link target=_blank} 📉 💽 🔬. - -👆 💪 💚 ⚒ 🆙 🎏 💽 🔬, 💾 💽 ⏮️ 💯, 🏤-🥧 ⚫️ ⏮️ 🔬 💽, ♒️. - -👑 💭 ⚫️❔ 🎏 👆 👀 👈 ⏮️ 📃. - -## 🚮 💯 🗄 📱 - -➡️ ℹ 🖼 ⚪️➡️ [🗄 (🔗) 💽](../tutorial/sql-databases.md){.internal-link target=_blank} ⚙️ 🔬 💽. - -🌐 📱 📟 🎏, 👆 💪 🚶 🔙 👈 📃 ✅ ❔ ⚫️. - -🕴 🔀 📥 🆕 🔬 📁. - -👆 😐 🔗 `get_db()` 🔜 📨 💽 🎉. - -💯, 👆 💪 ⚙️ 🔗 🔐 📨 👆 *🛃* 💽 🎉 ↩️ 1️⃣ 👈 🔜 ⚙️ 🛎. - -👉 🖼 👥 🔜 ✍ 🍕 💽 🕴 💯. - -## 📁 📊 - -👥 ✍ 🆕 📁 `sql_app/tests/test_sql_app.py`. - -🆕 📁 📊 👀 💖: - -``` hl_lines="9-11" -. -└── sql_app - ├── __init__.py - ├── crud.py - ├── database.py - ├── main.py - ├── models.py - ├── schemas.py - └── tests - ├── __init__.py - └── test_sql_app.py -``` - -## ✍ 🆕 💽 🎉 - -🥇, 👥 ✍ 🆕 💽 🎉 ⏮️ 🆕 💽. - -💯 👥 🔜 ⚙️ 📁 `test.db` ↩️ `sql_app.db`. - -✋️ 🎂 🎉 📟 🌅 ⚖️ 🌘 🎏, 👥 📁 ⚫️. - -```Python hl_lines="8-13" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -!!! tip - 👆 💪 📉 ❎ 👈 📟 🚮 ⚫️ 🔢 & ⚙️ ⚫️ ⚪️➡️ 👯‍♂️ `database.py` & `tests/test_sql_app.py`. - - 🦁 & 🎯 🔛 🎯 🔬 📟, 👥 🖨 ⚫️. - -## ✍ 💽 - -↩️ 🔜 👥 🔜 ⚙️ 🆕 💽 🆕 📁, 👥 💪 ⚒ 💭 👥 ✍ 💽 ⏮️: - -```Python -Base.metadata.create_all(bind=engine) -``` - -👈 🛎 🤙 `main.py`, ✋️ ⏸ `main.py` ⚙️ 💽 📁 `sql_app.db`, & 👥 💪 ⚒ 💭 👥 ✍ `test.db` 💯. - -👥 🚮 👈 ⏸ 📥, ⏮️ 🆕 📁. - -```Python hl_lines="16" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -## 🔗 🔐 - -🔜 👥 ✍ 🔗 🔐 & 🚮 ⚫️ 🔐 👆 📱. - -```Python hl_lines="19-24 27" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -!!! tip - 📟 `override_get_db()` 🌖 ⚫️❔ 🎏 `get_db()`, ✋️ `override_get_db()` 👥 ⚙️ `TestingSessionLocal` 🔬 💽 ↩️. - -## 💯 📱 - -⤴️ 👥 💪 💯 📱 🛎. - -```Python hl_lines="32-47" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -& 🌐 🛠️ 👥 ⚒ 💽 ⏮️ 💯 🔜 `test.db` 💽 ↩️ 👑 `sql_app.db`. diff --git a/docs/em/docs/advanced/testing-dependencies.md b/docs/em/docs/advanced/testing-dependencies.md index 104a6325e..b2b4b480d 100644 --- a/docs/em/docs/advanced/testing-dependencies.md +++ b/docs/em/docs/advanced/testing-dependencies.md @@ -28,16 +28,17 @@ & ⤴️ **FastAPI** 🔜 🤙 👈 🔐 ↩️ ⏮️ 🔗. -```Python hl_lines="28-29 32" -{!../../../docs_src/dependency_testing/tutorial001.py!} -``` +{* ../../docs_src/dependency_testing/tutorial001.py hl[28:29,32] *} + +/// tip + +👆 💪 ⚒ 🔗 🔐 🔗 ⚙️ 🙆 👆 **FastAPI** 🈸. -!!! tip - 👆 💪 ⚒ 🔗 🔐 🔗 ⚙️ 🙆 👆 **FastAPI** 🈸. +⏮️ 🔗 💪 ⚙️ *➡ 🛠️ 🔢*, *➡ 🛠️ 👨‍🎨* (🕐❔ 👆 🚫 ⚙️ 📨 💲), `.include_router()` 🤙, ♒️. - ⏮️ 🔗 💪 ⚙️ *➡ 🛠️ 🔢*, *➡ 🛠️ 👨‍🎨* (🕐❔ 👆 🚫 ⚙️ 📨 💲), `.include_router()` 🤙, ♒️. +FastAPI 🔜 💪 🔐 ⚫️. - FastAPI 🔜 💪 🔐 ⚫️. +/// ⤴️ 👆 💪 ⏲ 👆 🔐 (❎ 👫) ⚒ `app.dependency_overrides` 🛁 `dict`: @@ -45,5 +46,8 @@ app.dependency_overrides = {} ``` -!!! tip - 🚥 👆 💚 🔐 🔗 🕴 ⏮️ 💯, 👆 💪 ⚒ 🔐 ▶️ 💯 (🔘 💯 🔢) & ⏲ ⚫️ 🔚 (🔚 💯 🔢). +/// tip + +🚥 👆 💚 🔐 🔗 🕴 ⏮️ 💯, 👆 💪 ⚒ 🔐 ▶️ 💯 (🔘 💯 🔢) & ⏲ ⚫️ 🔚 (🔚 💯 🔢). + +/// diff --git a/docs/em/docs/advanced/testing-events.md b/docs/em/docs/advanced/testing-events.md index d64436eb9..f62e9e069 100644 --- a/docs/em/docs/advanced/testing-events.md +++ b/docs/em/docs/advanced/testing-events.md @@ -2,6 +2,4 @@ 🕐❔ 👆 💪 👆 🎉 🐕‍🦺 (`startup` & `shutdown`) 🏃 👆 💯, 👆 💪 ⚙️ `TestClient` ⏮️ `with` 📄: -```Python hl_lines="9-12 20-24" -{!../../../docs_src/app_testing/tutorial003.py!} -``` +{* ../../docs_src/app_testing/tutorial003.py hl[9:12,20:24] *} diff --git a/docs/em/docs/advanced/testing-websockets.md b/docs/em/docs/advanced/testing-websockets.md index 3b8e7e420..2a01de629 100644 --- a/docs/em/docs/advanced/testing-websockets.md +++ b/docs/em/docs/advanced/testing-websockets.md @@ -4,9 +4,10 @@ 👉, 👆 ⚙️ `TestClient` `with` 📄, 🔗*️⃣: -```Python hl_lines="27-31" -{!../../../docs_src/app_testing/tutorial002.py!} -``` +{* ../../docs_src/app_testing/tutorial002.py hl[27:31] *} -!!! note - 🌅 ℹ, ✅ 💃 🧾 🔬 *️⃣ . +/// note + +🌅 ℹ, ✅ 💃 🧾 🔬 *️⃣ . + +/// diff --git a/docs/em/docs/advanced/using-request-directly.md b/docs/em/docs/advanced/using-request-directly.md index faeadb1aa..9530d49bc 100644 --- a/docs/em/docs/advanced/using-request-directly.md +++ b/docs/em/docs/advanced/using-request-directly.md @@ -29,24 +29,28 @@ 👈 👆 💪 🔐 📨 🔗. -```Python hl_lines="1 7-8" -{!../../../docs_src/using_request_directly/tutorial001.py!} -``` +{* ../../docs_src/using_request_directly/tutorial001.py hl[1,7:8] *} 📣 *➡ 🛠️ 🔢* 🔢 ⏮️ 🆎 ➖ `Request` **FastAPI** 🔜 💭 🚶‍♀️ `Request` 👈 🔢. -!!! tip - 🗒 👈 👉 💼, 👥 📣 ➡ 🔢 ⤴️ 📨 🔢. +/// tip - , ➡ 🔢 🔜 ⚗, ✔, 🗜 ✔ 🆎 & ✍ ⏮️ 🗄. +🗒 👈 👉 💼, 👥 📣 ➡ 🔢 ⤴️ 📨 🔢. - 🎏 🌌, 👆 💪 📣 🙆 🎏 🔢 🛎, & ➡, 🤚 `Request` 💁‍♂️. +, ➡ 🔢 🔜 ⚗, ✔, 🗜 ✔ 🆎 & ✍ ⏮️ 🗄. + +🎏 🌌, 👆 💪 📣 🙆 🎏 🔢 🛎, & ➡, 🤚 `Request` 💁‍♂️. + +/// ## `Request` 🧾 👆 💪 ✍ 🌅 ℹ 🔃 `Request` 🎚 🛂 💃 🧾 🕸. -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.requests import Request`. +/// note | 📡 ℹ + +👆 💪 ⚙️ `from starlette.requests import Request`. + +**FastAPI** 🚚 ⚫️ 🔗 🏪 👆, 👩‍💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. - **FastAPI** 🚚 ⚫️ 🔗 🏪 👆, 👩‍💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. +/// diff --git a/docs/em/docs/advanced/websockets.md b/docs/em/docs/advanced/websockets.md index 6ba9b999d..cc6e5c5f0 100644 --- a/docs/em/docs/advanced/websockets.md +++ b/docs/em/docs/advanced/websockets.md @@ -38,30 +38,27 @@ $ pip install websockets ✋️ ⚫️ 🙅 🌌 🎯 🔛 💽-🚄 *️⃣ & ✔️ 👷 🖼: -```Python hl_lines="2 6-38 41-43" -{!../../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[2,6:38,41:43] *} ## ✍ `websocket` 👆 **FastAPI** 🈸, ✍ `websocket`: -```Python hl_lines="1 46-47" -{!../../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[1,46:47] *} + +/// note | 📡 ℹ + +👆 💪 ⚙️ `from starlette.websockets import WebSocket`. -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.websockets import WebSocket`. +**FastAPI** 🚚 🎏 `WebSocket` 🔗 🏪 👆, 👩‍💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. - **FastAPI** 🚚 🎏 `WebSocket` 🔗 🏪 👆, 👩‍💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. +/// ## ⌛ 📧 & 📨 📧 👆 *️⃣ 🛣 👆 💪 `await` 📧 & 📨 📧. -```Python hl_lines="48-52" -{!../../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[48:52] *} 👆 💪 📨 & 📨 💱, ✍, & 🎻 💽. @@ -112,14 +109,15 @@ $ uvicorn main:app --reload 👫 👷 🎏 🌌 🎏 FastAPI 🔗/*➡ 🛠️*: -```Python hl_lines="66-77 76-91" -{!../../../docs_src/websockets/tutorial002.py!} -``` +{* ../../docs_src/websockets/tutorial002.py hl[66:77,76:91] *} + +/// info -!!! info - 👉 *️⃣ ⚫️ 🚫 🤙 ⚒ 🔑 🤚 `HTTPException`, ↩️ 👥 🤚 `WebSocketException`. +👉 *️⃣ ⚫️ 🚫 🤙 ⚒ 🔑 🤚 `HTTPException`, ↩️ 👥 🤚 `WebSocketException`. - 👆 💪 ⚙️ 📪 📟 ⚪️➡️ ☑ 📟 🔬 🔧. +👆 💪 ⚙️ 📪 📟 ⚪️➡️ ☑ 📟 🔬 🔧. + +/// ### 🔄 *️⃣ ⏮️ 🔗 @@ -142,8 +140,11 @@ $ uvicorn main:app --reload * "🏬 🆔", ⚙️ ➡. * "🤝" ⚙️ 🔢 🔢. -!!! tip - 👀 👈 🔢 `token` 🔜 🍵 🔗. +/// tip + +👀 👈 🔢 `token` 🔜 🍵 🔗. + +/// ⏮️ 👈 👆 💪 🔗 *️⃣ & ⤴️ 📨 & 📨 📧: @@ -153,9 +154,7 @@ $ uvicorn main:app --reload 🕐❔ *️⃣ 🔗 📪, `await websocket.receive_text()` 🔜 🤚 `WebSocketDisconnect` ⚠, ❔ 👆 💪 ⤴️ ✊ & 🍵 💖 👉 🖼. -```Python hl_lines="81-83" -{!../../../docs_src/websockets/tutorial003.py!} -``` +{* ../../docs_src/websockets/tutorial003.py hl[81:83] *} 🔄 ⚫️ 👅: @@ -169,12 +168,15 @@ $ uvicorn main:app --reload Client #1596980209979 left the chat ``` -!!! tip - 📱 🔛 ⭐ & 🙅 🖼 🎦 ❔ 🍵 & 📻 📧 📚 *️⃣ 🔗. +/// tip + +📱 🔛 ⭐ & 🙅 🖼 🎦 ❔ 🍵 & 📻 📧 📚 *️⃣ 🔗. + +✋️ ✔️ 🤯 👈, 🌐 🍵 💾, 👁 📇, ⚫️ 🔜 🕴 👷 ⏪ 🛠️ 🏃, & 🔜 🕴 👷 ⏮️ 👁 🛠️. - ✋️ ✔️ 🤯 👈, 🌐 🍵 💾, 👁 📇, ⚫️ 🔜 🕴 👷 ⏪ 🛠️ 🏃, & 🔜 🕴 👷 ⏮️ 👁 🛠️. +🚥 👆 💪 🕳 ⏩ 🛠️ ⏮️ FastAPI ✋️ 👈 🌖 🏋️, 🐕‍🦺 ✳, ✳ ⚖️ 🎏, ✅ 🗜/📻. - 🚥 👆 💪 🕳 ⏩ 🛠️ ⏮️ FastAPI ✋️ 👈 🌖 🏋️, 🐕‍🦺 ✳, ✳ ⚖️ 🎏, ✅ 🗜/📻. +/// ## 🌅 ℹ diff --git a/docs/em/docs/advanced/wsgi.md b/docs/em/docs/advanced/wsgi.md index 4d051807f..d923347d5 100644 --- a/docs/em/docs/advanced/wsgi.md +++ b/docs/em/docs/advanced/wsgi.md @@ -1,6 +1,6 @@ # ✅ 🇨🇻 - 🏺, ✳, 🎏 -👆 💪 🗻 🇨🇻 🈸 👆 👀 ⏮️ [🎧 🈸 - 🗻](./sub-applications.md){.internal-link target=_blank}, [⛅ 🗳](./behind-a-proxy.md){.internal-link target=_blank}. +👆 💪 🗻 🇨🇻 🈸 👆 👀 ⏮️ [🎧 🈸 - 🗻](sub-applications.md){.internal-link target=_blank}, [⛅ 🗳](behind-a-proxy.md){.internal-link target=_blank}. 👈, 👆 💪 ⚙️ `WSGIMiddleware` & ⚙️ ⚫️ 🎁 👆 🇨🇻 🈸, 🖼, 🏺, ✳, ♒️. @@ -12,9 +12,7 @@ & ⤴️ 🗻 👈 🔽 ➡. -```Python hl_lines="2-3 22" -{!../../../docs_src/wsgi/tutorial001.py!} -``` +{* ../../docs_src/wsgi/tutorial001.py hl[2:3,22] *} ## ✅ ⚫️ diff --git a/docs/em/docs/alternatives.md b/docs/em/docs/alternatives.md index 6169aa52d..59b587285 100644 --- a/docs/em/docs/alternatives.md +++ b/docs/em/docs/alternatives.md @@ -30,12 +30,17 @@ ⚫️ 🕐 🥇 🖼 **🏧 🛠️ 🧾**, & 👉 🎯 🕐 🥇 💭 👈 😮 "🔎" **FastAPI**. -!!! note - ✳ 🎂 🛠️ ✍ ✡ 🇺🇸🏛. 🎏 👼 💃 & Uvicorn, 🔛 ❔ **FastAPI** ⚓️. +/// note +✳ 🎂 🛠️ ✍ ✡ 🇺🇸🏛. 🎏 👼 💃 & Uvicorn, 🔛 ❔ **FastAPI** ⚓️. -!!! check "😮 **FastAPI** " - ✔️ 🏧 🛠️ 🧾 🕸 👩‍💻 🔢. +/// + +/// check | 😮 **FastAPI** + +✔️ 🏧 🛠️ 🧾 🕸 👩‍💻 🔢. + +/// ### 🏺 @@ -51,11 +56,13 @@ 👐 🦁 🏺, ⚫️ 😑 💖 👍 🏏 🏗 🔗. ⏭ 👜 🔎 "✳ 🎂 🛠️" 🏺. -!!! check "😮 **FastAPI** " - ◾-🛠️. ⚒ ⚫️ ⏩ 🌀 & 🏏 🧰 & 🍕 💪. +/// check | 😮 **FastAPI** - ✔️ 🙅 & ⏩ ⚙️ 🕹 ⚙️. +◾-🛠️. ⚒ ⚫️ ⏩ 🌀 & 🏏 🧰 & 🍕 💪. +✔️ 🙅 & ⏩ ⚙️ 🕹 ⚙️. + +/// ### 📨 @@ -91,11 +98,13 @@ def read_url(): 👀 🔀 `requests.get(...)` & `@app.get(...)`. -!!! check "😮 **FastAPI** " - * ✔️ 🙅 & 🏋️ 🛠️. - * ⚙️ 🇺🇸🔍 👩‍🔬 📛 (🛠️) 🔗, 🎯 & 🏋️ 🌌. - * ✔️ 🤔 🔢, ✋️ 🏋️ 🛃. +/// check | 😮 **FastAPI** + +* ✔️ 🙅 & 🏋️ 🛠️. +* ⚙️ 🇺🇸🔍 👩‍🔬 📛 (🛠️) 🔗, 🎯 & 🏋️ 🌌. +* ✔️ 🤔 🔢, ✋️ 🏋️ 🛃. +/// ### 🦁 / 🗄 @@ -109,15 +118,18 @@ def read_url(): 👈 ⚫️❔ 🕐❔ 💬 🔃 ⏬ 2️⃣.0️⃣ ⚫️ ⚠ 💬 "🦁", & ⏬ 3️⃣ ➕ "🗄". -!!! check "😮 **FastAPI** " - 🛠️ & ⚙️ 📂 🐩 🛠️ 🔧, ↩️ 🛃 🔗. +/// check | 😮 **FastAPI** + +🛠️ & ⚙️ 📂 🐩 🛠️ 🔧, ↩️ 🛃 🔗. - & 🛠️ 🐩-⚓️ 👩‍💻 🔢 🧰: + & 🛠️ 🐩-⚓️ 👩‍💻 🔢 🧰: - * 🦁 🎚 - * 📄 +* 🦁 🎚 +* 📄 - 👫 2️⃣ 👐 ➖ 📶 🌟 & ⚖, ✋️ 🔨 ⏩ 🔎, 👆 💪 🔎 💯 🌖 🎛 👩‍💻 🔢 🗄 (👈 👆 💪 ⚙️ ⏮️ **FastAPI**). +👫 2️⃣ 👐 ➖ 📶 🌟 & ⚖, ✋️ 🔨 ⏩ 🔎, 👆 💪 🔎 💯 🌖 🎛 👩‍💻 🔢 🗄 (👈 👆 💪 ⚙️ ⏮️ **FastAPI**). + +/// ### 🏺 🎂 🛠️ @@ -135,8 +147,11 @@ def read_url(): ✋️ ⚫️ ✍ ⏭ 📤 🔀 🐍 🆎 🔑. , 🔬 🔠 🔗 👆 💪 ⚙️ 🎯 🇨🇻 & 🎓 🚚 🍭. -!!! check "😮 **FastAPI** " - ⚙️ 📟 🔬 "🔗" 👈 🚚 💽 🆎 & 🔬, 🔁. +/// check | 😮 **FastAPI** + +⚙️ 📟 🔬 "🔗" 👈 🚚 💽 🆎 & 🔬, 🔁. + +/// ### Webarg @@ -148,11 +163,17 @@ Webarg 🧰 👈 ⚒ 🚚 👈 🔛 🔝 📚 🛠️, 🔌 🏺. ⚫️ 👑 🧰 & 👤 ✔️ ⚙️ ⚫️ 📚 💁‍♂️, ⏭ ✔️ **FastAPI**. -!!! info - Webarg ✍ 🎏 🍭 👩‍💻. +/// info + +Webarg ✍ 🎏 🍭 👩‍💻. + +/// + +/// check | 😮 **FastAPI** -!!! check "😮 **FastAPI** " - ✔️ 🏧 🔬 📨 📨 💽. +✔️ 🏧 🔬 📨 📨 💽. + +/// ### APISpec @@ -172,12 +193,17 @@ Webarg 🧰 👈 ⚒ 🚚 👈 🔛 🔝 📚 🛠️, 🔌 🏺. 👨‍🎨 💪 🚫 ℹ 🌅 ⏮️ 👈. & 🚥 👥 🔀 🔢 ⚖️ 🍭 🔗 & 💭 🔀 👈 📁#️⃣, 🏗 🔗 🔜 ❌. -!!! info - APISpec ✍ 🎏 🍭 👩‍💻. +/// info + +APISpec ✍ 🎏 🍭 👩‍💻. + +/// +/// check | 😮 **FastAPI** -!!! check "😮 **FastAPI** " - 🐕‍🦺 📂 🐩 🛠️, 🗄. +🐕‍🦺 📂 🐩 🛠️, 🗄. + +/// ### 🏺-Apispec @@ -199,11 +225,17 @@ Webarg 🧰 👈 ⚒ 🚚 👈 🔛 🔝 📚 🛠️, 🔌 🏺. & 👫 🎏 🌕-📚 🚂 🧢 [**FastAPI** 🏗 🚂](project-generation.md){.internal-link target=_blank}. -!!! info - 🏺-Apispec ✍ 🎏 🍭 👩‍💻. +/// info + +🏺-Apispec ✍ 🎏 🍭 👩‍💻. + +/// -!!! check "😮 **FastAPI** " - 🏗 🗄 🔗 🔁, ⚪️➡️ 🎏 📟 👈 🔬 🛠️ & 🔬. +/// check | 😮 **FastAPI** + +🏗 🗄 🔗 🔁, ⚪️➡️ 🎏 📟 👈 🔬 🛠️ & 🔬. + +/// ### NestJS (& 📐) @@ -219,24 +251,33 @@ Webarg 🧰 👈 ⚒ 🚚 👈 🔛 🔝 📚 🛠️, 🔌 🏺. ⚫️ 💪 🚫 🍵 🔁 🏷 📶 👍. , 🚥 🎻 💪 📨 🎻 🎚 👈 ✔️ 🔘 🏑 👈 🔄 🐦 🎻 🎚, ⚫️ 🚫🔜 ☑ 📄 & ✔. -!!! check "😮 **FastAPI** " - ⚙️ 🐍 🆎 ✔️ 👑 👨‍🎨 🐕‍🦺. +/// check | 😮 **FastAPI** + +⚙️ 🐍 🆎 ✔️ 👑 👨‍🎨 🐕‍🦺. - ✔️ 🏋️ 🔗 💉 ⚙️. 🔎 🌌 📉 📟 🔁. +✔️ 🏋️ 🔗 💉 ⚙️. 🔎 🌌 📉 📟 🔁. + +/// ### 🤣 ⚫️ 🕐 🥇 📶 ⏩ 🐍 🛠️ ⚓️ 🔛 `asyncio`. ⚫️ ⚒ 📶 🎏 🏺. -!!! note "📡 ℹ" - ⚫️ ⚙️ `uvloop` ↩️ 🔢 🐍 `asyncio` ➰. 👈 ⚫️❔ ⚒ ⚫️ ⏩. +/// note | 📡 ℹ + +⚫️ ⚙️ `uvloop` ↩️ 🔢 🐍 `asyncio` ➰. 👈 ⚫️❔ ⚒ ⚫️ ⏩. - ⚫️ 🎯 😮 Uvicorn & 💃, 👈 ⏳ ⏩ 🌘 🤣 📂 📇. +⚫️ 🎯 😮 Uvicorn & 💃, 👈 ⏳ ⏩ 🌘 🤣 📂 📇. -!!! check "😮 **FastAPI** " - 🔎 🌌 ✔️ 😜 🎭. +/// - 👈 ⚫️❔ **FastAPI** ⚓️ 🔛 💃, ⚫️ ⏩ 🛠️ 💪 (💯 🥉-🥳 📇). +/// check | 😮 **FastAPI** + +🔎 🌌 ✔️ 😜 🎭. + +👈 ⚫️❔ **FastAPI** ⚓️ 🔛 💃, ⚫️ ⏩ 🛠️ 💪 (💯 🥉-🥳 📇). + +/// ### 🦅 @@ -246,12 +287,15 @@ Webarg 🧰 👈 ⚒ 🚚 👈 🔛 🔝 📚 🛠️, 🔌 🏺. , 💽 🔬, 🛠️, & 🧾, ✔️ ⌛ 📟, 🚫 🔁. ⚖️ 👫 ✔️ 🛠️ 🛠️ 🔛 🔝 🦅, 💖 🤗. 👉 🎏 🔺 🔨 🎏 🛠️ 👈 😮 🦅 🔧, ✔️ 1️⃣ 📨 🎚 & 1️⃣ 📨 🎚 🔢. -!!! check "😮 **FastAPI** " - 🔎 🌌 🤚 👑 🎭. +/// check | 😮 **FastAPI** - ⤴️ ⏮️ 🤗 (🤗 ⚓️ 🔛 🦅) 😮 **FastAPI** 📣 `response` 🔢 🔢. +🔎 🌌 🤚 👑 🎭. - 👐 FastAPI ⚫️ 📦, & ⚙️ ✴️ ⚒ 🎚, 🍪, & 🎛 👔 📟. +⤴️ ⏮️ 🤗 (🤗 ⚓️ 🔛 🦅) 😮 **FastAPI** 📣 `response` 🔢 🔢. + +👐 FastAPI ⚫️ 📦, & ⚙️ ✴️ ⚒ 🎚, 🍪, & 🎛 👔 📟. + +/// ### @@ -269,12 +313,15 @@ Webarg 🧰 👈 ⚒ 🚚 👈 🔛 🔝 📚 🛠️, 🔌 🏺. 🛣 📣 👁 🥉, ⚙️ 🔢 📣 🎏 🥉 (↩️ ⚙️ 👨‍🎨 👈 💪 🥉 ▶️️ 🔛 🔝 🔢 👈 🍵 🔗). 👉 🔐 ❔ ✳ 🔨 ⚫️ 🌘 ❔ 🏺 (& 💃) 🔨 ⚫️. ⚫️ 🎏 📟 👜 👈 📶 😆 🔗. -!!! check "😮 **FastAPI** " - 🔬 ➕ 🔬 💽 🆎 ⚙️ "🔢" 💲 🏷 🔢. 👉 📉 👨‍🎨 🐕‍🦺, & ⚫️ 🚫 💪 Pydantic ⏭. +/// check | 😮 **FastAPI** + +🔬 ➕ 🔬 💽 🆎 ⚙️ "🔢" 💲 🏷 🔢. 👉 📉 👨‍🎨 🐕‍🦺, & ⚫️ 🚫 💪 Pydantic ⏭. - 👉 🤙 😮 🛠️ 🍕 Pydantic, 🐕‍🦺 🎏 🔬 📄 👗 (🌐 👉 🛠️ 🔜 ⏪ 💪 Pydantic). +👉 🤙 😮 🛠️ 🍕 Pydantic, 🐕‍🦺 🎏 🔬 📄 👗 (🌐 👉 🛠️ 🔜 ⏪ 💪 Pydantic). -### 🤗 +/// + +### 🤗 🤗 🕐 🥇 🛠️ 🛠️ 📄 🛠️ 🔢 🆎 ⚙️ 🐍 🆎 🔑. 👉 👑 💭 👈 😮 🎏 🧰 🎏. @@ -288,15 +335,21 @@ Webarg 🧰 👈 ⚒ 🚚 👈 🔛 🔝 📚 🛠️, 🔌 🏺. ⚫️ ⚓️ 🔛 ⏮️ 🐩 🔁 🐍 🕸 🛠️ (🇨🇻), ⚫️ 💪 🚫 🍵 *️⃣ & 🎏 👜, 👐 ⚫️ ✔️ ↕ 🎭 💁‍♂️. -!!! info - 🤗 ✍ ✡ 🗄, 🎏 👼 `isort`, 👑 🧰 🔁 😇 🗄 🐍 📁. +/// info + +🤗 ✍ ✡ 🗄, 🎏 👼 `isort`, 👑 🧰 🔁 😇 🗄 🐍 📁. + +/// -!!! check "💭 😮 **FastAPI**" - 🤗 😮 🍕 APIStar, & 1️⃣ 🧰 👤 🔎 🏆 👍, 🌟 APIStar. +/// check | 💭 😮 **FastAPI** - 🤗 ℹ 😍 **FastAPI** ⚙️ 🐍 🆎 🔑 📣 🔢, & 🏗 🔗 ⚖ 🛠️ 🔁. +🤗 😮 🍕 APIStar, & 1️⃣ 🧰 👤 🔎 🏆 👍, 🌟 APIStar. - 🤗 😮 **FastAPI** 📣 `response` 🔢 🔢 ⚒ 🎚 & 🍪. +🤗 ℹ 😍 **FastAPI** ⚙️ 🐍 🆎 🔑 📣 🔢, & 🏗 🔗 ⚖ 🛠️ 🔁. + +🤗 😮 **FastAPI** 📣 `response` 🔢 🔢 ⚒ 🎚 & 🍪. + +/// ### APIStar (<= 0️⃣.5️⃣) @@ -322,27 +375,33 @@ Webarg 🧰 👈 ⚒ 🚚 👈 🔛 🔝 📚 🛠️, 🔌 🏺. 🔜 APIStar ⚒ 🧰 ✔ 🗄 🔧, 🚫 🕸 🛠️. -!!! info - APIStar ✍ ✡ 🇺🇸🏛. 🎏 👨 👈 ✍: +/// info + +APIStar ✍ ✡ 🇺🇸🏛. 🎏 👨 👈 ✍: - * ✳ 🎂 🛠️ - * 💃 (❔ **FastAPI** ⚓️) - * Uvicorn (⚙️ 💃 & **FastAPI**) +* ✳ 🎂 🛠️ +* 💃 (❔ **FastAPI** ⚓️) +* Uvicorn (⚙️ 💃 & **FastAPI**) -!!! check "😮 **FastAPI** " - 🔀. +/// - 💭 📣 💗 👜 (💽 🔬, 🛠️ & 🧾) ⏮️ 🎏 🐍 🆎, 👈 🎏 🕰 🚚 👑 👨‍🎨 🐕‍🦺, 🕳 👤 🤔 💎 💭. +/// check | 😮 **FastAPI** - & ⏮️ 🔎 📏 🕰 🎏 🛠️ & 🔬 📚 🎏 🎛, APIStar 🏆 🎛 💪. +🔀. - ⤴️ APIStar ⛔️ 🔀 💽 & 💃 ✍, & 🆕 👻 🏛 ✅ ⚙️. 👈 🏁 🌈 🏗 **FastAPI**. +💭 📣 💗 👜 (💽 🔬, 🛠️ & 🧾) ⏮️ 🎏 🐍 🆎, 👈 🎏 🕰 🚚 👑 👨‍🎨 🐕‍🦺, 🕳 👤 🤔 💎 💭. - 👤 🤔 **FastAPI** "🛐 👨‍💼" APIStar, ⏪ 📉 & 📈 ⚒, ⌨ ⚙️, & 🎏 🍕, ⚓️ 🔛 🏫 ⚪️➡️ 🌐 👉 ⏮️ 🧰. + & ⏮️ 🔎 📏 🕰 🎏 🛠️ & 🔬 📚 🎏 🎛, APIStar 🏆 🎛 💪. + +⤴️ APIStar ⛔️ 🔀 💽 & 💃 ✍, & 🆕 👻 🏛 ✅ ⚙️. 👈 🏁 🌈 🏗 **FastAPI**. + +👤 🤔 **FastAPI** "🛐 👨‍💼" APIStar, ⏪ 📉 & 📈 ⚒, ⌨ ⚙️, & 🎏 🍕, ⚓️ 🔛 🏫 ⚪️➡️ 🌐 👉 ⏮️ 🧰. + +/// ## ⚙️ **FastAPI** -### Pydantic +### Pydantic Pydantic 🗃 🔬 💽 🔬, 🛠️ & 🧾 (⚙️ 🎻 🔗) ⚓️ 🔛 🐍 🆎 🔑. @@ -350,10 +409,13 @@ Pydantic 🗃 🔬 💽 🔬, 🛠️ & 🧾 (⚙️ 🎻 🔗) ⚓️ 🔛 ⚫️ ⭐ 🍭. 👐 ⚫️ ⏩ 🌘 🍭 📇. & ⚫️ ⚓️ 🔛 🎏 🐍 🆎 🔑, 👨‍🎨 🐕‍🦺 👑. -!!! check "**FastAPI** ⚙️ ⚫️" - 🍵 🌐 💽 🔬, 💽 🛠️ & 🏧 🏷 🧾 (⚓️ 🔛 🎻 🔗). +/// check | **FastAPI** ⚙️ ⚫️ - **FastAPI** ⤴️ ✊ 👈 🎻 🔗 💽 & 🚮 ⚫️ 🗄, ↖️ ⚪️➡️ 🌐 🎏 👜 ⚫️ 🔨. +🍵 🌐 💽 🔬, 💽 🛠️ & 🏧 🏷 🧾 (⚓️ 🔛 🎻 🔗). + +**FastAPI** ⤴️ ✊ 👈 🎻 🔗 💽 & 🚮 ⚫️ 🗄, ↖️ ⚪️➡️ 🌐 🎏 👜 ⚫️ 🔨. + +/// ### 💃 @@ -382,17 +444,23 @@ Pydantic 🗃 🔬 💽 🔬, 🛠️ & 🧾 (⚙️ 🎻 🔗) ⚓️ 🔛 👈 1️⃣ 👑 👜 👈 **FastAPI** 🚮 🔛 🔝, 🌐 ⚓️ 🔛 🐍 🆎 🔑 (⚙️ Pydantic). 👈, ➕ 🔗 💉 ⚙️, 💂‍♂ 🚙, 🗄 🔗 ⚡, ♒️. -!!! note "📡 ℹ" - 🔫 🆕 "🐩" ➖ 🛠️ ✳ 🐚 🏉 👨‍🎓. ⚫️ 🚫 "🐍 🐩" (🇩🇬), 👐 👫 🛠️ 🔨 👈. +/// note | 📡 ℹ + +🔫 🆕 "🐩" ➖ 🛠️ ✳ 🐚 🏉 👨‍🎓. ⚫️ 🚫 "🐍 🐩" (🇩🇬), 👐 👫 🛠️ 🔨 👈. - 👐, ⚫️ ⏪ ➖ ⚙️ "🐩" 📚 🧰. 👉 📉 📉 🛠️, 👆 💪 🎛 Uvicorn 🙆 🎏 🔫 💽 (💖 👸 ⚖️ Hypercorn), ⚖️ 👆 💪 🚮 🔫 🔗 🧰, 💖 `python-socketio`. +👐, ⚫️ ⏪ ➖ ⚙️ "🐩" 📚 🧰. 👉 📉 📉 🛠️, 👆 💪 🎛 Uvicorn 🙆 🎏 🔫 💽 (💖 👸 ⚖️ Hypercorn), ⚖️ 👆 💪 🚮 🔫 🔗 🧰, 💖 `python-socketio`. -!!! check "**FastAPI** ⚙️ ⚫️" - 🍵 🌐 🐚 🕸 🍕. ❎ ⚒ 🔛 🔝. +/// - 🎓 `FastAPI` ⚫️ 😖 🔗 ⚪️➡️ 🎓 `Starlette`. +/// check | **FastAPI** ⚙️ ⚫️ - , 🕳 👈 👆 💪 ⏮️ 💃, 👆 💪 ⚫️ 🔗 ⏮️ **FastAPI**, ⚫️ 🌖 💃 🔛 💊. +🍵 🌐 🐚 🕸 🍕. ❎ ⚒ 🔛 🔝. + +🎓 `FastAPI` ⚫️ 😖 🔗 ⚪️➡️ 🎓 `Starlette`. + +, 🕳 👈 👆 💪 ⏮️ 💃, 👆 💪 ⚫️ 🔗 ⏮️ **FastAPI**, ⚫️ 🌖 💃 🔛 💊. + +/// ### Uvicorn @@ -402,12 +470,15 @@ Uvicorn 🌩-⏩ 🔫 💽, 🏗 🔛 uvloop & httptool. ⚫️ 👍 💽 💃 & **FastAPI**. -!!! check "**FastAPI** 👍 ⚫️" - 👑 🕸 💽 🏃 **FastAPI** 🈸. +/// check | **FastAPI** 👍 ⚫️ + +👑 🕸 💽 🏃 **FastAPI** 🈸. + +👆 💪 🌀 ⚫️ ⏮️ 🐁, ✔️ 🔁 👁-🛠️ 💽. - 👆 💪 🌀 ⚫️ ⏮️ 🐁, ✔️ 🔁 👁-🛠️ 💽. +✅ 🌅 ℹ [🛠️](deployment/index.md){.internal-link target=_blank} 📄. - ✅ 🌅 ℹ [🛠️](deployment/index.md){.internal-link target=_blank} 📄. +/// ## 📇 & 🚅 diff --git a/docs/em/docs/async.md b/docs/em/docs/async.md index ddcae1573..ac9804f64 100644 --- a/docs/em/docs/async.md +++ b/docs/em/docs/async.md @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! note - 👆 💪 🕴 ⚙️ `await` 🔘 🔢 ✍ ⏮️ `async def`. +/// note + +👆 💪 🕴 ⚙️ `await` 🔘 🔢 ✍ ⏮️ `async def`. + +/// --- @@ -136,8 +139,11 @@ def results(): -!!! info - 🌹 🖼 👯 🍏. 👶 +/// info + +🌹 🖼 👯 🍏. 👶 + +/// --- @@ -199,8 +205,11 @@ def results(): 📤 🚫 🌅 💬 ⚖️ 😏 🌅 🕰 💸 ⌛ 👶 🚪 ⏲. 👶 -!!! info - 🌹 🖼 👯 🍏. 👶 +/// info + +🌹 🖼 👯 🍏. 👶 + +/// --- @@ -392,12 +401,15 @@ async def read_burgers(): ## 📶 📡 ℹ -!!! warning - 👆 💪 🎲 🚶 👉. +/// warning + +👆 💪 🎲 🚶 👉. + +👉 📶 📡 ℹ ❔ **FastAPI** 👷 🔘. - 👉 📶 📡 ℹ ❔ **FastAPI** 👷 🔘. +🚥 👆 ✔️ 📡 💡 (🈶-🏋, 🧵, 🍫, ♒️.) & 😟 🔃 ❔ FastAPI 🍵 `async def` 🆚 😐 `def`, 🚶 ⤴️. - 🚥 👆 ✔️ 📡 💡 (🈶-🏋, 🧵, 🍫, ♒️.) & 😟 🔃 ❔ FastAPI 🍵 `async def` 🆚 😐 `def`, 🚶 ⤴️. +/// ### ➡ 🛠️ 🔢 @@ -405,15 +417,15 @@ async def read_burgers(): 🚥 👆 👟 ⚪️➡️ ➕1️⃣ 🔁 🛠️ 👈 🔨 🚫 👷 🌌 🔬 🔛 & 👆 ⚙️ ⚖ 🙃 📊-🕴 *➡ 🛠️ 🔢* ⏮️ ✅ `def` 🤪 🎭 📈 (🔃 1️⃣0️⃣0️⃣ 💓), 🙏 🗒 👈 **FastAPI** ⭐ 🔜 🔄. 👫 💼, ⚫️ 👻 ⚙️ `async def` 🚥 👆 *➡ 🛠️ 🔢* ⚙️ 📟 👈 🎭 🚧 👤/🅾. -, 👯‍♂️ ⚠, 🤞 👈 **FastAPI** 🔜 [⏩](/#performance){.internal-link target=_blank} 🌘 (⚖️ 🌘 ⭐) 👆 ⏮️ 🛠️. +, 👯‍♂️ ⚠, 🤞 👈 **FastAPI** 🔜 [⏩](index.md#_15){.internal-link target=_blank} 🌘 (⚖️ 🌘 ⭐) 👆 ⏮️ 🛠️. ### 🔗 -🎏 ✔ [🔗](./tutorial/dependencies/index.md){.internal-link target=_blank}. 🚥 🔗 🐩 `def` 🔢 ↩️ `async def`, ⚫️ 🏃 🔢 🧵. +🎏 ✔ [🔗](tutorial/dependencies/index.md){.internal-link target=_blank}. 🚥 🔗 🐩 `def` 🔢 ↩️ `async def`, ⚫️ 🏃 🔢 🧵. ### 🎧-🔗 -👆 💪 ✔️ 💗 🔗 & [🎧-🔗](./tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} 🚫 🔠 🎏 (🔢 🔢 🔑), 👫 💪 ✍ ⏮️ `async def` & ⏮️ 😐 `def`. ⚫️ 🔜 👷, & 🕐 ✍ ⏮️ 😐 `def` 🔜 🤙 🔛 🔢 🧵 (⚪️➡️ 🧵) ↩️ ➖ "⌛". +👆 💪 ✔️ 💗 🔗 & [🎧-🔗](tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} 🚫 🔠 🎏 (🔢 🔢 🔑), 👫 💪 ✍ ⏮️ `async def` & ⏮️ 😐 `def`. ⚫️ 🔜 👷, & 🕐 ✍ ⏮️ 😐 `def` 🔜 🤙 🔛 🔢 🧵 (⚪️➡️ 🧵) ↩️ ➖ "⌛". ### 🎏 🚙 🔢 @@ -427,4 +439,4 @@ async def read_burgers(): 🔄, 👉 📶 📡 ℹ 👈 🔜 🎲 ⚠ 🚥 👆 👟 🔎 👫. -⏪, 👆 🔜 👍 ⏮️ 📄 ⚪️➡️ 📄 🔛: 🏃 ❓. +⏪, 👆 🔜 👍 ⏮️ 📄 ⚪️➡️ 📄 🔛: 🏃 ❓. diff --git a/docs/em/docs/contributing.md b/docs/em/docs/contributing.md deleted file mode 100644 index 748928f88..000000000 --- a/docs/em/docs/contributing.md +++ /dev/null @@ -1,465 +0,0 @@ -# 🛠️ - 📉 - -🥇, 👆 💪 💚 👀 🔰 🌌 [ℹ FastAPI & 🤚 ℹ](help-fastapi.md){.internal-link target=_blank}. - -## 🛠️ - -🚥 👆 ⏪ 🖖 🗃 & 👆 💭 👈 👆 💪 ⏬ 🤿 📟, 📥 📄 ⚒ 🆙 👆 🌐. - -### 🕹 🌐 ⏮️ `venv` - -👆 💪 ✍ 🕹 🌐 📁 ⚙️ 🐍 `venv` 🕹: - -
- -```console -$ python -m venv env -``` - -
- -👈 🔜 ✍ 📁 `./env/` ⏮️ 🐍 💱 & ⤴️ 👆 🔜 💪 ❎ 📦 👈 ❎ 🌐. - -### 🔓 🌐 - -🔓 🆕 🌐 ⏮️: - -=== "💾, 🇸🇻" - -
- - ```console - $ source ./env/bin/activate - ``` - -
- -=== "🚪 📋" - -
- - ```console - $ .\env\Scripts\Activate.ps1 - ``` - -
- -=== "🚪 🎉" - - ⚖️ 🚥 👆 ⚙️ 🎉 🖥 (✅ 🐛 🎉): - -
- - ```console - $ source ./env/Scripts/activate - ``` - -
- -✅ ⚫️ 👷, ⚙️: - -=== "💾, 🇸🇻, 🚪 🎉" - -
- - ```console - $ which pip - - some/directory/fastapi/env/bin/pip - ``` - -
- -=== "🚪 📋" - -
- - ```console - $ Get-Command pip - - some/directory/fastapi/env/bin/pip - ``` - -
- -🚥 ⚫️ 🎦 `pip` 💱 `env/bin/pip` ⤴️ ⚫️ 👷. 👶 - -⚒ 💭 👆 ✔️ 📰 🐖 ⏬ 🔛 👆 🕹 🌐 ❎ ❌ 🔛 ⏭ 📶: - -
- -```console -$ python -m pip install --upgrade pip - ----> 100% -``` - -
- -!!! tip - 🔠 🕰 👆 ❎ 🆕 📦 ⏮️ `pip` 🔽 👈 🌐, 🔓 🌐 🔄. - - 👉 ⚒ 💭 👈 🚥 👆 ⚙️ 📶 📋 ❎ 👈 📦, 👆 ⚙️ 1️⃣ ⚪️➡️ 👆 🇧🇿 🌐 & 🚫 🙆 🎏 👈 💪 ❎ 🌐. - -### 🐖 - -⏮️ 🔓 🌐 🔬 🔛: - -
- -```console -$ pip install -r requirements.txt - ----> 100% -``` - -
- -⚫️ 🔜 ❎ 🌐 🔗 & 👆 🇧🇿 FastAPI 👆 🇧🇿 🌐. - -#### ⚙️ 👆 🇧🇿 FastAPI - -🚥 👆 ✍ 🐍 📁 👈 🗄 & ⚙️ FastAPI, & 🏃 ⚫️ ⏮️ 🐍 ⚪️➡️ 👆 🇧🇿 🌐, ⚫️ 🔜 ⚙️ 👆 🇧🇿 FastAPI ℹ 📟. - -& 🚥 👆 ℹ 👈 🇧🇿 FastAPI ℹ 📟, ⚫️ ❎ ⏮️ `-e`, 🕐❔ 👆 🏃 👈 🐍 📁 🔄, ⚫️ 🔜 ⚙️ 🍋 ⏬ FastAPI 👆 ✍. - -👈 🌌, 👆 🚫 ✔️ "❎" 👆 🇧🇿 ⏬ 💪 💯 🔠 🔀. - -### 📁 - -📤 ✍ 👈 👆 💪 🏃 👈 🔜 📁 & 🧹 🌐 👆 📟: - -
- -```console -$ bash scripts/format.sh -``` - -
- -⚫️ 🔜 🚘-😇 🌐 👆 🗄. - -⚫️ 😇 👫 ☑, 👆 💪 ✔️ FastAPI ❎ 🌐 👆 🌐, ⏮️ 📋 📄 🔛 ⚙️ `-e`. - -## 🩺 - -🥇, ⚒ 💭 👆 ⚒ 🆙 👆 🌐 🔬 🔛, 👈 🔜 ❎ 🌐 📄. - -🧾 ⚙️ . - -& 📤 ➕ 🧰/✍ 🥉 🍵 ✍ `./scripts/docs.py`. - -!!! tip - 👆 🚫 💪 👀 📟 `./scripts/docs.py`, 👆 ⚙️ ⚫️ 📋 ⏸. - -🌐 🧾 ✍ 📁 📁 `./docs/en/`. - -📚 🔰 ✔️ 🍫 📟. - -🌅 💼, 👫 🍫 📟 ☑ 🏁 🈸 👈 💪 🏃. - -👐, 👈 🍫 📟 🚫 ✍ 🔘 ✍, 👫 🐍 📁 `./docs_src/` 📁. - -& 👈 🐍 📁 🔌/💉 🧾 🕐❔ 🏭 🕸. - -### 🩺 💯 - -🏆 💯 🤙 🏃 🛡 🖼 ℹ 📁 🧾. - -👉 ℹ ⚒ 💭 👈: - -* 🧾 🆙 📅. -* 🧾 🖼 💪 🏃. -* 🌅 ⚒ 📔 🧾, 🚚 💯 💰. - -⏮️ 🇧🇿 🛠️, 📤 ✍ 👈 🏗 🕸 & ✅ 🙆 🔀, 🖖-🔫: - -
- -```console -$ python ./scripts/docs.py live - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -⚫️ 🔜 🍦 🧾 🔛 `http://127.0.0.1:8008`. - -👈 🌌, 👆 💪 ✍ 🧾/ℹ 📁 & 👀 🔀 🖖. - -#### 🏎 ✳ (📦) - -👩‍🌾 📥 🎦 👆 ❔ ⚙️ ✍ `./scripts/docs.py` ⏮️ `python` 📋 🔗. - -✋️ 👆 💪 ⚙️ 🏎 ✳, & 👆 🔜 🤚 ✍ 👆 📶 📋 ⏮️ ❎ 🛠️. - -🚥 👆 ❎ 🏎 ✳, 👆 💪 ❎ 🛠️ ⏮️: - -
- -```console -$ typer --install-completion - -zsh completion installed in /home/user/.bashrc. -Completion will take effect once you restart the terminal. -``` - -
- -### 📱 & 🩺 🎏 🕰 - -🚥 👆 🏃 🖼 ⏮️, ✅: - -
- -```console -$ uvicorn tutorial001:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -Uvicorn 🔢 🔜 ⚙️ ⛴ `8000`, 🧾 🔛 ⛴ `8008` 🏆 🚫 ⚔. - -### ✍ - -ℹ ⏮️ ✍ 📶 🌅 👍 ❗ & ⚫️ 💪 🚫 🔨 🍵 ℹ ⚪️➡️ 👪. 👶 👶 - -📥 📶 ℹ ⏮️ ✍. - -#### 💁‍♂ & 📄 - -* ✅ ⏳ ♻ 🚲 📨 👆 🇪🇸 & 🚮 📄 ✔ 🔀 ⚖️ ✔ 👫. - -!!! tip - 👆 💪 🚮 🏤 ⏮️ 🔀 🔑 ♻ 🚲 📨. - - ✅ 🩺 🔃 ❎ 🚲 📨 📄 ✔ ⚫️ ⚖️ 📨 🔀. - -* ✅ 👀 🚥 📤 1️⃣ 🛠️ ✍ 👆 🇪🇸. - -* 🚮 👁 🚲 📨 📍 📃 💬. 👈 🔜 ⚒ ⚫️ 🌅 ⏩ 🎏 📄 ⚫️. - -🇪🇸 👤 🚫 💬, 👤 🔜 ⌛ 📚 🎏 📄 ✍ ⏭ 🔗. - -* 👆 💪 ✅ 🚥 📤 ✍ 👆 🇪🇸 & 🚮 📄 👫, 👈 🔜 ℹ 👤 💭 👈 ✍ ☑ & 👤 💪 🔗 ⚫️. - -* ⚙️ 🎏 🐍 🖼 & 🕴 💬 ✍ 🩺. 👆 🚫 ✔️ 🔀 🕳 👉 👷. - -* ⚙️ 🎏 🖼, 📁 📛, & 🔗. 👆 🚫 ✔️ 🔀 🕳 ⚫️ 👷. - -* ✅ 2️⃣-🔤 📟 🇪🇸 👆 💚 💬 👆 💪 ⚙️ 🏓 📇 💾 6️⃣3️⃣9️⃣-1️⃣ 📟. - -#### ♻ 🇪🇸 - -➡️ 💬 👆 💚 💬 📃 🇪🇸 👈 ⏪ ✔️ ✍ 📃, 💖 🇪🇸. - -💼 🇪🇸, 2️⃣-🔤 📟 `es`. , 📁 🇪🇸 ✍ 🔎 `docs/es/`. - -!!! tip - 👑 ("🛂") 🇪🇸 🇪🇸, 🔎 `docs/en/`. - -🔜 🏃 🖖 💽 🩺 🇪🇸: - -
- -```console -// Use the command "live" and pass the language code as a CLI argument -$ python ./scripts/docs.py live es - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -🔜 👆 💪 🚶 http://127.0.0.1:8008 & 👀 👆 🔀 🖖. - -🚥 👆 👀 FastAPI 🩺 🕸, 👆 🔜 👀 👈 🔠 🇪🇸 ✔️ 🌐 📃. ✋️ 📃 🚫 💬 & ✔️ 📨 🔃 ❌ ✍. - -✋️ 🕐❔ 👆 🏃 ⚫️ 🌐 💖 👉, 👆 🔜 🕴 👀 📃 👈 ⏪ 💬. - -🔜 ➡️ 💬 👈 👆 💚 🚮 ✍ 📄 [⚒](features.md){.internal-link target=_blank}. - -* 📁 📁: - -``` -docs/en/docs/features.md -``` - -* 📋 ⚫️ ⚫️❔ 🎏 🗺 ✋️ 🇪🇸 👆 💚 💬, ✅: - -``` -docs/es/docs/features.md -``` - -!!! tip - 👀 👈 🕴 🔀 ➡ & 📁 📛 🇪🇸 📟, ⚪️➡️ `en` `es`. - -* 🔜 📂 ⬜ 📁 📁 🇪🇸: - -``` -docs/en/mkdocs.yml -``` - -* 🔎 🥉 🌐❔ 👈 `docs/features.md` 🔎 📁 📁. 👱 💖: - -```YAML hl_lines="8" -site_name: FastAPI -# More stuff -nav: -- FastAPI: index.md -- Languages: - - en: / - - es: /es/ -- features.md -``` - -* 📂 ⬜ 📁 📁 🇪🇸 👆 ✍, ✅: - -``` -docs/es/mkdocs.yml -``` - -* 🚮 ⚫️ 📤 ☑ 🎏 🗺 ⚫️ 🇪🇸, ✅: - -```YAML hl_lines="8" -site_name: FastAPI -# More stuff -nav: -- FastAPI: index.md -- Languages: - - en: / - - es: /es/ -- features.md -``` - -⚒ 💭 👈 🚥 📤 🎏 ⛔, 🆕 ⛔ ⏮️ 👆 ✍ ⚫️❔ 🎏 ✔ 🇪🇸 ⏬. - -🚥 👆 🚶 👆 🖥 👆 🔜 👀 👈 🔜 🩺 🎦 👆 🆕 📄. 👶 - -🔜 👆 💪 💬 ⚫️ 🌐 & 👀 ❔ ⚫️ 👀 👆 🖊 📁. - -#### 🆕 🇪🇸 - -➡️ 💬 👈 👆 💚 🚮 ✍ 🇪🇸 👈 🚫 💬, 🚫 📃. - -➡️ 💬 👆 💚 🚮 ✍ 🇭🇹, & ⚫️ 🚫 📤 🩺. - -✅ 🔗 ⚪️➡️ 🔛, 📟 "🇭🇹" `ht`. - -⏭ 🔁 🏃 ✍ 🏗 🆕 ✍ 📁: - -
- -```console -// Use the command new-lang, pass the language code as a CLI argument -$ python ./scripts/docs.py new-lang ht - -Successfully initialized: docs/ht -Updating ht -Updating en -``` - -
- -🔜 👆 💪 ✅ 👆 📟 👨‍🎨 ⏳ ✍ 📁 `docs/ht/`. - -!!! tip - ✍ 🥇 🚲 📨 ⏮️ 👉, ⚒ 🆙 📳 🆕 🇪🇸, ⏭ ❎ ✍. - - 👈 🌌 🎏 💪 ℹ ⏮️ 🎏 📃 ⏪ 👆 👷 🔛 🥇 🕐. 👶 - -▶️ ✍ 👑 📃, `docs/ht/index.md`. - -⤴️ 👆 💪 😣 ⏮️ ⏮️ 👩‍🌾, "♻ 🇪🇸". - -##### 🆕 🇪🇸 🚫 🐕‍🦺 - -🚥 🕐❔ 🏃‍♂ 🖖 💽 ✍ 👆 🤚 ❌ 🔃 🇪🇸 🚫 ➖ 🐕‍🦺, 🕳 💖: - -``` - raise TemplateNotFound(template) -jinja2.exceptions.TemplateNotFound: partials/language/xx.html -``` - -👈 ⛓ 👈 🎢 🚫 🐕‍🦺 👈 🇪🇸 (👉 💼, ⏮️ ❌ 2️⃣-🔤 📟 `xx`). - -✋️ 🚫 😟, 👆 💪 ⚒ 🎢 🇪🇸 🇪🇸 & ⤴️ 💬 🎚 🩺. - -🚥 👆 💪 👈, ✍ `mkdocs.yml` 👆 🆕 🇪🇸, ⚫️ 🔜 ✔️ 🕳 💖: - -```YAML hl_lines="5" -site_name: FastAPI -# More stuff -theme: - # More stuff - language: xx -``` - -🔀 👈 🇪🇸 ⚪️➡️ `xx` (⚪️➡️ 👆 🇪🇸 📟) `en`. - -⤴️ 👆 💪 ▶️ 🖖 💽 🔄. - -#### 🎮 🏁 - -🕐❔ 👆 ⚙️ ✍ `./scripts/docs.py` ⏮️ `live` 📋 ⚫️ 🕴 🎦 📁 & ✍ 💪 ⏮️ 🇪🇸. - -✋️ 🕐 👆 🔨, 👆 💪 💯 ⚫️ 🌐 ⚫️ 🔜 👀 💳. - -👈, 🥇 🏗 🌐 🩺: - -
- -```console -// Use the command "build-all", this will take a bit -$ python ./scripts/docs.py build-all - -Updating es -Updating en -Building docs for: en -Building docs for: es -Successfully built docs for: es -Copying en index.md to README.md -``` - -
- -👈 🏗 🌐 🩺 `./docs_build/` 🔠 🇪🇸. 👉 🔌 ❎ 🙆 📁 ⏮️ ❌ ✍, ⏮️ 🗒 💬 👈 "👉 📁 🚫 ✔️ ✍". ✋️ 👆 🚫 ✔️ 🕳 ⏮️ 👈 📁. - -⤴️ ⚫️ 🏗 🌐 👈 🔬 ⬜ 🕸 🔠 🇪🇸, 🌀 👫, & 🏗 🏁 🔢 `./site/`. - -⤴️ 👆 💪 🍦 👈 ⏮️ 📋 `serve`: - -
- -```console -// Use the command "serve" after running "build-all" -$ python ./scripts/docs.py serve - -Warning: this is a very simple server. For development, use mkdocs serve instead. -This is here only to preview a site with translations already built. -Make sure you run the build-all command first. -Serving at: http://127.0.0.1:8008 -``` - -
- -## 💯 - -📤 ✍ 👈 👆 💪 🏃 🌐 💯 🌐 📟 & 🏗 💰 📄 🕸: - -
- -```console -$ bash scripts/test-cov-html.sh -``` - -
- -👉 📋 🏗 📁 `./htmlcov/`, 🚥 👆 📂 📁 `./htmlcov/index.html` 👆 🖥, 👆 💪 🔬 🖥 🇹🇼 📟 👈 📔 💯, & 👀 🚥 📤 🙆 🇹🇼 ❌. diff --git a/docs/em/docs/deployment/concepts.md b/docs/em/docs/deployment/concepts.md index 162b68615..019703296 100644 --- a/docs/em/docs/deployment/concepts.md +++ b/docs/em/docs/deployment/concepts.md @@ -25,7 +25,7 @@ ## 💂‍♂ - 🇺🇸🔍 -[⏮️ 📃 🔃 🇺🇸🔍](./https.md){.internal-link target=_blank} 👥 🇭🇲 🔃 ❔ 🇺🇸🔍 🚚 🔐 👆 🛠️. +[⏮️ 📃 🔃 🇺🇸🔍](https.md){.internal-link target=_blank} 👥 🇭🇲 🔃 ❔ 🇺🇸🔍 🚚 🔐 👆 🛠️. 👥 👀 👈 🇺🇸🔍 🛎 🚚 🦲 **🔢** 👆 🈸 💽, **🤝 ❎ 🗳**. @@ -151,10 +151,13 @@ ✋️ 👈 💼 ⏮️ 🤙 👎 ❌ 👈 💥 🏃‍♂ **🛠️**, 👆 🔜 💚 🔢 🦲 👈 🈚 **🔁** 🛠️, 🌘 👩‍❤‍👨 🕰... -!!! tip - ...👐 🚥 🎂 🈸 **💥 ⏪** ⚫️ 🎲 🚫 ⚒ 🔑 🚧 🔁 ⚫️ ♾. ✋️ 📚 💼, 👆 🔜 🎲 👀 ⚫️ ⏮️ 🛠️, ⚖️ 🌘 ▶️️ ⏮️ 🛠️. +/// tip - ➡️ 🎯 🔛 👑 💼, 🌐❔ ⚫️ 💪 💥 🍕 🎯 💼 **🔮**, & ⚫️ ⚒ 🔑 ⏏ ⚫️. +...👐 🚥 🎂 🈸 **💥 ⏪** ⚫️ 🎲 🚫 ⚒ 🔑 🚧 🔁 ⚫️ ♾. ✋️ 📚 💼, 👆 🔜 🎲 👀 ⚫️ ⏮️ 🛠️, ⚖️ 🌘 ▶️️ ⏮️ 🛠️. + +➡️ 🎯 🔛 👑 💼, 🌐❔ ⚫️ 💪 💥 🍕 🎯 💼 **🔮**, & ⚫️ ⚒ 🔑 ⏏ ⚫️. + +/// 👆 🔜 🎲 💚 ✔️ 👜 🈚 🔁 👆 🈸 **🔢 🦲**, ↩️ 👈 ☝, 🎏 🈸 ⏮️ Uvicorn & 🐍 ⏪ 💥, 📤 🕳 🎏 📟 🎏 📱 👈 💪 🕳 🔃 ⚫️. @@ -187,7 +190,7 @@ ### 👨‍🏭 🛠️ & ⛴ -💭 ⚪️➡️ 🩺 [🔃 🇺🇸🔍](./https.md){.internal-link target=_blank} 👈 🕴 1️⃣ 🛠️ 💪 👂 🔛 1️⃣ 🌀 ⛴ & 📢 📢 💽 ❓ +💭 ⚪️➡️ 🩺 [🔃 🇺🇸🔍](https.md){.internal-link target=_blank} 👈 🕴 1️⃣ 🛠️ 💪 👂 🔛 1️⃣ 🌀 ⛴ & 📢 📢 💽 ❓ 👉 ☑. @@ -238,10 +241,13 @@ * **☁ 🐕‍🦺** 👈 🍵 👉 👆 * ☁ 🐕‍🦺 🔜 🎲 **🍵 🧬 👆**. ⚫️ 🔜 🎲 ➡️ 👆 🔬 **🛠️ 🏃**, ⚖️ **📦 🖼** ⚙️, 🙆 💼, ⚫️ 🔜 🌅 🎲 **👁 Uvicorn 🛠️**, & ☁ 🐕‍🦺 🔜 🈚 🔁 ⚫️. -!!! tip - 🚫 😟 🚥 👫 🏬 🔃 **📦**, ☁, ⚖️ Kubernetes 🚫 ⚒ 📚 🔑. +/// tip + +🚫 😟 🚥 👫 🏬 🔃 **📦**, ☁, ⚖️ Kubernetes 🚫 ⚒ 📚 🔑. + +👤 🔜 💬 👆 🌅 🔃 📦 🖼, ☁, Kubernetes, ♒️. 🔮 📃: [FastAPI 📦 - ☁](docker.md){.internal-link target=_blank}. - 👤 🔜 💬 👆 🌅 🔃 📦 🖼, ☁, Kubernetes, ♒️. 🔮 📃: [FastAPI 📦 - ☁](./docker.md){.internal-link target=_blank}. +/// ## ⏮️ 🔁 ⏭ ▶️ @@ -257,10 +263,13 @@ ↗️, 📤 💼 🌐❔ 📤 🙅‍♂ ⚠ 🏃 ⏮️ 🔁 💗 🕰, 👈 💼, ⚫️ 📚 ⏩ 🍵. -!!! tip - , ✔️ 🤯 👈 ⚓️ 🔛 👆 🖥, 💼 👆 **5️⃣📆 🚫 💪 🙆 ⏮️ 🔁** ⏭ ▶️ 👆 🈸. +/// tip - 👈 💼, 👆 🚫🔜 ✔️ 😟 🔃 🙆 👉. 🤷 +, ✔️ 🤯 👈 ⚓️ 🔛 👆 🖥, 💼 👆 **5️⃣📆 🚫 💪 🙆 ⏮️ 🔁** ⏭ ▶️ 👆 🈸. + +👈 💼, 👆 🚫🔜 ✔️ 😟 🔃 🙆 👉. 🤷 + +/// ### 🖼 ⏮️ 🔁 🎛 @@ -272,8 +281,11 @@ * 🎉 ✍ 👈 🏃 ⏮️ 🔁 & ⤴️ ▶️ 👆 🈸 * 👆 🔜 💪 🌌 ▶️/⏏ *👈* 🎉 ✍, 🔍 ❌, ♒️. -!!! tip - 👤 🔜 🤝 👆 🌅 🧱 🖼 🔨 👉 ⏮️ 📦 🔮 📃: [FastAPI 📦 - ☁](./docker.md){.internal-link target=_blank}. +/// tip + +👤 🔜 🤝 👆 🌅 🧱 🖼 🔨 👉 ⏮️ 📦 🔮 📃: [FastAPI 📦 - ☁](docker.md){.internal-link target=_blank}. + +/// ## ℹ 🛠️ diff --git a/docs/em/docs/deployment/docker.md b/docs/em/docs/deployment/docker.md index f28735ed7..2152f1a0e 100644 --- a/docs/em/docs/deployment/docker.md +++ b/docs/em/docs/deployment/docker.md @@ -4,8 +4,11 @@ ⚙️ 💾 📦 ✔️ 📚 📈 ✅ **💂‍♂**, **🔬**, **🦁**, & 🎏. -!!! tip - 🏃 & ⏪ 💭 👉 💩 ❓ 🦘 [`Dockerfile` 🔛 👶](#build-a-docker-image-for-fastapi). +/// tip + +🏃 & ⏪ 💭 👉 💩 ❓ 🦘 [`Dockerfile` 🔛 👶](#fastapi). + +///
📁 🎮 👶 @@ -108,7 +111,7 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 🌅 ⚠ 🌌 ⚫️ ✔️ 📁 `requirements.txt` ⏮️ 📦 📛 & 👫 ⏬, 1️⃣ 📍 ⏸. -👆 🔜 ↗️ ⚙️ 🎏 💭 👆 ✍ [🔃 FastAPI ⏬](./versions.md){.internal-link target=_blank} ⚒ ↔ ⏬. +👆 🔜 ↗️ ⚙️ 🎏 💭 👆 ✍ [🔃 FastAPI ⏬](versions.md){.internal-link target=_blank} ⚒ ↔ ⏬. 🖼, 👆 `requirements.txt` 💪 👀 💖: @@ -130,10 +133,13 @@ Successfully installed fastapi pydantic uvicorn -!!! info - 📤 🎏 📁 & 🧰 🔬 & ❎ 📦 🔗. +/// info + +📤 🎏 📁 & 🧰 🔬 & ❎ 📦 🔗. - 👤 🔜 🎦 👆 🖼 ⚙️ 🎶 ⏪ 📄 🔛. 👶 +👤 🔜 🎦 👆 🖼 ⚙️ 🎶 ⏪ 📄 🔛. 👶 + +/// ### ✍ **FastAPI** 📟 @@ -199,8 +205,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] `--no-cache-dir` 🎛 💬 `pip` 🚫 🖊 ⏬ 📦 🌐, 👈 🕴 🚥 `pip` 🔜 🏃 🔄 ❎ 🎏 📦, ✋️ 👈 🚫 💼 🕐❔ 👷 ⏮️ 📦. - !!! note - `--no-cache-dir` 🕴 🔗 `pip`, ⚫️ ✔️ 🕳 ⏮️ ☁ ⚖️ 📦. + /// note + + `--no-cache-dir` 🕴 🔗 `pip`, ⚫️ ✔️ 🕳 ⏮️ ☁ ⚖️ 📦. + + /// `--upgrade` 🎛 💬 `pip` ♻ 📦 🚥 👫 ⏪ ❎. @@ -222,8 +231,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] ↩️ 📋 🔜 ▶️ `/code` & 🔘 ⚫️ 📁 `./app` ⏮️ 👆 📟, **Uvicorn** 🔜 💪 👀 & **🗄** `app` ⚪️➡️ `app.main`. -!!! tip - 📄 ⚫️❔ 🔠 ⏸ 🔨 🖊 🔠 🔢 💭 📟. 👶 +/// tip + +📄 ⚫️❔ 🔠 ⏸ 🔨 🖊 🔠 🔢 💭 📟. 👶 + +/// 👆 🔜 🔜 ✔️ 📁 📊 💖: @@ -293,10 +305,13 @@ $ docker build -t myimage . -!!! tip - 👀 `.` 🔚, ⚫️ 🌓 `./`, ⚫️ 💬 ☁ 📁 ⚙️ 🏗 📦 🖼. +/// tip + +👀 `.` 🔚, ⚫️ 🌓 `./`, ⚫️ 💬 ☁ 📁 ⚙️ 🏗 📦 🖼. - 👉 💼, ⚫️ 🎏 ⏮️ 📁 (`.`). +👉 💼, ⚫️ 🎏 ⏮️ 📁 (`.`). + +/// ### ▶️ ☁ 📦 @@ -373,7 +388,7 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ## 🛠️ 🔧 -➡️ 💬 🔄 🔃 🎏 [🛠️ 🔧](./concepts.md){.internal-link target=_blank} ⚖ 📦. +➡️ 💬 🔄 🔃 🎏 [🛠️ 🔧](concepts.md){.internal-link target=_blank} ⚖ 📦. 📦 ✴️ 🧰 📉 🛠️ **🏗 & 🛠️** 🈸, ✋️ 👫 🚫 🛠️ 🎯 🎯 🍵 👉 **🛠️ 🔧**, & 📤 📚 💪 🎛. @@ -394,8 +409,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ⚫️ 💪 ➕1️⃣ 📦, 🖼 ⏮️ Traefik, 🚚 **🇺🇸🔍** & **🏧** 🛠️ **📄**. -!!! tip - Traefik ✔️ 🛠️ ⏮️ ☁, Kubernetes, & 🎏, ⚫️ 📶 ⏩ ⚒ 🆙 & 🔗 🇺🇸🔍 👆 📦 ⏮️ ⚫️. +/// tip + +Traefik ✔️ 🛠️ ⏮️ ☁, Kubernetes, & 🎏, ⚫️ 📶 ⏩ ⚒ 🆙 & 🔗 🇺🇸🔍 👆 📦 ⏮️ ⚫️. + +/// 👐, 🇺🇸🔍 💪 🍵 ☁ 🐕‍🦺 1️⃣ 👫 🐕‍🦺 (⏪ 🏃 🈸 📦). @@ -415,7 +433,7 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] 1️⃣ 📚 📎 📦 🧾 ⚙️ 💖 Kubernetes 🛎 ✔️ 🛠️ 🌌 🚚 **🧬 📦** ⏪ 🔗 **📐 ⚖** 📨 📨. 🌐 **🌑 🎚**. -📚 💼, 👆 🔜 🎲 💚 🏗 **☁ 🖼 ⚪️➡️ 🖌** [🔬 🔛](#dockerfile), ❎ 👆 🔗, & 🏃‍♂ **👁 Uvicorn 🛠️** ↩️ 🏃‍♂ 🕳 💖 🐁 ⏮️ Uvicorn 👨‍🏭. +📚 💼, 👆 🔜 🎲 💚 🏗 **☁ 🖼 ⚪️➡️ 🖌** [🔬 🔛](#_6), ❎ 👆 🔗, & 🏃‍♂ **👁 Uvicorn 🛠️** ↩️ 🏃‍♂ 🕳 💖 🐁 ⏮️ Uvicorn 👨‍🏭. ### 📐 ⚙ @@ -423,8 +441,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] 👉 🦲 🔜 ✊ **📐** 📨 & 📎 👈 👪 👨‍🏭 (🤞) **⚖** 🌌, ⚫️ 🛎 🤙 **📐 ⚙**. -!!! tip - 🎏 **🤝 ❎ 🗳** 🦲 ⚙️ 🇺🇸🔍 🔜 🎲 **📐 ⚙**. +/// tip + +🎏 **🤝 ❎ 🗳** 🦲 ⚙️ 🇺🇸🔍 🔜 🎲 **📐 ⚙**. + +/// & 🕐❔ 👷 ⏮️ 📦, 🎏 ⚙️ 👆 ⚙️ ▶️ & 🛠️ 👫 🔜 ⏪ ✔️ 🔗 🧰 📶 **🕸 📻** (✅ 🇺🇸🔍 📨) ⚪️➡️ 👈 **📐 ⚙** (👈 💪 **🤝 ❎ 🗳**) 📦(Ⓜ) ⏮️ 👆 📱. @@ -450,7 +471,7 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ↗️, 📤 **🎁 💼** 🌐❔ 👆 💪 💚 ✔️ **📦** ⏮️ **🐁 🛠️ 👨‍💼** ▶️ 📚 **Uvicorn 👨‍🏭 🛠️** 🔘. -📚 💼, 👆 💪 ⚙️ **🛂 ☁ 🖼** 👈 🔌 **🐁** 🛠️ 👨‍💼 🏃‍♂ 💗 **Uvicorn 👨‍🏭 🛠️**, & 🔢 ⚒ 🔆 🔢 👨‍🏭 ⚓️ 🔛 ⏮️ 💽 🐚 🔁. 👤 🔜 💬 👆 🌅 🔃 ⚫️ 🔛 [🛂 ☁ 🖼 ⏮️ 🐁 - Uvicorn](#official-docker-image-with-gunicorn-uvicorn). +📚 💼, 👆 💪 ⚙️ **🛂 ☁ 🖼** 👈 🔌 **🐁** 🛠️ 👨‍💼 🏃‍♂ 💗 **Uvicorn 👨‍🏭 🛠️**, & 🔢 ⚒ 🔆 🔢 👨‍🏭 ⚓️ 🔛 ⏮️ 💽 🐚 🔁. 👤 🔜 💬 👆 🌅 🔃 ⚫️ 🔛 [🛂 ☁ 🖼 ⏮️ 🐁 - Uvicorn](#-uvicorn). 📥 🖼 🕐❔ 👈 💪 ⚒ 🔑: @@ -503,8 +524,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] 🚥 👆 ✔️ **💗 📦**, 🎲 🔠 1️⃣ 🏃 **👁 🛠️** (🖼, **Kubernetes** 🌑), ⤴️ 👆 🔜 🎲 💚 ✔️ **🎏 📦** 🔨 👷 **⏮️ 📶** 👁 📦, 🏃 👁 🛠️, **⏭** 🏃 🔁 👨‍🏭 📦. -!!! info - 🚥 👆 ⚙️ Kubernetes, 👉 🔜 🎲 🕑 📦. +/// info + +🚥 👆 ⚙️ Kubernetes, 👉 🔜 🎲 🕑 📦. + +/// 🚥 👆 ⚙️ 💼 📤 🙅‍♂ ⚠ 🏃‍♂ 👈 ⏮️ 📶 **💗 🕰 🔗** (🖼 🚥 👆 🚫 🏃 💽 🛠️, ✋️ ✅ 🚥 💽 🔜), ⤴️ 👆 💪 🚮 👫 🔠 📦 ▶️️ ⏭ ▶️ 👑 🛠️. @@ -514,14 +538,17 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ## 🛂 ☁ 🖼 ⏮️ 🐁 - Uvicorn -📤 🛂 ☁ 🖼 👈 🔌 🐁 🏃‍♂ ⏮️ Uvicorn 👨‍🏭, ℹ ⏮️ 📃: [💽 👨‍🏭 - 🐁 ⏮️ Uvicorn](./server-workers.md){.internal-link target=_blank}. +📤 🛂 ☁ 🖼 👈 🔌 🐁 🏃‍♂ ⏮️ Uvicorn 👨‍🏭, ℹ ⏮️ 📃: [💽 👨‍🏭 - 🐁 ⏮️ Uvicorn](server-workers.md){.internal-link target=_blank}. -👉 🖼 🔜 ⚠ ✴️ ⚠ 🔬 🔛: [📦 ⏮️ 💗 🛠️ & 🎁 💼](#containers-with-multiple-processes-and-special-cases). +👉 🖼 🔜 ⚠ ✴️ ⚠ 🔬 🔛: [📦 ⏮️ 💗 🛠️ & 🎁 💼](#_18). * tiangolo/uvicorn-🐁-fastapi. -!!! warning - 📤 ↕ 🤞 👈 👆 **🚫** 💪 👉 🧢 🖼 ⚖️ 🙆 🎏 🎏 1️⃣, & 🔜 👻 📆 🏗 🖼 ⚪️➡️ 🖌 [🔬 🔛: 🏗 ☁ 🖼 FastAPI](#build-a-docker-image-for-fastapi). +/// warning + +📤 ↕ 🤞 👈 👆 **🚫** 💪 👉 🧢 🖼 ⚖️ 🙆 🎏 🎏 1️⃣, & 🔜 👻 📆 🏗 🖼 ⚪️➡️ 🖌 [🔬 🔛: 🏗 ☁ 🖼 FastAPI](#fastapi). + +/// 👉 🖼 ✔️ **🚘-📳** 🛠️ 🔌 ⚒ **🔢 👨‍🏭 🛠️** ⚓️ 🔛 💽 🐚 💪. @@ -529,8 +556,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ⚫️ 🐕‍🦺 🏃 **⏮️ 🔁 ⏭ ▶️** ⏮️ ✍. -!!! tip - 👀 🌐 📳 & 🎛, 🚶 ☁ 🖼 📃: Tiangolo/uvicorn-🐁-fastapi. +/// tip + +👀 🌐 📳 & 🎛, 🚶 ☁ 🖼 📃: Tiangolo/uvicorn-🐁-fastapi. + +/// ### 🔢 🛠️ 🔛 🛂 ☁ 🖼 @@ -574,9 +604,9 @@ COPY ./app /app/app ### 🕐❔ ⚙️ -👆 🔜 🎲 **🚫** ⚙️ 👉 🛂 🧢 🖼 (⚖️ 🙆 🎏 🎏 1️⃣) 🚥 👆 ⚙️ **Kubernetes** (⚖️ 🎏) & 👆 ⏪ ⚒ **🧬** 🌑 🎚, ⏮️ 💗 **📦**. 📚 💼, 👆 👍 📆 **🏗 🖼 ⚪️➡️ 🖌** 🔬 🔛: [🏗 ☁ 🖼 FastAPI](#build-a-docker-image-for-fastapi). +👆 🔜 🎲 **🚫** ⚙️ 👉 🛂 🧢 🖼 (⚖️ 🙆 🎏 🎏 1️⃣) 🚥 👆 ⚙️ **Kubernetes** (⚖️ 🎏) & 👆 ⏪ ⚒ **🧬** 🌑 🎚, ⏮️ 💗 **📦**. 📚 💼, 👆 👍 📆 **🏗 🖼 ⚪️➡️ 🖌** 🔬 🔛: [🏗 ☁ 🖼 FastAPI](#fastapi). -👉 🖼 🔜 ⚠ ✴️ 🎁 💼 🔬 🔛 [📦 ⏮️ 💗 🛠️ & 🎁 💼](#containers-with-multiple-processes-and-special-cases). 🖼, 🚥 👆 🈸 **🙅 🥃** 👈 ⚒ 🔢 🔢 🛠️ ⚓️ 🔛 💽 👷 👍, 👆 🚫 💚 😥 ⏮️ ❎ 🛠️ 🧬 🌑 🎚, & 👆 🚫 🏃 🌅 🌘 1️⃣ 📦 ⏮️ 👆 📱. ⚖️ 🚥 👆 🛠️ ⏮️ **☁ ✍**, 🏃 🔛 👁 💽, ♒️. +👉 🖼 🔜 ⚠ ✴️ 🎁 💼 🔬 🔛 [📦 ⏮️ 💗 🛠️ & 🎁 💼](#_18). 🖼, 🚥 👆 🈸 **🙅 🥃** 👈 ⚒ 🔢 🔢 🛠️ ⚓️ 🔛 💽 👷 👍, 👆 🚫 💚 😥 ⏮️ ❎ 🛠️ 🧬 🌑 🎚, & 👆 🚫 🏃 🌅 🌘 1️⃣ 📦 ⏮️ 👆 📱. ⚖️ 🚥 👆 🛠️ ⏮️ **☁ ✍**, 🏃 🔛 👁 💽, ♒️. ## 🛠️ 📦 🖼 @@ -657,8 +687,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 1️⃣1️⃣. 🏃 `uvicorn` 📋, 💬 ⚫️ ⚙️ `app` 🎚 🗄 ⚪️➡️ `app.main`. -!!! tip - 🖊 💭 🔢 👀 ⚫️❔ 🔠 ⏸ 🔨. +/// tip + +🖊 💭 🔢 👀 ⚫️❔ 🔠 ⏸ 🔨. + +/// **☁ ▶️** 🍕 `Dockerfile` 👈 👷 **🍕 📦 🖼** 👈 🕴 ⚙️ 🏗 📁 ⚙️ ⏪. diff --git a/docs/em/docs/deployment/https.md b/docs/em/docs/deployment/https.md index 3feb3a2c2..31cf99001 100644 --- a/docs/em/docs/deployment/https.md +++ b/docs/em/docs/deployment/https.md @@ -4,8 +4,11 @@ ✋️ ⚫️ 🌌 🌖 🏗 🌘 👈. -!!! tip - 🚥 👆 🏃 ⚖️ 🚫 💅, 😣 ⏮️ ⏭ 📄 🔁 🔁 👩‍🌾 ⚒ 🌐 🆙 ⏮️ 🎏 ⚒. +/// tip + +🚥 👆 🏃 ⚖️ 🚫 💅, 😣 ⏮️ ⏭ 📄 🔁 🔁 👩‍🌾 ⚒ 🌐 🆙 ⏮️ 🎏 ⚒. + +/// **💡 🔰 🇺🇸🔍**, ⚪️➡️ 🏬 🤔, ✅ https://howhttps.works/. @@ -68,8 +71,11 @@ 👆 🔜 🎲 👉 🕐, 🥇 🕰, 🕐❔ ⚒ 🌐 🆙. -!!! tip - 👉 🆔 📛 🍕 🌌 ⏭ 🇺🇸🔍, ✋️ 🌐 🪀 🔛 🆔 & 📢 📢, ⚫️ 💸 💬 ⚫️ 📥. +/// tip + +👉 🆔 📛 🍕 🌌 ⏭ 🇺🇸🔍, ✋️ 🌐 🪀 🔛 🆔 & 📢 📢, ⚫️ 💸 💬 ⚫️ 📥. + +/// ### 🏓 @@ -115,8 +121,11 @@ & 👈 ⚫️❔ **🇺🇸🔍** , ⚫️ ✅ **🇺🇸🔍** 🔘 **🔐 🤝 🔗** ↩️ 😁 (💽) 🕸 🔗. -!!! tip - 👀 👈 🔐 📻 🔨 **🕸 🎚**, 🚫 🇺🇸🔍 🎚. +/// tip + +👀 👈 🔐 📻 🔨 **🕸 🎚**, 🚫 🇺🇸🔍 🎚. + +/// ### 🇺🇸🔍 📨 diff --git a/docs/em/docs/deployment/manually.md b/docs/em/docs/deployment/manually.md index f27b423e2..8ebe00c7c 100644 --- a/docs/em/docs/deployment/manually.md +++ b/docs/em/docs/deployment/manually.md @@ -5,7 +5,7 @@ 📤 3️⃣ 👑 🎛: * Uvicorn: ↕ 🎭 🔫 💽. -* Hypercorn: 🔫 💽 🔗 ⏮️ 🇺🇸🔍/2️⃣ & 🎻 👪 🎏 ⚒. +* Hypercorn: 🔫 💽 🔗 ⏮️ 🇺🇸🔍/2️⃣ & 🎻 👪 🎏 ⚒. * 👸: 🔫 💽 🏗 ✳ 📻. ## 💽 🎰 & 💽 📋 @@ -22,75 +22,89 @@ 👆 💪 ❎ 🔫 🔗 💽 ⏮️: -=== "Uvicorn" +//// tab | Uvicorn - * Uvicorn, 🌩-⏩ 🔫 💽, 🏗 🔛 uvloop & httptool. +* Uvicorn, 🌩-⏩ 🔫 💽, 🏗 🔛 uvloop & httptool. -
+
+ +```console +$ pip install "uvicorn[standard]" - ```console - $ pip install "uvicorn[standard]" +---> 100% +``` + +
- ---> 100% - ``` +/// tip -
+❎ `standard`, Uvicorn 🔜 ❎ & ⚙️ 👍 ➕ 🔗. - !!! tip - ❎ `standard`, Uvicorn 🔜 ❎ & ⚙️ 👍 ➕ 🔗. +👈 ✅ `uvloop`, ↕-🎭 💧-♻ `asyncio`, 👈 🚚 🦏 🛠️ 🎭 📈. - 👈 ✅ `uvloop`, ↕-🎭 💧-♻ `asyncio`, 👈 🚚 🦏 🛠️ 🎭 📈. +/// -=== "Hypercorn" +//// - * Hypercorn, 🔫 💽 🔗 ⏮️ 🇺🇸🔍/2️⃣. +//// tab | Hypercorn -
+* Hypercorn, 🔫 💽 🔗 ⏮️ 🇺🇸🔍/2️⃣. - ```console - $ pip install hypercorn +
+ +```console +$ pip install hypercorn + +---> 100% +``` - ---> 100% - ``` +
-
+...⚖️ 🙆 🎏 🔫 💽. - ...⚖️ 🙆 🎏 🔫 💽. +//// ## 🏃 💽 📋 👆 💪 ⤴️ 🏃 👆 🈸 🎏 🌌 👆 ✔️ ⌛ 🔰, ✋️ 🍵 `--reload` 🎛, ✅: -=== "Uvicorn" +//// tab | Uvicorn -
+
- ```console - $ uvicorn main:app --host 0.0.0.0 --port 80 +```console +$ uvicorn main:app --host 0.0.0.0 --port 80 - INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) - ``` +INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) +``` -
+
+ +//// -=== "Hypercorn" +//// tab | Hypercorn -
+
+ +```console +$ hypercorn main:app --bind 0.0.0.0:80 + +Running on 0.0.0.0:8080 over http (CTRL + C to quit) +``` + +
- ```console - $ hypercorn main:app --bind 0.0.0.0:80 +//// - Running on 0.0.0.0:8080 over http (CTRL + C to quit) - ``` +/// warning -
+💭 ❎ `--reload` 🎛 🚥 👆 ⚙️ ⚫️. -!!! warning - 💭 ❎ `--reload` 🎛 🚥 👆 ⚙️ ⚫️. + `--reload` 🎛 🍴 🌅 🌅 ℹ, 🌅 ⚠, ♒️. - `--reload` 🎛 🍴 🌅 🌅 ℹ, 🌅 ⚠, ♒️. +⚫️ ℹ 📚 ⏮️ **🛠️**, ✋️ 👆 **🚫🔜 🚫** ⚙️ ⚫️ **🏭**. - ⚫️ ℹ 📚 ⏮️ **🛠️**, ✋️ 👆 **🚫🔜 🚫** ⚙️ ⚫️ **🏭**. +/// ## Hypercorn ⏮️ 🎻 diff --git a/docs/em/docs/deployment/server-workers.md b/docs/em/docs/deployment/server-workers.md index b7e58c4f4..eb29b2376 100644 --- a/docs/em/docs/deployment/server-workers.md +++ b/docs/em/docs/deployment/server-workers.md @@ -13,14 +13,17 @@ 🕐❔ 🛠️ 🈸 👆 🔜 🎲 💚 ✔️ **🧬 🛠️** ✊ 📈 **💗 🐚** & 💪 🍵 🌅 📨. -👆 👀 ⏮️ 📃 🔃 [🛠️ 🔧](./concepts.md){.internal-link target=_blank}, 📤 💗 🎛 👆 💪 ⚙️. +👆 👀 ⏮️ 📃 🔃 [🛠️ 🔧](concepts.md){.internal-link target=_blank}, 📤 💗 🎛 👆 💪 ⚙️. 📥 👤 🔜 🎦 👆 ❔ ⚙️ **🐁** ⏮️ **Uvicorn 👨‍🏭 🛠️**. -!!! info - 🚥 👆 ⚙️ 📦, 🖼 ⏮️ ☁ ⚖️ Kubernetes, 👤 🔜 💬 👆 🌅 🔃 👈 ⏭ 📃: [FastAPI 📦 - ☁](./docker.md){.internal-link target=_blank}. +/// info - 🎯, 🕐❔ 🏃 🔛 **Kubernetes** 👆 🔜 🎲 **🚫** 💚 ⚙️ 🐁 & ↩️ 🏃 **👁 Uvicorn 🛠️ 📍 📦**, ✋️ 👤 🔜 💬 👆 🔃 ⚫️ ⏪ 👈 📃. +🚥 👆 ⚙️ 📦, 🖼 ⏮️ ☁ ⚖️ Kubernetes, 👤 🔜 💬 👆 🌅 🔃 👈 ⏭ 📃: [FastAPI 📦 - ☁](docker.md){.internal-link target=_blank}. + +🎯, 🕐❔ 🏃 🔛 **Kubernetes** 👆 🔜 🎲 **🚫** 💚 ⚙️ 🐁 & ↩️ 🏃 **👁 Uvicorn 🛠️ 📍 📦**, ✋️ 👤 🔜 💬 👆 🔃 ⚫️ ⏪ 👈 📃. + +/// ## 🐁 ⏮️ Uvicorn 👨‍🏭 @@ -163,7 +166,7 @@ $ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4 ## 📦 & ☁ -⏭ 📃 🔃 [FastAPI 📦 - ☁](./docker.md){.internal-link target=_blank} 👤 🔜 💬 🎛 👆 💪 ⚙️ 🍵 🎏 **🛠️ 🔧**. +⏭ 📃 🔃 [FastAPI 📦 - ☁](docker.md){.internal-link target=_blank} 👤 🔜 💬 🎛 👆 💪 ⚙️ 🍵 🎏 **🛠️ 🔧**. 👤 🔜 🎦 👆 **🛂 ☁ 🖼** 👈 🔌 **🐁 ⏮️ Uvicorn 👨‍🏭** & 🔢 📳 👈 💪 ⚠ 🙅 💼. diff --git a/docs/em/docs/deployment/versions.md b/docs/em/docs/deployment/versions.md index 8bfdf9731..6c9b8f9bb 100644 --- a/docs/em/docs/deployment/versions.md +++ b/docs/em/docs/deployment/versions.md @@ -42,8 +42,11 @@ fastapi>=0.45.0,<0.46.0 FastAPI ⏩ 🏛 👈 🙆 "🐛" ⏬ 🔀 🐛 🔧 & 🚫-💔 🔀. -!!! tip - "🐛" 🏁 🔢, 🖼, `0.2.3`, 🐛 ⏬ `3`. +/// tip + +"🐛" 🏁 🔢, 🖼, `0.2.3`, 🐛 ⏬ `3`. + +/// , 👆 🔜 💪 📌 ⏬ 💖: @@ -53,8 +56,11 @@ fastapi>=0.45.0,<0.46.0 💔 🔀 & 🆕 ⚒ 🚮 "🇺🇲" ⏬. -!!! tip - "🇺🇲" 🔢 🖕, 🖼, `0.2.3`, 🇺🇲 ⏬ `2`. +/// tip + +"🇺🇲" 🔢 🖕, 🖼, `0.2.3`, 🇺🇲 ⏬ `2`. + +/// ## ♻ FastAPI ⏬ diff --git a/docs/em/docs/external-links.md b/docs/em/docs/external-links.md deleted file mode 100644 index 5ba668bfa..000000000 --- a/docs/em/docs/external-links.md +++ /dev/null @@ -1,35 +0,0 @@ -# 🔢 🔗 & 📄 - -**FastAPI** ✔️ 👑 👪 🕧 💗. - -📤 📚 🏤, 📄, 🧰, & 🏗, 🔗 **FastAPI**. - -📥 ❌ 📇 👫. - -!!! tip - 🚥 👆 ✔️ 📄, 🏗, 🧰, ⚖️ 🕳 🔗 **FastAPI** 👈 🚫 📇 📥, ✍ 🚲 📨 ❎ ⚫️. - -## 📄 - -{% for section_name, section_content in external_links.items() %} - -## {{ section_name }} - -{% for lang_name, lang_content in section_content.items() %} - -### {{ lang_name }} - -{% for item in lang_content %} - -* {{ item.title }} by {{ item.author }}. - -{% endfor %} -{% endfor %} -{% endfor %} - -## 🏗 - -⏪ 📂 🏗 ⏮️ ❔ `fastapi`: - -
-
diff --git a/docs/em/docs/fastapi-people.md b/docs/em/docs/fastapi-people.md deleted file mode 100644 index dc94d80da..000000000 --- a/docs/em/docs/fastapi-people.md +++ /dev/null @@ -1,178 +0,0 @@ -# FastAPI 👫👫 - -FastAPI ✔️ 🎆 👪 👈 🙋 👫👫 ⚪️➡️ 🌐 🖥. - -## 👼 - 🐛 - -🙋 ❗ 👶 - -👉 👤: - -{% if people %} -
-{% for user in people.maintainers %} - -
@{{ user.login }}
❔: {{ user.answers }}
🚲 📨: {{ user.prs }}
-{% endfor %} - -
-{% endif %} - -👤 👼 & 🐛 **FastAPI**. 👆 💪 ✍ 🌅 🔃 👈 [ℹ FastAPI - 🤚 ℹ - 🔗 ⏮️ 📕](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. - -...✋️ 📥 👤 💚 🎦 👆 👪. - ---- - -**FastAPI** 📨 📚 🐕‍🦺 ⚪️➡️ 👪. & 👤 💚 🎦 👫 💰. - -👫 👫👫 👈: - -* [ℹ 🎏 ⏮️ ❔ 📂](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. -* [✍ 🚲 📨](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. -* 📄 🚲 📨, [✴️ ⚠ ✍](contributing.md#translations){.internal-link target=_blank}. - -👏 👫. 👶 👶 - -## 🌅 🦁 👩‍💻 🏁 🗓️ - -👫 👩‍💻 👈 ✔️ [🤝 🎏 🏆 ⏮️ ❔ 📂](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} ⏮️ 🏁 🗓️. 👶 - -{% if people %} -
-{% for user in people.last_month_active %} - -
@{{ user.login }}
❔ 📨: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## 🕴 - -📥 **FastAPI 🕴**. 👶 - -👫 👩‍💻 👈 ✔️ [ℹ 🎏 🏆 ⏮️ ❔ 📂](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} 🔘 *🌐 🕰*. - -👫 ✔️ 🎦 🕴 🤝 📚 🎏. 👶 - -{% if people %} -
-{% for user in people.experts %} - -
@{{ user.login }}
❔ 📨: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## 🔝 👨‍🔬 - -📥 **🔝 👨‍🔬**. 👶 - -👉 👩‍💻 ✔️ [✍ 🏆 🚲 📨](help-fastapi.md#create-a-pull-request){.internal-link target=_blank} 👈 ✔️ *🔗*. - -👫 ✔️ 📉 ℹ 📟, 🧾, ✍, ♒️. 👶 - -{% if people %} -
-{% for user in people.top_contributors %} - -
@{{ user.login }}
🚲 📨: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -📤 📚 🎏 👨‍🔬 (🌅 🌘 💯), 👆 💪 👀 👫 🌐 FastAPI 📂 👨‍🔬 📃. 👶 - -## 🔝 👨‍🔬 - -👫 👩‍💻 **🔝 👨‍🔬**. 👶 👶 - -### 📄 ✍ - -👤 🕴 💬 👩‍❤‍👨 🇪🇸 (& 🚫 📶 👍 👶). , 👨‍🔬 🕐 👈 ✔️ [**🏋️ ✔ ✍**](contributing.md#translations){.internal-link target=_blank} 🧾. 🍵 👫, 📤 🚫🔜 🧾 📚 🎏 🇪🇸. - ---- - -**🔝 👨‍🔬** 👶 👶 ✔️ 📄 🏆 🚲 📨 ⚪️➡️ 🎏, 🚚 🔆 📟, 🧾, & ✴️, **✍**. - -{% if people %} -
-{% for user in people.top_reviewers %} - -
@{{ user.login }}
📄: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## 💰 - -👫 **💰**. 👶 - -👫 🔗 👇 👷 ⏮️ **FastAPI** (& 🎏), ✴️ 🔘 📂 💰. - -{% if sponsors %} - -{% if sponsors.gold %} - -### 🌟 💰 - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### 🥇1st 💰 - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### 🥈2nd 💰 - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -{% endif %} - -### 🎯 💰 - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
- -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
- -{% endfor %} -{% endif %} - -## 🔃 📊 - 📡 ℹ - -👑 🎯 👉 📃 🎦 🎯 👪 ℹ 🎏. - -✴️ ✅ 🎯 👈 🛎 🌘 ⭐, & 📚 💼 🌅 😩, 💖 🤝 🎏 ⏮️ ❔ & ⚖ 🚲 📨 ⏮️ ✍. - -💽 ⚖ 🔠 🗓️, 👆 💪 ✍ ℹ 📟 📥. - -📥 👤 🎦 💰 ⚪️➡️ 💰. - -👤 🏦 ▶️️ ℹ 📊, 📄, ⚡, ♒️ (💼 🤷). diff --git a/docs/em/docs/features.md b/docs/em/docs/features.md index 19193da07..13cafa72f 100644 --- a/docs/em/docs/features.md +++ b/docs/em/docs/features.md @@ -63,10 +63,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` ⛓: +/// info - 🚶‍♀️ 🔑 & 💲 `second_user_data` #️⃣ 🔗 🔑-💲 ❌, 🌓: `User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` ⛓: + +🚶‍♀️ 🔑 & 💲 `second_user_data` #️⃣ 🔗 🔑-💲 ❌, 🌓: `User(id=4, name="Mary", joined="2018-11-30")` + +/// ### 👨‍🎨 🐕‍🦺 @@ -174,7 +177,7 @@ FastAPI 🔌 📶 ⏩ ⚙️, ✋️ 📶 🏋️ 💾/🧶/🧠**: * ↩️ Pydantic 📊 📊 👐 🎓 👆 🔬; 🚘-🛠️, 🧽, ✍ & 👆 🤔 🔜 🌐 👷 ☑ ⏮️ 👆 ✔ 💽. -* **⏩**: - * 📇 Pydantic ⏩ 🌘 🌐 🎏 💯 🗃. * ✔ **🏗 📊**: * ⚙️ 🔗 Pydantic 🏷, 🐍 `typing`'Ⓜ `List` & `Dict`, ♒️. * & 💳 ✔ 🏗 💽 🔗 🎯 & 💪 🔬, ✅ & 📄 🎻 🔗. diff --git a/docs/em/docs/help-fastapi.md b/docs/em/docs/help-fastapi.md index b998ade42..099485222 100644 --- a/docs/em/docs/help-fastapi.md +++ b/docs/em/docs/help-fastapi.md @@ -12,7 +12,7 @@ ## 👱📔 📰 -👆 💪 👱📔 (🐌) [**FastAPI & 👨‍👧‍👦** 📰](/newsletter/){.internal-link target=_blank} 🚧 ℹ 🔃: +👆 💪 👱📔 (🐌) [**FastAPI & 👨‍👧‍👦** 📰](newsletter.md){.internal-link target=_blank} 🚧 ℹ 🔃: * 📰 🔃 FastAPI & 👨‍👧‍👦 👶 * 🦮 👶 @@ -26,13 +26,13 @@ ## ✴ **FastAPI** 📂 -👆 💪 "✴" FastAPI 📂 (🖊 ✴ 🔼 🔝 ▶️️): https://github.com/tiangolo/fastapi. 👶 👶 +👆 💪 "✴" FastAPI 📂 (🖊 ✴ 🔼 🔝 ▶️️): https://github.com/fastapi/fastapi. 👶 👶 ❎ ✴, 🎏 👩‍💻 🔜 💪 🔎 ⚫️ 🌅 💪 & 👀 👈 ⚫️ ✔️ ⏪ ⚠ 🎏. ## ⌚ 📂 🗃 🚀 -👆 💪 "⌚" FastAPI 📂 (🖊 "⌚" 🔼 🔝 ▶️️): https://github.com/tiangolo/fastapi. 👶 +👆 💪 "⌚" FastAPI 📂 (🖊 "⌚" 🔼 🔝 ▶️️): https://github.com/fastapi/fastapi. 👶 📤 👆 💪 🖊 "🚀 🕴". @@ -59,7 +59,7 @@ ## 👱📔 🔃 **FastAPI** -👱📔 🔃 **FastAPI** & ➡️ 👤 & 🎏 💭 ⚫️❔ 👆 💖 ⚫️. 👶 +👱📔 🔃 **FastAPI** & ➡️ 👤 & 🎏 💭 ⚫️❔ 👆 💖 ⚫️. 👶 👤 💌 👂 🔃 ❔ **FastAPI** 💆‍♂ ⚙️, ⚫️❔ 👆 ✔️ 💖 ⚫️, ❔ 🏗/🏢 👆 ⚙️ ⚫️, ♒️. @@ -73,12 +73,12 @@ 👆 💪 🔄 & ℹ 🎏 ⏮️ 👫 ❔: -* 📂 💬 -* 📂 ❔ +* 📂 💬 +* 📂 ❔ 📚 💼 👆 5️⃣📆 ⏪ 💭 ❔ 📚 ❔. 👶 -🚥 👆 🤝 📚 👫👫 ⏮️ 👫 ❔, 👆 🔜 ▶️️ 🛂 [FastAPI 🕴](fastapi-people.md#experts){.internal-link target=_blank}. 👶 +🚥 👆 🤝 📚 👫👫 ⏮️ 👫 ❔, 👆 🔜 ▶️️ 🛂 [FastAPI 🕴](fastapi-people.md#_2){.internal-link target=_blank}. 👶 💭, 🏆 ⚠ ☝: 🔄 😇. 👫👫 👟 ⏮️ 👫 😩 & 📚 💼 🚫 💭 🏆 🌌, ✋️ 🔄 🏆 👆 💪 😇. 👶 @@ -125,7 +125,7 @@ ## ⌚ 📂 🗃 -👆 💪 "⌚" FastAPI 📂 (🖊 "⌚" 🔼 🔝 ▶️️): https://github.com/tiangolo/fastapi. 👶 +👆 💪 "⌚" FastAPI 📂 (🖊 "⌚" 🔼 🔝 ▶️️): https://github.com/fastapi/fastapi. 👶 🚥 👆 🖊 "👀" ↩️ "🚀 🕴" 👆 🔜 📨 📨 🕐❔ 👱 ✍ 🆕 ❔ ⚖️ ❔. 👆 💪 ✔ 👈 👆 🕴 💚 🚨 🔃 🆕 ❔, ⚖️ 💬, ⚖️ 🎸, ♒️. @@ -133,7 +133,7 @@ ## 💭 ❔ -👆 💪 ✍ 🆕 ❔ 📂 🗃, 🖼: +👆 💪 ✍ 🆕 ❔ 📂 🗃, 🖼: * 💭 **❔** ⚖️ 💭 🔃 **⚠**. * 🤔 🆕 **⚒**. @@ -170,12 +170,15 @@ * ⤴️ **🏤** 💬 👈 👆 👈, 👈 ❔ 👤 🔜 💭 👆 🤙 ✅ ⚫️. -!!! info - 👐, 👤 💪 🚫 🎯 💙 🎸 👈 ✔️ 📚 ✔. +/// info - 📚 🕰 ⚫️ ✔️ 🔨 👈 📤 🎸 ⏮️ 3️⃣, 5️⃣ ⚖️ 🌅 ✔, 🎲 ↩️ 📛 😌, ✋️ 🕐❔ 👤 ✅ 🎸, 👫 🤙 💔, ✔️ 🐛, ⚖️ 🚫 ❎ ⚠ 👫 🛄 ❎. 👶 +👐, 👤 💪 🚫 🎯 💙 🎸 👈 ✔️ 📚 ✔. - , ⚫️ 🤙 ⚠ 👈 👆 🤙 ✍ & 🏃 📟, & ➡️ 👤 💭 🏤 👈 👆. 👶 +📚 🕰 ⚫️ ✔️ 🔨 👈 📤 🎸 ⏮️ 3️⃣, 5️⃣ ⚖️ 🌅 ✔, 🎲 ↩️ 📛 😌, ✋️ 🕐❔ 👤 ✅ 🎸, 👫 🤙 💔, ✔️ 🐛, ⚖️ 🚫 ❎ ⚠ 👫 🛄 ❎. 👶 + +, ⚫️ 🤙 ⚠ 👈 👆 🤙 ✍ & 🏃 📟, & ➡️ 👤 💭 🏤 👈 👆. 👶 + +/// * 🚥 🇵🇷 💪 📉 🌌, 👆 💪 💭 👈, ✋️ 📤 🙅‍♂ 💪 💁‍♂️ 😟, 📤 5️⃣📆 📚 🤔 ☝ 🎑 (& 👤 🔜 ✔️ 👇 👍 👍 👶), ⚫️ 👻 🚥 👆 💪 🎯 🔛 ⚛ 👜. @@ -196,9 +199,9 @@ 👆 💪 [📉](contributing.md){.internal-link target=_blank} ℹ 📟 ⏮️ 🚲 📨, 🖼: * 🔧 🤭 👆 🔎 🔛 🧾. -* 💰 📄, 📹, ⚖️ 📻 👆 ✍ ⚖️ 🔎 🔃 FastAPI ✍ 👉 📁. +* 💰 📄, 📹, ⚖️ 📻 👆 ✍ ⚖️ 🔎 🔃 FastAPI ✍ 👉 📁. * ⚒ 💭 👆 🚮 👆 🔗 ▶️ 🔗 📄. -* ℹ [💬 🧾](contributing.md#translations){.internal-link target=_blank} 👆 🇪🇸. +* ℹ [💬 🧾](contributing.md#_9){.internal-link target=_blank} 👆 🇪🇸. * 👆 💪 ℹ 📄 ✍ ✍ 🎏. * 🛠️ 🆕 🧾 📄. * 🔧 ♻ ❔/🐛. @@ -215,8 +218,8 @@ 👑 📋 👈 👆 💪 ▶️️ 🔜: -* [ℹ 🎏 ⏮️ ❔ 📂](#help-others-with-questions-in-github){.internal-link target=_blank} (👀 📄 🔛). -* [📄 🚲 📨](#review-pull-requests){.internal-link target=_blank} (👀 📄 🔛). +* [ℹ 🎏 ⏮️ ❔ 📂](#i){.internal-link target=_blank} (👀 📄 🔛). +* [📄 🚲 📨](#i){.internal-link target=_blank} (👀 📄 🔛). 👈 2️⃣ 📋 ⚫️❔ **🍴 🕰 🏆**. 👈 👑 👷 🏆 FastAPI. @@ -226,10 +229,13 @@ 🛑 👶 😧 💬 💽 👶 & 🤙 👅 ⏮️ 🎏 FastAPI 👪. -!!! tip - ❔, 💭 👫 📂 💬, 📤 🌅 👍 🤞 👆 🔜 📨 ℹ [FastAPI 🕴](fastapi-people.md#experts){.internal-link target=_blank}. +/// tip + +❔, 💭 👫 📂 💬, 📤 🌅 👍 🤞 👆 🔜 📨 ℹ [FastAPI 🕴](fastapi-people.md#_2){.internal-link target=_blank}. + +⚙️ 💬 🕴 🎏 🏢 💬. - ⚙️ 💬 🕴 🎏 🏢 💬. +/// ### 🚫 ⚙️ 💬 ❔ @@ -237,7 +243,7 @@ 📂, 📄 🔜 🦮 👆 ✍ ▶️️ ❔ 👈 👆 💪 🌖 💪 🤚 👍 ❔, ⚖️ ❎ ⚠ 👆 ⏭ 💬. & 📂 👤 💪 ⚒ 💭 👤 🕧 ❔ 🌐, 🚥 ⚫️ ✊ 🕰. 👤 💪 🚫 🤙 👈 ⏮️ 💬 ⚙️. 👶 -💬 💬 ⚙️ 🚫 💪 📇 📂, ❔ & ❔ 5️⃣📆 🤚 💸 💬. & 🕴 🕐 📂 💯 ▶️️ [FastAPI 🕴](fastapi-people.md#experts){.internal-link target=_blank}, 👆 🔜 🌅 🎲 📨 🌅 🙋 📂. +💬 💬 ⚙️ 🚫 💪 📇 📂, ❔ & ❔ 5️⃣📆 🤚 💸 💬. & 🕴 🕐 📂 💯 ▶️️ [FastAPI 🕴](fastapi-people.md#_2){.internal-link target=_blank}, 👆 🔜 🌅 🎲 📨 🌅 🙋 📂. 🔛 🎏 🚄, 📤 💯 👩‍💻 💬 ⚙️, 📤 ↕ 🤞 👆 🔜 🔎 👱 💬 📤, 🌖 🌐 🕰. 👶 diff --git a/docs/em/docs/history-design-future.md b/docs/em/docs/history-design-future.md index 7e39972de..2238bec2b 100644 --- a/docs/em/docs/history-design-future.md +++ b/docs/em/docs/history-design-future.md @@ -1,6 +1,6 @@ # 📖, 🔧 & 🔮 -🕰 🏁, **FastAPI** 👩‍💻 💭: +🕰 🏁, **FastAPI** 👩‍💻 💭: > ⚫️❔ 📖 👉 🏗 ❓ ⚫️ 😑 ✔️ 👟 ⚪️➡️ 🕳 👌 👩‍❤‍👨 🗓️ [...] @@ -54,7 +54,7 @@ ## 📄 -⏮️ 🔬 📚 🎛, 👤 💭 👈 👤 🔜 ⚙️ **Pydantic** 🚮 📈. +⏮️ 🔬 📚 🎛, 👤 💭 👈 👤 🔜 ⚙️ **Pydantic** 🚮 📈. ⤴️ 👤 📉 ⚫️, ⚒ ⚫️ 🍕 🛠️ ⏮️ 🎻 🔗, 🐕‍🦺 🎏 🌌 🔬 ⚛ 📄, & 📉 👨‍🎨 🐕‍🦺 (🆎 ✅, ✍) ⚓️ 🔛 💯 📚 👨‍🎨. diff --git a/docs/em/docs/how-to/conditional-openapi.md b/docs/em/docs/how-to/conditional-openapi.md index a17ba4eec..e47ea0c35 100644 --- a/docs/em/docs/how-to/conditional-openapi.md +++ b/docs/em/docs/how-to/conditional-openapi.md @@ -29,9 +29,7 @@ 🖼: -```Python hl_lines="6 11" -{!../../../docs_src/conditional_openapi/tutorial001.py!} -``` +{* ../../docs_src/conditional_openapi/tutorial001.py hl[6,11] *} 📥 👥 📣 ⚒ `openapi_url` ⏮️ 🎏 🔢 `"/openapi.json"`. diff --git a/docs/em/docs/how-to/custom-request-and-route.md b/docs/em/docs/how-to/custom-request-and-route.md index d6fafa2ea..8974e7d95 100644 --- a/docs/em/docs/how-to/custom-request-and-route.md +++ b/docs/em/docs/how-to/custom-request-and-route.md @@ -6,10 +6,13 @@ 🖼, 🚥 👆 💚 ✍ ⚖️ 🔬 📨 💪 ⏭ ⚫️ 🛠️ 👆 🈸. -!!! danger - 👉 "🏧" ⚒. +/// danger - 🚥 👆 ▶️ ⏮️ **FastAPI** 👆 💪 💚 🚶 👉 📄. +👉 "🏧" ⚒. + +🚥 👆 ▶️ ⏮️ **FastAPI** 👆 💪 💚 🚶 👉 📄. + +/// ## ⚙️ 💼 @@ -27,8 +30,11 @@ ### ✍ 🛃 `GzipRequest` 🎓 -!!! tip - 👉 🧸 🖼 🎦 ❔ ⚫️ 👷, 🚥 👆 💪 🗜 🐕‍🦺, 👆 💪 ⚙️ 🚚 [`GzipMiddleware`](./middleware.md#gzipmiddleware){.internal-link target=_blank}. +/// tip + +👉 🧸 🖼 🎦 ❔ ⚫️ 👷, 🚥 👆 💪 🗜 🐕‍🦺, 👆 💪 ⚙️ 🚚 [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank}. + +/// 🥇, 👥 ✍ `GzipRequest` 🎓, ❔ 🔜 📁 `Request.body()` 👩‍🔬 🗜 💪 🔍 ☑ 🎚. @@ -36,9 +42,7 @@ 👈 🌌, 🎏 🛣 🎓 💪 🍵 🗜 🗜 ⚖️ 🗜 📨. -```Python hl_lines="8-15" -{!../../../docs_src/custom_request_and_route/tutorial001.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial001.py hl[8:15] *} ### ✍ 🛃 `GzipRoute` 🎓 @@ -50,20 +54,21 @@ 📥 👥 ⚙️ ⚫️ ✍ `GzipRequest` ⚪️➡️ ⏮️ 📨. -```Python hl_lines="18-26" -{!../../../docs_src/custom_request_and_route/tutorial001.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial001.py hl[18:26] *} -!!! note "📡 ℹ" - `Request` ✔️ `request.scope` 🔢, 👈 🐍 `dict` ⚗ 🗃 🔗 📨. +/// note | 📡 ℹ - `Request` ✔️ `request.receive`, 👈 🔢 "📨" 💪 📨. +`Request` ✔️ `request.scope` 🔢, 👈 🐍 `dict` ⚗ 🗃 🔗 📨. - `scope` `dict` & `receive` 🔢 👯‍♂️ 🍕 🔫 🔧. + `Request` ✔️ `request.receive`, 👈 🔢 "📨" 💪 📨. - & 👈 2️⃣ 👜, `scope` & `receive`, ⚫️❔ 💪 ✍ 🆕 `Request` 👐. + `scope` `dict` & `receive` 🔢 👯‍♂️ 🍕 🔫 🔧. - 💡 🌅 🔃 `Request` ✅ 💃 🩺 🔃 📨. + & 👈 2️⃣ 👜, `scope` & `receive`, ⚫️❔ 💪 ✍ 🆕 `Request` 👐. + +💡 🌅 🔃 `Request` ✅ 💃 🩺 🔃 📨. + +/// 🕴 👜 🔢 📨 `GzipRequest.get_route_handler` 🔨 🎏 🗜 `Request` `GzipRequest`. @@ -75,35 +80,30 @@ ## 🔐 📨 💪 ⚠ 🐕‍🦺 -!!! tip - ❎ 👉 🎏 ⚠, ⚫️ 🎲 📚 ⏩ ⚙️ `body` 🛃 🐕‍🦺 `RequestValidationError` ([🚚 ❌](../tutorial/handling-errors.md#use-the-requestvalidationerror-body){.internal-link target=_blank}). +/// tip + +❎ 👉 🎏 ⚠, ⚫️ 🎲 📚 ⏩ ⚙️ `body` 🛃 🐕‍🦺 `RequestValidationError` ([🚚 ❌](../tutorial/handling-errors.md#requestvalidationerror){.internal-link target=_blank}). + +✋️ 👉 🖼 ☑ & ⚫️ 🎦 ❔ 🔗 ⏮️ 🔗 🦲. - ✋️ 👉 🖼 ☑ & ⚫️ 🎦 ❔ 🔗 ⏮️ 🔗 🦲. +/// 👥 💪 ⚙️ 👉 🎏 🎯 🔐 📨 💪 ⚠ 🐕‍🦺. 🌐 👥 💪 🍵 📨 🔘 `try`/`except` 🍫: -```Python hl_lines="13 15" -{!../../../docs_src/custom_request_and_route/tutorial002.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial002.py hl[13,15] *} 🚥 ⚠ 📉, `Request` 👐 🔜 ↔, 👥 💪 ✍ & ⚒ ⚙️ 📨 💪 🕐❔ 🚚 ❌: -```Python hl_lines="16-18" -{!../../../docs_src/custom_request_and_route/tutorial002.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial002.py hl[16:18] *} ## 🛃 `APIRoute` 🎓 📻 👆 💪 ⚒ `route_class` 🔢 `APIRouter`: -```Python hl_lines="26" -{!../../../docs_src/custom_request_and_route/tutorial003.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial003.py hl[26] *} 👉 🖼, *➡ 🛠️* 🔽 `router` 🔜 ⚙️ 🛃 `TimedRoute` 🎓, & 🔜 ✔️ ➕ `X-Response-Time` 🎚 📨 ⏮️ 🕰 ⚫️ ✊ 🏗 📨: -```Python hl_lines="13-20" -{!../../../docs_src/custom_request_and_route/tutorial003.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial003.py hl[13:20] *} diff --git a/docs/em/docs/how-to/extending-openapi.md b/docs/em/docs/how-to/extending-openapi.md index 6b3bc0075..c3e6c7f66 100644 --- a/docs/em/docs/how-to/extending-openapi.md +++ b/docs/em/docs/how-to/extending-openapi.md @@ -1,11 +1,14 @@ # ↔ 🗄 -!!! warning - 👉 👍 🏧 ⚒. 👆 🎲 💪 🚶 ⚫️. +/// warning - 🚥 👆 📄 🔰 - 👩‍💻 🦮, 👆 💪 🎲 🚶 👉 📄. +👉 👍 🏧 ⚒. 👆 🎲 💪 🚶 ⚫️. - 🚥 👆 ⏪ 💭 👈 👆 💪 🔀 🏗 🗄 🔗, 😣 👂. +🚥 👆 📄 🔰 - 👩‍💻 🦮, 👆 💪 🎲 🚶 👉 📄. + +🚥 👆 ⏪ 💭 👈 👆 💪 🔀 🏗 🗄 🔗, 😣 👂. + +/// 📤 💼 🌐❔ 👆 💪 💪 🔀 🏗 🗄 🔗. @@ -43,25 +46,19 @@ 🥇, ✍ 🌐 👆 **FastAPI** 🈸 🛎: -```Python hl_lines="1 4 7-9" -{!../../../docs_src/extending_openapi/tutorial001.py!} -``` +{* ../../docs_src/extending_openapi/tutorial001.py hl[1,4,7:9] *} ### 🏗 🗄 🔗 ⤴️, ⚙️ 🎏 🚙 🔢 🏗 🗄 🔗, 🔘 `custom_openapi()` 🔢: -```Python hl_lines="2 15-20" -{!../../../docs_src/extending_openapi/tutorial001.py!} -``` +{* ../../docs_src/extending_openapi/tutorial001.py hl[2,15:20] *} ### 🔀 🗄 🔗 🔜 👆 💪 🚮 📄 ↔, ❎ 🛃 `x-logo` `info` "🎚" 🗄 🔗: -```Python hl_lines="21-23" -{!../../../docs_src/extending_openapi/tutorial001.py!} -``` +{* ../../docs_src/extending_openapi/tutorial001.py hl[21:23] *} ### 💾 🗄 🔗 @@ -71,17 +68,13 @@ ⚫️ 🔜 🏗 🕴 🕐, & ⤴️ 🎏 💾 🔗 🔜 ⚙️ ⏭ 📨. -```Python hl_lines="13-14 24-25" -{!../../../docs_src/extending_openapi/tutorial001.py!} -``` +{* ../../docs_src/extending_openapi/tutorial001.py hl[13:14,24:25] *} ### 🔐 👩‍🔬 🔜 👆 💪 ❎ `.openapi()` 👩‍🔬 ⏮️ 👆 🆕 🔢. -```Python hl_lines="28" -{!../../../docs_src/extending_openapi/tutorial001.py!} -``` +{* ../../docs_src/extending_openapi/tutorial001.py hl[28] *} ### ✅ ⚫️ diff --git a/docs/em/docs/how-to/graphql.md b/docs/em/docs/how-to/graphql.md index 8509643ce..083e9ebd2 100644 --- a/docs/em/docs/how-to/graphql.md +++ b/docs/em/docs/how-to/graphql.md @@ -4,12 +4,15 @@ 👆 💪 🌀 😐 FastAPI *➡ 🛠️* ⏮️ 🕹 🔛 🎏 🈸. -!!! tip - **🕹** ❎ 📶 🎯 ⚙️ 💼. +/// tip - ⚫️ ✔️ **📈** & **⚠** 🕐❔ 🔬 ⚠ **🕸 🔗**. +**🕹** ❎ 📶 🎯 ⚙️ 💼. - ⚒ 💭 👆 🔬 🚥 **💰** 👆 ⚙️ 💼 ⚖ **👐**. 👶 +⚫️ ✔️ **📈** & **⚠** 🕐❔ 🔬 ⚠ **🕸 🔗**. + +⚒ 💭 👆 🔬 🚥 **💰** 👆 ⚙️ 💼 ⚖ **👐**. 👶 + +/// ## 🕹 🗃 @@ -18,7 +21,7 @@ * 🍓 👶 * ⏮️ 🩺 FastAPI * 👸 - * ⏮️ 🩺 💃 (👈 ✔ FastAPI) + * ⏮️ 🩺 FastAPI * 🍟 * ⏮️ 🍟 🔫 🚚 🔫 🛠️ * @@ -32,9 +35,7 @@ 📥 🤪 🎮 ❔ 👆 💪 🛠️ 🍓 ⏮️ FastAPI: -```Python hl_lines="3 22 25-26" -{!../../../docs_src/graphql/tutorial001.py!} -``` +{* ../../docs_src/graphql/tutorial001.py hl[3,22,25:26] *} 👆 💪 💡 🌅 🔃 🍓 🍓 🧾. @@ -46,8 +47,11 @@ ⚫️ 😢 ⚪️➡️ 💃, ✋️ 🚥 👆 ✔️ 📟 👈 ⚙️ ⚫️, 👆 💪 💪 **↔** 💃-Graphene3️⃣, 👈 📔 🎏 ⚙️ 💼 & ✔️ **🌖 🌓 🔢**. -!!! tip - 🚥 👆 💪 🕹, 👤 🔜 👍 👆 ✅ 👅 🍓, ⚫️ ⚓️ 🔛 🆎 ✍ ↩️ 🛃 🎓 & 🆎. +/// tip + +🚥 👆 💪 🕹, 👤 🔜 👍 👆 ✅ 👅 🍓, ⚫️ ⚓️ 🔛 🆎 ✍ ↩️ 🛃 🎓 & 🆎. + +/// ## 💡 🌅 diff --git a/docs/em/docs/how-to/sql-databases-peewee.md b/docs/em/docs/how-to/sql-databases-peewee.md deleted file mode 100644 index 62619fc2c..000000000 --- a/docs/em/docs/how-to/sql-databases-peewee.md +++ /dev/null @@ -1,529 +0,0 @@ -# 🗄 (🔗) 💽 ⏮️ 🏒 - -!!! warning - 🚥 👆 ▶️, 🔰 [🗄 (🔗) 💽](../tutorial/sql-databases.md){.internal-link target=_blank} 👈 ⚙️ 🇸🇲 🔜 🥃. - - 💭 🆓 🚶 👉. - -🚥 👆 ▶️ 🏗 ⚪️➡️ 🖌, 👆 🎲 👻 📆 ⏮️ 🇸🇲 🐜 ([🗄 (🔗) 💽](../tutorial/sql-databases.md){.internal-link target=_blank}), ⚖️ 🙆 🎏 🔁 🐜. - -🚥 👆 ⏪ ✔️ 📟 🧢 👈 ⚙️ 🏒 🐜, 👆 💪 ✅ 📥 ❔ ⚙️ ⚫️ ⏮️ **FastAPI**. - -!!! warning "🐍 3️⃣.7️⃣ ➕ ✔" - 👆 🔜 💪 🐍 3️⃣.7️⃣ ⚖️ 🔛 🔒 ⚙️ 🏒 ⏮️ FastAPI. - -## 🏒 🔁 - -🏒 🚫 🔧 🔁 🛠️, ⚖️ ⏮️ 👫 🤯. - -🏒 ✔️ 🏋️ 🔑 🔃 🚮 🔢 & 🔃 ❔ ⚫️ 🔜 ⚙️. - -🚥 👆 🛠️ 🈸 ⏮️ 🗝 🚫-🔁 🛠️, & 💪 👷 ⏮️ 🌐 🚮 🔢, **⚫️ 💪 👑 🧰**. - -✋️ 🚥 👆 💪 🔀 🔢, 🐕‍🦺 🌖 🌘 1️⃣ 🔁 💽, 👷 ⏮️ 🔁 🛠️ (💖 FastAPI), ♒️, 👆 🔜 💪 🚮 🏗 ➕ 📟 🔐 👈 🔢. - -👐, ⚫️ 💪 ⚫️, & 📥 👆 🔜 👀 ⚫️❔ ⚫️❔ 📟 👆 ✔️ 🚮 💪 ⚙️ 🏒 ⏮️ FastAPI. - -!!! note "📡 ℹ" - 👆 💪 ✍ 🌅 🔃 🏒 🧍 🔃 🔁 🐍 🩺, , 🇵🇷. - -## 🎏 📱 - -👥 🔜 ✍ 🎏 🈸 🇸🇲 🔰 ([🗄 (🔗) 💽](../tutorial/sql-databases.md){.internal-link target=_blank}). - -🌅 📟 🤙 🎏. - -, 👥 🔜 🎯 🕴 🔛 🔺. - -## 📁 📊 - -➡️ 💬 👆 ✔️ 📁 📛 `my_super_project` 👈 🔌 🎧-📁 🤙 `sql_app` ⏮️ 📊 💖 👉: - -``` -. -└── sql_app - ├── __init__.py - ├── crud.py - ├── database.py - ├── main.py - └── schemas.py -``` - -👉 🌖 🎏 📊 👥 ✔️ 🇸🇲 🔰. - -🔜 ➡️ 👀 ⚫️❔ 🔠 📁/🕹 🔨. - -## ✍ 🏒 🍕 - -➡️ 🔗 📁 `sql_app/database.py`. - -### 🐩 🏒 📟 - -➡️ 🥇 ✅ 🌐 😐 🏒 📟, ✍ 🏒 💽: - -```Python hl_lines="3 5 22" -{!../../../docs_src/sql_databases_peewee/sql_app/database.py!} -``` - -!!! tip - ✔️ 🤯 👈 🚥 👆 💚 ⚙️ 🎏 💽, 💖 ✳, 👆 🚫 🚫 🔀 🎻. 👆 🔜 💪 ⚙️ 🎏 🏒 💽 🎓. - -#### 🗒 - -❌: - -```Python -check_same_thread=False -``` - -🌓 1️⃣ 🇸🇲 🔰: - -```Python -connect_args={"check_same_thread": False} -``` - -...⚫️ 💪 🕴 `SQLite`. - -!!! info "📡 ℹ" - - ⚫️❔ 🎏 📡 ℹ [🗄 (🔗) 💽](../tutorial/sql-databases.md#note){.internal-link target=_blank} ✔. - -### ⚒ 🏒 🔁-🔗 `PeeweeConnectionState` - -👑 ❔ ⏮️ 🏒 & FastAPI 👈 🏒 ⚓️ 🙇 🔛 🐍 `threading.local`, & ⚫️ 🚫 ✔️ 🎯 🌌 🔐 ⚫️ ⚖️ ➡️ 👆 🍵 🔗/🎉 🔗 (🔨 🇸🇲 🔰). - -& `threading.local` 🚫 🔗 ⏮️ 🆕 🔁 ⚒ 🏛 🐍. - -!!! note "📡 ℹ" - `threading.local` ⚙️ ✔️ "🎱" 🔢 👈 ✔️ 🎏 💲 🔠 🧵. - - 👉 ⚠ 🗝 🛠️ 🏗 ✔️ 1️⃣ 👁 🧵 📍 📨, 🙅‍♂ 🌖, 🙅‍♂ 🌘. - - ⚙️ 👉, 🔠 📨 🔜 ✔️ 🚮 👍 💽 🔗/🎉, ❔ ☑ 🏁 🥅. - - ✋️ FastAPI, ⚙️ 🆕 🔁 ⚒, 💪 🍵 🌅 🌘 1️⃣ 📨 🔛 🎏 🧵. & 🎏 🕰, 👁 📨, ⚫️ 💪 🏃 💗 👜 🎏 🧵 (🧵), ⚓️ 🔛 🚥 👆 ⚙️ `async def` ⚖️ 😐 `def`. 👉 ⚫️❔ 🤝 🌐 🎭 📈 FastAPI. - -✋️ 🐍 3️⃣.7️⃣ & 🔛 🚚 🌖 🏧 🎛 `threading.local`, 👈 💪 ⚙️ 🥉 🌐❔ `threading.local` 🔜 ⚙️, ✋️ 🔗 ⏮️ 🆕 🔁 ⚒. - -👥 🔜 ⚙️ 👈. ⚫️ 🤙 `contextvars`. - -👥 🔜 🔐 🔗 🍕 🏒 👈 ⚙️ `threading.local` & ❎ 👫 ⏮️ `contextvars`, ⏮️ 🔗 ℹ. - -👉 5️⃣📆 😑 🍖 🏗 (& ⚫️ 🤙), 👆 🚫 🤙 💪 🍕 🤔 ❔ ⚫️ 👷 ⚙️ ⚫️. - -👥 🔜 ✍ `PeeweeConnectionState`: - -```Python hl_lines="10-19" -{!../../../docs_src/sql_databases_peewee/sql_app/database.py!} -``` - -👉 🎓 😖 ⚪️➡️ 🎁 🔗 🎓 ⚙️ 🏒. - -⚫️ ✔️ 🌐 ⚛ ⚒ 🏒 ⚙️ `contextvars` ↩️ `threading.local`. - -`contextvars` 👷 🍖 🎏 🌘 `threading.local`. ✋️ 🎂 🏒 🔗 📟 🤔 👈 👉 🎓 👷 ⏮️ `threading.local`. - -, 👥 💪 ➕ 🎱 ⚒ ⚫️ 👷 🚥 ⚫️ ⚙️ `threading.local`. `__init__`, `__setattr__`, & `__getattr__` 🛠️ 🌐 ✔ 🎱 👉 ⚙️ 🏒 🍵 🤔 👈 ⚫️ 🔜 🔗 ⏮️ FastAPI. - -!!! tip - 👉 🔜 ⚒ 🏒 🎭 ☑ 🕐❔ ⚙️ ⏮️ FastAPI. 🚫 🎲 📂 ⚖️ 📪 🔗 👈 ➖ ⚙️, 🏗 ❌, ♒️. - - ✋️ ⚫️ 🚫 🤝 🏒 🔁 💎-🏋️. 👆 🔜 ⚙️ 😐 `def` 🔢 & 🚫 `async def`. - -### ⚙️ 🛃 `PeeweeConnectionState` 🎓 - -🔜, 📁 `._state` 🔗 🔢 🏒 💽 `db` 🎚 ⚙️ 🆕 `PeeweeConnectionState`: - -```Python hl_lines="24" -{!../../../docs_src/sql_databases_peewee/sql_app/database.py!} -``` - -!!! tip - ⚒ 💭 👆 📁 `db._state` *⏮️* 🏗 `db`. - -!!! tip - 👆 🔜 🎏 🙆 🎏 🏒 💽, 🔌 `PostgresqlDatabase`, `MySQLDatabase`, ♒️. - -## ✍ 💽 🏷 - -➡️ 🔜 👀 📁 `sql_app/models.py`. - -### ✍ 🏒 🏷 👆 💽 - -🔜 ✍ 🏒 🏷 (🎓) `User` & `Item`. - -👉 🎏 👆 🔜 🚥 👆 ⏩ 🏒 🔰 & ℹ 🏷 ✔️ 🎏 💽 🇸🇲 🔰. - -!!! tip - 🏒 ⚙️ ⚖ "**🏷**" 🔗 👉 🎓 & 👐 👈 🔗 ⏮️ 💽. - - ✋️ Pydantic ⚙️ ⚖ "**🏷**" 🔗 🕳 🎏, 💽 🔬, 🛠️, & 🧾 🎓 & 👐. - -🗄 `db` ⚪️➡️ `database` (📁 `database.py` ⚪️➡️ 🔛) & ⚙️ ⚫️ 📥. - -```Python hl_lines="3 6-12 15-21" -{!../../../docs_src/sql_databases_peewee/sql_app/models.py!} -``` - -!!! tip - 🏒 ✍ 📚 🎱 🔢. - - ⚫️ 🔜 🔁 🚮 `id` 🔢 🔢 👑 🔑. - - ⚫️ 🔜 ⚒ 📛 🏓 ⚓️ 🔛 🎓 📛. - - `Item`, ⚫️ 🔜 ✍ 🔢 `owner_id` ⏮️ 🔢 🆔 `User`. ✋️ 👥 🚫 📣 ⚫️ 🙆. - -## ✍ Pydantic 🏷 - -🔜 ➡️ ✅ 📁 `sql_app/schemas.py`. - -!!! tip - ❎ 😨 🖖 🏒 *🏷* & Pydantic *🏷*, 👥 🔜 ✔️ 📁 `models.py` ⏮️ 🏒 🏷, & 📁 `schemas.py` ⏮️ Pydantic 🏷. - - 👫 Pydantic 🏷 🔬 🌅 ⚖️ 🌘 "🔗" (☑ 📊 💠). - - 👉 🔜 ℹ 👥 ❎ 😨 ⏪ ⚙️ 👯‍♂️. - -### ✍ Pydantic *🏷* / 🔗 - -✍ 🌐 🎏 Pydantic 🏷 🇸🇲 🔰: - -```Python hl_lines="16-18 21-22 25-30 34-35 38-39 42-48" -{!../../../docs_src/sql_databases_peewee/sql_app/schemas.py!} -``` - -!!! tip - 📥 👥 🏗 🏷 ⏮️ `id`. - - 👥 🚫 🎯 ✔ `id` 🔢 🏒 🏷, ✋️ 🏒 🚮 1️⃣ 🔁. - - 👥 ❎ 🎱 `owner_id` 🔢 `Item`. - -### ✍ `PeeweeGetterDict` Pydantic *🏷* / 🔗 - -🕐❔ 👆 🔐 💛 🏒 🎚, 💖 `some_user.items`, 🏒 🚫 🚚 `list` `Item`. - -⚫️ 🚚 🎁 🛃 🎚 🎓 `ModelSelect`. - -⚫️ 💪 ✍ `list` 🚮 🏬 ⏮️ `list(some_user.items)`. - -✋️ 🎚 ⚫️ 🚫 `list`. & ⚫️ 🚫 ☑ 🐍 🚂. ↩️ 👉, Pydantic 🚫 💭 🔢 ❔ 🗜 ⚫️ `list` Pydantic *🏷* / 🔗. - -✋️ ⏮️ ⏬ Pydantic ✔ 🚚 🛃 🎓 👈 😖 ⚪️➡️ `pydantic.utils.GetterDict`, 🚚 🛠️ ⚙️ 🕐❔ ⚙️ `orm_mode = True` 🗃 💲 🐜 🏷 🔢. - -👥 🔜 ✍ 🛃 `PeeweeGetterDict` 🎓 & ⚙️ ⚫️ 🌐 🎏 Pydantic *🏷* / 🔗 👈 ⚙️ `orm_mode`: - -```Python hl_lines="3 8-13 31 49" -{!../../../docs_src/sql_databases_peewee/sql_app/schemas.py!} -``` - -📥 👥 ✅ 🚥 🔢 👈 ➖ 🔐 (✅ `.items` `some_user.items`) 👐 `peewee.ModelSelect`. - -& 🚥 👈 💼, 📨 `list` ⏮️ ⚫️. - -& ⤴️ 👥 ⚙️ ⚫️ Pydantic *🏷* / 🔗 👈 ⚙️ `orm_mode = True`, ⏮️ 📳 🔢 `getter_dict = PeeweeGetterDict`. - -!!! tip - 👥 🕴 💪 ✍ 1️⃣ `PeeweeGetterDict` 🎓, & 👥 💪 ⚙️ ⚫️ 🌐 Pydantic *🏷* / 🔗. - -## 💩 🇨🇻 - -🔜 ➡️ 👀 📁 `sql_app/crud.py`. - -### ✍ 🌐 💩 🇨🇻 - -✍ 🌐 🎏 💩 🇨🇻 🇸🇲 🔰, 🌐 📟 📶 🎏: - -```Python hl_lines="1 4-5 8-9 12-13 16-20 23-24 27-30" -{!../../../docs_src/sql_databases_peewee/sql_app/crud.py!} -``` - -📤 🔺 ⏮️ 📟 🇸🇲 🔰. - -👥 🚫 🚶‍♀️ `db` 🔢 🤭. ↩️ 👥 ⚙️ 🏷 🔗. 👉 ↩️ `db` 🎚 🌐 🎚, 👈 🔌 🌐 🔗 ⚛. 👈 ⚫️❔ 👥 ✔️ 🌐 `contextvars` ℹ 🔛. - -🆖, 🕐❔ 🛬 📚 🎚, 💖 `get_users`, 👥 🔗 🤙 `list`, 💖: - -```Python -list(models.User.select()) -``` - -👉 🎏 🤔 👈 👥 ✔️ ✍ 🛃 `PeeweeGetterDict`. ✋️ 🛬 🕳 👈 ⏪ `list` ↩️ `peewee.ModelSelect` `response_model` *➡ 🛠️* ⏮️ `List[models.User]` (👈 👥 🔜 👀 ⏪) 🔜 👷 ☑. - -## 👑 **FastAPI** 📱 - -& 🔜 📁 `sql_app/main.py` ➡️ 🛠️ & ⚙️ 🌐 🎏 🍕 👥 ✍ ⏭. - -### ✍ 💽 🏓 - -📶 🙃 🌌 ✍ 💽 🏓: - -```Python hl_lines="9-11" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -### ✍ 🔗 - -✍ 🔗 👈 🔜 🔗 💽 ▶️️ ▶️ 📨 & 🔌 ⚫️ 🔚: - -```Python hl_lines="23-29" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -📥 👥 ✔️ 🛁 `yield` ↩️ 👥 🤙 🚫 ⚙️ 💽 🎚 🔗. - -⚫️ 🔗 💽 & ♻ 🔗 💽 🔗 🔢 👈 🔬 🔠 📨 (⚙️ `contextvars` 🎱 ⚪️➡️ 🔛). - -↩️ 💽 🔗 ⚠ 👤/🅾 🚧, 👉 🔗 ✍ ⏮️ 😐 `def` 🔢. - -& ⤴️, 🔠 *➡ 🛠️ 🔢* 👈 💪 🔐 💽 👥 🚮 ⚫️ 🔗. - -✋️ 👥 🚫 ⚙️ 💲 👐 👉 🔗 (⚫️ 🤙 🚫 🤝 🙆 💲, ⚫️ ✔️ 🛁 `yield`). , 👥 🚫 🚮 ⚫️ *➡ 🛠️ 🔢* ✋️ *➡ 🛠️ 👨‍🎨* `dependencies` 🔢: - -```Python hl_lines="32 40 47 59 65 72" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -### 🔑 🔢 🎧-🔗 - -🌐 `contextvars` 🍕 👷, 👥 💪 ⚒ 💭 👥 ✔️ 🔬 💲 `ContextVar` 🔠 📨 👈 ⚙️ 💽, & 👈 💲 🔜 ⚙️ 💽 🇵🇸 (🔗, 💵, ♒️) 🎂 📨. - -👈, 👥 💪 ✍ ➕1️⃣ `async` 🔗 `reset_db_state()` 👈 ⚙️ 🎧-🔗 `get_db()`. ⚫️ 🔜 ⚒ 💲 🔑 🔢 (⏮️ 🔢 `dict`) 👈 🔜 ⚙️ 💽 🇵🇸 🎂 📨. & ⤴️ 🔗 `get_db()` 🔜 🏪 ⚫️ 💽 🇵🇸 (🔗, 💵, ♒️). - -```Python hl_lines="18-20" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -**⏭ 📨**, 👥 🔜 ⏲ 👈 🔑 🔢 🔄 `async` 🔗 `reset_db_state()` & ⤴️ ✍ 🆕 🔗 `get_db()` 🔗, 👈 🆕 📨 🔜 ✔️ 🚮 👍 💽 🇵🇸 (🔗, 💵, ♒️). - -!!! tip - FastAPI 🔁 🛠️, 1️⃣ 📨 💪 ▶️ ➖ 🛠️, & ⏭ 🏁, ➕1️⃣ 📨 💪 📨 & ▶️ 🏭 👍, & ⚫️ 🌐 💪 🛠️ 🎏 🧵. - - ✋️ 🔑 🔢 🤔 👫 🔁 ⚒,, 🏒 💽 🇵🇸 ⚒ `async` 🔗 `reset_db_state()` 🔜 🚧 🚮 👍 💽 🎂 🎂 📨. - - & 🎏 🕰, 🎏 🛠️ 📨 🔜 ✔️ 🚮 👍 💽 🇵🇸 👈 🔜 🔬 🎂 📨. - -#### 🏒 🗳 - -🚥 👆 ⚙️ 🏒 🗳, ☑ 💽 `db.obj`. - -, 👆 🔜 ⏲ ⚫️ ⏮️: - -```Python hl_lines="3-4" -async def reset_db_state(): - database.db.obj._state._state.set(db_state_default.copy()) - database.db.obj._state.reset() -``` - -### ✍ 👆 **FastAPI** *➡ 🛠️* - -🔜, 😒, 📥 🐩 **FastAPI** *➡ 🛠️* 📟. - -```Python hl_lines="32-37 40-43 46-53 56-62 65-68 71-79" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -### 🔃 `def` 🆚 `async def` - -🎏 ⏮️ 🇸🇲, 👥 🚫 🔨 🕳 💖: - -```Python -user = await models.User.select().first() -``` - -...✋️ ↩️ 👥 ⚙️: - -```Python -user = models.User.select().first() -``` - -, 🔄, 👥 🔜 📣 *➡ 🛠️ 🔢* & 🔗 🍵 `async def`, ⏮️ 😐 `def`,: - -```Python hl_lines="2" -# Something goes here -def read_users(skip: int = 0, limit: int = 100): - # Something goes here -``` - -## 🔬 🏒 ⏮️ 🔁 - -👉 🖼 🔌 ➕ *➡ 🛠️* 👈 🔬 📏 🏭 📨 ⏮️ `time.sleep(sleep_time)`. - -⚫️ 🔜 ✔️ 💽 🔗 📂 ▶️ & 🔜 ⌛ 🥈 ⏭ 🙇 🔙. & 🔠 🆕 📨 🔜 ⌛ 🕐 🥈 🌘. - -👉 🔜 💪 ➡️ 👆 💯 👈 👆 📱 ⏮️ 🏒 & FastAPI 🎭 ☑ ⏮️ 🌐 💩 🔃 🧵. - -🚥 👆 💚 ✅ ❔ 🏒 🔜 💔 👆 📱 🚥 ⚙️ 🍵 🛠️, 🚶 `sql_app/database.py` 📁 & 🏤 ⏸: - -```Python -# db._state = PeeweeConnectionState() -``` - -& 📁 `sql_app/main.py` 📁, 🏤 💪 `async` 🔗 `reset_db_state()` & ❎ ⚫️ ⏮️ `pass`: - -```Python -async def reset_db_state(): -# database.db._state._state.set(db_state_default.copy()) -# database.db._state.reset() - pass -``` - -⤴️ 🏃 👆 📱 ⏮️ Uvicorn: - -
- -```console -$ uvicorn sql_app.main:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -📂 👆 🖥 http://127.0.0.1:8000/docs & ✍ 👩‍❤‍👨 👩‍💻. - -⤴️ 📂 1️⃣0️⃣ 📑 http://127.0.0.1:8000/docs#/default/read_🐌_👩‍💻_slowusers_ = 🎏 🕰. - -🚶 *➡ 🛠️* "🤚 `/slowusers/`" 🌐 📑. ⚙️ "🔄 ⚫️ 👅" 🔼 & 🛠️ 📨 🔠 📑, 1️⃣ ▶️️ ⏮️ 🎏. - -📑 🔜 ⌛ 🍖 & ⤴️ 👫 🔜 🎦 `Internal Server Error`. - -### ⚫️❔ 🔨 - -🥇 📑 🔜 ⚒ 👆 📱 ✍ 🔗 💽 & ⌛ 🥈 ⏭ 🙇 🔙 & 📪 💽 🔗. - -⤴️, 📨 ⏭ 📑, 👆 📱 🔜 ⌛ 🕐 🥈 🌘, & 🔛. - -👉 ⛓ 👈 ⚫️ 🔜 🔚 🆙 🏁 🏁 📑' 📨 ⏪ 🌘 ⏮️ 🕐. - -⤴️ 1️⃣ 🏁 📨 👈 ⌛ 🌘 🥈 🔜 🔄 📂 💽 🔗, ✋️ 1️⃣ 📚 ⏮️ 📨 🎏 📑 🔜 🎲 🍵 🎏 🧵 🥇 🕐, ⚫️ 🔜 ✔️ 🎏 💽 🔗 👈 ⏪ 📂, & 🏒 🔜 🚮 ❌ & 👆 🔜 👀 ⚫️ 📶, & 📨 🔜 ✔️ `Internal Server Error`. - -👉 🔜 🎲 🔨 🌅 🌘 1️⃣ 📚 📑. - -🚥 👆 ✔️ 💗 👩‍💻 💬 👆 📱 ⚫️❔ 🎏 🕰, 👉 ⚫️❔ 💪 🔨. - -& 👆 📱 ▶️ 🍵 🌅 & 🌖 👩‍💻 🎏 🕰, ⌛ 🕰 👁 📨 💪 📏 & 📏 ⏲ ❌. - -### 🔧 🏒 ⏮️ FastAPI - -🔜 🚶 🔙 📁 `sql_app/database.py`, & ✍ ⏸: - -```Python -db._state = PeeweeConnectionState() -``` - -& 📁 `sql_app/main.py` 📁, ✍ 💪 `async` 🔗 `reset_db_state()`: - -```Python -async def reset_db_state(): - database.db._state._state.set(db_state_default.copy()) - database.db._state.reset() -``` - -❎ 👆 🏃‍♂ 📱 & ▶️ ⚫️ 🔄. - -🔁 🎏 🛠️ ⏮️ 1️⃣0️⃣ 📑. 👉 🕰 🌐 👫 🔜 ⌛ & 👆 🔜 🤚 🌐 🏁 🍵 ❌. - -...👆 🔧 ⚫️ ❗ - -## 📄 🌐 📁 - - 💭 👆 🔜 ✔️ 📁 📛 `my_super_project` (⚖️ 👐 👆 💚) 👈 🔌 🎧-📁 🤙 `sql_app`. - -`sql_app` 🔜 ✔️ 📄 📁: - -* `sql_app/__init__.py`: 🛁 📁. - -* `sql_app/database.py`: - -```Python -{!../../../docs_src/sql_databases_peewee/sql_app/database.py!} -``` - -* `sql_app/models.py`: - -```Python -{!../../../docs_src/sql_databases_peewee/sql_app/models.py!} -``` - -* `sql_app/schemas.py`: - -```Python -{!../../../docs_src/sql_databases_peewee/sql_app/schemas.py!} -``` - -* `sql_app/crud.py`: - -```Python -{!../../../docs_src/sql_databases_peewee/sql_app/crud.py!} -``` - -* `sql_app/main.py`: - -```Python -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -## 📡 ℹ - -!!! warning - 👉 📶 📡 ℹ 👈 👆 🎲 🚫 💪. - -### ⚠ - -🏒 ⚙️ `threading.local` 🔢 🏪 ⚫️ 💽 "🇵🇸" 💽 (🔗, 💵, ♒️). - -`threading.local` ✍ 💲 🌟 ⏮️ 🧵, ✋️ 🔁 🛠️ 🔜 🏃 🌐 📟 (✅ 🔠 📨) 🎏 🧵, & 🎲 🚫 ✔. - -🔛 🔝 👈, 🔁 🛠️ 💪 🏃 🔁 📟 🧵 (⚙️ `asyncio.run_in_executor`), ✋️ 🔗 🎏 📨. - -👉 ⛓ 👈, ⏮️ 🏒 ⏮️ 🛠️, 💗 📋 💪 ⚙️ 🎏 `threading.local` 🔢 & 🔚 🆙 🤝 🎏 🔗 & 💽 (👈 👫 🚫🔜 🚫), & 🎏 🕰, 🚥 👫 🛠️ 🔁 👤/🅾-🚧 📟 🧵 (⏮️ 😐 `def` 🔢 FastAPI, *➡ 🛠️* & 🔗), 👈 📟 🏆 🚫 ✔️ 🔐 💽 🇵🇸 🔢, ⏪ ⚫️ 🍕 🎏 📨 & ⚫️ 🔜 💪 🤚 🔐 🎏 💽 🇵🇸. - -### 🔑 🔢 - -🐍 3️⃣.7️⃣ ✔️ `contextvars` 👈 💪 ✍ 🇧🇿 🔢 📶 🎏 `threading.local`, ✋️ 🔗 👫 🔁 ⚒. - -📤 📚 👜 ✔️ 🤯. - -`ContextVar` ✔️ ✍ 🔝 🕹, 💖: - -```Python -some_var = ContextVar("some_var", default="default value") -``` - -⚒ 💲 ⚙️ ⏮️ "🔑" (✅ ⏮️ 📨) ⚙️: - -```Python -some_var.set("new value") -``` - -🤚 💲 🙆 🔘 🔑 (✅ 🙆 🍕 🚚 ⏮️ 📨) ⚙️: - -```Python -some_var.get() -``` - -### ⚒ 🔑 🔢 `async` 🔗 `reset_db_state()` - -🚥 🍕 🔁 📟 ⚒ 💲 ⏮️ `some_var.set("updated in function")` (✅ 💖 `async` 🔗), 🎂 📟 ⚫️ & 📟 👈 🚶 ⏮️ (✅ 📟 🔘 `async` 🔢 🤙 ⏮️ `await`) 🔜 👀 👈 🆕 💲. - -, 👆 💼, 🚥 👥 ⚒ 🏒 🇵🇸 🔢 (⏮️ 🔢 `dict`) `async` 🔗, 🌐 🎂 🔗 📟 👆 📱 🔜 👀 👉 💲 & 🔜 💪 ♻ ⚫️ 🎂 📨. - -& 🔑 🔢 🔜 ⚒ 🔄 ⏭ 📨, 🚥 👫 🛠️. - -### ⚒ 💽 🇵🇸 🔗 `get_db()` - -`get_db()` 😐 `def` 🔢, **FastAPI** 🔜 ⚒ ⚫️ 🏃 🧵, ⏮️ *📁* "🔑", 🧑‍🤝‍🧑 🎏 💲 🔑 🔢 ( `dict` ⏮️ ⏲ 💽 🇵🇸). ⤴️ ⚫️ 💪 🚮 💽 🇵🇸 👈 `dict`, 💖 🔗, ♒️. - -✋️ 🚥 💲 🔑 🔢 (🔢 `dict`) ⚒ 👈 😐 `def` 🔢, ⚫️ 🔜 ✍ 🆕 💲 👈 🔜 🚧 🕴 👈 🧵 🧵, & 🎂 📟 (💖 *➡ 🛠️ 🔢*) 🚫🔜 ✔️ 🔐 ⚫️. `get_db()` 👥 💪 🕴 ⚒ 💲 `dict`, ✋️ 🚫 🎂 `dict` ⚫️. - -, 👥 💪 ✔️ `async` 🔗 `reset_db_state()` ⚒ `dict` 🔑 🔢. 👈 🌌, 🌐 📟 ✔️ 🔐 🎏 `dict` 💽 🇵🇸 👁 📨. - -### 🔗 & 🔌 🔗 `get_db()` - -⤴️ ⏭ ❔ 🔜, ⚫️❔ 🚫 🔗 & 🔌 💽 `async` 🔗 ⚫️, ↩️ `get_db()`❓ - -`async` 🔗 ✔️ `async` 🔑 🔢 🛡 🎂 📨, ✋️ 🏗 & 📪 💽 🔗 ⚠ 🚧, ⚫️ 💪 📉 🎭 🚥 ⚫️ 📤. - -👥 💪 😐 `def` 🔗 `get_db()`. diff --git a/docs/em/docs/index.md b/docs/em/docs/index.md index c7df28160..57be59b07 100644 --- a/docs/em/docs/index.md +++ b/docs/em/docs/index.md @@ -1,3 +1,9 @@ +# FastAPI + + +

FastAPI

@@ -5,11 +11,11 @@ FastAPI 🛠️, ↕ 🎭, ⏩ 💡, ⏩ 📟, 🔜 🏭

- - Test + + Test - - Coverage + + Coverage Package version @@ -23,7 +29,7 @@ **🧾**: https://fastapi.tiangolo.com -**ℹ 📟**: https://github.com/tiangolo/fastapi +**ℹ 📟**: https://github.com/fastapi/fastapi --- @@ -31,7 +37,7 @@ FastAPI 🏛, ⏩ (↕-🎭), 🕸 🛠️ 🏗 🛠️ ⏮️ 🐍 3️⃣.8️ 🔑 ⚒: -* **⏩**: 📶 ↕ 🎭, 🔛 🇷🇪 ⏮️ **✳** & **🚶** (👏 💃 & Pydantic). [1️⃣ ⏩ 🐍 🛠️ 💪](#performance). +* **⏩**: 📶 ↕ 🎭, 🔛 🇷🇪 ⏮️ **✳** & **🚶** (👏 💃 & Pydantic). [1️⃣ ⏩ 🐍 🛠️ 💪](#_15). * **⏩ 📟**: 📈 🚅 🛠️ ⚒ 🔃 2️⃣0️⃣0️⃣ 💯 3️⃣0️⃣0️⃣ 💯. * * **👩‍❤‍👨 🐛**: 📉 🔃 4️⃣0️⃣ 💯 🗿 (👩‍💻) 📉 ❌. * * **🏋️**: 👑 👨‍🎨 🐕‍🦺. 🛠️ 🌐. 🌘 🕰 🛠️. @@ -63,7 +69,7 @@ FastAPI 🏛, ⏩ (↕-🎭), 🕸 🛠️ 🏗 🛠️ ⏮️ 🐍 3️⃣.8️ "_[...] 👤 ⚙️ **FastAPI** 📚 👫 📆. [...] 👤 🤙 📆 ⚙️ ⚫️ 🌐 👇 🏉 **⚗ 🐕‍🦺 🤸‍♂**. 👫 💆‍♂ 🛠️ 🔘 🐚 **🖥** 🏬 & **📠** 🏬._" -

🧿 🇵🇰 - 🤸‍♂ (🇦🇪)
+
🧿 🇵🇰 - 🤸‍♂ (🇦🇪)
--- @@ -87,7 +93,7 @@ FastAPI 🏛, ⏩ (↕-🎭), 🕸 🛠️ 🏗 🛠️ ⏮️ 🐍 3️⃣.8️ "_🤙, ⚫️❔ 👆 ✔️ 🏗 👀 💎 💠 & 🇵🇱. 📚 🌌, ⚫️ ⚫️❔ 👤 💚 **🤗** - ⚫️ 🤙 😍 👀 👱 🏗 👈._" -
✡ 🗄 - 🤗 👼 (🇦🇪)
+
✡ 🗄 - 🤗 👼 (🇦🇪)
--- @@ -120,14 +126,14 @@ FastAPI 🏛, ⏩ (↕-🎭), 🕸 🛠️ 🏗 🛠️ ⏮️ 🐍 3️⃣.8️ FastAPI 🧍 🔛 ⌚ 🐘: * 💃 🕸 🍕. -* Pydantic 📊 🍕. +* Pydantic 📊 🍕. ## 👷‍♂
```console -$ pip install fastapi +$ pip install "fastapi[standard]" ---> 100% ``` @@ -445,22 +451,21 @@ item: Item ⚙️ Pydantic: -* ujson - ⏩ 🎻 "🎻". -* email_validator - 📧 🔬. +* email-validator - 📧 🔬. ⚙️ 💃: * httpx - ✔ 🚥 👆 💚 ⚙️ `TestClient`. * jinja2 - ✔ 🚥 👆 💚 ⚙️ 🔢 📄 📳. -* python-multipart - ✔ 🚥 👆 💚 🐕‍🦺 📨 "✍", ⏮️ `request.form()`. +* python-multipart - ✔ 🚥 👆 💚 🐕‍🦺 📨 "✍", ⏮️ `request.form()`. * itsdangerous - ✔ `SessionMiddleware` 🐕‍🦺. * pyyaml - ✔ 💃 `SchemaGenerator` 🐕‍🦺 (👆 🎲 🚫 💪 ⚫️ ⏮️ FastAPI). -* ujson - ✔ 🚥 👆 💚 ⚙️ `UJSONResponse`. ⚙️ FastAPI / 💃: * uvicorn - 💽 👈 📐 & 🍦 👆 🈸. * orjson - ✔ 🚥 👆 💚 ⚙️ `ORJSONResponse`. +* ujson - ✔ 🚥 👆 💚 ⚙️ `UJSONResponse`. 👆 💪 ❎ 🌐 👫 ⏮️ `pip install "fastapi[all]"`. diff --git a/docs/em/docs/project-generation.md b/docs/em/docs/project-generation.md index ae959e1d5..ef6a21821 100644 --- a/docs/em/docs/project-generation.md +++ b/docs/em/docs/project-generation.md @@ -14,7 +14,7 @@ * ☁ 🐝 📳 🛠️. * **☁ ✍** 🛠️ & 🛠️ 🇧🇿 🛠️. * **🏭 🔜** 🐍 🕸 💽 ⚙️ Uvicorn & 🐁. -* 🐍 **FastAPI** 👩‍💻: +* 🐍 **FastAPI** 👩‍💻: * **⏩**: 📶 ↕ 🎭, 🔛 🇷🇪 ⏮️ **✳** & **🚶** (👏 💃 & Pydantic). * **🏋️**: 👑 👨‍🎨 🐕‍🦺. 🛠️ 🌐. 🌘 🕰 🛠️. * **⏩**: 🔧 ⏩ ⚙️ & 💡. 🌘 🕰 👂 🩺. diff --git a/docs/em/docs/python-types.md b/docs/em/docs/python-types.md index e079d9039..d2af23bb9 100644 --- a/docs/em/docs/python-types.md +++ b/docs/em/docs/python-types.md @@ -12,15 +12,18 @@ ✋️ 🚥 👆 🙅 ⚙️ **FastAPI**, 👆 🔜 💰 ⚪️➡️ 🏫 🍖 🔃 👫. -!!! note - 🚥 👆 🐍 🕴, & 👆 ⏪ 💭 🌐 🔃 🆎 🔑, 🚶 ⏭ 📃. +/// note + +🚥 👆 🐍 🕴, & 👆 ⏪ 💭 🌐 🔃 🆎 🔑, 🚶 ⏭ 📃. + +/// ## 🎯 ➡️ ▶️ ⏮️ 🙅 🖼: ```Python -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` 🤙 👉 📋 🔢: @@ -36,7 +39,7 @@ John Doe * 🔢 👫 ⏮️ 🚀 🖕. ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} +{!../../docs_src/python_types/tutorial001.py!} ``` ### ✍ ⚫️ @@ -80,7 +83,7 @@ John Doe 👈 "🆎 🔑": ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} +{!../../docs_src/python_types/tutorial002.py!} ``` 👈 🚫 🎏 📣 🔢 💲 💖 🔜 ⏮️: @@ -110,7 +113,7 @@ John Doe ✅ 👉 🔢, ⚫️ ⏪ ✔️ 🆎 🔑: ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} +{!../../docs_src/python_types/tutorial003.py!} ``` ↩️ 👨‍🎨 💭 🆎 🔢, 👆 🚫 🕴 🤚 🛠️, 👆 🤚 ❌ ✅: @@ -120,7 +123,7 @@ John Doe 🔜 👆 💭 👈 👆 ✔️ 🔧 ⚫️, 🗜 `age` 🎻 ⏮️ `str(age)`: ```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} +{!../../docs_src/python_types/tutorial004.py!} ``` ## 📣 🆎 @@ -141,7 +144,7 @@ John Doe * `bytes` ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} +{!../../docs_src/python_types/tutorial005.py!} ``` ### 💊 🆎 ⏮️ 🆎 🔢 @@ -164,45 +167,55 @@ John Doe 🖼, ➡️ 🔬 🔢 `list` `str`. -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ⚪️➡️ `typing`, 🗄 `List` (⏮️ 🔠 `L`): +⚪️➡️ `typing`, 🗄 `List` (⏮️ 🔠 `L`): + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial006.py!} +``` - ``` Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +📣 🔢, ⏮️ 🎏 ❤ (`:`) ❕. - 📣 🔢, ⏮️ 🎏 ❤ (`:`) ❕. +🆎, 🚮 `List` 👈 👆 🗄 ⚪️➡️ `typing`. - 🆎, 🚮 `List` 👈 👆 🗄 ⚪️➡️ `typing`. +📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜: - 📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜: +```Python hl_lines="4" +{!> ../../docs_src/python_types/tutorial006.py!} +``` - ```Python hl_lines="4" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - 📣 🔢, ⏮️ 🎏 ❤ (`:`) ❕. +📣 🔢, ⏮️ 🎏 ❤ (`:`) ❕. - 🆎, 🚮 `list`. +🆎, 🚮 `list`. - 📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜: +📇 🆎 👈 🔌 🔗 🆎, 👆 🚮 👫 ⬜ 🗜: - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial006_py39.py!} +``` -!!! info - 👈 🔗 🆎 ⬜ 🗜 🤙 "🆎 🔢". +//// - 👉 💼, `str` 🆎 🔢 🚶‍♀️ `List` (⚖️ `list` 🐍 3️⃣.9️⃣ & 🔛). +/// info + +👈 🔗 🆎 ⬜ 🗜 🤙 "🆎 🔢". + +👉 💼, `str` 🆎 🔢 🚶‍♀️ `List` (⚖️ `list` 🐍 3️⃣.9️⃣ & 🔛). + +/// 👈 ⛓: "🔢 `items` `list`, & 🔠 🏬 👉 📇 `str`". -!!! tip - 🚥 👆 ⚙️ 🐍 3️⃣.9️⃣ ⚖️ 🔛, 👆 🚫 ✔️ 🗄 `List` ⚪️➡️ `typing`, 👆 💪 ⚙️ 🎏 🥔 `list` 🆎 ↩️. +/// tip + +🚥 👆 ⚙️ 🐍 3️⃣.9️⃣ ⚖️ 🔛, 👆 🚫 ✔️ 🗄 `List` ⚪️➡️ `typing`, 👆 💪 ⚙️ 🎏 🥔 `list` 🆎 ↩️. + +/// 🔨 👈, 👆 👨‍🎨 💪 🚚 🐕‍🦺 ⏪ 🏭 🏬 ⚪️➡️ 📇: @@ -218,17 +231,21 @@ John Doe 👆 🔜 🎏 📣 `tuple`Ⓜ & `set`Ⓜ: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial007.py!} - ``` +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial007.py!} +``` -=== "🐍 3️⃣.9️⃣ & 🔛" +//// - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial007_py39.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial007_py39.py!} +``` + +//// 👉 ⛓: @@ -243,17 +260,21 @@ John Doe 🥈 🆎 🔢 💲 `dict`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial008.py!} +``` + +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008.py!} - ``` +//// tab | 🐍 3️⃣.9️⃣ & 🔛 -=== "🐍 3️⃣.9️⃣ & 🔛" +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial008_py39.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008_py39.py!} - ``` +//// 👉 ⛓: @@ -269,17 +290,21 @@ John Doe 🐍 3️⃣.1️⃣0️⃣ 📤 **🎛 ❕** 🌐❔ 👆 💪 🚮 💪 🆎 👽 ⏸ ⏸ (`|`). -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial008b.py!} +``` + +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008b.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial008b_py310.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008b_py310.py!} - ``` +//// 👯‍♂️ 💼 👉 ⛓ 👈 `item` 💪 `int` ⚖️ `str`. @@ -290,7 +315,7 @@ John Doe 🐍 3️⃣.6️⃣ & 🔛 (✅ 🐍 3️⃣.1️⃣0️⃣) 👆 💪 📣 ⚫️ 🏭 & ⚙️ `Optional` ⚪️➡️ `typing` 🕹. ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` ⚙️ `Optional[str]` ↩️ `str` 🔜 ➡️ 👨‍🎨 ℹ 👆 🔍 ❌ 🌐❔ 👆 💪 🤔 👈 💲 🕧 `str`, 🕐❔ ⚫️ 💪 🤙 `None` 💁‍♂️. @@ -299,23 +324,29 @@ John Doe 👉 ⛓ 👈 🐍 3️⃣.1️⃣0️⃣, 👆 💪 ⚙️ `Something | None`: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial009.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009.py!} - ``` +//// -=== "🐍 3️⃣.6️⃣ & 🔛 - 🎛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - 🎛 - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009b.py!} - ``` +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial009b.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial009_py310.py!} - ``` +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial009_py310.py!} +``` + +//// #### ⚙️ `Union` ⚖️ `Optional` @@ -333,7 +364,7 @@ John Doe 🖼, ➡️ ✊ 👉 🔢: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009c.py!} +{!../../docs_src/python_types/tutorial009c.py!} ``` 🔢 `name` 🔬 `Optional[str]`, ✋️ ⚫️ **🚫 📦**, 👆 🚫🔜 🤙 🔢 🍵 🔢: @@ -351,7 +382,7 @@ say_hi(name=None) # This works, None is valid 🎉 👍 📰, 🕐 👆 🔛 🐍 3️⃣.1️⃣0️⃣ 👆 🏆 🚫 ✔️ 😟 🔃 👈, 👆 🔜 💪 🎯 ⚙️ `|` 🔬 🇪🇺 🆎: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009c_py310.py!} +{!../../docs_src/python_types/tutorial009c_py310.py!} ``` & ⤴️ 👆 🏆 🚫 ✔️ 😟 🔃 📛 💖 `Optional` & `Union`. 👶 @@ -360,47 +391,53 @@ say_hi(name=None) # This works, None is valid 🎉 👉 🆎 👈 ✊ 🆎 🔢 ⬜ 🗜 🤙 **💊 🆎** ⚖️ **💊**, 🖼: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 + +* `List` +* `Tuple` +* `Set` +* `Dict` +* `Union` +* `Optional` +* ...& 🎏. - * `List` - * `Tuple` - * `Set` - * `Dict` - * `Union` - * `Optional` - * ...& 🎏. +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +//// tab | 🐍 3️⃣.9️⃣ & 🔛 - 👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘): +👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘): - * `list` - * `tuple` - * `set` - * `dict` +* `list` +* `tuple` +* `set` +* `dict` - & 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹: + & 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹: - * `Union` - * `Optional` - * ...& 🎏. +* `Union` +* `Optional` +* ...& 🎏. -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - 👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘): +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - * `list` - * `tuple` - * `set` - * `dict` +👆 💪 ⚙️ 🎏 💽 🆎 💊 (⏮️ ⬜ 🗜 & 🆎 🔘): - & 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹: +* `list` +* `tuple` +* `set` +* `dict` - * `Union` - * `Optional` (🎏 ⏮️ 🐍 3️⃣.6️⃣) - * ...& 🎏. + & 🎏 ⏮️ 🐍 3️⃣.6️⃣, ⚪️➡️ `typing` 🕹: - 🐍 3️⃣.1️⃣0️⃣, 🎛 ⚙️ 💊 `Union` & `Optional`, 👆 💪 ⚙️ ⏸ ⏸ (`|`) 📣 🇪🇺 🆎. +* `Union` +* `Optional` (🎏 ⏮️ 🐍 3️⃣.6️⃣) +* ...& 🎏. + +🐍 3️⃣.1️⃣0️⃣, 🎛 ⚙️ 💊 `Union` & `Optional`, 👆 💪 ⚙️ ⏸ ⏸ (`|`) 📣 🇪🇺 🆎. + +//// ### 🎓 🆎 @@ -409,13 +446,13 @@ say_hi(name=None) # This works, None is valid 🎉 ➡️ 💬 👆 ✔️ 🎓 `Person`, ⏮️ 📛: ```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` ⤴️ 👆 💪 📣 🔢 🆎 `Person`: ```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} +{!../../docs_src/python_types/tutorial010.py!} ``` & ⤴️, 🔄, 👆 🤚 🌐 👨‍🎨 🐕‍🦺: @@ -424,7 +461,7 @@ say_hi(name=None) # This works, None is valid 🎉 ## Pydantic 🏷 -Pydantic 🐍 🗃 🎭 📊 🔬. +Pydantic 🐍 🗃 🎭 📊 🔬. 👆 📣 "💠" 💽 🎓 ⏮️ 🔢. @@ -436,33 +473,45 @@ say_hi(name=None) # This works, None is valid 🎉 🖼 ⚪️➡️ 🛂 Pydantic 🩺: -=== "🐍 3️⃣.6️⃣ & 🔛" +//// tab | 🐍 3️⃣.6️⃣ & 🔛 - ```Python - {!> ../../../docs_src/python_types/tutorial011.py!} - ``` +```Python +{!> ../../docs_src/python_types/tutorial011.py!} +``` + +//// + +//// tab | 🐍 3️⃣.9️⃣ & 🔛 + +```Python +{!> ../../docs_src/python_types/tutorial011_py39.py!} +``` + +//// -=== "🐍 3️⃣.9️⃣ & 🔛" +//// tab | 🐍 3️⃣.1️⃣0️⃣ & 🔛 - ```Python - {!> ../../../docs_src/python_types/tutorial011_py39.py!} - ``` +```Python +{!> ../../docs_src/python_types/tutorial011_py310.py!} +``` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +//// - ```Python - {!> ../../../docs_src/python_types/tutorial011_py310.py!} - ``` +/// info -!!! info - 💡 🌖 🔃 Pydantic, ✅ 🚮 🩺. +💡 🌖 🔃 Pydantic, ✅ 🚮 🩺. + +/// **FastAPI** 🌐 ⚓️ 🔛 Pydantic. 👆 🔜 👀 📚 🌅 🌐 👉 💡 [🔰 - 👩‍💻 🦮](tutorial/index.md){.internal-link target=_blank}. -!!! tip - Pydantic ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 ✔ 📦 🏑. +/// tip + +Pydantic ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 ✔ 📦 🏑. + +/// ## 🆎 🔑 **FastAPI** @@ -486,5 +535,8 @@ say_hi(name=None) # This works, None is valid 🎉 ⚠ 👜 👈 ⚙️ 🐩 🐍 🆎, 👁 🥉 (↩️ ❎ 🌖 🎓, 👨‍🎨, ♒️), **FastAPI** 🔜 📚 👷 👆. -!!! info - 🚥 👆 ⏪ 🚶 🔘 🌐 🔰 & 👟 🔙 👀 🌅 🔃 🆎, 👍 ℹ "🎮 🎼" ⚪️➡️ `mypy`. +/// info + +🚥 👆 ⏪ 🚶 🔘 🌐 🔰 & 👟 🔙 👀 🌅 🔃 🆎, 👍 ℹ "🎮 🎼" ⚪️➡️ `mypy`. + +/// diff --git a/docs/em/docs/tutorial/background-tasks.md b/docs/em/docs/tutorial/background-tasks.md index e28ead415..aed60c754 100644 --- a/docs/em/docs/tutorial/background-tasks.md +++ b/docs/em/docs/tutorial/background-tasks.md @@ -15,9 +15,7 @@ 🥇, 🗄 `BackgroundTasks` & 🔬 🔢 👆 *➡ 🛠️ 🔢* ⏮️ 🆎 📄 `BackgroundTasks`: -```Python hl_lines="1 13" -{!../../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *} **FastAPI** 🔜 ✍ 🎚 🆎 `BackgroundTasks` 👆 & 🚶‍♀️ ⚫️ 👈 🔢. @@ -33,17 +31,13 @@ & ✍ 🛠️ 🚫 ⚙️ `async` & `await`, 👥 🔬 🔢 ⏮️ 😐 `def`: -```Python hl_lines="6-9" -{!../../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *} ## 🚮 🖥 📋 🔘 👆 *➡ 🛠️ 🔢*, 🚶‍♀️ 👆 📋 🔢 *🖥 📋* 🎚 ⏮️ 👩‍🔬 `.add_task()`: -```Python hl_lines="14" -{!../../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[14] *} `.add_task()` 📨 ❌: @@ -57,17 +51,7 @@ **FastAPI** 💭 ⚫️❔ 🔠 💼 & ❔ 🏤-⚙️ 🎏 🎚, 👈 🌐 🖥 📋 🔗 👯‍♂️ & 🏃 🖥 ⏮️: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="11 13 20 23" - {!> ../../../docs_src/background_tasks/tutorial002_py310.py!} - ``` +{* ../../docs_src/background_tasks/tutorial002.py hl[13,15,22,25] *} 👉 🖼, 📧 🔜 ✍ `log.txt` 📁 *⏮️* 📨 📨. @@ -93,8 +77,6 @@ 👫 😑 🚚 🌖 🏗 📳, 📧/👨‍🏭 📤 👨‍💼, 💖 ✳ ⚖️ ✳, ✋️ 👫 ✔ 👆 🏃 🖥 📋 💗 🛠️, & ✴️, 💗 💽. -👀 🖼, ✅ [🏗 🚂](../project-generation.md){.internal-link target=_blank}, 👫 🌐 🔌 🥒 ⏪ 📶. - ✋️ 🚥 👆 💪 🔐 🔢 & 🎚 ⚪️➡️ 🎏 **FastAPI** 📱, ⚖️ 👆 💪 🎭 🤪 🖥 📋 (💖 📨 📧 📨), 👆 💪 🎯 ⚙️ `BackgroundTasks`. ## 🌃 diff --git a/docs/em/docs/tutorial/bigger-applications.md b/docs/em/docs/tutorial/bigger-applications.md index c30bba106..68f506f27 100644 --- a/docs/em/docs/tutorial/bigger-applications.md +++ b/docs/em/docs/tutorial/bigger-applications.md @@ -4,8 +4,11 @@ **FastAPI** 🚚 🏪 🧰 📊 👆 🈸 ⏪ 🚧 🌐 💪. -!!! info - 🚥 👆 👟 ⚪️➡️ 🏺, 👉 🔜 🌓 🏺 📗. +/// info + +🚥 👆 👟 ⚪️➡️ 🏺, 👉 🔜 🌓 🏺 📗. + +/// ## 🖼 📁 📊 @@ -26,16 +29,19 @@ │   └── admin.py ``` -!!! tip - 📤 📚 `__init__.py` 📁: 1️⃣ 🔠 📁 ⚖️ 📁. +/// tip + +📤 📚 `__init__.py` 📁: 1️⃣ 🔠 📁 ⚖️ 📁. - 👉 ⚫️❔ ✔ 🏭 📟 ⚪️➡️ 1️⃣ 📁 🔘 ➕1️⃣. +👉 ⚫️❔ ✔ 🏭 📟 ⚪️➡️ 1️⃣ 📁 🔘 ➕1️⃣. - 🖼, `app/main.py` 👆 💪 ✔️ ⏸ 💖: +🖼, `app/main.py` 👆 💪 ✔️ ⏸ 💖: + +``` +from app.routers import items +``` - ``` - from app.routers import items - ``` +/// * `app` 📁 🔌 🌐. & ⚫️ ✔️ 🛁 📁 `app/__init__.py`, ⚫️ "🐍 📦" (🗃 "🐍 🕹"): `app`. * ⚫️ 🔌 `app/main.py` 📁. ⚫️ 🔘 🐍 📦 (📁 ⏮️ 📁 `__init__.py`), ⚫️ "🕹" 👈 📦: `app.main`. @@ -80,7 +86,7 @@ 👆 🗄 ⚫️ & ✍ "👐" 🎏 🌌 👆 🔜 ⏮️ 🎓 `FastAPI`: ```Python hl_lines="1 3" title="app/routers/users.py" -{!../../../docs_src/bigger_applications/app/routers/users.py!} +{!../../docs_src/bigger_applications/app/routers/users.py!} ``` ### *➡ 🛠️* ⏮️ `APIRouter` @@ -90,7 +96,7 @@ ⚙️ ⚫️ 🎏 🌌 👆 🔜 ⚙️ `FastAPI` 🎓: ```Python hl_lines="6 11 16" title="app/routers/users.py" -{!../../../docs_src/bigger_applications/app/routers/users.py!} +{!../../docs_src/bigger_applications/app/routers/users.py!} ``` 👆 💪 💭 `APIRouter` "🐩 `FastAPI`" 🎓. @@ -99,8 +105,11 @@ 🌐 🎏 `parameters`, `responses`, `dependencies`, `tags`, ♒️. -!!! tip - 👉 🖼, 🔢 🤙 `router`, ✋️ 👆 💪 📛 ⚫️ 👐 👆 💚. +/// tip + +👉 🖼, 🔢 🤙 `router`, ✋️ 👆 💪 📛 ⚫️ 👐 👆 💚. + +/// 👥 🔜 🔌 👉 `APIRouter` 👑 `FastAPI` 📱, ✋️ 🥇, ➡️ ✅ 🔗 & ➕1️⃣ `APIRouter`. @@ -113,13 +122,16 @@ 👥 🔜 🔜 ⚙️ 🙅 🔗 ✍ 🛃 `X-Token` 🎚: ```Python hl_lines="1 4-6" title="app/dependencies.py" -{!../../../docs_src/bigger_applications/app/dependencies.py!} +{!../../docs_src/bigger_applications/app/dependencies.py!} ``` -!!! tip - 👥 ⚙️ 💭 🎚 📉 👉 🖼. +/// tip + +👥 ⚙️ 💭 🎚 📉 👉 🖼. + +✋️ 🎰 💼 👆 🔜 🤚 👍 🏁 ⚙️ 🛠️ [💂‍♂ 🚙](security/index.md){.internal-link target=_blank}. - ✋️ 🎰 💼 👆 🔜 🤚 👍 🏁 ⚙️ 🛠️ [💂‍♂ 🚙](./security/index.md){.internal-link target=_blank}. +/// ## ➕1️⃣ 🕹 ⏮️ `APIRouter` @@ -144,7 +156,7 @@ , ↩️ ❎ 🌐 👈 🔠 *➡ 🛠️*, 👥 💪 🚮 ⚫️ `APIRouter`. ```Python hl_lines="5-10 16 21" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` ➡ 🔠 *➡ 🛠️* ✔️ ▶️ ⏮️ `/`, 💖: @@ -163,8 +175,11 @@ async def read_item(item_id: str): & 👥 💪 🚮 📇 `dependencies` 👈 🔜 🚮 🌐 *➡ 🛠️* 📻 & 🔜 🛠️/❎ 🔠 📨 ⚒ 👫. -!!! tip - 🗒 👈, 🌅 💖 [🔗 *➡ 🛠️ 👨‍🎨*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, 🙅‍♂ 💲 🔜 🚶‍♀️ 👆 *➡ 🛠️ 🔢*. +/// tip + +🗒 👈, 🌅 💖 [🔗 *➡ 🛠️ 👨‍🎨*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, 🙅‍♂ 💲 🔜 🚶‍♀️ 👆 *➡ 🛠️ 🔢*. + +/// 🔚 🏁 👈 🏬 ➡ 🔜: @@ -181,11 +196,17 @@ async def read_item(item_id: str): * 📻 🔗 🛠️ 🥇, ⤴️ [`dependencies` 👨‍🎨](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, & ⤴️ 😐 🔢 🔗. * 👆 💪 🚮 [`Security` 🔗 ⏮️ `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}. -!!! tip - ✔️ `dependencies` `APIRouter` 💪 ⚙️, 🖼, 🚚 🤝 🎂 👪 *➡ 🛠️*. 🚥 🔗 🚫 🚮 📦 🔠 1️⃣ 👫. +/// tip + +✔️ `dependencies` `APIRouter` 💪 ⚙️, 🖼, 🚚 🤝 🎂 👪 *➡ 🛠️*. 🚥 🔗 🚫 🚮 📦 🔠 1️⃣ 👫. + +/// + +/// check -!!! check - `prefix`, `tags`, `responses`, & `dependencies` 🔢 (📚 🎏 💼) ⚒ ⚪️➡️ **FastAPI** ℹ 👆 ❎ 📟 ❎. +`prefix`, `tags`, `responses`, & `dependencies` 🔢 (📚 🎏 💼) ⚒ ⚪️➡️ **FastAPI** ℹ 👆 ❎ 📟 ❎. + +/// ### 🗄 🔗 @@ -196,13 +217,16 @@ async def read_item(item_id: str): 👥 ⚙️ ⚖ 🗄 ⏮️ `..` 🔗: ```Python hl_lines="3" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` #### ❔ ⚖ 🗄 👷 -!!! tip - 🚥 👆 💭 👌 ❔ 🗄 👷, 😣 ⏭ 📄 🔛. +/// tip + +🚥 👆 💭 👌 ❔ 🗄 👷, 😣 ⏭ 📄 🔛. + +/// 👁 ❣ `.`, 💖: @@ -266,13 +290,16 @@ that 🔜 ⛓: ✋️ 👥 💪 🚮 _🌅_ `tags` 👈 🔜 ✔ 🎯 *➡ 🛠️*, & ➕ `responses` 🎯 👈 *➡ 🛠️*: ```Python hl_lines="30-31" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` -!!! tip - 👉 🏁 ➡ 🛠️ 🔜 ✔️ 🌀 🔖: `["items", "custom"]`. +/// tip + +👉 🏁 ➡ 🛠️ 🔜 ✔️ 🌀 🔖: `["items", "custom"]`. - & ⚫️ 🔜 ✔️ 👯‍♂️ 📨 🧾, 1️⃣ `404` & 1️⃣ `403`. + & ⚫️ 🔜 ✔️ 👯‍♂️ 📨 🧾, 1️⃣ `404` & 1️⃣ `403`. + +/// ## 👑 `FastAPI` @@ -291,7 +318,7 @@ that 🔜 ⛓: & 👥 💪 📣 [🌐 🔗](dependencies/global-dependencies.md){.internal-link target=_blank} 👈 🔜 🌀 ⏮️ 🔗 🔠 `APIRouter`: ```Python hl_lines="1 3 7" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` ### 🗄 `APIRouter` @@ -299,7 +326,7 @@ that 🔜 ⛓: 🔜 👥 🗄 🎏 🔁 👈 ✔️ `APIRouter`Ⓜ: ```Python hl_lines="5" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` 📁 `app/routers/users.py` & `app/routers/items.py` 🔁 👈 🍕 🎏 🐍 📦 `app`, 👥 💪 ⚙️ 👁 ❣ `.` 🗄 👫 ⚙️ "⚖ 🗄". @@ -328,20 +355,23 @@ from .routers import items, users from app.routers import items, users ``` -!!! info - 🥇 ⏬ "⚖ 🗄": +/// info + +🥇 ⏬ "⚖ 🗄": - ```Python - from .routers import items, users - ``` +```Python +from .routers import items, users +``` - 🥈 ⏬ "🎆 🗄": +🥈 ⏬ "🎆 🗄": + +```Python +from app.routers import items, users +``` - ```Python - from app.routers import items, users - ``` +💡 🌅 🔃 🐍 📦 & 🕹, ✍ 🛂 🐍 🧾 🔃 🕹. - 💡 🌅 🔃 🐍 📦 & 🕹, ✍ 🛂 🐍 🧾 🔃 🕹. +/// ### ❎ 📛 💥 @@ -361,7 +391,7 @@ from .routers.users import router , 💪 ⚙️ 👯‍♂️ 👫 🎏 📁, 👥 🗄 🔁 🔗: ```Python hl_lines="5" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` ### 🔌 `APIRouter`Ⓜ `users` & `items` @@ -369,29 +399,38 @@ from .routers.users import router 🔜, ➡️ 🔌 `router`Ⓜ ⚪️➡️ 🔁 `users` & `items`: ```Python hl_lines="10-11" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` -!!! info - `users.router` 🔌 `APIRouter` 🔘 📁 `app/routers/users.py`. +/// info - & `items.router` 🔌 `APIRouter` 🔘 📁 `app/routers/items.py`. +`users.router` 🔌 `APIRouter` 🔘 📁 `app/routers/users.py`. + + & `items.router` 🔌 `APIRouter` 🔘 📁 `app/routers/items.py`. + +/// ⏮️ `app.include_router()` 👥 💪 🚮 🔠 `APIRouter` 👑 `FastAPI` 🈸. ⚫️ 🔜 🔌 🌐 🛣 ⚪️➡️ 👈 📻 🍕 ⚫️. -!!! note "📡 ℹ" - ⚫️ 🔜 🤙 🔘 ✍ *➡ 🛠️* 🔠 *➡ 🛠️* 👈 📣 `APIRouter`. +/// note | 📡 ℹ + +⚫️ 🔜 🤙 🔘 ✍ *➡ 🛠️* 🔠 *➡ 🛠️* 👈 📣 `APIRouter`. + +, ⛅ 🎑, ⚫️ 🔜 🤙 👷 🚥 🌐 🎏 👁 📱. + +/// - , ⛅ 🎑, ⚫️ 🔜 🤙 👷 🚥 🌐 🎏 👁 📱. +/// check -!!! check - 👆 🚫 ✔️ 😟 🔃 🎭 🕐❔ ✅ 📻. +👆 🚫 ✔️ 😟 🔃 🎭 🕐❔ ✅ 📻. - 👉 🔜 ✊ ⏲ & 🔜 🕴 🔨 🕴. +👉 🔜 ✊ ⏲ & 🔜 🕴 🔨 🕴. - ⚫️ 🏆 🚫 📉 🎭. 👶 +⚫️ 🏆 🚫 📉 🎭. 👶 + +/// ### 🔌 `APIRouter` ⏮️ 🛃 `prefix`, `tags`, `responses`, & `dependencies` @@ -402,7 +441,7 @@ from .routers.users import router 👉 🖼 ⚫️ 🔜 💎 🙅. ✋️ ➡️ 💬 👈 ↩️ ⚫️ 💰 ⏮️ 🎏 🏗 🏢, 👥 🚫🔜 🔀 ⚫️ & 🚮 `prefix`, `dependencies`, `tags`, ♒️. 🔗 `APIRouter`: ```Python hl_lines="3" title="app/internal/admin.py" -{!../../../docs_src/bigger_applications/app/internal/admin.py!} +{!../../docs_src/bigger_applications/app/internal/admin.py!} ``` ✋️ 👥 💚 ⚒ 🛃 `prefix` 🕐❔ ✅ `APIRouter` 👈 🌐 🚮 *➡ 🛠️* ▶️ ⏮️ `/admin`, 👥 💚 🔐 ⚫️ ⏮️ `dependencies` 👥 ⏪ ✔️ 👉 🏗, & 👥 💚 🔌 `tags` & `responses`. @@ -410,7 +449,7 @@ from .routers.users import router 👥 💪 📣 🌐 👈 🍵 ✔️ 🔀 ⏮️ `APIRouter` 🚶‍♀️ 👈 🔢 `app.include_router()`: ```Python hl_lines="14-17" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` 👈 🌌, ⏮️ `APIRouter` 🔜 🚧 ⚗, 👥 💪 💰 👈 🎏 `app/internal/admin.py` 📁 ⏮️ 🎏 🏗 🏢. @@ -433,21 +472,24 @@ from .routers.users import router 📥 👥 ⚫️... 🎦 👈 👥 💪 🤷: ```Python hl_lines="21-23" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` & ⚫️ 🔜 👷 ☑, 👯‍♂️ ⏮️ 🌐 🎏 *➡ 🛠️* 🚮 ⏮️ `app.include_router()`. -!!! info "📶 📡 ℹ" - **🗒**: 👉 📶 📡 ℹ 👈 👆 🎲 💪 **🚶**. +/// info | 📶 📡 ℹ + +**🗒**: 👉 📶 📡 ℹ 👈 👆 🎲 💪 **🚶**. + +--- - --- + `APIRouter`Ⓜ 🚫 "🗻", 👫 🚫 👽 ⚪️➡️ 🎂 🈸. - `APIRouter`Ⓜ 🚫 "🗻", 👫 🚫 👽 ⚪️➡️ 🎂 🈸. +👉 ↩️ 👥 💚 🔌 👫 *➡ 🛠️* 🗄 🔗 & 👩‍💻 🔢. - 👉 ↩️ 👥 💚 🔌 👫 *➡ 🛠️* 🗄 🔗 & 👩‍💻 🔢. +👥 🚫🔜 ❎ 👫 & "🗻" 👫 ➡ 🎂, *➡ 🛠️* "🖖" (🏤-✍), 🚫 🔌 🔗. - 👥 🚫🔜 ❎ 👫 & "🗻" 👫 ➡ 🎂, *➡ 🛠️* "🖖" (🏤-✍), 🚫 🔌 🔗. +/// ## ✅ 🏧 🛠️ 🩺 diff --git a/docs/em/docs/tutorial/body-fields.md b/docs/em/docs/tutorial/body-fields.md index 9f2c914f4..f202284b5 100644 --- a/docs/em/docs/tutorial/body-fields.md +++ b/docs/em/docs/tutorial/body-fields.md @@ -6,50 +6,39 @@ 🥇, 👆 ✔️ 🗄 ⚫️: -=== "🐍 3️⃣.6️⃣ & 🔛" +{* ../../docs_src/body_fields/tutorial001.py hl[4] *} - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +/// warning -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +👀 👈 `Field` 🗄 🔗 ⚪️➡️ `pydantic`, 🚫 ⚪️➡️ `fastapi` 🌐 🎂 (`Query`, `Path`, `Body`, ♒️). - ```Python hl_lines="2" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` - -!!! warning - 👀 👈 `Field` 🗄 🔗 ⚪️➡️ `pydantic`, 🚫 ⚪️➡️ `fastapi` 🌐 🎂 (`Query`, `Path`, `Body`, ♒️). +/// ## 📣 🏷 🔢 👆 💪 ⤴️ ⚙️ `Field` ⏮️ 🏷 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" +{* ../../docs_src/body_fields/tutorial001.py hl[11:14] *} - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +`Field` 👷 🎏 🌌 `Query`, `Path` & `Body`, ⚫️ ✔️ 🌐 🎏 🔢, ♒️. -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// note | 📡 ℹ - ```Python hl_lines="9-12" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +🤙, `Query`, `Path` & 🎏 👆 🔜 👀 ⏭ ✍ 🎚 🏿 ⚠ `Param` 🎓, ❔ ⚫️ 🏿 Pydantic `FieldInfo` 🎓. -`Field` 👷 🎏 🌌 `Query`, `Path` & `Body`, ⚫️ ✔️ 🌐 🎏 🔢, ♒️. + & Pydantic `Field` 📨 👐 `FieldInfo` 👍. -!!! note "📡 ℹ" - 🤙, `Query`, `Path` & 🎏 👆 🔜 👀 ⏭ ✍ 🎚 🏿 ⚠ `Param` 🎓, ❔ ⚫️ 🏿 Pydantic `FieldInfo` 🎓. +`Body` 📨 🎚 🏿 `FieldInfo` 🔗. & 📤 🎏 👆 🔜 👀 ⏪ 👈 🏿 `Body` 🎓. - & Pydantic `Field` 📨 👐 `FieldInfo` 👍. +💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. - `Body` 📨 🎚 🏿 `FieldInfo` 🔗. & 📤 🎏 👆 🔜 👀 ⏪ 👈 🏿 `Body` 🎓. +/// - 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. +/// tip -!!! tip - 👀 ❔ 🔠 🏷 🔢 ⏮️ 🆎, 🔢 💲 & `Field` ✔️ 🎏 📊 *➡ 🛠️ 🔢* 🔢, ⏮️ `Field` ↩️ `Path`, `Query` & `Body`. +👀 ❔ 🔠 🏷 🔢 ⏮️ 🆎, 🔢 💲 & `Field` ✔️ 🎏 📊 *➡ 🛠️ 🔢* 🔢, ⏮️ `Field` ↩️ `Path`, `Query` & `Body`. + +/// ## 🚮 ➕ ℹ @@ -57,9 +46,12 @@ 👆 🔜 💡 🌅 🔃 ❎ ➕ ℹ ⏪ 🩺, 🕐❔ 🏫 📣 🖼. -!!! warning - ➕ 🔑 🚶‍♀️ `Field` 🔜 🎁 📉 🗄 🔗 👆 🈸. - 👫 🔑 5️⃣📆 🚫 🎯 🍕 🗄 🔧, 🗄 🧰, 🖼 [🗄 💳](https://validator.swagger.io/), 5️⃣📆 🚫 👷 ⏮️ 👆 🏗 🔗. +/// warning + +➕ 🔑 🚶‍♀️ `Field` 🔜 🎁 📉 🗄 🔗 👆 🈸. +👫 🔑 5️⃣📆 🚫 🎯 🍕 🗄 🔧, 🗄 🧰, 🖼 [🗄 💳](https://validator.swagger.io/), 5️⃣📆 🚫 👷 ⏮️ 👆 🏗 🔗. + +/// ## 🌃 diff --git a/docs/em/docs/tutorial/body-multiple-params.md b/docs/em/docs/tutorial/body-multiple-params.md index 9ada7dee1..3a2f2bd54 100644 --- a/docs/em/docs/tutorial/body-multiple-params.md +++ b/docs/em/docs/tutorial/body-multiple-params.md @@ -8,20 +8,13 @@ & 👆 💪 📣 💪 🔢 📦, ⚒ 🔢 `None`: -=== "🐍 3️⃣.6️⃣ & 🔛" +{* ../../docs_src/body_multiple_params/tutorial001.py hl[19:21] *} - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001.py!} - ``` +/// note -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +👀 👈, 👉 💼, `item` 👈 🔜 ✊ ⚪️➡️ 💪 📦. ⚫️ ✔️ `None` 🔢 💲. - ```Python hl_lines="17-19" - {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} - ``` - -!!! note - 👀 👈, 👉 💼, `item` 👈 🔜 ✊ ⚪️➡️ 💪 📦. ⚫️ ✔️ `None` 🔢 💲. +/// ## 💗 💪 🔢 @@ -38,17 +31,7 @@ ✋️ 👆 💪 📣 💗 💪 🔢, ✅ `item` & `user`: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial002.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} - ``` +{* ../../docs_src/body_multiple_params/tutorial002.py hl[22] *} 👉 💼, **FastAPI** 🔜 👀 👈 📤 🌅 🌘 1️⃣ 💪 🔢 🔢 (2️⃣ 🔢 👈 Pydantic 🏷). @@ -69,9 +52,11 @@ } ``` -!!! note - 👀 👈 ✋️ `item` 📣 🎏 🌌 ⏭, ⚫️ 🔜 ⌛ 🔘 💪 ⏮️ 🔑 `item`. +/// note + +👀 👈 ✋️ `item` 📣 🎏 🌌 ⏭, ⚫️ 🔜 ⌛ 🔘 💪 ⏮️ 🔑 `item`. +/// **FastAPI** 🔜 🏧 🛠️ ⚪️➡️ 📨, 👈 🔢 `item` 📨 ⚫️ 🎯 🎚 & 🎏 `user`. @@ -87,17 +72,7 @@ ✋️ 👆 💪 💡 **FastAPI** 😥 ⚫️ ➕1️⃣ 💪 🔑 ⚙️ `Body`: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial003.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} - ``` +{* ../../docs_src/body_multiple_params/tutorial003.py hl[22] *} 👉 💼, **FastAPI** 🔜 ⌛ 💪 💖: @@ -137,20 +112,13 @@ q: str | None = None 🖼: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004.py!} - ``` +{* ../../docs_src/body_multiple_params/tutorial004.py hl[27] *} -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// info - ```Python hl_lines="26" - {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} - ``` +`Body` ✔️ 🌐 🎏 ➕ 🔬 & 🗃 🔢 `Query`,`Path` & 🎏 👆 🔜 👀 ⏪. -!!! info - `Body` ✔️ 🌐 🎏 ➕ 🔬 & 🗃 🔢 `Query`,`Path` & 🎏 👆 🔜 👀 ⏪. +/// ## ⏯ 👁 💪 🔢 @@ -166,17 +134,7 @@ item: Item = Body(embed=True) : -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="15" - {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} - ``` +{* ../../docs_src/body_multiple_params/tutorial005.py hl[17] *} 👉 💼 **FastAPI** 🔜 ⌛ 💪 💖: diff --git a/docs/em/docs/tutorial/body-nested-models.md b/docs/em/docs/tutorial/body-nested-models.md index f4bd50f5c..6c8d5a610 100644 --- a/docs/em/docs/tutorial/body-nested-models.md +++ b/docs/em/docs/tutorial/body-nested-models.md @@ -6,17 +6,7 @@ 👆 💪 🔬 🔢 🏾. 🖼, 🐍 `list`: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial001.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} - ``` +{* ../../docs_src/body_nested_models/tutorial001.py hl[14] *} 👉 🔜 ⚒ `tags` 📇, 👐 ⚫️ 🚫 📣 🆎 🔣 📇. @@ -30,9 +20,7 @@ ✋️ 🐍 ⏬ ⏭ 3️⃣.9️⃣ (3️⃣.6️⃣ & 🔛), 👆 🥇 💪 🗄 `List` ⚪️➡️ 🐩 🐍 `typing` 🕹: -```Python hl_lines="1" -{!> ../../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *} ### 📣 `list` ⏮️ 🆎 🔢 @@ -61,23 +49,7 @@ my_list: List[str] , 👆 🖼, 👥 💪 ⚒ `tags` 🎯 "📇 🎻": -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial002.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} - ``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[14] *} ## ⚒ 🆎 @@ -87,23 +59,7 @@ my_list: List[str] ⤴️ 👥 💪 📣 `tags` ⚒ 🎻: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="1 14" - {!> ../../../docs_src/body_nested_models/tutorial003.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} - ``` +{* ../../docs_src/body_nested_models/tutorial003.py hl[1,14] *} ⏮️ 👉, 🚥 👆 📨 📨 ⏮️ ❎ 📊, ⚫️ 🔜 🗜 ⚒ 😍 🏬. @@ -125,45 +81,13 @@ my_list: List[str] 🖼, 👥 💪 🔬 `Image` 🏷: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="9-11" - {!> ../../../docs_src/body_nested_models/tutorial004.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="9-11" - {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="7-9" - {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} - ``` +{* ../../docs_src/body_nested_models/tutorial004.py hl[9:11] *} ### ⚙️ 📊 🆎 & ⤴️ 👥 💪 ⚙️ ⚫️ 🆎 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial004.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="18" - {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} - ``` +{* ../../docs_src/body_nested_models/tutorial004.py hl[20] *} 👉 🔜 ⛓ 👈 **FastAPI** 🔜 ⌛ 💪 🎏: @@ -192,27 +116,11 @@ my_list: List[str] ↖️ ⚪️➡️ 😐 ⭐ 🆎 💖 `str`, `int`, `float`, ♒️. 👆 💪 ⚙️ 🌅 🏗 ⭐ 🆎 👈 😖 ⚪️➡️ `str`. -👀 🌐 🎛 👆 ✔️, 🛒 🩺 Pydantic 😍 🆎. 👆 🔜 👀 🖼 ⏭ 📃. +👀 🌐 🎛 👆 ✔️, 🛒 🩺 Pydantic 😍 🆎. 👆 🔜 👀 🖼 ⏭ 📃. 🖼, `Image` 🏷 👥 ✔️ `url` 🏑, 👥 💪 📣 ⚫️ ↩️ `str`, Pydantic `HttpUrl`: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="4 10" - {!> ../../../docs_src/body_nested_models/tutorial005.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="4 10" - {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="2 8" - {!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} - ``` +{* ../../docs_src/body_nested_models/tutorial005.py hl[4,10] *} 🎻 🔜 ✅ ☑ 📛, & 📄 🎻 🔗 / 🗄 ✅. @@ -220,23 +128,7 @@ my_list: List[str] 👆 💪 ⚙️ Pydantic 🏷 🏾 `list`, `set`, ♒️: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial006.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="18" - {!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} - ``` +{* ../../docs_src/body_nested_models/tutorial006.py hl[20] *} 👉 🔜 ⌛ (🗜, ✔, 📄, ♒️) 🎻 💪 💖: @@ -264,33 +156,23 @@ my_list: List[str] } ``` -!!! info - 👀 ❔ `images` 🔑 🔜 ✔️ 📇 🖼 🎚. +/// info -## 🙇 🐦 🏷 +👀 ❔ `images` 🔑 🔜 ✔️ 📇 🖼 🎚. -👆 💪 🔬 🎲 🙇 🐦 🏷: +/// -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="9 14 20 23 27" - {!> ../../../docs_src/body_nested_models/tutorial007.py!} - ``` +## 🙇 🐦 🏷 -=== "🐍 3️⃣.9️⃣ & 🔛" +👆 💪 🔬 🎲 🙇 🐦 🏷: - ```Python hl_lines="9 14 20 23 27" - {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} - ``` +{* ../../docs_src/body_nested_models/tutorial007.py hl[9,14,20,23,27] *} -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// info - ```Python hl_lines="7 12 18 21 25" - {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} - ``` +👀 ❔ `Offer` ✔️ 📇 `Item`Ⓜ, ❔ 🔄 ✔️ 📦 📇 `Image`Ⓜ -!!! info - 👀 ❔ `Offer` ✔️ 📇 `Item`Ⓜ, ❔ 🔄 ✔️ 📦 📇 `Image`Ⓜ +/// ## 💪 😁 📇 @@ -308,17 +190,7 @@ images: list[Image] : -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="15" - {!> ../../../docs_src/body_nested_models/tutorial008.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="13" - {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} - ``` +{* ../../docs_src/body_nested_models/tutorial008.py hl[15] *} ## 👨‍🎨 🐕‍🦺 🌐 @@ -348,26 +220,19 @@ images: list[Image] 👉 💼, 👆 🔜 🚫 🙆 `dict` 📏 ⚫️ ✔️ `int` 🔑 ⏮️ `float` 💲: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="9" - {!> ../../../docs_src/body_nested_models/tutorial009.py!} - ``` +{* ../../docs_src/body_nested_models/tutorial009.py hl[9] *} -=== "🐍 3️⃣.9️⃣ & 🔛" +/// tip - ```Python hl_lines="7" - {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} - ``` +✔️ 🤯 👈 🎻 🕴 🐕‍🦺 `str` 🔑. -!!! tip - ✔️ 🤯 👈 🎻 🕴 🐕‍🦺 `str` 🔑. +✋️ Pydantic ✔️ 🏧 💽 🛠️. - ✋️ Pydantic ✔️ 🏧 💽 🛠️. +👉 ⛓ 👈, ✋️ 👆 🛠️ 👩‍💻 💪 🕴 📨 🎻 🔑, 📏 👈 🎻 🔌 😁 🔢, Pydantic 🔜 🗜 👫 & ✔ 👫. - 👉 ⛓ 👈, ✋️ 👆 🛠️ 👩‍💻 💪 🕴 📨 🎻 🔑, 📏 👈 🎻 🔌 😁 🔢, Pydantic 🔜 🗜 👫 & ✔ 👫. + & `dict` 👆 📨 `weights` 🔜 🤙 ✔️ `int` 🔑 & `float` 💲. - & `dict` 👆 📨 `weights` 🔜 🤙 ✔️ `int` 🔑 & `float` 💲. +/// ## 🌃 diff --git a/docs/em/docs/tutorial/body-updates.md b/docs/em/docs/tutorial/body-updates.md index 98058ab52..7e2fbfaf7 100644 --- a/docs/em/docs/tutorial/body-updates.md +++ b/docs/em/docs/tutorial/body-updates.md @@ -6,23 +6,7 @@ 👆 💪 ⚙️ `jsonable_encoder` 🗜 🔢 💽 📊 👈 💪 🏪 🎻 (✅ ⏮️ ☁ 💽). 🖼, 🏭 `datetime` `str`. -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="30-35" - {!> ../../../docs_src/body_updates/tutorial001.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="30-35" - {!> ../../../docs_src/body_updates/tutorial001_py39.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="28-33" - {!> ../../../docs_src/body_updates/tutorial001_py310.py!} - ``` +{* ../../docs_src/body_updates/tutorial001.py hl[30:35] *} `PUT` ⚙️ 📨 💽 👈 🔜 ❎ ♻ 💽. @@ -48,14 +32,17 @@ 👉 ⛓ 👈 👆 💪 📨 🕴 💽 👈 👆 💚 ℹ, 🍂 🎂 🐣. -!!! Note - `PATCH` 🌘 🛎 ⚙️ & 💭 🌘 `PUT`. +/// note - & 📚 🏉 ⚙️ 🕴 `PUT`, 🍕 ℹ. +`PATCH` 🌘 🛎 ⚙️ & 💭 🌘 `PUT`. - 👆 **🆓** ⚙️ 👫 👐 👆 💚, **FastAPI** 🚫 🚫 🙆 🚫. + & 📚 🏉 ⚙️ 🕴 `PUT`, 🍕 ℹ. - ✋️ 👉 🦮 🎦 👆, 🌖 ⚖️ 🌘, ❔ 👫 🎯 ⚙️. +👆 **🆓** ⚙️ 👫 👐 👆 💚, **FastAPI** 🚫 🚫 🙆 🚫. + +✋️ 👉 🦮 🎦 👆, 🌖 ⚖️ 🌘, ❔ 👫 🎯 ⚙️. + +/// ### ⚙️ Pydantic `exclude_unset` 🔢 @@ -67,23 +54,7 @@ ⤴️ 👆 💪 ⚙️ 👉 🏗 `dict` ⏮️ 🕴 💽 👈 ⚒ (📨 📨), 🚫 🔢 💲: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="34" - {!> ../../../docs_src/body_updates/tutorial002.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="34" - {!> ../../../docs_src/body_updates/tutorial002_py39.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="32" - {!> ../../../docs_src/body_updates/tutorial002_py310.py!} - ``` +{* ../../docs_src/body_updates/tutorial002.py hl[34] *} ### ⚙️ Pydantic `update` 🔢 @@ -91,23 +62,7 @@ 💖 `stored_item_model.copy(update=update_data)`: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="35" - {!> ../../../docs_src/body_updates/tutorial002.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="35" - {!> ../../../docs_src/body_updates/tutorial002_py39.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="33" - {!> ../../../docs_src/body_updates/tutorial002_py310.py!} - ``` +{* ../../docs_src/body_updates/tutorial002.py hl[35] *} ### 🍕 ℹ 🌃 @@ -124,32 +79,22 @@ * 🖊 💽 👆 💽. * 📨 ℹ 🏷. -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="30-37" - {!> ../../../docs_src/body_updates/tutorial002.py!} - ``` +{* ../../docs_src/body_updates/tutorial002.py hl[30:37] *} -=== "🐍 3️⃣.9️⃣ & 🔛" +/// tip - ```Python hl_lines="30-37" - {!> ../../../docs_src/body_updates/tutorial002_py39.py!} - ``` +👆 💪 🤙 ⚙️ 👉 🎏 ⚒ ⏮️ 🇺🇸🔍 `PUT` 🛠️. -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +✋️ 🖼 📥 ⚙️ `PATCH` ↩️ ⚫️ ✍ 👫 ⚙️ 💼. - ```Python hl_lines="28-35" - {!> ../../../docs_src/body_updates/tutorial002_py310.py!} - ``` +/// -!!! tip - 👆 💪 🤙 ⚙️ 👉 🎏 ⚒ ⏮️ 🇺🇸🔍 `PUT` 🛠️. +/// note - ✋️ 🖼 📥 ⚙️ `PATCH` ↩️ ⚫️ ✍ 👫 ⚙️ 💼. +👀 👈 🔢 🏷 ✔. -!!! note - 👀 👈 🔢 🏷 ✔. +, 🚥 👆 💚 📨 🍕 ℹ 👈 💪 🚫 🌐 🔢, 👆 💪 ✔️ 🏷 ⏮️ 🌐 🔢 ™ 📦 (⏮️ 🔢 💲 ⚖️ `None`). - , 🚥 👆 💚 📨 🍕 ℹ 👈 💪 🚫 🌐 🔢, 👆 💪 ✔️ 🏷 ⏮️ 🌐 🔢 ™ 📦 (⏮️ 🔢 💲 ⚖️ `None`). +🔬 ⚪️➡️ 🏷 ⏮️ 🌐 📦 💲 **ℹ** & 🏷 ⏮️ ✔ 💲 **🏗**, 👆 💪 ⚙️ 💭 🔬 [➕ 🏷](extra-models.md){.internal-link target=_blank}. - 🔬 ⚪️➡️ 🏷 ⏮️ 🌐 📦 💲 **ℹ** & 🏷 ⏮️ ✔ 💲 **🏗**, 👆 💪 ⚙️ 💭 🔬 [➕ 🏷](extra-models.md){.internal-link target=_blank}. +/// diff --git a/docs/em/docs/tutorial/body.md b/docs/em/docs/tutorial/body.md index ca2f113bf..09e1d7cca 100644 --- a/docs/em/docs/tutorial/body.md +++ b/docs/em/docs/tutorial/body.md @@ -6,30 +6,23 @@ 👆 🛠️ 🌖 🕧 ✔️ 📨 **📨** 💪. ✋️ 👩‍💻 🚫 🎯 💪 📨 **📨** 💪 🌐 🕰. -📣 **📨** 💪, 👆 ⚙️ Pydantic 🏷 ⏮️ 🌐 👫 🏋️ & 💰. +📣 **📨** 💪, 👆 ⚙️ Pydantic 🏷 ⏮️ 🌐 👫 🏋️ & 💰. -!!! info - 📨 💽, 👆 🔜 ⚙️ 1️⃣: `POST` (🌅 ⚠), `PUT`, `DELETE` ⚖️ `PATCH`. +/// info - 📨 💪 ⏮️ `GET` 📨 ✔️ ⚠ 🎭 🔧, 👐, ⚫️ 🐕‍🦺 FastAPI, 🕴 📶 🏗/😕 ⚙️ 💼. +📨 💽, 👆 🔜 ⚙️ 1️⃣: `POST` (🌅 ⚠), `PUT`, `DELETE` ⚖️ `PATCH`. - ⚫️ 🚫, 🎓 🩺 ⏮️ 🦁 🎚 🏆 🚫 🎦 🧾 💪 🕐❔ ⚙️ `GET`, & 🗳 🖕 💪 🚫 🐕‍🦺 ⚫️. +📨 💪 ⏮️ `GET` 📨 ✔️ ⚠ 🎭 🔧, 👐, ⚫️ 🐕‍🦺 FastAPI, 🕴 📶 🏗/😕 ⚙️ 💼. -## 🗄 Pydantic `BaseModel` - -🥇, 👆 💪 🗄 `BaseModel` ⚪️➡️ `pydantic`: +⚫️ 🚫, 🎓 🩺 ⏮️ 🦁 🎚 🏆 🚫 🎦 🧾 💪 🕐❔ ⚙️ `GET`, & 🗳 🖕 💪 🚫 🐕‍🦺 ⚫️. -=== "🐍 3️⃣.6️⃣ & 🔛" +/// - ```Python hl_lines="4" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +## 🗄 Pydantic `BaseModel` -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +🥇, 👆 💪 🗄 `BaseModel` ⚪️➡️ `pydantic`: - ```Python hl_lines="2" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +{* ../../docs_src/body/tutorial001.py hl[4] *} ## ✍ 👆 💽 🏷 @@ -37,17 +30,7 @@ ⚙️ 🐩 🐍 🆎 🌐 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="7-11" - {!> ../../../docs_src/body/tutorial001.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="5-9" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +{* ../../docs_src/body/tutorial001.py hl[7:11] *} 🎏 🕐❔ 📣 🔢 🔢, 🕐❔ 🏷 🔢 ✔️ 🔢 💲, ⚫️ 🚫 ✔. ⏪, ⚫️ ✔. ⚙️ `None` ⚒ ⚫️ 📦. @@ -75,17 +58,7 @@ 🚮 ⚫️ 👆 *➡ 🛠️*, 📣 ⚫️ 🎏 🌌 👆 📣 ➡ & 🔢 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial001.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +{* ../../docs_src/body/tutorial001.py hl[18] *} ...& 📣 🚮 🆎 🏷 👆 ✍, `Item`. @@ -134,32 +107,25 @@ -!!! tip - 🚥 👆 ⚙️ 🗒 👆 👨‍🎨, 👆 💪 ⚙️ Pydantic 🗒 📁. - - ⚫️ 📉 👨‍🎨 🐕‍🦺 Pydantic 🏷, ⏮️: +/// tip - * 🚘-🛠️ - * 🆎 ✅ - * 🛠️ - * 🔎 - * 🔬 +🚥 👆 ⚙️ 🗒 👆 👨‍🎨, 👆 💪 ⚙️ Pydantic 🗒 📁. -## ⚙️ 🏷 +⚫️ 📉 👨‍🎨 🐕‍🦺 Pydantic 🏷, ⏮️: -🔘 🔢, 👆 💪 🔐 🌐 🔢 🏷 🎚 🔗: +* 🚘-🛠️ +* 🆎 ✅ +* 🛠️ +* 🔎 +* 🔬 -=== "🐍 3️⃣.6️⃣ & 🔛" +/// - ```Python hl_lines="21" - {!> ../../../docs_src/body/tutorial002.py!} - ``` +## ⚙️ 🏷 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +🔘 🔢, 👆 💪 🔐 🌐 🔢 🏷 🎚 🔗: - ```Python hl_lines="19" - {!> ../../../docs_src/body/tutorial002_py310.py!} - ``` +{* ../../docs_src/body/tutorial002.py hl[21] *} ## 📨 💪 ➕ ➡ 🔢 @@ -167,17 +133,7 @@ **FastAPI** 🔜 🤔 👈 🔢 🔢 👈 🏏 ➡ 🔢 🔜 **✊ ⚪️➡️ ➡**, & 👈 🔢 🔢 👈 📣 Pydantic 🏷 🔜 **✊ ⚪️➡️ 📨 💪**. -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="17-18" - {!> ../../../docs_src/body/tutorial003.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="15-16" - {!> ../../../docs_src/body/tutorial003_py310.py!} - ``` +{* ../../docs_src/body/tutorial003.py hl[17:18] *} ## 📨 💪 ➕ ➡ ➕ 🔢 🔢 @@ -185,17 +141,7 @@ **FastAPI** 🔜 🤔 🔠 👫 & ✊ 📊 ⚪️➡️ ☑ 🥉. -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial004.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial004_py310.py!} - ``` +{* ../../docs_src/body/tutorial004.py hl[18] *} 🔢 🔢 🔜 🤔 ⏩: @@ -203,11 +149,14 @@ * 🚥 🔢 **⭐ 🆎** (💖 `int`, `float`, `str`, `bool`, ♒️) ⚫️ 🔜 🔬 **🔢** 🔢. * 🚥 🔢 📣 🆎 **Pydantic 🏷**, ⚫️ 🔜 🔬 📨 **💪**. -!!! note - FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`. +/// note + +FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`. + + `Union` `Union[str, None]` 🚫 ⚙️ FastAPI, ✋️ 🔜 ✔ 👆 👨‍🎨 🤝 👆 👍 🐕‍🦺 & 🔍 ❌. - `Union` `Union[str, None]` 🚫 ⚙️ FastAPI, ✋️ 🔜 ✔ 👆 👨‍🎨 🤝 👆 👍 🐕‍🦺 & 🔍 ❌. +/// ## 🍵 Pydantic -🚥 👆 🚫 💚 ⚙️ Pydantic 🏷, 👆 💪 ⚙️ **💪** 🔢. 👀 🩺 [💪 - 💗 🔢: ⭐ 💲 💪](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}. +🚥 👆 🚫 💚 ⚙️ Pydantic 🏷, 👆 💪 ⚙️ **💪** 🔢. 👀 🩺 [💪 - 💗 🔢: ⭐ 💲 💪](body-multiple-params.md#_2){.internal-link target=_blank}. diff --git a/docs/em/docs/tutorial/cookie-params.md b/docs/em/docs/tutorial/cookie-params.md index 47f4a62f5..4699fe2a5 100644 --- a/docs/em/docs/tutorial/cookie-params.md +++ b/docs/em/docs/tutorial/cookie-params.md @@ -6,17 +6,7 @@ 🥇 🗄 `Cookie`: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="1" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +{* ../../docs_src/cookie_params/tutorial001.py hl[3] *} ## 📣 `Cookie` 🔢 @@ -24,25 +14,21 @@ 🥇 💲 🔢 💲, 👆 💪 🚶‍♀️ 🌐 ➕ 🔬 ⚖️ ✍ 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" +{* ../../docs_src/cookie_params/tutorial001.py hl[9] *} + +/// note | 📡 ℹ - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +`Cookie` "👭" 🎓 `Path` & `Query`. ⚫️ 😖 ⚪️➡️ 🎏 ⚠ `Param` 🎓. -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `Cookie` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. - ```Python hl_lines="7" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +/// -!!! note "📡 ℹ" - `Cookie` "👭" 🎓 `Path` & `Query`. ⚫️ 😖 ⚪️➡️ 🎏 ⚠ `Param` 🎓. +/// info - ✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `Cookie` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. +📣 🍪, 👆 💪 ⚙️ `Cookie`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢. -!!! info - 📣 🍪, 👆 💪 ⚙️ `Cookie`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢. +/// ## 🌃 diff --git a/docs/em/docs/tutorial/cors.md b/docs/em/docs/tutorial/cors.md index 8c5e33ed7..44ab4adc5 100644 --- a/docs/em/docs/tutorial/cors.md +++ b/docs/em/docs/tutorial/cors.md @@ -46,9 +46,7 @@ * 🎯 🇺🇸🔍 👩‍🔬 (`POST`, `PUT`) ⚖️ 🌐 👫 ⏮️ 🃏 `"*"`. * 🎯 🇺🇸🔍 🎚 ⚖️ 🌐 👫 ⏮️ 🃏 `"*"`. -```Python hl_lines="2 6-11 13-19" -{!../../../docs_src/cors/tutorial001.py!} -``` +{* ../../docs_src/cors/tutorial001.py hl[2,6:11,13:19] *} 🔢 🔢 ⚙️ `CORSMiddleware` 🛠️ 🚫 🔢, 👆 🔜 💪 🎯 🛠️ 🎯 🇨🇳, 👩‍🔬, ⚖️ 🎚, ✔ 🖥 ✔ ⚙️ 👫 ✖️-🆔 🔑. @@ -78,7 +76,10 @@ 🌖 ℹ 🔃 , ✅ 🦎 ⚜ 🧾. -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.middleware.cors import CORSMiddleware`. +/// note | 📡 ℹ - **FastAPI** 🚚 📚 🛠️ `fastapi.middleware` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 🛠️ 👟 🔗 ⚪️➡️ 💃. +👆 💪 ⚙️ `from starlette.middleware.cors import CORSMiddleware`. + +**FastAPI** 🚚 📚 🛠️ `fastapi.middleware` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 🛠️ 👟 🔗 ⚪️➡️ 💃. + +/// diff --git a/docs/em/docs/tutorial/debugging.md b/docs/em/docs/tutorial/debugging.md index c7c11b5ce..97e61a763 100644 --- a/docs/em/docs/tutorial/debugging.md +++ b/docs/em/docs/tutorial/debugging.md @@ -6,9 +6,7 @@ 👆 FastAPI 🈸, 🗄 & 🏃 `uvicorn` 🔗: -```Python hl_lines="1 15" -{!../../../docs_src/debugging/tutorial001.py!} -``` +{* ../../docs_src/debugging/tutorial001.py hl[1,15] *} ### 🔃 `__name__ == "__main__"` @@ -74,8 +72,11 @@ from myapp import app 🔜 🚫 🛠️. -!!! info - 🌅 ℹ, ✅ 🛂 🐍 🩺. +/// info + +🌅 ℹ, ✅ 🛂 🐍 🩺. + +/// ## 🏃 👆 📟 ⏮️ 👆 🕹 diff --git a/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md index e2d2686d3..41938bc7b 100644 --- a/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/em/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,17 +6,7 @@ ⏮️ 🖼, 👥 🛬 `dict` ⚪️➡️ 👆 🔗 ("☑"): -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +{* ../../docs_src/dependencies/tutorial001.py hl[9] *} ✋️ ⤴️ 👥 🤚 `dict` 🔢 `commons` *➡ 🛠️ 🔢*. @@ -79,45 +69,15 @@ fluffy = Cat(name="Mr Fluffy") ⤴️, 👥 💪 🔀 🔗 "☑" `common_parameters` ⚪️➡️ 🔛 🎓 `CommonQueryParams`: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="9-13" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +{* ../../docs_src/dependencies/tutorial002.py hl[11:15] *} 💸 🙋 `__init__` 👩‍🔬 ⚙️ ✍ 👐 🎓: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +{* ../../docs_src/dependencies/tutorial002.py hl[12] *} ...⚫️ ✔️ 🎏 🔢 👆 ⏮️ `common_parameters`: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="6" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +{* ../../docs_src/dependencies/tutorial001.py hl[9] *} 📚 🔢 ⚫️❔ **FastAPI** 🔜 ⚙️ "❎" 🔗. @@ -133,17 +93,7 @@ fluffy = Cat(name="Mr Fluffy") 🔜 👆 💪 📣 👆 🔗 ⚙️ 👉 🎓. -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +{* ../../docs_src/dependencies/tutorial002.py hl[19] *} **FastAPI** 🤙 `CommonQueryParams` 🎓. 👉 ✍ "👐" 👈 🎓 & 👐 🔜 🚶‍♀️ 🔢 `commons` 👆 🔢. @@ -183,17 +133,7 @@ commons = Depends(CommonQueryParams) ...: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial003_py310.py!} - ``` +{* ../../docs_src/dependencies/tutorial003.py hl[19] *} ✋️ 📣 🆎 💡 👈 🌌 👆 👨‍🎨 🔜 💭 ⚫️❔ 🔜 🚶‍♀️ 🔢 `commons`, & ⤴️ ⚫️ 💪 ℹ 👆 ⏮️ 📟 🛠️, 🆎 ✅, ♒️: @@ -227,21 +167,14 @@ commons: CommonQueryParams = Depends() 🎏 🖼 🔜 ⤴️ 👀 💖: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004.py!} - ``` +{* ../../docs_src/dependencies/tutorial004.py hl[19] *} -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +...& **FastAPI** 🔜 💭 ⚫️❔. - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial004_py310.py!} - ``` +/// tip -...& **FastAPI** 🔜 💭 ⚫️❔. +🚥 👈 😑 🌅 😨 🌘 👍, 🤷‍♂ ⚫️, 👆 🚫 *💪* ⚫️. -!!! tip - 🚥 👈 😑 🌅 😨 🌘 👍, 🤷‍♂ ⚫️, 👆 🚫 *💪* ⚫️. +⚫️ ⌨. ↩️ **FastAPI** 💅 🔃 🤝 👆 📉 📟 🔁. - ⚫️ ⌨. ↩️ **FastAPI** 💅 🔃 🤝 👆 📉 📟 🔁. +/// diff --git a/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 4d54b91c7..ab144a497 100644 --- a/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/em/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -14,23 +14,27 @@ ⚫️ 🔜 `list` `Depends()`: -```Python hl_lines="17" -{!../../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[17] *} 👉 🔗 🔜 🛠️/❎ 🎏 🌌 😐 🔗. ✋️ 👫 💲 (🚥 👫 📨 🙆) 🏆 🚫 🚶‍♀️ 👆 *➡ 🛠️ 🔢*. -!!! tip - 👨‍🎨 ✅ ♻ 🔢 🔢, & 🎦 👫 ❌. +/// tip - ⚙️ 👉 `dependencies` *➡ 🛠️ 👨‍🎨* 👆 💪 ⚒ 💭 👫 🛠️ ⏪ ❎ 👨‍🎨/🏭 ❌. +👨‍🎨 ✅ ♻ 🔢 🔢, & 🎦 👫 ❌. - ⚫️ 💪 ℹ ❎ 😨 🆕 👩‍💻 👈 👀 ♻ 🔢 👆 📟 & 💪 💭 ⚫️ 🙃. +⚙️ 👉 `dependencies` *➡ 🛠️ 👨‍🎨* 👆 💪 ⚒ 💭 👫 🛠️ ⏪ ❎ 👨‍🎨/🏭 ❌. -!!! info - 👉 🖼 👥 ⚙️ 💭 🛃 🎚 `X-Key` & `X-Token`. +⚫️ 💪 ℹ ❎ 😨 🆕 👩‍💻 👈 👀 ♻ 🔢 👆 📟 & 💪 💭 ⚫️ 🙃. - ✋️ 🎰 💼, 🕐❔ 🛠️ 💂‍♂, 👆 🔜 🤚 🌖 💰 ⚪️➡️ ⚙️ 🛠️ [💂‍♂ 🚙 (⏭ 📃)](../security/index.md){.internal-link target=_blank}. +/// + +/// info + +👉 🖼 👥 ⚙️ 💭 🛃 🎚 `X-Key` & `X-Token`. + +✋️ 🎰 💼, 🕐❔ 🛠️ 💂‍♂, 👆 🔜 🤚 🌖 💰 ⚪️➡️ ⚙️ 🛠️ [💂‍♂ 🚙 (⏭ 📃)](../security/index.md){.internal-link target=_blank}. + +/// ## 🔗 ❌ & 📨 💲 @@ -40,17 +44,13 @@ 👫 💪 📣 📨 📄 (💖 🎚) ⚖️ 🎏 🎧-🔗: -```Python hl_lines="6 11" -{!../../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[6,11] *} ### 🤚 ⚠ 👫 🔗 💪 `raise` ⚠, 🎏 😐 🔗: -```Python hl_lines="8 13" -{!../../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[8,13] *} ### 📨 💲 @@ -58,9 +58,7 @@ , 👆 💪 🏤-⚙️ 😐 🔗 (👈 📨 💲) 👆 ⏪ ⚙️ 👱 🙆, & ✋️ 💲 🏆 🚫 ⚙️, 🔗 🔜 🛠️: -```Python hl_lines="9 14" -{!../../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[9,14] *} ## 🔗 👪 *➡ 🛠️* diff --git a/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md index 9617667f4..1b37b1cf2 100644 --- a/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/em/docs/tutorial/dependencies/dependencies-with-yield.md @@ -4,18 +4,24 @@ FastAPI 🐕‍🦺 🔗 👈 🔑 👨‍💼. +/// note | 📡 ℹ + +👉 👷 👏 🐍 🔑 👨‍💼. - **FastAPI** ⚙️ 👫 🔘 🏆 👉. +**FastAPI** ⚙️ 👫 🔘 🏆 👉. + +/// ## 🔗 ⏮️ `yield` & `HTTPException` @@ -99,7 +99,7 @@ FastAPI 🐕‍🦺 🔗 👈 🏗 🎓 ⏮️ 2️⃣ 👩‍🔬: `__enter__()` & `__exit__()`. 👆 💪 ⚙️ 👫 🔘 **FastAPI** 🔗 ⏮️ `yield` ⚙️ `with` ⚖️ `async with` 📄 🔘 🔗 🔢: -```Python hl_lines="1-9 13" -{!../../../docs_src/dependencies/tutorial010.py!} -``` +{* ../../docs_src/dependencies/tutorial010.py hl[1:9,13] *} + +/// tip + +➕1️⃣ 🌌 ✍ 🔑 👨‍💼 ⏮️: -!!! tip - ➕1️⃣ 🌌 ✍ 🔑 👨‍💼 ⏮️: +* `@contextlib.contextmanager` ⚖️ +* `@contextlib.asynccontextmanager` - * `@contextlib.contextmanager` ⚖️ - * `@contextlib.asynccontextmanager` +⚙️ 👫 🎀 🔢 ⏮️ 👁 `yield`. - ⚙️ 👫 🎀 🔢 ⏮️ 👁 `yield`. +👈 ⚫️❔ **FastAPI** ⚙️ 🔘 🔗 ⏮️ `yield`. - 👈 ⚫️❔ **FastAPI** ⚙️ 🔘 🔗 ⏮️ `yield`. +✋️ 👆 🚫 ✔️ ⚙️ 👨‍🎨 FastAPI 🔗 (& 👆 🚫🔜 🚫). - ✋️ 👆 🚫 ✔️ ⚙️ 👨‍🎨 FastAPI 🔗 (& 👆 🚫🔜 🚫). +FastAPI 🔜 ⚫️ 👆 🔘. - FastAPI 🔜 ⚫️ 👆 🔘. +/// diff --git a/docs/em/docs/tutorial/dependencies/global-dependencies.md b/docs/em/docs/tutorial/dependencies/global-dependencies.md index 81759d0e8..5a22e5f1c 100644 --- a/docs/em/docs/tutorial/dependencies/global-dependencies.md +++ b/docs/em/docs/tutorial/dependencies/global-dependencies.md @@ -6,9 +6,7 @@ 👈 💼, 👫 🔜 ✔ 🌐 *➡ 🛠️* 🈸: -```Python hl_lines="15" -{!../../../docs_src/dependencies/tutorial012.py!} -``` +{* ../../docs_src/dependencies/tutorial012.py hl[15] *} & 🌐 💭 📄 🔃 [❎ `dependencies` *➡ 🛠️ 👨‍🎨*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} ✔, ✋️ 👉 💼, 🌐 *➡ 🛠️* 📱. diff --git a/docs/em/docs/tutorial/dependencies/index.md b/docs/em/docs/tutorial/dependencies/index.md index ffd38d716..ce87d9ee4 100644 --- a/docs/em/docs/tutorial/dependencies/index.md +++ b/docs/em/docs/tutorial/dependencies/index.md @@ -31,17 +31,7 @@ ⚫️ 🔢 👈 💪 ✊ 🌐 🎏 🔢 👈 *➡ 🛠️ 🔢* 💪 ✊: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="8-11" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="6-7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +{* ../../docs_src/dependencies/tutorial001.py hl[8:11] *} 👈 ⚫️. @@ -63,33 +53,13 @@ ### 🗄 `Depends` -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="3" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="1" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +{* ../../docs_src/dependencies/tutorial001.py hl[3] *} ### 📣 🔗, "⚓️" 🎏 🌌 👆 ⚙️ `Body`, `Query`, ♒️. ⏮️ 👆 *➡ 🛠️ 🔢* 🔢, ⚙️ `Depends` ⏮️ 🆕 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="15 20" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="11 16" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +{* ../../docs_src/dependencies/tutorial001.py hl[15,20] *} 👐 👆 ⚙️ `Depends` 🔢 👆 🔢 🎏 🌌 👆 ⚙️ `Body`, `Query`, ♒️, `Depends` 👷 👄 🎏. @@ -99,8 +69,11 @@ & 👈 🔢 ✊ 🔢 🎏 🌌 👈 *➡ 🛠️ 🔢* . -!!! tip - 👆 🔜 👀 ⚫️❔ 🎏 "👜", ↖️ ⚪️➡️ 🔢, 💪 ⚙️ 🔗 ⏭ 📃. +/// tip + +👆 🔜 👀 ⚫️❔ 🎏 "👜", ↖️ ⚪️➡️ 🔢, 💪 ⚙️ 🔗 ⏭ 📃. + +/// 🕐❔ 🆕 📨 🛬, **FastAPI** 🔜 ✊ 💅: @@ -121,10 +94,13 @@ common_parameters --> read_users 👉 🌌 👆 ✍ 🔗 📟 🕐 & **FastAPI** ✊ 💅 🤙 ⚫️ 👆 *➡ 🛠️*. -!!! check - 👀 👈 👆 🚫 ✔️ ✍ 🎁 🎓 & 🚶‍♀️ ⚫️ 👱 **FastAPI** "®" ⚫️ ⚖️ 🕳 🎏. +/// check + +👀 👈 👆 🚫 ✔️ ✍ 🎁 🎓 & 🚶‍♀️ ⚫️ 👱 **FastAPI** "®" ⚫️ ⚖️ 🕳 🎏. - 👆 🚶‍♀️ ⚫️ `Depends` & **FastAPI** 💭 ❔ 🎂. +👆 🚶‍♀️ ⚫️ `Depends` & **FastAPI** 💭 ❔ 🎂. + +/// ## `async` ⚖️ 🚫 `async` @@ -136,8 +112,11 @@ common_parameters --> read_users ⚫️ 🚫 🤔. **FastAPI** 🔜 💭 ⚫️❔. -!!! note - 🚥 👆 🚫 💭, ✅ [🔁: *"🏃 ❓" *](../../async.md){.internal-link target=_blank} 📄 🔃 `async` & `await` 🩺. +/// note + +🚥 👆 🚫 💭, ✅ [🔁: *"🏃 ❓" *](../../async.md){.internal-link target=_blank} 📄 🔃 `async` & `await` 🩺. + +/// ## 🛠️ ⏮️ 🗄 diff --git a/docs/em/docs/tutorial/dependencies/sub-dependencies.md b/docs/em/docs/tutorial/dependencies/sub-dependencies.md index 454ff5129..6d622e952 100644 --- a/docs/em/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/em/docs/tutorial/dependencies/sub-dependencies.md @@ -10,17 +10,7 @@ 👆 💪 ✍ 🥇 🔗 ("☑") 💖: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="8-9" - {!> ../../../docs_src/dependencies/tutorial005.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="6-7" - {!> ../../../docs_src/dependencies/tutorial005_py310.py!} - ``` +{* ../../docs_src/dependencies/tutorial005.py hl[8:9] *} ⚫️ 📣 📦 🔢 🔢 `q` `str`, & ⤴️ ⚫️ 📨 ⚫️. @@ -30,17 +20,7 @@ ⤴️ 👆 💪 ✍ ➕1️⃣ 🔗 🔢 ("☑") 👈 🎏 🕰 📣 🔗 🚮 👍 (⚫️ "⚓️" 💁‍♂️): -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="13" - {!> ../../../docs_src/dependencies/tutorial005.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial005_py310.py!} - ``` +{* ../../docs_src/dependencies/tutorial005.py hl[13] *} ➡️ 🎯 🔛 🔢 📣: @@ -53,22 +33,15 @@ ⤴️ 👥 💪 ⚙️ 🔗 ⏮️: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="22" - {!> ../../../docs_src/dependencies/tutorial005.py!} - ``` +{* ../../docs_src/dependencies/tutorial005.py hl[22] *} -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// info - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial005_py310.py!} - ``` +👀 👈 👥 🕴 📣 1️⃣ 🔗 *➡ 🛠️ 🔢*, `query_or_cookie_extractor`. -!!! info - 👀 👈 👥 🕴 📣 1️⃣ 🔗 *➡ 🛠️ 🔢*, `query_or_cookie_extractor`. +✋️ **FastAPI** 🔜 💭 👈 ⚫️ ✔️ ❎ `query_extractor` 🥇, 🚶‍♀️ 🏁 👈 `query_or_cookie_extractor` ⏪ 🤙 ⚫️. - ✋️ **FastAPI** 🔜 💭 👈 ⚫️ ✔️ ❎ `query_extractor` 🥇, 🚶‍♀️ 🏁 👈 `query_or_cookie_extractor` ⏪ 🤙 ⚫️. +/// ```mermaid graph TB @@ -102,9 +75,12 @@ async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False ✋️, ⚫️ 📶 🏋️, & ✔ 👆 📣 🎲 🙇 🐦 🔗 "📊" (🌲). -!!! tip - 🌐 👉 💪 🚫 😑 ⚠ ⏮️ 👫 🙅 🖼. +/// tip + +🌐 👉 💪 🚫 😑 ⚠ ⏮️ 👫 🙅 🖼. + +✋️ 👆 🔜 👀 ❔ ⚠ ⚫️ 📃 🔃 **💂‍♂**. - ✋️ 👆 🔜 👀 ❔ ⚠ ⚫️ 📃 🔃 **💂‍♂**. + & 👆 🔜 👀 💸 📟 ⚫️ 🔜 🖊 👆. - & 👆 🔜 👀 💸 📟 ⚫️ 🔜 🖊 👆. +/// diff --git a/docs/em/docs/tutorial/encoder.md b/docs/em/docs/tutorial/encoder.md index 75ca3824d..ad05f701e 100644 --- a/docs/em/docs/tutorial/encoder.md +++ b/docs/em/docs/tutorial/encoder.md @@ -20,17 +20,7 @@ ⚫️ 📨 🎚, 💖 Pydantic 🏷, & 📨 🎻 🔗 ⏬: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="5 22" - {!> ../../../docs_src/encoder/tutorial001.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="4 21" - {!> ../../../docs_src/encoder/tutorial001_py310.py!} - ``` +{* ../../docs_src/encoder/tutorial001.py hl[5,22] *} 👉 🖼, ⚫️ 🔜 🗜 Pydantic 🏷 `dict`, & `datetime` `str`. @@ -38,5 +28,8 @@ ⚫️ 🚫 📨 ⭕ `str` ⚗ 💽 🎻 📁 (🎻). ⚫️ 📨 🐍 🐩 💽 📊 (✅ `dict`) ⏮️ 💲 & 🎧-💲 👈 🌐 🔗 ⏮️ 🎻. -!!! note - `jsonable_encoder` 🤙 ⚙️ **FastAPI** 🔘 🗜 💽. ✋️ ⚫️ ⚠ 📚 🎏 😐. +/// note + +`jsonable_encoder` 🤙 ⚙️ **FastAPI** 🔘 🗜 💽. ✋️ ⚫️ ⚠ 📚 🎏 😐. + +/// diff --git a/docs/em/docs/tutorial/extra-data-types.md b/docs/em/docs/tutorial/extra-data-types.md index dfdf6141b..f15a74b4a 100644 --- a/docs/em/docs/tutorial/extra-data-types.md +++ b/docs/em/docs/tutorial/extra-data-types.md @@ -36,7 +36,7 @@ * `datetime.timedelta`: * 🐍 `datetime.timedelta`. * 📨 & 📨 🔜 🎨 `float` 🌐 🥈. - * Pydantic ✔ 🎦 ⚫️ "💾 8️⃣6️⃣0️⃣1️⃣ 🕰 ➕ 🔢", 👀 🩺 🌅 ℹ. + * Pydantic ✔ 🎦 ⚫️ "💾 8️⃣6️⃣0️⃣1️⃣ 🕰 ➕ 🔢", 👀 🩺 🌅 ℹ. * `frozenset`: * 📨 & 📨, 😥 🎏 `set`: * 📨, 📇 🔜 ✍, ❎ ❎ & 🏭 ⚫️ `set`. @@ -49,34 +49,14 @@ * `Decimal`: * 🐩 🐍 `Decimal`. * 📨 & 📨, 🍵 🎏 `float`. -* 👆 💪 ✅ 🌐 ☑ Pydantic 📊 🆎 📥: Pydantic 📊 🆎. +* 👆 💪 ✅ 🌐 ☑ Pydantic 📊 🆎 📥: Pydantic 📊 🆎. ## 🖼 📥 🖼 *➡ 🛠️* ⏮️ 🔢 ⚙️ 🔛 🆎. -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="1 2 11-15" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +{* ../../docs_src/extra_data_types/tutorial001.py hl[1,3,12:16] *} 🗒 👈 🔢 🔘 🔢 ✔️ 👫 🐠 💽 🆎, & 👆 💪, 🖼, 🎭 😐 📅 🎭, 💖: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="17-18" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +{* ../../docs_src/extra_data_types/tutorial001.py hl[18:19] *} diff --git a/docs/em/docs/tutorial/extra-models.md b/docs/em/docs/tutorial/extra-models.md index 06c36285d..19ab5b798 100644 --- a/docs/em/docs/tutorial/extra-models.md +++ b/docs/em/docs/tutorial/extra-models.md @@ -8,26 +8,19 @@ * **🔢 🏷** 🔜 🚫 ✔️ 🔐. * **💽 🏷** 🔜 🎲 💪 ✔️ #️⃣ 🔐. -!!! danger - 🙅 🏪 👩‍💻 🔢 🔐. 🕧 🏪 "🔐 #️⃣" 👈 👆 💪 ⤴️ ✔. +/// danger - 🚥 👆 🚫 💭, 👆 🔜 💡 ⚫️❔ "🔐#️⃣" [💂‍♂ 📃](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}. +🙅 🏪 👩‍💻 🔢 🔐. 🕧 🏪 "🔐 #️⃣" 👈 👆 💪 ⤴️ ✔. -## 💗 🏷 - -📥 🏢 💭 ❔ 🏷 💪 👀 💖 ⏮️ 👫 🔐 🏑 & 🥉 🌐❔ 👫 ⚙️: +🚥 👆 🚫 💭, 👆 🔜 💡 ⚫️❔ "🔐#️⃣" [💂‍♂ 📃](security/simple-oauth2.md#_4){.internal-link target=_blank}. -=== "🐍 3️⃣.6️⃣ & 🔛" +/// - ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" - {!> ../../../docs_src/extra_models/tutorial001.py!} - ``` +## 💗 🏷 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +📥 🏢 💭 ❔ 🏷 💪 👀 💖 ⏮️ 👫 🔐 🏑 & 🥉 🌐❔ 👫 ⚙️: - ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" - {!> ../../../docs_src/extra_models/tutorial001_py310.py!} - ``` +{* ../../docs_src/extra_models/tutorial001.py hl[9,11,16,22,24,29:30,33:35,40:41] *} ### 🔃 `**user_in.dict()` @@ -139,8 +132,11 @@ UserInDB( ) ``` -!!! warning - 🔗 🌖 🔢 🤖 💪 💧 💽, ✋️ 👫 ↗️ 🚫 🚚 🙆 🎰 💂‍♂. +/// warning + +🔗 🌖 🔢 🤖 💪 💧 💽, ✋️ 👫 ↗️ 🚫 🚚 🙆 🎰 💂‍♂. + +/// ## 📉 ❎ @@ -158,17 +154,7 @@ UserInDB( 👈 🌌, 👥 💪 📣 🔺 🖖 🏷 (⏮️ 🔢 `password`, ⏮️ `hashed_password` & 🍵 🔐): -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="9 15-16 19-20 23-24" - {!> ../../../docs_src/extra_models/tutorial002.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="7 13-14 17-18 21-22" - {!> ../../../docs_src/extra_models/tutorial002_py310.py!} - ``` +{* ../../docs_src/extra_models/tutorial002.py hl[9,15:16,19:20,23:24] *} ## `Union` ⚖️ `anyOf` @@ -178,20 +164,13 @@ UserInDB( 👈, ⚙️ 🐩 🐍 🆎 🔑 `typing.Union`: -!!! note - 🕐❔ ⚖ `Union`, 🔌 🏆 🎯 🆎 🥇, ⏩ 🌘 🎯 🆎. 🖼 🔛, 🌖 🎯 `PlaneItem` 👟 ⏭ `CarItem` `Union[PlaneItem, CarItem]`. - -=== "🐍 3️⃣.6️⃣ & 🔛" +/// note - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003.py!} - ``` +🕐❔ ⚖ `Union`, 🔌 🏆 🎯 🆎 🥇, ⏩ 🌘 🎯 🆎. 🖼 🔛, 🌖 🎯 `PlaneItem` 👟 ⏭ `CarItem` `Union[PlaneItem, CarItem]`. -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003_py310.py!} - ``` +{* ../../docs_src/extra_models/tutorial003.py hl[1,14:15,18:20,33] *} ### `Union` 🐍 3️⃣.1️⃣0️⃣ @@ -213,17 +192,7 @@ some_variable: PlaneItem | CarItem 👈, ⚙️ 🐩 🐍 `typing.List` (⚖️ `list` 🐍 3️⃣.9️⃣ & 🔛): -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="1 20" - {!> ../../../docs_src/extra_models/tutorial004.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="18" - {!> ../../../docs_src/extra_models/tutorial004_py39.py!} - ``` +{* ../../docs_src/extra_models/tutorial004.py hl[1,20] *} ## 📨 ⏮️ ❌ `dict` @@ -233,17 +202,7 @@ some_variable: PlaneItem | CarItem 👉 💼, 👆 💪 ⚙️ `typing.Dict` (⚖️ `dict` 🐍 3️⃣.9️⃣ & 🔛): -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="1 8" - {!> ../../../docs_src/extra_models/tutorial005.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="6" - {!> ../../../docs_src/extra_models/tutorial005_py39.py!} - ``` +{* ../../docs_src/extra_models/tutorial005.py hl[1,8] *} ## 🌃 diff --git a/docs/em/docs/tutorial/first-steps.md b/docs/em/docs/tutorial/first-steps.md index 252e769f4..a8f936b01 100644 --- a/docs/em/docs/tutorial/first-steps.md +++ b/docs/em/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ 🙅 FastAPI 📁 💪 👀 💖 👉: -```Python -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} 📁 👈 📁 `main.py`. @@ -24,12 +22,15 @@ $ uvicorn main:app --reload
-!!! note - 📋 `uvicorn main:app` 🔗: +/// note + +📋 `uvicorn main:app` 🔗: + +* `main`: 📁 `main.py` (🐍 "🕹"). +* `app`: 🎚 ✍ 🔘 `main.py` ⏮️ ⏸ `app = FastAPI()`. +* `--reload`: ⚒ 💽 ⏏ ⏮️ 📟 🔀. 🕴 ⚙️ 🛠️. - * `main`: 📁 `main.py` (🐍 "🕹"). - * `app`: 🎚 ✍ 🔘 `main.py` ⏮️ ⏸ `app = FastAPI()`. - * `--reload`: ⚒ 💽 ⏏ ⏮️ 📟 🔀. 🕴 ⚙️ 🛠️. +/// 🔢, 📤 ⏸ ⏮️ 🕳 💖: @@ -130,22 +131,21 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ### 🔁 1️⃣: 🗄 `FastAPI` -```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI` 🐍 🎓 👈 🚚 🌐 🛠️ 👆 🛠️. -!!! note "📡 ℹ" - `FastAPI` 🎓 👈 😖 🔗 ⚪️➡️ `Starlette`. +/// note | 📡 ℹ + +`FastAPI` 🎓 👈 😖 🔗 ⚪️➡️ `Starlette`. - 👆 💪 ⚙️ 🌐 💃 🛠️ ⏮️ `FastAPI` 💁‍♂️. +👆 💪 ⚙️ 🌐 💃 🛠️ ⏮️ `FastAPI` 💁‍♂️. + +/// ### 🔁 2️⃣: ✍ `FastAPI` "👐" -```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[3] *} 📥 `app` 🔢 🔜 "👐" 🎓 `FastAPI`. @@ -165,9 +165,7 @@ $ uvicorn main:app --reload 🚥 👆 ✍ 👆 📱 💖: -```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} -``` +{* ../../docs_src/first_steps/tutorial002.py hl[3] *} & 🚮 ⚫️ 📁 `main.py`, ⤴️ 👆 🔜 🤙 `uvicorn` 💖: @@ -199,8 +197,11 @@ https://example.com/items/foo /items/foo ``` -!!! info - "➡" 🛎 🤙 "🔗" ⚖️ "🛣". +/// info + +"➡" 🛎 🤙 "🔗" ⚖️ "🛣". + +/// ⏪ 🏗 🛠️, "➡" 👑 🌌 🎏 "⚠" & "ℹ". @@ -241,25 +242,26 @@ https://example.com/items/foo #### 🔬 *➡ 🛠️ 👨‍🎨* -```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[6] *} `@app.get("/")` 💬 **FastAPI** 👈 🔢 ▶️️ 🔛 🈚 🚚 📨 👈 🚶: * ➡ `/` * ⚙️ get 🛠️ -!!! info "`@decorator` ℹ" - 👈 `@something` ❕ 🐍 🤙 "👨‍🎨". +/// info | `@decorator` ℹ + +👈 `@something` ❕ 🐍 🤙 "👨‍🎨". + +👆 🚮 ⚫️ 🔛 🔝 🔢. 💖 📶 📔 👒 (👤 💭 👈 🌐❔ ⚖ 👟 ⚪️➡️). - 👆 🚮 ⚫️ 🔛 🔝 🔢. 💖 📶 📔 👒 (👤 💭 👈 🌐❔ ⚖ 👟 ⚪️➡️). + "👨‍🎨" ✊ 🔢 🔛 & 🔨 🕳 ⏮️ ⚫️. - "👨‍🎨" ✊ 🔢 🔛 & 🔨 🕳 ⏮️ ⚫️. +👆 💼, 👉 👨‍🎨 💬 **FastAPI** 👈 🔢 🔛 🔗 **➡** `/` ⏮️ **🛠️** `get`. - 👆 💼, 👉 👨‍🎨 💬 **FastAPI** 👈 🔢 🔛 🔗 **➡** `/` ⏮️ **🛠️** `get`. +⚫️ "**➡ 🛠️ 👨‍🎨**". - ⚫️ "**➡ 🛠️ 👨‍🎨**". +/// 👆 💪 ⚙️ 🎏 🛠️: @@ -274,14 +276,17 @@ https://example.com/items/foo * `@app.patch()` * `@app.trace()` -!!! tip - 👆 🆓 ⚙️ 🔠 🛠️ (🇺🇸🔍 👩‍🔬) 👆 🎋. +/// tip + +👆 🆓 ⚙️ 🔠 🛠️ (🇺🇸🔍 👩‍🔬) 👆 🎋. + +**FastAPI** 🚫 🛠️ 🙆 🎯 🔑. - **FastAPI** 🚫 🛠️ 🙆 🎯 🔑. +ℹ 📥 🎁 📄, 🚫 📄. - ℹ 📥 🎁 📄, 🚫 📄. +🖼, 🕐❔ ⚙️ 🕹 👆 🛎 🎭 🌐 🎯 ⚙️ 🕴 `POST` 🛠️. - 🖼, 🕐❔ ⚙️ 🕹 👆 🛎 🎭 🌐 🎯 ⚙️ 🕴 `POST` 🛠️. +/// ### 🔁 4️⃣: 🔬 **➡ 🛠️ 🔢** @@ -291,9 +296,7 @@ https://example.com/items/foo * **🛠️**: `get`. * **🔢**: 🔢 🔛 "👨‍🎨" (🔛 `@app.get("/")`). -```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[7] *} 👉 🐍 🔢. @@ -305,18 +308,17 @@ https://example.com/items/foo 👆 💪 🔬 ⚫️ 😐 🔢 ↩️ `async def`: -```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} -``` +{* ../../docs_src/first_steps/tutorial003.py hl[7] *} + +/// note -!!! note - 🚥 👆 🚫 💭 🔺, ✅ [🔁: *"🏃 ❓"*](../async.md#in-a-hurry){.internal-link target=_blank}. +🚥 👆 🚫 💭 🔺, ✅ [🔁: *"🏃 ❓"*](../async.md#_2){.internal-link target=_blank}. + +/// ### 🔁 5️⃣: 📨 🎚 -```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[8] *} 👆 💪 📨 `dict`, `list`, ⭐ 💲 `str`, `int`, ♒️. diff --git a/docs/em/docs/tutorial/handling-errors.md b/docs/em/docs/tutorial/handling-errors.md index ef7bbfa65..d73b730e1 100644 --- a/docs/em/docs/tutorial/handling-errors.md +++ b/docs/em/docs/tutorial/handling-errors.md @@ -25,9 +25,7 @@ ### 🗄 `HTTPException` -```Python hl_lines="1" -{!../../../docs_src/handling_errors/tutorial001.py!} -``` +{* ../../docs_src/handling_errors/tutorial001.py hl[1] *} ### 🤚 `HTTPException` 👆 📟 @@ -41,9 +39,7 @@ 👉 🖼, 🕐❔ 👩‍💻 📨 🏬 🆔 👈 🚫 🔀, 🤚 ⚠ ⏮️ 👔 📟 `404`: -```Python hl_lines="11" -{!../../../docs_src/handling_errors/tutorial001.py!} -``` +{* ../../docs_src/handling_errors/tutorial001.py hl[11] *} ### 📉 📨 @@ -63,12 +59,15 @@ } ``` -!!! tip - 🕐❔ 🙋‍♀ `HTTPException`, 👆 💪 🚶‍♀️ 🙆 💲 👈 💪 🗜 🎻 🔢 `detail`, 🚫 🕴 `str`. +/// tip + +🕐❔ 🙋‍♀ `HTTPException`, 👆 💪 🚶‍♀️ 🙆 💲 👈 💪 🗜 🎻 🔢 `detail`, 🚫 🕴 `str`. + +👆 💪 🚶‍♀️ `dict`, `list`, ♒️. - 👆 💪 🚶‍♀️ `dict`, `list`, ♒️. +👫 🍵 🔁 **FastAPI** & 🗜 🎻. - 👫 🍵 🔁 **FastAPI** & 🗜 🎻. +/// ## 🚮 🛃 🎚 @@ -78,9 +77,7 @@ ✋️ 💼 👆 💪 ⚫️ 🏧 😐, 👆 💪 🚮 🛃 🎚: -```Python hl_lines="14" -{!../../../docs_src/handling_errors/tutorial002.py!} -``` +{* ../../docs_src/handling_errors/tutorial002.py hl[14] *} ## ❎ 🛃 ⚠ 🐕‍🦺 @@ -92,9 +89,7 @@ 👆 💪 🚮 🛃 ⚠ 🐕‍🦺 ⏮️ `@app.exception_handler()`: -```Python hl_lines="5-7 13-18 24" -{!../../../docs_src/handling_errors/tutorial003.py!} -``` +{* ../../docs_src/handling_errors/tutorial003.py hl[5:7,13:18,24] *} 📥, 🚥 👆 📨 `/unicorns/yolo`, *➡ 🛠️* 🔜 `raise` `UnicornException`. @@ -106,10 +101,13 @@ {"message": "Oops! yolo did something. There goes a rainbow..."} ``` -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.requests import Request` & `from starlette.responses import JSONResponse`. +/// note | 📡 ℹ + +👆 💪 ⚙️ `from starlette.requests import Request` & `from starlette.responses import JSONResponse`. + +**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ `Request`. - **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. 🎏 ⏮️ `Request`. +/// ## 🔐 🔢 ⚠ 🐕‍🦺 @@ -129,9 +127,7 @@ ⚠ 🐕‍🦺 🔜 📨 `Request` & ⚠. -```Python hl_lines="2 14-16" -{!../../../docs_src/handling_errors/tutorial004.py!} -``` +{* ../../docs_src/handling_errors/tutorial004.py hl[2,14:16] *} 🔜, 🚥 👆 🚶 `/items/foo`, ↩️ 💆‍♂ 🔢 🎻 ❌ ⏮️: @@ -160,10 +156,13 @@ path -> item_id #### `RequestValidationError` 🆚 `ValidationError` -!!! warning - 👫 📡 ℹ 👈 👆 💪 🚶 🚥 ⚫️ 🚫 ⚠ 👆 🔜. +/// warning + +👫 📡 ℹ 👈 👆 💪 🚶 🚥 ⚫️ 🚫 ⚠ 👆 🔜. -`RequestValidationError` 🎧-🎓 Pydantic `ValidationError`. +/// + +`RequestValidationError` 🎧-🎓 Pydantic `ValidationError`. **FastAPI** ⚙️ ⚫️ 👈, 🚥 👆 ⚙️ Pydantic 🏷 `response_model`, & 👆 💽 ✔️ ❌, 👆 🔜 👀 ❌ 👆 🕹. @@ -179,14 +178,15 @@ path -> item_id 🖼, 👆 💪 💚 📨 ✅ ✍ 📨 ↩️ 🎻 👫 ❌: -```Python hl_lines="3-4 9-11 22" -{!../../../docs_src/handling_errors/tutorial004.py!} -``` +{* ../../docs_src/handling_errors/tutorial004.py hl[3:4,9:11,22] *} -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.responses import PlainTextResponse`. +/// note | 📡 ℹ - **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. +👆 💪 ⚙️ `from starlette.responses import PlainTextResponse`. + +**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. + +/// ### ⚙️ `RequestValidationError` 💪 @@ -194,9 +194,7 @@ path -> item_id 👆 💪 ⚙️ ⚫️ ⏪ 🛠️ 👆 📱 🕹 💪 & ℹ ⚫️, 📨 ⚫️ 👩‍💻, ♒️. -```Python hl_lines="14" -{!../../../docs_src/handling_errors/tutorial005.py!} -``` +{* ../../docs_src/handling_errors/tutorial005.py hl[14] *} 🔜 🔄 📨 ❌ 🏬 💖: @@ -254,8 +252,6 @@ from starlette.exceptions import HTTPException as StarletteHTTPException 🚥 👆 💚 ⚙️ ⚠ ⤴️ ⏮️ 🎏 🔢 ⚠ 🐕‍🦺 ⚪️➡️ **FastAPI**, 👆 💪 🗄 & 🏤-⚙️ 🔢 ⚠ 🐕‍🦺 ⚪️➡️ `fastapi.exception_handlers`: -```Python hl_lines="2-5 15 21" -{!../../../docs_src/handling_errors/tutorial006.py!} -``` +{* ../../docs_src/handling_errors/tutorial006.py hl[2:5,15,21] *} 👉 🖼 👆 `print`😅 ❌ ⏮️ 📶 🎨 📧, ✋️ 👆 🤚 💭. 👆 💪 ⚙️ ⚠ & ⤴️ 🏤-⚙️ 🔢 ⚠ 🐕‍🦺. diff --git a/docs/em/docs/tutorial/header-params.md b/docs/em/docs/tutorial/header-params.md index 0f33a1774..fa5e3a22b 100644 --- a/docs/em/docs/tutorial/header-params.md +++ b/docs/em/docs/tutorial/header-params.md @@ -6,17 +6,7 @@ 🥇 🗄 `Header`: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="1" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` +{* ../../docs_src/header_params/tutorial001.py hl[3] *} ## 📣 `Header` 🔢 @@ -24,25 +14,21 @@ 🥇 💲 🔢 💲, 👆 💪 🚶‍♀️ 🌐 ➕ 🔬 ⚖️ ✍ 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" +{* ../../docs_src/header_params/tutorial001.py hl[9] *} - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` +/// note | 📡 ℹ -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +`Header` "👭" 🎓 `Path`, `Query` & `Cookie`. ⚫️ 😖 ⚪️➡️ 🎏 ⚠ `Param` 🎓. - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` +✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `Header`, & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. -!!! note "📡 ℹ" - `Header` "👭" 🎓 `Path`, `Query` & `Cookie`. ⚫️ 😖 ⚪️➡️ 🎏 ⚠ `Param` 🎓. +/// - ✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `Header`, & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. +/// info -!!! info - 📣 🎚, 👆 💪 ⚙️ `Header`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢. +📣 🎚, 👆 💪 ⚙️ `Header`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢. + +/// ## 🏧 🛠️ @@ -60,20 +46,13 @@ 🚥 🤔 👆 💪 ❎ 🏧 🛠️ 🎦 🔠, ⚒ 🔢 `convert_underscores` `Header` `False`: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial002.py!} - ``` +{* ../../docs_src/header_params/tutorial002.py hl[10] *} -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// warning - ```Python hl_lines="8" - {!> ../../../docs_src/header_params/tutorial002_py310.py!} - ``` +⏭ ⚒ `convert_underscores` `False`, 🐻 🤯 👈 🇺🇸🔍 🗳 & 💽 / ⚙️ 🎚 ⏮️ 🎦. -!!! warning - ⏭ ⚒ `convert_underscores` `False`, 🐻 🤯 👈 🇺🇸🔍 🗳 & 💽 / ⚙️ 🎚 ⏮️ 🎦. +/// ## ❎ 🎚 @@ -85,23 +64,7 @@ 🖼, 📣 🎚 `X-Token` 👈 💪 😑 🌅 🌘 🕐, 👆 💪 ✍: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_py39.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial003_py310.py!} - ``` +{* ../../docs_src/header_params/tutorial003.py hl[9] *} 🚥 👆 🔗 ⏮️ 👈 *➡ 🛠️* 📨 2️⃣ 🇺🇸🔍 🎚 💖: diff --git a/docs/em/docs/tutorial/index.md b/docs/em/docs/tutorial/index.md index 26b4c1913..5f7532341 100644 --- a/docs/em/docs/tutorial/index.md +++ b/docs/em/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ...👈 🔌 `uvicorn`, 👈 👆 💪 ⚙️ 💽 👈 🏃 👆 📟. -!!! note - 👆 💪 ❎ ⚫️ 🍕 🍕. +/// note - 👉 ⚫️❔ 👆 🔜 🎲 🕐 👆 💚 🛠️ 👆 🈸 🏭: +👆 💪 ❎ ⚫️ 🍕 🍕. - ``` - pip install fastapi - ``` +👉 ⚫️❔ 👆 🔜 🎲 🕐 👆 💚 🛠️ 👆 🈸 🏭: - ❎ `uvicorn` 👷 💽: +``` +pip install "fastapi[standard]" +``` + +❎ `uvicorn` 👷 💽: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` + & 🎏 🔠 📦 🔗 👈 👆 💚 ⚙️. - & 🎏 🔠 📦 🔗 👈 👆 💚 ⚙️. +/// ## 🏧 👩‍💻 🦮 diff --git a/docs/em/docs/tutorial/metadata.md b/docs/em/docs/tutorial/metadata.md index 00098cdf5..eaf605de1 100644 --- a/docs/em/docs/tutorial/metadata.md +++ b/docs/em/docs/tutorial/metadata.md @@ -17,12 +17,13 @@ 👆 💪 ⚒ 👫 ⏩: -```Python hl_lines="3-16 19-31" -{!../../../docs_src/metadata/tutorial001.py!} -``` +{* ../../docs_src/metadata/tutorial001.py hl[3:16,19:31] *} -!!! tip - 👆 💪 ✍ ✍ `description` 🏑 & ⚫️ 🔜 ✍ 🔢. +/// tip + +👆 💪 ✍ ✍ `description` 🏑 & ⚫️ 🔜 ✍ 🔢. + +/// ⏮️ 👉 📳, 🏧 🛠️ 🩺 🔜 👀 💖: @@ -48,25 +49,27 @@ ✍ 🗃 👆 🔖 & 🚶‍♀️ ⚫️ `openapi_tags` 🔢: -```Python hl_lines="3-16 18" -{!../../../docs_src/metadata/tutorial004.py!} -``` +{* ../../docs_src/metadata/tutorial004.py hl[3:16,18] *} 👀 👈 👆 💪 ⚙️ ✍ 🔘 📛, 🖼 "💳" 🔜 🎦 🦁 (**💳**) & "🎀" 🔜 🎦 ❕ (_🎀_). -!!! tip - 👆 🚫 ✔️ 🚮 🗃 🌐 🔖 👈 👆 ⚙️. +/// tip + +👆 🚫 ✔️ 🚮 🗃 🌐 🔖 👈 👆 ⚙️. + +/// ### ⚙️ 👆 🔖 ⚙️ `tags` 🔢 ⏮️ 👆 *➡ 🛠️* (& `APIRouter`Ⓜ) 🛠️ 👫 🎏 🔖: -```Python hl_lines="21 26" -{!../../../docs_src/metadata/tutorial004.py!} -``` +{* ../../docs_src/metadata/tutorial004.py hl[21,26] *} + +/// info + +✍ 🌅 🔃 🔖 [➡ 🛠️ 📳](path-operation-configuration.md#_3){.internal-link target=_blank}. -!!! info - ✍ 🌅 🔃 🔖 [➡ 🛠️ 📳](../path-operation-configuration/#tags){.internal-link target=_blank}. +/// ### ✅ 🩺 @@ -88,9 +91,7 @@ 🖼, ⚒ ⚫️ 🍦 `/api/v1/openapi.json`: -```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial002.py!} -``` +{* ../../docs_src/metadata/tutorial002.py hl[3] *} 🚥 👆 💚 ❎ 🗄 🔗 🍕 👆 💪 ⚒ `openapi_url=None`, 👈 🔜 ❎ 🧾 👩‍💻 🔢 👈 ⚙️ ⚫️. @@ -107,6 +108,4 @@ 🖼, ⚒ 🦁 🎚 🍦 `/documentation` & ❎ 📄: -```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial003.py!} -``` +{* ../../docs_src/metadata/tutorial003.py hl[3] *} diff --git a/docs/em/docs/tutorial/middleware.md b/docs/em/docs/tutorial/middleware.md index 644b4690c..d203471e8 100644 --- a/docs/em/docs/tutorial/middleware.md +++ b/docs/em/docs/tutorial/middleware.md @@ -11,10 +11,13 @@ * ⚫️ 💪 🕳 👈 **📨** ⚖️ 🏃 🙆 💪 📟. * ⤴️ ⚫️ 📨 **📨**. -!!! note "📡 ℹ" - 🚥 👆 ✔️ 🔗 ⏮️ `yield`, 🚪 📟 🔜 🏃 *⏮️* 🛠️. +/// note | 📡 ℹ - 🚥 📤 🙆 🖥 📋 (📄 ⏪), 👫 🔜 🏃 *⏮️* 🌐 🛠️. +🚥 👆 ✔️ 🔗 ⏮️ `yield`, 🚪 📟 🔜 🏃 *⏮️* 🛠️. + +🚥 📤 🙆 🖥 📋 (📄 ⏪), 👫 🔜 🏃 *⏮️* 🌐 🛠️. + +/// ## ✍ 🛠️ @@ -28,19 +31,23 @@ * ⤴️ ⚫️ 📨 `response` 🏗 🔗 *➡ 🛠️*. * 👆 💪 ⤴️ 🔀 🌅 `response` ⏭ 🛬 ⚫️. -```Python hl_lines="8-9 11 14" -{!../../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[8:9,11,14] *} + +/// tip + +✔️ 🤯 👈 🛃 © 🎚 💪 🚮 ⚙️ '✖-' 🔡. + +✋️ 🚥 👆 ✔️ 🛃 🎚 👈 👆 💚 👩‍💻 🖥 💪 👀, 👆 💪 🚮 👫 👆 ⚜ 📳 ([⚜ (✖️-🇨🇳 ℹ 🤝)](cors.md){.internal-link target=_blank}) ⚙️ 🔢 `expose_headers` 📄 💃 ⚜ 🩺. + +/// -!!! tip - ✔️ 🤯 👈 🛃 © 🎚 💪 🚮 ⚙️ '✖-' 🔡. +/// note | 📡 ℹ - ✋️ 🚥 👆 ✔️ 🛃 🎚 👈 👆 💚 👩‍💻 🖥 💪 👀, 👆 💪 🚮 👫 👆 ⚜ 📳 ([⚜ (✖️-🇨🇳 ℹ 🤝)](cors.md){.internal-link target=_blank}) ⚙️ 🔢 `expose_headers` 📄 💃 ⚜ 🩺. +👆 💪 ⚙️ `from starlette.requests import Request`. -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.requests import Request`. +**FastAPI** 🚚 ⚫️ 🏪 👆, 👩‍💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. - **FastAPI** 🚚 ⚫️ 🏪 👆, 👩‍💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. +/// ### ⏭ & ⏮️ `response` @@ -50,9 +57,7 @@ 🖼, 👆 💪 🚮 🛃 🎚 `X-Process-Time` ⚗ 🕰 🥈 👈 ⚫️ ✊ 🛠️ 📨 & 🏗 📨: -```Python hl_lines="10 12-13" -{!../../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *} ## 🎏 🛠️ diff --git a/docs/em/docs/tutorial/path-operation-configuration.md b/docs/em/docs/tutorial/path-operation-configuration.md index 916529258..c6030c089 100644 --- a/docs/em/docs/tutorial/path-operation-configuration.md +++ b/docs/em/docs/tutorial/path-operation-configuration.md @@ -2,8 +2,11 @@ 📤 📚 🔢 👈 👆 💪 🚶‍♀️ 👆 *➡ 🛠️ 👨‍🎨* 🔗 ⚫️. -!!! warning - 👀 👈 👫 🔢 🚶‍♀️ 🔗 *➡ 🛠️ 👨‍🎨*, 🚫 👆 *➡ 🛠️ 🔢*. +/// warning + +👀 👈 👫 🔢 🚶‍♀️ 🔗 *➡ 🛠️ 👨‍🎨*, 🚫 👆 *➡ 🛠️ 🔢*. + +/// ## 📨 👔 📟 @@ -13,52 +16,23 @@ ✋️ 🚥 👆 🚫 💭 ⚫️❔ 🔠 🔢 📟, 👆 💪 ⚙️ ⌨ 📉 `status`: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="3 17" - {!> ../../../docs_src/path_operation_configuration/tutorial001.py!} - ``` +{* ../../docs_src/path_operation_configuration/tutorial001.py hl[3,17] *} -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="3 17" - {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +👈 👔 📟 🔜 ⚙️ 📨 & 🔜 🚮 🗄 🔗. - ```Python hl_lines="1 15" - {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} - ``` +/// note | 📡 ℹ -👈 👔 📟 🔜 ⚙️ 📨 & 🔜 🚮 🗄 🔗. +👆 💪 ⚙️ `from starlette import status`. -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette import status`. +**FastAPI** 🚚 🎏 `starlette.status` `fastapi.status` 🏪 👆, 👩‍💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. - **FastAPI** 🚚 🎏 `starlette.status` `fastapi.status` 🏪 👆, 👩‍💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. +/// ## 🔖 👆 💪 🚮 🔖 👆 *➡ 🛠️*, 🚶‍♀️ 🔢 `tags` ⏮️ `list` `str` (🛎 1️⃣ `str`): -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="17 22 27" - {!> ../../../docs_src/path_operation_configuration/tutorial002.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="17 22 27" - {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="15 20 25" - {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} - ``` +{* ../../docs_src/path_operation_configuration/tutorial002.py hl[17,22,27] *} 👫 🔜 🚮 🗄 🔗 & ⚙️ 🏧 🧾 🔢: @@ -72,31 +46,13 @@ **FastAPI** 🐕‍🦺 👈 🎏 🌌 ⏮️ ✅ 🎻: -```Python hl_lines="1 8-10 13 18" -{!../../../docs_src/path_operation_configuration/tutorial002b.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial002b.py hl[1,8:10,13,18] *} ## 📄 & 📛 👆 💪 🚮 `summary` & `description`: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="20-21" - {!> ../../../docs_src/path_operation_configuration/tutorial003.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="20-21" - {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="18-19" - {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} - ``` +{* ../../docs_src/path_operation_configuration/tutorial003.py hl[20:21] *} ## 📛 ⚪️➡️ #️⃣ @@ -104,23 +60,7 @@ 👆 💪 ✍ #️⃣ , ⚫️ 🔜 🔬 & 🖥 ☑ (✊ 🔘 🏧 #️⃣ 📐). -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="19-27" - {!> ../../../docs_src/path_operation_configuration/tutorial004.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="19-27" - {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="17-25" - {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} - ``` +{* ../../docs_src/path_operation_configuration/tutorial004.py hl[19:27] *} ⚫️ 🔜 ⚙️ 🎓 🩺: @@ -130,31 +70,21 @@ 👆 💪 ✔ 📨 📛 ⏮️ 🔢 `response_description`: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="21" - {!> ../../../docs_src/path_operation_configuration/tutorial005.py!} - ``` +{* ../../docs_src/path_operation_configuration/tutorial005.py hl[21] *} -=== "🐍 3️⃣.9️⃣ & 🔛" +/// info - ```Python hl_lines="21" - {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} - ``` +👀 👈 `response_description` 🔗 🎯 📨, `description` 🔗 *➡ 🛠️* 🏢. -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// - ```Python hl_lines="19" - {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} - ``` +/// check -!!! info - 👀 👈 `response_description` 🔗 🎯 📨, `description` 🔗 *➡ 🛠️* 🏢. +🗄 ✔ 👈 🔠 *➡ 🛠️* 🚚 📨 📛. -!!! check - 🗄 ✔ 👈 🔠 *➡ 🛠️* 🚚 📨 📛. +, 🚥 👆 🚫 🚚 1️⃣, **FastAPI** 🔜 🔁 🏗 1️⃣ "🏆 📨". - , 🚥 👆 🚫 🚚 1️⃣, **FastAPI** 🔜 🔁 🏗 1️⃣ "🏆 📨". +/// @@ -162,9 +92,7 @@ 🚥 👆 💪 ™ *➡ 🛠️* 😢, ✋️ 🍵 ❎ ⚫️, 🚶‍♀️ 🔢 `deprecated`: -```Python hl_lines="16" -{!../../../docs_src/path_operation_configuration/tutorial006.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial006.py hl[16] *} ⚫️ 🔜 🎯 ™ 😢 🎓 🩺: diff --git a/docs/em/docs/tutorial/path-params-numeric-validations.md b/docs/em/docs/tutorial/path-params-numeric-validations.md index b1ba2670b..b45e0557b 100644 --- a/docs/em/docs/tutorial/path-params-numeric-validations.md +++ b/docs/em/docs/tutorial/path-params-numeric-validations.md @@ -6,17 +6,7 @@ 🥇, 🗄 `Path` ⚪️➡️ `fastapi`: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="1" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +{* ../../docs_src/path_params_numeric_validations/tutorial001.py hl[3] *} ## 📣 🗃 @@ -24,24 +14,17 @@ 🖼, 📣 `title` 🗃 💲 ➡ 🔢 `item_id` 👆 💪 🆎: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +{* ../../docs_src/path_params_numeric_validations/tutorial001.py hl[10] *} -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// note - ```Python hl_lines="8" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +➡ 🔢 🕧 ✔ ⚫️ ✔️ 🍕 ➡. -!!! note - ➡ 🔢 🕧 ✔ ⚫️ ✔️ 🍕 ➡. +, 👆 🔜 📣 ⚫️ ⏮️ `...` ™ ⚫️ ✔. - , 👆 🔜 📣 ⚫️ ⏮️ `...` ™ ⚫️ ✔. +👐, 🚥 👆 📣 ⚫️ ⏮️ `None` ⚖️ ⚒ 🔢 💲, ⚫️ 🔜 🚫 📉 🕳, ⚫️ 🔜 🕧 🚚. - 👐, 🚥 👆 📣 ⚫️ ⏮️ `None` ⚖️ ⚒ 🔢 💲, ⚫️ 🔜 🚫 📉 🕳, ⚫️ 🔜 🕧 🚚. +/// ## ✔ 🔢 👆 💪 @@ -59,9 +42,7 @@ , 👆 💪 📣 👆 🔢: -```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial002.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial002.py hl[7] *} ## ✔ 🔢 👆 💪, 🎱 @@ -71,9 +52,7 @@ 🐍 🏆 🚫 🕳 ⏮️ 👈 `*`, ✋️ ⚫️ 🔜 💭 👈 🌐 📄 🔢 🔜 🤙 🇨🇻 ❌ (🔑-💲 👫), 💭 kwargs. 🚥 👫 🚫 ✔️ 🔢 💲. -```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial003.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *} ## 🔢 🔬: 👑 🌘 ⚖️ 🌓 @@ -81,9 +60,7 @@ 📥, ⏮️ `ge=1`, `item_id` 🔜 💪 🔢 🔢 "`g`🅾 🌘 ⚖️ `e`🅾" `1`. -```Python hl_lines="8" -{!../../../docs_src/path_params_numeric_validations/tutorial004.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial004.py hl[8] *} ## 🔢 🔬: 🌘 🌘 & 🌘 🌘 ⚖️ 🌓 @@ -92,9 +69,7 @@ * `gt`: `g`🅾 `t`👲 * `le`: `l`👭 🌘 ⚖️ `e`🅾 -```Python hl_lines="9" -{!../../../docs_src/path_params_numeric_validations/tutorial005.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial005.py hl[9] *} ## 🔢 🔬: 🎈, 🌘 🌘 & 🌘 🌘 @@ -106,9 +81,7 @@ & 🎏 lt. -```Python hl_lines="11" -{!../../../docs_src/path_params_numeric_validations/tutorial006.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial006.py hl[11] *} ## 🌃 @@ -121,18 +94,24 @@ * `lt`: `l`👭 `t`👲 * `le`: `l`👭 🌘 ⚖️ `e`🅾 -!!! info - `Query`, `Path`, & 🎏 🎓 👆 🔜 👀 ⏪ 🏿 ⚠ `Param` 🎓. +/// info + +`Query`, `Path`, & 🎏 🎓 👆 🔜 👀 ⏪ 🏿 ⚠ `Param` 🎓. + +🌐 👫 💰 🎏 🔢 🌖 🔬 & 🗃 👆 ✔️ 👀. + +/// + +/// note | 📡 ℹ - 🌐 👫 💰 🎏 🔢 🌖 🔬 & 🗃 👆 ✔️ 👀. +🕐❔ 👆 🗄 `Query`, `Path` & 🎏 ⚪️➡️ `fastapi`, 👫 🤙 🔢. -!!! note "📡 ℹ" - 🕐❔ 👆 🗄 `Query`, `Path` & 🎏 ⚪️➡️ `fastapi`, 👫 🤙 🔢. +👈 🕐❔ 🤙, 📨 👐 🎓 🎏 📛. - 👈 🕐❔ 🤙, 📨 👐 🎓 🎏 📛. +, 👆 🗄 `Query`, ❔ 🔢. & 🕐❔ 👆 🤙 ⚫️, ⚫️ 📨 👐 🎓 🌟 `Query`. - , 👆 🗄 `Query`, ❔ 🔢. & 🕐❔ 👆 🤙 ⚫️, ⚫️ 📨 👐 🎓 🌟 `Query`. +👫 🔢 📤 (↩️ ⚙️ 🎓 🔗) 👈 👆 👨‍🎨 🚫 ™ ❌ 🔃 👫 🆎. - 👫 🔢 📤 (↩️ ⚙️ 🎓 🔗) 👈 👆 👨‍🎨 🚫 ™ ❌ 🔃 👫 🆎. +👈 🌌 👆 💪 ⚙️ 👆 😐 👨‍🎨 & 🛠️ 🧰 🍵 ✔️ 🚮 🛃 📳 🤷‍♂ 📚 ❌. - 👈 🌌 👆 💪 ⚙️ 👆 😐 👨‍🎨 & 🛠️ 🧰 🍵 ✔️ 🚮 🛃 📳 🤷‍♂ 📚 ❌. +/// diff --git a/docs/em/docs/tutorial/path-params.md b/docs/em/docs/tutorial/path-params.md index ea939b458..a914dc905 100644 --- a/docs/em/docs/tutorial/path-params.md +++ b/docs/em/docs/tutorial/path-params.md @@ -2,9 +2,7 @@ 👆 💪 📣 ➡ "🔢" ⚖️ "🔢" ⏮️ 🎏 ❕ ⚙️ 🐍 📁 🎻: -```Python hl_lines="6-7" -{!../../../docs_src/path_params/tutorial001.py!} -``` +{* ../../docs_src/path_params/tutorial001.py hl[6:7] *} 💲 ➡ 🔢 `item_id` 🔜 🚶‍♀️ 👆 🔢 ❌ `item_id`. @@ -18,14 +16,15 @@ 👆 💪 📣 🆎 ➡ 🔢 🔢, ⚙️ 🐩 🐍 🆎 ✍: -```Python hl_lines="7" -{!../../../docs_src/path_params/tutorial002.py!} -``` +{* ../../docs_src/path_params/tutorial002.py hl[7] *} 👉 💼, `item_id` 📣 `int`. -!!! check - 👉 🔜 🤝 👆 👨‍🎨 🐕‍🦺 🔘 👆 🔢, ⏮️ ❌ ✅, 🛠️, ♒️. +/// check + +👉 🔜 🤝 👆 👨‍🎨 🐕‍🦺 🔘 👆 🔢, ⏮️ ❌ ✅, 🛠️, ♒️. + +/// ## 💽 🛠️ @@ -35,10 +34,13 @@ {"item_id":3} ``` -!!! check - 👀 👈 💲 👆 🔢 📨 (& 📨) `3`, 🐍 `int`, 🚫 🎻 `"3"`. +/// check - , ⏮️ 👈 🆎 📄, **FastAPI** 🤝 👆 🏧 📨 "✍". +👀 👈 💲 👆 🔢 📨 (& 📨) `3`, 🐍 `int`, 🚫 🎻 `"3"`. + +, ⏮️ 👈 🆎 📄, **FastAPI** 🤝 👆 🏧 📨 "✍". + +/// ## 💽 🔬 @@ -63,12 +65,15 @@ 🎏 ❌ 🔜 😑 🚥 👆 🚚 `float` ↩️ `int`,: http://127.0.0.1:8000/items/4.2 -!!! check - , ⏮️ 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 💽 🔬. +/// check + +, ⏮️ 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 💽 🔬. - 👀 👈 ❌ 🎯 🇵🇸 ⚫️❔ ☝ 🌐❔ 🔬 🚫 🚶‍♀️. +👀 👈 ❌ 🎯 🇵🇸 ⚫️❔ ☝ 🌐❔ 🔬 🚫 🚶‍♀️. - 👉 🙃 👍 ⏪ 🛠️ & 🛠️ 📟 👈 🔗 ⏮️ 👆 🛠️. +👉 🙃 👍 ⏪ 🛠️ & 🛠️ 📟 👈 🔗 ⏮️ 👆 🛠️. + +/// ## 🧾 @@ -76,10 +81,13 @@ -!!! check - 🔄, ⏮️ 👈 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 🏧, 🎓 🧾 (🛠️ 🦁 🎚). +/// check + +🔄, ⏮️ 👈 🎏 🐍 🆎 📄, **FastAPI** 🤝 👆 🏧, 🎓 🧾 (🛠️ 🦁 🎚). + +👀 👈 ➡ 🔢 📣 🔢. - 👀 👈 ➡ 🔢 📣 🔢. +/// ## 🐩-⚓️ 💰, 🎛 🧾 @@ -93,7 +101,7 @@ ## Pydantic -🌐 💽 🔬 🎭 🔽 🚘 Pydantic, 👆 🤚 🌐 💰 ⚪️➡️ ⚫️. & 👆 💭 👆 👍 ✋. +🌐 💽 🔬 🎭 🔽 🚘 Pydantic, 👆 🤚 🌐 💰 ⚪️➡️ ⚫️. & 👆 💭 👆 👍 ✋. 👆 💪 ⚙️ 🎏 🆎 📄 ⏮️ `str`, `float`, `bool` & 📚 🎏 🏗 📊 🆎. @@ -109,17 +117,13 @@ ↩️ *➡ 🛠️* 🔬 ✔, 👆 💪 ⚒ 💭 👈 ➡ `/users/me` 📣 ⏭ 1️⃣ `/users/{user_id}`: -```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003.py!} -``` +{* ../../docs_src/path_params/tutorial003.py hl[6,11] *} ⏪, ➡ `/users/{user_id}` 🔜 🏏 `/users/me`, "💭" 👈 ⚫️ 📨 🔢 `user_id` ⏮️ 💲 `"me"`. ➡, 👆 🚫🔜 ↔ ➡ 🛠️: -```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003b.py!} -``` +{* ../../docs_src/path_params/tutorial003b.py hl[6,11] *} 🥇 🕐 🔜 🕧 ⚙️ ↩️ ➡ 🏏 🥇. @@ -135,23 +139,25 @@ ⤴️ ✍ 🎓 🔢 ⏮️ 🔧 💲, ❔ 🔜 💪 ☑ 💲: -```Python hl_lines="1 6-9" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *} -!!! info - 🔢 (⚖️ 🔢) 💪 🐍 ↩️ ⏬ 3️⃣.4️⃣. +/// info -!!! tip - 🚥 👆 💭, "📊", "🎓", & "🍏" 📛 🎰 🏫 🏷. +🔢 (⚖️ 🔢) 💪 🐍 ↩️ ⏬ 3️⃣.4️⃣. + +/// + +/// tip + +🚥 👆 💭, "📊", "🎓", & "🍏" 📛 🎰 🏫 🏷. + +/// ### 📣 *➡ 🔢* ⤴️ ✍ *➡ 🔢* ⏮️ 🆎 ✍ ⚙️ 🔢 🎓 👆 ✍ (`ModelName`): -```Python hl_lines="16" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[16] *} ### ✅ 🩺 @@ -167,20 +173,19 @@ 👆 💪 🔬 ⚫️ ⏮️ *🔢 👨‍🎓* 👆 ✍ 🔢 `ModelName`: -```Python hl_lines="17" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[17] *} #### 🤚 *🔢 💲* 👆 💪 🤚 ☑ 💲 ( `str` 👉 💼) ⚙️ `model_name.value`, ⚖️ 🏢, `your_enum_member.value`: -```Python hl_lines="20" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[20] *} -!!! tip - 👆 💪 🔐 💲 `"lenet"` ⏮️ `ModelName.lenet.value`. +/// tip + +👆 💪 🔐 💲 `"lenet"` ⏮️ `ModelName.lenet.value`. + +/// #### 📨 *🔢 👨‍🎓* @@ -188,9 +193,7 @@ 👫 🔜 🗜 👫 🔗 💲 (🎻 👉 💼) ⏭ 🛬 👫 👩‍💻: -```Python hl_lines="18 21 23" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *} 👆 👩‍💻 👆 🔜 🤚 🎻 📨 💖: @@ -229,14 +232,15 @@ , 👆 💪 ⚙️ ⚫️ ⏮️: -```Python hl_lines="6" -{!../../../docs_src/path_params/tutorial004.py!} -``` +{* ../../docs_src/path_params/tutorial004.py hl[6] *} + +/// tip + +👆 💪 💪 🔢 🔌 `/home/johndoe/myfile.txt`, ⏮️ 🏁 🔪 (`/`). -!!! tip - 👆 💪 💪 🔢 🔌 `/home/johndoe/myfile.txt`, ⏮️ 🏁 🔪 (`/`). +👈 💼, 📛 🔜: `/files//home/johndoe/myfile.txt`, ⏮️ 2️⃣✖️ 🔪 (`//`) 🖖 `files` & `home`. - 👈 💼, 📛 🔜: `/files//home/johndoe/myfile.txt`, ⏮️ 2️⃣✖️ 🔪 (`//`) 🖖 `files` & `home`. +/// ## 🌃 diff --git a/docs/em/docs/tutorial/query-params-str-validations.md b/docs/em/docs/tutorial/query-params-str-validations.md index f0e455abe..fd077bf8f 100644 --- a/docs/em/docs/tutorial/query-params-str-validations.md +++ b/docs/em/docs/tutorial/query-params-str-validations.md @@ -4,24 +4,17 @@ ➡️ ✊ 👉 🈸 🖼: -=== "🐍 3️⃣.6️⃣ & 🔛" +{* ../../docs_src/query_params_str_validations/tutorial001.py hl[9] *} - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial001.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +🔢 🔢 `q` 🆎 `Union[str, None]` (⚖️ `str | None` 🐍 3️⃣.1️⃣0️⃣), 👈 ⛓ 👈 ⚫️ 🆎 `str` ✋️ 💪 `None`, & 👐, 🔢 💲 `None`, FastAPI 🔜 💭 ⚫️ 🚫 ✔. - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} - ``` +/// note -🔢 🔢 `q` 🆎 `Union[str, None]` (⚖️ `str | None` 🐍 3️⃣.1️⃣0️⃣), 👈 ⛓ 👈 ⚫️ 🆎 `str` ✋️ 💪 `None`, & 👐, 🔢 💲 `None`, FastAPI 🔜 💭 ⚫️ 🚫 ✔. +FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`. -!!! note - FastAPI 🔜 💭 👈 💲 `q` 🚫 ✔ ↩️ 🔢 💲 `= None`. + `Union` `Union[str, None]` 🔜 ✔ 👆 👨‍🎨 🤝 👆 👍 🐕‍🦺 & 🔍 ❌. - `Union` `Union[str, None]` 🔜 ✔ 👆 👨‍🎨 🤝 👆 👍 🐕‍🦺 & 🔍 ❌. +/// ## 🌖 🔬 @@ -31,33 +24,13 @@ 🏆 👈, 🥇 🗄 `Query` ⚪️➡️ `fastapi`: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="3" - {!> ../../../docs_src/query_params_str_validations/tutorial002.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="1" - {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} - ``` +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[3] *} ## ⚙️ `Query` 🔢 💲 & 🔜 ⚙️ ⚫️ 🔢 💲 👆 🔢, ⚒ 🔢 `max_length` 5️⃣0️⃣: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial002.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} - ``` +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[9] *} 👥 ✔️ ❎ 🔢 💲 `None` 🔢 ⏮️ `Query()`, 👥 💪 🔜 ⚒ 🔢 💲 ⏮️ 🔢 `Query(default=None)`, ⚫️ 🍦 🎏 🎯 ⚖ 👈 🔢 💲. @@ -87,22 +60,25 @@ q: str | None = None ✋️ ⚫️ 📣 ⚫️ 🎯 💆‍♂ 🔢 🔢. -!!! info - ✔️ 🤯 👈 🌅 ⚠ 🍕 ⚒ 🔢 📦 🍕: +/// info - ```Python - = None - ``` +✔️ 🤯 👈 🌅 ⚠ 🍕 ⚒ 🔢 📦 🍕: - ⚖️: +```Python += None +``` + +⚖️: + +```Python += Query(default=None) +``` - ```Python - = Query(default=None) - ``` +⚫️ 🔜 ⚙️ 👈 `None` 🔢 💲, & 👈 🌌 ⚒ 🔢 **🚫 ✔**. - ⚫️ 🔜 ⚙️ 👈 `None` 🔢 💲, & 👈 🌌 ⚒ 🔢 **🚫 ✔**. + `Union[str, None]` 🍕 ✔ 👆 👨‍🎨 🚚 👻 🐕‍🦺, ✋️ ⚫️ 🚫 ⚫️❔ 💬 FastAPI 👈 👉 🔢 🚫 ✔. - `Union[str, None]` 🍕 ✔ 👆 👨‍🎨 🚚 👻 🐕‍🦺, ✋️ ⚫️ 🚫 ⚫️❔ 💬 FastAPI 👈 👉 🔢 🚫 ✔. +/// ⤴️, 👥 💪 🚶‍♀️ 🌅 🔢 `Query`. 👉 💼, `max_length` 🔢 👈 ✔ 🎻: @@ -116,33 +92,13 @@ q: Union[str, None] = Query(default=None, max_length=50) 👆 💪 🚮 🔢 `min_length`: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial003.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!} - ``` +{* ../../docs_src/query_params_str_validations/tutorial003.py hl[10] *} ## 🚮 🥔 🧬 👆 💪 🔬 🥔 🧬 👈 🔢 🔜 🏏: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial004.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!} - ``` +{* ../../docs_src/query_params_str_validations/tutorial004.py hl[11] *} 👉 🎯 🥔 🧬 ✅ 👈 📨 🔢 💲: @@ -160,12 +116,13 @@ q: Union[str, None] = Query(default=None, max_length=50) ➡️ 💬 👈 👆 💚 📣 `q` 🔢 🔢 ✔️ `min_length` `3`, & ✔️ 🔢 💲 `"fixedquery"`: -```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial005.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial005.py hl[7] *} + +/// note -!!! note - ✔️ 🔢 💲 ⚒ 🔢 📦. +✔️ 🔢 💲 ⚒ 🔢 📦. + +/// ## ⚒ ⚫️ ✔ @@ -189,24 +146,7 @@ q: Union[str, None] = Query(default=None, min_length=3) , 🕐❔ 👆 💪 📣 💲 ✔ ⏪ ⚙️ `Query`, 👆 💪 🎯 🚫 📣 🔢 💲: -```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial006.py!} -``` - -### ✔ ⏮️ ❕ (`...`) - -📤 🎛 🌌 🎯 📣 👈 💲 ✔. 👆 💪 ⚒ `default` 🔢 🔑 💲 `...`: - -```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial006b.py!} -``` - -!!! info - 🚥 👆 🚫 👀 👈 `...` ⏭: ⚫️ 🎁 👁 💲, ⚫️ 🍕 🐍 & 🤙 "❕". - - ⚫️ ⚙️ Pydantic & FastAPI 🎯 📣 👈 💲 ✔. - -👉 🔜 ➡️ **FastAPI** 💭 👈 👉 🔢 ✔. +{* ../../docs_src/query_params_str_validations/tutorial006.py hl[7] *} ### ✔ ⏮️ `None` @@ -214,31 +154,13 @@ q: Union[str, None] = Query(default=None, min_length=3) 👈, 👆 💪 📣 👈 `None` ☑ 🆎 ✋️ ⚙️ `default=...`: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006c.py!} - ``` +{* ../../docs_src/query_params_str_validations/tutorial006c.py hl[9] *} -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// tip - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!} - ``` +Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 ✔ 📦 🏑. -!!! tip - Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ 🎁 🎭 🕐❔ 👆 ⚙️ `Optional` ⚖️ `Union[Something, None]` 🍵 🔢 💲, 👆 💪 ✍ 🌅 🔃 ⚫️ Pydantic 🩺 🔃 ✔ 📦 🏑. - -### ⚙️ Pydantic `Required` ↩️ ❕ (`...`) - -🚥 👆 💭 😬 ⚙️ `...`, 👆 💪 🗄 & ⚙️ `Required` ⚪️➡️ Pydantic: - -```Python hl_lines="2 8" -{!../../../docs_src/query_params_str_validations/tutorial006d.py!} -``` - -!!! tip - 💭 👈 🌅 💼, 🕐❔ 🕳 🚚, 👆 💪 🎯 🚫 `default` 🔢, 👆 🛎 🚫 ✔️ ⚙️ `...` 🚫 `Required`. +/// ## 🔢 🔢 📇 / 💗 💲 @@ -246,23 +168,7 @@ q: Union[str, None] = Query(default=None, min_length=3) 🖼, 📣 🔢 🔢 `q` 👈 💪 😑 💗 🕰 📛, 👆 💪 ✍: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!} - ``` +{* ../../docs_src/query_params_str_validations/tutorial011.py hl[9] *} ⤴️, ⏮️ 📛 💖: @@ -283,8 +189,11 @@ http://localhost:8000/items/?q=foo&q=bar } ``` -!!! tip - 📣 🔢 🔢 ⏮️ 🆎 `list`, 💖 🖼 🔛, 👆 💪 🎯 ⚙️ `Query`, ⏪ ⚫️ 🔜 🔬 📨 💪. +/// tip + +📣 🔢 🔢 ⏮️ 🆎 `list`, 💖 🖼 🔛, 👆 💪 🎯 ⚙️ `Query`, ⏪ ⚫️ 🔜 🔬 📨 💪. + +/// 🎓 🛠️ 🩺 🔜 ℹ ➡️, ✔ 💗 💲: @@ -294,17 +203,7 @@ http://localhost:8000/items/?q=foo&q=bar & 👆 💪 🔬 🔢 `list` 💲 🚥 👌 🚚: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial012.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!} - ``` +{* ../../docs_src/query_params_str_validations/tutorial012.py hl[9] *} 🚥 👆 🚶: @@ -327,14 +226,15 @@ http://localhost:8000/items/ 👆 💪 ⚙️ `list` 🔗 ↩️ `List[str]` (⚖️ `list[str]` 🐍 3️⃣.9️⃣ ➕): -```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial013.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial013.py hl[7] *} + +/// note -!!! note - ✔️ 🤯 👈 👉 💼, FastAPI 🏆 🚫 ✅ 🎚 📇. +✔️ 🤯 👈 👉 💼, FastAPI 🏆 🚫 ✅ 🎚 📇. - 🖼, `List[int]` 🔜 ✅ (& 📄) 👈 🎚 📇 🔢. ✋️ `list` 😞 🚫🔜. +🖼, `List[int]` 🔜 ✅ (& 📄) 👈 🎚 📇 🔢. ✋️ `list` 😞 🚫🔜. + +/// ## 📣 🌅 🗃 @@ -342,38 +242,21 @@ http://localhost:8000/items/ 👈 ℹ 🔜 🔌 🏗 🗄 & ⚙️ 🧾 👩‍💻 🔢 & 🔢 🧰. -!!! note - ✔️ 🤯 👈 🎏 🧰 5️⃣📆 ✔️ 🎏 🎚 🗄 🐕‍🦺. - - 👫 💪 🚫 🎦 🌐 ➕ ℹ 📣, 👐 🌅 💼, ❌ ⚒ ⏪ 📄 🛠️. +/// note -👆 💪 🚮 `title`: +✔️ 🤯 👈 🎏 🧰 5️⃣📆 ✔️ 🎏 🎚 🗄 🐕‍🦺. -=== "🐍 3️⃣.6️⃣ & 🔛" +👫 💪 🚫 🎦 🌐 ➕ ℹ 📣, 👐 🌅 💼, ❌ ⚒ ⏪ 📄 🛠️. - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial007.py!} - ``` +/// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +👆 💪 🚮 `title`: - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!} - ``` +{* ../../docs_src/query_params_str_validations/tutorial007.py hl[10] *} & `description`: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="13" - {!> ../../../docs_src/query_params_str_validations/tutorial008.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!} - ``` +{* ../../docs_src/query_params_str_validations/tutorial008.py hl[13] *} ## 📛 🔢 @@ -393,17 +276,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems ⤴️ 👆 💪 📣 `alias`, & 👈 📛 ⚫️❔ 🔜 ⚙️ 🔎 🔢 💲: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial009.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!} - ``` +{* ../../docs_src/query_params_str_validations/tutorial009.py hl[9] *} ## 😛 🔢 @@ -413,17 +286,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems ⤴️ 🚶‍♀️ 🔢 `deprecated=True` `Query`: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="18" - {!> ../../../docs_src/query_params_str_validations/tutorial010.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="16" - {!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!} - ``` +{* ../../docs_src/query_params_str_validations/tutorial010.py hl[18] *} 🩺 🔜 🎦 ⚫️ 💖 👉: @@ -433,17 +296,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems 🚫 🔢 🔢 ⚪️➡️ 🏗 🗄 🔗 (& ➡️, ⚪️➡️ 🏧 🧾 ⚙️), ⚒ 🔢 `include_in_schema` `Query` `False`: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial014.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!} - ``` +{* ../../docs_src/query_params_str_validations/tutorial014.py hl[10] *} ## 🌃 diff --git a/docs/em/docs/tutorial/query-params.md b/docs/em/docs/tutorial/query-params.md index ccb235c15..5c8d868a9 100644 --- a/docs/em/docs/tutorial/query-params.md +++ b/docs/em/docs/tutorial/query-params.md @@ -2,9 +2,7 @@ 🕐❔ 👆 📣 🎏 🔢 🔢 👈 🚫 🍕 ➡ 🔢, 👫 🔁 🔬 "🔢" 🔢. -```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial001.py!} -``` +{* ../../docs_src/query_params/tutorial001.py hl[9] *} 🔢 ⚒ 🔑-💲 👫 👈 🚶 ⏮️ `?` 📛, 🎏 `&` 🦹. @@ -63,38 +61,21 @@ http://127.0.0.1:8000/items/?skip=20 🎏 🌌, 👆 💪 📣 📦 🔢 🔢, ⚒ 👫 🔢 `None`: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial002.py!} - ``` +{* ../../docs_src/query_params/tutorial002.py hl[9] *} -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +👉 💼, 🔢 🔢 `q` 🔜 📦, & 🔜 `None` 🔢. - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial002_py310.py!} - ``` +/// check -👉 💼, 🔢 🔢 `q` 🔜 📦, & 🔜 `None` 🔢. +👀 👈 **FastAPI** 🙃 🥃 👀 👈 ➡ 🔢 `item_id` ➡ 🔢 & `q` 🚫,, ⚫️ 🔢 🔢. -!!! check - 👀 👈 **FastAPI** 🙃 🥃 👀 👈 ➡ 🔢 `item_id` ➡ 🔢 & `q` 🚫,, ⚫️ 🔢 🔢. +/// ## 🔢 🔢 🆎 🛠️ 👆 💪 📣 `bool` 🆎, & 👫 🔜 🗜: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial003.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial003_py310.py!} - ``` +{* ../../docs_src/query_params/tutorial003.py hl[9] *} 👉 💼, 🚥 👆 🚶: @@ -137,17 +118,7 @@ http://127.0.0.1:8000/items/foo?short=yes 👫 🔜 🔬 📛: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="8 10" - {!> ../../../docs_src/query_params/tutorial004.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="6 8" - {!> ../../../docs_src/query_params/tutorial004_py310.py!} - ``` +{* ../../docs_src/query_params/tutorial004.py hl[8,10] *} ## ✔ 🔢 🔢 @@ -157,9 +128,7 @@ http://127.0.0.1:8000/items/foo?short=yes ✋️ 🕐❔ 👆 💚 ⚒ 🔢 🔢 ✔, 👆 💪 🚫 📣 🙆 🔢 💲: -```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} -``` +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} 📥 🔢 🔢 `needy` ✔ 🔢 🔢 🆎 `str`. @@ -203,17 +172,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy & ↗️, 👆 💪 🔬 🔢 ✔, ✔️ 🔢 💲, & 🍕 📦: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="10" - {!> ../../../docs_src/query_params/tutorial006.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="8" - {!> ../../../docs_src/query_params/tutorial006_py310.py!} - ``` +{* ../../docs_src/query_params/tutorial006.py hl[10] *} 👉 💼, 📤 3️⃣ 🔢 🔢: @@ -221,5 +180,8 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy * `skip`, `int` ⏮️ 🔢 💲 `0`. * `limit`, 📦 `int`. -!!! tip - 👆 💪 ⚙️ `Enum`Ⓜ 🎏 🌌 ⏮️ [➡ 🔢](path-params.md#predefined-values){.internal-link target=_blank}. +/// tip + +👆 💪 ⚙️ `Enum`Ⓜ 🎏 🌌 ⏮️ [➡ 🔢](path-params.md#_7){.internal-link target=_blank}. + +/// diff --git a/docs/em/docs/tutorial/request-files.md b/docs/em/docs/tutorial/request-files.md index 26631823f..c3bdeafd4 100644 --- a/docs/em/docs/tutorial/request-files.md +++ b/docs/em/docs/tutorial/request-files.md @@ -2,36 +2,41 @@ 👆 💪 🔬 📁 📂 👩‍💻 ⚙️ `File`. -!!! info - 📨 📂 📁, 🥇 ❎ `python-multipart`. +/// info - 🤶 Ⓜ. `pip install python-multipart`. +📨 📂 📁, 🥇 ❎ `python-multipart`. - 👉 ↩️ 📂 📁 📨 "📨 💽". +🤶 Ⓜ. `pip install python-multipart`. + +👉 ↩️ 📂 📁 📨 "📨 💽". + +/// ## 🗄 `File` 🗄 `File` & `UploadFile` ⚪️➡️ `fastapi`: -```Python hl_lines="1" -{!../../../docs_src/request_files/tutorial001.py!} -``` +{* ../../docs_src/request_files/tutorial001.py hl[1] *} ## 🔬 `File` 🔢 ✍ 📁 🔢 🎏 🌌 👆 🔜 `Body` ⚖️ `Form`: -```Python hl_lines="7" -{!../../../docs_src/request_files/tutorial001.py!} -``` +{* ../../docs_src/request_files/tutorial001.py hl[7] *} + +/// info + +`File` 🎓 👈 😖 🔗 ⚪️➡️ `Form`. + +✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `File` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. -!!! info - `File` 🎓 👈 😖 🔗 ⚪️➡️ `Form`. +/// - ✋️ 💭 👈 🕐❔ 👆 🗄 `Query`, `Path`, `File` & 🎏 ⚪️➡️ `fastapi`, 👈 🤙 🔢 👈 📨 🎁 🎓. +/// tip -!!! tip - 📣 📁 💪, 👆 💪 ⚙️ `File`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢. +📣 📁 💪, 👆 💪 ⚙️ `File`, ↩️ ⏪ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢. + +/// 📁 🔜 📂 "📨 💽". @@ -45,9 +50,7 @@ 🔬 📁 🔢 ⏮️ 🆎 `UploadFile`: -```Python hl_lines="12" -{!../../../docs_src/request_files/tutorial001.py!} -``` +{* ../../docs_src/request_files/tutorial001.py hl[12] *} ⚙️ `UploadFile` ✔️ 📚 📈 🤭 `bytes`: @@ -90,11 +93,17 @@ contents = await myfile.read() contents = myfile.file.read() ``` -!!! note "`async` 📡 ℹ" - 🕐❔ 👆 ⚙️ `async` 👩‍🔬, **FastAPI** 🏃 📁 👩‍🔬 🧵 & ⌛ 👫. +/// note | `async` 📡 ℹ + +🕐❔ 👆 ⚙️ `async` 👩‍🔬, **FastAPI** 🏃 📁 👩‍🔬 🧵 & ⌛ 👫. + +/// + +/// note | 💃 📡 ℹ + +**FastAPI**'Ⓜ `UploadFile` 😖 🔗 ⚪️➡️ **💃**'Ⓜ `UploadFile`, ✋️ 🚮 💪 🍕 ⚒ ⚫️ 🔗 ⏮️ **Pydantic** & 🎏 🍕 FastAPI. -!!! note "💃 📡 ℹ" - **FastAPI**'Ⓜ `UploadFile` 😖 🔗 ⚪️➡️ **💃**'Ⓜ `UploadFile`, ✋️ 🚮 💪 🍕 ⚒ ⚫️ 🔗 ⏮️ **Pydantic** & 🎏 🍕 FastAPI. +/// ## ⚫️❔ "📨 💽" @@ -102,41 +111,35 @@ contents = myfile.file.read() **FastAPI** 🔜 ⚒ 💭 ✍ 👈 📊 ⚪️➡️ ▶️️ 🥉 ↩️ 🎻. -!!! note "📡 ℹ" - 📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded` 🕐❔ ⚫️ 🚫 🔌 📁. +/// note | 📡 ℹ - ✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 🚥 👆 ⚙️ `File`, **FastAPI** 🔜 💭 ⚫️ ✔️ 🤚 📁 ⚪️➡️ ☑ 🍕 💪. +📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded` 🕐❔ ⚫️ 🚫 🔌 📁. - 🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 🏇 🕸 🩺 POST. +✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 🚥 👆 ⚙️ `File`, **FastAPI** 🔜 💭 ⚫️ ✔️ 🤚 📁 ⚪️➡️ ☑ 🍕 💪. -!!! warning - 👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`. +🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 🏇 🕸 🩺 POST. - 👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️. +/// -## 📦 📁 📂 +/// warning -👆 💪 ⚒ 📁 📦 ⚙️ 🐩 🆎 ✍ & ⚒ 🔢 💲 `None`: +👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`. + +👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️. -=== "🐍 3️⃣.6️⃣ & 🔛" +/// - ```Python hl_lines="9 17" - {!> ../../../docs_src/request_files/tutorial001_02.py!} - ``` +## 📦 📁 📂 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +👆 💪 ⚒ 📁 📦 ⚙️ 🐩 🆎 ✍ & ⚒ 🔢 💲 `None`: - ```Python hl_lines="7 14" - {!> ../../../docs_src/request_files/tutorial001_02_py310.py!} - ``` +{* ../../docs_src/request_files/tutorial001_02.py hl[9,17] *} ## `UploadFile` ⏮️ 🌖 🗃 👆 💪 ⚙️ `File()` ⏮️ `UploadFile`, 🖼, ⚒ 🌖 🗃: -```Python hl_lines="13" -{!../../../docs_src/request_files/tutorial001_03.py!} -``` +{* ../../docs_src/request_files/tutorial001_03.py hl[13] *} ## 💗 📁 📂 @@ -146,40 +149,23 @@ contents = myfile.file.read() ⚙️ 👈, 📣 📇 `bytes` ⚖️ `UploadFile`: -=== "🐍 3️⃣.6️⃣ & 🔛" +{* ../../docs_src/request_files/tutorial002.py hl[10,15] *} - ```Python hl_lines="10 15" - {!> ../../../docs_src/request_files/tutorial002.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" +👆 🔜 📨, 📣, `list` `bytes` ⚖️ `UploadFile`Ⓜ. - ```Python hl_lines="8 13" - {!> ../../../docs_src/request_files/tutorial002_py39.py!} - ``` +/// note | 📡 ℹ -👆 🔜 📨, 📣, `list` `bytes` ⚖️ `UploadFile`Ⓜ. +👆 💪 ⚙️ `from starlette.responses import HTMLResponse`. -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.responses import HTMLResponse`. +**FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. - **FastAPI** 🚚 🎏 `starlette.responses` `fastapi.responses` 🏪 👆, 👩‍💻. ✋️ 🌅 💪 📨 👟 🔗 ⚪️➡️ 💃. +/// ### 💗 📁 📂 ⏮️ 🌖 🗃 & 🎏 🌌 ⏭, 👆 💪 ⚙️ `File()` ⚒ 🌖 🔢, `UploadFile`: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="18" - {!> ../../../docs_src/request_files/tutorial003.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="16" - {!> ../../../docs_src/request_files/tutorial003_py39.py!} - ``` +{* ../../docs_src/request_files/tutorial003.py hl[18] *} ## 🌃 diff --git a/docs/em/docs/tutorial/request-forms-and-files.md b/docs/em/docs/tutorial/request-forms-and-files.md index 99aeca000..680b1a96a 100644 --- a/docs/em/docs/tutorial/request-forms-and-files.md +++ b/docs/em/docs/tutorial/request-forms-and-files.md @@ -2,33 +2,35 @@ 👆 💪 🔬 📁 & 📨 🏑 🎏 🕰 ⚙️ `File` & `Form`. -!!! info - 📨 📂 📁 & /⚖️ 📨 📊, 🥇 ❎ `python-multipart`. +/// info - 🤶 Ⓜ. `pip install python-multipart`. +📨 📂 📁 & /⚖️ 📨 📊, 🥇 ❎ `python-multipart`. + +🤶 Ⓜ. `pip install python-multipart`. + +/// ## 🗄 `File` & `Form` -```Python hl_lines="1" -{!../../../docs_src/request_forms_and_files/tutorial001.py!} -``` +{* ../../docs_src/request_forms_and_files/tutorial001.py hl[1] *} ## 🔬 `File` & `Form` 🔢 ✍ 📁 & 📨 🔢 🎏 🌌 👆 🔜 `Body` ⚖️ `Query`: -```Python hl_lines="8" -{!../../../docs_src/request_forms_and_files/tutorial001.py!} -``` +{* ../../docs_src/request_forms_and_files/tutorial001.py hl[8] *} 📁 & 📨 🏑 🔜 📂 📨 📊 & 👆 🔜 📨 📁 & 📨 🏑. & 👆 💪 📣 📁 `bytes` & `UploadFile`. -!!! warning - 👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`. +/// warning + +👆 💪 📣 💗 `File` & `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `multipart/form-data` ↩️ `application/json`. + +👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️. - 👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️. +/// ## 🌃 diff --git a/docs/em/docs/tutorial/request-forms.md b/docs/em/docs/tutorial/request-forms.md index fa74adae5..1cc1ea5dc 100644 --- a/docs/em/docs/tutorial/request-forms.md +++ b/docs/em/docs/tutorial/request-forms.md @@ -2,26 +2,25 @@ 🕐❔ 👆 💪 📨 📨 🏑 ↩️ 🎻, 👆 💪 ⚙️ `Form`. -!!! info - ⚙️ 📨, 🥇 ❎ `python-multipart`. +/// info - 🤶 Ⓜ. `pip install python-multipart`. +⚙️ 📨, 🥇 ❎ `python-multipart`. + +🤶 Ⓜ. `pip install python-multipart`. + +/// ## 🗄 `Form` 🗄 `Form` ⚪️➡️ `fastapi`: -```Python hl_lines="1" -{!../../../docs_src/request_forms/tutorial001.py!} -``` +{* ../../docs_src/request_forms/tutorial001.py hl[1] *} ## 🔬 `Form` 🔢 ✍ 📨 🔢 🎏 🌌 👆 🔜 `Body` ⚖️ `Query`: -```Python hl_lines="7" -{!../../../docs_src/request_forms/tutorial001.py!} -``` +{* ../../docs_src/request_forms/tutorial001.py hl[7] *} 🖼, 1️⃣ 🌌 Oauth2️⃣ 🔧 💪 ⚙️ (🤙 "🔐 💧") ⚫️ ✔ 📨 `username` & `password` 📨 🏑. @@ -29,11 +28,17 @@ ⏮️ `Form` 👆 💪 📣 🎏 📳 ⏮️ `Body` (& `Query`, `Path`, `Cookie`), 🔌 🔬, 🖼, 📛 (✅ `user-name` ↩️ `username`), ♒️. -!!! info - `Form` 🎓 👈 😖 🔗 ⚪️➡️ `Body`. +/// info + +`Form` 🎓 👈 😖 🔗 ⚪️➡️ `Body`. + +/// + +/// tip -!!! tip - 📣 📨 💪, 👆 💪 ⚙️ `Form` 🎯, ↩️ 🍵 ⚫️ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢. +📣 📨 💪, 👆 💪 ⚙️ `Form` 🎯, ↩️ 🍵 ⚫️ 🔢 🔜 🔬 🔢 🔢 ⚖️ 💪 (🎻) 🔢. + +/// ## 🔃 "📨 🏑" @@ -41,17 +46,23 @@ **FastAPI** 🔜 ⚒ 💭 ✍ 👈 📊 ⚪️➡️ ▶️️ 🥉 ↩️ 🎻. -!!! note "📡 ℹ" - 📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded`. +/// note | 📡 ℹ + +📊 ⚪️➡️ 📨 🛎 🗜 ⚙️ "📻 🆎" `application/x-www-form-urlencoded`. + +✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 👆 🔜 ✍ 🔃 🚚 📁 ⏭ 📃. + +🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 🏇 🕸 🩺 POST. + +/// - ✋️ 🕐❔ 📨 🔌 📁, ⚫️ 🗜 `multipart/form-data`. 👆 🔜 ✍ 🔃 🚚 📁 ⏭ 📃. +/// warning - 🚥 👆 💚 ✍ 🌖 🔃 👉 🔢 & 📨 🏑, 👳 🏇 🕸 🩺 POST. +👆 💪 📣 💗 `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `application/x-www-form-urlencoded` ↩️ `application/json`. -!!! warning - 👆 💪 📣 💗 `Form` 🔢 *➡ 🛠️*, ✋️ 👆 💪 🚫 📣 `Body` 🏑 👈 👆 ⌛ 📨 🎻, 📨 🔜 ✔️ 💪 🗜 ⚙️ `application/x-www-form-urlencoded` ↩️ `application/json`. +👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️. - 👉 🚫 🚫 **FastAPI**, ⚫️ 🍕 🇺🇸🔍 🛠️. +/// ## 🌃 diff --git a/docs/em/docs/tutorial/response-model.md b/docs/em/docs/tutorial/response-model.md index 6ea4413f8..477376458 100644 --- a/docs/em/docs/tutorial/response-model.md +++ b/docs/em/docs/tutorial/response-model.md @@ -4,23 +4,7 @@ 👆 💪 ⚙️ **🆎 ✍** 🎏 🌌 👆 🔜 🔢 💽 🔢 **🔢**, 👆 💪 ⚙️ Pydantic 🏷, 📇, 📖, 📊 💲 💖 🔢, 🎻, ♒️. -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="18 23" - {!> ../../../docs_src/response_model/tutorial001_01.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="18 23" - {!> ../../../docs_src/response_model/tutorial001_01_py39.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="16 21" - {!> ../../../docs_src/response_model/tutorial001_01_py310.py!} - ``` +{* ../../docs_src/response_model/tutorial001_01.py hl[18,23] *} FastAPI 🔜 ⚙️ 👉 📨 🆎: @@ -53,35 +37,25 @@ FastAPI 🔜 ⚙️ 👉 📨 🆎: * `@app.delete()` * ♒️. -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" +{* ../../docs_src/response_model/tutorial001.py hl[17,22,24:27] *} - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001_py39.py!} - ``` +/// note -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +👀 👈 `response_model` 🔢 "👨‍🎨" 👩‍🔬 (`get`, `post`, ♒️). 🚫 👆 *➡ 🛠️ 🔢*, 💖 🌐 🔢 & 💪. - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001_py310.py!} - ``` - -!!! note - 👀 👈 `response_model` 🔢 "👨‍🎨" 👩‍🔬 (`get`, `post`, ♒️). 🚫 👆 *➡ 🛠️ 🔢*, 💖 🌐 🔢 & 💪. +/// `response_model` 📨 🎏 🆎 👆 🔜 📣 Pydantic 🏷 🏑,, ⚫️ 💪 Pydantic 🏷, ✋️ ⚫️ 💪, ✅ `list` Pydantic 🏷, 💖 `List[Item]`. FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & **🗜 & ⛽ 🔢 📊** 🚮 🆎 📄. -!!! tip - 🚥 👆 ✔️ ⚠ 🆎 ✅ 👆 👨‍🎨, ✍, ♒️, 👆 💪 📣 🔢 📨 🆎 `Any`. +/// tip + +🚥 👆 ✔️ ⚠ 🆎 ✅ 👆 👨‍🎨, ✍, ♒️, 👆 💪 📣 🔢 📨 🆎 `Any`. - 👈 🌌 👆 💬 👨‍🎨 👈 👆 😫 🛬 🕳. ✋️ FastAPI 🔜 💽 🧾, 🔬, 🖥, ♒️. ⏮️ `response_model`. +👈 🌌 👆 💬 👨‍🎨 👈 👆 😫 🛬 🕳. ✋️ FastAPI 🔜 💽 🧾, 🔬, 🖥, ♒️. ⏮️ `response_model`. + +/// ### `response_model` 📫 @@ -95,37 +69,20 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** 📥 👥 📣 `UserIn` 🏷, ⚫️ 🔜 🔌 🔢 🔐: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="9 11" - {!> ../../../docs_src/response_model/tutorial002.py!} - ``` +{* ../../docs_src/response_model/tutorial002.py hl[9,11] *} -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// info - ```Python hl_lines="7 9" - {!> ../../../docs_src/response_model/tutorial002_py310.py!} - ``` +⚙️ `EmailStr`, 🥇 ❎ `email-validator`. -!!! info - ⚙️ `EmailStr`, 🥇 ❎ `email_validator`. +🤶 Ⓜ. `pip install email-validator` +⚖️ `pip install pydantic[email]`. - 🤶 Ⓜ. `pip install email-validator` - ⚖️ `pip install pydantic[email]`. +/// & 👥 ⚙️ 👉 🏷 📣 👆 🔢 & 🎏 🏷 📣 👆 🔢: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="18" - {!> ../../../docs_src/response_model/tutorial002.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="16" - {!> ../../../docs_src/response_model/tutorial002_py310.py!} - ``` +{* ../../docs_src/response_model/tutorial002.py hl[18] *} 🔜, 🕐❔ 🖥 🏗 👩‍💻 ⏮️ 🔐, 🛠️ 🔜 📨 🎏 🔐 📨. @@ -133,52 +90,25 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** ✋️ 🚥 👥 ⚙️ 🎏 🏷 ➕1️⃣ *➡ 🛠️*, 👥 💪 📨 👆 👩‍💻 🔐 🔠 👩‍💻. -!!! danger - 🙅 🏪 ✅ 🔐 👩‍💻 ⚖️ 📨 ⚫️ 📨 💖 👉, 🚥 👆 💭 🌐 ⚠ & 👆 💭 ⚫️❔ 👆 🔨. +/// danger -## 🚮 🔢 🏷 - -👥 💪 ↩️ ✍ 🔢 🏷 ⏮️ 🔢 🔐 & 🔢 🏷 🍵 ⚫️: +🙅 🏪 ✅ 🔐 👩‍💻 ⚖️ 📨 ⚫️ 📨 💖 👉, 🚥 👆 💭 🌐 ⚠ & 👆 💭 ⚫️❔ 👆 🔨. -=== "🐍 3️⃣.6️⃣ & 🔛" +/// - ```Python hl_lines="9 11 16" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +## 🚮 🔢 🏷 -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +👥 💪 ↩️ ✍ 🔢 🏷 ⏮️ 🔢 🔐 & 🔢 🏷 🍵 ⚫️: - ```Python hl_lines="9 11 16" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +{* ../../docs_src/response_model/tutorial003.py hl[9,11,16] *} 📥, ✋️ 👆 *➡ 🛠️ 🔢* 🛬 🎏 🔢 👩‍💻 👈 🔌 🔐: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +{* ../../docs_src/response_model/tutorial003.py hl[24] *} ...👥 📣 `response_model` 👆 🏷 `UserOut`, 👈 🚫 🔌 🔐: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +{* ../../docs_src/response_model/tutorial003.py hl[22] *} , **FastAPI** 🔜 ✊ 💅 🖥 👅 🌐 💽 👈 🚫 📣 🔢 🏷 (⚙️ Pydantic). @@ -202,17 +132,7 @@ FastAPI 🔜 ⚙️ 👉 `response_model` 🌐 💽 🧾, 🔬, ♒️. & ** & 👈 💼, 👥 💪 ⚙️ 🎓 & 🧬 ✊ 📈 🔢 **🆎 ✍** 🤚 👍 🐕‍🦺 👨‍🎨 & 🧰, & 🤚 FastAPI **💽 🖥**. -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="9-13 15-16 20" - {!> ../../../docs_src/response_model/tutorial003_01.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="7-10 13-14 18" - {!> ../../../docs_src/response_model/tutorial003_01_py310.py!} - ``` +{* ../../docs_src/response_model/tutorial003_01.py hl[9:13,15:16,20] *} ⏮️ 👉, 👥 🤚 🏭 🐕‍🦺, ⚪️➡️ 👨‍🎨 & ✍ 👉 📟 ☑ ⚖ 🆎, ✋️ 👥 🤚 💽 🖥 ⚪️➡️ FastAPI. @@ -254,9 +174,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 🏆 ⚠ 💼 🔜 [🛬 📨 🔗 🔬 ⏪ 🏧 🩺](../advanced/response-directly.md){.internal-link target=_blank}. -```Python hl_lines="8 10-11" -{!> ../../../docs_src/response_model/tutorial003_02.py!} -``` +{* ../../docs_src/response_model/tutorial003_02.py hl[8,10:11] *} 👉 🙅 💼 🍵 🔁 FastAPI ↩️ 📨 🆎 ✍ 🎓 (⚖️ 🏿) `Response`. @@ -266,9 +184,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 👆 💪 ⚙️ 🏿 `Response` 🆎 ✍: -```Python hl_lines="8-9" -{!> ../../../docs_src/response_model/tutorial003_03.py!} -``` +{* ../../docs_src/response_model/tutorial003_03.py hl[8:9] *} 👉 🔜 👷 ↩️ `RedirectResponse` 🏿 `Response`, & FastAPI 🔜 🔁 🍵 👉 🙅 💼. @@ -278,17 +194,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 🎏 🔜 🔨 🚥 👆 ✔️ 🕳 💖 🇪🇺 🖖 🎏 🆎 🌐❔ 1️⃣ ⚖️ 🌅 👫 🚫 ☑ Pydantic 🆎, 🖼 👉 🔜 ❌ 👶: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="10" - {!> ../../../docs_src/response_model/tutorial003_04.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="8" - {!> ../../../docs_src/response_model/tutorial003_04_py310.py!} - ``` +{* ../../docs_src/response_model/tutorial003_04.py hl[10] *} ...👉 ❌ ↩️ 🆎 ✍ 🚫 Pydantic 🆎 & 🚫 👁 `Response` 🎓 ⚖️ 🏿, ⚫️ 🇪🇺 (🙆 2️⃣) 🖖 `Response` & `dict`. @@ -300,17 +206,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 👉 💼, 👆 💪 ❎ 📨 🏷 ⚡ ⚒ `response_model=None`: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="9" - {!> ../../../docs_src/response_model/tutorial003_05.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="7" - {!> ../../../docs_src/response_model/tutorial003_05_py310.py!} - ``` +{* ../../docs_src/response_model/tutorial003_05.py hl[9] *} 👉 🔜 ⚒ FastAPI 🚶 📨 🏷 ⚡ & 👈 🌌 👆 💪 ✔️ 🙆 📨 🆎 ✍ 👆 💪 🍵 ⚫️ 🤕 👆 FastAPI 🈸. 👶 @@ -318,23 +214,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 👆 📨 🏷 💪 ✔️ 🔢 💲, 💖: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="11 13-14" - {!> ../../../docs_src/response_model/tutorial004.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="11 13-14" - {!> ../../../docs_src/response_model/tutorial004_py39.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="9 11-12" - {!> ../../../docs_src/response_model/tutorial004_py310.py!} - ``` +{* ../../docs_src/response_model/tutorial004.py hl[11,13:14] *} * `description: Union[str, None] = None` (⚖️ `str | None = None` 🐍 3️⃣.1️⃣0️⃣) ✔️ 🔢 `None`. * `tax: float = 10.5` ✔️ 🔢 `10.5`. @@ -348,23 +228,7 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 👆 💪 ⚒ *➡ 🛠️ 👨‍🎨* 🔢 `response_model_exclude_unset=True`: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial004.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial004_py39.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial004_py310.py!} - ``` +{* ../../docs_src/response_model/tutorial004.py hl[24] *} & 👈 🔢 💲 🏆 🚫 🔌 📨, 🕴 💲 🤙 ⚒. @@ -377,16 +241,22 @@ FastAPI 🔨 📚 👜 🔘 ⏮️ Pydantic ⚒ 💭 👈 📚 🎏 🚫 🎓 } ``` -!!! info - FastAPI ⚙️ Pydantic 🏷 `.dict()` ⏮️ 🚮 `exclude_unset` 🔢 🏆 👉. +/// info + +FastAPI ⚙️ Pydantic 🏷 `.dict()` ⏮️ 🚮 `exclude_unset` 🔢 🏆 👉. + +/// + +/// info -!!! info - 👆 💪 ⚙️: +👆 💪 ⚙️: - * `response_model_exclude_defaults=True` - * `response_model_exclude_none=True` +* `response_model_exclude_defaults=True` +* `response_model_exclude_none=True` - 🔬 Pydantic 🩺 `exclude_defaults` & `exclude_none`. +🔬 Pydantic 🩺 `exclude_defaults` & `exclude_none`. + +/// #### 📊 ⏮️ 💲 🏑 ⏮️ 🔢 @@ -421,10 +291,13 @@ FastAPI 🙃 🥃 (🤙, Pydantic 🙃 🥃) 🤔 👈, ✋️ `description`, `t , 👫 🔜 🔌 🎻 📨. -!!! tip - 👀 👈 🔢 💲 💪 🕳, 🚫 🕴 `None`. +/// tip + +👀 👈 🔢 💲 💪 🕳, 🚫 🕴 `None`. - 👫 💪 📇 (`[]`), `float` `10.5`, ♒️. +👫 💪 📇 (`[]`), `float` `10.5`, ♒️. + +/// ### `response_model_include` & `response_model_exclude` @@ -434,45 +307,31 @@ FastAPI 🙃 🥃 (🤙, Pydantic 🙃 🥃) 🤔 👈, ✋️ `description`, `t 👉 💪 ⚙️ ⏩ ⌨ 🚥 👆 ✔️ 🕴 1️⃣ Pydantic 🏷 & 💚 ❎ 💽 ⚪️➡️ 🔢. -!!! tip - ✋️ ⚫️ 👍 ⚙️ 💭 🔛, ⚙️ 💗 🎓, ↩️ 👫 🔢. +/// tip + +✋️ ⚫️ 👍 ⚙️ 💭 🔛, ⚙️ 💗 🎓, ↩️ 👫 🔢. - 👉 ↩️ 🎻 🔗 🏗 👆 📱 🗄 (& 🩺) 🔜 1️⃣ 🏁 🏷, 🚥 👆 ⚙️ `response_model_include` ⚖️ `response_model_exclude` 🚫 🔢. +👉 ↩️ 🎻 🔗 🏗 👆 📱 🗄 (& 🩺) 🔜 1️⃣ 🏁 🏷, 🚥 👆 ⚙️ `response_model_include` ⚖️ `response_model_exclude` 🚫 🔢. - 👉 ✔ `response_model_by_alias` 👈 👷 ➡. +👉 ✔ `response_model_by_alias` 👈 👷 ➡. -=== "🐍 3️⃣.6️⃣ & 🔛" +/// - ```Python hl_lines="31 37" - {!> ../../../docs_src/response_model/tutorial005.py!} - ``` +{* ../../docs_src/response_model/tutorial005.py hl[31,37] *} -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// tip - ```Python hl_lines="29 35" - {!> ../../../docs_src/response_model/tutorial005_py310.py!} - ``` +❕ `{"name", "description"}` ✍ `set` ⏮️ 📚 2️⃣ 💲. -!!! tip - ❕ `{"name", "description"}` ✍ `set` ⏮️ 📚 2️⃣ 💲. +⚫️ 🌓 `set(["name", "description"])`. - ⚫️ 🌓 `set(["name", "description"])`. +/// #### ⚙️ `list`Ⓜ ↩️ `set`Ⓜ 🚥 👆 💭 ⚙️ `set` & ⚙️ `list` ⚖️ `tuple` ↩️, FastAPI 🔜 🗜 ⚫️ `set` & ⚫️ 🔜 👷 ☑: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="31 37" - {!> ../../../docs_src/response_model/tutorial006.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="29 35" - {!> ../../../docs_src/response_model/tutorial006_py310.py!} - ``` +{* ../../docs_src/response_model/tutorial006.py hl[31,37] *} ## 🌃 diff --git a/docs/em/docs/tutorial/response-status-code.md b/docs/em/docs/tutorial/response-status-code.md index e5149de7d..413ceb916 100644 --- a/docs/em/docs/tutorial/response-status-code.md +++ b/docs/em/docs/tutorial/response-status-code.md @@ -8,17 +8,21 @@ * `@app.delete()` * ♒️. -```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} -!!! note - 👀 👈 `status_code` 🔢 "👨‍🎨" 👩‍🔬 (`get`, `post`, ♒️). 🚫 👆 *➡ 🛠️ 🔢*, 💖 🌐 🔢 & 💪. +/// note + +👀 👈 `status_code` 🔢 "👨‍🎨" 👩‍🔬 (`get`, `post`, ♒️). 🚫 👆 *➡ 🛠️ 🔢*, 💖 🌐 🔢 & 💪. + +/// `status_code` 🔢 📨 🔢 ⏮️ 🇺🇸🔍 👔 📟. -!!! info - `status_code` 💪 👐 📨 `IntEnum`, ✅ 🐍 `http.HTTPStatus`. +/// info + +`status_code` 💪 👐 📨 `IntEnum`, ✅ 🐍 `http.HTTPStatus`. + +/// ⚫️ 🔜: @@ -27,15 +31,21 @@ -!!! note - 📨 📟 (👀 ⏭ 📄) 🎦 👈 📨 🔨 🚫 ✔️ 💪. +/// note + +📨 📟 (👀 ⏭ 📄) 🎦 👈 📨 🔨 🚫 ✔️ 💪. + +FastAPI 💭 👉, & 🔜 🏭 🗄 🩺 👈 🇵🇸 📤 🙅‍♂ 📨 💪. - FastAPI 💭 👉, & 🔜 🏭 🗄 🩺 👈 🇵🇸 📤 🙅‍♂ 📨 💪. +/// ## 🔃 🇺🇸🔍 👔 📟 -!!! note - 🚥 👆 ⏪ 💭 ⚫️❔ 🇺🇸🔍 👔 📟, 🚶 ⏭ 📄. +/// note + +🚥 👆 ⏪ 💭 ⚫️❔ 🇺🇸🔍 👔 📟, 🚶 ⏭ 📄. + +/// 🇺🇸🔍, 👆 📨 🔢 👔 📟 3️⃣ 9️⃣ 🍕 📨. @@ -54,16 +64,17 @@ * 💊 ❌ ⚪️➡️ 👩‍💻, 👆 💪 ⚙️ `400`. * `500` & 🔛 💽 ❌. 👆 🌖 🙅 ⚙️ 👫 🔗. 🕐❔ 🕳 🚶 ❌ 🍕 👆 🈸 📟, ⚖️ 💽, ⚫️ 🔜 🔁 📨 1️⃣ 👫 👔 📟. -!!! tip - 💭 🌅 🔃 🔠 👔 📟 & ❔ 📟 ⚫️❔, ✅ 🏇 🧾 🔃 🇺🇸🔍 👔 📟. +/// tip + +💭 🌅 🔃 🔠 👔 📟 & ❔ 📟 ⚫️❔, ✅ 🏇 🧾 🔃 🇺🇸🔍 👔 📟. + +/// ## ⌨ 💭 📛 ➡️ 👀 ⏮️ 🖼 🔄: -```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} `201` 👔 📟 "✍". @@ -71,18 +82,19 @@ 👆 💪 ⚙️ 🏪 🔢 ⚪️➡️ `fastapi.status`. -```Python hl_lines="1 6" -{!../../../docs_src/response_status_code/tutorial002.py!} -``` +{* ../../docs_src/response_status_code/tutorial002.py hl[1,6] *} 👫 🏪, 👫 🧑‍🤝‍🧑 🎏 🔢, ✋️ 👈 🌌 👆 💪 ⚙️ 👨‍🎨 📋 🔎 👫: -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette import status`. +/// note | 📡 ℹ + +👆 💪 ⚙️ `from starlette import status`. + +**FastAPI** 🚚 🎏 `starlette.status` `fastapi.status` 🏪 👆, 👩‍💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. - **FastAPI** 🚚 🎏 `starlette.status` `fastapi.status` 🏪 👆, 👩‍💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. +/// ## 🔀 🔢 diff --git a/docs/em/docs/tutorial/schema-extra-example.md b/docs/em/docs/tutorial/schema-extra-example.md index d5bf8810a..1bd314c51 100644 --- a/docs/em/docs/tutorial/schema-extra-example.md +++ b/docs/em/docs/tutorial/schema-extra-example.md @@ -6,26 +6,19 @@ ## Pydantic `schema_extra` -👆 💪 📣 `example` Pydantic 🏷 ⚙️ `Config` & `schema_extra`, 🔬 Pydantic 🩺: 🔗 🛃: +👆 💪 📣 `example` Pydantic 🏷 ⚙️ `Config` & `schema_extra`, 🔬 Pydantic 🩺: 🔗 🛃: -=== "🐍 3️⃣.6️⃣ & 🔛" +{* ../../docs_src/schema_extra_example/tutorial001.py hl[15:23] *} - ```Python hl_lines="15-23" - {!> ../../../docs_src/schema_extra_example/tutorial001.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +👈 ➕ ℹ 🔜 🚮-🔢 **🎻 🔗** 👈 🏷, & ⚫️ 🔜 ⚙️ 🛠️ 🩺. - ```Python hl_lines="13-21" - {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} - ``` +/// tip -👈 ➕ ℹ 🔜 🚮-🔢 **🎻 🔗** 👈 🏷, & ⚫️ 🔜 ⚙️ 🛠️ 🩺. +👆 💪 ⚙️ 🎏 ⚒ ↔ 🎻 🔗 & 🚮 👆 👍 🛃 ➕ ℹ. -!!! tip - 👆 💪 ⚙️ 🎏 ⚒ ↔ 🎻 🔗 & 🚮 👆 👍 🛃 ➕ ℹ. +🖼 👆 💪 ⚙️ ⚫️ 🚮 🗃 🕸 👩‍💻 🔢, ♒️. - 🖼 👆 💪 ⚙️ ⚫️ 🚮 🗃 🕸 👩‍💻 🔢, ♒️. +/// ## `Field` 🌖 ❌ @@ -33,20 +26,13 @@ 👆 💪 ⚙️ 👉 🚮 `example` 🔠 🏑: -=== "🐍 3️⃣.6️⃣ & 🔛" +{* ../../docs_src/schema_extra_example/tutorial002.py hl[4,10:13] *} - ```Python hl_lines="4 10-13" - {!> ../../../docs_src/schema_extra_example/tutorial002.py!} - ``` +/// warning -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +🚧 🤯 👈 📚 ➕ ❌ 🚶‍♀️ 🏆 🚫 🚮 🙆 🔬, 🕴 ➕ ℹ, 🧾 🎯. - ```Python hl_lines="2 8-11" - {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} - ``` - -!!! warning - 🚧 🤯 👈 📚 ➕ ❌ 🚶‍♀️ 🏆 🚫 🚮 🙆 🔬, 🕴 ➕ ℹ, 🧾 🎯. +/// ## `example` & `examples` 🗄 @@ -66,17 +52,7 @@ 📥 👥 🚶‍♀️ `example` 📊 ⌛ `Body()`: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="20-25" - {!> ../../../docs_src/schema_extra_example/tutorial003.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="18-23" - {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} - ``` +{* ../../docs_src/schema_extra_example/tutorial003.py hl[20:25] *} ### 🖼 🩺 🎚 @@ -97,17 +73,7 @@ * `value`: 👉 ☑ 🖼 🎦, ✅ `dict`. * `externalValue`: 🎛 `value`, 📛 ☝ 🖼. 👐 👉 5️⃣📆 🚫 🐕‍🦺 📚 🧰 `value`. -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="21-47" - {!> ../../../docs_src/schema_extra_example/tutorial004.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="19-45" - {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} - ``` +{* ../../docs_src/schema_extra_example/tutorial004.py hl[21:47] *} ### 🖼 🩺 🎚 @@ -117,10 +83,13 @@ ## 📡 ℹ -!!! warning - 👉 📶 📡 ℹ 🔃 🐩 **🎻 🔗** & **🗄**. +/// warning + +👉 📶 📡 ℹ 🔃 🐩 **🎻 🔗** & **🗄**. + +🚥 💭 🔛 ⏪ 👷 👆, 👈 💪 🥃, & 👆 🎲 🚫 💪 👉 ℹ, 💭 🆓 🚶 👫. - 🚥 💭 🔛 ⏪ 👷 👆, 👈 💪 🥃, & 👆 🎲 🚫 💪 👉 ℹ, 💭 🆓 🚶 👫. +/// 🕐❔ 👆 🚮 🖼 🔘 Pydantic 🏷, ⚙️ `schema_extra` ⚖️ `Field(example="something")` 👈 🖼 🚮 **🎻 🔗** 👈 Pydantic 🏷. diff --git a/docs/em/docs/tutorial/security/first-steps.md b/docs/em/docs/tutorial/security/first-steps.md index 6dec6f2c3..8fb459a65 100644 --- a/docs/em/docs/tutorial/security/first-steps.md +++ b/docs/em/docs/tutorial/security/first-steps.md @@ -20,18 +20,19 @@ 📁 🖼 📁 `main.py`: -```Python -{!../../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py *} ## 🏃 ⚫️ -!!! info - 🥇 ❎ `python-multipart`. +/// info + +🥇 ❎ `python-multipart`. - 🤶 Ⓜ. `pip install python-multipart`. +🤶 Ⓜ. `pip install python-multipart`. - 👉 ↩️ **Oauth2️⃣** ⚙️ "📨 📊" 📨 `username` & `password`. +👉 ↩️ **Oauth2️⃣** ⚙️ "📨 📊" 📨 `username` & `password`. + +/// 🏃 🖼 ⏮️: @@ -53,17 +54,23 @@ $ uvicorn main:app --reload -!!! check "✔ 🔼 ❗" - 👆 ⏪ ✔️ ✨ 🆕 "✔" 🔼. +/// check | ✔ 🔼 ❗ + +👆 ⏪ ✔️ ✨ 🆕 "✔" 🔼. - & 👆 *➡ 🛠️* ✔️ 🐥 🔒 🔝-▶️️ ↩ 👈 👆 💪 🖊. + & 👆 *➡ 🛠️* ✔️ 🐥 🔒 🔝-▶️️ ↩ 👈 👆 💪 🖊. + +/// & 🚥 👆 🖊 ⚫️, 👆 ✔️ 🐥 ✔ 📨 🆎 `username` & `password` (& 🎏 📦 🏑): -!!! note - ⚫️ 🚫 🤔 ⚫️❔ 👆 🆎 📨, ⚫️ 🏆 🚫 👷. ✋️ 👥 🔜 🤚 📤. +/// note + +⚫️ 🚫 🤔 ⚫️❔ 👆 🆎 📨, ⚫️ 🏆 🚫 👷. ✋️ 👥 🔜 🤚 📤. + +/// 👉 ↗️ 🚫 🕸 🏁 👩‍💻, ✋️ ⚫️ 👑 🏧 🧰 📄 🖥 🌐 👆 🛠️. @@ -105,36 +112,43 @@ Oauth2️⃣ 🔧 👈 👩‍💻 ⚖️ 🛠️ 💪 🔬 💽 👈 🔓 👩 👉 🖼 👥 🔜 ⚙️ **Oauth2️⃣**, ⏮️ **🔐** 💧, ⚙️ **📨** 🤝. 👥 👈 ⚙️ `OAuth2PasswordBearer` 🎓. -!!! info - "📨" 🤝 🚫 🕴 🎛. +/// info + +"📨" 🤝 🚫 🕴 🎛. - ✋️ ⚫️ 🏆 1️⃣ 👆 ⚙️ 💼. +✋️ ⚫️ 🏆 1️⃣ 👆 ⚙️ 💼. - & ⚫️ 💪 🏆 🏆 ⚙️ 💼, 🚥 👆 Oauth2️⃣ 🕴 & 💭 ⚫️❔ ⚫️❔ 📤 ➕1️⃣ 🎛 👈 ♣ 👻 👆 💪. + & ⚫️ 💪 🏆 🏆 ⚙️ 💼, 🚥 👆 Oauth2️⃣ 🕴 & 💭 ⚫️❔ ⚫️❔ 📤 ➕1️⃣ 🎛 👈 ♣ 👻 👆 💪. - 👈 💼, **FastAPI** 🚚 👆 ⏮️ 🧰 🏗 ⚫️. +👈 💼, **FastAPI** 🚚 👆 ⏮️ 🧰 🏗 ⚫️. + +/// 🕐❔ 👥 ✍ 👐 `OAuth2PasswordBearer` 🎓 👥 🚶‍♀️ `tokenUrl` 🔢. 👉 🔢 🔌 📛 👈 👩‍💻 (🕸 🏃 👩‍💻 🖥) 🔜 ⚙️ 📨 `username` & `password` ✔ 🤚 🤝. -```Python hl_lines="6" -{!../../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[6] *} + +/// tip -!!! tip - 📥 `tokenUrl="token"` 🔗 ⚖ 📛 `token` 👈 👥 🚫 ✍. ⚫️ ⚖ 📛, ⚫️ 🌓 `./token`. +📥 `tokenUrl="token"` 🔗 ⚖ 📛 `token` 👈 👥 🚫 ✍. ⚫️ ⚖ 📛, ⚫️ 🌓 `./token`. - ↩️ 👥 ⚙️ ⚖ 📛, 🚥 👆 🛠️ 🔎 `https://example.com/`, ⤴️ ⚫️ 🔜 🔗 `https://example.com/token`. ✋️ 🚥 👆 🛠️ 🔎 `https://example.com/api/v1/`, ⤴️ ⚫️ 🔜 🔗 `https://example.com/api/v1/token`. +↩️ 👥 ⚙️ ⚖ 📛, 🚥 👆 🛠️ 🔎 `https://example.com/`, ⤴️ ⚫️ 🔜 🔗 `https://example.com/token`. ✋️ 🚥 👆 🛠️ 🔎 `https://example.com/api/v1/`, ⤴️ ⚫️ 🔜 🔗 `https://example.com/api/v1/token`. - ⚙️ ⚖ 📛 ⚠ ⚒ 💭 👆 🈸 🚧 👷 🏧 ⚙️ 💼 💖 [⛅ 🗳](../../advanced/behind-a-proxy.md){.internal-link target=_blank}. +⚙️ ⚖ 📛 ⚠ ⚒ 💭 👆 🈸 🚧 👷 🏧 ⚙️ 💼 💖 [⛅ 🗳](../../advanced/behind-a-proxy.md){.internal-link target=_blank}. + +/// 👉 🔢 🚫 ✍ 👈 🔗 / *➡ 🛠️*, ✋️ 📣 👈 📛 `/token` 🔜 1️⃣ 👈 👩‍💻 🔜 ⚙️ 🤚 🤝. 👈 ℹ ⚙️ 🗄, & ⤴️ 🎓 🛠️ 🧾 ⚙️. 👥 🔜 🔜 ✍ ☑ ➡ 🛠️. -!!! info - 🚥 👆 📶 ⚠ "✍" 👆 💪 👎 👗 🔢 📛 `tokenUrl` ↩️ `token_url`. +/// info + +🚥 👆 📶 ⚠ "✍" 👆 💪 👎 👗 🔢 📛 `tokenUrl` ↩️ `token_url`. - 👈 ↩️ ⚫️ ⚙️ 🎏 📛 🗄 🔌. 👈 🚥 👆 💪 🔬 🌅 🔃 🙆 👫 💂‍♂ ⚖ 👆 💪 📁 & 📋 ⚫️ 🔎 🌖 ℹ 🔃 ⚫️. +👈 ↩️ ⚫️ ⚙️ 🎏 📛 🗄 🔌. 👈 🚥 👆 💪 🔬 🌅 🔃 🙆 👫 💂‍♂ ⚖ 👆 💪 📁 & 📋 ⚫️ 🔎 🌖 ℹ 🔃 ⚫️. + +/// `oauth2_scheme` 🔢 👐 `OAuth2PasswordBearer`, ✋️ ⚫️ "🇧🇲". @@ -150,18 +164,19 @@ oauth2_scheme(some, parameters) 🔜 👆 💪 🚶‍♀️ 👈 `oauth2_scheme` 🔗 ⏮️ `Depends`. -```Python hl_lines="10" -{!../../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[10] *} 👉 🔗 🔜 🚚 `str` 👈 🛠️ 🔢 `token` *➡ 🛠️ 🔢*. **FastAPI** 🔜 💭 👈 ⚫️ 💪 ⚙️ 👉 🔗 🔬 "💂‍♂ ⚖" 🗄 🔗 (& 🏧 🛠️ 🩺). -!!! info "📡 ℹ" - **FastAPI** 🔜 💭 👈 ⚫️ 💪 ⚙️ 🎓 `OAuth2PasswordBearer` (📣 🔗) 🔬 💂‍♂ ⚖ 🗄 ↩️ ⚫️ 😖 ⚪️➡️ `fastapi.security.oauth2.OAuth2`, ❔ 🔄 😖 ⚪️➡️ `fastapi.security.base.SecurityBase`. +/// info | 📡 ℹ + +**FastAPI** 🔜 💭 👈 ⚫️ 💪 ⚙️ 🎓 `OAuth2PasswordBearer` (📣 🔗) 🔬 💂‍♂ ⚖ 🗄 ↩️ ⚫️ 😖 ⚪️➡️ `fastapi.security.oauth2.OAuth2`, ❔ 🔄 😖 ⚪️➡️ `fastapi.security.base.SecurityBase`. + +🌐 💂‍♂ 🚙 👈 🛠️ ⏮️ 🗄 (& 🏧 🛠️ 🩺) 😖 ⚪️➡️ `SecurityBase`, 👈 ❔ **FastAPI** 💪 💭 ❔ 🛠️ 👫 🗄. - 🌐 💂‍♂ 🚙 👈 🛠️ ⏮️ 🗄 (& 🏧 🛠️ 🩺) 😖 ⚪️➡️ `SecurityBase`, 👈 ❔ **FastAPI** 💪 💭 ❔ 🛠️ 👫 🗄. +/// ## ⚫️❔ ⚫️ 🔨 diff --git a/docs/em/docs/tutorial/security/get-current-user.md b/docs/em/docs/tutorial/security/get-current-user.md index 455cb4f46..2f4a26f35 100644 --- a/docs/em/docs/tutorial/security/get-current-user.md +++ b/docs/em/docs/tutorial/security/get-current-user.md @@ -2,9 +2,7 @@ ⏮️ 📃 💂‍♂ ⚙️ (❔ 🧢 🔛 🔗 💉 ⚙️) 🤝 *➡ 🛠️ 🔢* `token` `str`: -```Python hl_lines="10" -{!../../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[10] *} ✋️ 👈 🚫 👈 ⚠. @@ -16,17 +14,7 @@ 🎏 🌌 👥 ⚙️ Pydantic 📣 💪, 👥 💪 ⚙️ ⚫️ 🙆 🙆: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="5 12-16" - {!> ../../../docs_src/security/tutorial002.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="3 10-14" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +{* ../../docs_src/security/tutorial002.py hl[5,12:16] *} ## ✍ `get_current_user` 🔗 @@ -38,63 +26,39 @@ 🎏 👥 🔨 ⏭ *➡ 🛠️* 🔗, 👆 🆕 🔗 `get_current_user` 🔜 📨 `token` `str` ⚪️➡️ 🎧-🔗 `oauth2_scheme`: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="25" - {!> ../../../docs_src/security/tutorial002.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="23" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +{* ../../docs_src/security/tutorial002.py hl[25] *} ## 🤚 👩‍💻 `get_current_user` 🔜 ⚙️ (❌) 🚙 🔢 👥 ✍, 👈 ✊ 🤝 `str` & 📨 👆 Pydantic `User` 🏷: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="19-22 26-27" - {!> ../../../docs_src/security/tutorial002.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="17-20 24-25" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +{* ../../docs_src/security/tutorial002.py hl[19:22,26:27] *} ## 💉 ⏮️ 👩‍💻 🔜 👥 💪 ⚙️ 🎏 `Depends` ⏮️ 👆 `get_current_user` *➡ 🛠️*: -=== "🐍 3️⃣.6️⃣ & 🔛" +{* ../../docs_src/security/tutorial002.py hl[31] *} - ```Python hl_lines="31" - {!> ../../../docs_src/security/tutorial002.py!} - ``` +👀 👈 👥 📣 🆎 `current_user` Pydantic 🏷 `User`. -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +👉 🔜 ℹ 🇺🇲 🔘 🔢 ⏮️ 🌐 🛠️ & 🆎 ✅. - ```Python hl_lines="29" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +/// tip -👀 👈 👥 📣 🆎 `current_user` Pydantic 🏷 `User`. +👆 5️⃣📆 💭 👈 📨 💪 📣 ⏮️ Pydantic 🏷. -👉 🔜 ℹ 🇺🇲 🔘 🔢 ⏮️ 🌐 🛠️ & 🆎 ✅. +📥 **FastAPI** 🏆 🚫 🤚 😨 ↩️ 👆 ⚙️ `Depends`. -!!! tip - 👆 5️⃣📆 💭 👈 📨 💪 📣 ⏮️ Pydantic 🏷. +/// - 📥 **FastAPI** 🏆 🚫 🤚 😨 ↩️ 👆 ⚙️ `Depends`. +/// check -!!! check - 🌌 👉 🔗 ⚙️ 🏗 ✔ 👥 ✔️ 🎏 🔗 (🎏 "☑") 👈 🌐 📨 `User` 🏷. +🌌 👉 🔗 ⚙️ 🏗 ✔ 👥 ✔️ 🎏 🔗 (🎏 "☑") 👈 🌐 📨 `User` 🏷. - 👥 🚫 🚫 ✔️ 🕴 1️⃣ 🔗 👈 💪 📨 👈 🆎 💽. +👥 🚫 🚫 ✔️ 🕴 1️⃣ 🔗 👈 💪 📨 👈 🆎 💽. + +/// ## 🎏 🏷 @@ -128,17 +92,7 @@ & 🌐 👉 💯 *➡ 🛠️* 💪 🤪 3️⃣ ⏸: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="30-32" - {!> ../../../docs_src/security/tutorial002.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="28-30" - {!> ../../../docs_src/security/tutorial002_py310.py!} - ``` +{* ../../docs_src/security/tutorial002.py hl[30:32] *} ## 🌃 diff --git a/docs/em/docs/tutorial/security/index.md b/docs/em/docs/tutorial/security/index.md index d76f7203f..1a47e5510 100644 --- a/docs/em/docs/tutorial/security/index.md +++ b/docs/em/docs/tutorial/security/index.md @@ -32,9 +32,11 @@ Oauth2️⃣ 🔧 👈 🔬 📚 🌌 🍵 🤝 & ✔. Oauth2️⃣ 🚫 ✔ ❔ 🗜 📻, ⚫️ ⌛ 👆 ✔️ 👆 🈸 🍦 ⏮️ 🇺🇸🔍. -!!! tip - 📄 🔃 **🛠️** 👆 🔜 👀 ❔ ⚒ 🆙 🇺🇸🔍 🆓, ⚙️ Traefik & ➡️ 🗜. +/// tip +📄 🔃 **🛠️** 👆 🔜 👀 ❔ ⚒ 🆙 🇺🇸🔍 🆓, ⚙️ Traefik & ➡️ 🗜. + +/// ## 👩‍💻 🔗 @@ -87,10 +89,13 @@ Oauth2️⃣ 🚫 ✔ ❔ 🗜 📻, ⚫️ ⌛ 👆 ✔️ 👆 🈸 🍦 ⏮ * 👉 🏧 🔍 ⚫️❔ 🔬 👩‍💻 🔗 🔧. -!!! tip - 🛠️ 🎏 🤝/✔ 🐕‍🦺 💖 🇺🇸🔍, 👱📔, 👱📔, 📂, ♒️. 💪 & 📶 ⏩. +/// tip + +🛠️ 🎏 🤝/✔ 🐕‍🦺 💖 🇺🇸🔍, 👱📔, 👱📔, 📂, ♒️. 💪 & 📶 ⏩. + +🌅 🏗 ⚠ 🏗 🤝/✔ 🐕‍🦺 💖 👈, ✋️ **FastAPI** 🤝 👆 🧰 ⚫️ 💪, ⏪ 🔨 🏋️ 🏋‍♂ 👆. - 🌅 🏗 ⚠ 🏗 🤝/✔ 🐕‍🦺 💖 👈, ✋️ **FastAPI** 🤝 👆 🧰 ⚫️ 💪, ⏪ 🔨 🏋️ 🏋‍♂ 👆. +/// ## **FastAPI** 🚙 diff --git a/docs/em/docs/tutorial/security/oauth2-jwt.md b/docs/em/docs/tutorial/security/oauth2-jwt.md index bc3c943f8..ee7bc2d28 100644 --- a/docs/em/docs/tutorial/security/oauth2-jwt.md +++ b/docs/em/docs/tutorial/security/oauth2-jwt.md @@ -44,10 +44,13 @@ $ pip install "python-jose[cryptography]" 📥 👥 ⚙️ 👍 1️⃣: )/⚛. -!!! tip - 👉 🔰 ⏪ ⚙️ PyJWT. +/// tip - ✋️ ⚫️ ℹ ⚙️ 🐍-🇩🇬 ↩️ ⚫️ 🚚 🌐 ⚒ ⚪️➡️ PyJWT ➕ ➕ 👈 👆 💪 💪 ⏪ 🕐❔ 🏗 🛠️ ⏮️ 🎏 🧰. +👉 🔰 ⏪ ⚙️ PyJWT. + +✋️ ⚫️ ℹ ⚙️ 🐍-🇩🇬 ↩️ ⚫️ 🚚 🌐 ⚒ ⚪️➡️ PyJWT ➕ ➕ 👈 👆 💪 💪 ⏪ 🕐❔ 🏗 🛠️ ⏮️ 🎏 🧰. + +/// ## 🔐 🔁 @@ -83,12 +86,15 @@ $ pip install "passlib[bcrypt]" -!!! tip - ⏮️ `passlib`, 👆 💪 🔗 ⚫️ 💪 ✍ 🔐 ✍ **✳**, **🏺** 💂‍♂ 🔌-⚖️ 📚 🎏. +/// tip + +⏮️ `passlib`, 👆 💪 🔗 ⚫️ 💪 ✍ 🔐 ✍ **✳**, **🏺** 💂‍♂ 🔌-⚖️ 📚 🎏. - , 👆 🔜 💪, 🖼, 💰 🎏 📊 ⚪️➡️ ✳ 🈸 💽 ⏮️ FastAPI 🈸. ⚖️ 📉 ↔ ✳ 🈸 ⚙️ 🎏 💽. +, 👆 🔜 💪, 🖼, 💰 🎏 📊 ⚪️➡️ ✳ 🈸 💽 ⏮️ FastAPI 🈸. ⚖️ 📉 ↔ ✳ 🈸 ⚙️ 🎏 💽. - & 👆 👩‍💻 🔜 💪 💳 ⚪️➡️ 👆 ✳ 📱 ⚖️ ⚪️➡️ 👆 **FastAPI** 📱, 🎏 🕰. + & 👆 👩‍💻 🔜 💪 💳 ⚪️➡️ 👆 ✳ 📱 ⚖️ ⚪️➡️ 👆 **FastAPI** 📱, 🎏 🕰. + +/// ## #️⃣ & ✔ 🔐 @@ -96,12 +102,15 @@ $ pip install "passlib[bcrypt]" ✍ 🇸🇲 "🔑". 👉 ⚫️❔ 🔜 ⚙️ #️⃣ & ✔ 🔐. -!!! tip - 🇸🇲 🔑 ✔️ 🛠️ ⚙️ 🎏 🔁 📊, 🔌 😢 🗝 🕐 🕴 ✔ ✔ 👫, ♒️. +/// tip + +🇸🇲 🔑 ✔️ 🛠️ ⚙️ 🎏 🔁 📊, 🔌 😢 🗝 🕐 🕴 ✔ ✔ 👫, ♒️. - 🖼, 👆 💪 ⚙️ ⚫️ ✍ & ✔ 🔐 🏗 ➕1️⃣ ⚙️ (💖 ✳) ✋️ #️⃣ 🙆 🆕 🔐 ⏮️ 🎏 📊 💖 🐡. +🖼, 👆 💪 ⚙️ ⚫️ ✍ & ✔ 🔐 🏗 ➕1️⃣ ⚙️ (💖 ✳) ✋️ #️⃣ 🙆 🆕 🔐 ⏮️ 🎏 📊 💖 🐡. - & 🔗 ⏮️ 🌐 👫 🎏 🕰. + & 🔗 ⏮️ 🌐 👫 🎏 🕰. + +/// ✍ 🚙 🔢 #️⃣ 🔐 👟 ⚪️➡️ 👩‍💻. @@ -109,20 +118,13 @@ $ pip install "passlib[bcrypt]" & ➕1️⃣ 1️⃣ 🔓 & 📨 👩‍💻. -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="7 48 55-56 59-60 69-75" - {!> ../../../docs_src/security/tutorial004.py!} - ``` +{* ../../docs_src/security/tutorial004.py hl[7,48,55:56,59:60,69:75] *} -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// note - ```Python hl_lines="6 47 54-55 58-59 68-74" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +🚥 👆 ✅ 🆕 (❌) 💽 `fake_users_db`, 👆 🔜 👀 ❔ #️⃣ 🔐 👀 💖 🔜: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`. -!!! note - 🚥 👆 ✅ 🆕 (❌) 💽 `fake_users_db`, 👆 🔜 👀 ❔ #️⃣ 🔐 👀 💖 🔜: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`. +/// ## 🍵 🥙 🤝 @@ -152,17 +154,7 @@ $ openssl rand -hex 32 ✍ 🚙 🔢 🏗 🆕 🔐 🤝. -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="6 12-14 28-30 78-86" - {!> ../../../docs_src/security/tutorial004.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="5 11-13 27-29 77-85" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +{* ../../docs_src/security/tutorial004.py hl[6,12:14,28:30,78:86] *} ## ℹ 🔗 @@ -172,17 +164,7 @@ $ openssl rand -hex 32 🚥 🤝 ❌, 📨 🇺🇸🔍 ❌ ▶️️ ↖️. -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="89-106" - {!> ../../../docs_src/security/tutorial004.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="88-105" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +{* ../../docs_src/security/tutorial004.py hl[89:106] *} ## ℹ `/token` *➡ 🛠️* @@ -190,17 +172,7 @@ $ openssl rand -hex 32 ✍ 🎰 🥙 🔐 🤝 & 📨 ⚫️. -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="115-130" - {!> ../../../docs_src/security/tutorial004.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="114-129" - {!> ../../../docs_src/security/tutorial004_py310.py!} - ``` +{* ../../docs_src/security/tutorial004.py hl[115:130] *} ### 📡 ℹ 🔃 🥙 "📄" `sub` @@ -239,8 +211,11 @@ $ openssl rand -hex 32 🆔: `johndoe` 🔐: `secret` -!!! check - 👀 👈 🕳 📟 🔢 🔐 "`secret`", 👥 🕴 ✔️ #️⃣ ⏬. +/// check + +👀 👈 🕳 📟 🔢 🔐 "`secret`", 👥 🕴 ✔️ #️⃣ ⏬. + +/// @@ -261,8 +236,11 @@ $ openssl rand -hex 32 -!!! note - 👀 🎚 `Authorization`, ⏮️ 💲 👈 ▶️ ⏮️ `Bearer `. +/// note + +👀 🎚 `Authorization`, ⏮️ 💲 👈 ▶️ ⏮️ `Bearer `. + +/// ## 🏧 ⚙️ ⏮️ `scopes` diff --git a/docs/em/docs/tutorial/security/simple-oauth2.md b/docs/em/docs/tutorial/security/simple-oauth2.md index 765d94039..1fd513d48 100644 --- a/docs/em/docs/tutorial/security/simple-oauth2.md +++ b/docs/em/docs/tutorial/security/simple-oauth2.md @@ -32,14 +32,17 @@ Oauth2️⃣ ✔ 👈 🕐❔ ⚙️ "🔐 💧" (👈 👥 ⚙️) 👩‍💻/ * `instagram_basic` ⚙️ 👱📔 / 👱📔. * `https://www.googleapis.com/auth/drive` ⚙️ 🇺🇸🔍. -!!! info - Oauth2️⃣ "↔" 🎻 👈 📣 🎯 ✔ ✔. +/// info - ⚫️ 🚫 🤔 🚥 ⚫️ ✔️ 🎏 🦹 💖 `:` ⚖️ 🚥 ⚫️ 📛. +Oauth2️⃣ "↔" 🎻 👈 📣 🎯 ✔ ✔. - 👈 ℹ 🛠️ 🎯. +⚫️ 🚫 🤔 🚥 ⚫️ ✔️ 🎏 🦹 💖 `:` ⚖️ 🚥 ⚫️ 📛. - Oauth2️⃣ 👫 🎻. +👈 ℹ 🛠️ 🎯. + +Oauth2️⃣ 👫 🎻. + +/// ## 📟 🤚 `username` & `password` @@ -49,17 +52,7 @@ Oauth2️⃣ ✔ 👈 🕐❔ ⚙️ "🔐 💧" (👈 👥 ⚙️) 👩‍💻/ 🥇, 🗄 `OAuth2PasswordRequestForm`, & ⚙️ ⚫️ 🔗 ⏮️ `Depends` *➡ 🛠️* `/token`: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="4 76" - {!> ../../../docs_src/security/tutorial003.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="2 74" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +{* ../../docs_src/security/tutorial003.py hl[4,76] *} `OAuth2PasswordRequestForm` 🎓 🔗 👈 📣 📨 💪 ⏮️: @@ -68,29 +61,38 @@ Oauth2️⃣ ✔ 👈 🕐❔ ⚙️ "🔐 💧" (👈 👥 ⚙️) 👩‍💻/ * 📦 `scope` 🏑 🦏 🎻, ✍ 🎻 🎏 🚀. * 📦 `grant_type`. -!!! tip - Oauth2️⃣ 🔌 🤙 *🚚* 🏑 `grant_type` ⏮️ 🔧 💲 `password`, ✋️ `OAuth2PasswordRequestForm` 🚫 🛠️ ⚫️. +/// tip + +Oauth2️⃣ 🔌 🤙 *🚚* 🏑 `grant_type` ⏮️ 🔧 💲 `password`, ✋️ `OAuth2PasswordRequestForm` 🚫 🛠️ ⚫️. - 🚥 👆 💪 🛠️ ⚫️, ⚙️ `OAuth2PasswordRequestFormStrict` ↩️ `OAuth2PasswordRequestForm`. +🚥 👆 💪 🛠️ ⚫️, ⚙️ `OAuth2PasswordRequestFormStrict` ↩️ `OAuth2PasswordRequestForm`. + +/// * 📦 `client_id` (👥 🚫 💪 ⚫️ 👆 🖼). * 📦 `client_secret` (👥 🚫 💪 ⚫️ 👆 🖼). -!!! info - `OAuth2PasswordRequestForm` 🚫 🎁 🎓 **FastAPI** `OAuth2PasswordBearer`. +/// info + +`OAuth2PasswordRequestForm` 🚫 🎁 🎓 **FastAPI** `OAuth2PasswordBearer`. + +`OAuth2PasswordBearer` ⚒ **FastAPI** 💭 👈 ⚫️ 💂‍♂ ⚖. ⚫️ 🚮 👈 🌌 🗄. - `OAuth2PasswordBearer` ⚒ **FastAPI** 💭 👈 ⚫️ 💂‍♂ ⚖. ⚫️ 🚮 👈 🌌 🗄. +✋️ `OAuth2PasswordRequestForm` 🎓 🔗 👈 👆 💪 ✔️ ✍ 👆, ⚖️ 👆 💪 ✔️ 📣 `Form` 🔢 🔗. - ✋️ `OAuth2PasswordRequestForm` 🎓 🔗 👈 👆 💪 ✔️ ✍ 👆, ⚖️ 👆 💪 ✔️ 📣 `Form` 🔢 🔗. +✋️ ⚫️ ⚠ ⚙️ 💼, ⚫️ 🚚 **FastAPI** 🔗, ⚒ ⚫️ ⏩. - ✋️ ⚫️ ⚠ ⚙️ 💼, ⚫️ 🚚 **FastAPI** 🔗, ⚒ ⚫️ ⏩. +/// ### ⚙️ 📨 💽 -!!! tip - 👐 🔗 🎓 `OAuth2PasswordRequestForm` 🏆 🚫 ✔️ 🔢 `scope` ⏮️ 📏 🎻 👽 🚀, ↩️, ⚫️ 🔜 ✔️ `scopes` 🔢 ⏮️ ☑ 📇 🎻 🔠 ↔ 📨. +/// tip + +👐 🔗 🎓 `OAuth2PasswordRequestForm` 🏆 🚫 ✔️ 🔢 `scope` ⏮️ 📏 🎻 👽 🚀, ↩️, ⚫️ 🔜 ✔️ `scopes` 🔢 ⏮️ ☑ 📇 🎻 🔠 ↔ 📨. + +👥 🚫 ⚙️ `scopes` 👉 🖼, ✋️ 🛠️ 📤 🚥 👆 💪 ⚫️. - 👥 🚫 ⚙️ `scopes` 👉 🖼, ✋️ 🛠️ 📤 🚥 👆 💪 ⚫️. +/// 🔜, 🤚 👩‍💻 📊 ⚪️➡️ (❌) 💽, ⚙️ `username` ⚪️➡️ 📨 🏑. @@ -98,17 +100,7 @@ Oauth2️⃣ ✔ 👈 🕐❔ ⚙️ "🔐 💧" (👈 👥 ⚙️) 👩‍💻/ ❌, 👥 ⚙️ ⚠ `HTTPException`: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="3 77-79" - {!> ../../../docs_src/security/tutorial003.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="1 75-77" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +{* ../../docs_src/security/tutorial003.py hl[3,77:79] *} ### ✅ 🔐 @@ -134,17 +126,7 @@ Oauth2️⃣ ✔ 👈 🕐❔ ⚙️ "🔐 💧" (👈 👥 ⚙️) 👩‍💻/ , 🧙‍♀ 🏆 🚫 💪 🔄 ⚙️ 👈 🎏 🔐 ➕1️⃣ ⚙️ (📚 👩‍💻 ⚙️ 🎏 🔐 🌐, 👉 🔜 ⚠). -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="80-83" - {!> ../../../docs_src/security/tutorial003.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="78-81" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +{* ../../docs_src/security/tutorial003.py hl[80:83] *} #### 🔃 `**user_dict` @@ -162,8 +144,11 @@ UserInDB( ) ``` -!!! info - 🌅 🏁 🔑 `**👩‍💻_ #️⃣ ` ✅ 🔙 [🧾 **➕ 🏷**](../extra-models.md#about-user_indict){.internal-link target=_blank}. +/// info + +🌅 🏁 🔑 `**👩‍💻_ #️⃣ ` ✅ 🔙 [🧾 **➕ 🏷**](../extra-models.md#user_indict){.internal-link target=_blank}. + +/// ## 📨 🤝 @@ -175,31 +160,27 @@ UserInDB( 👉 🙅 🖼, 👥 🔜 🍕 😟 & 📨 🎏 `username` 🤝. -!!! tip - ⏭ 📃, 👆 🔜 👀 🎰 🔐 🛠️, ⏮️ 🔐 #️⃣ & 🥙 🤝. +/// tip - ✋️ 🔜, ➡️ 🎯 🔛 🎯 ℹ 👥 💪. +⏭ 📃, 👆 🔜 👀 🎰 🔐 🛠️, ⏮️ 🔐 #️⃣ & 🥙 🤝. -=== "🐍 3️⃣.6️⃣ & 🔛" +✋️ 🔜, ➡️ 🎯 🔛 🎯 ℹ 👥 💪. - ```Python hl_lines="85" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +/// -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +{* ../../docs_src/security/tutorial003.py hl[85] *} - ```Python hl_lines="83" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +/// tip -!!! tip - 🔌, 👆 🔜 📨 🎻 ⏮️ `access_token` & `token_type`, 🎏 👉 🖼. +🔌, 👆 🔜 📨 🎻 ⏮️ `access_token` & `token_type`, 🎏 👉 🖼. - 👉 🕳 👈 👆 ✔️ 👆 👆 📟, & ⚒ 💭 👆 ⚙️ 📚 🎻 🔑. +👉 🕳 👈 👆 ✔️ 👆 👆 📟, & ⚒ 💭 👆 ⚙️ 📚 🎻 🔑. - ⚫️ 🌖 🕴 👜 👈 👆 ✔️ 💭 ☑ 👆, 🛠️ ⏮️ 🔧. +⚫️ 🌖 🕴 👜 👈 👆 ✔️ 💭 ☑ 👆, 🛠️ ⏮️ 🔧. - 🎂, **FastAPI** 🍵 ⚫️ 👆. +🎂, **FastAPI** 🍵 ⚫️ 👆. + +/// ## ℹ 🔗 @@ -213,32 +194,25 @@ UserInDB( , 👆 🔗, 👥 🔜 🕴 🤚 👩‍💻 🚥 👩‍💻 🔀, ☑ 🔓, & 🦁: -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="58-66 69-72 90" - {!> ../../../docs_src/security/tutorial003.py!} - ``` +{* ../../docs_src/security/tutorial003.py hl[58:66,69:72,90] *} -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" +/// info - ```Python hl_lines="55-64 67-70 88" - {!> ../../../docs_src/security/tutorial003_py310.py!} - ``` +🌖 🎚 `WWW-Authenticate` ⏮️ 💲 `Bearer` 👥 🛬 📥 🍕 🔌. -!!! info - 🌖 🎚 `WWW-Authenticate` ⏮️ 💲 `Bearer` 👥 🛬 📥 🍕 🔌. +🙆 🇺🇸🔍 (❌) 👔 📟 4️⃣0️⃣1️⃣ "⛔" 🤔 📨 `WWW-Authenticate` 🎚. - 🙆 🇺🇸🔍 (❌) 👔 📟 4️⃣0️⃣1️⃣ "⛔" 🤔 📨 `WWW-Authenticate` 🎚. +💼 📨 🤝 (👆 💼), 💲 👈 🎚 🔜 `Bearer`. - 💼 📨 🤝 (👆 💼), 💲 👈 🎚 🔜 `Bearer`. +👆 💪 🤙 🚶 👈 ➕ 🎚 & ⚫️ 🔜 👷. - 👆 💪 🤙 🚶 👈 ➕ 🎚 & ⚫️ 🔜 👷. +✋️ ⚫️ 🚚 📥 🛠️ ⏮️ 🔧. - ✋️ ⚫️ 🚚 📥 🛠️ ⏮️ 🔧. +, 📤 5️⃣📆 🧰 👈 ⌛ & ⚙️ ⚫️ (🔜 ⚖️ 🔮) & 👈 💪 ⚠ 👆 ⚖️ 👆 👩‍💻, 🔜 ⚖️ 🔮. - , 📤 5️⃣📆 🧰 👈 ⌛ & ⚙️ ⚫️ (🔜 ⚖️ 🔮) & 👈 💪 ⚠ 👆 ⚖️ 👆 👩‍💻, 🔜 ⚖️ 🔮. +👈 💰 🐩... - 👈 💰 🐩... +/// ## 👀 ⚫️ 🎯 diff --git a/docs/em/docs/tutorial/sql-databases.md b/docs/em/docs/tutorial/sql-databases.md deleted file mode 100644 index e3ced7ef4..000000000 --- a/docs/em/docs/tutorial/sql-databases.md +++ /dev/null @@ -1,786 +0,0 @@ -# 🗄 (🔗) 💽 - -**FastAPI** 🚫 🚚 👆 ⚙️ 🗄 (🔗) 💽. - -✋️ 👆 💪 ⚙️ 🙆 🔗 💽 👈 👆 💚. - -📥 👥 🔜 👀 🖼 ⚙️ 🇸🇲. - -👆 💪 💪 🛠️ ⚫️ 🙆 💽 🐕‍🦺 🇸🇲, 💖: - -* ✳ -* ✳ -* 🗄 -* 🐸 -* 🤸‍♂ 🗄 💽, ♒️. - -👉 🖼, 👥 🔜 ⚙️ **🗄**, ↩️ ⚫️ ⚙️ 👁 📁 & 🐍 ✔️ 🛠️ 🐕‍🦺. , 👆 💪 📁 👉 🖼 & 🏃 ⚫️. - -⏪, 👆 🏭 🈸, 👆 💪 💚 ⚙️ 💽 💽 💖 **✳**. - -!!! tip - 📤 🛂 🏗 🚂 ⏮️ **FastAPI** & **✳**, 🌐 ⚓️ 🔛 **☁**, 🔌 🕸 & 🌖 🧰: https://github.com/tiangolo/full-stack-fastapi-postgresql - -!!! note - 👀 👈 📚 📟 🐩 `SQLAlchemy` 📟 👆 🔜 ⚙️ ⏮️ 🙆 🛠️. - - **FastAPI** 🎯 📟 🤪 🕧. - -## 🐜 - -**FastAPI** 👷 ⏮️ 🙆 💽 & 🙆 👗 🗃 💬 💽. - -⚠ ⚓ ⚙️ "🐜": "🎚-🔗 🗺" 🗃. - -🐜 ✔️ 🧰 🗜 ("*🗺*") 🖖 *🎚* 📟 & 💽 🏓 ("*🔗*"). - -⏮️ 🐜, 👆 🛎 ✍ 🎓 👈 🎨 🏓 🗄 💽, 🔠 🔢 🎓 🎨 🏓, ⏮️ 📛 & 🆎. - -🖼 🎓 `Pet` 💪 🎨 🗄 🏓 `pets`. - -& 🔠 *👐* 🎚 👈 🎓 🎨 ⏭ 💽. - -🖼 🎚 `orion_cat` (👐 `Pet`) 💪 ✔️ 🔢 `orion_cat.type`, 🏓 `type`. & 💲 👈 🔢 💪, ✅ `"cat"`. - -👫 🐜 ✔️ 🧰 ⚒ 🔗 ⚖️ 🔗 🖖 🏓 ⚖️ 👨‍💼. - -👉 🌌, 👆 💪 ✔️ 🔢 `orion_cat.owner` & 👨‍💼 🔜 🔌 💽 👉 🐶 👨‍💼, ✊ ⚪️➡️ 🏓 *👨‍💼*. - -, `orion_cat.owner.name` 💪 📛 (⚪️➡️ `name` 🏓 `owners` 🏓) 👉 🐶 👨‍💼. - -⚫️ 💪 ✔️ 💲 💖 `"Arquilian"`. - -& 🐜 🔜 🌐 👷 🤚 ℹ ⚪️➡️ 🔗 🏓 *👨‍💼* 🕐❔ 👆 🔄 🔐 ⚫️ ⚪️➡️ 👆 🐶 🎚. - -⚠ 🐜 🖼: ✳-🐜 (🍕 ✳ 🛠️), 🇸🇲 🐜 (🍕 🇸🇲, 🔬 🛠️) & 🏒 (🔬 🛠️), 👪 🎏. - -📥 👥 🔜 👀 ❔ 👷 ⏮️ **🇸🇲 🐜**. - -🎏 🌌 👆 💪 ⚙️ 🙆 🎏 🐜. - -!!! tip - 📤 🌓 📄 ⚙️ 🏒 📥 🩺. - -## 📁 📊 - -👫 🖼, ➡️ 💬 👆 ✔️ 📁 📛 `my_super_project` 👈 🔌 🎧-📁 🤙 `sql_app` ⏮️ 📊 💖 👉: - -``` -. -└── sql_app - ├── __init__.py - ├── crud.py - ├── database.py - ├── main.py - ├── models.py - └── schemas.py -``` - -📁 `__init__.py` 🛁 📁, ✋️ ⚫️ 💬 🐍 👈 `sql_app` ⏮️ 🌐 🚮 🕹 (🐍 📁) 📦. - -🔜 ➡️ 👀 ⚫️❔ 🔠 📁/🕹 🔨. - -## ❎ `SQLAlchemy` - -🥇 👆 💪 ❎ `SQLAlchemy`: - -
- -```console -$ pip install sqlalchemy - ----> 100% -``` - -
- -## ✍ 🇸🇲 🍕 - -➡️ 🔗 📁 `sql_app/database.py`. - -### 🗄 🇸🇲 🍕 - -```Python hl_lines="1-3" -{!../../../docs_src/sql_databases/sql_app/database.py!} -``` - -### ✍ 💽 📛 🇸🇲 - -```Python hl_lines="5-6" -{!../../../docs_src/sql_databases/sql_app/database.py!} -``` - -👉 🖼, 👥 "🔗" 🗄 💽 (📂 📁 ⏮️ 🗄 💽). - -📁 🔜 🔎 🎏 📁 📁 `sql_app.db`. - -👈 ⚫️❔ 🏁 🍕 `./sql_app.db`. - -🚥 👆 ⚙️ **✳** 💽 ↩️, 👆 🔜 ✔️ ✍ ⏸: - -```Python -SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" -``` - -...& 🛠️ ⚫️ ⏮️ 👆 💽 📊 & 🎓 (📊 ✳, ✳ ⚖️ 🙆 🎏). - -!!! tip - - 👉 👑 ⏸ 👈 👆 🔜 ✔️ 🔀 🚥 👆 💚 ⚙️ 🎏 💽. - -### ✍ 🇸🇲 `engine` - -🥇 🔁 ✍ 🇸🇲 "🚒". - -👥 🔜 ⏪ ⚙️ 👉 `engine` 🎏 🥉. - -```Python hl_lines="8-10" -{!../../../docs_src/sql_databases/sql_app/database.py!} -``` - -#### 🗒 - -❌: - -```Python -connect_args={"check_same_thread": False} -``` - -...💪 🕴 `SQLite`. ⚫️ 🚫 💪 🎏 💽. - -!!! info "📡 ℹ" - - 🔢 🗄 🔜 🕴 ✔ 1️⃣ 🧵 🔗 ⏮️ ⚫️, 🤔 👈 🔠 🧵 🔜 🍵 🔬 📨. - - 👉 ❎ 😫 🤝 🎏 🔗 🎏 👜 (🎏 📨). - - ✋️ FastAPI, ⚙️ 😐 🔢 (`def`) 🌅 🌘 1️⃣ 🧵 💪 🔗 ⏮️ 💽 🎏 📨, 👥 💪 ⚒ 🗄 💭 👈 ⚫️ 🔜 ✔ 👈 ⏮️ `connect_args={"check_same_thread": False}`. - - , 👥 🔜 ⚒ 💭 🔠 📨 🤚 🚮 👍 💽 🔗 🎉 🔗, 📤 🙅‍♂ 💪 👈 🔢 🛠️. - -### ✍ `SessionLocal` 🎓 - -🔠 👐 `SessionLocal` 🎓 🔜 💽 🎉. 🎓 ⚫️ 🚫 💽 🎉. - -✋️ 🕐 👥 ✍ 👐 `SessionLocal` 🎓, 👉 👐 🔜 ☑ 💽 🎉. - -👥 📛 ⚫️ `SessionLocal` 🔬 ⚫️ ⚪️➡️ `Session` 👥 🏭 ⚪️➡️ 🇸🇲. - -👥 🔜 ⚙️ `Session` (1️⃣ 🗄 ⚪️➡️ 🇸🇲) ⏪. - -✍ `SessionLocal` 🎓, ⚙️ 🔢 `sessionmaker`: - -```Python hl_lines="11" -{!../../../docs_src/sql_databases/sql_app/database.py!} -``` - -### ✍ `Base` 🎓 - -🔜 👥 🔜 ⚙️ 🔢 `declarative_base()` 👈 📨 🎓. - -⏪ 👥 🔜 😖 ⚪️➡️ 👉 🎓 ✍ 🔠 💽 🏷 ⚖️ 🎓 (🐜 🏷): - -```Python hl_lines="13" -{!../../../docs_src/sql_databases/sql_app/database.py!} -``` - -## ✍ 💽 🏷 - -➡️ 🔜 👀 📁 `sql_app/models.py`. - -### ✍ 🇸🇲 🏷 ⚪️➡️ `Base` 🎓 - -👥 🔜 ⚙️ 👉 `Base` 🎓 👥 ✍ ⏭ ✍ 🇸🇲 🏷. - -!!! tip - 🇸🇲 ⚙️ ⚖ "**🏷**" 🔗 👉 🎓 & 👐 👈 🔗 ⏮️ 💽. - - ✋️ Pydantic ⚙️ ⚖ "**🏷**" 🔗 🕳 🎏, 💽 🔬, 🛠️, & 🧾 🎓 & 👐. - -🗄 `Base` ⚪️➡️ `database` (📁 `database.py` ⚪️➡️ 🔛). - -✍ 🎓 👈 😖 ⚪️➡️ ⚫️. - -👫 🎓 🇸🇲 🏷. - -```Python hl_lines="4 7-8 18-19" -{!../../../docs_src/sql_databases/sql_app/models.py!} -``` - -`__tablename__` 🔢 💬 🇸🇲 📛 🏓 ⚙️ 💽 🔠 👫 🏷. - -### ✍ 🏷 🔢/🏓 - -🔜 ✍ 🌐 🏷 (🎓) 🔢. - -🔠 👫 🔢 🎨 🏓 🚮 🔗 💽 🏓. - -👥 ⚙️ `Column` ⚪️➡️ 🇸🇲 🔢 💲. - -& 👥 🚶‍♀️ 🇸🇲 🎓 "🆎", `Integer`, `String`, & `Boolean`, 👈 🔬 🆎 💽, ❌. - -```Python hl_lines="1 10-13 21-24" -{!../../../docs_src/sql_databases/sql_app/models.py!} -``` - -### ✍ 💛 - -🔜 ✍ 💛. - -👉, 👥 ⚙️ `relationship` 🚚 🇸🇲 🐜. - -👉 🔜 ▶️️, 🌅 ⚖️ 🌘, "🎱" 🔢 👈 🔜 🔌 💲 ⚪️➡️ 🎏 🏓 🔗 👉 1️⃣. - -```Python hl_lines="2 15 26" -{!../../../docs_src/sql_databases/sql_app/models.py!} -``` - -🕐❔ 🔐 🔢 `items` `User`, `my_user.items`, ⚫️ 🔜 ✔️ 📇 `Item` 🇸🇲 🏷 (⚪️➡️ `items` 🏓) 👈 ✔️ 💱 🔑 ☝ 👉 ⏺ `users` 🏓. - -🕐❔ 👆 🔐 `my_user.items`, 🇸🇲 🔜 🤙 🚶 & ☕ 🏬 ⚪️➡️ 💽 `items` 🏓 & 🔗 👫 📥. - -& 🕐❔ 🔐 🔢 `owner` `Item`, ⚫️ 🔜 🔌 `User` 🇸🇲 🏷 ⚪️➡️ `users` 🏓. ⚫️ 🔜 ⚙️ `owner_id` 🔢/🏓 ⏮️ 🚮 💱 🔑 💭 ❔ ⏺ 🤚 ⚪️➡️ `users` 🏓. - -## ✍ Pydantic 🏷 - -🔜 ➡️ ✅ 📁 `sql_app/schemas.py`. - -!!! tip - ❎ 😨 🖖 🇸🇲 *🏷* & Pydantic *🏷*, 👥 🔜 ✔️ 📁 `models.py` ⏮️ 🇸🇲 🏷, & 📁 `schemas.py` ⏮️ Pydantic 🏷. - - 👫 Pydantic 🏷 🔬 🌅 ⚖️ 🌘 "🔗" (☑ 📊 💠). - - 👉 🔜 ℹ 👥 ❎ 😨 ⏪ ⚙️ 👯‍♂️. - -### ✍ ▶️ Pydantic *🏷* / 🔗 - -✍ `ItemBase` & `UserBase` Pydantic *🏷* (⚖️ ➡️ 💬 "🔗") ✔️ ⚠ 🔢 ⏪ 🏗 ⚖️ 👂 📊. - -& ✍ `ItemCreate` & `UserCreate` 👈 😖 ⚪️➡️ 👫 (👫 🔜 ✔️ 🎏 🔢), ➕ 🙆 🌖 📊 (🔢) 💪 🏗. - -, 👩‍💻 🔜 ✔️ `password` 🕐❔ 🏗 ⚫️. - -✋️ 💂‍♂, `password` 🏆 🚫 🎏 Pydantic *🏷*, 🖼, ⚫️ 🏆 🚫 📨 ⚪️➡️ 🛠️ 🕐❔ 👂 👩‍💻. - -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="3 6-8 11-12 23-24 27-28" - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="3 6-8 11-12 23-24 27-28" - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="1 4-6 9-10 21-22 25-26" - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` - -#### 🇸🇲 👗 & Pydantic 👗 - -👀 👈 🇸🇲 *🏷* 🔬 🔢 ⚙️ `=`, & 🚶‍♀️ 🆎 🔢 `Column`, 💖: - -```Python -name = Column(String) -``` - -⏪ Pydantic *🏷* 📣 🆎 ⚙️ `:`, 🆕 🆎 ✍ ❕/🆎 🔑: - -```Python -name: str -``` - -✔️ ⚫️ 🤯, 👆 🚫 🤚 😕 🕐❔ ⚙️ `=` & `:` ⏮️ 👫. - -### ✍ Pydantic *🏷* / 🔗 👂 / 📨 - -🔜 ✍ Pydantic *🏷* (🔗) 👈 🔜 ⚙️ 🕐❔ 👂 💽, 🕐❔ 🛬 ⚫️ ⚪️➡️ 🛠️. - -🖼, ⏭ 🏗 🏬, 👥 🚫 💭 ⚫️❔ 🔜 🆔 🛠️ ⚫️, ✋️ 🕐❔ 👂 ⚫️ (🕐❔ 🛬 ⚫️ ⚪️➡️ 🛠️) 👥 🔜 ⏪ 💭 🚮 🆔. - -🎏 🌌, 🕐❔ 👂 👩‍💻, 👥 💪 🔜 📣 👈 `items` 🔜 🔌 🏬 👈 💭 👉 👩‍💻. - -🚫 🕴 🆔 📚 🏬, ✋️ 🌐 💽 👈 👥 🔬 Pydantic *🏷* 👂 🏬: `Item`. - -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="15-17 31-34" - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="15-17 31-34" - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="13-15 29-32" - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` - -!!! tip - 👀 👈 `User`, Pydantic *🏷* 👈 🔜 ⚙️ 🕐❔ 👂 👩‍💻 (🛬 ⚫️ ⚪️➡️ 🛠️) 🚫 🔌 `password`. - -### ⚙️ Pydantic `orm_mode` - -🔜, Pydantic *🏷* 👂, `Item` & `User`, 🚮 🔗 `Config` 🎓. - -👉 `Config` 🎓 ⚙️ 🚚 📳 Pydantic. - -`Config` 🎓, ⚒ 🔢 `orm_mode = True`. - -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="15 19-20 31 36-37" - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="15 19-20 31 36-37" - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python hl_lines="13 17-18 29 34-35" - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` - -!!! tip - 👀 ⚫️ ⚖ 💲 ⏮️ `=`, 💖: - - `orm_mode = True` - - ⚫️ 🚫 ⚙️ `:` 🆎 📄 ⏭. - - 👉 ⚒ 📁 💲, 🚫 📣 🆎. - -Pydantic `orm_mode` 🔜 💬 Pydantic *🏷* ✍ 💽 🚥 ⚫️ 🚫 `dict`, ✋️ 🐜 🏷 (⚖️ 🙆 🎏 ❌ 🎚 ⏮️ 🔢). - -👉 🌌, ↩️ 🕴 🔄 🤚 `id` 💲 ⚪️➡️ `dict`,: - -```Python -id = data["id"] -``` - -⚫️ 🔜 🔄 🤚 ⚫️ ⚪️➡️ 🔢,: - -```Python -id = data.id -``` - -& ⏮️ 👉, Pydantic *🏷* 🔗 ⏮️ 🐜, & 👆 💪 📣 ⚫️ `response_model` ❌ 👆 *➡ 🛠️*. - -👆 🔜 💪 📨 💽 🏷 & ⚫️ 🔜 ✍ 💽 ⚪️➡️ ⚫️. - -#### 📡 ℹ 🔃 🐜 📳 - -🇸🇲 & 📚 🎏 🔢 "🙃 🚚". - -👈 ⛓, 🖼, 👈 👫 🚫 ☕ 💽 💛 ⚪️➡️ 💽 🚥 👆 🔄 🔐 🔢 👈 🔜 🔌 👈 💽. - -🖼, 🔐 🔢 `items`: - -```Python -current_user.items -``` - -🔜 ⚒ 🇸🇲 🚶 `items` 🏓 & 🤚 🏬 👉 👩‍💻, ✋️ 🚫 ⏭. - -🍵 `orm_mode`, 🚥 👆 📨 🇸🇲 🏷 ⚪️➡️ 👆 *➡ 🛠️*, ⚫️ 🚫🔜 🔌 💛 💽. - -🚥 👆 📣 📚 💛 👆 Pydantic 🏷. - -✋️ ⏮️ 🐜 📳, Pydantic ⚫️ 🔜 🔄 🔐 💽 ⚫️ 💪 ⚪️➡️ 🔢 (↩️ 🤔 `dict`), 👆 💪 📣 🎯 💽 👆 💚 📨 & ⚫️ 🔜 💪 🚶 & 🤚 ⚫️, ⚪️➡️ 🐜. - -## 💩 🇨🇻 - -🔜 ➡️ 👀 📁 `sql_app/crud.py`. - -👉 📁 👥 🔜 ✔️ ♻ 🔢 🔗 ⏮️ 💽 💽. - -**💩** 👟 ⚪️➡️: **🅱**📧, **Ⓜ**💳, **👤** = , & **🇨🇮**📧. - -...👐 👉 🖼 👥 🕴 🏗 & 👂. - -### ✍ 💽 - -🗄 `Session` ⚪️➡️ `sqlalchemy.orm`, 👉 🔜 ✔ 👆 📣 🆎 `db` 🔢 & ✔️ 👻 🆎 ✅ & 🛠️ 👆 🔢. - -🗄 `models` (🇸🇲 🏷) & `schemas` (Pydantic *🏷* / 🔗). - -✍ 🚙 🔢: - -* ✍ 👁 👩‍💻 🆔 & 📧. -* ✍ 💗 👩‍💻. -* ✍ 💗 🏬. - -```Python hl_lines="1 3 6-7 10-11 14-15 27-28" -{!../../../docs_src/sql_databases/sql_app/crud.py!} -``` - -!!! tip - 🏗 🔢 👈 🕴 💡 🔗 ⏮️ 💽 (🤚 👩‍💻 ⚖️ 🏬) 🔬 👆 *➡ 🛠️ 🔢*, 👆 💪 🌖 💪 ♻ 👫 💗 🍕 & 🚮 ⚒ 💯 👫. - -### ✍ 💽 - -🔜 ✍ 🚙 🔢 ✍ 💽. - -🔁: - -* ✍ 🇸🇲 🏷 *👐* ⏮️ 👆 📊. -* `add` 👈 👐 🎚 👆 💽 🎉. -* `commit` 🔀 💽 (👈 👫 🖊). -* `refresh` 👆 👐 (👈 ⚫️ 🔌 🙆 🆕 📊 ⚪️➡️ 💽, 💖 🏗 🆔). - -```Python hl_lines="18-24 31-36" -{!../../../docs_src/sql_databases/sql_app/crud.py!} -``` - -!!! tip - 🇸🇲 🏷 `User` 🔌 `hashed_password` 👈 🔜 🔌 🔐 #️⃣ ⏬ 🔐. - - ✋️ ⚫️❔ 🛠️ 👩‍💻 🚚 ⏮️ 🔐, 👆 💪 ⚗ ⚫️ & 🏗 #️⃣ 🔐 👆 🈸. - - & ⤴️ 🚶‍♀️ `hashed_password` ❌ ⏮️ 💲 🖊. - -!!! warning - 👉 🖼 🚫 🔐, 🔐 🚫#️⃣. - - 🎰 👨‍❤‍👨 🈸 👆 🔜 💪 #️⃣ 🔐 & 🙅 🖊 👫 🔢. - - 🌅 ℹ, 🚶 🔙 💂‍♂ 📄 🔰. - - 📥 👥 🎯 🕴 🔛 🧰 & 👨‍🔧 💽. - -!!! tip - ↩️ 🚶‍♀️ 🔠 🇨🇻 ❌ `Item` & 👂 🔠 1️⃣ 👫 ⚪️➡️ Pydantic *🏷*, 👥 🏭 `dict` ⏮️ Pydantic *🏷*'Ⓜ 📊 ⏮️: - - `item.dict()` - - & ⤴️ 👥 🚶‍♀️ `dict`'Ⓜ 🔑-💲 👫 🇨🇻 ❌ 🇸🇲 `Item`, ⏮️: - - `Item(**item.dict())` - - & ⤴️ 👥 🚶‍♀️ ➕ 🇨🇻 ❌ `owner_id` 👈 🚫 🚚 Pydantic *🏷*, ⏮️: - - `Item(**item.dict(), owner_id=user_id)` - -## 👑 **FastAPI** 📱 - -& 🔜 📁 `sql_app/main.py` ➡️ 🛠️ & ⚙️ 🌐 🎏 🍕 👥 ✍ ⏭. - -### ✍ 💽 🏓 - -📶 🙃 🌌 ✍ 💽 🏓: - -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="9" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="7" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` - -#### ⚗ 🗒 - -🛎 👆 🔜 🎲 🔢 👆 💽 (✍ 🏓, ♒️) ⏮️ . - -& 👆 🔜 ⚙️ ⚗ "🛠️" (👈 🚮 👑 👨‍🏭). - -"🛠️" ⚒ 🔁 💪 🕐❔ 👆 🔀 📊 👆 🇸🇲 🏷, 🚮 🆕 🔢, ♒️. 🔁 👈 🔀 💽, 🚮 🆕 🏓, 🆕 🏓, ♒️. - -👆 💪 🔎 🖼 ⚗ FastAPI 🏗 📄 ⚪️➡️ [🏗 ⚡ - 📄](../project-generation.md){.internal-link target=_blank}. 🎯 `alembic` 📁 ℹ 📟. - -### ✍ 🔗 - -🔜 ⚙️ `SessionLocal` 🎓 👥 ✍ `sql_app/database.py` 📁 ✍ 🔗. - -👥 💪 ✔️ 🔬 💽 🎉/🔗 (`SessionLocal`) 📍 📨, ⚙️ 🎏 🎉 🔘 🌐 📨 & ⤴️ 🔐 ⚫️ ⏮️ 📨 🏁. - -& ⤴️ 🆕 🎉 🔜 ✍ ⏭ 📨. - -👈, 👥 🔜 ✍ 🆕 🔗 ⏮️ `yield`, 🔬 ⏭ 📄 🔃 [🔗 ⏮️ `yield`](dependencies/dependencies-with-yield.md){.internal-link target=_blank}. - -👆 🔗 🔜 ✍ 🆕 🇸🇲 `SessionLocal` 👈 🔜 ⚙️ 👁 📨, & ⤴️ 🔐 ⚫️ 🕐 📨 🏁. - -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="15-20" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="13-18" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` - -!!! info - 👥 🚮 🏗 `SessionLocal()` & 🚚 📨 `try` 🍫. - - & ⤴️ 👥 🔐 ⚫️ `finally` 🍫. - - 👉 🌌 👥 ⚒ 💭 💽 🎉 🕧 📪 ⏮️ 📨. 🚥 📤 ⚠ ⏪ 🏭 📨. - - ✋️ 👆 💪 🚫 🤚 ➕1️⃣ ⚠ ⚪️➡️ 🚪 📟 (⏮️ `yield`). 👀 🌖 [🔗 ⏮️ `yield` & `HTTPException`](./dependencies/dependencies-with-yield.md#dependencies-with-yield-and-httpexception){.internal-link target=_blank} - -& ⤴️, 🕐❔ ⚙️ 🔗 *➡ 🛠️ 🔢*, 👥 📣 ⚫️ ⏮️ 🆎 `Session` 👥 🗄 🔗 ⚪️➡️ 🇸🇲. - -👉 🔜 ⤴️ 🤝 👥 👍 👨‍🎨 🐕‍🦺 🔘 *➡ 🛠️ 🔢*, ↩️ 👨‍🎨 🔜 💭 👈 `db` 🔢 🆎 `Session`: - -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="24 32 38 47 53" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="22 30 36 45 51" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` - -!!! info "📡 ℹ" - 🔢 `db` 🤙 🆎 `SessionLocal`, ✋️ 👉 🎓 (✍ ⏮️ `sessionmaker()`) "🗳" 🇸🇲 `Session`,, 👨‍🎨 🚫 🤙 💭 ⚫️❔ 👩‍🔬 🚚. - - ✋️ 📣 🆎 `Session`, 👨‍🎨 🔜 💪 💭 💪 👩‍🔬 (`.add()`, `.query()`, `.commit()`, ♒️) & 💪 🚚 👍 🐕‍🦺 (💖 🛠️). 🆎 📄 🚫 📉 ☑ 🎚. - -### ✍ 👆 **FastAPI** *➡ 🛠️* - -🔜, 😒, 📥 🐩 **FastAPI** *➡ 🛠️* 📟. - -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="23-28 31-34 37-42 45-49 52-55" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="21-26 29-32 35-40 43-47 50-53" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` - -👥 🏗 💽 🎉 ⏭ 🔠 📨 🔗 ⏮️ `yield`, & ⤴️ 📪 ⚫️ ⏮️. - -& ⤴️ 👥 💪 ✍ 🚚 🔗 *➡ 🛠️ 🔢*, 🤚 👈 🎉 🔗. - -⏮️ 👈, 👥 💪 🤙 `crud.get_user` 🔗 ⚪️➡️ 🔘 *➡ 🛠️ 🔢* & ⚙️ 👈 🎉. - -!!! tip - 👀 👈 💲 👆 📨 🇸🇲 🏷, ⚖️ 📇 🇸🇲 🏷. - - ✋️ 🌐 *➡ 🛠️* ✔️ `response_model` ⏮️ Pydantic *🏷* / 🔗 ⚙️ `orm_mode`, 💽 📣 👆 Pydantic 🏷 🔜 ⚗ ⚪️➡️ 👫 & 📨 👩‍💻, ⏮️ 🌐 😐 ⛽ & 🔬. - -!!! tip - 👀 👈 📤 `response_models` 👈 ✔️ 🐩 🐍 🆎 💖 `List[schemas.Item]`. - - ✋️ 🎚/🔢 👈 `List` Pydantic *🏷* ⏮️ `orm_mode`, 💽 🔜 🗃 & 📨 👩‍💻 🛎, 🍵 ⚠. - -### 🔃 `def` 🆚 `async def` - -📥 👥 ⚙️ 🇸🇲 📟 🔘 *➡ 🛠️ 🔢* & 🔗, &, 🔄, ⚫️ 🔜 🚶 & 🔗 ⏮️ 🔢 💽. - -👈 💪 ⚠ 🚚 "⌛". - -✋️ 🇸🇲 🚫 ✔️ 🔗 ⚙️ `await` 🔗, 🔜 ⏮️ 🕳 💖: - -```Python -user = await db.query(User).first() -``` - -...& ↩️ 👥 ⚙️: - -```Python -user = db.query(User).first() -``` - -⤴️ 👥 🔜 📣 *➡ 🛠️ 🔢* & 🔗 🍵 `async def`, ⏮️ 😐 `def`,: - -```Python hl_lines="2" -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - ... -``` - -!!! info - 🚥 👆 💪 🔗 👆 🔗 💽 🔁, 👀 [🔁 🗄 (🔗) 💽](../advanced/async-sql-databases.md){.internal-link target=_blank}. - -!!! note "📶 📡 ℹ" - 🚥 👆 😟 & ✔️ ⏬ 📡 💡, 👆 💪 ✅ 📶 📡 ℹ ❔ 👉 `async def` 🆚 `def` 🍵 [🔁](../async.md#very-technical-details){.internal-link target=_blank} 🩺. - -## 🛠️ - -↩️ 👥 ⚙️ 🇸🇲 🔗 & 👥 🚫 🚚 🙆 😇 🔌-⚫️ 👷 ⏮️ **FastAPI**, 👥 💪 🛠️ 💽 🛠️ ⏮️ 🔗. - -& 📟 🔗 🇸🇲 & 🇸🇲 🏷 🖖 🎏 🔬 📁, 👆 🔜 💪 🎭 🛠️ ⏮️ ⚗ 🍵 ✔️ ❎ FastAPI, Pydantic, ⚖️ 🕳 🙆. - -🎏 🌌, 👆 🔜 💪 ⚙️ 🎏 🇸🇲 🏷 & 🚙 🎏 🍕 👆 📟 👈 🚫 🔗 **FastAPI**. - -🖼, 🖥 📋 👨‍🏭 ⏮️ 🥒, 🅿, ⚖️ 📶. - -## 📄 🌐 📁 - - 💭 👆 🔜 ✔️ 📁 📛 `my_super_project` 👈 🔌 🎧-📁 🤙 `sql_app`. - -`sql_app` 🔜 ✔️ 📄 📁: - -* `sql_app/__init__.py`: 🛁 📁. - -* `sql_app/database.py`: - -```Python -{!../../../docs_src/sql_databases/sql_app/database.py!} -``` - -* `sql_app/models.py`: - -```Python -{!../../../docs_src/sql_databases/sql_app/models.py!} -``` - -* `sql_app/schemas.py`: - -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` - -* `sql_app/crud.py`: - -```Python -{!../../../docs_src/sql_databases/sql_app/crud.py!} -``` - -* `sql_app/main.py`: - -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` - -## ✅ ⚫️ - -👆 💪 📁 👉 📟 & ⚙️ ⚫️. - -!!! info - - 👐, 📟 🎦 📥 🍕 💯. 🌅 📟 👉 🩺. - -⤴️ 👆 💪 🏃 ⚫️ ⏮️ Uvicorn: - - -
- -```console -$ uvicorn sql_app.main:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -& ⤴️, 👆 💪 📂 👆 🖥 http://127.0.0.1:8000/docs. - -& 👆 🔜 💪 🔗 ⏮️ 👆 **FastAPI** 🈸, 👂 📊 ⚪️➡️ 🎰 💽: - - - -## 🔗 ⏮️ 💽 🔗 - -🚥 👆 💚 🔬 🗄 💽 (📁) 🔗, ➡ FastAPI, ℹ 🚮 🎚, 🚮 🏓, 🏓, ⏺, 🔀 📊, ♒️. 👆 💪 ⚙️ 💽 🖥 🗄. - -⚫️ 🔜 👀 💖 👉: - - - -👆 💪 ⚙️ 💳 🗄 🖥 💖 🗄 📋 ⚖️ ExtendsClass. - -## 🎛 💽 🎉 ⏮️ 🛠️ - -🚥 👆 💪 🚫 ⚙️ 🔗 ⏮️ `yield` - 🖼, 🚥 👆 🚫 ⚙️ **🐍 3️⃣.7️⃣** & 💪 🚫 ❎ "🐛" 🤔 🔛 **🐍 3️⃣.6️⃣** - 👆 💪 ⚒ 🆙 🎉 "🛠️" 🎏 🌌. - -"🛠️" 🌖 🔢 👈 🕧 🛠️ 🔠 📨, ⏮️ 📟 🛠️ ⏭, & 📟 🛠️ ⏮️ 🔗 🔢. - -### ✍ 🛠️ - -🛠️ 👥 🔜 🚮 (🔢) 🔜 ✍ 🆕 🇸🇲 `SessionLocal` 🔠 📨, 🚮 ⚫️ 📨 & ⤴️ 🔐 ⚫️ 🕐 📨 🏁. - -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python hl_lines="14-22" - {!> ../../../docs_src/sql_databases/sql_app/alt_main.py!} - ``` - -=== "🐍 3️⃣.9️⃣ & 🔛" - - ```Python hl_lines="12-20" - {!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!} - ``` - -!!! info - 👥 🚮 🏗 `SessionLocal()` & 🚚 📨 `try` 🍫. - - & ⤴️ 👥 🔐 ⚫️ `finally` 🍫. - - 👉 🌌 👥 ⚒ 💭 💽 🎉 🕧 📪 ⏮️ 📨. 🚥 📤 ⚠ ⏪ 🏭 📨. - -### 🔃 `request.state` - -`request.state` 🏠 🔠 `Request` 🎚. ⚫️ 📤 🏪 ❌ 🎚 📎 📨 ⚫️, 💖 💽 🎉 👉 💼. 👆 💪 ✍ 🌅 🔃 ⚫️ 💃 🩺 🔃 `Request` 🇵🇸. - -👥 👉 💼, ⚫️ ℹ 👥 🚚 👁 💽 🎉 ⚙️ 🔘 🌐 📨, & ⤴️ 🔐 ⏮️ (🛠️). - -### 🔗 ⏮️ `yield` ⚖️ 🛠️ - -❎ **🛠️** 📥 🎏 ⚫️❔ 🔗 ⏮️ `yield` 🔨, ⏮️ 🔺: - -* ⚫️ 🚚 🌖 📟 & 👄 🌅 🏗. -* 🛠️ ✔️ `async` 🔢. - * 🚥 📤 📟 ⚫️ 👈 ✔️ "⌛" 🕸, ⚫️ 💪 "🍫" 👆 🈸 📤 & 📉 🎭 🍖. - * 👐 ⚫️ 🎲 🚫 📶 ⚠ 📥 ⏮️ 🌌 `SQLAlchemy` 👷. - * ✋️ 🚥 👆 🚮 🌖 📟 🛠️ 👈 ✔️ 📚 👤/🅾 ⌛, ⚫️ 💪 ⤴️ ⚠. -* 🛠️ 🏃 *🔠* 📨. - * , 🔗 🔜 ✍ 🔠 📨. - * 🕐❔ *➡ 🛠️* 👈 🍵 👈 📨 🚫 💪 💽. - -!!! tip - ⚫️ 🎲 👍 ⚙️ 🔗 ⏮️ `yield` 🕐❔ 👫 🥃 ⚙️ 💼. - -!!! info - 🔗 ⏮️ `yield` 🚮 ⏳ **FastAPI**. - - ⏮️ ⏬ 👉 🔰 🕴 ✔️ 🖼 ⏮️ 🛠️ & 📤 🎲 📚 🈸 ⚙️ 🛠️ 💽 🎉 🧾. diff --git a/docs/em/docs/tutorial/static-files.md b/docs/em/docs/tutorial/static-files.md index 6090c5338..6ff6e37a9 100644 --- a/docs/em/docs/tutorial/static-files.md +++ b/docs/em/docs/tutorial/static-files.md @@ -7,14 +7,15 @@ * 🗄 `StaticFiles`. * "🗻" `StaticFiles()` 👐 🎯 ➡. -```Python hl_lines="2 6" -{!../../../docs_src/static_files/tutorial001.py!} -``` +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.staticfiles import StaticFiles`. +/// note | 📡 ℹ - **FastAPI** 🚚 🎏 `starlette.staticfiles` `fastapi.staticfiles` 🏪 👆, 👩‍💻. ✋️ ⚫️ 🤙 👟 🔗 ⚪️➡️ 💃. +👆 💪 ⚙️ `from starlette.staticfiles import StaticFiles`. + +**FastAPI** 🚚 🎏 `starlette.staticfiles` `fastapi.staticfiles` 🏪 👆, 👩‍💻. ✋️ ⚫️ 🤙 👟 🔗 ⚪️➡️ 💃. + +/// ### ⚫️❔ "🗜" diff --git a/docs/em/docs/tutorial/testing.md b/docs/em/docs/tutorial/testing.md index 999d67cd3..cb4a1ca21 100644 --- a/docs/em/docs/tutorial/testing.md +++ b/docs/em/docs/tutorial/testing.md @@ -8,10 +8,13 @@ ## ⚙️ `TestClient` -!!! info - ⚙️ `TestClient`, 🥇 ❎ `httpx`. +/// info - 🤶 Ⓜ. `pip install httpx`. +⚙️ `TestClient`, 🥇 ❎ `httpx`. + +🤶 Ⓜ. `pip install httpx`. + +/// 🗄 `TestClient`. @@ -23,24 +26,31 @@ ✍ 🙅 `assert` 📄 ⏮️ 🐩 🐍 🧬 👈 👆 💪 ✅ (🔄, 🐩 `pytest`). -```Python hl_lines="2 12 15-18" -{!../../../docs_src/app_testing/tutorial001.py!} -``` +{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *} + +/// tip + +👀 👈 🔬 🔢 😐 `def`, 🚫 `async def`. + + & 🤙 👩‍💻 😐 🤙, 🚫 ⚙️ `await`. + +👉 ✔ 👆 ⚙️ `pytest` 🔗 🍵 🤢. + +/// + +/// note | 📡 ℹ -!!! tip - 👀 👈 🔬 🔢 😐 `def`, 🚫 `async def`. +👆 💪 ⚙️ `from starlette.testclient import TestClient`. - & 🤙 👩‍💻 😐 🤙, 🚫 ⚙️ `await`. +**FastAPI** 🚚 🎏 `starlette.testclient` `fastapi.testclient` 🏪 👆, 👩‍💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. - 👉 ✔ 👆 ⚙️ `pytest` 🔗 🍵 🤢. +/// -!!! note "📡 ℹ" - 👆 💪 ⚙️ `from starlette.testclient import TestClient`. +/// tip - **FastAPI** 🚚 🎏 `starlette.testclient` `fastapi.testclient` 🏪 👆, 👩‍💻. ✋️ ⚫️ 👟 🔗 ⚪️➡️ 💃. +🚥 👆 💚 🤙 `async` 🔢 👆 💯 ↖️ ⚪️➡️ 📨 📨 👆 FastAPI 🈸 (✅ 🔁 💽 🔢), ✔️ 👀 [🔁 💯](../advanced/async-tests.md){.internal-link target=_blank} 🏧 🔰. -!!! tip - 🚥 👆 💚 🤙 `async` 🔢 👆 💯 ↖️ ⚪️➡️ 📨 📨 👆 FastAPI 🈸 (✅ 🔁 💽 🔢), ✔️ 👀 [🔁 💯](../advanced/async-tests.md){.internal-link target=_blank} 🏧 🔰. +/// ## 🎏 💯 @@ -50,7 +60,7 @@ ### **FastAPI** 📱 📁 -➡️ 💬 👆 ✔️ 📁 📊 🔬 [🦏 🈸](./bigger-applications.md){.internal-link target=_blank}: +➡️ 💬 👆 ✔️ 📁 📊 🔬 [🦏 🈸](bigger-applications.md){.internal-link target=_blank}: ``` . @@ -62,9 +72,7 @@ 📁 `main.py` 👆 ✔️ 👆 **FastAPI** 📱: -```Python -{!../../../docs_src/app_testing/main.py!} -``` +{* ../../docs_src/app_testing/main.py *} ### 🔬 📁 @@ -80,9 +88,7 @@ ↩️ 👉 📁 🎏 📦, 👆 💪 ⚙️ ⚖ 🗄 🗄 🎚 `app` ⚪️➡️ `main` 🕹 (`main.py`): -```Python hl_lines="3" -{!../../../docs_src/app_testing/test_main.py!} -``` +{* ../../docs_src/app_testing/test_main.py hl[3] *} ...& ✔️ 📟 💯 💖 ⏭. @@ -110,25 +116,13 @@ 👯‍♂️ *➡ 🛠️* 🚚 `X-Token` 🎚. -=== "🐍 3️⃣.6️⃣ & 🔛" - - ```Python - {!> ../../../docs_src/app_testing/app_b/main.py!} - ``` - -=== "🐍 3️⃣.1️⃣0️⃣ & 🔛" - - ```Python - {!> ../../../docs_src/app_testing/app_b_py310/main.py!} - ``` +{* ../../docs_src/app_testing/app_b/main.py *} ### ↔ 🔬 📁 👆 💪 ⤴️ ℹ `test_main.py` ⏮️ ↔ 💯: -```Python -{!> ../../../docs_src/app_testing/app_b/test_main.py!} -``` +{* ../../docs_src/app_testing/app_b/test_main.py *} 🕐❔ 👆 💪 👩‍💻 🚶‍♀️ ℹ 📨 & 👆 🚫 💭 ❔, 👆 💪 🔎 (🇺🇸🔍) ❔ ⚫️ `httpx`, ⚖️ ❔ ⚫️ ⏮️ `requests`, 🇸🇲 🔧 ⚓️ 🔛 📨' 🔧. @@ -144,10 +138,13 @@ 🌖 ℹ 🔃 ❔ 🚶‍♀️ 💽 👩‍💻 (⚙️ `httpx` ⚖️ `TestClient`) ✅ 🇸🇲 🧾. -!!! info - 🗒 👈 `TestClient` 📨 💽 👈 💪 🗜 🎻, 🚫 Pydantic 🏷. +/// info + +🗒 👈 `TestClient` 📨 💽 👈 💪 🗜 🎻, 🚫 Pydantic 🏷. + +🚥 👆 ✔️ Pydantic 🏷 👆 💯 & 👆 💚 📨 🚮 💽 🈸 ⏮️ 🔬, 👆 💪 ⚙️ `jsonable_encoder` 🔬 [🎻 🔗 🔢](encoder.md){.internal-link target=_blank}. - 🚥 👆 ✔️ Pydantic 🏷 👆 💯 & 👆 💚 📨 🚮 💽 🈸 ⏮️ 🔬, 👆 💪 ⚙️ `jsonable_encoder` 🔬 [🎻 🔗 🔢](encoder.md){.internal-link target=_blank}. +/// ## 🏃 ⚫️ diff --git a/docs/en/data/contributors.yml b/docs/en/data/contributors.yml new file mode 100644 index 000000000..c4364e923 --- /dev/null +++ b/docs/en/data/contributors.yml @@ -0,0 +1,530 @@ +tiangolo: + login: tiangolo + count: 723 + avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 + url: https://github.com/tiangolo +dependabot: + login: dependabot + count: 94 + avatarUrl: https://avatars.githubusercontent.com/in/29110?v=4 + url: https://github.com/apps/dependabot +alejsdev: + login: alejsdev + count: 47 + avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=356f39ff3f0211c720b06d3dbb060e98884085e3&v=4 + url: https://github.com/alejsdev +github-actions: + login: github-actions + count: 26 + avatarUrl: https://avatars.githubusercontent.com/in/15368?v=4 + url: https://github.com/apps/github-actions +Kludex: + login: Kludex + count: 23 + avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4 + url: https://github.com/Kludex +pre-commit-ci: + login: pre-commit-ci + count: 22 + avatarUrl: https://avatars.githubusercontent.com/in/68672?v=4 + url: https://github.com/apps/pre-commit-ci +dmontagu: + login: dmontagu + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 + url: https://github.com/dmontagu +euri10: + login: euri10 + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/1104190?u=321a2e953e6645a7d09b732786c7a8061e0f8a8b&v=4 + url: https://github.com/euri10 +kantandane: + login: kantandane + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/3978368?u=cccc199291f991a73b1ebba5abc735a948e0bd16&v=4 + url: https://github.com/kantandane +nilslindemann: + login: nilslindemann + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/6892179?u=1dca6a22195d6cd1ab20737c0e19a4c55d639472&v=4 + url: https://github.com/nilslindemann +zhaohan-dong: + login: zhaohan-dong + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/65422392?u=8260f8781f50248410ebfa4c9bf70e143fe5c9f2&v=4 + url: https://github.com/zhaohan-dong +mariacamilagl: + login: mariacamilagl + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/11489395?u=4adb6986bf3debfc2b8216ae701f2bd47d73da7d&v=4 + url: https://github.com/mariacamilagl +handabaldeep: + login: handabaldeep + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/12239103?u=6c39ef15d14c6d5211f5dd775cc4842f8d7f2f3a&v=4 + url: https://github.com/handabaldeep +vishnuvskvkl: + login: vishnuvskvkl + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/84698110?u=8af5de0520dd4fa195f53c2850a26f57c0f6bc64&v=4 + url: https://github.com/vishnuvskvkl +svlandeg: + login: svlandeg + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/8796347?u=556c97650c27021911b0b9447ec55e75987b0e8a&v=4 + url: https://github.com/svlandeg +alissadb: + login: alissadb + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/96190409?u=be42d85938c241be781505a5a872575be28b2906&v=4 + url: https://github.com/alissadb +wshayes: + login: wshayes + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4 + url: https://github.com/wshayes +samuelcolvin: + login: samuelcolvin + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/4039449?u=42eb3b833047c8c4b4f647a031eaef148c16d93f&v=4 + url: https://github.com/samuelcolvin +waynerv: + login: waynerv + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/39515546?u=ec35139777597cdbbbddda29bf8b9d4396b429a9&v=4 + url: https://github.com/waynerv +krishnamadhavan: + login: krishnamadhavan + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/31798870?u=950693b28f3ae01105fd545c046e46ca3d31ab06&v=4 + url: https://github.com/krishnamadhavan +alv2017: + login: alv2017 + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 + url: https://github.com/alv2017 +jekirl: + login: jekirl + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/2546697?u=a027452387d85bd4a14834e19d716c99255fb3b7&v=4 + url: https://github.com/jekirl +hitrust: + login: hitrust + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/3360631?u=5fa1f475ad784d64eb9666bdd43cc4d285dcc773&v=4 + url: https://github.com/hitrust +ShahriyarR: + login: ShahriyarR + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/3852029?u=c9a1691e5ebdc94cbf543086099a6ed705cdb873&v=4 + url: https://github.com/ShahriyarR +adriangb: + login: adriangb + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4 + url: https://github.com/adriangb +iudeen: + login: iudeen + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=f09cdd745e5bf16138f29b42732dd57c7f02bee1&v=4 + url: https://github.com/iudeen +philipokiokio: + login: philipokiokio + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/55271518?u=d30994d339aaaf1f6bf1b8fc810132016fbd4fdc&v=4 + url: https://github.com/philipokiokio +AlexWendland: + login: AlexWendland + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/3949212?u=c4c0c615e0ea33d00bfe16b779cf6ebc0f58071c&v=4 + url: https://github.com/AlexWendland +divums: + login: divums + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/1397556?v=4 + url: https://github.com/divums +prostomarkeloff: + login: prostomarkeloff + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/28061158?u=6918e39a1224194ba636e897461a02a20126d7ad&v=4 + url: https://github.com/prostomarkeloff +nsidnev: + login: nsidnev + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/22559461?u=a9cc3238217e21dc8796a1a500f01b722adb082c&v=4 + url: https://github.com/nsidnev +pawamoy: + login: pawamoy + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/3999221?u=b030e4c89df2f3a36bc4710b925bdeb6745c9856&v=4 + url: https://github.com/pawamoy +patrickmckenna: + login: patrickmckenna + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/3589536?u=53aef07250d226d35e526768e26891964907b41a&v=4 + url: https://github.com/patrickmckenna +hukkin: + login: hukkin + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/3275109?u=77bb83759127965eacbfe67e2ca983066e964fde&v=4 + url: https://github.com/hukkin +marcosmmb: + login: marcosmmb + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/6181089?u=b8567a842b38c5570c315b2b7ca766fa7be6721e&v=4 + url: https://github.com/marcosmmb +Serrones: + login: Serrones + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/22691749?u=4795b880e13ca33a73e52fc0ef7dc9c60c8fce47&v=4 + url: https://github.com/Serrones +uriyyo: + login: uriyyo + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/32038156?u=a27b65a9ec3420586a827a0facccbb8b6df1ffb3&v=4 + url: https://github.com/uriyyo +amacfie: + login: amacfie + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/889657?u=d70187989940b085bcbfa3bedad8dbc5f3ab1fe7&v=4 + url: https://github.com/amacfie +rkbeatss: + login: rkbeatss + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/23391143?u=56ab6bff50be950fa8cae5cf736f2ae66e319ff3&v=4 + url: https://github.com/rkbeatss +asheux: + login: asheux + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/22955146?u=4553ebf5b5a7c7fe031a46182083aa224faba2e1&v=4 + url: https://github.com/asheux +n25a: + login: n25a + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/49960770?u=7d8a6d5f0a75a5e9a865a2527edfd48895ea27ae&v=4 + url: https://github.com/n25a +ghandic: + login: ghandic + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/23500353?u=e2e1d736f924d9be81e8bfc565b6d8836ba99773&v=4 + url: https://github.com/ghandic +TeoZosa: + login: TeoZosa + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/13070236?u=96fdae85800ef85dcfcc4b5f8281dc8778c8cb7d&v=4 + url: https://github.com/TeoZosa +graingert: + login: graingert + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/413772?v=4 + url: https://github.com/graingert +jaystone776: + login: jaystone776 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/11191137?u=299205a95e9b6817a43144a48b643346a5aac5cc&v=4 + url: https://github.com/jaystone776 +zanieb: + login: zanieb + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/2586601?u=e5c86f7ff3b859e7e183187ac2b17fd6ee32b3ab&v=4 + url: https://github.com/zanieb +MicaelJarniac: + login: MicaelJarniac + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/19514231?u=158c91874ea98d6e9e6f0c6db37ee2ce60c55ff2&v=4 + url: https://github.com/MicaelJarniac +papb: + login: papb + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/20914054?u=890511fae7ea90d887e2a65ce44a1775abba38d5&v=4 + url: https://github.com/papb +musicinmybrain: + login: musicinmybrain + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/6898909?u=9010312053e7141383b9bdf538036c7f37fbaba0&v=4 + url: https://github.com/musicinmybrain +gitworkflows: + login: gitworkflows + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/118260833?v=4 + url: https://github.com/gitworkflows +Nimitha-jagadeesha: + login: Nimitha-jagadeesha + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/58389915?v=4 + url: https://github.com/Nimitha-jagadeesha +lucaromagnoli: + login: lucaromagnoli + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/38782977?u=e66396859f493b4ddcb3a837a1b2b2039c805417&v=4 + url: https://github.com/lucaromagnoli +salmantec: + login: salmantec + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/41512228?u=443551b893ff2425c59d5d021644f098cf7c68d5&v=4 + url: https://github.com/salmantec +OCE1960: + login: OCE1960 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/45076670?u=0e9a44712b92ffa89ddfbaa83c112f3f8e1d68e2&v=4 + url: https://github.com/OCE1960 +hamidrasti: + login: hamidrasti + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/43915620?v=4 + url: https://github.com/hamidrasti +kkinder: + login: kkinder + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1115018?u=c5e90284a9f5c5049eae1bb029e3655c7dc913ed&v=4 + url: https://github.com/kkinder +kabirkhan: + login: kabirkhan + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/13891834?u=e0eabf792376443ac853e7dca6f550db4166fe35&v=4 + url: https://github.com/kabirkhan +zamiramir: + login: zamiramir + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/40475662?u=e58ef61034e8d0d6a312cc956fb09b9c3332b449&v=4 + url: https://github.com/zamiramir +trim21: + login: trim21 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/13553903?u=3cadf0f02095c9621aa29df6875f53a80ca4fbfb&v=4 + url: https://github.com/trim21 +koxudaxi: + login: koxudaxi + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/630670?u=507d8577b4b3670546b449c4c2ccbc5af40d72f7&v=4 + url: https://github.com/koxudaxi +pablogamboa: + login: pablogamboa + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/12892536?u=326a57059ee0c40c4eb1b38413957236841c631b&v=4 + url: https://github.com/pablogamboa +dconathan: + login: dconathan + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/15098095?v=4 + url: https://github.com/dconathan +Jamim: + login: Jamim + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/5607572?u=0cf3027bec78ba4f0b89802430c136bc69847d7a&v=4 + url: https://github.com/Jamim +svalouch: + login: svalouch + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/54674660?v=4 + url: https://github.com/svalouch +frankie567: + login: frankie567 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1144727?u=c159fe047727aedecbbeeaa96a1b03ceb9d39add&v=4 + url: https://github.com/frankie567 +marier-nico: + login: marier-nico + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/30477068?u=c7df6af853c8f4163d1517814f3e9a0715c82713&v=4 + url: https://github.com/marier-nico +Dustyposa: + login: Dustyposa + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/27180793?u=5cf2877f50b3eb2bc55086089a78a36f07042889&v=4 + url: https://github.com/Dustyposa +aviramha: + login: aviramha + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/41201924?u=6883cc4fc13a7b2e60d4deddd4be06f9c5287880&v=4 + url: https://github.com/aviramha +iwpnd: + login: iwpnd + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/6152183?u=ec59396e9437fff488791c5ecdf6d23f1f1ebf3a&v=4 + url: https://github.com/iwpnd +raphaelauv: + login: raphaelauv + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/10202690?u=e6f86f5c0c3026a15d6b51792fa3e532b12f1371&v=4 + url: https://github.com/raphaelauv +windson: + login: windson + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1826682?u=8b28dcd716c46289f191f8828e01d74edd058bef&v=4 + url: https://github.com/windson +sm-Fifteen: + login: sm-Fifteen + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/516999?u=437c0c5038558c67e887ccd863c1ba0f846c03da&v=4 + url: https://github.com/sm-Fifteen +sattosan: + login: sattosan + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/20574756?u=b0d8474d2938189c6954423ae8d81d91013f80a8&v=4 + url: https://github.com/sattosan +michaeloliverx: + login: michaeloliverx + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/55017335?u=e606eb5cc397c07523be47637b1ee796904fbb59&v=4 + url: https://github.com/michaeloliverx +voegtlel: + login: voegtlel + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/5764745?u=db8df3d70d427928ab6d7dbfc395a4a7109c1d1b&v=4 + url: https://github.com/voegtlel +HarshaLaxman: + login: HarshaLaxman + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/19939186?u=a112f38b0f6b4d4402dc8b51978b5a0b2e5c5970&v=4 + url: https://github.com/HarshaLaxman +RunningIkkyu: + login: RunningIkkyu + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/31848542?u=494ecc298e3f26197495bb357ad0f57cfd5f7a32&v=4 + url: https://github.com/RunningIkkyu +cassiobotaro: + login: cassiobotaro + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/3127847?u=a08022b191ddbd0a6159b2981d9d878b6d5bb71f&v=4 + url: https://github.com/cassiobotaro +chenl: + login: chenl + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1677651?u=c618508eaad6d596cea36c8ea784b424288f6857&v=4 + url: https://github.com/chenl +retnikt: + login: retnikt + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/24581770?v=4 + url: https://github.com/retnikt +yankeexe: + login: yankeexe + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/13623913?u=f970e66421775a8d3cdab89c0c752eaead186f6d&v=4 + url: https://github.com/yankeexe +patrickkwang: + login: patrickkwang + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1263870?u=4bf74020e15be490f19ef8322a76eec882220b96&v=4 + url: https://github.com/patrickkwang +victorphoenix3: + login: victorphoenix3 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/48182195?u=e4875bd088623cb4ddeb7be194ec54b453aff035&v=4 + url: https://github.com/victorphoenix3 +davidefiocco: + login: davidefiocco + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/4547987?v=4 + url: https://github.com/davidefiocco +adriencaccia: + login: adriencaccia + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/19605940?u=980b0b366a02791a5600b2e9f9ac2037679acaa8&v=4 + url: https://github.com/adriencaccia +jamescurtin: + login: jamescurtin + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/10189269?u=0b491fc600ca51f41cf1d95b49fa32a3eba1de57&v=4 + url: https://github.com/jamescurtin +jmriebold: + login: jmriebold + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/6983392?u=4efdc97bf2422dcc7e9ff65b9ff80087c8eb2a20&v=4 + url: https://github.com/jmriebold +nukopy: + login: nukopy + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/42367320?u=6061be0bd060506f6d564a8df3ae73fab048cdfe&v=4 + url: https://github.com/nukopy +imba-tjd: + login: imba-tjd + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/24759802?u=01e901a4fe004b4b126549d3ff1c4000fe3720b5&v=4 + url: https://github.com/imba-tjd +johnthagen: + login: johnthagen + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/10340167?u=47147fc4e4db1f573bee3fe428deeacb3197bc5f&v=4 + url: https://github.com/johnthagen +paxcodes: + login: paxcodes + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/13646646?u=e7429cc7ab11211ef762f4cd3efea7db6d9ef036&v=4 + url: https://github.com/paxcodes +kaustubhgupta: + login: kaustubhgupta + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/43691873?u=8dd738718ac7ffad4ef31e86b5d780a1141c695d&v=4 + url: https://github.com/kaustubhgupta +kinuax: + login: kinuax + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/13321374?u=22dc9873d6d9f2c7e4fc44c6480c3505efb1531f&v=4 + url: https://github.com/kinuax +wakabame: + login: wakabame + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/35513518?u=41ef6b0a55076e5c540620d68fb006e386c2ddb0&v=4 + url: https://github.com/wakabame +nzig: + login: nzig + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/7372858?u=e769add36ed73c778cdb136eb10bf96b1e119671&v=4 + url: https://github.com/nzig +yezz123: + login: yezz123 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/52716203?u=d7062cbc6eb7671d5dc9cc0e32a24ae335e0f225&v=4 + url: https://github.com/yezz123 +softwarebloat: + login: softwarebloat + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/16540684?v=4 + url: https://github.com/softwarebloat +Lancetnik: + login: Lancetnik + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/44573917?u=f9a18be7324333daf9cc314c35c3051f0a20a7a6&v=4 + url: https://github.com/Lancetnik +yogabonito: + login: yogabonito + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/7026269?v=4 + url: https://github.com/yogabonito +s111d: + login: s111d + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/4954856?v=4 + url: https://github.com/s111d +estebanx64: + login: estebanx64 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 + url: https://github.com/estebanx64 +tamird: + login: tamird + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1535036?v=4 + url: https://github.com/tamird +rabinlamadong: + login: rabinlamadong + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/170439781?v=4 + url: https://github.com/rabinlamadong +AyushSinghal1794: + login: AyushSinghal1794 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/89984761?v=4 + url: https://github.com/AyushSinghal1794 +DanielKusyDev: + login: DanielKusyDev + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/36250676?u=2ea6114ff751fc48b55f231987a0e2582c6b1bd2&v=4 + url: https://github.com/DanielKusyDev +DanielYang59: + login: DanielYang59 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/80093591?u=63873f701c7c74aac83c906800a1dddc0bc8c92f&v=4 + url: https://github.com/DanielYang59 diff --git a/docs/en/data/external_links.yml b/docs/en/data/external_links.yml index 00d6f696d..9e411a631 100644 --- a/docs/en/data/external_links.yml +++ b/docs/en/data/external_links.yml @@ -1,5 +1,29 @@ Articles: English: + - author: Balthazar Rouberol + author_link: https://balthazar-rouberol.com + link: https://blog.balthazar-rouberol.com/how-to-profile-a-fastapi-asynchronous-request + title: How to profile a FastAPI asynchronous request + - author: Stephen Siegert - Neon + link: https://neon.tech/blog/deploy-a-serverless-fastapi-app-with-neon-postgres-and-aws-app-runner-at-any-scale + title: Deploy a Serverless FastAPI App with Neon Postgres and AWS App Runner at any scale + - author: Kurtis Pykes - NVIDIA + link: https://developer.nvidia.com/blog/building-a-machine-learning-microservice-with-fastapi/ + title: Building a Machine Learning Microservice with FastAPI + - author: Ravgeet Dhillon - Twilio + link: https://www.twilio.com/en-us/blog/booking-appointments-twilio-notion-fastapi + title: Booking Appointments with Twilio, Notion, and FastAPI + - author: Abhinav Tripathi - Microsoft Blogs + link: https://devblogs.microsoft.com/cosmosdb/azure-cosmos-db-python-and-fastapi/ + title: Write a Python data layer with Azure Cosmos DB and FastAPI + - author: Donny Peeters + author_link: https://github.com/Donnype + link: https://bitestreams.com/blog/fastapi-sqlalchemy/ + title: 10 Tips for adding SQLAlchemy to FastAPI + - author: Jessica Temporal + author_link: https://jtemporal.com/socials + link: https://jtemporal.com/tips-on-migrating-from-flask-to-fastapi-and-vice-versa/ + title: Tips on migrating from Flask to FastAPI and vice-versa - author: Ankit Anchlia author_link: https://linkedin.com/in/aanchlia21 link: https://hackernoon.com/explore-how-to-effectively-use-jwt-with-fastapi @@ -7,7 +31,7 @@ Articles: - author: Nicoló Lino author_link: https://www.nlino.com link: https://github.com/softwarebloat/python-tracing-demo - title: Instrument a FastAPI service adding tracing with OpenTelemetry and send/show traces in Grafana Tempo + title: Instrument FastAPI with OpenTelemetry tracing and visualize traces in Grafana Tempo. - author: Mikhail Rozhkov, Elena Samuylova author_link: https://www.linkedin.com/in/mnrozhkov/ link: https://www.evidentlyai.com/blog/fastapi-tutorial @@ -240,6 +264,18 @@ Articles: author_link: https://medium.com/@krishnardt365 link: https://medium.com/@krishnardt365/fastapi-docker-and-postgres-91943e71be92 title: Fastapi, Docker(Docker compose) and Postgres + - author: Devon Ray + author_link: https://devonray.com + link: https://devonray.com/blog/deploying-a-fastapi-project-using-aws-lambda-aurora-cdk + title: Deployment using Docker, Lambda, Aurora, CDK & GH Actions + - author: Shubhendra Kushwaha + author_link: https://www.linkedin.com/in/theshubhendra/ + link: https://theshubhendra.medium.com/mastering-soft-delete-advanced-sqlalchemy-techniques-4678f4738947 + title: 'Mastering Soft Delete: Advanced SQLAlchemy Techniques' + - author: Shubhendra Kushwaha + author_link: https://www.linkedin.com/in/theshubhendra/ + link: https://theshubhendra.medium.com/role-based-row-filtering-advanced-sqlalchemy-techniques-733e6b1328f6 + title: 'Role based row filtering: Advanced SQLAlchemy Techniques' German: - author: Marcel Sander (actidoo) author_link: https://www.actidoo.com @@ -302,6 +338,15 @@ Articles: author_link: https://qiita.com/mtitg link: https://qiita.com/mtitg/items/47770e9a562dd150631d title: FastAPI|DB接続してCRUDするPython製APIサーバーを構築 + Portuguese: + - author: Eduardo Mendes + author_link: https://bolha.us/@dunossauro + link: https://fastapidozero.dunossauro.com/ + title: FastAPI do ZERO + - author: Jessica Temporal + author_link: https://jtemporal.com/socials + link: https://jtemporal.com/dicas-para-migrar-de-flask-para-fastapi-e-vice-versa/ + title: Dicas para migrar uma aplicação de Flask para FastAPI e vice-versa Russian: - author: Troy Köhler author_link: https://www.linkedin.com/in/trkohler/ @@ -325,8 +370,21 @@ Articles: author_link: http://editor.leonh.space/ link: https://editor.leonh.space/2022/tortoise/ title: 'Tortoise ORM / FastAPI 整合快速筆記' + Spanish: + - author: Eduardo Zepeda + author_link: https://coffeebytes.dev/en/authors/eduardo-zepeda/ + link: https://coffeebytes.dev/es/python-fastapi-el-mejor-framework-de-python/ + title: 'Tutorial de FastAPI, ¿el mejor framework de Python?' Podcasts: English: + - author: Real Python + author_link: https://realpython.com/ + link: https://realpython.com/podcasts/rpp/72/ + title: Starting With FastAPI and Examining Python's Import System - Episode 72 + - author: Python Bytes FM + author_link: https://pythonbytes.fm/ + link: https://www.pythonpodcast.com/fastapi-web-application-framework-episode-259/ + title: 'Do you dare to press "."? - Episode 247 - Dan #6: SQLModel - use the same models for SQL and FastAPI' - author: Podcast.`__init__` author_link: https://www.pythonpodcast.com/ link: https://www.pythonpodcast.com/fastapi-web-application-framework-episode-259/ diff --git a/docs/en/data/github_sponsors.yml b/docs/en/data/github_sponsors.yml index 713f229cf..805d72b73 100644 --- a/docs/en/data/github_sponsors.yml +++ b/docs/en/data/github_sponsors.yml @@ -1,151 +1,196 @@ sponsors: -- - login: scalar - avatarUrl: https://avatars.githubusercontent.com/u/301879?v=4 - url: https://github.com/scalar - - login: codacy - avatarUrl: https://avatars.githubusercontent.com/u/1834093?v=4 - url: https://github.com/codacy +- - login: renderinc + avatarUrl: https://avatars.githubusercontent.com/u/36424661?v=4 + url: https://github.com/renderinc - login: bump-sh avatarUrl: https://avatars.githubusercontent.com/u/33217836?v=4 url: https://github.com/bump-sh - - login: Alek99 - avatarUrl: https://avatars.githubusercontent.com/u/38776361?u=bd6c163fe787c2de1a26c881598e54b67e2482dd&v=4 - url: https://github.com/Alek99 - - login: cryptapi - avatarUrl: https://avatars.githubusercontent.com/u/44925437?u=61369138589bc7fee6c417f3fbd50fbd38286cc4&v=4 - url: https://github.com/cryptapi - - login: porter-dev - avatarUrl: https://avatars.githubusercontent.com/u/62078005?v=4 - url: https://github.com/porter-dev + - login: Nixtla + avatarUrl: https://avatars.githubusercontent.com/u/79945230?v=4 + url: https://github.com/Nixtla - login: andrew-propelauth avatarUrl: https://avatars.githubusercontent.com/u/89474256?u=1188c27cb744bbec36447a2cfd4453126b2ddb5c&v=4 url: https://github.com/andrew-propelauth -- - login: nihpo - avatarUrl: https://avatars.githubusercontent.com/u/1841030?u=0264956d7580f7e46687a762a7baa629f84cf97c&v=4 - url: https://github.com/nihpo - - login: ObliviousAI + - login: liblaber + avatarUrl: https://avatars.githubusercontent.com/u/100821118?v=4 + url: https://github.com/liblaber + - login: zanfaruqui + avatarUrl: https://avatars.githubusercontent.com/u/104461687?v=4 + url: https://github.com/zanfaruqui + - login: blockbee-io + avatarUrl: https://avatars.githubusercontent.com/u/115143449?u=1b8620c2d6567c4df2111a371b85a51f448f9b85&v=4 + url: https://github.com/blockbee-io + - login: zuplo + avatarUrl: https://avatars.githubusercontent.com/u/85497839?v=4 + url: https://github.com/zuplo + - login: coderabbitai + avatarUrl: https://avatars.githubusercontent.com/u/132028505?v=4 + url: https://github.com/coderabbitai + - login: porter-dev + avatarUrl: https://avatars.githubusercontent.com/u/62078005?v=4 + url: https://github.com/porter-dev + - login: scalar + avatarUrl: https://avatars.githubusercontent.com/u/301879?v=4 + url: https://github.com/scalar +- - login: ObliviousAI avatarUrl: https://avatars.githubusercontent.com/u/65656077?v=4 url: https://github.com/ObliviousAI -- - login: mikeckennedy - avatarUrl: https://avatars.githubusercontent.com/u/2035561?u=ce6165b799ea3164cb6f5ff54ea08042057442af&v=4 - url: https://github.com/mikeckennedy - - login: ndimares - avatarUrl: https://avatars.githubusercontent.com/u/6267663?u=cfb27efde7a7212be8142abb6c058a1aeadb41b1&v=4 - url: https://github.com/ndimares - - login: deta - avatarUrl: https://avatars.githubusercontent.com/u/47275976?v=4 - url: https://github.com/deta - - login: deepset-ai - avatarUrl: https://avatars.githubusercontent.com/u/51827949?v=4 - url: https://github.com/deepset-ai +- - login: svix + avatarUrl: https://avatars.githubusercontent.com/u/80175132?v=4 + url: https://github.com/svix + - login: stainless-api + avatarUrl: https://avatars.githubusercontent.com/u/88061651?v=4 + url: https://github.com/stainless-api + - login: speakeasy-api + avatarUrl: https://avatars.githubusercontent.com/u/91446104?v=4 + url: https://github.com/speakeasy-api - login: databento avatarUrl: https://avatars.githubusercontent.com/u/64141749?v=4 url: https://github.com/databento - - login: svix - avatarUrl: https://avatars.githubusercontent.com/u/80175132?v=4 - url: https://github.com/svix - - login: VincentParedes - avatarUrl: https://avatars.githubusercontent.com/u/103889729?v=4 - url: https://github.com/VincentParedes -- - login: acsone - avatarUrl: https://avatars.githubusercontent.com/u/7601056?v=4 - url: https://github.com/acsone - - login: takashi-yoneya - avatarUrl: https://avatars.githubusercontent.com/u/33813153?u=2d0522bceba0b8b69adf1f2db866503bd96f944e&v=4 - url: https://github.com/takashi-yoneya + - login: permitio + avatarUrl: https://avatars.githubusercontent.com/u/71775833?v=4 + url: https://github.com/permitio +- - login: mercedes-benz + avatarUrl: https://avatars.githubusercontent.com/u/34240465?v=4 + url: https://github.com/mercedes-benz - login: xoflare avatarUrl: https://avatars.githubusercontent.com/u/74335107?v=4 url: https://github.com/xoflare - login: marvin-robot - avatarUrl: https://avatars.githubusercontent.com/u/41086007?u=091c5cb75af363123d66f58194805a97220ee1a7&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/41086007?u=b9fcab402d0cd0aec738b6574fe60855cb0cd36d&v=4 url: https://github.com/marvin-robot + - login: Ponte-Energy-Partners + avatarUrl: https://avatars.githubusercontent.com/u/114745848?v=4 + url: https://github.com/Ponte-Energy-Partners + - login: LambdaTest-Inc + avatarUrl: https://avatars.githubusercontent.com/u/171592363?u=96606606a45fa170427206199014f2a5a2a4920b&v=4 + url: https://github.com/LambdaTest-Inc - login: BoostryJP avatarUrl: https://avatars.githubusercontent.com/u/57932412?v=4 url: https://github.com/BoostryJP - - login: jina-ai - avatarUrl: https://avatars.githubusercontent.com/u/60539444?v=4 - url: https://github.com/jina-ai + - login: acsone + avatarUrl: https://avatars.githubusercontent.com/u/7601056?v=4 + url: https://github.com/acsone - - login: Trivie avatarUrl: https://avatars.githubusercontent.com/u/8161763?v=4 url: https://github.com/Trivie -- - login: birkjernstrom - avatarUrl: https://avatars.githubusercontent.com/u/281715?u=4be14b43f76b4bd497b1941309bb390250b405e6&v=4 - url: https://github.com/birkjernstrom - - login: yasyf - avatarUrl: https://avatars.githubusercontent.com/u/709645?u=f36736b3c6a85f578886ecc42a740e7b436e7a01&v=4 - url: https://github.com/yasyf - - login: AccentDesign - avatarUrl: https://avatars.githubusercontent.com/u/2429332?v=4 - url: https://github.com/AccentDesign - - login: americanair - avatarUrl: https://avatars.githubusercontent.com/u/12281813?v=4 - url: https://github.com/americanair - - login: mainframeindustries +- - login: takashi-yoneya + avatarUrl: https://avatars.githubusercontent.com/u/33813153?u=2d0522bceba0b8b69adf1f2db866503bd96f944e&v=4 + url: https://github.com/takashi-yoneya +- - login: mainframeindustries avatarUrl: https://avatars.githubusercontent.com/u/55092103?v=4 url: https://github.com/mainframeindustries - - login: doseiai - avatarUrl: https://avatars.githubusercontent.com/u/57115726?v=4 - url: https://github.com/doseiai - login: CanoaPBC avatarUrl: https://avatars.githubusercontent.com/u/64223768?v=4 url: https://github.com/CanoaPBC -- - login: povilasb - avatarUrl: https://avatars.githubusercontent.com/u/1213442?u=b11f58ed6ceea6e8297c9b310030478ebdac894d&v=4 - url: https://github.com/povilasb - - login: primer-io + - login: yasyf + avatarUrl: https://avatars.githubusercontent.com/u/709645?u=f36736b3c6a85f578886ecc42a740e7b436e7a01&v=4 + url: https://github.com/yasyf +- - login: primer-io avatarUrl: https://avatars.githubusercontent.com/u/62146168?v=4 url: https://github.com/primer-io + - login: povilasb + avatarUrl: https://avatars.githubusercontent.com/u/1213442?u=b11f58ed6ceea6e8297c9b310030478ebdac894d&v=4 + url: https://github.com/povilasb - - login: upciti avatarUrl: https://avatars.githubusercontent.com/u/43346262?v=4 url: https://github.com/upciti -- - login: Kludex - avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 - url: https://github.com/Kludex - - login: samuelcolvin + - login: freddiev4 + avatarUrl: https://avatars.githubusercontent.com/u/8339018?u=1aad5b4f5a04cb750852b843d5e1d8f4ce339c2e&v=4 + url: https://github.com/freddiev4 +- - login: samuelcolvin avatarUrl: https://avatars.githubusercontent.com/u/4039449?u=42eb3b833047c8c4b4f647a031eaef148c16d93f&v=4 url: https://github.com/samuelcolvin - - login: koconder - avatarUrl: https://avatars.githubusercontent.com/u/25068?u=582657b23622aaa3dfe68bd028a780f272f456fa&v=4 - url: https://github.com/koconder - - login: jefftriplett - avatarUrl: https://avatars.githubusercontent.com/u/50527?u=af1ddfd50f6afd6d99f333ba2ac8d0a5b245ea74&v=4 - url: https://github.com/jefftriplett - - login: jstanden - avatarUrl: https://avatars.githubusercontent.com/u/63288?u=c3658d57d2862c607a0e19c2101c3c51876e36ad&v=4 - url: https://github.com/jstanden - - login: andreaso - avatarUrl: https://avatars.githubusercontent.com/u/285964?u=837265cc7562c0685f25b2d81cd9de0434fe107c&v=4 - url: https://github.com/andreaso - - login: pamelafox - avatarUrl: https://avatars.githubusercontent.com/u/297042?v=4 - url: https://github.com/pamelafox - - login: ericof - avatarUrl: https://avatars.githubusercontent.com/u/306014?u=cf7c8733620397e6584a451505581c01c5d842d7&v=4 - url: https://github.com/ericof - - login: wshayes - avatarUrl: https://avatars.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4 - url: https://github.com/wshayes - - login: koxudaxi - avatarUrl: https://avatars.githubusercontent.com/u/630670?u=507d8577b4b3670546b449c4c2ccbc5af40d72f7&v=4 - url: https://github.com/koxudaxi - - login: falkben - avatarUrl: https://avatars.githubusercontent.com/u/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4 - url: https://github.com/falkben - - login: mintuhouse - avatarUrl: https://avatars.githubusercontent.com/u/769950?u=ecfbd79a97d33177e0d093ddb088283cf7fe8444&v=4 - url: https://github.com/mintuhouse - - login: tcsmith - avatarUrl: https://avatars.githubusercontent.com/u/989034?u=7d8d741552b3279e8f4d3878679823a705a46f8f&v=4 - url: https://github.com/tcsmith - - login: mickaelandrieu - avatarUrl: https://avatars.githubusercontent.com/u/1247388?u=599f6e73e452a9453f2bd91e5c3100750e731ad4&v=4 - url: https://github.com/mickaelandrieu + - login: vincentkoc + avatarUrl: https://avatars.githubusercontent.com/u/25068?u=fbd5b2d51142daa4bdbc21e21953a3b8b8188a4a&v=4 + url: https://github.com/vincentkoc + - login: ddilidili + avatarUrl: https://avatars.githubusercontent.com/u/42176885?u=c0a849dde06987434653197b5f638d3deb55fc6c&v=4 + url: https://github.com/ddilidili + - login: otosky + avatarUrl: https://avatars.githubusercontent.com/u/42260747?u=69d089387c743d89427aa4ad8740cfb34045a9e0&v=4 + url: https://github.com/otosky + - login: ramonalmeidam + avatarUrl: https://avatars.githubusercontent.com/u/45269580?u=3358750b3a5854d7c3ed77aaca7dd20a0f529d32&v=4 + url: https://github.com/ramonalmeidam + - login: sepsi77 + avatarUrl: https://avatars.githubusercontent.com/u/18682303?v=4 + url: https://github.com/sepsi77 + - login: RaamEEIL + avatarUrl: https://avatars.githubusercontent.com/u/20320552?v=4 + url: https://github.com/RaamEEIL + - login: jhundman + avatarUrl: https://avatars.githubusercontent.com/u/24263908?v=4 + url: https://github.com/jhundman + - login: b-rad-c + avatarUrl: https://avatars.githubusercontent.com/u/25362581?u=5bb10629f4015b62bec1f9a366675d5085551af9&v=4 + url: https://github.com/b-rad-c + - login: ehaca + avatarUrl: https://avatars.githubusercontent.com/u/25950317?u=cec1a3e0643b785288ae8260cc295a85ab344995&v=4 + url: https://github.com/ehaca + - login: raphaellaude + avatarUrl: https://avatars.githubusercontent.com/u/28026311?u=28faad3e62250ef91a0c3c5d0faba39592d9ab39&v=4 + url: https://github.com/raphaellaude + - login: timlrx + avatarUrl: https://avatars.githubusercontent.com/u/28362229?u=9a745ca31372ee324af682715ae88ce8522f9094&v=4 + url: https://github.com/timlrx + - login: Leay15 + avatarUrl: https://avatars.githubusercontent.com/u/32212558?u=c4aa9c1737e515959382a5515381757b1fd86c53&v=4 + url: https://github.com/Leay15 + - login: BoYanZh + avatarUrl: https://avatars.githubusercontent.com/u/32470225?u=55b174d080382822759d74307f8a0355fa86e808&v=4 + url: https://github.com/BoYanZh + - login: ygorpontelo + avatarUrl: https://avatars.githubusercontent.com/u/32963605?u=35f7103f9c4c4c2589ae5737ee882e9375ef072e&v=4 + url: https://github.com/ygorpontelo + - login: ProteinQure + avatarUrl: https://avatars.githubusercontent.com/u/33707203?v=4 + url: https://github.com/ProteinQure + - login: chickenandstats + avatarUrl: https://avatars.githubusercontent.com/u/79477966?u=ae2b894aa954070db1d7830dab99b49eba4e4567&v=4 + url: https://github.com/chickenandstats + - login: kaoru0310 + avatarUrl: https://avatars.githubusercontent.com/u/80977929?u=1b61d10142b490e56af932ddf08a390fae8ee94f&v=4 + url: https://github.com/kaoru0310 + - login: DelfinaCare + avatarUrl: https://avatars.githubusercontent.com/u/83734439?v=4 + url: https://github.com/DelfinaCare + - login: Karine-Bauch + avatarUrl: https://avatars.githubusercontent.com/u/90465103?u=7feb1018abb1a5631cfd9a91fea723d1ceb5f49b&v=4 + url: https://github.com/Karine-Bauch + - login: eruditis + avatarUrl: https://avatars.githubusercontent.com/u/95244703?v=4 + url: https://github.com/eruditis + - login: jugeeem + avatarUrl: https://avatars.githubusercontent.com/u/116043716?u=ae590d79c38ac79c91b9c5caa6887d061e865a3d&v=4 + url: https://github.com/jugeeem + - login: logic-automation + avatarUrl: https://avatars.githubusercontent.com/u/144732884?v=4 + url: https://github.com/logic-automation + - login: roboflow + avatarUrl: https://avatars.githubusercontent.com/u/53104118?v=4 + url: https://github.com/roboflow + - login: dudikbender + avatarUrl: https://avatars.githubusercontent.com/u/53487583?u=3a57542938ebfd57579a0111db2b297e606d9681&v=4 + url: https://github.com/dudikbender + - login: patsatsia + avatarUrl: https://avatars.githubusercontent.com/u/61111267?u=3271b85f7a37b479c8d0ae0a235182e83c166edf&v=4 + url: https://github.com/patsatsia + - login: anthonycepeda + avatarUrl: https://avatars.githubusercontent.com/u/72019805?u=60bdf46240cff8fca482ff0fc07d963fd5e1a27c&v=4 + url: https://github.com/anthonycepeda + - login: patricioperezv + avatarUrl: https://avatars.githubusercontent.com/u/73832292?u=5f471f156e19ee7920e62ae0f4a47b95580e61cf&v=4 + url: https://github.com/patricioperezv + - login: dodo5522 + avatarUrl: https://avatars.githubusercontent.com/u/1362607?u=9bf1e0e520cccc547c046610c468ce6115bbcf9f&v=4 + url: https://github.com/dodo5522 + - login: nihpo + avatarUrl: https://avatars.githubusercontent.com/u/1841030?u=0264956d7580f7e46687a762a7baa629f84cf97c&v=4 + url: https://github.com/nihpo - login: knallgelb avatarUrl: https://avatars.githubusercontent.com/u/2358812?u=c48cb6362b309d74cbf144bd6ad3aed3eb443e82&v=4 url: https://github.com/knallgelb - - login: johannquerne - avatarUrl: https://avatars.githubusercontent.com/u/2736484?u=9b3381546a25679913a2b08110e4373c98840821&v=4 - url: https://github.com/johannquerne - login: Shark009 avatarUrl: https://avatars.githubusercontent.com/u/3163309?u=0c6f4091b0eda05c44c390466199826e6dc6e431&v=4 url: https://github.com/Shark009 @@ -164,30 +209,84 @@ sponsors: - login: anomaly avatarUrl: https://avatars.githubusercontent.com/u/3654837?v=4 url: https://github.com/anomaly - - login: jgreys - avatarUrl: https://avatars.githubusercontent.com/u/4136890?u=096820d1ef89877d57d0f68e669ead8b0fde84df&v=4 - url: https://github.com/jgreys + - login: gorhack + avatarUrl: https://avatars.githubusercontent.com/u/4141690?u=ec119ebc4bdf00a7bc84657a71aa17834f4f27f3&v=4 + url: https://github.com/gorhack + - login: Ryandaydev + avatarUrl: https://avatars.githubusercontent.com/u/4292423?u=48f68868db8886fce31a1d802c1003914c6cd7c6&v=4 + url: https://github.com/Ryandaydev - login: jaredtrog avatarUrl: https://avatars.githubusercontent.com/u/4381365?v=4 url: https://github.com/jaredtrog + - login: jstanden + avatarUrl: https://avatars.githubusercontent.com/u/63288?u=c3658d57d2862c607a0e19c2101c3c51876e36ad&v=4 + url: https://github.com/jstanden + - login: paulcwatts + avatarUrl: https://avatars.githubusercontent.com/u/150269?u=1819e145d573b44f0ad74b87206d21cd60331d4e&v=4 + url: https://github.com/paulcwatts + - login: andreaso + avatarUrl: https://avatars.githubusercontent.com/u/285964?u=837265cc7562c0685f25b2d81cd9de0434fe107c&v=4 + url: https://github.com/andreaso + - login: robintw + avatarUrl: https://avatars.githubusercontent.com/u/296686?v=4 + url: https://github.com/robintw + - login: pamelafox + avatarUrl: https://avatars.githubusercontent.com/u/297042?v=4 + url: https://github.com/pamelafox + - login: ericof + avatarUrl: https://avatars.githubusercontent.com/u/306014?u=cf7c8733620397e6584a451505581c01c5d842d7&v=4 + url: https://github.com/ericof + - login: wshayes + avatarUrl: https://avatars.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4 + url: https://github.com/wshayes + - login: gaetanBloch + avatarUrl: https://avatars.githubusercontent.com/u/583199?u=50c49e83d6b4feb78a091901ea02ead1462f442b&v=4 + url: https://github.com/gaetanBloch + - login: koxudaxi + avatarUrl: https://avatars.githubusercontent.com/u/630670?u=507d8577b4b3670546b449c4c2ccbc5af40d72f7&v=4 + url: https://github.com/koxudaxi + - login: falkben + avatarUrl: https://avatars.githubusercontent.com/u/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4 + url: https://github.com/falkben + - login: mintuhouse + avatarUrl: https://avatars.githubusercontent.com/u/769950?u=ecfbd79a97d33177e0d093ddb088283cf7fe8444&v=4 + url: https://github.com/mintuhouse + - login: TrevorBenson + avatarUrl: https://avatars.githubusercontent.com/u/9167887?u=dccbea3327a57750923333d8ebf1a0b3f1948949&v=4 + url: https://github.com/TrevorBenson + - login: wdwinslow + avatarUrl: https://avatars.githubusercontent.com/u/11562137?u=dc01daafb354135603a263729e3d26d939c0c452&v=4 + url: https://github.com/wdwinslow + - login: catherinenelson1 + avatarUrl: https://avatars.githubusercontent.com/u/11951946?u=fe11bc35d36b6038cd46a946e4e46ef8aa5688ab&v=4 + url: https://github.com/catherinenelson1 + - login: jsoques + avatarUrl: https://avatars.githubusercontent.com/u/12414216?u=620921d94196546cc8b9eae2cc4cbc3f95bab42f&v=4 + url: https://github.com/jsoques + - login: joeds13 + avatarUrl: https://avatars.githubusercontent.com/u/13631604?u=628eb122e08bef43767b3738752b883e8e7f6259&v=4 + url: https://github.com/joeds13 + - login: dannywade + avatarUrl: https://avatars.githubusercontent.com/u/13680237?u=418ee985bd41577b20fde81417fb2d901e875e8a&v=4 + url: https://github.com/dannywade + - login: khadrawy + avatarUrl: https://avatars.githubusercontent.com/u/13686061?u=59f25ef42ecf04c22657aac4238ce0e2d3d30304&v=4 + url: https://github.com/khadrawy + - login: mjohnsey + avatarUrl: https://avatars.githubusercontent.com/u/16784016?u=38fad2e6b411244560b3af99c5f5a4751bc81865&v=4 + url: https://github.com/mjohnsey + - login: ashi-agrawal + avatarUrl: https://avatars.githubusercontent.com/u/17105294?u=99c7a854035e5398d8e7b674f2d42baae6c957f8&v=4 + url: https://github.com/ashi-agrawal - login: oliverxchen avatarUrl: https://avatars.githubusercontent.com/u/4471774?u=534191f25e32eeaadda22dfab4b0a428733d5489&v=4 url: https://github.com/oliverxchen - - login: ennui93 - avatarUrl: https://avatars.githubusercontent.com/u/5300907?u=5b5452725ddb391b2caaebf34e05aba873591c3a&v=4 - url: https://github.com/ennui93 - login: ternaus - avatarUrl: https://avatars.githubusercontent.com/u/5481618?u=fabc8d75c921b3380126adb5a931c5da6e7db04f&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/5481618?u=513a26b02a39e7a28d587cd37c6cc877ea368e6e&v=4 url: https://github.com/ternaus - login: eseglem avatarUrl: https://avatars.githubusercontent.com/u/5920492?u=208d419cf667b8ac594c82a8db01932c7e50d057&v=4 url: https://github.com/eseglem - - login: Yaleesa - avatarUrl: https://avatars.githubusercontent.com/u/6135475?v=4 - url: https://github.com/Yaleesa - - login: iwpnd - avatarUrl: https://avatars.githubusercontent.com/u/6152183?u=c485eefca5c6329600cae63dd35e4f5682ce6924&v=4 - url: https://github.com/iwpnd - login: FernandoCelmer avatarUrl: https://avatars.githubusercontent.com/u/6262214?u=d29fff3fd862fda4ca752079f13f32e84c762ea4&v=4 url: https://github.com/FernandoCelmer @@ -200,138 +299,66 @@ sponsors: - login: hiancdtrsnm avatarUrl: https://avatars.githubusercontent.com/u/7343177?v=4 url: https://github.com/hiancdtrsnm - - login: wdwinslow - avatarUrl: https://avatars.githubusercontent.com/u/11562137?u=dc01daafb354135603a263729e3d26d939c0c452&v=4 - url: https://github.com/wdwinslow - - login: drcat101 - avatarUrl: https://avatars.githubusercontent.com/u/11951946?u=e714b957185b8cf3d301cced7fc3ad2842122c6a&v=4 - url: https://github.com/drcat101 - - login: jsoques - avatarUrl: https://avatars.githubusercontent.com/u/12414216?u=620921d94196546cc8b9eae2cc4cbc3f95bab42f&v=4 - url: https://github.com/jsoques - - login: joeds13 - avatarUrl: https://avatars.githubusercontent.com/u/13631604?u=628eb122e08bef43767b3738752b883e8e7f6259&v=4 - url: https://github.com/joeds13 - - login: dannywade - avatarUrl: https://avatars.githubusercontent.com/u/13680237?u=418ee985bd41577b20fde81417fb2d901e875e8a&v=4 - url: https://github.com/dannywade - - login: khadrawy - avatarUrl: https://avatars.githubusercontent.com/u/13686061?u=59f25ef42ecf04c22657aac4238ce0e2d3d30304&v=4 - url: https://github.com/khadrawy - - login: mjohnsey - avatarUrl: https://avatars.githubusercontent.com/u/16784016?u=38fad2e6b411244560b3af99c5f5a4751bc81865&v=4 - url: https://github.com/mjohnsey - - login: wedwardbeck - avatarUrl: https://avatars.githubusercontent.com/u/19333237?u=1de4ae2bf8d59eb4c013f21d863cbe0f2010575f&v=4 - url: https://github.com/wedwardbeck - - login: RaamEEIL - avatarUrl: https://avatars.githubusercontent.com/u/20320552?v=4 - url: https://github.com/RaamEEIL - - login: Filimoa - avatarUrl: https://avatars.githubusercontent.com/u/21352040?u=0be845711495bbd7b756e13fcaeb8efc1ebd78ba&v=4 - url: https://github.com/Filimoa - - login: ehaca - avatarUrl: https://avatars.githubusercontent.com/u/25950317?u=cec1a3e0643b785288ae8260cc295a85ab344995&v=4 - url: https://github.com/ehaca - - login: timlrx - avatarUrl: https://avatars.githubusercontent.com/u/28362229?u=9a745ca31372ee324af682715ae88ce8522f9094&v=4 - url: https://github.com/timlrx - - login: BrettskiPy - avatarUrl: https://avatars.githubusercontent.com/u/30988215?u=d8a94a67e140d5ee5427724b292cc52d8827087a&v=4 - url: https://github.com/BrettskiPy - - login: Leay15 - avatarUrl: https://avatars.githubusercontent.com/u/32212558?u=c4aa9c1737e515959382a5515381757b1fd86c53&v=4 - url: https://github.com/Leay15 - - login: ygorpontelo - avatarUrl: https://avatars.githubusercontent.com/u/32963605?u=35f7103f9c4c4c2589ae5737ee882e9375ef072e&v=4 - url: https://github.com/ygorpontelo - - login: ProteinQure - avatarUrl: https://avatars.githubusercontent.com/u/33707203?v=4 - url: https://github.com/ProteinQure - - login: RafaelWO - avatarUrl: https://avatars.githubusercontent.com/u/38643099?u=56c676f024667ee416dc8b1cdf0c2611b9dc994f&v=4 - url: https://github.com/RafaelWO - - login: arleybri18 - avatarUrl: https://avatars.githubusercontent.com/u/39681546?u=5c028f81324b0e8c73b3c15bc4e7b0218d2ba0c3&v=4 - url: https://github.com/arleybri18 - - login: thenickben - avatarUrl: https://avatars.githubusercontent.com/u/40610922?u=1e907d904041b7c91213951a3cb344cd37c14aaf&v=4 - url: https://github.com/thenickben - - login: ddilidili - avatarUrl: https://avatars.githubusercontent.com/u/42176885?u=c0a849dde06987434653197b5f638d3deb55fc6c&v=4 - url: https://github.com/ddilidili - - login: ramonalmeidam - avatarUrl: https://avatars.githubusercontent.com/u/45269580?u=3358750b3a5854d7c3ed77aaca7dd20a0f529d32&v=4 - url: https://github.com/ramonalmeidam - - login: dudikbender - avatarUrl: https://avatars.githubusercontent.com/u/53487583?u=3a57542938ebfd57579a0111db2b297e606d9681&v=4 - url: https://github.com/dudikbender - - login: Amirshox - avatarUrl: https://avatars.githubusercontent.com/u/56707784?u=2a2f8cc243d6f5b29cd63fd2772f7a97aadc6c6b&v=4 - url: https://github.com/Amirshox - - login: prodhype - avatarUrl: https://avatars.githubusercontent.com/u/60444672?u=3f278cff25ea37ead487d7861d4a984795de819e&v=4 - url: https://github.com/prodhype - - login: yakkonaut - avatarUrl: https://avatars.githubusercontent.com/u/60633704?u=90a71fd631aa998ba4a96480788f017c9904e07b&v=4 - url: https://github.com/yakkonaut - - login: patsatsia - avatarUrl: https://avatars.githubusercontent.com/u/61111267?u=3271b85f7a37b479c8d0ae0a235182e83c166edf&v=4 - url: https://github.com/patsatsia - - login: anthonycepeda - avatarUrl: https://avatars.githubusercontent.com/u/72019805?u=4252c6b6dc5024af502a823a3ac5e7a03a69963f&v=4 - url: https://github.com/anthonycepeda - - login: patricioperezv - avatarUrl: https://avatars.githubusercontent.com/u/73832292?u=5f471f156e19ee7920e62ae0f4a47b95580e61cf&v=4 - url: https://github.com/patricioperezv - - login: kaoru0310 - avatarUrl: https://avatars.githubusercontent.com/u/80977929?u=1b61d10142b490e56af932ddf08a390fae8ee94f&v=4 - url: https://github.com/kaoru0310 - - login: DelfinaCare - avatarUrl: https://avatars.githubusercontent.com/u/83734439?v=4 - url: https://github.com/DelfinaCare - - login: osawa-koki - avatarUrl: https://avatars.githubusercontent.com/u/94336223?u=59c6fe6945bcbbaff87b2a794238671b060620d2&v=4 - url: https://github.com/osawa-koki - - login: apitally - avatarUrl: https://avatars.githubusercontent.com/u/138365043?v=4 - url: https://github.com/apitally -- - login: getsentry - avatarUrl: https://avatars.githubusercontent.com/u/1396951?v=4 - url: https://github.com/getsentry - - login: pawamoy avatarUrl: https://avatars.githubusercontent.com/u/3999221?u=b030e4c89df2f3a36bc4710b925bdeb6745c9856&v=4 url: https://github.com/pawamoy - - login: ddanier - avatarUrl: https://avatars.githubusercontent.com/u/113563?u=ed1dc79de72f93bd78581f88ebc6952b62f472da&v=4 - url: https://github.com/ddanier - - login: bryanculbertson - avatarUrl: https://avatars.githubusercontent.com/u/144028?u=defda4f90e93429221cc667500944abde60ebe4a&v=4 - url: https://github.com/bryanculbertson - - login: slafs - avatarUrl: https://avatars.githubusercontent.com/u/210173?v=4 - url: https://github.com/slafs - - login: adamghill - avatarUrl: https://avatars.githubusercontent.com/u/317045?u=f1349d5ffe84a19f324e204777859fbf69ddf633&v=4 - url: https://github.com/adamghill - - login: eteq - avatarUrl: https://avatars.githubusercontent.com/u/346587?v=4 - url: https://github.com/eteq - - login: dmig - avatarUrl: https://avatars.githubusercontent.com/u/388564?v=4 - url: https://github.com/dmig - - login: securancy - avatarUrl: https://avatars.githubusercontent.com/u/606673?v=4 - url: https://github.com/securancy - - login: natehouk - avatarUrl: https://avatars.githubusercontent.com/u/805439?u=d8e4be629dc5d7efae7146157e41ee0bd129d9bc&v=4 - url: https://github.com/natehouk + - login: bnkc + avatarUrl: https://avatars.githubusercontent.com/u/34930566?u=db5e6f4f87836cad26c2aa90ce390ce49041c5a9&v=4 + url: https://github.com/bnkc + - login: petercool + avatarUrl: https://avatars.githubusercontent.com/u/37613029?u=81c525232bb35780945a68e88afd96bb2cdad9c4&v=4 + url: https://github.com/petercool + - login: siavashyj + avatarUrl: https://avatars.githubusercontent.com/u/43583410?u=562005ddc7901cd27a1219a118a2363817b14977&v=4 + url: https://github.com/siavashyj + - login: mobyw + avatarUrl: https://avatars.githubusercontent.com/u/44370805?v=4 + url: https://github.com/mobyw + - login: ArtyomVancyan + avatarUrl: https://avatars.githubusercontent.com/u/44609997?v=4 + url: https://github.com/ArtyomVancyan + - login: caviri + avatarUrl: https://avatars.githubusercontent.com/u/45425937?u=4e14bd64282bad8f385eafbdb004b5a279366d6e&v=4 + url: https://github.com/caviri + - login: SebTota + avatarUrl: https://avatars.githubusercontent.com/u/25122511?v=4 + url: https://github.com/SebTota + - login: nisutec + avatarUrl: https://avatars.githubusercontent.com/u/25281462?u=e562484c451fdfc59053163f64405f8eb262b8b0&v=4 + url: https://github.com/nisutec + - login: hoenie-ams + avatarUrl: https://avatars.githubusercontent.com/u/25708487?u=cda07434f0509ac728d9edf5e681117c0f6b818b&v=4 + url: https://github.com/hoenie-ams + - login: joerambo + avatarUrl: https://avatars.githubusercontent.com/u/26282974?v=4 + url: https://github.com/joerambo + - login: rlnchow + avatarUrl: https://avatars.githubusercontent.com/u/28018479?u=a93ca9cf1422b9ece155784a72d5f2fdbce7adff&v=4 + url: https://github.com/rlnchow + - login: dvlpjrs + avatarUrl: https://avatars.githubusercontent.com/u/32254642?u=fbd6ad0324d4f1eb6231cf775be1c7bd4404e961&v=4 + url: https://github.com/dvlpjrs + - login: engineerjoe440 + avatarUrl: https://avatars.githubusercontent.com/u/33275230?u=eb223cad27017bb1e936ee9b429b450d092d0236&v=4 + url: https://github.com/engineerjoe440 + - login: hgalytoby + avatarUrl: https://avatars.githubusercontent.com/u/50397689?u=62c7ff3519858423579676cd0efbd7e3f1ffe63a&v=4 + url: https://github.com/hgalytoby + - login: conservative-dude + avatarUrl: https://avatars.githubusercontent.com/u/55538308?u=f250c44942ea6e73a6bd90739b381c470c192c11&v=4 + url: https://github.com/conservative-dude + - login: CR1337 + avatarUrl: https://avatars.githubusercontent.com/u/62649536?u=57a6aab10d2421a497306da8bcded01b826c54ae&v=4 + url: https://github.com/CR1337 + - login: PunRabbit + avatarUrl: https://avatars.githubusercontent.com/u/70463212?u=1a835cfbc99295a60c8282f6aa6199d1b42241a5&v=4 + url: https://github.com/PunRabbit + - login: PelicanQ + avatarUrl: https://avatars.githubusercontent.com/u/77930606?v=4 + url: https://github.com/PelicanQ - login: browniebroke avatarUrl: https://avatars.githubusercontent.com/u/861044?u=5abfca5588f3e906b31583d7ee62f6de4b68aa24&v=4 url: https://github.com/browniebroke - - login: dodo5522 - avatarUrl: https://avatars.githubusercontent.com/u/1362607?u=9bf1e0e520cccc547c046610c468ce6115bbcf9f&v=4 - url: https://github.com/dodo5522 - login: miguelgr avatarUrl: https://avatars.githubusercontent.com/u/1484589?u=54556072b8136efa12ae3b6902032ea2a39ace4b&v=4 url: https://github.com/miguelgr @@ -344,59 +371,32 @@ sponsors: - login: leobiscassi avatarUrl: https://avatars.githubusercontent.com/u/1977418?u=f9f82445a847ab479bd7223debd677fcac6c49a0&v=4 url: https://github.com/leobiscassi - - login: cbonoz - avatarUrl: https://avatars.githubusercontent.com/u/2351087?u=fd3e8030b2cc9fbfbb54a65e9890c548a016f58b&v=4 - url: https://github.com/cbonoz - - login: anthonycorletti - avatarUrl: https://avatars.githubusercontent.com/u/3477132?v=4 - url: https://github.com/anthonycorletti - login: Alisa-lisa avatarUrl: https://avatars.githubusercontent.com/u/4137964?u=e7e393504f554f4ff15863a1e01a5746863ef9ce&v=4 url: https://github.com/Alisa-lisa - - login: gowikel - avatarUrl: https://avatars.githubusercontent.com/u/4339072?u=0e325ffcc539c38f89d9aa876bd87f9ec06ce0ee&v=4 - url: https://github.com/gowikel - - login: danielunderwood - avatarUrl: https://avatars.githubusercontent.com/u/4472301?v=4 - url: https://github.com/danielunderwood - - login: yuawn - avatarUrl: https://avatars.githubusercontent.com/u/5111198?u=5315576f3fe1a70fd2d0f02181588f4eea5d353d&v=4 - url: https://github.com/yuawn - - login: sdevkota - avatarUrl: https://avatars.githubusercontent.com/u/5250987?u=4ed9a120c89805a8aefda1cbdc0cf6512e64d1b4&v=4 - url: https://github.com/sdevkota - - login: unredundant - avatarUrl: https://avatars.githubusercontent.com/u/5607577?u=1ffbf39f5bb8736b75c0d235707d6e8f803725c5&v=4 - url: https://github.com/unredundant - - login: Baghdady92 - avatarUrl: https://avatars.githubusercontent.com/u/5708590?v=4 - url: https://github.com/Baghdady92 - - login: jakeecolution - avatarUrl: https://avatars.githubusercontent.com/u/5884696?u=4a7c7883fb064b593b50cb6697b54687e6f7aafe&v=4 - url: https://github.com/jakeecolution - - login: KentShikama - avatarUrl: https://avatars.githubusercontent.com/u/6329898?u=8b236810db9b96333230430837e1f021f9246da1&v=4 - url: https://github.com/KentShikama - - login: katnoria - avatarUrl: https://avatars.githubusercontent.com/u/7674948?u=09767eb13e07e09496c5fee4e5ce21d9eac34a56&v=4 - url: https://github.com/katnoria - - login: harsh183 - avatarUrl: https://avatars.githubusercontent.com/u/7780198?v=4 - url: https://github.com/harsh183 - - login: hcristea - avatarUrl: https://avatars.githubusercontent.com/u/7814406?u=61d7a4fcf846983a4606788eac25e1c6c1209ba8&v=4 - url: https://github.com/hcristea - - login: moonape1226 - avatarUrl: https://avatars.githubusercontent.com/u/8532038?u=d9f8b855a429fff9397c3833c2ff83849ebf989d&v=4 - url: https://github.com/moonape1226 - - login: albertkun - avatarUrl: https://avatars.githubusercontent.com/u/8574425?u=aad2a9674273c9275fe414d99269b7418d144089&v=4 - url: https://github.com/albertkun + - login: ddanier + avatarUrl: https://avatars.githubusercontent.com/u/113563?u=ed1dc79de72f93bd78581f88ebc6952b62f472da&v=4 + url: https://github.com/ddanier + - login: bryanculbertson + avatarUrl: https://avatars.githubusercontent.com/u/144028?u=defda4f90e93429221cc667500944abde60ebe4a&v=4 + url: https://github.com/bryanculbertson + - login: slafs + avatarUrl: https://avatars.githubusercontent.com/u/210173?v=4 + url: https://github.com/slafs + - login: ceb10n + avatarUrl: https://avatars.githubusercontent.com/u/235213?u=edcce471814a1eba9f0cdaa4cd0de18921a940a6&v=4 + url: https://github.com/ceb10n + - login: tochikuji + avatarUrl: https://avatars.githubusercontent.com/u/851759?v=4 + url: https://github.com/tochikuji + - login: msehnout + avatarUrl: https://avatars.githubusercontent.com/u/9369632?u=8c988f1b008a3f601385a3616f9327820f66e3a5&v=4 + url: https://github.com/msehnout - login: xncbf - avatarUrl: https://avatars.githubusercontent.com/u/9462045?u=ee91e210ae93b9cdd8f248b21cb028316cc0b747&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/9462045?u=a80a7bb349555b277645632ed66639ff43400614&v=4 url: https://github.com/xncbf - login: DMantis - avatarUrl: https://avatars.githubusercontent.com/u/9536869?v=4 + avatarUrl: https://avatars.githubusercontent.com/u/9536869?u=652dd0d49717803c0cbcbf44f7740e53cf2d4892&v=4 url: https://github.com/DMantis - login: hard-coders avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4 @@ -404,135 +404,87 @@ sponsors: - login: supdann avatarUrl: https://avatars.githubusercontent.com/u/9986994?u=9671810f4ae9504c063227fee34fd47567ff6954&v=4 url: https://github.com/supdann - - login: satwikkansal - avatarUrl: https://avatars.githubusercontent.com/u/10217535?u=b12d6ef74ea297de9e46da6933b1a5b7ba9e6a61&v=4 - url: https://github.com/satwikkansal - login: mntolia avatarUrl: https://avatars.githubusercontent.com/u/10390224?v=4 url: https://github.com/mntolia - login: pheanex avatarUrl: https://avatars.githubusercontent.com/u/10408624?u=5b6bab6ee174aa6e991333e06eb29f628741013d&v=4 url: https://github.com/pheanex - - login: dzoladz - avatarUrl: https://avatars.githubusercontent.com/u/10561752?u=5ee314d54aa79592c18566827ad8914debd5630d&v=4 - url: https://github.com/dzoladz - - login: JimFawkes - avatarUrl: https://avatars.githubusercontent.com/u/12075115?u=dc58ecfd064d72887c34bf500ddfd52592509acd&v=4 - url: https://github.com/JimFawkes + - login: Zuzah + avatarUrl: https://avatars.githubusercontent.com/u/10934846?u=1ef43e075ddc87bd1178372bf4d95ee6175cae27&v=4 + url: https://github.com/Zuzah - login: artempronevskiy avatarUrl: https://avatars.githubusercontent.com/u/12235104?u=03df6e1e55c9c6fe5d230adabb8dd7d43d8bbe8f&v=4 url: https://github.com/artempronevskiy - - login: giuliano-oliveira - avatarUrl: https://avatars.githubusercontent.com/u/13181797?u=0ef2dfbf7fc9a9726d45c21d32b5d1038a174870&v=4 - url: https://github.com/giuliano-oliveira - login: TheR1D avatarUrl: https://avatars.githubusercontent.com/u/16740832?u=b0dfdbdb27b79729430c71c6128962f77b7b53f7&v=4 url: https://github.com/TheR1D - login: joshuatz avatarUrl: https://avatars.githubusercontent.com/u/17817563?u=f1bf05b690d1fc164218f0b420cdd3acb7913e21&v=4 url: https://github.com/joshuatz - - login: jangia - avatarUrl: https://avatars.githubusercontent.com/u/17927101?u=9261b9bb0c3e3bb1ecba43e8915dc58d8c9a077e&v=4 - url: https://github.com/jangia - - login: shuheng-liu - avatarUrl: https://avatars.githubusercontent.com/u/22414322?u=813c45f30786c6b511b21a661def025d8f7b609e&v=4 - url: https://github.com/shuheng-liu - - login: salahelfarissi - avatarUrl: https://avatars.githubusercontent.com/u/23387408?u=73222a4be627c1a3dee9736e0da22224eccdc8f6&v=4 - url: https://github.com/salahelfarissi - - login: pers0n4 - avatarUrl: https://avatars.githubusercontent.com/u/24864600?u=f211a13a7b572cbbd7779b9c8d8cb428cc7ba07e&v=4 - url: https://github.com/pers0n4 - - login: kxzk - avatarUrl: https://avatars.githubusercontent.com/u/25046261?u=e185e58080090f9e678192cd214a14b14a2b232b&v=4 - url: https://github.com/kxzk - - login: SebTota - avatarUrl: https://avatars.githubusercontent.com/u/25122511?v=4 - url: https://github.com/SebTota - - login: nisutec - avatarUrl: https://avatars.githubusercontent.com/u/25281462?u=e562484c451fdfc59053163f64405f8eb262b8b0&v=4 - url: https://github.com/nisutec - - login: hoenie-ams - avatarUrl: https://avatars.githubusercontent.com/u/25708487?u=cda07434f0509ac728d9edf5e681117c0f6b818b&v=4 - url: https://github.com/hoenie-ams - - login: joerambo - avatarUrl: https://avatars.githubusercontent.com/u/26282974?v=4 - url: https://github.com/joerambo - - login: rlnchow - avatarUrl: https://avatars.githubusercontent.com/u/28018479?u=a93ca9cf1422b9ece155784a72d5f2fdbce7adff&v=4 - url: https://github.com/rlnchow - - login: White-Mask - avatarUrl: https://avatars.githubusercontent.com/u/31826970?u=8625355dc25ddf9c85a8b2b0b9932826c4c8f44c&v=4 - url: https://github.com/White-Mask - - login: HosamAlmoghraby - avatarUrl: https://avatars.githubusercontent.com/u/32025281?u=aa1b09feabccbf9dc506b81c71155f32d126cefa&v=4 - url: https://github.com/HosamAlmoghraby - - login: engineerjoe440 - avatarUrl: https://avatars.githubusercontent.com/u/33275230?u=eb223cad27017bb1e936ee9b429b450d092d0236&v=4 - url: https://github.com/engineerjoe440 - - login: bnkc - avatarUrl: https://avatars.githubusercontent.com/u/34930566?u=fa1dc8db3e920cf5c5636b97180a6f811fa01aaf&v=4 - url: https://github.com/bnkc - - login: declon - avatarUrl: https://avatars.githubusercontent.com/u/36180226?v=4 - url: https://github.com/declon - - login: curegit - avatarUrl: https://avatars.githubusercontent.com/u/37978051?u=1733c322079118c0cdc573c03d92813f50a9faec&v=4 - url: https://github.com/curegit - - login: kristiangronberg - avatarUrl: https://avatars.githubusercontent.com/u/42678548?v=4 - url: https://github.com/kristiangronberg - - login: arrrrrmin - avatarUrl: https://avatars.githubusercontent.com/u/43553423?u=36a3880a6eb29309c19e6cadbb173bafbe91deb1&v=4 - url: https://github.com/arrrrrmin - - login: ArtyomVancyan - avatarUrl: https://avatars.githubusercontent.com/u/44609997?v=4 - url: https://github.com/ArtyomVancyan - - login: hgalytoby - avatarUrl: https://avatars.githubusercontent.com/u/50397689?u=f4888c2c54929bd86eed0d3971d09fcb306e5088&v=4 - url: https://github.com/hgalytoby - - login: conservative-dude - avatarUrl: https://avatars.githubusercontent.com/u/55538308?u=f250c44942ea6e73a6bd90739b381c470c192c11&v=4 - url: https://github.com/conservative-dude - - login: Calesi19 - avatarUrl: https://avatars.githubusercontent.com/u/58052598?u=273d4fc364c004602c93dd6adeaf5cc915b93cd2&v=4 - url: https://github.com/Calesi19 - - login: 0417taehyun - avatarUrl: https://avatars.githubusercontent.com/u/63915557?u=47debaa860fd52c9b98c97ef357ddcec3b3fb399&v=4 - url: https://github.com/0417taehyun - - login: fernandosmither - avatarUrl: https://avatars.githubusercontent.com/u/66154723?u=a76a037b5d674938a75d2cff862fb6dfd63ec214&v=4 - url: https://github.com/fernandosmither - - login: romabozhanovgithub - avatarUrl: https://avatars.githubusercontent.com/u/67696229?u=e4b921eef096415300425aca249348f8abb78ad7&v=4 - url: https://github.com/romabozhanovgithub - - login: mbukeRepo - avatarUrl: https://avatars.githubusercontent.com/u/70356088?u=d2eb23e2b222a3b316c4183b05a3236b32819dc2&v=4 - url: https://github.com/mbukeRepo - - login: adriiamontoto - avatarUrl: https://avatars.githubusercontent.com/u/75563346?u=eeb1350b82ecb4d96592f9b6cd1a16870c355e38&v=4 - url: https://github.com/adriiamontoto - - login: PelicanQ - avatarUrl: https://avatars.githubusercontent.com/u/77930606?v=4 - url: https://github.com/PelicanQ - - login: tahmarrrr23 - avatarUrl: https://avatars.githubusercontent.com/u/138208610?u=465a46b0ff72a74252d3e3a71ac7d2f1919cda28&v=4 - url: https://github.com/tahmarrrr23 -- - login: ssbarnea - avatarUrl: https://avatars.githubusercontent.com/u/102495?u=b4bf6818deefe59952ac22fec6ed8c76de1b8f7c&v=4 - url: https://github.com/ssbarnea - - login: Patechoc - avatarUrl: https://avatars.githubusercontent.com/u/2376641?u=23b49e9eda04f078cb74fa3f93593aa6a57bb138&v=4 - url: https://github.com/Patechoc - - login: DazzyMlv - avatarUrl: https://avatars.githubusercontent.com/u/23006212?u=df429da52882b0432e5ac81d4f1b489abc86433c&v=4 - url: https://github.com/DazzyMlv - - login: sadikkuzu - avatarUrl: https://avatars.githubusercontent.com/u/23168063?u=d179c06bb9f65c4167fcab118526819f8e0dac17&v=4 - url: https://github.com/sadikkuzu - - login: danburonline - avatarUrl: https://avatars.githubusercontent.com/u/34251194?u=94935cccfbec58083ab1e535212d54f1bf2c978a&v=4 - url: https://github.com/danburonline + - login: danielunderwood + avatarUrl: https://avatars.githubusercontent.com/u/4472301?v=4 + url: https://github.com/danielunderwood + - login: rangulvers + avatarUrl: https://avatars.githubusercontent.com/u/5235430?u=e254d4af4ace5a05fa58372ae677c7d26f0d5a53&v=4 + url: https://github.com/rangulvers + - login: sdevkota + avatarUrl: https://avatars.githubusercontent.com/u/5250987?u=4ed9a120c89805a8aefda1cbdc0cf6512e64d1b4&v=4 + url: https://github.com/sdevkota + - login: brizzbuzz + avatarUrl: https://avatars.githubusercontent.com/u/5607577?u=58d5aae33bc97e52f11f334d2702e8710314b5c1&v=4 + url: https://github.com/brizzbuzz + - login: Baghdady92 + avatarUrl: https://avatars.githubusercontent.com/u/5708590?v=4 + url: https://github.com/Baghdady92 + - login: KentShikama + avatarUrl: https://avatars.githubusercontent.com/u/6329898?u=8b236810db9b96333230430837e1f021f9246da1&v=4 + url: https://github.com/KentShikama + - login: katnoria + avatarUrl: https://avatars.githubusercontent.com/u/7674948?u=09767eb13e07e09496c5fee4e5ce21d9eac34a56&v=4 + url: https://github.com/katnoria + - login: harsh183 + avatarUrl: https://avatars.githubusercontent.com/u/7780198?v=4 + url: https://github.com/harsh183 + - login: hcristea + avatarUrl: https://avatars.githubusercontent.com/u/7814406?u=19092923a4ea5b338567961c8270b9206a6d81bb&v=4 + url: https://github.com/hcristea + - login: moonape1226 + avatarUrl: https://avatars.githubusercontent.com/u/8532038?u=d9f8b855a429fff9397c3833c2ff83849ebf989d&v=4 + url: https://github.com/moonape1226 +- - login: larsyngvelundin + avatarUrl: https://avatars.githubusercontent.com/u/34173819?u=74958599695bf83ac9f1addd935a51548a10c6b0&v=4 + url: https://github.com/larsyngvelundin + - login: andrecorumba + avatarUrl: https://avatars.githubusercontent.com/u/37807517?u=9b9be3b41da9bda60957da9ef37b50dbf65baa61&v=4 + url: https://github.com/andrecorumba - login: rwxd avatarUrl: https://avatars.githubusercontent.com/u/40308458?u=cd04a39e3655923be4f25c2ba8a5a07b3da3230a&v=4 url: https://github.com/rwxd + - login: morzan1001 + avatarUrl: https://avatars.githubusercontent.com/u/47593005?u=c30ab7230f82a12a9b938dcb54f84a996931409a&v=4 + url: https://github.com/morzan1001 + - login: sadikkuzu + avatarUrl: https://avatars.githubusercontent.com/u/23168063?u=d179c06bb9f65c4167fcab118526819f8e0dac17&v=4 + url: https://github.com/sadikkuzu + - login: Olegt0rr + avatarUrl: https://avatars.githubusercontent.com/u/25399456?u=3e87b5239a2f4600975ba13be73054f8567c6060&v=4 + url: https://github.com/Olegt0rr + - login: FabulousCodingFox + avatarUrl: https://avatars.githubusercontent.com/u/78906517?u=924a27cbee3db7e0ece5cc1509921402e1445e74&v=4 + url: https://github.com/FabulousCodingFox + - login: anqorithm + avatarUrl: https://avatars.githubusercontent.com/u/61029571?u=468256fa4e2d9ce2870b608299724bebb7a33f18&v=4 + url: https://github.com/anqorithm + - login: Materacl + avatarUrl: https://avatars.githubusercontent.com/u/70155818?u=ae11d084518856127cca483816a91a187e3124ee&v=4 + url: https://github.com/Materacl + - login: Toothwitch + avatarUrl: https://avatars.githubusercontent.com/u/1710406?u=5eebb23b46cd26e48643b9e5179536cad491c17a&v=4 + url: https://github.com/Toothwitch + - login: ssbarnea + avatarUrl: https://avatars.githubusercontent.com/u/102495?u=c7bd9ddf127785286fc939dd18cb02db0a453bce&v=4 + url: https://github.com/ssbarnea + - login: andreagrandi + avatarUrl: https://avatars.githubusercontent.com/u/636391?u=13d90cb8ec313593a5b71fbd4e33b78d6da736f5&v=4 + url: https://github.com/andreagrandi diff --git a/docs/en/data/members.yml b/docs/en/data/members.yml new file mode 100644 index 000000000..7ec16e917 --- /dev/null +++ b/docs/en/data/members.yml @@ -0,0 +1,22 @@ +members: +- login: tiangolo + avatar_url: https://avatars.githubusercontent.com/u/1326112 + url: https://github.com/tiangolo +- login: Kludex + avatar_url: https://avatars.githubusercontent.com/u/7353520 + url: https://github.com/Kludex +- login: alejsdev + avatar_url: https://avatars.githubusercontent.com/u/90076947 + url: https://github.com/alejsdev +- login: svlandeg + avatar_url: https://avatars.githubusercontent.com/u/8796347 + url: https://github.com/svlandeg +- login: YuriiMotov + avatar_url: https://avatars.githubusercontent.com/u/109919500 + url: https://github.com/YuriiMotov +- login: patrick91 + avatar_url: https://avatars.githubusercontent.com/u/667029 + url: https://github.com/patrick91 +- login: luzzodev + avatar_url: https://avatars.githubusercontent.com/u/27291415 + url: https://github.com/luzzodev diff --git a/docs/en/data/people.yml b/docs/en/data/people.yml index 2877e7938..7f910ab34 100644 --- a/docs/en/data/people.yml +++ b/docs/en/data/people.yml @@ -1,32 +1,43 @@ maintainers: - login: tiangolo - answers: 1870 - prs: 523 - avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=740f11212a731f56798f558ceddb0bd07642afa7&v=4 + answers: 1894 + avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 url: https://github.com/tiangolo experts: +- login: tiangolo + count: 1894 + avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 + url: https://github.com/tiangolo +- login: github-actions + count: 770 + avatarUrl: https://avatars.githubusercontent.com/in/15368?v=4 + url: https://github.com/apps/github-actions - login: Kludex - count: 522 - avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 + count: 645 + avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4 url: https://github.com/Kludex +- login: jgould22 + count: 250 + avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 + url: https://github.com/jgould22 - login: dmontagu - count: 241 + count: 240 avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 url: https://github.com/dmontagu +- login: YuriiMotov + count: 223 + avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 + url: https://github.com/YuriiMotov - login: Mause - count: 220 + count: 219 avatarUrl: https://avatars.githubusercontent.com/u/1405026?v=4 url: https://github.com/Mause - login: ycd count: 217 - avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=bba5af018423a2858d49309bed2a899bb5c34ac5&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=29682e4b6ac7d5293742ccf818188394b9a82972&v=4 url: https://github.com/ycd -- login: jgould22 - count: 205 - avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 - url: https://github.com/jgould22 - login: JarroVGIT - count: 193 + count: 192 avatarUrl: https://avatars.githubusercontent.com/u/13659033?u=e8bea32d07a5ef72f7dde3b2079ceb714923ca05&v=4 url: https://github.com/JarroVGIT - login: euri10 @@ -34,53 +45,61 @@ experts: avatarUrl: https://avatars.githubusercontent.com/u/1104190?u=321a2e953e6645a7d09b732786c7a8061e0f8a8b&v=4 url: https://github.com/euri10 - login: iudeen - count: 127 + count: 128 avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 url: https://github.com/iudeen - login: phy25 count: 126 avatarUrl: https://avatars.githubusercontent.com/u/331403?v=4 url: https://github.com/phy25 +- login: JavierSanchezCastro + count: 85 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro - login: raphaelauv count: 83 avatarUrl: https://avatars.githubusercontent.com/u/10202690?u=e6f86f5c0c3026a15d6b51792fa3e532b12f1371&v=4 url: https://github.com/raphaelauv -- login: ArcLightSlavik - count: 71 - avatarUrl: https://avatars.githubusercontent.com/u/31127044?u=b0f2c37142f4b762e41ad65dc49581813422bd71&v=4 - url: https://github.com/ArcLightSlavik - login: ghandic count: 71 avatarUrl: https://avatars.githubusercontent.com/u/23500353?u=e2e1d736f924d9be81e8bfc565b6d8836ba99773&v=4 url: https://github.com/ghandic +- login: ArcLightSlavik + count: 71 + avatarUrl: https://avatars.githubusercontent.com/u/31127044?u=b0f2c37142f4b762e41ad65dc49581813422bd71&v=4 + url: https://github.com/ArcLightSlavik +- login: n8sty + count: 66 + avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 + url: https://github.com/n8sty - login: falkben - count: 57 + count: 59 avatarUrl: https://avatars.githubusercontent.com/u/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4 url: https://github.com/falkben +- login: acidjunk + count: 50 + avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 + url: https://github.com/acidjunk - login: sm-Fifteen count: 49 avatarUrl: https://avatars.githubusercontent.com/u/516999?u=437c0c5038558c67e887ccd863c1ba0f846c03da&v=4 url: https://github.com/sm-Fifteen - login: yinziyan1206 - count: 48 + count: 49 avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 url: https://github.com/yinziyan1206 -- login: insomnes - count: 45 - avatarUrl: https://avatars.githubusercontent.com/u/16958893?u=f8be7088d5076d963984a21f95f44e559192d912&v=4 - url: https://github.com/insomnes - login: adriangb - count: 45 + count: 46 avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4 url: https://github.com/adriangb -- login: acidjunk - count: 45 - avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 - url: https://github.com/acidjunk - login: Dustyposa count: 45 avatarUrl: https://avatars.githubusercontent.com/u/27180793?u=5cf2877f50b3eb2bc55086089a78a36f07042889&v=4 url: https://github.com/Dustyposa +- login: insomnes + count: 45 + avatarUrl: https://avatars.githubusercontent.com/u/16958893?u=f8be7088d5076d963984a21f95f44e559192d912&v=4 + url: https://github.com/insomnes - login: odiseo0 count: 43 avatarUrl: https://avatars.githubusercontent.com/u/87550035?u=241a71f6b7068738b81af3e57f45ffd723538401&v=4 @@ -93,12 +112,16 @@ experts: count: 40 avatarUrl: https://avatars.githubusercontent.com/u/11836741?u=8bd5ef7e62fe6a82055e33c4c0e0a7879ff8cfb6&v=4 url: https://github.com/includeamin -- login: n8sty - count: 40 - avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 - url: https://github.com/n8sty +- login: sinisaos + count: 39 + avatarUrl: https://avatars.githubusercontent.com/u/30960668?v=4 + url: https://github.com/sinisaos +- login: luzzodev + count: 37 + avatarUrl: https://avatars.githubusercontent.com/u/27291415?v=4 + url: https://github.com/luzzodev - login: chbndrhnns - count: 38 + count: 37 avatarUrl: https://avatars.githubusercontent.com/u/7534547?v=4 url: https://github.com/chbndrhnns - login: STeveShary @@ -113,14 +136,14 @@ experts: count: 32 avatarUrl: https://avatars.githubusercontent.com/u/41326348?u=ba2fda6b30110411ecbf406d187907e2b420ac19&v=4 url: https://github.com/panla -- login: JavierSanchezCastro - count: 30 - avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 - url: https://github.com/JavierSanchezCastro - login: prostomarkeloff count: 28 - avatarUrl: https://avatars.githubusercontent.com/u/28061158?u=72309cc1f2e04e40fa38b29969cb4e9d3f722e7b&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/28061158?u=6918e39a1224194ba636e897461a02a20126d7ad&v=4 url: https://github.com/prostomarkeloff +- login: hasansezertasan + count: 27 + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan - login: dbanty count: 26 avatarUrl: https://avatars.githubusercontent.com/u/43723790?u=9bcce836bbce55835291c5b2ac93a4e311f4b3c3&v=4 @@ -129,22 +152,30 @@ experts: count: 25 avatarUrl: https://avatars.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4 url: https://github.com/wshayes -- login: acnebs - count: 23 - avatarUrl: https://avatars.githubusercontent.com/u/9054108?v=4 - url: https://github.com/acnebs - login: SirTelemak count: 23 avatarUrl: https://avatars.githubusercontent.com/u/9435877?u=719327b7d2c4c62212456d771bfa7c6b8dbb9eac&v=4 url: https://github.com/SirTelemak +- login: nymous + count: 22 + avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 + url: https://github.com/nymous +- login: acnebs + count: 22 + avatarUrl: https://avatars.githubusercontent.com/u/9054108?v=4 + url: https://github.com/acnebs +- login: chrisK824 + count: 22 + avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 + url: https://github.com/chrisK824 - login: rafsaf count: 21 avatarUrl: https://avatars.githubusercontent.com/u/51059348?u=5fe59a56e1f2f9ccd8005d71752a8276f133ae1a&v=4 url: https://github.com/rafsaf -- login: nymous +- login: ebottos94 count: 20 - avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 - url: https://github.com/nymous + avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=8b91053b3abe4a9209375e3651e1c1ef192d884b&v=4 + url: https://github.com/ebottos94 - login: nsidnev count: 20 avatarUrl: https://avatars.githubusercontent.com/u/22559461?u=a9cc3238217e21dc8796a1a500f01b722adb082c&v=4 @@ -153,22 +184,26 @@ experts: count: 20 avatarUrl: https://avatars.githubusercontent.com/u/565544?v=4 url: https://github.com/chris-allnutt -- login: chrisK824 - count: 20 - avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 - url: https://github.com/chrisK824 -- login: ebottos94 - count: 20 - avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4 - url: https://github.com/ebottos94 -- login: retnikt +- login: estebanx64 + count: 19 + avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 + url: https://github.com/estebanx64 +- login: sehraramiz count: 18 - avatarUrl: https://avatars.githubusercontent.com/u/24581770?v=4 - url: https://github.com/retnikt + avatarUrl: https://avatars.githubusercontent.com/u/14166324?u=8fac65e84dfff24245d304a5b5b09f7b5bd69dc9&v=4 + url: https://github.com/sehraramiz - login: zoliknemet count: 18 avatarUrl: https://avatars.githubusercontent.com/u/22326718?u=31ba446ac290e23e56eea8e4f0c558aaf0b40779&v=4 url: https://github.com/zoliknemet +- login: retnikt + count: 18 + avatarUrl: https://avatars.githubusercontent.com/u/24581770?v=4 + url: https://github.com/retnikt +- login: caeser1996 + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/16540232?u=05d2beb8e034d584d0a374b99d8826327bd7f614&v=4 + url: https://github.com/caeser1996 - login: Hultner count: 17 avatarUrl: https://avatars.githubusercontent.com/u/2669034?u=115e53df959309898ad8dc9443fbb35fee71df07&v=4 @@ -179,376 +214,657 @@ experts: url: https://github.com/harunyasar - login: nkhitrov count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/28262306?u=66ee21316275ef356081c2efc4ed7a4572e690dc&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/28262306?u=e19427d8dc296d6950e9c424adacc92d37496fe9&v=4 url: https://github.com/nkhitrov -- login: caeser1996 - count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/16540232?u=05d2beb8e034d584d0a374b99d8826327bd7f614&v=4 - url: https://github.com/caeser1996 -- login: dstlny - count: 16 - avatarUrl: https://avatars.githubusercontent.com/u/41964673?u=9f2174f9d61c15c6e3a4c9e3aeee66f711ce311f&v=4 - url: https://github.com/dstlny - login: jonatasoli count: 16 avatarUrl: https://avatars.githubusercontent.com/u/26334101?u=071c062d2861d3dd127f6b4a5258cd8ef55d4c50&v=4 url: https://github.com/jonatasoli +- login: dstlny + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/41964673?u=9f2174f9d61c15c6e3a4c9e3aeee66f711ce311f&v=4 + url: https://github.com/dstlny +- login: ceb10n + count: 15 + avatarUrl: https://avatars.githubusercontent.com/u/235213?u=edcce471814a1eba9f0cdaa4cd0de18921a940a6&v=4 + url: https://github.com/ceb10n +- login: jorgerpo + count: 15 + avatarUrl: https://avatars.githubusercontent.com/u/12537771?u=7444d20019198e34911082780cc7ad73f2b97cb3&v=4 + url: https://github.com/jorgerpo +- login: simondale00 + count: 15 + avatarUrl: https://avatars.githubusercontent.com/u/33907262?u=2721fb37014d50daf473267c808aa678ecaefe09&v=4 + url: https://github.com/simondale00 - login: ghost count: 15 avatarUrl: https://avatars.githubusercontent.com/u/10137?u=b1951d34a583cf12ec0d3b0781ba19be97726318&v=4 url: https://github.com/ghost -last_month_active: -- login: Ventura94 +- login: abhint + count: 15 + avatarUrl: https://avatars.githubusercontent.com/u/25699289?u=b5d219277b4d001ac26fb8be357fddd88c29d51b&v=4 + url: https://github.com/abhint +last_month_experts: +- login: Kludex + count: 14 + avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4 + url: https://github.com/Kludex +- login: YuriiMotov + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 + url: https://github.com/YuriiMotov +- login: sehraramiz + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/14166324?u=8fac65e84dfff24245d304a5b5b09f7b5bd69dc9&v=4 + url: https://github.com/sehraramiz +- login: luzzodev count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/43103937?u=ccb837005aaf212a449c374618c4339089e2f733&v=4 - url: https://github.com/Ventura94 -- login: JavierSanchezCastro + avatarUrl: https://avatars.githubusercontent.com/u/27291415?v=4 + url: https://github.com/luzzodev +- login: yokwejuste count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 - url: https://github.com/JavierSanchezCastro -- login: jgould22 + avatarUrl: https://avatars.githubusercontent.com/u/71908316?u=592c1e42aa0ee5cb94890e0b863e2acc78cc3bbc&v=4 + url: https://github.com/yokwejuste +- login: alv2017 count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 + url: https://github.com/alv2017 +- login: Trinkes + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/9466879?v=4 + url: https://github.com/Trinkes +- login: PREPONDERANCE + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/112809059?u=30ab12dc9ddba2f94ab90e6ad4ad8bc5cfa7fccd&v=4 + url: https://github.com/PREPONDERANCE +- login: nbx3 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/34649527?u=943812f69e0d40adbd3fa1c9b8ef50dd971a2a45&v=4 + url: https://github.com/nbx3 +- login: XiaoXinYo + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/56395004?u=b3b7cb758997f283c271a581833e407229dab82c&v=4 + url: https://github.com/XiaoXinYo +- login: iloveitaly + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/150855?v=4 + url: https://github.com/iloveitaly +three_months_experts: +- login: luzzodev + count: 33 + avatarUrl: https://avatars.githubusercontent.com/u/27291415?v=4 + url: https://github.com/luzzodev +- login: YuriiMotov + count: 31 + avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 + url: https://github.com/YuriiMotov +- login: Kludex + count: 24 + avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4 + url: https://github.com/Kludex +- login: sehraramiz + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/14166324?u=8fac65e84dfff24245d304a5b5b09f7b5bd69dc9&v=4 + url: https://github.com/sehraramiz +- login: estebanx64 + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 + url: https://github.com/estebanx64 +- login: yvallois + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/36999744?v=4 + url: https://github.com/yvallois +- login: yokwejuste + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/71908316?u=592c1e42aa0ee5cb94890e0b863e2acc78cc3bbc&v=4 + url: https://github.com/yokwejuste +- login: jgould22 + count: 4 avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 url: https://github.com/jgould22 -- login: Kludex +- login: alv2017 count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 - url: https://github.com/Kludex -- login: n8sty + avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 + url: https://github.com/alv2017 +- login: viniciusCalcantara count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 - url: https://github.com/n8sty -top_contributors: -- login: waynerv - count: 25 - avatarUrl: https://avatars.githubusercontent.com/u/39515546?u=ec35139777597cdbbbddda29bf8b9d4396b429a9&v=4 - url: https://github.com/waynerv -- login: tokusumi - count: 22 - avatarUrl: https://avatars.githubusercontent.com/u/41147016?u=55010621aece725aa702270b54fed829b6a1fe60&v=4 - url: https://github.com/tokusumi + avatarUrl: https://avatars.githubusercontent.com/u/108818737?u=3d7ffe5808843ee4372f9cc5a559ff1674cf1792&v=4 + url: https://github.com/viniciusCalcantara +- login: Trinkes + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/9466879?v=4 + url: https://github.com/Trinkes +- login: PREPONDERANCE + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/112809059?u=30ab12dc9ddba2f94ab90e6ad4ad8bc5cfa7fccd&v=4 + url: https://github.com/PREPONDERANCE +- login: nbx3 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/34649527?u=943812f69e0d40adbd3fa1c9b8ef50dd971a2a45&v=4 + url: https://github.com/nbx3 +- login: XiaoXinYo + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/56395004?u=b3b7cb758997f283c271a581833e407229dab82c&v=4 + url: https://github.com/XiaoXinYo +- login: JavierSanchezCastro + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro +- login: iloveitaly + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/150855?v=4 + url: https://github.com/iloveitaly +- login: LincolnPuzey + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/18750802?v=4 + url: https://github.com/LincolnPuzey +- login: Knighthawk-Leo + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/72437494?u=27c68db94a3107b605e603cc136f4ba83f0106d5&v=4 + url: https://github.com/Knighthawk-Leo +- login: gelezo43 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/40732698?u=611f39d3c1d2f4207a590937a78c1f10eed6232c&v=4 + url: https://github.com/gelezo43 +- login: AliYmn + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/18416653?u=98c1fca46c7e4dabe8c39d17b5e55d1511d41cf9&v=4 + url: https://github.com/AliYmn +- login: RichieB2B + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1461970?u=edaa57d1077705244ea5c9244f4783d94ff11f12&v=4 + url: https://github.com/RichieB2B +- login: Synrom + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/30272537?v=4 + url: https://github.com/Synrom +- login: iiotsrc + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/131771119?u=bcaf2559ef6266af70b151b7fda31a1ee3dbecb3&v=4 + url: https://github.com/iiotsrc +- login: Kfir-G + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/57500876?u=0cd29db046a17f12f382d398141319fca7ff230a&v=4 + url: https://github.com/Kfir-G +six_months_experts: +- login: YuriiMotov + count: 72 + avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 + url: https://github.com/YuriiMotov - login: Kludex - count: 21 - avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 + count: 40 + avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4 url: https://github.com/Kludex -- login: jaystone776 - count: 18 - avatarUrl: https://avatars.githubusercontent.com/u/11191137?u=299205a95e9b6817a43144a48b643346a5aac5cc&v=4 - url: https://github.com/jaystone776 -- login: dmontagu - count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 - url: https://github.com/dmontagu -- login: Xewus - count: 14 - avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4 - url: https://github.com/Xewus -- login: euri10 +- login: luzzodev + count: 37 + avatarUrl: https://avatars.githubusercontent.com/u/27291415?v=4 + url: https://github.com/luzzodev +- login: sinisaos + count: 37 + avatarUrl: https://avatars.githubusercontent.com/u/30960668?v=4 + url: https://github.com/sinisaos +- login: JavierSanchezCastro + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro +- login: Kfir-G count: 13 - avatarUrl: https://avatars.githubusercontent.com/u/1104190?u=321a2e953e6645a7d09b732786c7a8061e0f8a8b&v=4 - url: https://github.com/euri10 -- login: mariacamilagl + avatarUrl: https://avatars.githubusercontent.com/u/57500876?u=0cd29db046a17f12f382d398141319fca7ff230a&v=4 + url: https://github.com/Kfir-G +- login: tiangolo count: 12 - avatarUrl: https://avatars.githubusercontent.com/u/11489395?u=4adb6986bf3debfc2b8216ae701f2bd47d73da7d&v=4 - url: https://github.com/mariacamilagl -- login: Smlep + avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 + url: https://github.com/tiangolo +- login: sehraramiz count: 11 - avatarUrl: https://avatars.githubusercontent.com/u/16785985?v=4 - url: https://github.com/Smlep -- login: Serrones - count: 8 - avatarUrl: https://avatars.githubusercontent.com/u/22691749?u=4795b880e13ca33a73e52fc0ef7dc9c60c8fce47&v=4 - url: https://github.com/Serrones -- login: rjNemo - count: 8 - avatarUrl: https://avatars.githubusercontent.com/u/56785022?u=d5c3a02567c8649e146fcfc51b6060ccaf8adef8&v=4 - url: https://github.com/rjNemo -- login: RunningIkkyu - count: 7 - avatarUrl: https://avatars.githubusercontent.com/u/31848542?u=494ecc298e3f26197495bb357ad0f57cfd5f7a32&v=4 - url: https://github.com/RunningIkkyu -- login: hard-coders - count: 7 - avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4 - url: https://github.com/hard-coders -- login: Alexandrhub + avatarUrl: https://avatars.githubusercontent.com/u/14166324?u=8fac65e84dfff24245d304a5b5b09f7b5bd69dc9&v=4 + url: https://github.com/sehraramiz +- login: ceb10n + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/235213?u=edcce471814a1eba9f0cdaa4cd0de18921a940a6&v=4 + url: https://github.com/ceb10n +- login: estebanx64 count: 7 - avatarUrl: https://avatars.githubusercontent.com/u/119126536?u=9fc0d48f3307817bafecc5861eb2168401a6cb04&v=4 - url: https://github.com/Alexandrhub -- login: NinaHwang - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/79563565?u=eee6bfe9224c71193025ab7477f4f96ceaa05c62&v=4 - url: https://github.com/NinaHwang -- login: batlopes + avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 + url: https://github.com/estebanx64 +- login: yvallois count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/33462923?u=0fb3d7acb316764616f11e4947faf080e49ad8d9&v=4 - url: https://github.com/batlopes -- login: wshayes - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4 - url: https://github.com/wshayes -- login: samuelcolvin - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/4039449?u=42eb3b833047c8c4b4f647a031eaef148c16d93f&v=4 - url: https://github.com/samuelcolvin -- login: SwftAlpc - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/52768429?u=6a3aa15277406520ad37f6236e89466ed44bc5b8&v=4 - url: https://github.com/SwftAlpc -- login: Attsun1031 - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/1175560?v=4 - url: https://github.com/Attsun1031 -- login: ComicShrimp - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=f440bc9062afb3c43b9b9c6cdfdcfe31d58699ef&v=4 - url: https://github.com/ComicShrimp -- login: tamtam-fitness + avatarUrl: https://avatars.githubusercontent.com/u/36999744?v=4 + url: https://github.com/yvallois +- login: n8sty count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/62091034?u=8da19a6bd3d02f5d6ba30c7247d5b46c98dd1403&v=4 - url: https://github.com/tamtam-fitness -- login: jekirl - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/2546697?u=a027452387d85bd4a14834e19d716c99255fb3b7&v=4 - url: https://github.com/jekirl -- login: jfunez - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/805749?v=4 - url: https://github.com/jfunez -- login: ycd - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=bba5af018423a2858d49309bed2a899bb5c34ac5&v=4 - url: https://github.com/ycd -- login: komtaki - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/39375566?u=260ad6b1a4b34c07dbfa728da5e586f16f6d1824&v=4 - url: https://github.com/komtaki -- login: hitrust - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/3360631?u=5fa1f475ad784d64eb9666bdd43cc4d285dcc773&v=4 - url: https://github.com/hitrust -- login: JulianMaurin - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/63545168?u=b7d15ac865268cbefc2d739e2f23d9aeeac1a622&v=4 - url: https://github.com/JulianMaurin -- login: lsglucas - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/61513630?u=320e43fe4dc7bc6efc64e9b8f325f8075634fd20&v=4 - url: https://github.com/lsglucas -- login: adriangb - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4 - url: https://github.com/adriangb -- login: iudeen - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 - url: https://github.com/iudeen -- login: axel584 + avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 + url: https://github.com/n8sty +- login: TomFaulkner count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/1334088?u=9667041f5b15dc002b6f9665fda8c0412933ac04&v=4 - url: https://github.com/axel584 -- login: ivan-abc + avatarUrl: https://avatars.githubusercontent.com/u/14956620?v=4 + url: https://github.com/TomFaulkner +- login: yokwejuste count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/36765187?u=c6e0ba571c1ccb6db9d94e62e4b8b5eda811a870&v=4 - url: https://github.com/ivan-abc -- login: rostik1410 + avatarUrl: https://avatars.githubusercontent.com/u/71908316?u=592c1e42aa0ee5cb94890e0b863e2acc78cc3bbc&v=4 + url: https://github.com/yokwejuste +- login: jgould22 count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/11443899?u=e26a635c2ba220467b308a326a579b8ccf4a8701&v=4 - url: https://github.com/rostik1410 -top_reviewers: + avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 + url: https://github.com/jgould22 +- login: alv2017 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 + url: https://github.com/alv2017 +- login: viniciusCalcantara + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/108818737?u=3d7ffe5808843ee4372f9cc5a559ff1674cf1792&v=4 + url: https://github.com/viniciusCalcantara +- login: pawelad + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/7062874?u=d27dc220545a8401ad21840590a97d474d7101e6&v=4 + url: https://github.com/pawelad +- login: dbfreem + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/9778569?u=f2f1e9135b5e4f1b0c6821a548b17f97572720fc&v=4 + url: https://github.com/dbfreem +- login: Isuxiz + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/48672727?u=34d7b4ade252687d22a27cf53037b735b244bfc1&v=4 + url: https://github.com/Isuxiz +- login: bertomaniac + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/10235051?u=14484a96833228a7b29fee4a7916d411c242c4f6&v=4 + url: https://github.com/bertomaniac +- login: PhysicallyActive + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 + url: https://github.com/PhysicallyActive +- login: Minibrams + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/8108085?u=b028dbc308fa8485e0e2e9402b3d03d8deb22bf9&v=4 + url: https://github.com/Minibrams +- login: AIdjis + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/88404339?u=2a80d80b054e9228391e32fb9bb39571509dab6a&v=4 + url: https://github.com/AIdjis +- login: svlandeg + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/8796347?u=556c97650c27021911b0b9447ec55e75987b0e8a&v=4 + url: https://github.com/svlandeg +- login: Trinkes + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/9466879?v=4 + url: https://github.com/Trinkes +- login: PREPONDERANCE + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/112809059?u=30ab12dc9ddba2f94ab90e6ad4ad8bc5cfa7fccd&v=4 + url: https://github.com/PREPONDERANCE +- login: nbx3 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/34649527?u=943812f69e0d40adbd3fa1c9b8ef50dd971a2a45&v=4 + url: https://github.com/nbx3 +- login: yanggeorge + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/2434407?v=4 + url: https://github.com/yanggeorge +- login: XiaoXinYo + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/56395004?u=b3b7cb758997f283c271a581833e407229dab82c&v=4 + url: https://github.com/XiaoXinYo +- login: pythonweb2 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 + url: https://github.com/pythonweb2 +- login: slafs + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/210173?v=4 + url: https://github.com/slafs +- login: AmirHmZz + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/38752106?u=07f80e451bda00a9492bbc764e49d24ad3ada8cc&v=4 + url: https://github.com/AmirHmZz +- login: iloveitaly + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/150855?v=4 + url: https://github.com/iloveitaly +- login: LincolnPuzey + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/18750802?v=4 + url: https://github.com/LincolnPuzey +- login: alejsdev + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=356f39ff3f0211c720b06d3dbb060e98884085e3&v=4 + url: https://github.com/alejsdev +- login: Knighthawk-Leo + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/72437494?u=27c68db94a3107b605e603cc136f4ba83f0106d5&v=4 + url: https://github.com/Knighthawk-Leo +- login: gelezo43 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/40732698?u=611f39d3c1d2f4207a590937a78c1f10eed6232c&v=4 + url: https://github.com/gelezo43 +- login: christiansicari + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/29756552?v=4 + url: https://github.com/christiansicari +- login: 1001pepi + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/82064861?u=8c6ffdf2275d6970a07294752c545cd2702c57d3&v=4 + url: https://github.com/1001pepi +- login: AliYmn + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/18416653?u=98c1fca46c7e4dabe8c39d17b5e55d1511d41cf9&v=4 + url: https://github.com/AliYmn +- login: RichieB2B + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1461970?u=edaa57d1077705244ea5c9244f4783d94ff11f12&v=4 + url: https://github.com/RichieB2B +- login: Synrom + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/30272537?v=4 + url: https://github.com/Synrom +- login: ecly + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/8410422?v=4 + url: https://github.com/ecly +- login: iiotsrc + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/131771119?u=bcaf2559ef6266af70b151b7fda31a1ee3dbecb3&v=4 + url: https://github.com/iiotsrc +- login: simondale00 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/33907262?u=2721fb37014d50daf473267c808aa678ecaefe09&v=4 + url: https://github.com/simondale00 +- login: jd-solanki + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/47495003?u=6e225cb42c688d0cd70e65c6baedb9f5922b1178&v=4 + url: https://github.com/jd-solanki +- login: AumGupta + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/86357151?u=7d05aa606c0611a18f4db16cf26361ce10a6e195&v=4 + url: https://github.com/AumGupta +- login: DeoLeung + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/3764720?u=4c222ef513814de4c7fb3736d0a7adf11d953d43&v=4 + url: https://github.com/DeoLeung +- login: Reemyos + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/44867003?v=4 + url: https://github.com/Reemyos +- login: deight93 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/37678115?u=a608798b5bd0034183a9c430ebb42fb266db86ce&v=4 + url: https://github.com/deight93 +- login: Jkrox + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/83181939?u=d6a922d97129f7f3916d6a1c166bc011b3a72b7f&v=4 + url: https://github.com/Jkrox +- login: mmzeynalli + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/33568903?u=19efd0c0722730b83a70b7c86c36e5b7d83e07d2&v=4 + url: https://github.com/mmzeynalli +- login: ddahan + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1933516?u=1d200a620e8d6841df017e9f2bb7efb58b580f40&v=4 + url: https://github.com/ddahan +- login: jfeaver + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1091338?u=0bcba366447d8fadad63f6705a52d128da4c7ec2&v=4 + url: https://github.com/jfeaver +- login: Wurstnase + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/8709415?u=f479af475a97aee9a1dab302cfc35d07e9ea245f&v=4 + url: https://github.com/Wurstnase +- login: tristan + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1412?u=aab8aaa4cc0f1210ac45fc93873a5909d314c965&v=4 + url: https://github.com/tristan +- login: chandanch + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/8663552?u=afc484bc0a952c83f1fb6a1583cda443f807cd66&v=4 + url: https://github.com/chandanch +- login: rvishruth + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/79176273?v=4 + url: https://github.com/rvishruth +- login: mattmess1221 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/3409962?u=723662989f2027755e67d200137c13c53ae154ac&v=4 + url: https://github.com/mattmess1221 +one_year_experts: +- login: YuriiMotov + count: 223 + avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 + url: https://github.com/YuriiMotov - login: Kludex - count: 145 - avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 + count: 81 + avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4 url: https://github.com/Kludex -- login: BilalAlpaslan - count: 86 - avatarUrl: https://avatars.githubusercontent.com/u/47563997?u=63ed66e304fe8d765762c70587d61d9196e5c82d&v=4 - url: https://github.com/BilalAlpaslan -- login: yezz123 - count: 82 - avatarUrl: https://avatars.githubusercontent.com/u/52716203?u=d7062cbc6eb7671d5dc9cc0e32a24ae335e0f225&v=4 - url: https://github.com/yezz123 -- login: iudeen - count: 55 - avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 - url: https://github.com/iudeen -- login: tokusumi - count: 51 - avatarUrl: https://avatars.githubusercontent.com/u/41147016?u=55010621aece725aa702270b54fed829b6a1fe60&v=4 - url: https://github.com/tokusumi -- login: Xewus - count: 50 - avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4 - url: https://github.com/Xewus -- login: waynerv - count: 47 - avatarUrl: https://avatars.githubusercontent.com/u/39515546?u=ec35139777597cdbbbddda29bf8b9d4396b429a9&v=4 - url: https://github.com/waynerv -- login: Laineyzhang55 +- login: JavierSanchezCastro count: 47 - avatarUrl: https://avatars.githubusercontent.com/u/59285379?v=4 - url: https://github.com/Laineyzhang55 -- login: ycd - count: 45 - avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=bba5af018423a2858d49309bed2a899bb5c34ac5&v=4 - url: https://github.com/ycd -- login: cikay - count: 41 - avatarUrl: https://avatars.githubusercontent.com/u/24587499?u=e772190a051ab0eaa9c8542fcff1892471638f2b&v=4 - url: https://github.com/cikay -- login: JarroVGIT - count: 34 - avatarUrl: https://avatars.githubusercontent.com/u/13659033?u=e8bea32d07a5ef72f7dde3b2079ceb714923ca05&v=4 - url: https://github.com/JarroVGIT -- login: AdrianDeAnda - count: 33 - avatarUrl: https://avatars.githubusercontent.com/u/1024932?u=b2ea249c6b41ddf98679c8d110d0f67d4a3ebf93&v=4 - url: https://github.com/AdrianDeAnda -- login: ArcLightSlavik - count: 31 - avatarUrl: https://avatars.githubusercontent.com/u/31127044?u=b0f2c37142f4b762e41ad65dc49581813422bd71&v=4 - url: https://github.com/ArcLightSlavik -- login: cassiobotaro - count: 28 - avatarUrl: https://avatars.githubusercontent.com/u/3127847?u=b0a652331da17efeb85cd6e3a4969182e5004804&v=4 - url: https://github.com/cassiobotaro -- login: lsglucas - count: 27 - avatarUrl: https://avatars.githubusercontent.com/u/61513630?u=320e43fe4dc7bc6efc64e9b8f325f8075634fd20&v=4 - url: https://github.com/lsglucas -- login: komtaki - count: 27 - avatarUrl: https://avatars.githubusercontent.com/u/39375566?u=260ad6b1a4b34c07dbfa728da5e586f16f6d1824&v=4 - url: https://github.com/komtaki -- login: Ryandaydev - count: 25 - avatarUrl: https://avatars.githubusercontent.com/u/4292423?u=48f68868db8886fce31a1d802c1003914c6cd7c6&v=4 - url: https://github.com/Ryandaydev -- login: LorhanSohaky + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro +- login: jgould22 + count: 42 + avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 + url: https://github.com/jgould22 +- login: sinisaos + count: 39 + avatarUrl: https://avatars.githubusercontent.com/u/30960668?v=4 + url: https://github.com/sinisaos +- login: luzzodev + count: 37 + avatarUrl: https://avatars.githubusercontent.com/u/27291415?v=4 + url: https://github.com/luzzodev +- login: tiangolo count: 24 - avatarUrl: https://avatars.githubusercontent.com/u/16273730?u=095b66f243a2cd6a0aadba9a095009f8aaf18393&v=4 - url: https://github.com/LorhanSohaky -- login: dmontagu + avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 + url: https://github.com/tiangolo +- login: n8sty count: 23 - avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 - url: https://github.com/dmontagu -- login: rjNemo - count: 21 - avatarUrl: https://avatars.githubusercontent.com/u/56785022?u=d5c3a02567c8649e146fcfc51b6060ccaf8adef8&v=4 - url: https://github.com/rjNemo -- login: hard-coders - count: 21 - avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4 - url: https://github.com/hard-coders -- login: odiseo0 - count: 20 - avatarUrl: https://avatars.githubusercontent.com/u/87550035?u=241a71f6b7068738b81af3e57f45ffd723538401&v=4 - url: https://github.com/odiseo0 -- login: 0417taehyun + avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 + url: https://github.com/n8sty +- login: estebanx64 count: 19 - avatarUrl: https://avatars.githubusercontent.com/u/63915557?u=47debaa860fd52c9b98c97ef357ddcec3b3fb399&v=4 - url: https://github.com/0417taehyun -- login: Smlep - count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/16785985?v=4 - url: https://github.com/Smlep -- login: zy7y - count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/67154681?u=5d634834cc514028ea3f9115f7030b99a1f4d5a4&v=4 - url: https://github.com/zy7y -- login: peidrao - count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/32584628?u=a66902b40c13647d0ed0e573d598128240a4dd04&v=4 - url: https://github.com/peidrao -- login: yanever - count: 16 - avatarUrl: https://avatars.githubusercontent.com/u/21978760?v=4 - url: https://github.com/yanever -- login: SwftAlpc - count: 16 - avatarUrl: https://avatars.githubusercontent.com/u/52768429?u=6a3aa15277406520ad37f6236e89466ed44bc5b8&v=4 - url: https://github.com/SwftAlpc -- login: nilslindemann - count: 16 - avatarUrl: https://avatars.githubusercontent.com/u/6892179?u=1dca6a22195d6cd1ab20737c0e19a4c55d639472&v=4 - url: https://github.com/nilslindemann -- login: axel584 - count: 16 - avatarUrl: https://avatars.githubusercontent.com/u/1334088?u=9667041f5b15dc002b6f9665fda8c0412933ac04&v=4 - url: https://github.com/axel584 -- login: Alexandrhub - count: 16 - avatarUrl: https://avatars.githubusercontent.com/u/119126536?u=9fc0d48f3307817bafecc5861eb2168401a6cb04&v=4 - url: https://github.com/Alexandrhub -- login: DevDae - count: 16 - avatarUrl: https://avatars.githubusercontent.com/u/87962045?u=08e10fa516e844934f4b3fc7c38b33c61697e4a1&v=4 - url: https://github.com/DevDae -- login: hasansezertasan - count: 16 - avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 - url: https://github.com/hasansezertasan -- login: pedabraham + avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 + url: https://github.com/estebanx64 +- login: ceb10n count: 15 - avatarUrl: https://avatars.githubusercontent.com/u/16860088?u=abf922a7b920bf8fdb7867d8b43e091f1e796178&v=4 - url: https://github.com/pedabraham -- login: delhi09 + avatarUrl: https://avatars.githubusercontent.com/u/235213?u=edcce471814a1eba9f0cdaa4cd0de18921a940a6&v=4 + url: https://github.com/ceb10n +- login: sehraramiz count: 15 - avatarUrl: https://avatars.githubusercontent.com/u/63476957?u=6c86e59b48e0394d4db230f37fc9ad4d7e2c27c7&v=4 - url: https://github.com/delhi09 -- login: sh0nk - count: 13 - avatarUrl: https://avatars.githubusercontent.com/u/6478810?u=af15d724875cec682ed8088a86d36b2798f981c0&v=4 - url: https://github.com/sh0nk -- login: wdh99 - count: 13 - avatarUrl: https://avatars.githubusercontent.com/u/108172295?u=8a8fb95d5afe3e0fa33257b2aecae88d436249eb&v=4 - url: https://github.com/wdh99 -- login: r0b2g1t + avatarUrl: https://avatars.githubusercontent.com/u/14166324?u=8fac65e84dfff24245d304a5b5b09f7b5bd69dc9&v=4 + url: https://github.com/sehraramiz +- login: PhysicallyActive + count: 14 + avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 + url: https://github.com/PhysicallyActive +- login: Kfir-G count: 13 - avatarUrl: https://avatars.githubusercontent.com/u/5357541?u=6428442d875d5d71aaa1bb38bb11c4be1a526bc2&v=4 - url: https://github.com/r0b2g1t -- login: RunningIkkyu - count: 12 - avatarUrl: https://avatars.githubusercontent.com/u/31848542?u=494ecc298e3f26197495bb357ad0f57cfd5f7a32&v=4 - url: https://github.com/RunningIkkyu -- login: ivan-abc - count: 12 - avatarUrl: https://avatars.githubusercontent.com/u/36765187?u=c6e0ba571c1ccb6db9d94e62e4b8b5eda811a870&v=4 - url: https://github.com/ivan-abc -- login: solomein-sv + avatarUrl: https://avatars.githubusercontent.com/u/57500876?u=0cd29db046a17f12f382d398141319fca7ff230a&v=4 + url: https://github.com/Kfir-G +- login: mattmess1221 count: 11 - avatarUrl: https://avatars.githubusercontent.com/u/46193920?u=789927ee09cfabd752d3bd554fa6baf4850d2777&v=4 - url: https://github.com/solomein-sv -- login: mariacamilagl - count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/11489395?u=4adb6986bf3debfc2b8216ae701f2bd47d73da7d&v=4 - url: https://github.com/mariacamilagl -- login: raphaelauv - count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/10202690?u=e6f86f5c0c3026a15d6b51792fa3e532b12f1371&v=4 - url: https://github.com/raphaelauv -- login: Attsun1031 - count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/1175560?v=4 - url: https://github.com/Attsun1031 -- login: maoyibo - count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/7887703?v=4 - url: https://github.com/maoyibo -- login: ComicShrimp + avatarUrl: https://avatars.githubusercontent.com/u/3409962?u=723662989f2027755e67d200137c13c53ae154ac&v=4 + url: https://github.com/mattmess1221 +- login: hasansezertasan count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=f440bc9062afb3c43b9b9c6cdfdcfe31d58699ef&v=4 - url: https://github.com/ComicShrimp -- login: romashevchenko - count: 9 - avatarUrl: https://avatars.githubusercontent.com/u/132477732?v=4 - url: https://github.com/romashevchenko -- login: izaguerreiro - count: 9 - avatarUrl: https://avatars.githubusercontent.com/u/2241504?v=4 - url: https://github.com/izaguerreiro -- login: graingert - count: 9 - avatarUrl: https://avatars.githubusercontent.com/u/413772?u=64b77b6aa405c68a9c6bcf45f84257c66eea5f32&v=4 - url: https://github.com/graingert + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan +- login: AIdjis + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/88404339?u=2a80d80b054e9228391e32fb9bb39571509dab6a&v=4 + url: https://github.com/AIdjis +- login: yvallois + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/36999744?v=4 + url: https://github.com/yvallois +- login: PREPONDERANCE + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/112809059?u=30ab12dc9ddba2f94ab90e6ad4ad8bc5cfa7fccd&v=4 + url: https://github.com/PREPONDERANCE +- login: pythonweb2 + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 + url: https://github.com/pythonweb2 +- login: acidjunk + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 + url: https://github.com/acidjunk +- login: gustavosett + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/99373133?u=1739ca547c3d200f1b72450520bce46a97aab184&v=4 + url: https://github.com/gustavosett +- login: binbjz + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/8213913?u=22b68b7a0d5bf5e09c02084c0f5f53d7503114cd&v=4 + url: https://github.com/binbjz +- login: chyok + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/32629225?u=3b7c30e8a09426a1b9284f6e8a0ae53a525596bf&v=4 + url: https://github.com/chyok +- login: TomFaulkner + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/14956620?v=4 + url: https://github.com/TomFaulkner +- login: yokwejuste + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/71908316?u=592c1e42aa0ee5cb94890e0b863e2acc78cc3bbc&v=4 + url: https://github.com/yokwejuste +- login: DeoLeung + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/3764720?u=4c222ef513814de4c7fb3736d0a7adf11d953d43&v=4 + url: https://github.com/DeoLeung +- login: flo-at + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/564288?v=4 + url: https://github.com/flo-at +- login: GodMoonGoodman + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/29688727?u=7b251da620d999644c37c1feeb292d033eed7ad6&v=4 + url: https://github.com/GodMoonGoodman +- login: bertomaniac + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/10235051?u=14484a96833228a7b29fee4a7916d411c242c4f6&v=4 + url: https://github.com/bertomaniac +- login: alv2017 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 + url: https://github.com/alv2017 +- login: msehnout + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/9369632?u=8c988f1b008a3f601385a3616f9327820f66e3a5&v=4 + url: https://github.com/msehnout +- login: viniciusCalcantara + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/108818737?u=3d7ffe5808843ee4372f9cc5a559ff1674cf1792&v=4 + url: https://github.com/viniciusCalcantara +- login: pawelad + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/7062874?u=d27dc220545a8401ad21840590a97d474d7101e6&v=4 + url: https://github.com/pawelad +- login: ThirVondukr + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/50728601?u=167c0bd655e52817082e50979a86d2f98f95b1a3&v=4 + url: https://github.com/ThirVondukr +- login: dbfreem + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/9778569?u=f2f1e9135b5e4f1b0c6821a548b17f97572720fc&v=4 + url: https://github.com/dbfreem +- login: Isuxiz + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/48672727?u=34d7b4ade252687d22a27cf53037b735b244bfc1&v=4 + url: https://github.com/Isuxiz +- login: angely-dev + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/4362224?v=4 + url: https://github.com/angely-dev +- login: deight93 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/37678115?u=a608798b5bd0034183a9c430ebb42fb266db86ce&v=4 + url: https://github.com/deight93 +- login: mmzeynalli + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/33568903?u=19efd0c0722730b83a70b7c86c36e5b7d83e07d2&v=4 + url: https://github.com/mmzeynalli +- login: Minibrams + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/8108085?u=b028dbc308fa8485e0e2e9402b3d03d8deb22bf9&v=4 + url: https://github.com/Minibrams +- login: ryanisn + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/53449841?v=4 + url: https://github.com/ryanisn +- login: svlandeg + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/8796347?u=556c97650c27021911b0b9447ec55e75987b0e8a&v=4 + url: https://github.com/svlandeg +- login: alexandercronin + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/8014288?u=69580504c51a0cdd756fc47b23bb7f404bd694e7&v=4 + url: https://github.com/alexandercronin +- login: aanchlia + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 + url: https://github.com/aanchlia +- login: chrisK824 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 + url: https://github.com/chrisK824 +- login: omarcruzpantoja + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/15116058?u=4b64c643fad49225d854e1aaecd1ffc6f9071a1b&v=4 + url: https://github.com/omarcruzpantoja +- login: ahmedabdou14 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=d87b866e7c1db970d6f8e8031643818349b046d5&v=4 + url: https://github.com/ahmedabdou14 +- login: Trinkes + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/9466879?v=4 + url: https://github.com/Trinkes +- login: Leon0824 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1922026?v=4 + url: https://github.com/Leon0824 +- login: CarlosOliveira-23 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/102637302?u=cf350a4db956f30cbb2c27d3be0d15c282e32b14&v=4 + url: https://github.com/CarlosOliveira-23 +- login: nbx3 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/34649527?u=943812f69e0d40adbd3fa1c9b8ef50dd971a2a45&v=4 + url: https://github.com/nbx3 +- login: yanggeorge + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/2434407?v=4 + url: https://github.com/yanggeorge +- login: XiaoXinYo + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/56395004?u=b3b7cb758997f283c271a581833e407229dab82c&v=4 + url: https://github.com/XiaoXinYo +- login: anantgupta129 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/66518357?u=6e25dcd84638f17d2c6df5dc26f07fd7c6dc118e&v=4 + url: https://github.com/anantgupta129 +- login: slafs + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/210173?v=4 + url: https://github.com/slafs +- login: monchin + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/18521800?v=4 + url: https://github.com/monchin +- login: AmirHmZz + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/38752106?u=07f80e451bda00a9492bbc764e49d24ad3ada8cc&v=4 + url: https://github.com/AmirHmZz +- login: iloveitaly + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/150855?v=4 + url: https://github.com/iloveitaly +- login: msukmanowsky + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/362755?u=782e6bf5b9f0356c3f74b4d894fda9f179252086&v=4 + url: https://github.com/msukmanowsky +- login: shurshilov + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/11828278?u=6bcadc5ce4f2f56a514331c9f68eb987d4afe29a&v=4 + url: https://github.com/shurshilov diff --git a/docs/en/data/skip_users.yml b/docs/en/data/skip_users.yml new file mode 100644 index 000000000..cf24003af --- /dev/null +++ b/docs/en/data/skip_users.yml @@ -0,0 +1,5 @@ +- tiangolo +- codecov +- github-actions +- pre-commit-ci +- dependabot diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index 121a3b761..b994e533a 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -1,7 +1,7 @@ gold: - - url: https://cryptapi.io/ - title: "CryptAPI: Your easy to use, secure and privacy oriented payment gateway." - img: https://fastapi.tiangolo.com/img/sponsors/cryptapi.svg + - url: https://blockbee.io?ref=fastapi + title: BlockBee Cryptocurrency Payment Gateway + img: https://fastapi.tiangolo.com/img/sponsors/blockbee.png - url: https://platform.sh/try-it-now/?utm_source=fastapi-signup&utm_medium=banner&utm_campaign=FastAPI-signup-June-2023 title: "Build, run and scale your apps on a modern, reliable, and secure PaaS." img: https://fastapi.tiangolo.com/img/sponsors/platform-sh.png @@ -11,47 +11,56 @@ gold: - url: https://bump.sh/fastapi?utm_source=fastapi&utm_medium=referral&utm_campaign=sponsor title: Automate FastAPI documentation generation with Bump.sh img: https://fastapi.tiangolo.com/img/sponsors/bump-sh.svg - - url: https://reflex.dev - title: Reflex - img: https://fastapi.tiangolo.com/img/sponsors/reflex.png - url: https://github.com/scalar/scalar/?utm_source=fastapi&utm_medium=website&utm_campaign=main-badge title: "Scalar: Beautiful Open-Source API References from Swagger/OpenAPI files" img: https://fastapi.tiangolo.com/img/sponsors/scalar.svg - url: https://www.propelauth.com/?utm_source=fastapi&utm_campaign=1223&utm_medium=mainbadge title: Auth, user management and more for your B2B product img: https://fastapi.tiangolo.com/img/sponsors/propelauth.png + - url: https://www.withcoherence.com/?utm_medium=advertising&utm_source=fastapi&utm_campaign=website + title: Coherence + img: https://fastapi.tiangolo.com/img/sponsors/coherence.png + - url: https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi/?utm_campaign=fastapi_framework&utm_source=fastapi_sponsorship&utm_medium=web_referral + title: Simplify Full Stack Development with FastAPI & MongoDB + img: https://fastapi.tiangolo.com/img/sponsors/mongodb.png + - url: https://zuplo.link/fastapi-gh + title: 'Zuplo: Scale, Protect, Document, and Monetize your FastAPI' + img: https://fastapi.tiangolo.com/img/sponsors/zuplo.png + - url: https://liblab.com?utm_source=fastapi + title: liblab - Generate SDKs from FastAPI + img: https://fastapi.tiangolo.com/img/sponsors/liblab.png + - url: https://docs.render.com/deploy-fastapi?utm_source=deploydoc&utm_medium=referral&utm_campaign=fastapi + title: Deploy & scale any full-stack web app on Render. Focus on building apps, not infra. + img: https://fastapi.tiangolo.com/img/sponsors/render.svg + - url: https://www.coderabbit.ai/?utm_source=fastapi&utm_medium=badge&utm_campaign=fastapi + title: Cut Code Review Time & Bugs in Half with CodeRabbit + img: https://fastapi.tiangolo.com/img/sponsors/coderabbit.png silver: - - url: https://www.deta.sh/?ref=fastapi - title: The launchpad for all your (team's) ideas - img: https://fastapi.tiangolo.com/img/sponsors/deta.svg - - url: https://training.talkpython.fm/fastapi-courses - title: FastAPI video courses on demand from people you trust - img: https://fastapi.tiangolo.com/img/sponsors/talkpython.png - - url: https://testdriven.io/courses/tdd-fastapi/ - title: Learn to build high-quality web apps with best practices - img: https://fastapi.tiangolo.com/img/sponsors/testdriven.svg - url: https://github.com/deepset-ai/haystack/ title: Build powerful search from composable, open source building blocks img: https://fastapi.tiangolo.com/img/sponsors/haystack-fastapi.svg - - url: https://careers.powens.com/ - title: Powens is hiring! - img: https://fastapi.tiangolo.com/img/sponsors/powens.png - url: https://databento.com/ title: Pay as you go for market data img: https://fastapi.tiangolo.com/img/sponsors/databento.svg - - url: https://speakeasyapi.dev?utm_source=fastapi+repo&utm_medium=github+sponsorship + - url: https://speakeasy.com?utm_source=fastapi+repo&utm_medium=github+sponsorship title: SDKs for your API | Speakeasy img: https://fastapi.tiangolo.com/img/sponsors/speakeasy.png - url: https://www.svix.com/ title: Svix - Webhooks as a service img: https://fastapi.tiangolo.com/img/sponsors/svix.svg - - url: https://www.codacy.com/?utm_source=github&utm_medium=sponsors&utm_id=pioneers - title: Take code reviews from hours to minutes - img: https://fastapi.tiangolo.com/img/sponsors/codacy.png + - url: https://www.stainlessapi.com/?utm_source=fastapi&utm_medium=referral + title: Stainless | Generate best-in-class SDKs + img: https://fastapi.tiangolo.com/img/sponsors/stainless.png + - url: https://www.permit.io/blog/implement-authorization-in-fastapi?utm_source=github&utm_medium=referral&utm_campaign=fastapi + title: Fine-Grained Authorization for FastAPI + img: https://fastapi.tiangolo.com/img/sponsors/permit.png bronze: - url: https://www.exoflare.com/open-source/?utm_source=FastAPI&utm_campaign=open_source title: Biosecurity risk assessments made easy. img: https://fastapi.tiangolo.com/img/sponsors/exoflare.png - - url: https://bit.ly/3JJ7y5C - title: Build cross-modal and multimodal applications on the cloud - img: https://fastapi.tiangolo.com/img/sponsors/jina2.svg + - url: https://testdriven.io/courses/tdd-fastapi/ + title: Learn to build high-quality web apps with best practices + img: https://fastapi.tiangolo.com/img/sponsors/testdriven.svg + - url: https://lambdatest.com/?utm_source=fastapi&utm_medium=partner&utm_campaign=sponsor&utm_term=opensource&utm_content=webpage + title: LambdaTest, AI-Powered Cloud-based Test Orchestration Platform + img: https://fastapi.tiangolo.com/img/sponsors/lambdatest.png diff --git a/docs/en/data/sponsors_badge.yml b/docs/en/data/sponsors_badge.yml index 4078454a8..d507a500f 100644 --- a/docs/en/data/sponsors_badge.yml +++ b/docs/en/data/sponsors_badge.yml @@ -23,3 +23,18 @@ logins: - svixhq - Alek99 - codacy + - zanfaruqui + - scalar + - bump-sh + - andrew-propelauth + - svix + - zuplo-oss + - zuplo + - Kong + - speakeasy-api + - jess-render + - blockbee-io + - liblaber + - render-sponsorships + - renderinc + - stainless-api diff --git a/docs/en/data/topic_repos.yml b/docs/en/data/topic_repos.yml new file mode 100644 index 000000000..633b0aee3 --- /dev/null +++ b/docs/en/data/topic_repos.yml @@ -0,0 +1,495 @@ +- name: full-stack-fastapi-template + html_url: https://github.com/fastapi/full-stack-fastapi-template + stars: 30645 + owner_login: fastapi + owner_html_url: https://github.com/fastapi +- name: Hello-Python + html_url: https://github.com/mouredev/Hello-Python + stars: 28690 + owner_login: mouredev + owner_html_url: https://github.com/mouredev +- name: serve + html_url: https://github.com/jina-ai/serve + stars: 21356 + owner_login: jina-ai + owner_html_url: https://github.com/jina-ai +- name: sqlmodel + html_url: https://github.com/fastapi/sqlmodel + stars: 15312 + owner_login: fastapi + owner_html_url: https://github.com/fastapi +- name: HivisionIDPhotos + html_url: https://github.com/Zeyi-Lin/HivisionIDPhotos + stars: 14957 + owner_login: Zeyi-Lin + owner_html_url: https://github.com/Zeyi-Lin +- name: Douyin_TikTok_Download_API + html_url: https://github.com/Evil0ctal/Douyin_TikTok_Download_API + stars: 11192 + owner_login: Evil0ctal + owner_html_url: https://github.com/Evil0ctal +- name: fastapi-best-practices + html_url: https://github.com/zhanymkanov/fastapi-best-practices + stars: 10501 + owner_login: zhanymkanov + owner_html_url: https://github.com/zhanymkanov +- name: awesome-fastapi + html_url: https://github.com/mjhea0/awesome-fastapi + stars: 9193 + owner_login: mjhea0 + owner_html_url: https://github.com/mjhea0 +- name: FastUI + html_url: https://github.com/pydantic/FastUI + stars: 8721 + owner_login: pydantic + owner_html_url: https://github.com/pydantic +- name: nonebot2 + html_url: https://github.com/nonebot/nonebot2 + stars: 6433 + owner_login: nonebot + owner_html_url: https://github.com/nonebot +- name: serge + html_url: https://github.com/serge-chat/serge + stars: 5699 + owner_login: serge-chat + owner_html_url: https://github.com/serge-chat +- name: FileCodeBox + html_url: https://github.com/vastsa/FileCodeBox + stars: 5534 + owner_login: vastsa + owner_html_url: https://github.com/vastsa +- name: fastapi-users + html_url: https://github.com/fastapi-users/fastapi-users + stars: 4921 + owner_login: fastapi-users + owner_html_url: https://github.com/fastapi-users +- name: polar + html_url: https://github.com/polarsource/polar + stars: 4598 + owner_login: polarsource + owner_html_url: https://github.com/polarsource +- name: hatchet + html_url: https://github.com/hatchet-dev/hatchet + stars: 4585 + owner_login: hatchet-dev + owner_html_url: https://github.com/hatchet-dev +- name: chatgpt-web-share + html_url: https://github.com/chatpire/chatgpt-web-share + stars: 4318 + owner_login: chatpire + owner_html_url: https://github.com/chatpire +- name: strawberry + html_url: https://github.com/strawberry-graphql/strawberry + stars: 4180 + owner_login: strawberry-graphql + owner_html_url: https://github.com/strawberry-graphql +- name: atrilabs-engine + html_url: https://github.com/Atri-Labs/atrilabs-engine + stars: 4114 + owner_login: Atri-Labs + owner_html_url: https://github.com/Atri-Labs +- name: dynaconf + html_url: https://github.com/dynaconf/dynaconf + stars: 3904 + owner_login: dynaconf + owner_html_url: https://github.com/dynaconf +- name: poem + html_url: https://github.com/poem-web/poem + stars: 3781 + owner_login: poem-web + owner_html_url: https://github.com/poem-web +- name: farfalle + html_url: https://github.com/rashadphz/farfalle + stars: 3190 + owner_login: rashadphz + owner_html_url: https://github.com/rashadphz +- name: opyrator + html_url: https://github.com/ml-tooling/opyrator + stars: 3119 + owner_login: ml-tooling + owner_html_url: https://github.com/ml-tooling +- name: fastapi-admin + html_url: https://github.com/fastapi-admin/fastapi-admin + stars: 3086 + owner_login: fastapi-admin + owner_html_url: https://github.com/fastapi-admin +- name: docarray + html_url: https://github.com/docarray/docarray + stars: 3021 + owner_login: docarray + owner_html_url: https://github.com/docarray +- name: datamodel-code-generator + html_url: https://github.com/koxudaxi/datamodel-code-generator + stars: 2988 + owner_login: koxudaxi + owner_html_url: https://github.com/koxudaxi +- name: LitServe + html_url: https://github.com/Lightning-AI/LitServe + stars: 2863 + owner_login: Lightning-AI + owner_html_url: https://github.com/Lightning-AI +- name: fastapi-realworld-example-app + html_url: https://github.com/nsidnev/fastapi-realworld-example-app + stars: 2850 + owner_login: nsidnev + owner_html_url: https://github.com/nsidnev +- name: logfire + html_url: https://github.com/pydantic/logfire + stars: 2757 + owner_login: pydantic + owner_html_url: https://github.com/pydantic +- name: uvicorn-gunicorn-fastapi-docker + html_url: https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker + stars: 2731 + owner_login: tiangolo + owner_html_url: https://github.com/tiangolo +- name: huma + html_url: https://github.com/danielgtaylor/huma + stars: 2700 + owner_login: danielgtaylor + owner_html_url: https://github.com/danielgtaylor +- name: tracecat + html_url: https://github.com/TracecatHQ/tracecat + stars: 2539 + owner_login: TracecatHQ + owner_html_url: https://github.com/TracecatHQ +- name: best-of-web-python + html_url: https://github.com/ml-tooling/best-of-web-python + stars: 2460 + owner_login: ml-tooling + owner_html_url: https://github.com/ml-tooling +- name: RasaGPT + html_url: https://github.com/paulpierre/RasaGPT + stars: 2401 + owner_login: paulpierre + owner_html_url: https://github.com/paulpierre +- name: fastapi-react + html_url: https://github.com/Buuntu/fastapi-react + stars: 2315 + owner_login: Buuntu + owner_html_url: https://github.com/Buuntu +- name: nextpy + html_url: https://github.com/dot-agent/nextpy + stars: 2266 + owner_login: dot-agent + owner_html_url: https://github.com/dot-agent +- name: 30-Days-of-Python + html_url: https://github.com/codingforentrepreneurs/30-Days-of-Python + stars: 2163 + owner_login: codingforentrepreneurs + owner_html_url: https://github.com/codingforentrepreneurs +- name: FastAPI-template + html_url: https://github.com/s3rius/FastAPI-template + stars: 2156 + owner_login: s3rius + owner_html_url: https://github.com/s3rius +- name: sqladmin + html_url: https://github.com/aminalaee/sqladmin + stars: 2051 + owner_login: aminalaee + owner_html_url: https://github.com/aminalaee +- name: langserve + html_url: https://github.com/langchain-ai/langserve + stars: 2025 + owner_login: langchain-ai + owner_html_url: https://github.com/langchain-ai +- name: fastapi-utils + html_url: https://github.com/fastapiutils/fastapi-utils + stars: 2021 + owner_login: fastapiutils + owner_html_url: https://github.com/fastapiutils +- name: solara + html_url: https://github.com/widgetti/solara + stars: 1980 + owner_login: widgetti + owner_html_url: https://github.com/widgetti +- name: supabase-py + html_url: https://github.com/supabase/supabase-py + stars: 1874 + owner_login: supabase + owner_html_url: https://github.com/supabase +- name: python-week-2022 + html_url: https://github.com/rochacbruno/python-week-2022 + stars: 1829 + owner_login: rochacbruno + owner_html_url: https://github.com/rochacbruno +- name: mangum + html_url: https://github.com/Kludex/mangum + stars: 1820 + owner_login: Kludex + owner_html_url: https://github.com/Kludex +- name: Kokoro-FastAPI + html_url: https://github.com/remsky/Kokoro-FastAPI + stars: 1771 + owner_login: remsky + owner_html_url: https://github.com/remsky +- name: manage-fastapi + html_url: https://github.com/ycd/manage-fastapi + stars: 1719 + owner_login: ycd + owner_html_url: https://github.com/ycd +- name: ormar + html_url: https://github.com/collerek/ormar + stars: 1710 + owner_login: collerek + owner_html_url: https://github.com/collerek +- name: agentkit + html_url: https://github.com/BCG-X-Official/agentkit + stars: 1658 + owner_login: BCG-X-Official + owner_html_url: https://github.com/BCG-X-Official +- name: langchain-serve + html_url: https://github.com/jina-ai/langchain-serve + stars: 1618 + owner_login: jina-ai + owner_html_url: https://github.com/jina-ai +- name: termpair + html_url: https://github.com/cs01/termpair + stars: 1611 + owner_login: cs01 + owner_html_url: https://github.com/cs01 +- name: coronavirus-tracker-api + html_url: https://github.com/ExpDev07/coronavirus-tracker-api + stars: 1588 + owner_login: ExpDev07 + owner_html_url: https://github.com/ExpDev07 +- name: piccolo + html_url: https://github.com/piccolo-orm/piccolo + stars: 1546 + owner_login: piccolo-orm + owner_html_url: https://github.com/piccolo-orm +- name: fastapi-cache + html_url: https://github.com/long2ice/fastapi-cache + stars: 1478 + owner_login: long2ice + owner_html_url: https://github.com/long2ice +- name: openapi-python-client + html_url: https://github.com/openapi-generators/openapi-python-client + stars: 1467 + owner_login: openapi-generators + owner_html_url: https://github.com/openapi-generators +- name: fastapi-crudrouter + html_url: https://github.com/awtkns/fastapi-crudrouter + stars: 1462 + owner_login: awtkns + owner_html_url: https://github.com/awtkns +- name: awesome-fastapi-projects + html_url: https://github.com/Kludex/awesome-fastapi-projects + stars: 1418 + owner_login: Kludex + owner_html_url: https://github.com/Kludex +- name: awesome-python-resources + html_url: https://github.com/DjangoEx/awesome-python-resources + stars: 1383 + owner_login: DjangoEx + owner_html_url: https://github.com/DjangoEx +- name: slowapi + html_url: https://github.com/laurentS/slowapi + stars: 1363 + owner_login: laurentS + owner_html_url: https://github.com/laurentS +- name: budgetml + html_url: https://github.com/ebhy/budgetml + stars: 1344 + owner_login: ebhy + owner_html_url: https://github.com/ebhy +- name: fastapi-pagination + html_url: https://github.com/uriyyo/fastapi-pagination + stars: 1284 + owner_login: uriyyo + owner_html_url: https://github.com/uriyyo +- name: fastapi-boilerplate + html_url: https://github.com/teamhide/fastapi-boilerplate + stars: 1234 + owner_login: teamhide + owner_html_url: https://github.com/teamhide +- name: fastapi-tutorial + html_url: https://github.com/liaogx/fastapi-tutorial + stars: 1181 + owner_login: liaogx + owner_html_url: https://github.com/liaogx +- name: fastapi-amis-admin + html_url: https://github.com/amisadmin/fastapi-amis-admin + stars: 1164 + owner_login: amisadmin + owner_html_url: https://github.com/amisadmin +- name: fastapi-code-generator + html_url: https://github.com/koxudaxi/fastapi-code-generator + stars: 1132 + owner_login: koxudaxi + owner_html_url: https://github.com/koxudaxi +- name: bolt-python + html_url: https://github.com/slackapi/bolt-python + stars: 1130 + owner_login: slackapi + owner_html_url: https://github.com/slackapi +- name: langchain-extract + html_url: https://github.com/langchain-ai/langchain-extract + stars: 1110 + owner_login: langchain-ai + owner_html_url: https://github.com/langchain-ai +- name: odmantic + html_url: https://github.com/art049/odmantic + stars: 1104 + owner_login: art049 + owner_html_url: https://github.com/art049 +- name: fastapi_production_template + html_url: https://github.com/zhanymkanov/fastapi_production_template + stars: 1093 + owner_login: zhanymkanov + owner_html_url: https://github.com/zhanymkanov +- name: SurfSense + html_url: https://github.com/MODSetter/SurfSense + stars: 1081 + owner_login: MODSetter + owner_html_url: https://github.com/MODSetter +- name: fastapi-alembic-sqlmodel-async + html_url: https://github.com/jonra1993/fastapi-alembic-sqlmodel-async + stars: 1063 + owner_login: jonra1993 + owner_html_url: https://github.com/jonra1993 +- name: prometheus-fastapi-instrumentator + html_url: https://github.com/trallnag/prometheus-fastapi-instrumentator + stars: 1059 + owner_login: trallnag + owner_html_url: https://github.com/trallnag +- name: bedrock-claude-chat + html_url: https://github.com/aws-samples/bedrock-claude-chat + stars: 1039 + owner_login: aws-samples + owner_html_url: https://github.com/aws-samples +- name: runhouse + html_url: https://github.com/run-house/runhouse + stars: 1005 + owner_login: run-house + owner_html_url: https://github.com/run-house +- name: vue-fastapi-admin + html_url: https://github.com/mizhexiaoxiao/vue-fastapi-admin + stars: 987 + owner_login: mizhexiaoxiao + owner_html_url: https://github.com/mizhexiaoxiao +- name: lanarky + html_url: https://github.com/ajndkr/lanarky + stars: 986 + owner_login: ajndkr + owner_html_url: https://github.com/ajndkr +- name: autollm + html_url: https://github.com/viddexa/autollm + stars: 986 + owner_login: viddexa + owner_html_url: https://github.com/viddexa +- name: restish + html_url: https://github.com/danielgtaylor/restish + stars: 984 + owner_login: danielgtaylor + owner_html_url: https://github.com/danielgtaylor +- name: fastcrud + html_url: https://github.com/igorbenav/fastcrud + stars: 964 + owner_login: igorbenav + owner_html_url: https://github.com/igorbenav +- name: secure + html_url: https://github.com/TypeError/secure + stars: 928 + owner_login: TypeError + owner_html_url: https://github.com/TypeError +- name: langcorn + html_url: https://github.com/msoedov/langcorn + stars: 916 + owner_login: msoedov + owner_html_url: https://github.com/msoedov +- name: energy-forecasting + html_url: https://github.com/iusztinpaul/energy-forecasting + stars: 898 + owner_login: iusztinpaul + owner_html_url: https://github.com/iusztinpaul +- name: authx + html_url: https://github.com/yezz123/authx + stars: 874 + owner_login: yezz123 + owner_html_url: https://github.com/yezz123 +- name: titiler + html_url: https://github.com/developmentseed/titiler + stars: 841 + owner_login: developmentseed + owner_html_url: https://github.com/developmentseed +- name: FastAPI-boilerplate + html_url: https://github.com/igorbenav/FastAPI-boilerplate + stars: 820 + owner_login: igorbenav + owner_html_url: https://github.com/igorbenav +- name: marker-api + html_url: https://github.com/adithya-s-k/marker-api + stars: 813 + owner_login: adithya-s-k + owner_html_url: https://github.com/adithya-s-k +- name: fastapi_best_architecture + html_url: https://github.com/fastapi-practices/fastapi_best_architecture + stars: 802 + owner_login: fastapi-practices + owner_html_url: https://github.com/fastapi-practices +- name: fastapi-do-zero + html_url: https://github.com/dunossauro/fastapi-do-zero + stars: 745 + owner_login: dunossauro + owner_html_url: https://github.com/dunossauro +- name: fastapi-mail + html_url: https://github.com/sabuhish/fastapi-mail + stars: 744 + owner_login: sabuhish + owner_html_url: https://github.com/sabuhish +- name: fastapi-observability + html_url: https://github.com/blueswen/fastapi-observability + stars: 743 + owner_login: blueswen + owner_html_url: https://github.com/blueswen +- name: lccn_predictor + html_url: https://github.com/baoliay2008/lccn_predictor + stars: 741 + owner_login: baoliay2008 + owner_html_url: https://github.com/baoliay2008 +- name: annotated-py-projects + html_url: https://github.com/hhstore/annotated-py-projects + stars: 727 + owner_login: hhstore + owner_html_url: https://github.com/hhstore +- name: learn-generative-ai + html_url: https://github.com/panaverse/learn-generative-ai + stars: 714 + owner_login: panaverse + owner_html_url: https://github.com/panaverse +- name: starlette-admin + html_url: https://github.com/jowilf/starlette-admin + stars: 713 + owner_login: jowilf + owner_html_url: https://github.com/jowilf +- name: chatGPT-web + html_url: https://github.com/mic1on/chatGPT-web + stars: 712 + owner_login: mic1on + owner_html_url: https://github.com/mic1on +- name: FastAPI-Backend-Template + html_url: https://github.com/Aeternalis-Ingenium/FastAPI-Backend-Template + stars: 709 + owner_login: Aeternalis-Ingenium + owner_html_url: https://github.com/Aeternalis-Ingenium +- name: linbing + html_url: https://github.com/taomujian/linbing + stars: 698 + owner_login: taomujian + owner_html_url: https://github.com/taomujian +- name: KonomiTV + html_url: https://github.com/tsukumijima/KonomiTV + stars: 687 + owner_login: tsukumijima + owner_html_url: https://github.com/tsukumijima +- name: fastapi-jwt-auth + html_url: https://github.com/IndominusByte/fastapi-jwt-auth + stars: 685 + owner_login: IndominusByte + owner_html_url: https://github.com/IndominusByte +- name: pity + html_url: https://github.com/wuranxu/pity + stars: 667 + owner_login: wuranxu + owner_html_url: https://github.com/wuranxu diff --git a/docs/en/data/translation_reviewers.yml b/docs/en/data/translation_reviewers.yml new file mode 100644 index 000000000..1a3c12988 --- /dev/null +++ b/docs/en/data/translation_reviewers.yml @@ -0,0 +1,1735 @@ +s111d: + login: s111d + count: 147 + avatarUrl: https://avatars.githubusercontent.com/u/4954856?v=4 + url: https://github.com/s111d +Xewus: + login: Xewus + count: 140 + avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4 + url: https://github.com/Xewus +ceb10n: + login: ceb10n + count: 112 + avatarUrl: https://avatars.githubusercontent.com/u/235213?u=edcce471814a1eba9f0cdaa4cd0de18921a940a6&v=4 + url: https://github.com/ceb10n +sodaMelon: + login: sodaMelon + count: 111 + avatarUrl: https://avatars.githubusercontent.com/u/66295123?u=be939db90f1119efee9e6110cc05066ff1f40f00&v=4 + url: https://github.com/sodaMelon +tokusumi: + login: tokusumi + count: 104 + avatarUrl: https://avatars.githubusercontent.com/u/41147016?u=55010621aece725aa702270b54fed829b6a1fe60&v=4 + url: https://github.com/tokusumi +hasansezertasan: + login: hasansezertasan + count: 95 + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan +hard-coders: + login: hard-coders + count: 92 + avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4 + url: https://github.com/hard-coders +nazarepiedady: + login: nazarepiedady + count: 83 + avatarUrl: https://avatars.githubusercontent.com/u/31008635?u=8dc25777dc9cb51fb0dbba2f137988953d330b78&v=4 + url: https://github.com/nazarepiedady +AlertRED: + login: AlertRED + count: 81 + avatarUrl: https://avatars.githubusercontent.com/u/15695000?u=f5a4944c6df443030409c88da7d7fa0b7ead985c&v=4 + url: https://github.com/AlertRED +alv2017: + login: alv2017 + count: 81 + avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 + url: https://github.com/alv2017 +Alexandrhub: + login: Alexandrhub + count: 68 + avatarUrl: https://avatars.githubusercontent.com/u/119126536?u=9fc0d48f3307817bafecc5861eb2168401a6cb04&v=4 + url: https://github.com/Alexandrhub +waynerv: + login: waynerv + count: 63 + avatarUrl: https://avatars.githubusercontent.com/u/39515546?u=ec35139777597cdbbbddda29bf8b9d4396b429a9&v=4 + url: https://github.com/waynerv +cassiobotaro: + login: cassiobotaro + count: 62 + avatarUrl: https://avatars.githubusercontent.com/u/3127847?u=a08022b191ddbd0a6159b2981d9d878b6d5bb71f&v=4 + url: https://github.com/cassiobotaro +mattwang44: + login: mattwang44 + count: 58 + avatarUrl: https://avatars.githubusercontent.com/u/24987826?u=58e37fb3927b9124b458945ac4c97aa0f1062d85&v=4 + url: https://github.com/mattwang44 +tiangolo: + login: tiangolo + count: 51 + avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 + url: https://github.com/tiangolo +Laineyzhang55: + login: Laineyzhang55 + count: 48 + avatarUrl: https://avatars.githubusercontent.com/u/59285379?v=4 + url: https://github.com/Laineyzhang55 +Kludex: + login: Kludex + count: 47 + avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4 + url: https://github.com/Kludex +komtaki: + login: komtaki + count: 45 + avatarUrl: https://avatars.githubusercontent.com/u/39375566?u=260ad6b1a4b34c07dbfa728da5e586f16f6d1824&v=4 + url: https://github.com/komtaki +alperiox: + login: alperiox + count: 42 + avatarUrl: https://avatars.githubusercontent.com/u/34214152?u=2c5acad3461d4dbc2d48371ba86cac56ae9b25cc&v=4 + url: https://github.com/alperiox +rostik1410: + login: rostik1410 + count: 41 + avatarUrl: https://avatars.githubusercontent.com/u/11443899?u=e26a635c2ba220467b308a326a579b8ccf4a8701&v=4 + url: https://github.com/rostik1410 +Winand: + login: Winand + count: 40 + avatarUrl: https://avatars.githubusercontent.com/u/53390?u=bb0e71a2fc3910a8e0ee66da67c33de40ea695f8&v=4 + url: https://github.com/Winand +solomein-sv: + login: solomein-sv + count: 38 + avatarUrl: https://avatars.githubusercontent.com/u/46193920?u=789927ee09cfabd752d3bd554fa6baf4850d2777&v=4 + url: https://github.com/solomein-sv +JavierSanchezCastro: + login: JavierSanchezCastro + count: 38 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro +stlucasgarcia: + login: stlucasgarcia + count: 36 + avatarUrl: https://avatars.githubusercontent.com/u/61513630?u=c22d8850e9dc396a8820766a59837f967e14f9a0&v=4 + url: https://github.com/stlucasgarcia +SwftAlpc: + login: SwftAlpc + count: 36 + avatarUrl: https://avatars.githubusercontent.com/u/52768429?u=6a3aa15277406520ad37f6236e89466ed44bc5b8&v=4 + url: https://github.com/SwftAlpc +alejsdev: + login: alejsdev + count: 36 + avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=356f39ff3f0211c720b06d3dbb060e98884085e3&v=4 + url: https://github.com/alejsdev +timothy-jeong: + login: timothy-jeong + count: 36 + avatarUrl: https://avatars.githubusercontent.com/u/53824764?u=db3d0cea2f5fab64d810113c5039a369699a2774&v=4 + url: https://github.com/timothy-jeong +nilslindemann: + login: nilslindemann + count: 35 + avatarUrl: https://avatars.githubusercontent.com/u/6892179?u=1dca6a22195d6cd1ab20737c0e19a4c55d639472&v=4 + url: https://github.com/nilslindemann +svlandeg: + login: svlandeg + count: 35 + avatarUrl: https://avatars.githubusercontent.com/u/8796347?u=556c97650c27021911b0b9447ec55e75987b0e8a&v=4 + url: https://github.com/svlandeg +Rishat-F: + login: Rishat-F + count: 35 + avatarUrl: https://avatars.githubusercontent.com/u/66554797?v=4 + url: https://github.com/Rishat-F +rjNemo: + login: rjNemo + count: 34 + avatarUrl: https://avatars.githubusercontent.com/u/56785022?u=d5c3a02567c8649e146fcfc51b6060ccaf8adef8&v=4 + url: https://github.com/rjNemo +codingjenny: + login: codingjenny + count: 34 + avatarUrl: https://avatars.githubusercontent.com/u/103817302?u=3a042740dc0ff58615da0d8679230966fd7693e8&v=4 + url: https://github.com/codingjenny +akarev0: + login: akarev0 + count: 33 + avatarUrl: https://avatars.githubusercontent.com/u/53393089?u=6e528bb4789d56af887ce6fe237bea4010885406&v=4 + url: https://github.com/akarev0 +romashevchenko: + login: romashevchenko + count: 32 + avatarUrl: https://avatars.githubusercontent.com/u/132477732?v=4 + url: https://github.com/romashevchenko +wdh99: + login: wdh99 + count: 31 + avatarUrl: https://avatars.githubusercontent.com/u/108172295?u=8a8fb95d5afe3e0fa33257b2aecae88d436249eb&v=4 + url: https://github.com/wdh99 +LorhanSohaky: + login: LorhanSohaky + count: 30 + avatarUrl: https://avatars.githubusercontent.com/u/16273730?u=095b66f243a2cd6a0aadba9a095009f8aaf18393&v=4 + url: https://github.com/LorhanSohaky +black-redoc: + login: black-redoc + count: 29 + avatarUrl: https://avatars.githubusercontent.com/u/18581590?u=7b6336166d0797fbbd44ea70c1c3ecadfc89af9e&v=4 + url: https://github.com/black-redoc +pedabraham: + login: pedabraham + count: 28 + avatarUrl: https://avatars.githubusercontent.com/u/16860088?u=abf922a7b920bf8fdb7867d8b43e091f1e796178&v=4 + url: https://github.com/pedabraham +Smlep: + login: Smlep + count: 28 + avatarUrl: https://avatars.githubusercontent.com/u/16785985?u=ffe99fa954c8e774ef1117e58d34aece92051e27&v=4 + url: https://github.com/Smlep +dedkot01: + login: dedkot01 + count: 28 + avatarUrl: https://avatars.githubusercontent.com/u/26196675?u=e2966887124e67932853df4f10f86cb526edc7b0&v=4 + url: https://github.com/dedkot01 +hsuanchi: + login: hsuanchi + count: 28 + avatarUrl: https://avatars.githubusercontent.com/u/24913710?u=0b094ae292292fee093818e37ceb645c114d2bff&v=4 + url: https://github.com/hsuanchi +dpinezich: + login: dpinezich + count: 28 + avatarUrl: https://avatars.githubusercontent.com/u/3204540?u=a2e1465e3ee10d537614d513589607eddefde09f&v=4 + url: https://github.com/dpinezich +maoyibo: + login: maoyibo + count: 27 + avatarUrl: https://avatars.githubusercontent.com/u/7887703?v=4 + url: https://github.com/maoyibo +0417taehyun: + login: 0417taehyun + count: 27 + avatarUrl: https://avatars.githubusercontent.com/u/63915557?u=47debaa860fd52c9b98c97ef357ddcec3b3fb399&v=4 + url: https://github.com/0417taehyun +BilalAlpaslan: + login: BilalAlpaslan + count: 26 + avatarUrl: https://avatars.githubusercontent.com/u/47563997?u=63ed66e304fe8d765762c70587d61d9196e5c82d&v=4 + url: https://github.com/BilalAlpaslan +junah201: + login: junah201 + count: 26 + avatarUrl: https://avatars.githubusercontent.com/u/75025529?u=2451c256e888fa2a06bcfc0646d09b87ddb6a945&v=4 + url: https://github.com/junah201 +mezgoodle: + login: mezgoodle + count: 26 + avatarUrl: https://avatars.githubusercontent.com/u/41520940?u=e871bc26734eb2436d98c19c3fb57a4773e13c24&v=4 + url: https://github.com/mezgoodle +Vincy1230: + login: Vincy1230 + count: 26 + avatarUrl: https://avatars.githubusercontent.com/u/81342412?u=ab5e256a4077a4a91f3f9cd2115ba80780454cbe&v=4 + url: https://github.com/Vincy1230 +zy7y: + login: zy7y + count: 25 + avatarUrl: https://avatars.githubusercontent.com/u/67154681?u=5d634834cc514028ea3f9115f7030b99a1f4d5a4&v=4 + url: https://github.com/zy7y +mycaule: + login: mycaule + count: 25 + avatarUrl: https://avatars.githubusercontent.com/u/6161385?u=e3cec75bd6d938a0d73fae0dc5534d1ab2ed1b0e&v=4 + url: https://github.com/mycaule +Aruelius: + login: Aruelius + count: 24 + avatarUrl: https://avatars.githubusercontent.com/u/25380989?u=574f8cfcda3ea77a3f81884f6b26a97068e36a9d&v=4 + url: https://github.com/Aruelius +OzgunCaglarArslan: + login: OzgunCaglarArslan + count: 24 + avatarUrl: https://avatars.githubusercontent.com/u/86166426?v=4 + url: https://github.com/OzgunCaglarArslan +sh0nk: + login: sh0nk + count: 23 + avatarUrl: https://avatars.githubusercontent.com/u/6478810?u=af15d724875cec682ed8088a86d36b2798f981c0&v=4 + url: https://github.com/sh0nk +axel584: + login: axel584 + count: 23 + avatarUrl: https://avatars.githubusercontent.com/u/1334088?u=9667041f5b15dc002b6f9665fda8c0412933ac04&v=4 + url: https://github.com/axel584 +wisderfin: + login: wisderfin + count: 23 + avatarUrl: https://avatars.githubusercontent.com/u/77553770?u=f3b00a26736ba664e9927a1116c6e8088295e073&v=4 + url: https://github.com/wisderfin +AGolicyn: + login: AGolicyn + count: 21 + avatarUrl: https://avatars.githubusercontent.com/u/86262613?u=3c21606ab8d210a061a1673decff1e7d5592b380&v=4 + url: https://github.com/AGolicyn +Attsun1031: + login: Attsun1031 + count: 20 + avatarUrl: https://avatars.githubusercontent.com/u/1175560?v=4 + url: https://github.com/Attsun1031 +ycd: + login: ycd + count: 20 + avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=f1e7bae394a315da950912c92dc861a8eaf95d4c&v=4 + url: https://github.com/ycd +delhi09: + login: delhi09 + count: 20 + avatarUrl: https://avatars.githubusercontent.com/u/63476957?u=6c86e59b48e0394d4db230f37fc9ad4d7e2c27c7&v=4 + url: https://github.com/delhi09 +rogerbrinkmann: + login: rogerbrinkmann + count: 20 + avatarUrl: https://avatars.githubusercontent.com/u/5690226?v=4 + url: https://github.com/rogerbrinkmann +DevDae: + login: DevDae + count: 20 + avatarUrl: https://avatars.githubusercontent.com/u/87962045?u=08e10fa516e844934f4b3fc7c38b33c61697e4a1&v=4 + url: https://github.com/DevDae +sattosan: + login: sattosan + count: 19 + avatarUrl: https://avatars.githubusercontent.com/u/20574756?u=b0d8474d2938189c6954423ae8d81d91013f80a8&v=4 + url: https://github.com/sattosan +yes0ng: + login: yes0ng + count: 19 + avatarUrl: https://avatars.githubusercontent.com/u/25501794?u=3aed18b0d491e0220a167a1e9e58bea3638c6707&v=4 + url: https://github.com/yes0ng +ComicShrimp: + login: ComicShrimp + count: 18 + avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=d2fbf412e7730183ce91686ca48d4147e1b7dc74&v=4 + url: https://github.com/ComicShrimp +simatheone: + login: simatheone + count: 18 + avatarUrl: https://avatars.githubusercontent.com/u/78508673?u=1b9658d9ee0bde33f56130dd52275493ddd38690&v=4 + url: https://github.com/simatheone +ivan-abc: + login: ivan-abc + count: 18 + avatarUrl: https://avatars.githubusercontent.com/u/36765187?u=c6e0ba571c1ccb6db9d94e62e4b8b5eda811a870&v=4 + url: https://github.com/ivan-abc +bezaca: + login: bezaca + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/69092910?u=4ac58eab99bd37d663f3d23551df96d4fbdbf760&v=4 + url: https://github.com/bezaca +lbmendes: + login: lbmendes + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/80999926?u=646619e2f07ac5a7c3f65fe7834197461a4fff9f&v=4 + url: https://github.com/lbmendes +spacesphere: + login: spacesphere + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/34628304?u=cde91f6002dd33156e1bf8005f11a7a3ed76b790&v=4 + url: https://github.com/spacesphere +panko: + login: panko + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/1569515?u=a84a5d255621ed82f8e1ca052f5f2eeb75997da2&v=4 + url: https://github.com/panko +jeison-araya: + login: jeison-araya + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/57369279?u=17001e68af7d8e5b8c343e5e9df4050f419998d5&v=4 + url: https://github.com/jeison-araya +Limsunoh: + login: Limsunoh + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/90311848?u=f456e0c5709fd50c8cd2898b551558eda14e5f21&v=4 + url: https://github.com/Limsunoh +yanever: + login: yanever + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/21978760?v=4 + url: https://github.com/yanever +mastizada: + login: mastizada + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/1975818?u=0751a06d7271c8bf17cb73b1b845644ab4d2c6dc&v=4 + url: https://github.com/mastizada +Joao-Pedro-P-Holanda: + login: Joao-Pedro-P-Holanda + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/110267046?u=331bd016326dac4cf3df4848f6db2dbbf8b5f978&v=4 + url: https://github.com/Joao-Pedro-P-Holanda +JaeHyuckSa: + login: JaeHyuckSa + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/104830931?v=4 + url: https://github.com/JaeHyuckSa +Jedore: + login: Jedore + count: 15 + avatarUrl: https://avatars.githubusercontent.com/u/17944025?u=81d503e1c800eb666b3861ca47a3a773bbc3f539&v=4 + url: https://github.com/Jedore +kim-sangah: + login: kim-sangah + count: 15 + avatarUrl: https://avatars.githubusercontent.com/u/173775778?v=4 + url: https://github.com/kim-sangah +PandaHun: + login: PandaHun + count: 14 + avatarUrl: https://avatars.githubusercontent.com/u/13096845?u=646eba44db720e37d0dbe8e98e77ab534ea78a20&v=4 + url: https://github.com/PandaHun +dukkee: + login: dukkee + count: 14 + avatarUrl: https://avatars.githubusercontent.com/u/36825394?u=ccfd86e6a4f2d093dad6f7544cc875af67fa2df8&v=4 + url: https://github.com/dukkee +mkdir700: + login: mkdir700 + count: 14 + avatarUrl: https://avatars.githubusercontent.com/u/56359329?u=3d6ea8714f5000829b60dcf7b13a75b1e73aaf47&v=4 + url: https://github.com/mkdir700 +BORA040126: + login: BORA040126 + count: 14 + avatarUrl: https://avatars.githubusercontent.com/u/88664069?u=98e382727a485971e04aaa7c873d9a75a17ee3be&v=4 + url: https://github.com/BORA040126 +mattkoehne: + login: mattkoehne + count: 14 + avatarUrl: https://avatars.githubusercontent.com/u/80362153?u=6e1439582715693407b86182eb66263bb578a761&v=4 + url: https://github.com/mattkoehne +jovicon: + login: jovicon + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/21287303?u=b049eac3e51a4c0473c2efe66b4d28a7d8f2b572&v=4 + url: https://github.com/jovicon +izaguerreiro: + login: izaguerreiro + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/2241504?v=4 + url: https://github.com/izaguerreiro +jburckel: + login: jburckel + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/11768758?u=044462e4130e086a0621f4abb45f0d7a289ab7fa&v=4 + url: https://github.com/jburckel +peidrao: + login: peidrao + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/32584628?u=64c634bb10381905038ff7faf3c8c3df47fb799a&v=4 + url: https://github.com/peidrao +impocode: + login: impocode + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/109408819?u=9cdfc5ccb31a2094c520f41b6087012fa9048982&v=4 + url: https://github.com/impocode +wesinalves: + login: wesinalves + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/13563128?u=9eb17ed50645dd684bfec47e75dba4e9772ec9c1&v=4 + url: https://github.com/wesinalves +NastasiaSaby: + login: NastasiaSaby + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/8245071?u=b3afd005f9e4bf080c219ef61a592b3a8004b764&v=4 + url: https://github.com/NastasiaSaby +oandersonmagalhaes: + login: oandersonmagalhaes + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/83456692?v=4 + url: https://github.com/oandersonmagalhaes +batlopes: + login: batlopes + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/33462923?u=0fb3d7acb316764616f11e4947faf080e49ad8d9&v=4 + url: https://github.com/batlopes +Lenclove: + login: Lenclove + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/32355298?u=d0065e01650c63c2b2413f42d983634b2ea85481&v=4 + url: https://github.com/Lenclove +joonas-yoon: + login: joonas-yoon + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/9527681?u=0166d22ef4749e617c6516e79f833cd8d73f1949&v=4 + url: https://github.com/joonas-yoon +baseplate-admin: + login: baseplate-admin + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/61817579?u=ce4c268fa949ae9a0290996e7949195302055812&v=4 + url: https://github.com/baseplate-admin +KaniKim: + login: KaniKim + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/19832624?u=296dbdd490e0eb96e3d45a2608c065603b17dc31&v=4 + url: https://github.com/KaniKim +andersonrocha0: + login: andersonrocha0 + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/22346169?u=93a1359c8c5461d894802c0cc65bcd09217e7a02&v=4 + url: https://github.com/andersonrocha0 +kwang1215: + login: kwang1215 + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/74170199?u=2a63ff6692119dde3f5e5693365b9fcd6f977b08&v=4 + url: https://github.com/kwang1215 +AdrianDeAnda: + login: AdrianDeAnda + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/1024932?u=b2ea249c6b41ddf98679c8d110d0f67d4a3ebf93&v=4 + url: https://github.com/AdrianDeAnda +blt232018: + login: blt232018 + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/43393471?u=172b0e0391db1aa6c1706498d6dfcb003c8a4857&v=4 + url: https://github.com/blt232018 +NinaHwang: + login: NinaHwang + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/79563565?u=241f2cb6d38a2d379536608a8ea5a22ed4b1a3ea&v=4 + url: https://github.com/NinaHwang +glsglsgls: + login: glsglsgls + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/76133879?v=4 + url: https://github.com/glsglsgls +k94-ishi: + login: k94-ishi + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/32672580?u=bc7c5c07af0656be9fe4f1784a444af8d81ded89&v=4 + url: https://github.com/k94-ishi +codespearhead: + login: codespearhead + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/72931357?u=0fce6b82219b604d58adb614a761556425579cb5&v=4 + url: https://github.com/codespearhead +emrhnsyts: + login: emrhnsyts + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/42899027?u=ad26798e3f8feed2041c5dd5f87e58933d6c3283&v=4 + url: https://github.com/emrhnsyts +Lufa1u: + login: Lufa1u + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/112495876?u=087658920ed9e74311597bdd921d8d2de939d276&v=4 + url: https://github.com/Lufa1u +KNChiu: + login: KNChiu + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/36751646?v=4 + url: https://github.com/KNChiu +gitgernit: + login: gitgernit + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/129539613?u=d04f10143ab32c93f563ea14bf242d1d2bc991b0&v=4 + url: https://github.com/gitgernit +mariacamilagl: + login: mariacamilagl + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/11489395?u=4adb6986bf3debfc2b8216ae701f2bd47d73da7d&v=4 + url: https://github.com/mariacamilagl +ryuckel: + login: ryuckel + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/36391432?u=094eec0cfddd5013f76f31e55e56147d78b19553&v=4 + url: https://github.com/ryuckel +umitkaanusta: + login: umitkaanusta + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/53405015?v=4 + url: https://github.com/umitkaanusta +kty4119: + login: kty4119 + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/49435654?v=4 + url: https://github.com/kty4119 +RobotToI: + login: RobotToI + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/44951382?u=e41dbc19191ce7abed86694b1a44ea0523e1c60e&v=4 + url: https://github.com/RobotToI +vitumenezes: + login: vitumenezes + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/9680878?u=05fd25cfafdc09382bf8907c37293a696c205754&v=4 + url: https://github.com/vitumenezes +fcrozetta: + login: fcrozetta + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/8006246?u=fa2a743e803de2c3a84d3ed8042faefed16c5e43&v=4 + url: https://github.com/fcrozetta +sUeharaE4: + login: sUeharaE4 + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/44468359?v=4 + url: https://github.com/sUeharaE4 +Ernilia: + login: Ernilia + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/125735800?u=13bfaac417a53fd5b5cf992efea363ca72598813&v=4 + url: https://github.com/Ernilia +socket-socket: + login: socket-socket + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/121552599?u=104df6503242e8d762fe293e7036f7260f245d49&v=4 + url: https://github.com/socket-socket +nick-cjyx9: + login: nick-cjyx9 + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/119087246?u=c35aab03f082430be8a1edd80f5625b44819a0d8&v=4 + url: https://github.com/nick-cjyx9 +waketzheng: + login: waketzheng + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/35413830?u=df19e4fd5bb928e7d086e053ef26a46aad23bf84&v=4 + url: https://github.com/waketzheng +lucasbalieiro: + login: lucasbalieiro + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/37416577?u=eabaf4aebbaa88a94a4886273edba689012cee70&v=4 + url: https://github.com/lucasbalieiro +RunningIkkyu: + login: RunningIkkyu + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/31848542?u=494ecc298e3f26197495bb357ad0f57cfd5f7a32&v=4 + url: https://github.com/RunningIkkyu +JulianMaurin: + login: JulianMaurin + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/63545168?u=b7d15ac865268cbefc2d739e2f23d9aeeac1a622&v=4 + url: https://github.com/JulianMaurin +JeongHyeongKim: + login: JeongHyeongKim + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/26577800?u=fe653349051c0acf62cd984e74c4ff60ca8d2cb6&v=4 + url: https://github.com/JeongHyeongKim +arthurio: + login: arthurio + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/950449?u=76b997138273ce5e1990b971c4f27c9aff979fd5&v=4 + url: https://github.com/arthurio +mahone3297: + login: mahone3297 + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/1701379?u=20588ff0e456d13e8017333eb237595d11410234&v=4 + url: https://github.com/mahone3297 +eVery1337: + login: eVery1337 + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/84917945?u=7af243f05ecfba59191199a70d8ba365c1327768&v=4 + url: https://github.com/eVery1337 +aykhans: + login: aykhans + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/88669260?u=798da457cc3276d3c6dd7fd628d0005ad8b298cc&v=4 + url: https://github.com/aykhans +riroan: + login: riroan + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/33053284?u=2d18e3771506ee874b66d6aa2b3b1107fd95c38f&v=4 + url: https://github.com/riroan +yodai-yodai: + login: yodai-yodai + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/7031039?u=4f3593f5931892b931a745cfab846eff6e9332e7&v=4 + url: https://github.com/yodai-yodai +marcelomarkus: + login: marcelomarkus + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/20115018?u=dda090ce9160ef0cd2ff69b1e5ea741283425cba&v=4 + url: https://github.com/marcelomarkus +JoaoGustavoRogel: + login: JoaoGustavoRogel + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/29525510?u=a0a91251f5e43e132608d55d28ccb8645c5ea405&v=4 + url: https://github.com/JoaoGustavoRogel +Zhongheng-Cheng: + login: Zhongheng-Cheng + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/95612344?u=a0f7730a3cc7486827965e01a119ad610bda4b0a&v=4 + url: https://github.com/Zhongheng-Cheng +Yarous: + login: Yarous + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/61277193?u=5b462347458a373b2d599c6f416d2b75eddbffad&v=4 + url: https://github.com/Yarous +dimaqq: + login: dimaqq + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/662249?u=15313dec91bae789685e4abb3c2152251de41948&v=4 + url: https://github.com/dimaqq +julianofischer: + login: julianofischer + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/158303?u=d91662eb949d4cc7368831cf37a5cdfd90b7010c&v=4 + url: https://github.com/julianofischer +bnzone: + login: bnzone + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/39371503?u=c16f00c41d88479fa2d57b0d7d233b758eacce2d&v=4 + url: https://github.com/bnzone +ChuyuChoyeon: + login: ChuyuChoyeon + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/129537877?u=f0c76f3327817a8b86b422d62e04a34bf2827f2b&v=4 + url: https://github.com/ChuyuChoyeon +shamosishen: + login: shamosishen + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/9498321?u=c83c20c79e019a0b555a125adf20fc4fb7a882c8&v=4 + url: https://github.com/shamosishen +mertssmnoglu: + login: mertssmnoglu + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/61623638?u=59dd885b68ff1832f9ab3b4a4446896358c23442&v=4 + url: https://github.com/mertssmnoglu +KimJoonSeo: + login: KimJoonSeo + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/17760162?u=a58cdc77ae1c069a64166f7ecc4d42eecfd9a468&v=4 + url: https://github.com/KimJoonSeo +MinLee0210: + login: MinLee0210 + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/57653278?u=7def7c0654ad82f43b46d6dfc3b51c4d2be15011&v=4 + url: https://github.com/MinLee0210 +camigomezdev: + login: camigomezdev + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/16061815?u=25b5ebc042fff53fa03dc107ded10e36b1b7a5b9&v=4 + url: https://github.com/camigomezdev +maru0123-2004: + login: maru0123-2004 + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/43961566?u=16ed8603a4d6a4665cb6c53a7aece6f31379b769&v=4 + url: https://github.com/maru0123-2004 +Serrones: + login: Serrones + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/22691749?u=4795b880e13ca33a73e52fc0ef7dc9c60c8fce47&v=4 + url: https://github.com/Serrones +israteneda: + login: israteneda + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/20668624?u=67574648f89019d1c73b16a6a009da659557f9e5&v=4 + url: https://github.com/israteneda +krocdort: + login: krocdort + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/34248814?v=4 + url: https://github.com/krocdort +anthonycepeda: + login: anthonycepeda + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/72019805?u=60bdf46240cff8fca482ff0fc07d963fd5e1a27c&v=4 + url: https://github.com/anthonycepeda +fabioueno: + login: fabioueno + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/14273852?u=edd700982b16317ac6ebfd24c47bc0029b21d360&v=4 + url: https://github.com/fabioueno +cfraboulet: + login: cfraboulet + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/62244267?u=ed0e286ba48fa1dafd64a08e50f3364b8e12df34&v=4 + url: https://github.com/cfraboulet +HiemalBeryl: + login: HiemalBeryl + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/63165207?u=276f4af2829baf28b912c718675852bfccb0e7b4&v=4 + url: https://github.com/HiemalBeryl +pablocm83: + login: pablocm83 + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/28315068?u=3310fbb05bb8bfc50d2c48b6cb64ac9ee4a14549&v=4 + url: https://github.com/pablocm83 +d2a-raudenaerde: + login: d2a-raudenaerde + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/5213150?v=4 + url: https://github.com/d2a-raudenaerde +deniscapeto: + login: deniscapeto + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/12864353?u=dbc20c5c1171feab5df4db46488b675d53cb5b07&v=4 + url: https://github.com/deniscapeto +bsab: + login: bsab + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/9799799?u=c4a09b1abb794cd8280c4793d43d0e2eb963ecda&v=4 + url: https://github.com/bsab +ArcLightSlavik: + login: ArcLightSlavik + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/31127044?u=b0f2c37142f4b762e41ad65dc49581813422bd71&v=4 + url: https://github.com/ArcLightSlavik +Cajuteq: + login: Cajuteq + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/26676532?u=8ee0422981810e51480855de1c0d67b6b79cd3f2&v=4 + url: https://github.com/Cajuteq +emmrichard: + login: emmrichard + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/1328018?u=8114d8fc0e8e42a092e4283013a1c54b792c466b&v=4 + url: https://github.com/emmrichard +wakabame: + login: wakabame + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/35513518?u=41ef6b0a55076e5c540620d68fb006e386c2ddb0&v=4 + url: https://github.com/wakabame +mawassk: + login: mawassk + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/84179197?v=4 + url: https://github.com/mawassk +diogoduartec: + login: diogoduartec + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/31852339?u=7514a5f05fcbeccc62f8c5dc25879efeb1ef9335&v=4 + url: https://github.com/diogoduartec +aqcool: + login: aqcool + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/52229895?v=4 + url: https://github.com/aqcool +'1320555911': + login: '1320555911' + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/58590086?u=6d8f4fbf08d5ac72c1c895892c461c5e0b013dc3&v=4 + url: https://github.com/1320555911 +mcthesw: + login: mcthesw + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/61224072?u=82a1b106298348f060c3f4f39817e0cae5ce2b7c&v=4 + url: https://github.com/mcthesw +xzmeng: + login: xzmeng + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/40202897?v=4 + url: https://github.com/xzmeng +negadive: + login: negadive + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/47322392?u=c1be2e9b9b346b4a77d9157da2a5739ab25ce0f8&v=4 + url: https://github.com/negadive +mbroton: + login: mbroton + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/50829834?u=a48610bf1bffaa9c75d03228926e2eb08a2e24ee&v=4 + url: https://github.com/mbroton +Kirilex: + login: Kirilex + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/100281552?v=4 + url: https://github.com/Kirilex +Mordson: + login: Mordson + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/39025897?u=b94ea96ef35bbe43bc85359cfb31d28ac16d470c&v=4 + url: https://github.com/Mordson +arunppsg: + login: arunppsg + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/26398753?v=4 + url: https://github.com/arunppsg +dimastbk: + login: dimastbk + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/3132181?u=66587398d43466a1dc75c238df5f048e0afc77ed&v=4 + url: https://github.com/dimastbk +lordqyxz: + login: lordqyxz + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/31722468?u=974553c0ba53526d9be7e9876544283291be3b0d&v=4 + url: https://github.com/lordqyxz +dudyaosuplayer: + login: dudyaosuplayer + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/62661898?u=7864cc5f01b1c845ae8ad49acf45dec6faca0c57&v=4 + url: https://github.com/dudyaosuplayer +talhaumer: + login: talhaumer + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/46643702?u=5d1fd7057ea9534fb3221931b809a3d750157212&v=4 + url: https://github.com/talhaumer +bankofsardine: + login: bankofsardine + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/44944207?u=0368e1b698ffab6bf29e202f9fd2dddd352429f1&v=4 + url: https://github.com/bankofsardine +SofiiaTrufanova: + login: SofiiaTrufanova + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/63260929?v=4 + url: https://github.com/SofiiaTrufanova +DianaTrufanova: + login: DianaTrufanova + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/119067607?v=4 + url: https://github.com/DianaTrufanova +rsip22: + login: rsip22 + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/16676222?v=4 + url: https://github.com/rsip22 +jessicapaz: + login: jessicapaz + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/20428941?u=6ffdaab5a85bf77a2d8870dade5e53555f34577b&v=4 + url: https://github.com/jessicapaz +mohsen-mahmoodi: + login: mohsen-mahmoodi + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/2872586?u=3a9fc1aa16a3a0ab93a1f8550de82a940592857d&v=4 + url: https://github.com/mohsen-mahmoodi +jeesang7: + login: jeesang7 + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/30719956?u=35fc8bca04d32d3c4ce085956f0636b959ba30f6&v=4 + url: https://github.com/jeesang7 +TemaSpb: + login: TemaSpb + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/20205738?u=d7dce0718720a7107803a573d628d8dd3d5c2fb4&v=4 + url: https://github.com/TemaSpb +BugLight: + login: BugLight + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/13618366?u=57572e544e40c2a491db5bf7255bd24886d2cb09&v=4 + url: https://github.com/BugLight +0x4Dark: + login: 0x4Dark + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/7569289?v=4 + url: https://github.com/0x4Dark +Wuerike: + login: Wuerike + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/35462243?u=80c753dedf4a78db12ef66316dbdebbe6d84a2b9&v=4 + url: https://github.com/Wuerike +jvmazagao: + login: jvmazagao + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/22477816?u=f3b2d503b53e6ec8c808f0601b756a063a07f06e&v=4 + url: https://github.com/jvmazagao +cun3yt: + login: cun3yt + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/24409240?u=39f651cdcc4991fb9fef5bbd9e9503db2174ac13&v=4 + url: https://github.com/cun3yt +aminkhani: + login: aminkhani + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/51851950?u=051896c4933816bc61d11091d887f6e8dfd1d27b&v=4 + url: https://github.com/aminkhani +nifadyev: + login: nifadyev + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/36514612?u=e101da8641d5a09901d2155255a93f8ab3d9c468&v=4 + url: https://github.com/nifadyev +LaurEars: + login: LaurEars + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/4914725?v=4 + url: https://github.com/LaurEars +Chushine: + login: Chushine + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/135534400?v=4 + url: https://github.com/Chushine +frwl404: + login: frwl404 + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/42642656?u=572a5a33762e07eaa6ebd58d9d773abdb1de41c3&v=4 + url: https://github.com/frwl404 +esrefzeki: + login: esrefzeki + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/54935247?u=193cf5a169ca05fc54995a4dceabc82c7dc6e5ea&v=4 + url: https://github.com/esrefzeki +dtleal: + login: dtleal + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/31096951?v=4 + url: https://github.com/dtleal +art3xa: + login: art3xa + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/92092049?v=4 + url: https://github.com/art3xa +SamuelBFavarin: + login: SamuelBFavarin + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/17628602?u=5aac13ae492fa9a86e397a70803ac723dba2efe7&v=4 + url: https://github.com/SamuelBFavarin +takacs: + login: takacs + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/44911031?u=f6c6b70b3ba86ceb93b0f9bcab609bf9328b2305&v=4 + url: https://github.com/takacs +anton2yakovlev: + login: anton2yakovlev + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/44229180?u=bdd445ba99074b378e7298d23c4bf6d707d2c282&v=4 + url: https://github.com/anton2yakovlev +ILoveSorasakiHina: + login: ILoveSorasakiHina + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/114038930?u=3d3ed8dc3bf57e641d1b26badee5bc79ef34f25b&v=4 + url: https://github.com/ILoveSorasakiHina +devluisrodrigues: + login: devluisrodrigues + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/103431660?u=d9674a3249edc4601d2c712cdebf899918503c3a&v=4 + url: https://github.com/devluisrodrigues +11kkw: + login: 11kkw + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/21125286?v=4 + url: https://github.com/11kkw +lpdswing: + login: lpdswing + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/20874036?u=7a4fc3e4d0719e37b305deb7af234a7b63200787&v=4 + url: https://github.com/lpdswing +SepehrRasouli: + login: SepehrRasouli + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/81516241?u=3987e880c77d653dd85963302150e07bb7c0ef99&v=4 + url: https://github.com/SepehrRasouli +Zxilly: + login: Zxilly + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/31370133?u=c5359b8d9d80a7cdc23d5295d179ed90174996c8&v=4 + url: https://github.com/Zxilly +eavv: + login: eavv + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/18273429?u=c05e8b4ea62810ee7889ca049e510cdd0a66fd26&v=4 + url: https://github.com/eavv +AlexandreBiguet: + login: AlexandreBiguet + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/1483079?u=ff926455cd4cab03c6c49441aa5dc2b21df3e266&v=4 + url: https://github.com/AlexandreBiguet +FelipeSilva93: + login: FelipeSilva93 + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/66804965?u=e7cb4b580e46f2e04ecb4cd4d7a12acdddd3c6c1&v=4 + url: https://github.com/FelipeSilva93 +bas-baskara: + login: bas-baskara + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/41407847?u=cdabfaff7481c3323f24a76d9350393b964f2b89&v=4 + url: https://github.com/bas-baskara +odiseo0: + login: odiseo0 + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/87550035?u=241a71f6b7068738b81af3e57f45ffd723538401&v=4 + url: https://github.com/odiseo0 +eryknn: + login: eryknn + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/87120651?v=4 + url: https://github.com/eryknn +personage-hub: + login: personage-hub + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/76659786?v=4 + url: https://github.com/personage-hub +aminalaee: + login: aminalaee + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/19784933?v=4 + url: https://github.com/aminalaee +erfan-rfmhr: + login: erfan-rfmhr + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/98986056?u=6c4f9218fe5bb04780dd92bfced360c55e2009f0&v=4 + url: https://github.com/erfan-rfmhr +Scorpionchiques: + login: Scorpionchiques + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/15703294?v=4 + url: https://github.com/Scorpionchiques +heysaeid: + login: heysaeid + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/63112273?u=5397ead391319a147a18b70cc04d1a334f235ef3&v=4 + url: https://github.com/heysaeid +Yois4101: + login: Yois4101 + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/119609381?v=4 + url: https://github.com/Yois4101 +tamtam-fitness: + login: tamtam-fitness + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/62091034?u=8da19a6bd3d02f5d6ba30c7247d5b46c98dd1403&v=4 + url: https://github.com/tamtam-fitness +mpmeleshko: + login: mpmeleshko + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/34425664?v=4 + url: https://github.com/mpmeleshko +SonnyYou: + login: SonnyYou + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/18657569?v=4 + url: https://github.com/SonnyYou +matiasbertani: + login: matiasbertani + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/65260383?u=d5edd86a6e2ab4fb1aab7751931fe045a963afd7&v=4 + url: https://github.com/matiasbertani +thiennc254: + login: thiennc254 + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/97406628?u=1b2860679694b9a552764d0fa81dbd7a016322ec&v=4 + url: https://github.com/thiennc254 +javillegasna: + login: javillegasna + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/38879192?u=df9ab0d628f8c1f1c849db7b3c0939337f42c3f1&v=4 + url: https://github.com/javillegasna +9zimin9: + login: 9zimin9 + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/174453744?v=4 + url: https://github.com/9zimin9 +ilhamfadillah: + login: ilhamfadillah + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/20577838?u=c56192cf99b55affcaad408b240259c62e633450&v=4 + url: https://github.com/ilhamfadillah +gerry-sabar: + login: gerry-sabar + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/1120123?v=4 + url: https://github.com/gerry-sabar +valentinDruzhinin: + login: valentinDruzhinin + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/12831905?u=aae1ebc675c91e8fa582df4fcc4fc4128106344d&v=4 + url: https://github.com/valentinDruzhinin +tyronedamasceno: + login: tyronedamasceno + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/12273721?u=913bca6bab96d9416ad8c9874c80de0833782050&v=4 + url: https://github.com/tyronedamasceno +LikoIlya: + login: LikoIlya + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/15039930?v=4 + url: https://github.com/LikoIlya +ss-o-furda: + login: ss-o-furda + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/56111536?u=d2326baa464a3778c280ed85fd14c00f87eb1080&v=4 + url: https://github.com/ss-o-furda +Frans06: + login: Frans06 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/5842109?u=77529d5517ae80438249b1a45f2d59372a31a212&v=4 + url: https://github.com/Frans06 +Jefidev: + login: Jefidev + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/9964497?u=1da6eee587a8b425ca4afbfdfc6c3a639fe85d02&v=4 + url: https://github.com/Jefidev +Xaraxx: + login: Xaraxx + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/29824698?u=dde2e233e22bb5ca1f8bb0c6e353ccd0d06e6066&v=4 + url: https://github.com/Xaraxx +Suyoung789: + login: Suyoung789 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/31277231?u=744bd3e641413e19bfad6b06a90bb0887c3f9332&v=4 + url: https://github.com/Suyoung789 +akagaeng: + login: akagaeng + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/17076841?u=9ada2eb6a33dc705ba96d58f802c787dea3859b8&v=4 + url: https://github.com/akagaeng +phamquanganh31101998: + login: phamquanganh31101998 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/43257497?u=36fa4ee689415d869a98453083a7c4213d2136ee&v=4 + url: https://github.com/phamquanganh31101998 +peebbv6364: + login: peebbv6364 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/26784747?u=75583df215ee01a5cd2dc646aecb81e7dbd33d06&v=4 + url: https://github.com/peebbv6364 +mrparalon: + login: mrparalon + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/19637629?u=6339508ceb665717cae862a4d33816ac874cbb8f&v=4 + url: https://github.com/mrparalon +creyD: + login: creyD + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/15138480?u=51cd2873cd93807beb578af8e23975856fdbc945&v=4 + url: https://github.com/creyD +zhoonit: + login: zhoonit + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/17230883?u=698cb26dcce4770374b592aad3b7489e91c07fc6&v=4 + url: https://github.com/zhoonit +Sefank: + login: Sefank + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/12670778?u=ca16995c68a82cabc7435c54ac0564930f62dd59&v=4 + url: https://github.com/Sefank +RuslanTer: + login: RuslanTer + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/48125303?v=4 + url: https://github.com/RuslanTer +FedorGN: + login: FedorGN + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/66411909?u=1c6734e92f50c7d66f130ef7d394e72b53770fe6&v=4 + url: https://github.com/FedorGN +rafsaf: + login: rafsaf + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/51059348?u=5fe59a56e1f2f9ccd8005d71752a8276f133ae1a&v=4 + url: https://github.com/rafsaf +frnsimoes: + login: frnsimoes + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/66239468?u=a405e8f10654251e239a4a1d9dd5bda59216727d&v=4 + url: https://github.com/frnsimoes +lieryan: + login: lieryan + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/1006989?v=4 + url: https://github.com/lieryan +ValeryVal: + login: ValeryVal + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/85856176?v=4 + url: https://github.com/ValeryVal +chesstrian: + login: chesstrian + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/3923412?u=8ea9bea6cfb5e6c64dc81be65ac2a9aaf23c5d47&v=4 + url: https://github.com/chesstrian +PabloEmidio: + login: PabloEmidio + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/69937719?u=f4d04cb78da68bb93a641f0b793ff665162e712a&v=4 + url: https://github.com/PabloEmidio +PraveenNanda124: + login: PraveenNanda124 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/116082827?u=b40c4f23c191692e88f676dc3bf33fc7f315edd4&v=4 + url: https://github.com/PraveenNanda124 +guites: + login: guites + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/71985299?u=5dab5eb82b0a67fe709fc893f47a423df4de5d46&v=4 + url: https://github.com/guites +Junhyung21: + login: Junhyung21 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/138214497?u=66377988eaad4f57004decb183f396560407a73f&v=4 + url: https://github.com/Junhyung21 +rinaatt: + login: rinaatt + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/6111202?u=9f62ebd2a72879db54d0b51c07c1d1e7203a4813&v=4 + url: https://github.com/rinaatt +Slijeff: + login: Slijeff + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/31459252?u=083776331690bbcf427766071e33ac28bb8d271d&v=4 + url: https://github.com/Slijeff +GeorchW: + login: GeorchW + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/8687777?u=ae4160f1d88f32692760003f3be9b5fc40a6e00d&v=4 + url: https://github.com/GeorchW +Vlad0395: + login: Vlad0395 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/37487589?u=57dc6660b9904cc0bc59b73569bbfb1ac871a4a1&v=4 + url: https://github.com/Vlad0395 +bisibuka: + login: bisibuka + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/221887?v=4 + url: https://github.com/bisibuka +aimasheraz1: + login: aimasheraz1 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/132935019?v=4 + url: https://github.com/aimasheraz1 +whysage: + login: whysage + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/67018871?u=a05d63a1b315dcf56a4c0dda3c0ca84ce3d6c87f&v=4 + url: https://github.com/whysage +Chake9928: + login: Chake9928 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/62596047?u=7aa2c0aad46911934ce3d22f83a895d05fa54e09&v=4 + url: https://github.com/Chake9928 +qaerial: + login: qaerial + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/41595550?v=4 + url: https://github.com/qaerial +bluefish6: + login: bluefish6 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/3324881?u=d107f6d0017927191644829fb845a8ceb8ac20ee&v=4 + url: https://github.com/bluefish6 +Sion99: + login: Sion99 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/82511301?v=4 + url: https://github.com/Sion99 +EpsilonRationes: + login: EpsilonRationes + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/148639079?v=4 + url: https://github.com/EpsilonRationes +SametEmin: + login: SametEmin + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/115692383?u=bda9052f698e50b0df6657fb9436d07e8496fe2f&v=4 + url: https://github.com/SametEmin +fhabers21: + login: fhabers21 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/58401847?v=4 + url: https://github.com/fhabers21 +kohiry: + login: kohiry + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/57669492?u=f6ab0a062740261e882879269a41a47788c84043&v=4 + url: https://github.com/kohiry +arynoot: + login: arynoot + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/73756088?v=4 + url: https://github.com/arynoot +GDemay: + login: GDemay + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/7033942?u=bbdcb4e2a67df4ec9caa2440362d8cebc44d65e8&v=4 + url: https://github.com/GDemay +maxscheijen: + login: maxscheijen + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/47034840?u=eb98f37882528ea349ca4e5255fa64ac3fef0294&v=4 + url: https://github.com/maxscheijen +celestywang: + login: celestywang + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/184830753?v=4 + url: https://github.com/celestywang +RyaWcksn: + login: RyaWcksn + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/42831964?u=0cb4265faf3e3425a89e59b6fddd3eb2de180af0&v=4 + url: https://github.com/RyaWcksn +Zerohertz: + login: Zerohertz + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/42334717?u=c6acda352c866b1747921e0ff8782b58571d849e&v=4 + url: https://github.com/Zerohertz +tienduong-21: + login: tienduong-21 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/80129618?v=4 + url: https://github.com/tienduong-21 +blaisep: + login: blaisep + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/254456?u=97d584b7c0a6faf583aa59975df4f993f671d121&v=4 + url: https://github.com/blaisep +SirTelemak: + login: SirTelemak + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/9435877?u=719327b7d2c4c62212456d771bfa7c6b8dbb9eac&v=4 + url: https://github.com/SirTelemak +ovezovs: + login: ovezovs + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/44060682?u=9cb4d738b15e64157cb65afbe2e31bd0c8f3f6e6&v=4 + url: https://github.com/ovezovs +neatek: + login: neatek + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/3075678?u=3001e778e4aa0bf6d3142d09f0b9d13b2c55066f&v=4 + url: https://github.com/neatek +sprytnyk: + login: sprytnyk + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/16718258?u=4893ea96bfebfbdbde8abd9e06851eca12b01bc9&v=4 + url: https://github.com/sprytnyk +wfpinedar: + login: wfpinedar + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/5309214?u=4af7b6b3907b015699a9994d0808137dd68f7658&v=4 + url: https://github.com/wfpinedar +italopenaforte: + login: italopenaforte + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/7786881?u=e64a8f24b1ba95eb82f283be8ab90892e40c5465&v=4 + url: https://github.com/italopenaforte +hackerneocom: + login: hackerneocom + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/67042948?u=ca365045bd261cec5a64059aa23cf80065148c3c&v=4 + url: https://github.com/hackerneocom +dmas-at-wiris: + login: dmas-at-wiris + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/24917162?u=0df147936a375b4b64232c650de31a227a6b59a0&v=4 + url: https://github.com/dmas-at-wiris +TorhamDev: + login: TorhamDev + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/87639984?u=07e5429fbd9c5d63c5ca55a0f31ef541216f0ce6&v=4 + url: https://github.com/TorhamDev +jaystone776: + login: jaystone776 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/11191137?u=299205a95e9b6817a43144a48b643346a5aac5cc&v=4 + url: https://github.com/jaystone776 +AaronDewes: + login: AaronDewes + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/67546953?v=4 + url: https://github.com/AaronDewes +kunansy: + login: kunansy + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/20476946?u=d8321cd00787d5ee29bfdd8ff6fde23ad783a581&v=4 + url: https://github.com/kunansy +TimorChow: + login: TimorChow + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/18365403?u=bcbb357be0a447bc682a161932eab5032cede4af&v=4 + url: https://github.com/TimorChow +ataberkciftlikli: + login: ataberkciftlikli + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/64265169?v=4 + url: https://github.com/ataberkciftlikli +leandrodesouzadev: + login: leandrodesouzadev + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/85115541?u=4eb25f43f1fe23727d61e986cf83b73b86e2a95a&v=4 + url: https://github.com/leandrodesouzadev +dutkiewicz: + login: dutkiewicz + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/6649846?u=e941be6e1ab2ffdf41cea227a73f0ffbef20628f&v=4 + url: https://github.com/dutkiewicz +mirusu400: + login: mirusu400 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/25397908?u=deda776115e4ee6f76fa526bb5127bd1a6c4b231&v=4 + url: https://github.com/mirusu400 +its0x08: + login: its0x08 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/15280042?u=d7c2058f29d4e8fbdae09b194e04c5e410350211&v=4 + url: https://github.com/its0x08 +lindsayzhou: + login: lindsayzhou + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/23748021?u=4db169ce262b69aa7292f82b785436544f69fb88&v=4 + url: https://github.com/lindsayzhou +0xflotus: + login: 0xflotus + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/26602940?u=3c52ce6393bb547c97e6380ccdee03e0c64152c6&v=4 + url: https://github.com/0xflotus +peacekimjapan: + login: peacekimjapan + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/33534175?u=e4219bcebc3773a7068cc34c3eb268ef77cec31b&v=4 + url: https://github.com/peacekimjapan +jonatasoli: + login: jonatasoli + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/26334101?u=071c062d2861d3dd127f6b4a5258cd8ef55d4c50&v=4 + url: https://github.com/jonatasoli +tyzh-dev: + login: tyzh-dev + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/51972581?u=ba3882da7c009918a8e2d6b9ead31c89f09c922d&v=4 + url: https://github.com/tyzh-dev +WaFeeAL: + login: WaFeeAL + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/45145188?u=db2de8c186073d95693279dcf085fcebffab57d0&v=4 + url: https://github.com/WaFeeAL +emp7yhead: + login: emp7yhead + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/20521260?u=9494c74cb9e1601d734b1f2726e292e257777d98&v=4 + url: https://github.com/emp7yhead +BartoszCki: + login: BartoszCki + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/17833351?u=40025e1182c32a9664834baec268dadad127703d&v=4 + url: https://github.com/BartoszCki +hakancelikdev: + login: hakancelikdev + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/19157033?u=095ea8e0af1de642edd92e5f806c70359e00c977&v=4 + url: https://github.com/hakancelikdev +KaterinaSolovyeva: + login: KaterinaSolovyeva + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/85114725?u=1fe81463cb6b1fd01ac047172fa4895e2a3cecaa&v=4 + url: https://github.com/KaterinaSolovyeva +zhanymkanov: + login: zhanymkanov + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/22341602?u=aa1c47285a4f5692d165ccb2a441c5553f23ef83&v=4 + url: https://github.com/zhanymkanov +felipebpl: + login: felipebpl + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/62957465?u=3c05f0f358b9575503c03122daefb115b6ac1414&v=4 + url: https://github.com/felipebpl +iudeen: + login: iudeen + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=f09cdd745e5bf16138f29b42732dd57c7f02bee1&v=4 + url: https://github.com/iudeen +dwisulfahnur: + login: dwisulfahnur + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/12431528?v=4 + url: https://github.com/dwisulfahnur +ayr-ton: + login: ayr-ton + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1090517?u=5cf70a0e0f0dbf084e074e494aa94d7c91a46ba6&v=4 + url: https://github.com/ayr-ton +raphaelauv: + login: raphaelauv + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/10202690?u=e6f86f5c0c3026a15d6b51792fa3e532b12f1371&v=4 + url: https://github.com/raphaelauv +Fahad-Md-Kamal: + login: Fahad-Md-Kamal + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/34704464?u=84abea85e59c30b2e3bc700ae42424f3fe704332&v=4 + url: https://github.com/Fahad-Md-Kamal +zxcq544: + login: zxcq544 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/5781268?u=25959ea03803742c3b28220b27fc07923a491dcb&v=4 + url: https://github.com/zxcq544 +AlexandrMaltsevYDX: + login: AlexandrMaltsevYDX + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/109986802?u=ed275d72bfcdb4d15abdd54e7be026adbb9ca098&v=4 + url: https://github.com/AlexandrMaltsevYDX +realFranco: + login: realFranco + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/45880759?u=22fea3007d3e2d4c8c82d6ccfbde71454c4c6dd8&v=4 + url: https://github.com/realFranco +piaria: + login: piaria + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/110835535?u=5af3d56254faa05bbca4258a46c5723489480f90&v=4 + url: https://github.com/piaria +mojtabapaso: + login: mojtabapaso + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/121169359?u=ced1d5ad673bcd9e949ebf967a4ab50185637443&v=4 + url: https://github.com/mojtabapaso +eghbalpoorMH: + login: eghbalpoorMH + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/36267498?v=4 + url: https://github.com/eghbalpoorMH +Tiazen: + login: Tiazen + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/16170159?u=0ce5e32f76e3f10733c8f25d97db9e31b753838c&v=4 + url: https://github.com/Tiazen +jfunez: + login: jfunez + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/805749?v=4 + url: https://github.com/jfunez +s-rigaud: + login: s-rigaud + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/46346622?u=eee0adaa9fdff9e312d52526fbd4020dd6860c27&v=4 + url: https://github.com/s-rigaud +Artem4es: + login: Artem4es + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/110793967?u=0f9d4e80e055adc1aa8b548e951f6b4989fa2e78&v=4 + url: https://github.com/Artem4es +sulemanhelp: + login: sulemanhelp + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/22400366?u=3e8e68750655c7f5b2e0ba1d54f5779ee526707d&v=4 + url: https://github.com/sulemanhelp +theRealNonso: + login: theRealNonso + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/29557286?u=6f062680edccfeb4c802daf3b1d8b2a9e21ae013&v=4 + url: https://github.com/theRealNonso +AhsanSheraz: + login: AhsanSheraz + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/51913596?u=08e31cacb3048be30722c94010ddd028f3fdbec4&v=4 + url: https://github.com/AhsanSheraz +HealerNguyen: + login: HealerNguyen + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/29653304?u=6ab095689054c63b1f4ceb26dd66847450225c87&v=4 + url: https://github.com/HealerNguyen +isulim: + login: isulim + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/30448496?u=44c47838defa48a16606b895dce08890fca8482f&v=4 + url: https://github.com/isulim +siavashyj: + login: siavashyj + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/43583410?u=562005ddc7901cd27a1219a118a2363817b14977&v=4 + url: https://github.com/siavashyj +DevSpace88: + login: DevSpace88 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/102557040?u=6b356e3e1b9b6bc6a208b363988d4089ef94193f&v=4 + url: https://github.com/DevSpace88 +Yum-git: + login: Yum-git + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/56100888?u=7c6ae21af081488b5fb703ab096fb1926025fd50&v=4 + url: https://github.com/Yum-git +oubush: + login: oubush + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/7489099?u=c86448bc61f5e7f03a1f14a768beeb09c33899d4&v=4 + url: https://github.com/oubush +KAZAMA-DREAM: + login: KAZAMA-DREAM + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/73453137?u=5108c757a3842733a448d9a16cdc65d82899eee1&v=4 + url: https://github.com/KAZAMA-DREAM +aprilcoskun: + login: aprilcoskun + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/17393603?u=18177d5bdba3a4567b8664587c882fb734e5fa09&v=4 + url: https://github.com/aprilcoskun +zhiquanchi: + login: zhiquanchi + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/29973289?u=744c74bc2635f839235ec32a0a934c5cef9a156d&v=4 + url: https://github.com/zhiquanchi +Jamim: + login: Jamim + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/5607572?u=0cf3027bec78ba4f0b89802430c136bc69847d7a&v=4 + url: https://github.com/Jamim +alvinkhalil: + login: alvinkhalil + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/84583022?u=ab0eeb9ce6ffe93fd9bb23daf782b9867b864149&v=4 + url: https://github.com/alvinkhalil +leylaeminova: + login: leylaeminova + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/100516839?u=35a9ce14bb86d7d7faa25d432f61dec2984cb818&v=4 + url: https://github.com/leylaeminova +UN-9BOT: + login: UN-9BOT + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/111110804?u=39e158937ed795972c2d0400fc521c50e9bfb9e7&v=4 + url: https://github.com/UN-9BOT +flasonme: + login: flasonme + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/30571019?v=4 + url: https://github.com/flasonme +ptt3199: + login: ptt3199 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/51350651?u=ccf51f8820787e17983954f26b06acf226cba293&v=4 + url: https://github.com/ptt3199 +gustavoprezoto: + login: gustavoprezoto + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/62812585?u=2e936a0c6a2f11ecf3a735ebd33386100bcfebf8&v=4 + url: https://github.com/gustavoprezoto +johnny630: + login: johnny630 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/2870590?v=4 + url: https://github.com/johnny630 +JCTrapero: + login: JCTrapero + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/109148166?u=bea607a04058176c4c2ae0d7c2e9ec647ccef002&v=4 + url: https://github.com/JCTrapero +ZhibangYue: + login: ZhibangYue + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/93324586?u=20fb23e3718e0364bb217966470d35e0637dd4fe&v=4 + url: https://github.com/ZhibangYue +saeye: + login: saeye + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/62229734?v=4 + url: https://github.com/saeye +Heumhub: + login: Heumhub + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/173761521?v=4 + url: https://github.com/Heumhub +logan2d5: + login: logan2d5 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/146642263?u=dbd6621f8b0330d6919f6a7131277b92e26fbe87&v=4 + url: https://github.com/logan2d5 +tiaggo16: + login: tiaggo16 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/62227573?u=359f4e2c51a4b13c8553ac5af405d635b07bb61f&v=4 + url: https://github.com/tiaggo16 +kiharito: + login: kiharito + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/38311245?v=4 + url: https://github.com/kiharito +J-Fuji: + login: J-Fuji + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/101452903?v=4 + url: https://github.com/J-Fuji diff --git a/docs/en/data/translators.yml b/docs/en/data/translators.yml new file mode 100644 index 000000000..9874afa56 --- /dev/null +++ b/docs/en/data/translators.yml @@ -0,0 +1,515 @@ +nilslindemann: + login: nilslindemann + count: 120 + avatarUrl: https://avatars.githubusercontent.com/u/6892179?u=1dca6a22195d6cd1ab20737c0e19a4c55d639472&v=4 + url: https://github.com/nilslindemann +jaystone776: + login: jaystone776 + count: 46 + avatarUrl: https://avatars.githubusercontent.com/u/11191137?u=299205a95e9b6817a43144a48b643346a5aac5cc&v=4 + url: https://github.com/jaystone776 +ceb10n: + login: ceb10n + count: 27 + avatarUrl: https://avatars.githubusercontent.com/u/235213?u=edcce471814a1eba9f0cdaa4cd0de18921a940a6&v=4 + url: https://github.com/ceb10n +tokusumi: + login: tokusumi + count: 23 + avatarUrl: https://avatars.githubusercontent.com/u/41147016?u=55010621aece725aa702270b54fed829b6a1fe60&v=4 + url: https://github.com/tokusumi +SwftAlpc: + login: SwftAlpc + count: 23 + avatarUrl: https://avatars.githubusercontent.com/u/52768429?u=6a3aa15277406520ad37f6236e89466ed44bc5b8&v=4 + url: https://github.com/SwftAlpc +hasansezertasan: + login: hasansezertasan + count: 22 + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan +waynerv: + login: waynerv + count: 20 + avatarUrl: https://avatars.githubusercontent.com/u/39515546?u=ec35139777597cdbbbddda29bf8b9d4396b429a9&v=4 + url: https://github.com/waynerv +AlertRED: + login: AlertRED + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/15695000?u=f5a4944c6df443030409c88da7d7fa0b7ead985c&v=4 + url: https://github.com/AlertRED +hard-coders: + login: hard-coders + count: 15 + avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4 + url: https://github.com/hard-coders +Joao-Pedro-P-Holanda: + login: Joao-Pedro-P-Holanda + count: 14 + avatarUrl: https://avatars.githubusercontent.com/u/110267046?u=331bd016326dac4cf3df4848f6db2dbbf8b5f978&v=4 + url: https://github.com/Joao-Pedro-P-Holanda +codingjenny: + login: codingjenny + count: 14 + avatarUrl: https://avatars.githubusercontent.com/u/103817302?u=3a042740dc0ff58615da0d8679230966fd7693e8&v=4 + url: https://github.com/codingjenny +valentinDruzhinin: + login: valentinDruzhinin + count: 14 + avatarUrl: https://avatars.githubusercontent.com/u/12831905?u=aae1ebc675c91e8fa582df4fcc4fc4128106344d&v=4 + url: https://github.com/valentinDruzhinin +Xewus: + login: Xewus + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4 + url: https://github.com/Xewus +Smlep: + login: Smlep + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/16785985?u=ffe99fa954c8e774ef1117e58d34aece92051e27&v=4 + url: https://github.com/Smlep +marcelomarkus: + login: marcelomarkus + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/20115018?u=dda090ce9160ef0cd2ff69b1e5ea741283425cba&v=4 + url: https://github.com/marcelomarkus +KaniKim: + login: KaniKim + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/19832624?u=296dbdd490e0eb96e3d45a2608c065603b17dc31&v=4 + url: https://github.com/KaniKim +Vincy1230: + login: Vincy1230 + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/81342412?u=ab5e256a4077a4a91f3f9cd2115ba80780454cbe&v=4 + url: https://github.com/Vincy1230 +Zhongheng-Cheng: + login: Zhongheng-Cheng + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/95612344?u=a0f7730a3cc7486827965e01a119ad610bda4b0a&v=4 + url: https://github.com/Zhongheng-Cheng +rjNemo: + login: rjNemo + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/56785022?u=d5c3a02567c8649e146fcfc51b6060ccaf8adef8&v=4 + url: https://github.com/rjNemo +xzmeng: + login: xzmeng + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/40202897?v=4 + url: https://github.com/xzmeng +pablocm83: + login: pablocm83 + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/28315068?u=3310fbb05bb8bfc50d2c48b6cb64ac9ee4a14549&v=4 + url: https://github.com/pablocm83 +batlopes: + login: batlopes + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/33462923?u=0fb3d7acb316764616f11e4947faf080e49ad8d9&v=4 + url: https://github.com/batlopes +lucasbalieiro: + login: lucasbalieiro + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/37416577?u=eabaf4aebbaa88a94a4886273edba689012cee70&v=4 + url: https://github.com/lucasbalieiro +Alexandrhub: + login: Alexandrhub + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/119126536?u=9fc0d48f3307817bafecc5861eb2168401a6cb04&v=4 + url: https://github.com/Alexandrhub +ptt3199: + login: ptt3199 + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/51350651?u=ccf51f8820787e17983954f26b06acf226cba293&v=4 + url: https://github.com/ptt3199 +Serrones: + login: Serrones + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/22691749?u=4795b880e13ca33a73e52fc0ef7dc9c60c8fce47&v=4 + url: https://github.com/Serrones +RunningIkkyu: + login: RunningIkkyu + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/31848542?u=494ecc298e3f26197495bb357ad0f57cfd5f7a32&v=4 + url: https://github.com/RunningIkkyu +Attsun1031: + login: Attsun1031 + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/1175560?v=4 + url: https://github.com/Attsun1031 +NinaHwang: + login: NinaHwang + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/79563565?u=241f2cb6d38a2d379536608a8ea5a22ed4b1a3ea&v=4 + url: https://github.com/NinaHwang +tiangolo: + login: tiangolo + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 + url: https://github.com/tiangolo +rostik1410: + login: rostik1410 + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/11443899?u=e26a635c2ba220467b308a326a579b8ccf4a8701&v=4 + url: https://github.com/rostik1410 +alv2017: + login: alv2017 + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 + url: https://github.com/alv2017 +komtaki: + login: komtaki + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/39375566?u=260ad6b1a4b34c07dbfa728da5e586f16f6d1824&v=4 + url: https://github.com/komtaki +JulianMaurin: + login: JulianMaurin + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/63545168?u=b7d15ac865268cbefc2d739e2f23d9aeeac1a622&v=4 + url: https://github.com/JulianMaurin +stlucasgarcia: + login: stlucasgarcia + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/61513630?u=c22d8850e9dc396a8820766a59837f967e14f9a0&v=4 + url: https://github.com/stlucasgarcia +ComicShrimp: + login: ComicShrimp + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=d2fbf412e7730183ce91686ca48d4147e1b7dc74&v=4 + url: https://github.com/ComicShrimp +BilalAlpaslan: + login: BilalAlpaslan + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/47563997?u=63ed66e304fe8d765762c70587d61d9196e5c82d&v=4 + url: https://github.com/BilalAlpaslan +axel584: + login: axel584 + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/1334088?u=9667041f5b15dc002b6f9665fda8c0412933ac04&v=4 + url: https://github.com/axel584 +tamtam-fitness: + login: tamtam-fitness + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/62091034?u=8da19a6bd3d02f5d6ba30c7247d5b46c98dd1403&v=4 + url: https://github.com/tamtam-fitness +Limsunoh: + login: Limsunoh + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/90311848?u=f456e0c5709fd50c8cd2898b551558eda14e5f21&v=4 + url: https://github.com/Limsunoh +kwang1215: + login: kwang1215 + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/74170199?u=2a63ff6692119dde3f5e5693365b9fcd6f977b08&v=4 + url: https://github.com/kwang1215 +jfunez: + login: jfunez + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/805749?v=4 + url: https://github.com/jfunez +ycd: + login: ycd + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=f1e7bae394a315da950912c92dc861a8eaf95d4c&v=4 + url: https://github.com/ycd +mariacamilagl: + login: mariacamilagl + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/11489395?u=4adb6986bf3debfc2b8216ae701f2bd47d73da7d&v=4 + url: https://github.com/mariacamilagl +maoyibo: + login: maoyibo + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/7887703?v=4 + url: https://github.com/maoyibo +blt232018: + login: blt232018 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/43393471?u=172b0e0391db1aa6c1706498d6dfcb003c8a4857&v=4 + url: https://github.com/blt232018 +magiskboy: + login: magiskboy + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/13352088?u=18b6d672523f9e9d98401f31dd50e28bb27d826f&v=4 + url: https://github.com/magiskboy +luccasmmg: + login: luccasmmg + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/11317382?u=65099a5a0d492b89119471f8a7014637cc2e04da&v=4 + url: https://github.com/luccasmmg +lbmendes: + login: lbmendes + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/80999926?u=646619e2f07ac5a7c3f65fe7834197461a4fff9f&v=4 + url: https://github.com/lbmendes +Zssaer: + login: Zssaer + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/45691504?u=4c0c195f25cb5ac6af32acfb0ab35427682938d2&v=4 + url: https://github.com/Zssaer +wdh99: + login: wdh99 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/108172295?u=8a8fb95d5afe3e0fa33257b2aecae88d436249eb&v=4 + url: https://github.com/wdh99 +ChuyuChoyeon: + login: ChuyuChoyeon + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/129537877?u=f0c76f3327817a8b86b422d62e04a34bf2827f2b&v=4 + url: https://github.com/ChuyuChoyeon +ivan-abc: + login: ivan-abc + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/36765187?u=c6e0ba571c1ccb6db9d94e62e4b8b5eda811a870&v=4 + url: https://github.com/ivan-abc +mojtabapaso: + login: mojtabapaso + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/121169359?u=ced1d5ad673bcd9e949ebf967a4ab50185637443&v=4 + url: https://github.com/mojtabapaso +hsuanchi: + login: hsuanchi + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/24913710?u=0b094ae292292fee093818e37ceb645c114d2bff&v=4 + url: https://github.com/hsuanchi +alejsdev: + login: alejsdev + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=356f39ff3f0211c720b06d3dbb060e98884085e3&v=4 + url: https://github.com/alejsdev +riroan: + login: riroan + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/33053284?u=2d18e3771506ee874b66d6aa2b3b1107fd95c38f&v=4 + url: https://github.com/riroan +nayeonkinn: + login: nayeonkinn + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/98254573?u=64a75ac99b320d4935eff8d1fceea9680fa07473&v=4 + url: https://github.com/nayeonkinn +pe-brian: + login: pe-brian + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/1783138?u=7e6242eb9e85bcf673fa88bbac9dd6dc3f03b1b5&v=4 + url: https://github.com/pe-brian +maxscheijen: + login: maxscheijen + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/47034840?u=eb98f37882528ea349ca4e5255fa64ac3fef0294&v=4 + url: https://github.com/maxscheijen +ilacftemp: + login: ilacftemp + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/159066669?v=4 + url: https://github.com/ilacftemp +devluisrodrigues: + login: devluisrodrigues + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/103431660?u=d9674a3249edc4601d2c712cdebf899918503c3a&v=4 + url: https://github.com/devluisrodrigues +devfernandoa: + login: devfernandoa + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/28360583?u=c4308abd62e8847c9e572e1bb9fe6b9dc9ef8e50&v=4 + url: https://github.com/devfernandoa +kim-sangah: + login: kim-sangah + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/173775778?v=4 + url: https://github.com/kim-sangah +9zimin9: + login: 9zimin9 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/174453744?v=4 + url: https://github.com/9zimin9 +nahyunkeem: + login: nahyunkeem + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/174440096?u=e12401d492eee58570f8914d0872b52e421a776e&v=4 + url: https://github.com/nahyunkeem +gerry-sabar: + login: gerry-sabar + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/1120123?v=4 + url: https://github.com/gerry-sabar +k94-ishi: + login: k94-ishi + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/32672580?u=bc7c5c07af0656be9fe4f1784a444af8d81ded89&v=4 + url: https://github.com/k94-ishi +Rishat-F: + login: Rishat-F + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/66554797?v=4 + url: https://github.com/Rishat-F +izaguerreiro: + login: izaguerreiro + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/2241504?v=4 + url: https://github.com/izaguerreiro +Xaraxx: + login: Xaraxx + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/29824698?u=dde2e233e22bb5ca1f8bb0c6e353ccd0d06e6066&v=4 + url: https://github.com/Xaraxx +sh0nk: + login: sh0nk + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/6478810?u=af15d724875cec682ed8088a86d36b2798f981c0&v=4 + url: https://github.com/sh0nk +dukkee: + login: dukkee + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/36825394?u=ccfd86e6a4f2d093dad6f7544cc875af67fa2df8&v=4 + url: https://github.com/dukkee +oandersonmagalhaes: + login: oandersonmagalhaes + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/83456692?v=4 + url: https://github.com/oandersonmagalhaes +leandrodesouzadev: + login: leandrodesouzadev + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/85115541?u=4eb25f43f1fe23727d61e986cf83b73b86e2a95a&v=4 + url: https://github.com/leandrodesouzadev +kty4119: + login: kty4119 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/49435654?v=4 + url: https://github.com/kty4119 +ASpathfinder: + login: ASpathfinder + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/31813636?u=2090bd1b7abb65cfeff0c618f99f11afa82c0548&v=4 + url: https://github.com/ASpathfinder +jujumilk3: + login: jujumilk3 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/41659814?u=538f7dfef03b59f25e43f10d59a31c19ef538a0c&v=4 + url: https://github.com/jujumilk3 +ayr-ton: + login: ayr-ton + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1090517?u=5cf70a0e0f0dbf084e074e494aa94d7c91a46ba6&v=4 + url: https://github.com/ayr-ton +KdHyeon0661: + login: KdHyeon0661 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/20253352?u=5ae1aae34b091a39f22cbe60a02b79dcbdbea031&v=4 + url: https://github.com/KdHyeon0661 +LorhanSohaky: + login: LorhanSohaky + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/16273730?u=095b66f243a2cd6a0aadba9a095009f8aaf18393&v=4 + url: https://github.com/LorhanSohaky +cfraboulet: + login: cfraboulet + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/62244267?u=ed0e286ba48fa1dafd64a08e50f3364b8e12df34&v=4 + url: https://github.com/cfraboulet +dedkot01: + login: dedkot01 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/26196675?u=e2966887124e67932853df4f10f86cb526edc7b0&v=4 + url: https://github.com/dedkot01 +AGolicyn: + login: AGolicyn + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/86262613?u=3c21606ab8d210a061a1673decff1e7d5592b380&v=4 + url: https://github.com/AGolicyn +fhabers21: + login: fhabers21 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/58401847?v=4 + url: https://github.com/fhabers21 +TabarakoAkula: + login: TabarakoAkula + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/113298631?u=add801e370dbc502cd94ce6d3484760d7fef5406&v=4 + url: https://github.com/TabarakoAkula +AhsanSheraz: + login: AhsanSheraz + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/51913596?u=08e31cacb3048be30722c94010ddd028f3fdbec4&v=4 + url: https://github.com/AhsanSheraz +ArtemKhymenko: + login: ArtemKhymenko + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/14346625?u=f2fa553d9e5ec5e0f05d66bd649f7be347169631&v=4 + url: https://github.com/ArtemKhymenko +hasnatsajid: + login: hasnatsajid + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/86589885?u=49958789e6385be624f2c6a55a860c599eb05e2c&v=4 + url: https://github.com/hasnatsajid +alperiox: + login: alperiox + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/34214152?u=2c5acad3461d4dbc2d48371ba86cac56ae9b25cc&v=4 + url: https://github.com/alperiox +emrhnsyts: + login: emrhnsyts + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/42899027?u=ad26798e3f8feed2041c5dd5f87e58933d6c3283&v=4 + url: https://github.com/emrhnsyts +vusallyv: + login: vusallyv + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/85983771?u=53a7b755cb338d9313966dbf2e4e68b512565186&v=4 + url: https://github.com/vusallyv +jackleeio: + login: jackleeio + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/20477587?u=c5184dab6d021733d10c8f975b20e391856303d6&v=4 + url: https://github.com/jackleeio +choi-haram: + login: choi-haram + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/62204475?v=4 + url: https://github.com/choi-haram +imtiaz101325: + login: imtiaz101325 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/54007087?u=194d972b501b9ea9d2ddeaed757c492936e0121a&v=4 + url: https://github.com/imtiaz101325 +waketzheng: + login: waketzheng + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/35413830?u=df19e4fd5bb928e7d086e053ef26a46aad23bf84&v=4 + url: https://github.com/waketzheng +billzhong: + login: billzhong + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1644011?v=4 + url: https://github.com/billzhong +chaoless: + login: chaoless + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/64477804?v=4 + url: https://github.com/chaoless +logan2d5: + login: logan2d5 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/146642263?u=dbd6621f8b0330d6919f6a7131277b92e26fbe87&v=4 + url: https://github.com/logan2d5 +andersonrocha0: + login: andersonrocha0 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/22346169?u=93a1359c8c5461d894802c0cc65bcd09217e7a02&v=4 + url: https://github.com/andersonrocha0 +saeye: + login: saeye + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/62229734?v=4 + url: https://github.com/saeye +timothy-jeong: + login: timothy-jeong + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/53824764?u=db3d0cea2f5fab64d810113c5039a369699a2774&v=4 + url: https://github.com/timothy-jeong +11kkw: + login: 11kkw + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/21125286?v=4 + url: https://github.com/11kkw diff --git a/docs/en/docs/advanced/additional-responses.md b/docs/en/docs/advanced/additional-responses.md index 41b39c18e..03d48c2a7 100644 --- a/docs/en/docs/advanced/additional-responses.md +++ b/docs/en/docs/advanced/additional-responses.md @@ -1,9 +1,12 @@ # Additional Responses in OpenAPI -!!! warning - This is a rather advanced topic. +/// warning - If you are starting with **FastAPI**, you might not need this. +This is a rather advanced topic. + +If you are starting with **FastAPI**, you might not need this. + +/// You can declare additional responses, with additional status codes, media types, descriptions, etc. @@ -15,7 +18,7 @@ But for those additional responses you have to make sure you return a `Response` You can pass to your *path operation decorators* a parameter `responses`. -It receives a `dict`, the keys are status codes for each response, like `200`, and the values are other `dict`s with the information for each of them. +It receives a `dict`: the keys are status codes for each response (like `200`), and the values are other `dict`s with the information for each of them. Each of those response `dict`s can have a key `model`, containing a Pydantic model, just like `response_model`. @@ -23,24 +26,28 @@ Each of those response `dict`s can have a key `model`, containing a Pydantic mod For example, to declare another response with a status code `404` and a Pydantic model `Message`, you can write: -```Python hl_lines="18 22" -{!../../../docs_src/additional_responses/tutorial001.py!} -``` +{* ../../docs_src/additional_responses/tutorial001.py hl[18,22] *} + +/// note + +Keep in mind that you have to return the `JSONResponse` directly. + +/// + +/// info -!!! note - Keep in mind that you have to return the `JSONResponse` directly. +The `model` key is not part of OpenAPI. -!!! info - The `model` key is not part of OpenAPI. +**FastAPI** will take the Pydantic model from there, generate the JSON Schema, and put it in the correct place. - **FastAPI** will take the Pydantic model from there, generate the `JSON Schema`, and put it in the correct place. +The correct place is: - The correct place is: +* In the key `content`, that has as value another JSON object (`dict`) that contains: + * A key with the media type, e.g. `application/json`, that contains as value another JSON object, that contains: + * A key `schema`, that has as the value the JSON Schema from the model, here's the correct place. + * **FastAPI** adds a reference here to the global JSON Schemas in another place in your OpenAPI instead of including it directly. This way, other applications and clients can use those JSON Schemas directly, provide better code generation tools, etc. - * In the key `content`, that has as value another JSON object (`dict`) that contains: - * A key with the media type, e.g. `application/json`, that contains as value another JSON object, that contains: - * A key `schema`, that has as the value the JSON Schema from the model, here's the correct place. - * **FastAPI** adds a reference here to the global JSON Schemas in another place in your OpenAPI instead of including it directly. This way, other applications and clients can use those JSON Schemas directly, provide better code generation tools, etc. +/// The generated responses in the OpenAPI for this *path operation* will be: @@ -168,17 +175,21 @@ You can use this same `responses` parameter to add different media types for the For example, you can add an additional media type of `image/png`, declaring that your *path operation* can return a JSON object (with media type `application/json`) or a PNG image: -```Python hl_lines="19-24 28" -{!../../../docs_src/additional_responses/tutorial002.py!} -``` +{* ../../docs_src/additional_responses/tutorial002.py hl[19:24,28] *} + +/// note + +Notice that you have to return the image using a `FileResponse` directly. + +/// -!!! note - Notice that you have to return the image using a `FileResponse` directly. +/// info -!!! info - Unless you specify a different media type explicitly in your `responses` parameter, FastAPI will assume the response has the same media type as the main response class (default `application/json`). +Unless you specify a different media type explicitly in your `responses` parameter, FastAPI will assume the response has the same media type as the main response class (default `application/json`). - But if you have specified a custom response class with `None` as its media type, FastAPI will use `application/json` for any additional response that has an associated model. +But if you have specified a custom response class with `None` as its media type, FastAPI will use `application/json` for any additional response that has an associated model. + +/// ## Combining information @@ -192,9 +203,7 @@ For example, you can declare a response with a status code `404` that uses a Pyd And a response with a status code `200` that uses your `response_model`, but includes a custom `example`: -```Python hl_lines="20-31" -{!../../../docs_src/additional_responses/tutorial003.py!} -``` +{* ../../docs_src/additional_responses/tutorial003.py hl[20:31] *} It will all be combined and included in your OpenAPI, and shown in the API docs: @@ -224,17 +233,15 @@ Here, `new_dict` will contain all the key-value pairs from `old_dict` plus the n } ``` -You can use that technique to re-use some predefined responses in your *path operations* and combine them with additional custom ones. +You can use that technique to reuse some predefined responses in your *path operations* and combine them with additional custom ones. For example: -```Python hl_lines="13-17 26" -{!../../../docs_src/additional_responses/tutorial004.py!} -``` +{* ../../docs_src/additional_responses/tutorial004.py hl[13:17,26] *} ## More information about OpenAPI responses To see what exactly you can include in the responses, you can check these sections in the OpenAPI specification: -* OpenAPI Responses Object, it includes the `Response Object`. -* OpenAPI Response Object, you can include anything from this directly in each response inside your `responses` parameter. Including `description`, `headers`, `content` (inside of this is that you declare different media types and JSON Schemas), and `links`. +* OpenAPI Responses Object, it includes the `Response Object`. +* OpenAPI Response Object, you can include anything from this directly in each response inside your `responses` parameter. Including `description`, `headers`, `content` (inside of this is that you declare different media types and JSON Schemas), and `links`. diff --git a/docs/en/docs/advanced/additional-status-codes.md b/docs/en/docs/advanced/additional-status-codes.md index 0ce275343..077a00488 100644 --- a/docs/en/docs/advanced/additional-status-codes.md +++ b/docs/en/docs/advanced/additional-status-codes.md @@ -14,53 +14,25 @@ But you also want it to accept new items. And when the items didn't exist before To achieve that, import `JSONResponse`, and return your content there directly, setting the `status_code` that you want: -=== "Python 3.10+" +{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *} - ```Python hl_lines="4 25" - {!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!} - ``` +/// warning -=== "Python 3.9+" +When you return a `Response` directly, like in the example above, it will be returned directly. - ```Python hl_lines="4 25" - {!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!} - ``` +It won't be serialized with a model, etc. -=== "Python 3.8+" +Make sure it has the data you want it to have, and that the values are valid JSON (if you are using `JSONResponse`). - ```Python hl_lines="4 26" - {!> ../../../docs_src/additional_status_codes/tutorial001_an.py!} - ``` +/// -=== "Python 3.10+ non-Annotated" +/// note | Technical Details - !!! tip - Prefer to use the `Annotated` version if possible. +You could also use `from starlette.responses import JSONResponse`. - ```Python hl_lines="2 23" - {!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!} - ``` +**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `status`. -=== "Python 3.8+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="4 25" - {!> ../../../docs_src/additional_status_codes/tutorial001.py!} - ``` - -!!! warning - When you return a `Response` directly, like in the example above, it will be returned directly. - - It won't be serialized with a model, etc. - - Make sure it has the data you want it to have, and that the values are valid JSON (if you are using `JSONResponse`). - -!!! note "Technical Details" - You could also use `from starlette.responses import JSONResponse`. - - **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `status`. +/// ## OpenAPI and API docs diff --git a/docs/en/docs/advanced/advanced-dependencies.md b/docs/en/docs/advanced/advanced-dependencies.md index 0cffab56d..f933fd264 100644 --- a/docs/en/docs/advanced/advanced-dependencies.md +++ b/docs/en/docs/advanced/advanced-dependencies.md @@ -18,26 +18,7 @@ Not the class itself (which is already a callable), but an instance of that clas To do that, we declare a method `__call__`: -=== "Python 3.9+" - - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[12] *} In this case, this `__call__` is what **FastAPI** will use to check for additional parameters and sub-dependencies, and this is what will be called to pass a value to the parameter in your *path operation function* later. @@ -45,26 +26,7 @@ In this case, this `__call__` is what **FastAPI** will use to check for addition And now, we can use `__init__` to declare the parameters of the instance that we can use to "parameterize" the dependency: -=== "Python 3.9+" - - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="8" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="7" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[9] *} In this case, **FastAPI** won't ever touch or care about `__init__`, we will use it directly in our code. @@ -72,26 +34,7 @@ In this case, **FastAPI** won't ever touch or care about `__init__`, we will use We could create an instance of this class with: -=== "Python 3.9+" - - ```Python hl_lines="18" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="16" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[18] *} And that way we are able to "parameterize" our dependency, that now has `"bar"` inside of it, as the attribute `checker.fixed_content`. @@ -107,32 +50,16 @@ checker(q="somequery") ...and pass whatever that returns as the value of the dependency in our *path operation function* as the parameter `fixed_content_included`: -=== "Python 3.9+" - - ```Python hl_lines="22" - {!> ../../../docs_src/dependencies/tutorial011_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="21" - {!> ../../../docs_src/dependencies/tutorial011_an.py!} - ``` - -=== "Python 3.8+ non-Annotated" +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[22] *} - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial011.py!} - ``` +All this might seem contrived. And it might not be very clear how is it useful yet. -!!! tip - All this might seem contrived. And it might not be very clear how is it useful yet. +These examples are intentionally simple, but show how it all works. - These examples are intentionally simple, but show how it all works. +In the chapters about security, there are utility functions that are implemented in this same way. - In the chapters about security, there are utility functions that are implemented in this same way. +If you understood all this, you already know how those utility tools for security work underneath. - If you understood all this, you already know how those utility tools for security work underneath. +/// diff --git a/docs/en/docs/advanced/async-tests.md b/docs/en/docs/advanced/async-tests.md index f9c82e6ab..8d6929222 100644 --- a/docs/en/docs/advanced/async-tests.md +++ b/docs/en/docs/advanced/async-tests.md @@ -32,15 +32,11 @@ For a simple example, let's consider a file structure similar to the one describ The file `main.py` would have: -```Python -{!../../../docs_src/async_tests/main.py!} -``` +{* ../../docs_src/async_tests/main.py *} The file `test_main.py` would have the tests for `main.py`, it could look like this now: -```Python -{!../../../docs_src/async_tests/test_main.py!} -``` +{* ../../docs_src/async_tests/test_main.py *} ## Run it @@ -60,18 +56,17 @@ $ pytest The marker `@pytest.mark.anyio` tells pytest that this test function should be called asynchronously: -```Python hl_lines="7" -{!../../../docs_src/async_tests/test_main.py!} -``` +{* ../../docs_src/async_tests/test_main.py hl[7] *} + +/// tip + +Note that the test function is now `async def` instead of just `def` as before when using the `TestClient`. -!!! tip - Note that the test function is now `async def` instead of just `def` as before when using the `TestClient`. +/// Then we can create an `AsyncClient` with the app, and send async requests to it, using `await`. -```Python hl_lines="9-10" -{!../../../docs_src/async_tests/test_main.py!} -``` +{* ../../docs_src/async_tests/test_main.py hl[9:12] *} This is the equivalent to: @@ -81,15 +76,24 @@ response = client.get('/') ...that we used to make our requests with the `TestClient`. -!!! tip - Note that we're using async/await with the new `AsyncClient` - the request is asynchronous. +/// tip + +Note that we're using async/await with the new `AsyncClient` - the request is asynchronous. + +/// + +/// warning -!!! warning - If your application relies on lifespan events, the `AsyncClient` won't trigger these events. To ensure they are triggered, use `LifespanManager` from florimondmanca/asgi-lifespan. +If your application relies on lifespan events, the `AsyncClient` won't trigger these events. To ensure they are triggered, use `LifespanManager` from florimondmanca/asgi-lifespan. + +/// ## Other Asynchronous Function Calls As the testing function is now asynchronous, you can now also call (and `await`) other `async` functions apart from sending requests to your FastAPI application in your tests, exactly as you would call them anywhere else in your code. -!!! tip - If you encounter a `RuntimeError: Task attached to a different loop` when integrating asynchronous function calls in your tests (e.g. when using MongoDB's MotorClient) Remember to instantiate objects that need an event loop only within async functions, e.g. an `'@app.on_event("startup")` callback. +/// tip + +If you encounter a `RuntimeError: Task attached to a different loop` when integrating asynchronous function calls in your tests (e.g. when using MongoDB's MotorClient), remember to instantiate objects that need an event loop only within async functions, e.g. an `'@app.on_event("startup")` callback. + +/// diff --git a/docs/en/docs/advanced/behind-a-proxy.md b/docs/en/docs/advanced/behind-a-proxy.md index 01998cc91..1f0d0fd9f 100644 --- a/docs/en/docs/advanced/behind-a-proxy.md +++ b/docs/en/docs/advanced/behind-a-proxy.md @@ -18,7 +18,9 @@ In this case, the original path `/app` would actually be served at `/api/v1/app` Even though all your code is written assuming there's just `/app`. -And the proxy would be **"stripping"** the **path prefix** on the fly before transmitting the request to Uvicorn, keep your application convinced that it is serving at `/app`, so that you don't have to update all your code to include the prefix `/api/v1`. +{* ../../docs_src/behind_a_proxy/tutorial001.py hl[6] *} + +And the proxy would be **"stripping"** the **path prefix** on the fly before transmitting the request to the app server (probably Uvicorn via FastAPI CLI), keeping your application convinced that it is being served at `/app`, so that you don't have to update all your code to include the prefix `/api/v1`. Up to here, everything would work as normally. @@ -39,8 +41,11 @@ browser --> proxy proxy --> server ``` -!!! tip - The IP `0.0.0.0` is commonly used to mean that the program listens on all the IPs available in that machine/server. +/// tip + +The IP `0.0.0.0` is commonly used to mean that the program listens on all the IPs available in that machine/server. + +/// The docs UI would also need the OpenAPI schema to declare that this API `server` is located at `/api/v1` (behind the proxy). For example: @@ -59,7 +64,7 @@ The docs UI would also need the OpenAPI schema to declare that this API `server` } ``` -In this example, the "Proxy" could be something like **Traefik**. And the server would be something like **Uvicorn**, running your FastAPI application. +In this example, the "Proxy" could be something like **Traefik**. And the server would be something like FastAPI CLI with **Uvicorn**, running your FastAPI application. ### Providing the `root_path` @@ -68,7 +73,7 @@ To achieve this, you can use the command line option `--root-path` like:
```console -$ uvicorn main:app --root-path /api/v1 +$ fastapi run main.py --root-path /api/v1 INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` @@ -77,10 +82,13 @@ $ uvicorn main:app --root-path /api/v1 If you use Hypercorn, it also has the option `--root-path`. -!!! note "Technical Details" - The ASGI specification defines a `root_path` for this use case. +/// note | Technical Details + +The ASGI specification defines a `root_path` for this use case. + +And the `--root-path` command line option provides that `root_path`. - And the `--root-path` command line option provides that `root_path`. +/// ### Checking the current `root_path` @@ -88,16 +96,14 @@ You can get the current `root_path` used by your application for each request, i Here we are including it in the message just for demonstration purposes. -```Python hl_lines="8" -{!../../../docs_src/behind_a_proxy/tutorial001.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial001.py hl[8] *} Then, if you start Uvicorn with:
```console -$ uvicorn main:app --root-path /api/v1 +$ fastapi run main.py --root-path /api/v1 INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` @@ -117,9 +123,7 @@ The response would be something like: Alternatively, if you don't have a way to provide a command line option like `--root-path` or equivalent, you can set the `root_path` parameter when creating your FastAPI app: -```Python hl_lines="3" -{!../../../docs_src/behind_a_proxy/tutorial002.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial002.py hl[3] *} Passing the `root_path` to `FastAPI` would be the equivalent of passing the `--root-path` command line option to Uvicorn or Hypercorn. @@ -168,8 +172,11 @@ Then create a file `traefik.toml` with: This tells Traefik to listen on port 9999 and to use another file `routes.toml`. -!!! tip - We are using port 9999 instead of the standard HTTP port 80 so that you don't have to run it with admin (`sudo`) privileges. +/// tip + +We are using port 9999 instead of the standard HTTP port 80 so that you don't have to run it with admin (`sudo`) privileges. + +/// Now create that other file `routes.toml`: @@ -198,7 +205,7 @@ Now create that other file `routes.toml`: This file configures Traefik to use the path prefix `/api/v1`. -And then it will redirect its requests to your Uvicorn running on `http://127.0.0.1:8000`. +And then Traefik will redirect its requests to your Uvicorn running on `http://127.0.0.1:8000`. Now start Traefik: @@ -212,12 +219,12 @@ INFO[0000] Configuration loaded from file: /home/user/awesomeapi/traefik.toml
-And now start your app with Uvicorn, using the `--root-path` option: +And now start your app, using the `--root-path` option:
```console -$ uvicorn main:app --root-path /api/v1 +$ fastapi run main.py --root-path /api/v1 INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` @@ -235,8 +242,11 @@ Now, if you go to the URL with the port for Uvicorn: http://127.0.0.1:9999/api/v1/app. @@ -279,20 +289,21 @@ This is because FastAPI uses this `root_path` to create the default `server` in ## Additional servers -!!! warning - This is a more advanced use case. Feel free to skip it. +/// warning + +This is a more advanced use case. Feel free to skip it. + +/// By default, **FastAPI** will create a `server` in the OpenAPI schema with the URL for the `root_path`. -But you can also provide other alternative `servers`, for example if you want *the same* docs UI to interact with a staging and production environments. +But you can also provide other alternative `servers`, for example if you want *the same* docs UI to interact with both a staging and a production environment. If you pass a custom list of `servers` and there's a `root_path` (because your API lives behind a proxy), **FastAPI** will insert a "server" with this `root_path` at the beginning of the list. For example: -```Python hl_lines="4-7" -{!../../../docs_src/behind_a_proxy/tutorial003.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial003.py hl[4:7] *} Will generate an OpenAPI schema like: @@ -319,28 +330,32 @@ Will generate an OpenAPI schema like: } ``` -!!! tip - Notice the auto-generated server with a `url` value of `/api/v1`, taken from the `root_path`. +/// tip + +Notice the auto-generated server with a `url` value of `/api/v1`, taken from the `root_path`. + +/// In the docs UI at http://127.0.0.1:9999/api/v1/docs it would look like: -!!! tip - The docs UI will interact with the server that you select. +/// tip + +The docs UI will interact with the server that you select. + +/// ### Disable automatic server from `root_path` If you don't want **FastAPI** to include an automatic server using the `root_path`, you can use the parameter `root_path_in_servers=False`: -```Python hl_lines="9" -{!../../../docs_src/behind_a_proxy/tutorial004.py!} -``` +{* ../../docs_src/behind_a_proxy/tutorial004.py hl[9] *} and then it won't include it in the OpenAPI schema. ## Mounting a sub-application -If you need to mount a sub-application (as described in [Sub Applications - Mounts](./sub-applications.md){.internal-link target=_blank}) while also using a proxy with `root_path`, you can do it normally, as you would expect. +If you need to mount a sub-application (as described in [Sub Applications - Mounts](sub-applications.md){.internal-link target=_blank}) while also using a proxy with `root_path`, you can do it normally, as you would expect. FastAPI will internally use the `root_path` smartly, so it will just work. ✨ diff --git a/docs/en/docs/advanced/custom-response.md b/docs/en/docs/advanced/custom-response.md index 827776f5e..8268dd81a 100644 --- a/docs/en/docs/advanced/custom-response.md +++ b/docs/en/docs/advanced/custom-response.md @@ -4,16 +4,19 @@ By default, **FastAPI** will return the responses using `JSONResponse`. You can override it by returning a `Response` directly as seen in [Return a Response directly](response-directly.md){.internal-link target=_blank}. -But if you return a `Response` directly, the data won't be automatically converted, and the documentation won't be automatically generated (for example, including the specific "media type", in the HTTP header `Content-Type` as part of the generated OpenAPI). +But if you return a `Response` directly (or any subclass, like `JSONResponse`), the data won't be automatically converted (even if you declare a `response_model`), and the documentation won't be automatically generated (for example, including the specific "media type", in the HTTP header `Content-Type` as part of the generated OpenAPI). -But you can also declare the `Response` that you want to be used, in the *path operation decorator*. +But you can also declare the `Response` that you want to be used (e.g. any `Response` subclass), in the *path operation decorator* using the `response_class` parameter. The contents that you return from your *path operation function* will be put inside of that `Response`. And if that `Response` has a JSON media type (`application/json`), like is the case with the `JSONResponse` and `UJSONResponse`, the data you return will be automatically converted (and filtered) with any Pydantic `response_model` that you declared in the *path operation decorator*. -!!! note - If you use a response class with no media type, FastAPI will expect your response to have no content, so it will not document the response format in its generated OpenAPI docs. +/// note + +If you use a response class with no media type, FastAPI will expect your response to have no content, so it will not document the response format in its generated OpenAPI docs. + +/// ## Use `ORJSONResponse` @@ -23,23 +26,27 @@ Import the `Response` class (sub-class) you want to use and declare it in the *p For large responses, returning a `Response` directly is much faster than returning a dictionary. -This is because by default, FastAPI will inspect every item inside and make sure it is serializable with JSON, using the same [JSON Compatible Encoder](../tutorial/encoder.md){.internal-link target=_blank} explained in the tutorial. This is what allows you to return **arbitrary objects**, for example database models. +This is because by default, FastAPI will inspect every item inside and make sure it is serializable as JSON, using the same [JSON Compatible Encoder](../tutorial/encoder.md){.internal-link target=_blank} explained in the tutorial. This is what allows you to return **arbitrary objects**, for example database models. But if you are certain that the content that you are returning is **serializable with JSON**, you can pass it directly to the response class and avoid the extra overhead that FastAPI would have by passing your return content through the `jsonable_encoder` before passing it to the response class. -```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial001b.py!} -``` +{* ../../docs_src/custom_response/tutorial001b.py hl[2,7] *} + +/// info + +The parameter `response_class` will also be used to define the "media type" of the response. + +In this case, the HTTP header `Content-Type` will be set to `application/json`. -!!! info - The parameter `response_class` will also be used to define the "media type" of the response. +And it will be documented as such in OpenAPI. - In this case, the HTTP header `Content-Type` will be set to `application/json`. +/// - And it will be documented as such in OpenAPI. +/// tip -!!! tip - The `ORJSONResponse` is currently only available in FastAPI, not in Starlette. +The `ORJSONResponse` is only available in FastAPI, not in Starlette. + +/// ## HTML Response @@ -48,16 +55,17 @@ To return a response with HTML directly from **FastAPI**, use `HTMLResponse`. * Import `HTMLResponse`. * Pass `HTMLResponse` as the parameter `response_class` of your *path operation decorator*. -```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial002.py!} -``` +{* ../../docs_src/custom_response/tutorial002.py hl[2,7] *} + +/// info -!!! info - The parameter `response_class` will also be used to define the "media type" of the response. +The parameter `response_class` will also be used to define the "media type" of the response. - In this case, the HTTP header `Content-Type` will be set to `text/html`. +In this case, the HTTP header `Content-Type` will be set to `text/html`. - And it will be documented as such in OpenAPI. +And it will be documented as such in OpenAPI. + +/// ### Return a `Response` @@ -65,15 +73,19 @@ As seen in [Return a Response directly](response-directly.md){.internal-link tar The same example from above, returning an `HTMLResponse`, could look like: -```Python hl_lines="2 7 19" -{!../../../docs_src/custom_response/tutorial003.py!} -``` +{* ../../docs_src/custom_response/tutorial003.py hl[2,7,19] *} -!!! warning - A `Response` returned directly by your *path operation function* won't be documented in OpenAPI (for example, the `Content-Type` won't be documented) and won't be visible in the automatic interactive docs. +/// warning -!!! info - Of course, the actual `Content-Type` header, status code, etc, will come from the `Response` object your returned. +A `Response` returned directly by your *path operation function* won't be documented in OpenAPI (for example, the `Content-Type` won't be documented) and won't be visible in the automatic interactive docs. + +/// + +/// info + +Of course, the actual `Content-Type` header, status code, etc, will come from the `Response` object you returned. + +/// ### Document in OpenAPI and override `Response` @@ -85,9 +97,7 @@ The `response_class` will then be used only to document the OpenAPI *path operat For example, it could be something like: -```Python hl_lines="7 21 23" -{!../../../docs_src/custom_response/tutorial004.py!} -``` +{* ../../docs_src/custom_response/tutorial004.py hl[7,21,23] *} In this example, the function `generate_html_response()` already generates and returns a `Response` instead of returning the HTML in a `str`. @@ -103,10 +113,13 @@ Here are some of the available responses. Keep in mind that you can use `Response` to return anything else, or even create a custom sub-class. -!!! note "Technical Details" - You could also use `from starlette.responses import HTMLResponse`. +/// note | Technical Details + +You could also use `from starlette.responses import HTMLResponse`. - **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. +**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. + +/// ### `Response` @@ -121,11 +134,9 @@ It accepts the following parameters: * `headers` - A `dict` of strings. * `media_type` - A `str` giving the media type. E.g. `"text/html"`. -FastAPI (actually Starlette) will automatically include a Content-Length header. It will also include a Content-Type header, based on the media_type and appending a charset for text types. +FastAPI (actually Starlette) will automatically include a Content-Length header. It will also include a Content-Type header, based on the `media_type` and appending a charset for text types. -```Python hl_lines="1 18" -{!../../../docs_src/response_directly/tutorial002.py!} -``` +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} ### `HTMLResponse` @@ -133,11 +144,9 @@ Takes some text or bytes and returns an HTML response, as you read above. ### `PlainTextResponse` -Takes some text or bytes and returns an plain text response. +Takes some text or bytes and returns a plain text response. -```Python hl_lines="2 7 9" -{!../../../docs_src/custom_response/tutorial005.py!} -``` +{* ../../docs_src/custom_response/tutorial005.py hl[2,7,9] *} ### `JSONResponse` @@ -149,19 +158,35 @@ This is the default response used in **FastAPI**, as you read above. A fast alternative JSON response using `orjson`, as you read above. +/// info + +This requires installing `orjson` for example with `pip install orjson`. + +/// + ### `UJSONResponse` An alternative JSON response using `ujson`. -!!! warning - `ujson` is less careful than Python's built-in implementation in how it handles some edge-cases. +/// info -```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial001.py!} -``` +This requires installing `ujson` for example with `pip install ujson`. + +/// + +/// warning + +`ujson` is less careful than Python's built-in implementation in how it handles some edge-cases. + +/// -!!! tip - It's possible that `ORJSONResponse` might be a faster alternative. +{* ../../docs_src/custom_response/tutorial001.py hl[2,7] *} + +/// tip + +It's possible that `ORJSONResponse` might be a faster alternative. + +/// ### `RedirectResponse` @@ -169,18 +194,14 @@ Returns an HTTP redirect. Uses a 307 status code (Temporary Redirect) by default You can return a `RedirectResponse` directly: -```Python hl_lines="2 9" -{!../../../docs_src/custom_response/tutorial006.py!} -``` +{* ../../docs_src/custom_response/tutorial006.py hl[2,9] *} --- Or you can use it in the `response_class` parameter: -```Python hl_lines="2 7 9" -{!../../../docs_src/custom_response/tutorial006b.py!} -``` +{* ../../docs_src/custom_response/tutorial006b.py hl[2,7,9] *} If you do that, then you can return the URL directly from your *path operation* function. @@ -190,17 +211,13 @@ In this case, the `status_code` used will be the default one for the `RedirectRe You can also use the `status_code` parameter combined with the `response_class` parameter: -```Python hl_lines="2 7 9" -{!../../../docs_src/custom_response/tutorial006c.py!} -``` +{* ../../docs_src/custom_response/tutorial006c.py hl[2,7,9] *} ### `StreamingResponse` Takes an async generator or a normal generator/iterator and streams the response body. -```Python hl_lines="2 14" -{!../../../docs_src/custom_response/tutorial007.py!} -``` +{* ../../docs_src/custom_response/tutorial007.py hl[2,14] *} #### Using `StreamingResponse` with file-like objects @@ -210,20 +227,21 @@ That way, you don't have to read it all first in memory, and you can pass that g This includes many libraries to interact with cloud storage, video processing, and others. -```{ .python .annotate hl_lines="2 10-12 14" } -{!../../../docs_src/custom_response/tutorial008.py!} -``` +{* ../../docs_src/custom_response/tutorial008.py hl[2,10:12,14] *} 1. This is the generator function. It's a "generator function" because it contains `yield` statements inside. 2. By using a `with` block, we make sure that the file-like object is closed after the generator function is done. So, after it finishes sending the response. -3. This `yield from` tells the function to iterate over that thing named `file_like`. And then, for each part iterated, yield that part as coming from this generator function. +3. This `yield from` tells the function to iterate over that thing named `file_like`. And then, for each part iterated, yield that part as coming from this generator function (`iterfile`). So, it is a generator function that transfers the "generating" work to something else internally. - By doing it this way, we can put it in a `with` block, and that way, ensure that it is closed after finishing. + By doing it this way, we can put it in a `with` block, and that way, ensure that the file-like object is closed after finishing. -!!! tip - Notice that here as we are using standard `open()` that doesn't support `async` and `await`, we declare the path operation with normal `def`. +/// tip + +Notice that here as we are using standard `open()` that doesn't support `async` and `await`, we declare the path operation with normal `def`. + +/// ### `FileResponse` @@ -231,22 +249,18 @@ Asynchronously streams a file as the response. Takes a different set of arguments to instantiate than the other response types: -* `path` - The filepath to the file to stream. +* `path` - The file path to the file to stream. * `headers` - Any custom headers to include, as a dictionary. * `media_type` - A string giving the media type. If unset, the filename or path will be used to infer a media type. * `filename` - If set, this will be included in the response `Content-Disposition`. File responses will include appropriate `Content-Length`, `Last-Modified` and `ETag` headers. -```Python hl_lines="2 10" -{!../../../docs_src/custom_response/tutorial009.py!} -``` +{* ../../docs_src/custom_response/tutorial009.py hl[2,10] *} You can also use the `response_class` parameter: -```Python hl_lines="2 8 10" -{!../../../docs_src/custom_response/tutorial009b.py!} -``` +{* ../../docs_src/custom_response/tutorial009b.py hl[2,8,10] *} In this case, you can return the file path directly from your *path operation* function. @@ -260,9 +274,7 @@ Let's say you want it to return indented and formatted JSON, so you want to use You could create a `CustomORJSONResponse`. The main thing you have to do is create a `Response.render(content)` method that returns the content as `bytes`: -```Python hl_lines="9-14 17" -{!../../../docs_src/custom_response/tutorial009c.py!} -``` +{* ../../docs_src/custom_response/tutorial009c.py hl[9:14,17] *} Now instead of returning: @@ -288,12 +300,13 @@ The parameter that defines this is `default_response_class`. In the example below, **FastAPI** will use `ORJSONResponse` by default, in all *path operations*, instead of `JSONResponse`. -```Python hl_lines="2 4" -{!../../../docs_src/custom_response/tutorial010.py!} -``` +{* ../../docs_src/custom_response/tutorial010.py hl[2,4] *} + +/// tip + +You can still override `response_class` in *path operations* as before. -!!! tip - You can still override `response_class` in *path operations* as before. +/// ## Additional documentation diff --git a/docs/en/docs/advanced/dataclasses.md b/docs/en/docs/advanced/dataclasses.md index ed1d5610f..2936c6d5d 100644 --- a/docs/en/docs/advanced/dataclasses.md +++ b/docs/en/docs/advanced/dataclasses.md @@ -4,11 +4,9 @@ FastAPI is built on top of **Pydantic**, and I have been showing you how to use But FastAPI also supports using `dataclasses` the same way: -```Python hl_lines="1 7-12 19-20" -{!../../../docs_src/dataclasses/tutorial001.py!} -``` +{* ../../docs_src/dataclasses/tutorial001.py hl[1,7:12,19:20] *} -This is still supported thanks to **Pydantic**, as it has internal support for `dataclasses`. +This is still supported thanks to **Pydantic**, as it has internal support for `dataclasses`. So, even with the code above that doesn't use Pydantic explicitly, FastAPI is using Pydantic to convert those standard dataclasses to Pydantic's own flavor of dataclasses. @@ -20,20 +18,21 @@ And of course, it supports the same: This works the same way as with Pydantic models. And it is actually achieved in the same way underneath, using Pydantic. -!!! info - Keep in mind that dataclasses can't do everything Pydantic models can do. +/// info - So, you might still need to use Pydantic models. +Keep in mind that dataclasses can't do everything Pydantic models can do. - But if you have a bunch of dataclasses laying around, this is a nice trick to use them to power a web API using FastAPI. 🤓 +So, you might still need to use Pydantic models. + +But if you have a bunch of dataclasses laying around, this is a nice trick to use them to power a web API using FastAPI. 🤓 + +/// ## Dataclasses in `response_model` You can also use `dataclasses` in the `response_model` parameter: -```Python hl_lines="1 7-13 19" -{!../../../docs_src/dataclasses/tutorial002.py!} -``` +{* ../../docs_src/dataclasses/tutorial002.py hl[1,7:13,19] *} The dataclass will be automatically converted to a Pydantic dataclass. @@ -49,9 +48,7 @@ In some cases, you might still have to use Pydantic's version of `dataclasses`. In that case, you can simply swap the standard `dataclasses` with `pydantic.dataclasses`, which is a drop-in replacement: -```{ .python .annotate hl_lines="1 5 8-11 14-17 23-25 28" } -{!../../../docs_src/dataclasses/tutorial003.py!} -``` +{* ../../docs_src/dataclasses/tutorial003.py hl[1,5,8:11,14:17,23:25,28] *} 1. We still import `field` from standard `dataclasses`. @@ -77,7 +74,7 @@ In that case, you can simply swap the standard `dataclasses` with `pydantic.data As always, in FastAPI you can combine `def` and `async def` as needed. - If you need a refresher about when to use which, check out the section _"In a hurry?"_ in the docs about `async` and `await`. + If you need a refresher about when to use which, check out the section _"In a hurry?"_ in the docs about [`async` and `await`](../async.md#in-a-hurry){.internal-link target=_blank}. 9. This *path operation function* is not returning dataclasses (although it could), but a list of dictionaries with internal data. @@ -91,7 +88,7 @@ Check the in-code annotation tips above to see more specific details. You can also combine `dataclasses` with other Pydantic models, inherit from them, include them in your own models, etc. -To learn more, check the Pydantic docs about dataclasses. +To learn more, check the Pydantic docs about dataclasses. ## Version diff --git a/docs/en/docs/advanced/events.md b/docs/en/docs/advanced/events.md index ca9d86ae4..19465d891 100644 --- a/docs/en/docs/advanced/events.md +++ b/docs/en/docs/advanced/events.md @@ -30,26 +30,25 @@ Let's start with an example and then see it in detail. We create an async function `lifespan()` with `yield` like this: -```Python hl_lines="16 19" -{!../../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[16,19] *} Here we are simulating the expensive *startup* operation of loading the model by putting the (fake) model function in the dictionary with machine learning models before the `yield`. This code will be executed **before** the application **starts taking requests**, during the *startup*. And then, right after the `yield`, we unload the model. This code will be executed **after** the application **finishes handling requests**, right before the *shutdown*. This could, for example, release resources like memory or a GPU. -!!! tip - The `shutdown` would happen when you are **stopping** the application. +/// tip + +The `shutdown` would happen when you are **stopping** the application. - Maybe you need to start a new version, or you just got tired of running it. 🤷 +Maybe you need to start a new version, or you just got tired of running it. 🤷 + +/// ### Lifespan function The first thing to notice, is that we are defining an async function with `yield`. This is very similar to Dependencies with `yield`. -```Python hl_lines="14-19" -{!../../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[14:19] *} The first part of the function, before the `yield`, will be executed **before** the application starts. @@ -61,9 +60,7 @@ If you check, the function is decorated with an `@asynccontextmanager`. That converts the function into something called an "**async context manager**". -```Python hl_lines="1 13" -{!../../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[1,13] *} A **context manager** in Python is something that you can use in a `with` statement, for example, `open()` can be used as a context manager: @@ -85,16 +82,17 @@ In our code example above, we don't use it directly, but we pass it to FastAPI f The `lifespan` parameter of the `FastAPI` app takes an **async context manager**, so we can pass our new `lifespan` async context manager to it. -```Python hl_lines="22" -{!../../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[22] *} ## Alternative Events (deprecated) -!!! warning - The recommended way to handle the *startup* and *shutdown* is using the `lifespan` parameter of the `FastAPI` app as described above. If you provide a `lifespan` parameter, `startup` and `shutdown` event handlers will no longer be called. It's all `lifespan` or all events, not both. +/// warning + +The recommended way to handle the *startup* and *shutdown* is using the `lifespan` parameter of the `FastAPI` app as described above. If you provide a `lifespan` parameter, `startup` and `shutdown` event handlers will no longer be called. It's all `lifespan` or all events, not both. + +You can probably skip this part. - You can probably skip this part. +/// There's an alternative way to define this logic to be executed during *startup* and during *shutdown*. @@ -106,9 +104,7 @@ These functions can be declared with `async def` or normal `def`. To add a function that should be run before the application starts, declare it with the event `"startup"`: -```Python hl_lines="8" -{!../../../docs_src/events/tutorial001.py!} -``` +{* ../../docs_src/events/tutorial001.py hl[8] *} In this case, the `startup` event handler function will initialize the items "database" (just a `dict`) with some values. @@ -120,23 +116,27 @@ And your application won't start receiving requests until all the `startup` even To add a function that should be run when the application is shutting down, declare it with the event `"shutdown"`: -```Python hl_lines="6" -{!../../../docs_src/events/tutorial002.py!} -``` +{* ../../docs_src/events/tutorial002.py hl[6] *} Here, the `shutdown` event handler function will write a text line `"Application shutdown"` to a file `log.txt`. -!!! info - In the `open()` function, the `mode="a"` means "append", so, the line will be added after whatever is on that file, without overwriting the previous contents. +/// info + +In the `open()` function, the `mode="a"` means "append", so, the line will be added after whatever is on that file, without overwriting the previous contents. + +/// -!!! tip - Notice that in this case we are using a standard Python `open()` function that interacts with a file. +/// tip - So, it involves I/O (input/output), that requires "waiting" for things to be written to disk. +Notice that in this case we are using a standard Python `open()` function that interacts with a file. - But `open()` doesn't use `async` and `await`. +So, it involves I/O (input/output), that requires "waiting" for things to be written to disk. - So, we declare the event handler function with standard `def` instead of `async def`. +But `open()` doesn't use `async` and `await`. + +So, we declare the event handler function with standard `def` instead of `async def`. + +/// ### `startup` and `shutdown` together @@ -152,11 +152,14 @@ Just a technical detail for the curious nerds. 🤓 Underneath, in the ASGI technical specification, this is part of the Lifespan Protocol, and it defines events called `startup` and `shutdown`. -!!! info - You can read more about the Starlette `lifespan` handlers in Starlette's Lifespan' docs. +/// info + +You can read more about the Starlette `lifespan` handlers in Starlette's Lifespan' docs. + +Including how to handle lifespan state that can be used in other areas of your code. - Including how to handle lifespan state that can be used in other areas of your code. +/// ## Sub Applications -🚨 Keep in mind that these lifespan events (startup and shutdown) will only be executed for the main application, not for [Sub Applications - Mounts](./sub-applications.md){.internal-link target=_blank}. +🚨 Keep in mind that these lifespan events (startup and shutdown) will only be executed for the main application, not for [Sub Applications - Mounts](sub-applications.md){.internal-link target=_blank}. diff --git a/docs/en/docs/advanced/generate-clients.md b/docs/en/docs/advanced/generate-clients.md index 3a810baee..3b9dc83f0 100644 --- a/docs/en/docs/advanced/generate-clients.md +++ b/docs/en/docs/advanced/generate-clients.md @@ -10,7 +10,7 @@ There are many tools to generate clients from **OpenAPI**. A common tool is OpenAPI Generator. -If you are building a **frontend**, a very interesting alternative is openapi-typescript-codegen. +If you are building a **frontend**, a very interesting alternative is openapi-ts. ## Client and SDK Generators - Sponsor @@ -20,7 +20,11 @@ Some of them also ✨ [**sponsor FastAPI**](../help-fastapi.md#sponsor-the-autho And it shows their true commitment to FastAPI and its **community** (you), as they not only want to provide you a **good service** but also want to make sure you have a **good and healthy framework**, FastAPI. 🙇 -For example, you might want to try Speakeasy. +For example, you might want to try: + +* Speakeasy +* Stainless +* liblab There are also several other companies offering similar services that you can search and find online. 🤓 @@ -28,17 +32,7 @@ There are also several other companies offering similar services that you can se Let's start with a simple FastAPI application: -=== "Python 3.9+" - - ```Python hl_lines="7-9 12-13 16-17 21" - {!> ../../../docs_src/generate_clients/tutorial001_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="9-11 14-15 18 19 23" - {!> ../../../docs_src/generate_clients/tutorial001.py!} - ``` +{* ../../docs_src/generate_clients/tutorial001_py39.py hl[7:9,12:13,16:17,21] *} Notice that the *path operations* define the models they use for request payload and response payload, using the models `Item` and `ResponseMessage`. @@ -58,14 +52,14 @@ And that same information from the models that is included in OpenAPI is what ca Now that we have the app with the models, we can generate the client code for the frontend. -#### Install `openapi-typescript-codegen` +#### Install `openapi-ts` -You can install `openapi-typescript-codegen` in your frontend code with: +You can install `openapi-ts` in your frontend code with:
```console -$ npm install openapi-typescript-codegen --save-dev +$ npm install @hey-api/openapi-ts --save-dev ---> 100% ``` @@ -74,7 +68,7 @@ $ npm install openapi-typescript-codegen --save-dev #### Generate Client Code -To generate the client code you can use the command line application `openapi` that would now be installed. +To generate the client code you can use the command line application `openapi-ts` that would now be installed. Because it is installed in the local project, you probably wouldn't be able to call that command directly, but you would put it on your `package.json` file. @@ -87,12 +81,12 @@ It could look like this: "description": "", "main": "index.js", "scripts": { - "generate-client": "openapi --input http://localhost:8000/openapi.json --output ./src/client --client axios --useOptions --useUnionTypes" + "generate-client": "openapi-ts --input http://localhost:8000/openapi.json --output ./src/client --client axios" }, "author": "", "license": "", "devDependencies": { - "openapi-typescript-codegen": "^0.20.1", + "@hey-api/openapi-ts": "^0.27.38", "typescript": "^4.6.2" } } @@ -106,7 +100,7 @@ After having that NPM `generate-client` script there, you can run it with: $ npm run generate-client frontend-app@1.0.0 generate-client /home/user/code/frontend-app -> openapi --input http://localhost:8000/openapi.json --output ./src/client --client axios --useOptions --useUnionTypes +> openapi-ts --input http://localhost:8000/openapi.json --output ./src/client --client axios ```
@@ -123,8 +117,11 @@ You will also get autocompletion for the payload to send: -!!! tip - Notice the autocompletion for `name` and `price`, that was defined in the FastAPI application, in the `Item` model. +/// tip + +Notice the autocompletion for `name` and `price`, that was defined in the FastAPI application, in the `Item` model. + +/// You will have inline errors for the data that you send: @@ -140,17 +137,7 @@ In many cases your FastAPI app will be bigger, and you will probably use tags to For example, you could have a section for **items** and another section for **users**, and they could be separated by tags: -=== "Python 3.9+" - - ```Python hl_lines="21 26 34" - {!> ../../../docs_src/generate_clients/tutorial002_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="23 28 36" - {!> ../../../docs_src/generate_clients/tutorial002.py!} - ``` +{* ../../docs_src/generate_clients/tutorial002_py39.py hl[21,26,34] *} ### Generate a TypeScript Client with Tags @@ -197,17 +184,7 @@ For example, here it is using the first tag (you will probably have only one tag You can then pass that custom function to **FastAPI** as the `generate_unique_id_function` parameter: -=== "Python 3.9+" - - ```Python hl_lines="6-7 10" - {!> ../../../docs_src/generate_clients/tutorial003_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="8-9 12" - {!> ../../../docs_src/generate_clients/tutorial003.py!} - ``` +{* ../../docs_src/generate_clients/tutorial003_py39.py hl[6:7,10] *} ### Generate a TypeScript Client with Custom Operation IDs @@ -229,17 +206,15 @@ But for the generated client we could **modify** the OpenAPI operation IDs right We could download the OpenAPI JSON to a file `openapi.json` and then we could **remove that prefixed tag** with a script like this: -=== "Python" +{* ../../docs_src/generate_clients/tutorial004.py *} - ```Python - {!> ../../../docs_src/generate_clients/tutorial004.py!} - ``` +//// tab | Node.js -=== "Node.js" +```Javascript +{!> ../../docs_src/generate_clients/tutorial004.js!} +``` - ```Python - {!> ../../../docs_src/generate_clients/tutorial004.js!} - ``` +//// With that, the operation IDs would be renamed from things like `items-get_items` to just `get_items`, that way the client generator can generate simpler method names. @@ -254,12 +229,12 @@ Now as the end result is in a file `openapi.json`, you would modify the `package "description": "", "main": "index.js", "scripts": { - "generate-client": "openapi --input ./openapi.json --output ./src/client --client axios --useOptions --useUnionTypes" + "generate-client": "openapi-ts --input ./openapi.json --output ./src/client --client axios" }, "author": "", "license": "", "devDependencies": { - "openapi-typescript-codegen": "^0.20.1", + "@hey-api/openapi-ts": "^0.27.38", "typescript": "^4.6.2" } } @@ -271,7 +246,7 @@ After generating the new client, you would now have **clean method names**, with ## Benefits -When using the automatically generated clients you would **autocompletion** for: +When using the automatically generated clients you would get **autocompletion** for: * Methods. * Request payloads in the body, query parameters, etc. diff --git a/docs/en/docs/advanced/index.md b/docs/en/docs/advanced/index.md index d8dcd4ca6..36f0720c0 100644 --- a/docs/en/docs/advanced/index.md +++ b/docs/en/docs/advanced/index.md @@ -2,24 +2,27 @@ ## Additional Features -The main [Tutorial - User Guide](../tutorial/){.internal-link target=_blank} should be enough to give you a tour through all the main features of **FastAPI**. +The main [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} should be enough to give you a tour through all the main features of **FastAPI**. In the next sections you will see other options, configurations, and additional features. -!!! tip - The next sections are **not necessarily "advanced"**. +/// tip - And it's possible that for your use case, the solution is in one of them. +The next sections are **not necessarily "advanced"**. + +And it's possible that for your use case, the solution is in one of them. + +/// ## Read the Tutorial first -You could still use most of the features in **FastAPI** with the knowledge from the main [Tutorial - User Guide](../tutorial/){.internal-link target=_blank}. +You could still use most of the features in **FastAPI** with the knowledge from the main [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank}. And the next sections assume you already read it, and assume that you know those main ideas. ## External Courses -Although the [Tutorial - User Guide](../tutorial/){.internal-link target=_blank} and this **Advanced User Guide** are written as a guided tutorial (like a book) and should be enough for you to **learn FastAPI**, you might want to complement it with additional courses. +Although the [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} and this **Advanced User Guide** are written as a guided tutorial (like a book) and should be enough for you to **learn FastAPI**, you might want to complement it with additional courses. Or it might be the case that you just prefer to take other courses because they adapt better to your learning style. diff --git a/docs/en/docs/advanced/middleware.md b/docs/en/docs/advanced/middleware.md index 9219f1d2c..1d40b1c8f 100644 --- a/docs/en/docs/advanced/middleware.md +++ b/docs/en/docs/advanced/middleware.md @@ -24,7 +24,7 @@ app = SomeASGIApp() new_app = UnicornMiddleware(app, some_config="rainbow") ``` -But FastAPI (actually Starlette) provides a simpler way to do it that makes sure that the internal middlewares to handle server errors and custom exception handlers work properly. +But FastAPI (actually Starlette) provides a simpler way to do it that makes sure that the internal middlewares handle server errors and custom exception handlers work properly. For that, you use `app.add_middleware()` (as in the example for CORS). @@ -43,28 +43,27 @@ app.add_middleware(UnicornMiddleware, some_config="rainbow") **FastAPI** includes several middlewares for common use cases, we'll see next how to use them. -!!! note "Technical Details" - For the next examples, you could also use `from starlette.middleware.something import SomethingMiddleware`. +/// note | Technical Details - **FastAPI** provides several middlewares in `fastapi.middleware` just as a convenience for you, the developer. But most of the available middlewares come directly from Starlette. +For the next examples, you could also use `from starlette.middleware.something import SomethingMiddleware`. + +**FastAPI** provides several middlewares in `fastapi.middleware` just as a convenience for you, the developer. But most of the available middlewares come directly from Starlette. + +/// ## `HTTPSRedirectMiddleware` Enforces that all incoming requests must either be `https` or `wss`. -Any incoming requests to `http` or `ws` will be redirected to the secure scheme instead. +Any incoming request to `http` or `ws` will be redirected to the secure scheme instead. -```Python hl_lines="2 6" -{!../../../docs_src/advanced_middleware/tutorial001.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial001.py hl[2,6] *} ## `TrustedHostMiddleware` Enforces that all incoming requests have a correctly set `Host` header, in order to guard against HTTP Host Header attacks. -```Python hl_lines="2 6-8" -{!../../../docs_src/advanced_middleware/tutorial002.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial002.py hl[2,6:8] *} The following arguments are supported: @@ -78,13 +77,12 @@ Handles GZip responses for any request that includes `"gzip"` in the `Accept-Enc The middleware will handle both standard and streaming responses. -```Python hl_lines="2 6" -{!../../../docs_src/advanced_middleware/tutorial003.py!} -``` +{* ../../docs_src/advanced_middleware/tutorial003.py hl[2,6] *} The following arguments are supported: * `minimum_size` - Do not GZip responses that are smaller than this minimum size in bytes. Defaults to `500`. +* `compresslevel` - Used during GZip compression. It is an integer ranging from 1 to 9. Defaults to `9`. Lower value results in faster compression but larger file sizes, while higher value results in slower compression but smaller file sizes. ## Other middlewares @@ -92,7 +90,6 @@ There are many other ASGI middlewares. For example: -* Sentry * Uvicorn's `ProxyHeadersMiddleware` * MessagePack diff --git a/docs/en/docs/advanced/openapi-callbacks.md b/docs/en/docs/advanced/openapi-callbacks.md index 03429b187..ca9065a89 100644 --- a/docs/en/docs/advanced/openapi-callbacks.md +++ b/docs/en/docs/advanced/openapi-callbacks.md @@ -31,12 +31,13 @@ It will have a *path operation* that will receive an `Invoice` body, and a query This part is pretty normal, most of the code is probably already familiar to you: -```Python hl_lines="9-13 36-53" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[9:13,36:53] *} + +/// tip -!!! tip - The `callback_url` query parameter uses a Pydantic URL type. +The `callback_url` query parameter uses a Pydantic Url type. + +/// The only new thing is the `callbacks=invoices_callback_router.routes` as an argument to the *path operation decorator*. We'll see what that is next. @@ -61,10 +62,13 @@ That documentation will show up in the Swagger UI at `/docs` in your API, and it This example doesn't implement the callback itself (that could be just a line of code), only the documentation part. -!!! tip - The actual callback is just an HTTP request. +/// tip + +The actual callback is just an HTTP request. - When implementing the callback yourself, you could use something like HTTPX or Requests. +When implementing the callback yourself, you could use something like HTTPX or Requests. + +/// ## Write the callback documentation code @@ -74,18 +78,19 @@ But, you already know how to easily create automatic documentation for an API wi So we are going to use that same knowledge to document how the *external API* should look like... by creating the *path operation(s)* that the external API should implement (the ones your API will call). -!!! tip - When writing the code to document a callback, it might be useful to imagine that you are that *external developer*. And that you are currently implementing the *external API*, not *your API*. +/// tip + +When writing the code to document a callback, it might be useful to imagine that you are that *external developer*. And that you are currently implementing the *external API*, not *your API*. + +Temporarily adopting this point of view (of the *external developer*) can help you feel like it's more obvious where to put the parameters, the Pydantic model for the body, for the response, etc. for that *external API*. - Temporarily adopting this point of view (of the *external developer*) can help you feel like it's more obvious where to put the parameters, the Pydantic model for the body, for the response, etc. for that *external API*. +/// ### Create a callback `APIRouter` First create a new `APIRouter` that will contain one or more callbacks. -```Python hl_lines="3 25" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[3,25] *} ### Create the callback *path operation* @@ -96,9 +101,7 @@ It should look just like a normal FastAPI *path operation*: * It should probably have a declaration of the body it should receive, e.g. `body: InvoiceEvent`. * And it could also have a declaration of the response it should return, e.g. `response_model=InvoiceEventReceived`. -```Python hl_lines="16-18 21-22 28-32" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[16:18,21:22,28:32] *} There are 2 main differences from a normal *path operation*: @@ -131,7 +134,7 @@ with a JSON body of: } ``` -Then *your API* will process the invoice, and at some point later, send a callback request to the `callback_url` (the *external API*): +then *your API* will process the invoice, and at some point later, send a callback request to the `callback_url` (the *external API*): ``` https://www.external.org/events/invoices/2expen51ve @@ -154,8 +157,11 @@ and it would expect a response from that *external API* with a JSON body like: } ``` -!!! tip - Notice how the callback URL used contains the URL received as a query parameter in `callback_url` (`https://www.external.org/events`) and also the invoice `id` from inside of the JSON body (`2expen51ve`). +/// tip + +Notice how the callback URL used contains the URL received as a query parameter in `callback_url` (`https://www.external.org/events`) and also the invoice `id` from inside of the JSON body (`2expen51ve`). + +/// ### Add the callback router @@ -163,17 +169,18 @@ At this point you have the *callback path operation(s)* needed (the one(s) that Now use the parameter `callbacks` in *your API's path operation decorator* to pass the attribute `.routes` (that's actually just a `list` of routes/*path operations*) from that callback router: -```Python hl_lines="35" -{!../../../docs_src/openapi_callbacks/tutorial001.py!} -``` +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[35] *} + +/// tip + +Notice that you are not passing the router itself (`invoices_callback_router`) to `callback=`, but the attribute `.routes`, as in `invoices_callback_router.routes`. -!!! tip - Notice that you are not passing the router itself (`invoices_callback_router`) to `callback=`, but the attribute `.routes`, as in `invoices_callback_router.routes`. +/// ### Check the docs -Now you can start your app with Uvicorn and go to http://127.0.0.1:8000/docs. +Now you can start your app and go to http://127.0.0.1:8000/docs. -You will see your docs including a "Callback" section for your *path operation* that shows how the *external API* should look like: +You will see your docs including a "Callbacks" section for your *path operation* that shows how the *external API* should look like: diff --git a/docs/en/docs/advanced/openapi-webhooks.md b/docs/en/docs/advanced/openapi-webhooks.md index 63cbdc610..97aaa41af 100644 --- a/docs/en/docs/advanced/openapi-webhooks.md +++ b/docs/en/docs/advanced/openapi-webhooks.md @@ -22,21 +22,25 @@ With **FastAPI**, using OpenAPI, you can define the names of these webhooks, the This can make it a lot easier for your users to **implement their APIs** to receive your **webhook** requests, they might even be able to autogenerate some of their own API code. -!!! info - Webhooks are available in OpenAPI 3.1.0 and above, supported by FastAPI `0.99.0` and above. +/// info + +Webhooks are available in OpenAPI 3.1.0 and above, supported by FastAPI `0.99.0` and above. + +/// ## An app with webhooks When you create a **FastAPI** application, there is a `webhooks` attribute that you can use to define *webhooks*, the same way you would define *path operations*, for example with `@app.webhooks.post()`. -```Python hl_lines="9-13 36-53" -{!../../../docs_src/openapi_webhooks/tutorial001.py!} -``` +{* ../../docs_src/openapi_webhooks/tutorial001.py hl[9:13,36:53] *} The webhooks that you define will end up in the **OpenAPI** schema and the automatic **docs UI**. -!!! info - The `app.webhooks` object is actually just an `APIRouter`, the same type you would use when structuring your app with multiple files. +/// info + +The `app.webhooks` object is actually just an `APIRouter`, the same type you would use when structuring your app with multiple files. + +/// Notice that with webhooks you are actually not declaring a *path* (like `/items/`), the text you pass there is just an **identifier** of the webhook (the name of the event), for example in `@app.webhooks.post("new-subscription")`, the webhook name is `new-subscription`. @@ -44,7 +48,7 @@ This is because it is expected that **your users** would define the actual **URL ### Check the docs -Now you can start your app with Uvicorn and go to http://127.0.0.1:8000/docs. +Now you can start your app and go to http://127.0.0.1:8000/docs. You will see your docs have the normal *path operations* and now also some **webhooks**: diff --git a/docs/en/docs/advanced/path-operation-advanced-configuration.md b/docs/en/docs/advanced/path-operation-advanced-configuration.md index 8b79bfe22..c4814ebd2 100644 --- a/docs/en/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/en/docs/advanced/path-operation-advanced-configuration.md @@ -2,16 +2,17 @@ ## OpenAPI operationId -!!! warning - If you are not an "expert" in OpenAPI, you probably don't need this. +/// warning + +If you are not an "expert" in OpenAPI, you probably don't need this. + +/// You can set the OpenAPI `operationId` to be used in your *path operation* with the parameter `operation_id`. You would have to make sure that it is unique for each operation. -```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *} ### Using the *path operation function* name as the operationId @@ -19,25 +20,27 @@ If you want to use your APIs' function names as `operationId`s, you can iterate You should do it after adding all your *path operations*. -```Python hl_lines="2 12-21 24" -{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2, 12:21, 24] *} + +/// tip + +If you manually call `app.openapi()`, you should update the `operationId`s before that. + +/// -!!! tip - If you manually call `app.openapi()`, you should update the `operationId`s before that. +/// warning -!!! warning - If you do this, you have to make sure each one of your *path operation functions* has a unique name. +If you do this, you have to make sure each one of your *path operation functions* has a unique name. - Even if they are in different modules (Python files). +Even if they are in different modules (Python files). + +/// ## Exclude from OpenAPI To exclude a *path operation* from the generated OpenAPI schema (and thus, from the automatic documentation systems), use the parameter `include_in_schema` and set it to `False`: -```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *} ## Advanced description from docstring @@ -47,9 +50,7 @@ Adding an `\f` (an escaped "form feed" character) causes **FastAPI** to truncate It won't show up in the documentation, but other tools (such as Sphinx) will be able to use the rest. -```Python hl_lines="19-29" -{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19:29] *} ## Additional Responses @@ -59,14 +60,17 @@ That defines the metadata about the main response of a *path operation*. You can also declare additional responses with their models, status codes, etc. -There's a whole chapter here in the documentation about it, you can read it at [Additional Responses in OpenAPI](./additional-responses.md){.internal-link target=_blank}. +There's a whole chapter here in the documentation about it, you can read it at [Additional Responses in OpenAPI](additional-responses.md){.internal-link target=_blank}. ## OpenAPI Extra When you declare a *path operation* in your application, **FastAPI** automatically generates the relevant metadata about that *path operation* to be included in the OpenAPI schema. -!!! note "Technical details" - In the OpenAPI specification it is called the Operation Object. +/// note | Technical details + +In the OpenAPI specification it is called the Operation Object. + +/// It has all the information about the *path operation* and is used to generate the automatic documentation. @@ -74,10 +78,13 @@ It includes the `tags`, `parameters`, `requestBody`, `responses`, etc. This *path operation*-specific OpenAPI schema is normally generated automatically by **FastAPI**, but you can also extend it. -!!! tip - This is a low level extension point. +/// tip + +This is a low level extension point. - If you only need to declare additional responses, a more convenient way to do it is with [Additional Responses in OpenAPI](./additional-responses.md){.internal-link target=_blank}. +If you only need to declare additional responses, a more convenient way to do it is with [Additional Responses in OpenAPI](additional-responses.md){.internal-link target=_blank}. + +/// You can extend the OpenAPI schema for a *path operation* using the parameter `openapi_extra`. @@ -85,9 +92,7 @@ You can extend the OpenAPI schema for a *path operation* using the parameter `op This `openapi_extra` can be helpful, for example, to declare [OpenAPI Extensions](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions): -```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial005.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial005.py hl[6] *} If you open the automatic API docs, your extension will show up at the bottom of the specific *path operation*. @@ -134,9 +139,7 @@ For example, you could decide to read and validate the request with your own cod You could do that with `openapi_extra`: -```Python hl_lines="20-37 39-40" -{!../../../docs_src/path_operation_advanced_configuration/tutorial006.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial006.py hl[19:36, 39:40] *} In this example, we didn't declare any Pydantic model. In fact, the request body is not even parsed as JSON, it is read directly as `bytes`, and the function `magic_data_reader()` would be in charge of parsing it in some way. @@ -150,20 +153,23 @@ And you could do this even if the data type in the request is not JSON. For example, in this application we don't use FastAPI's integrated functionality to extract the JSON Schema from Pydantic models nor the automatic validation for JSON. In fact, we are declaring the request content type as YAML, not JSON: -=== "Pydantic v2" +//// tab | Pydantic v2 + +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[17:22, 24] *} + +//// + +//// tab | Pydantic v1 + +{* ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py hl[17:22, 24] *} - ```Python hl_lines="17-22 24" - {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} - ``` +//// -=== "Pydantic v1" +/// info - ```Python hl_lines="17-22 24" - {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} - ``` +In Pydantic version 1 the method to get the JSON Schema for a model was called `Item.schema()`, in Pydantic version 2, the method is called `Item.model_json_schema()`. -!!! info - In Pydantic version 1 the method to get the JSON Schema for a model was called `Item.schema()`, in Pydantic version 2, the method is called `Item.model_json_schema()`. +/// Nevertheless, although we are not using the default integrated functionality, we are still using a Pydantic model to manually generate the JSON Schema for the data that we want to receive in YAML. @@ -171,22 +177,28 @@ Then we use the request directly, and extract the body as `bytes`. This means th And then in our code, we parse that YAML content directly, and then we are again using the same Pydantic model to validate the YAML content: -=== "Pydantic v2" +//// tab | Pydantic v2 + +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[26:33] *} + +//// + +//// tab | Pydantic v1 + +{* ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py hl[26:33] *} + +//// + +/// info - ```Python hl_lines="26-33" - {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} - ``` +In Pydantic version 1 the method to parse and validate an object was `Item.parse_obj()`, in Pydantic version 2, the method is called `Item.model_validate()`. -=== "Pydantic v1" +/// - ```Python hl_lines="26-33" - {!> ../../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py!} - ``` +/// tip -!!! info - In Pydantic version 1 the method to parse and validate an object was `Item.parse_obj()`, in Pydantic version 2, the method is called `Item.model_validate()`. +Here we reuse the same Pydantic model. -!!! tip - Here we re-use the same Pydantic model. +But the same way, we could have validated it in some other way. - But the same way, we could have validated it in some other way. +/// diff --git a/docs/en/docs/advanced/response-change-status-code.md b/docs/en/docs/advanced/response-change-status-code.md index b88d74a8a..6d3f9f3e8 100644 --- a/docs/en/docs/advanced/response-change-status-code.md +++ b/docs/en/docs/advanced/response-change-status-code.md @@ -20,9 +20,7 @@ You can declare a parameter of type `Response` in your *path operation function* And then you can set the `status_code` in that *temporal* response object. -```Python hl_lines="1 9 12" -{!../../../docs_src/response_change_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *} And then you can return any object you need, as you normally would (a `dict`, a database model, etc). diff --git a/docs/en/docs/advanced/response-cookies.md b/docs/en/docs/advanced/response-cookies.md index d53985dbb..f6d17f35d 100644 --- a/docs/en/docs/advanced/response-cookies.md +++ b/docs/en/docs/advanced/response-cookies.md @@ -6,9 +6,7 @@ You can declare a parameter of type `Response` in your *path operation function* And then you can set cookies in that *temporal* response object. -```Python hl_lines="1 8-9" -{!../../../docs_src/response_cookies/tutorial002.py!} -``` +{* ../../docs_src/response_cookies/tutorial002.py hl[1, 8:9] *} And then you can return any object you need, as you normally would (a `dict`, a database model, etc). @@ -26,24 +24,28 @@ To do that, you can create a response as described in [Return a Response Directl Then set Cookies in it, and then return it: -```Python hl_lines="10-12" -{!../../../docs_src/response_cookies/tutorial001.py!} -``` +{* ../../docs_src/response_cookies/tutorial001.py hl[10:12] *} -!!! tip - Keep in mind that if you return a response directly instead of using the `Response` parameter, FastAPI will return it directly. +/// tip - So, you will have to make sure your data is of the correct type. E.g. it is compatible with JSON, if you are returning a `JSONResponse`. +Keep in mind that if you return a response directly instead of using the `Response` parameter, FastAPI will return it directly. - And also that you are not sending any data that should have been filtered by a `response_model`. +So, you will have to make sure your data is of the correct type. E.g. it is compatible with JSON, if you are returning a `JSONResponse`. + +And also that you are not sending any data that should have been filtered by a `response_model`. + +/// ### More info -!!! note "Technical Details" - You could also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse`. +/// note | Technical Details + +You could also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse`. + +**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. - **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. +And as the `Response` can be used frequently to set headers and cookies, **FastAPI** also provides it at `fastapi.Response`. - And as the `Response` can be used frequently to set headers and cookies, **FastAPI** also provides it at `fastapi.Response`. +/// To see all the available parameters and options, check the documentation in Starlette. diff --git a/docs/en/docs/advanced/response-directly.md b/docs/en/docs/advanced/response-directly.md index 8836140ec..691b1e7cd 100644 --- a/docs/en/docs/advanced/response-directly.md +++ b/docs/en/docs/advanced/response-directly.md @@ -14,8 +14,11 @@ It might be useful, for example, to return custom headers or cookies. In fact, you can return any `Response` or any sub-class of it. -!!! tip - `JSONResponse` itself is a sub-class of `Response`. +/// tip + +`JSONResponse` itself is a sub-class of `Response`. + +/// And when you return a `Response`, **FastAPI** will pass it directly. @@ -25,20 +28,21 @@ This gives you a lot of flexibility. You can return any data type, override any ## Using the `jsonable_encoder` in a `Response` -Because **FastAPI** doesn't do any change to a `Response` you return, you have to make sure it's contents are ready for it. +Because **FastAPI** doesn't make any changes to a `Response` you return, you have to make sure its contents are ready for it. For example, you cannot put a Pydantic model in a `JSONResponse` without first converting it to a `dict` with all the data types (like `datetime`, `UUID`, etc) converted to JSON-compatible types. For those cases, you can use the `jsonable_encoder` to convert your data before passing it to a response: -```Python hl_lines="6-7 21-22" -{!../../../docs_src/response_directly/tutorial001.py!} -``` +{* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *} + +/// note | Technical Details + +You could also use `from starlette.responses import JSONResponse`. -!!! note "Technical Details" - You could also use `from starlette.responses import JSONResponse`. +**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. - **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. +/// ## Returning a custom `Response` @@ -48,11 +52,9 @@ Now, let's see how you could use that to return a custom response. Let's say that you want to return an XML response. -You could put your XML content in a string, put it in a `Response`, and return it: +You could put your XML content in a string, put that in a `Response`, and return it: -```Python hl_lines="1 18" -{!../../../docs_src/response_directly/tutorial002.py!} -``` +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} ## Notes diff --git a/docs/en/docs/advanced/response-headers.md b/docs/en/docs/advanced/response-headers.md index 49b5fe476..97e888983 100644 --- a/docs/en/docs/advanced/response-headers.md +++ b/docs/en/docs/advanced/response-headers.md @@ -6,9 +6,7 @@ You can declare a parameter of type `Response` in your *path operation function* And then you can set headers in that *temporal* response object. -```Python hl_lines="1 7-8" -{!../../../docs_src/response_headers/tutorial002.py!} -``` +{* ../../docs_src/response_headers/tutorial002.py hl[1, 7:8] *} And then you can return any object you need, as you normally would (a `dict`, a database model, etc). @@ -24,16 +22,17 @@ You can also add headers when you return a `Response` directly. Create a response as described in [Return a Response Directly](response-directly.md){.internal-link target=_blank} and pass the headers as an additional parameter: -```Python hl_lines="10-12" -{!../../../docs_src/response_headers/tutorial001.py!} -``` +{* ../../docs_src/response_headers/tutorial001.py hl[10:12] *} -!!! note "Technical Details" - You could also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse`. +/// note | Technical Details - **FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. +You could also use `from starlette.responses import Response` or `from starlette.responses import JSONResponse`. - And as the `Response` can be used frequently to set headers and cookies, **FastAPI** also provides it at `fastapi.Response`. +**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. + +And as the `Response` can be used frequently to set headers and cookies, **FastAPI** also provides it at `fastapi.Response`. + +/// ## Custom Headers diff --git a/docs/en/docs/advanced/security/http-basic-auth.md b/docs/en/docs/advanced/security/http-basic-auth.md index 680f4dff5..234e2f940 100644 --- a/docs/en/docs/advanced/security/http-basic-auth.md +++ b/docs/en/docs/advanced/security/http-basic-auth.md @@ -20,26 +20,7 @@ Then, when you type that username and password, the browser sends them in the he * It returns an object of type `HTTPBasicCredentials`: * It contains the `username` and `password` sent. -=== "Python 3.9+" - - ```Python hl_lines="4 8 12" - {!> ../../../docs_src/security/tutorial006_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="2 7 11" - {!> ../../../docs_src/security/tutorial006_an.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="2 6 10" - {!> ../../../docs_src/security/tutorial006.py!} - ``` +{* ../../docs_src/security/tutorial006_an_py39.py hl[4,8,12] *} When you try to open the URL for the first time (or click the "Execute" button in the docs) the browser will ask you for your username and password: @@ -59,26 +40,7 @@ To handle that, we first convert the `username` and `password` to `bytes` encodi Then we can use `secrets.compare_digest()` to ensure that `credentials.username` is `"stanleyjobson"`, and that `credentials.password` is `"swordfish"`. -=== "Python 3.9+" - - ```Python hl_lines="1 12-24" - {!> ../../../docs_src/security/tutorial007_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="1 12-24" - {!> ../../../docs_src/security/tutorial007_an.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="1 11-21" - {!> ../../../docs_src/security/tutorial007.py!} - ``` +{* ../../docs_src/security/tutorial007_an_py39.py hl[1,12:24] *} This would be similar to: @@ -126,7 +88,7 @@ And then they can try again knowing that it's probably something more similar to #### A "professional" attack -Of course, the attackers would not try all this by hand, they would write a program to do it, possibly with thousands or millions of tests per second. And would get just one extra correct letter at a time. +Of course, the attackers would not try all this by hand, they would write a program to do it, possibly with thousands or millions of tests per second. And they would get just one extra correct letter at a time. But doing that, in some minutes or hours the attackers would have guessed the correct username and password, with the "help" of our application, just using the time taken to answer. @@ -142,23 +104,4 @@ That way, using `secrets.compare_digest()` in your application code, it will be After detecting that the credentials are incorrect, return an `HTTPException` with a status code 401 (the same returned when no credentials are provided) and add the header `WWW-Authenticate` to make the browser show the login prompt again: -=== "Python 3.9+" - - ```Python hl_lines="26-30" - {!> ../../../docs_src/security/tutorial007_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="26-30" - {!> ../../../docs_src/security/tutorial007_an.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="23-27" - {!> ../../../docs_src/security/tutorial007.py!} - ``` +{* ../../docs_src/security/tutorial007_an_py39.py hl[26:30] *} diff --git a/docs/en/docs/advanced/security/index.md b/docs/en/docs/advanced/security/index.md index c18baf64b..edb42132e 100644 --- a/docs/en/docs/advanced/security/index.md +++ b/docs/en/docs/advanced/security/index.md @@ -2,15 +2,18 @@ ## Additional Features -There are some extra features to handle security apart from the ones covered in the [Tutorial - User Guide: Security](../../tutorial/security/){.internal-link target=_blank}. +There are some extra features to handle security apart from the ones covered in the [Tutorial - User Guide: Security](../../tutorial/security/index.md){.internal-link target=_blank}. -!!! tip - The next sections are **not necessarily "advanced"**. +/// tip - And it's possible that for your use case, the solution is in one of them. +The next sections are **not necessarily "advanced"**. + +And it's possible that for your use case, the solution is in one of them. + +/// ## Read the Tutorial first -The next sections assume you already read the main [Tutorial - User Guide: Security](../../tutorial/security/){.internal-link target=_blank}. +The next sections assume you already read the main [Tutorial - User Guide: Security](../../tutorial/security/index.md){.internal-link target=_blank}. They are all based on the same concepts, but allow some extra functionalities. diff --git a/docs/en/docs/advanced/security/oauth2-scopes.md b/docs/en/docs/advanced/security/oauth2-scopes.md index b93d2991c..4cb0b39bc 100644 --- a/docs/en/docs/advanced/security/oauth2-scopes.md +++ b/docs/en/docs/advanced/security/oauth2-scopes.md @@ -10,18 +10,21 @@ Every time you "log in with" Facebook, Google, GitHub, Microsoft, Twitter, that In this section you will see how to manage authentication and authorization with the same OAuth2 with scopes in your **FastAPI** application. -!!! warning - This is a more or less advanced section. If you are just starting, you can skip it. +/// warning - You don't necessarily need OAuth2 scopes, and you can handle authentication and authorization however you want. +This is a more or less advanced section. If you are just starting, you can skip it. - But OAuth2 with scopes can be nicely integrated into your API (with OpenAPI) and your API docs. +You don't necessarily need OAuth2 scopes, and you can handle authentication and authorization however you want. - Nevertheless, you still enforce those scopes, or any other security/authorization requirement, however you need, in your code. +But OAuth2 with scopes can be nicely integrated into your API (with OpenAPI) and your API docs. - In many cases, OAuth2 with scopes can be an overkill. +Nevertheless, you still enforce those scopes, or any other security/authorization requirement, however you need, in your code. - But if you know you need it, or you are curious, keep reading. +In many cases, OAuth2 with scopes can be an overkill. + +But if you know you need it, or you are curious, keep reading. + +/// ## OAuth2 scopes and OpenAPI @@ -43,63 +46,23 @@ They are normally used to declare specific security permissions, for example: * `instagram_basic` is used by Facebook / Instagram. * `https://www.googleapis.com/auth/drive` is used by Google. -!!! info - In OAuth2 a "scope" is just a string that declares a specific permission required. - - It doesn't matter if it has other characters like `:` or if it is a URL. - - Those details are implementation specific. - - For OAuth2 they are just strings. - -## Global view - -First, let's quickly see the parts that change from the examples in the main **Tutorial - User Guide** for [OAuth2 with Password (and hashing), Bearer with JWT tokens](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. Now using OAuth2 scopes: - -=== "Python 3.10+" - - ```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="2 4 8 12 47 65 106 108-116 122-125 129-135 140 156" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +/// info -=== "Python 3.10+ non-Annotated" +In OAuth2 a "scope" is just a string that declares a specific permission required. - !!! tip - Prefer to use the `Annotated` version if possible. +It doesn't matter if it has other characters like `:` or if it is a URL. - ```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 154" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +Those details are implementation specific. -=== "Python 3.9+ non-Annotated" +For OAuth2 they are just strings. - !!! tip - Prefer to use the `Annotated` version if possible. +/// - ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` - -=== "Python 3.8+ non-Annotated" +## Global view - !!! tip - Prefer to use the `Annotated` version if possible. +First, let's quickly see the parts that change from the examples in the main **Tutorial - User Guide** for [OAuth2 with Password (and hashing), Bearer with JWT tokens](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. Now using OAuth2 scopes: - ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +{* ../../docs_src/security/tutorial005_an_py310.py hl[5,9,13,47,65,106,108:116,122:125,129:135,140,156] *} Now let's review those changes step by step. @@ -109,51 +72,7 @@ The first change is that now we are declaring the OAuth2 security scheme with tw The `scopes` parameter receives a `dict` with each scope as a key and the description as the value: -=== "Python 3.10+" - - ```Python hl_lines="62-65" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="62-65" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="63-66" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="61-64" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` - - -=== "Python 3.9+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="62-65" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="62-65" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +{* ../../docs_src/security/tutorial005_an_py310.py hl[63:66] *} Because we are now declaring those scopes, they will show up in the API docs when you log-in/authorize. @@ -171,55 +90,15 @@ We are still using the same `OAuth2PasswordRequestForm`. It includes a property And we return the scopes as part of the JWT token. -!!! danger - For simplicity, here we are just adding the scopes received directly to the token. - - But in your application, for security, you should make sure you only add the scopes that the user is actually able to have, or the ones you have predefined. - -=== "Python 3.10+" - - ```Python hl_lines="155" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="155" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="156" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="154" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` - -=== "Python 3.9+ non-Annotated" +/// danger - !!! tip - Prefer to use the `Annotated` version if possible. +For simplicity, here we are just adding the scopes received directly to the token. - ```Python hl_lines="155" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +But in your application, for security, you should make sure you only add the scopes that the user is actually able to have, or the ones you have predefined. -=== "Python 3.8+ non-Annotated" +/// - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="155" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +{* ../../docs_src/security/tutorial005_an_py310.py hl[156] *} ## Declare scopes in *path operations* and dependencies @@ -237,62 +116,25 @@ And the dependency function `get_current_active_user` can also declare sub-depen In this case, it requires the scope `me` (it could require more than one scope). -!!! note - You don't necessarily need to add different scopes in different places. - - We are doing it here to demonstrate how **FastAPI** handles scopes declared at different levels. - -=== "Python 3.10+" - - ```Python hl_lines="4 139 170" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="4 139 170" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` - -=== "Python 3.8+" +/// note - ```Python hl_lines="4 140 171" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` +You don't necessarily need to add different scopes in different places. -=== "Python 3.10+ non-Annotated" +We are doing it here to demonstrate how **FastAPI** handles scopes declared at different levels. - !!! tip - Prefer to use the `Annotated` version if possible. +/// - ```Python hl_lines="3 138 167" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` +{* ../../docs_src/security/tutorial005_an_py310.py hl[5,140,171] *} -=== "Python 3.9+ non-Annotated" +/// info | Technical Details - !!! tip - Prefer to use the `Annotated` version if possible. +`Security` is actually a subclass of `Depends`, and it has just one extra parameter that we'll see later. - ```Python hl_lines="4 139 168" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` +But by using `Security` instead of `Depends`, **FastAPI** will know that it can declare security scopes, use them internally, and document the API with OpenAPI. -=== "Python 3.8+ non-Annotated" +But when you import `Query`, `Path`, `Depends`, `Security` and others from `fastapi`, those are actually functions that return special classes. - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="4 139 168" - {!> ../../../docs_src/security/tutorial005.py!} - ``` - -!!! info "Technical Details" - `Security` is actually a subclass of `Depends`, and it has just one extra parameter that we'll see later. - - But by using `Security` instead of `Depends`, **FastAPI** will know that it can declare security scopes, use them internally, and document the API with OpenAPI. - - But when you import `Query`, `Path`, `Depends`, `Security` and others from `fastapi`, those are actually functions that return special classes. +/// ## Use `SecurityScopes` @@ -300,7 +142,7 @@ Now update the dependency `get_current_user`. This is the one used by the dependencies above. -Here's were we are using the same OAuth2 scheme we created before, declaring it as a dependency: `oauth2_scheme`. +Here's where we are using the same OAuth2 scheme we created before, declaring it as a dependency: `oauth2_scheme`. Because this dependency function doesn't have any scope requirements itself, we can use `Depends` with `oauth2_scheme`, we don't have to use `Security` when we don't need to specify security scopes. @@ -308,50 +150,7 @@ We also declare a special parameter of type `SecurityScopes`, imported from `fas This `SecurityScopes` class is similar to `Request` (`Request` was used to get the request object directly). -=== "Python 3.10+" - - ```Python hl_lines="8 105" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="8 105" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="8 106" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="7 104" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` - -=== "Python 3.9+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="8 105" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="8 105" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +{* ../../docs_src/security/tutorial005_an_py310.py hl[9,106] *} ## Use the `scopes` @@ -361,54 +160,11 @@ It will have a property `scopes` with a list containing all the scopes required The `security_scopes` object (of class `SecurityScopes`) also provides a `scope_str` attribute with a single string, containing those scopes separated by spaces (we are going to use it). -We create an `HTTPException` that we can re-use (`raise`) later at several points. +We create an `HTTPException` that we can reuse (`raise`) later at several points. In this exception, we include the scopes required (if any) as a string separated by spaces (using `scope_str`). We put that string containing the scopes in the `WWW-Authenticate` header (this is part of the spec). -=== "Python 3.10+" - - ```Python hl_lines="105 107-115" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="105 107-115" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="106 108-116" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="104 106-114" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` - -=== "Python 3.9+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="105 107-115" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="105 107-115" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +{* ../../docs_src/security/tutorial005_an_py310.py hl[106,108:116] *} ## Verify the `username` and data shape @@ -424,50 +180,7 @@ Instead of, for example, a `dict`, or something else, as it could break the appl We also verify that we have a user with that username, and if not, we raise that same exception we created before. -=== "Python 3.10+" - - ```Python hl_lines="46 116-127" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="46 116-127" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="47 117-128" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="45 115-126" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` - -=== "Python 3.9+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="46 116-127" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="46 116-127" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +{* ../../docs_src/security/tutorial005_an_py310.py hl[47,117:128] *} ## Verify the `scopes` @@ -475,50 +188,7 @@ We now verify that all the scopes required, by this dependency and all the depen For this, we use `security_scopes.scopes`, that contains a `list` with all these scopes as `str`. -=== "Python 3.10+" - - ```Python hl_lines="128-134" - {!> ../../../docs_src/security/tutorial005_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="128-134" - {!> ../../../docs_src/security/tutorial005_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="129-135" - {!> ../../../docs_src/security/tutorial005_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="127-133" - {!> ../../../docs_src/security/tutorial005_py310.py!} - ``` - -=== "Python 3.9+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="128-134" - {!> ../../../docs_src/security/tutorial005_py39.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="128-134" - {!> ../../../docs_src/security/tutorial005.py!} - ``` +{* ../../docs_src/security/tutorial005_an_py310.py hl[129:135] *} ## Dependency tree and scopes @@ -543,12 +213,15 @@ Here's how the hierarchy of dependencies and scopes looks like: * This `security_scopes` parameter has a property `scopes` with a `list` containing all these scopes declared above, so: * `security_scopes.scopes` will contain `["me", "items"]` for the *path operation* `read_own_items`. * `security_scopes.scopes` will contain `["me"]` for the *path operation* `read_users_me`, because it is declared in the dependency `get_current_active_user`. - * `security_scopes.scopes` will contain `[]` (nothing) for the *path operation* `read_system_status`, because it didn't declare any `Security` with `scopes`, and its dependency, `get_current_user`, doesn't declare any `scope` either. + * `security_scopes.scopes` will contain `[]` (nothing) for the *path operation* `read_system_status`, because it didn't declare any `Security` with `scopes`, and its dependency, `get_current_user`, doesn't declare any `scopes` either. + +/// tip -!!! tip - The important and "magic" thing here is that `get_current_user` will have a different list of `scopes` to check for each *path operation*. +The important and "magic" thing here is that `get_current_user` will have a different list of `scopes` to check for each *path operation*. - All depending on the `scopes` declared in each *path operation* and each dependency in the dependency tree for that specific *path operation*. +All depending on the `scopes` declared in each *path operation* and each dependency in the dependency tree for that specific *path operation*. + +/// ## More details about `SecurityScopes` @@ -584,12 +257,15 @@ But if you are building an OAuth2 application that others would connect to (i.e. The most common is the implicit flow. -The most secure is the code flow, but is more complex to implement as it requires more steps. As it is more complex, many providers end up suggesting the implicit flow. +The most secure is the code flow, but it's more complex to implement as it requires more steps. As it is more complex, many providers end up suggesting the implicit flow. + +/// note + +It's common that each authentication provider names their flows in a different way, to make it part of their brand. -!!! note - It's common that each authentication provider names their flows in a different way, to make it part of their brand. +But in the end, they are implementing the same OAuth2 standard. - But in the end, they are implementing the same OAuth2 standard. +/// **FastAPI** includes utilities for all these OAuth2 authentication flows in `fastapi.security.oauth2`. diff --git a/docs/en/docs/advanced/settings.md b/docs/en/docs/advanced/settings.md index f6db8d2b1..1af19a045 100644 --- a/docs/en/docs/advanced/settings.md +++ b/docs/en/docs/advanced/settings.md @@ -6,130 +6,25 @@ Most of these settings are variable (can change), like database URLs. And many c For this reason it's common to provide them in environment variables that are read by the application. -## Environment Variables +/// tip -!!! tip - If you already know what "environment variables" are and how to use them, feel free to skip to the next section below. +To understand environment variables you can read [Environment Variables](../environment-variables.md){.internal-link target=_blank}. -An environment variable (also known as "env var") is a variable that lives outside of the Python code, in the operating system, and could be read by your Python code (or by other programs as well). +/// -You can create and use environment variables in the shell, without needing Python: - -=== "Linux, macOS, Windows Bash" - -
- - ```console - // You could create an env var MY_NAME with - $ export MY_NAME="Wade Wilson" - - // Then you could use it with other programs, like - $ echo "Hello $MY_NAME" - - Hello Wade Wilson - ``` - -
- -=== "Windows PowerShell" - -
- - ```console - // Create an env var MY_NAME - $ $Env:MY_NAME = "Wade Wilson" - - // Use it with other programs, like - $ echo "Hello $Env:MY_NAME" - - Hello Wade Wilson - ``` - -
- -### Read env vars in Python - -You could also create environment variables outside of Python, in the terminal (or with any other method), and then read them in Python. - -For example you could have a file `main.py` with: - -```Python hl_lines="3" -import os - -name = os.getenv("MY_NAME", "World") -print(f"Hello {name} from Python") -``` - -!!! tip - The second argument to `os.getenv()` is the default value to return. - - If not provided, it's `None` by default, here we provide `"World"` as the default value to use. - -Then you could call that Python program: - -
- -```console -// Here we don't set the env var yet -$ python main.py - -// As we didn't set the env var, we get the default value - -Hello World from Python - -// But if we create an environment variable first -$ export MY_NAME="Wade Wilson" - -// And then call the program again -$ python main.py - -// Now it can read the environment variable - -Hello Wade Wilson from Python -``` - -
- -As environment variables can be set outside of the code, but can be read by the code, and don't have to be stored (committed to `git`) with the rest of the files, it's common to use them for configurations or settings. - -You can also create an environment variable only for a specific program invocation, that is only available to that program, and only for its duration. - -To do that, create it right before the program itself, on the same line: - -
- -```console -// Create an env var MY_NAME in line for this program call -$ MY_NAME="Wade Wilson" python main.py - -// Now it can read the environment variable - -Hello Wade Wilson from Python - -// The env var no longer exists afterwards -$ python main.py - -Hello World from Python -``` - -
- -!!! tip - You can read more about it at The Twelve-Factor App: Config. - -### Types and validation +## Types and validation These environment variables can only handle text strings, as they are external to Python and have to be compatible with other programs and the rest of the system (and even with different operating systems, as Linux, Windows, macOS). -That means that any value read in Python from an environment variable will be a `str`, and any conversion to a different type or validation has to be done in code. +That means that any value read in Python from an environment variable will be a `str`, and any conversion to a different type or any validation has to be done in code. ## Pydantic `Settings` -Fortunately, Pydantic provides a great utility to handle these settings coming from environment variables with Pydantic: Settings management. +Fortunately, Pydantic provides a great utility to handle these settings coming from environment variables with Pydantic: Settings management. ### Install `pydantic-settings` -First, install the `pydantic-settings` package: +First, make sure you create your [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install the `pydantic-settings` package:
@@ -151,8 +46,11 @@ $ pip install "fastapi[all]"
-!!! info - In Pydantic v1 it came included with the main package. Now it is distributed as this independent package so that you can choose to install it or not if you don't need that functionality. +/// info + +In Pydantic v1 it came included with the main package. Now it is distributed as this independent package so that you can choose to install it or not if you don't need that functionality. + +/// ### Create the `Settings` object @@ -162,23 +60,29 @@ The same way as with Pydantic models, you declare class attributes with type ann You can use all the same validation features and tools you use for Pydantic models, like different data types and additional validations with `Field()`. -=== "Pydantic v2" +//// tab | Pydantic v2 + +{* ../../docs_src/settings/tutorial001.py hl[2,5:8,11] *} + +//// - ```Python hl_lines="2 5-8 11" - {!> ../../../docs_src/settings/tutorial001.py!} - ``` +//// tab | Pydantic v1 -=== "Pydantic v1" +/// info - !!! info - In Pydantic v1 you would import `BaseSettings` directly from `pydantic` instead of from `pydantic_settings`. +In Pydantic v1 you would import `BaseSettings` directly from `pydantic` instead of from `pydantic_settings`. - ```Python hl_lines="2 5-8 11" - {!> ../../../docs_src/settings/tutorial001_pv1.py!} - ``` +/// -!!! tip - If you want something quick to copy and paste, don't use this example, use the last one below. +{* ../../docs_src/settings/tutorial001_pv1.py hl[2,5:8,11] *} + +//// + +/// tip + +If you want something quick to copy and paste, don't use this example, use the last one below. + +/// Then, when you create an instance of that `Settings` class (in this case, in the `settings` object), Pydantic will read the environment variables in a case-insensitive way, so, an upper-case variable `APP_NAME` will still be read for the attribute `app_name`. @@ -188,9 +92,7 @@ Next it will convert and validate the data. So, when you use that `settings` obj Then you can use the new `settings` object in your application: -```Python hl_lines="18-20" -{!../../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[18:20] *} ### Run the server @@ -199,15 +101,18 @@ Next, you would run the server passing the configurations as environment variabl
```console -$ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uvicorn main:app +$ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" fastapi run main.py INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ```
-!!! tip - To set multiple env vars for a single command just separate them with a space, and put them all before the command. +/// tip + +To set multiple env vars for a single command just separate them with a space, and put them all before the command. + +/// And then the `admin_email` setting would be set to `"deadpool@example.com"`. @@ -221,18 +126,17 @@ You could put those settings in another module file as you saw in [Bigger Applic For example, you could have a file `config.py` with: -```Python -{!../../../docs_src/settings/app01/config.py!} -``` +{* ../../docs_src/settings/app01/config.py *} And then use it in a file `main.py`: -```Python hl_lines="3 11-13" -{!../../../docs_src/settings/app01/main.py!} -``` +{* ../../docs_src/settings/app01/main.py hl[3,11:13] *} + +/// tip + +You would also need a file `__init__.py` as you saw in [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}. -!!! tip - You would also need a file `__init__.py` as you saw on [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}. +/// ## Settings in a dependency @@ -244,9 +148,7 @@ This could be especially useful during testing, as it's very easy to override a Coming from the previous example, your `config.py` file could look like: -```Python hl_lines="10" -{!../../../docs_src/settings/app02/config.py!} -``` +{* ../../docs_src/settings/app02/config.py hl[10] *} Notice that now we don't create a default instance `settings = Settings()`. @@ -254,62 +156,25 @@ Notice that now we don't create a default instance `settings = Settings()`. Now we create a dependency that returns a new `config.Settings()`. -=== "Python 3.9+" - - ```Python hl_lines="6 12-13" - {!> ../../../docs_src/settings/app02_an_py39/main.py!} - ``` - -=== "Python 3.8+" +{* ../../docs_src/settings/app02_an_py39/main.py hl[6,12:13] *} - ```Python hl_lines="6 12-13" - {!> ../../../docs_src/settings/app02_an/main.py!} - ``` +/// tip -=== "Python 3.8+ non-Annotated" +We'll discuss the `@lru_cache` in a bit. - !!! tip - Prefer to use the `Annotated` version if possible. +For now you can assume `get_settings()` is a normal function. - ```Python hl_lines="5 11-12" - {!> ../../../docs_src/settings/app02/main.py!} - ``` - -!!! tip - We'll discuss the `@lru_cache` in a bit. - - For now you can assume `get_settings()` is a normal function. +/// And then we can require it from the *path operation function* as a dependency and use it anywhere we need it. -=== "Python 3.9+" - - ```Python hl_lines="17 19-21" - {!> ../../../docs_src/settings/app02_an_py39/main.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="17 19-21" - {!> ../../../docs_src/settings/app02_an/main.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="16 18-20" - {!> ../../../docs_src/settings/app02/main.py!} - ``` +{* ../../docs_src/settings/app02_an_py39/main.py hl[17,19:21] *} ### Settings and testing Then it would be very easy to provide a different settings object during testing by creating a dependency override for `get_settings`: -```Python hl_lines="9-10 13 21" -{!../../../docs_src/settings/app02/test_main.py!} -``` +{* ../../docs_src/settings/app02/test_main.py hl[9:10,13,21] *} In the dependency override we set a new value for the `admin_email` when creating the new `Settings` object, and then we return that new object. @@ -321,15 +186,21 @@ If you have many settings that possibly change a lot, maybe in different environ This practice is common enough that it has a name, these environment variables are commonly placed in a file `.env`, and the file is called a "dotenv". -!!! tip - A file starting with a dot (`.`) is a hidden file in Unix-like systems, like Linux and macOS. +/// tip - But a dotenv file doesn't really have to have that exact filename. +A file starting with a dot (`.`) is a hidden file in Unix-like systems, like Linux and macOS. + +But a dotenv file doesn't really have to have that exact filename. + +/// Pydantic has support for reading from these types of files using an external library. You can read more at Pydantic Settings: Dotenv (.env) support. -!!! tip - For this to work, you need to `pip install python-dotenv`. +/// tip + +For this to work, you need to `pip install python-dotenv`. + +/// ### The `.env` file @@ -344,32 +215,41 @@ APP_NAME="ChimichangApp" And then update your `config.py` with: -=== "Pydantic v2" +//// tab | Pydantic v2 + +{* ../../docs_src/settings/app03_an/config.py hl[9] *} + +/// tip - ```Python hl_lines="9" - {!> ../../../docs_src/settings/app03_an/config.py!} - ``` +The `model_config` attribute is used just for Pydantic configuration. You can read more at Pydantic: Concepts: Configuration. - !!! tip - The `model_config` attribute is used just for Pydantic configuration. You can read more at Pydantic Model Config. +/// -=== "Pydantic v1" +//// - ```Python hl_lines="9-10" - {!> ../../../docs_src/settings/app03_an/config_pv1.py!} - ``` +//// tab | Pydantic v1 - !!! tip - The `Config` class is used just for Pydantic configuration. You can read more at Pydantic Model Config. +{* ../../docs_src/settings/app03_an/config_pv1.py hl[9:10] *} -!!! info - In Pydantic version 1 the configuration was done in an internal class `Config`, in Pydantic version 2 it's done in an attribute `model_config`. This attribute takes a `dict`, and to get autocompletion and inline errors you can import and use `SettingsConfigDict` to define that `dict`. +/// tip + +The `Config` class is used just for Pydantic configuration. You can read more at Pydantic Model Config. + +/// + +//// + +/// info + +In Pydantic version 1 the configuration was done in an internal class `Config`, in Pydantic version 2 it's done in an attribute `model_config`. This attribute takes a `dict`, and to get autocompletion and inline errors you can import and use `SettingsConfigDict` to define that `dict`. + +/// Here we define the config `env_file` inside of your Pydantic `Settings` class, and set the value to the filename with the dotenv file we want to use. ### Creating the `Settings` only once with `lru_cache` -Reading a file from disk is normally a costly (slow) operation, so you probably want to do it only once and then re-use the same settings object, instead of reading it for each request. +Reading a file from disk is normally a costly (slow) operation, so you probably want to do it only once and then reuse the same settings object, instead of reading it for each request. But every time we do: @@ -390,28 +270,9 @@ we would create that object for each request, and we would be reading the `.env` But as we are using the `@lru_cache` decorator on top, the `Settings` object will be created only once, the first time it's called. ✔️ -=== "Python 3.9+" - - ```Python hl_lines="1 11" - {!> ../../../docs_src/settings/app03_an_py39/main.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="1 11" - {!> ../../../docs_src/settings/app03_an/main.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="1 10" - {!> ../../../docs_src/settings/app03/main.py!} - ``` +{* ../../docs_src/settings/app03_an_py39/main.py hl[1,11] *} -Then for any subsequent calls of `get_settings()` in the dependencies for the next requests, instead of executing the internal code of `get_settings()` and creating a new `Settings` object, it will return the same object that was returned on the first call, again and again. +Then for any subsequent call of `get_settings()` in the dependencies for the next requests, instead of executing the internal code of `get_settings()` and creating a new `Settings` object, it will return the same object that was returned on the first call, again and again. #### `lru_cache` Technical Details diff --git a/docs/en/docs/advanced/sub-applications.md b/docs/en/docs/advanced/sub-applications.md index a089632ac..48e329fc1 100644 --- a/docs/en/docs/advanced/sub-applications.md +++ b/docs/en/docs/advanced/sub-applications.md @@ -10,9 +10,7 @@ If you need to have two independent FastAPI applications, with their own indepen First, create the main, top-level, **FastAPI** application, and its *path operations*: -```Python hl_lines="3 6-8" -{!../../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[3, 6:8] *} ### Sub-application @@ -20,9 +18,7 @@ Then, create your sub-application, and its *path operations*. This sub-application is just another standard FastAPI application, but this is the one that will be "mounted": -```Python hl_lines="11 14-16" -{!../../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11, 14:16] *} ### Mount the sub-application @@ -30,18 +26,16 @@ In your top-level application, `app`, mount the sub-application, `subapi`. In this case, it will be mounted at the path `/subapi`: -```Python hl_lines="11 19" -{!../../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11, 19] *} ### Check the automatic API docs -Now, run `uvicorn` with the main app, if your file is `main.py`, it would be: +Now, run the `fastapi` command with your file:
```console -$ uvicorn main:app --reload +$ fastapi dev main.py INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` @@ -70,4 +64,4 @@ That way, the sub-application will know to use that path prefix for the docs UI. And the sub-application could also have its own mounted sub-applications and everything would work correctly, because FastAPI handles all these `root_path`s automatically. -You will learn more about the `root_path` and how to use it explicitly in the section about [Behind a Proxy](./behind-a-proxy.md){.internal-link target=_blank}. +You will learn more about the `root_path` and how to use it explicitly in the section about [Behind a Proxy](behind-a-proxy.md){.internal-link target=_blank}. diff --git a/docs/en/docs/advanced/templates.md b/docs/en/docs/advanced/templates.md index 6055b3017..d9b0ca6f1 100644 --- a/docs/en/docs/advanced/templates.md +++ b/docs/en/docs/advanced/templates.md @@ -8,7 +8,7 @@ There are utilities to configure it easily that you can use directly in your **F ## Install dependencies -Install `jinja2`: +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and install `jinja2`:
@@ -23,33 +23,40 @@ $ pip install jinja2 ## Using `Jinja2Templates` * Import `Jinja2Templates`. -* Create a `templates` object that you can re-use later. +* Create a `templates` object that you can reuse later. * Declare a `Request` parameter in the *path operation* that will return a template. * Use the `templates` you created to render and return a `TemplateResponse`, pass the name of the template, the request object, and a "context" dictionary with key-value pairs to be used inside of the Jinja2 template. -```Python hl_lines="4 11 15-18" -{!../../../docs_src/templates/tutorial001.py!} -``` +{* ../../docs_src/templates/tutorial001.py hl[4,11,15:18] *} + +/// note + +Before FastAPI 0.108.0, Starlette 0.29.0, the `name` was the first parameter. + +Also, before that, in previous versions, the `request` object was passed as part of the key-value pairs in the context for Jinja2. + +/// + +/// tip + +By declaring `response_class=HTMLResponse` the docs UI will be able to know that the response will be HTML. -!!! note - Before FastAPI 0.108.0, Starlette 0.29.0, the `name` was the first parameter. +/// - Also, before that, in previous versions, the `request` object was passed as part of the key-value pairs in the context for Jinja2. +/// note | Technical Details -!!! tip - By declaring `response_class=HTMLResponse` the docs UI will be able to know that the response will be HTML. +You could also use `from starlette.templating import Jinja2Templates`. -!!! note "Technical Details" - You could also use `from starlette.templating import Jinja2Templates`. +**FastAPI** provides the same `starlette.templating` as `fastapi.templating` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `Request` and `StaticFiles`. - **FastAPI** provides the same `starlette.templating` as `fastapi.templating` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `Request` and `StaticFiles`. +/// ## Writing templates Then you can write a template at `templates/item.html` with, for example: ```jinja hl_lines="7" -{!../../../docs_src/templates/templates/item.html!} +{!../../docs_src/templates/templates/item.html!} ``` ### Template Context Values @@ -103,13 +110,13 @@ For example, with an ID of `42`, this would render: You can also use `url_for()` inside of the template, and use it, for example, with the `StaticFiles` you mounted with the `name="static"`. ```jinja hl_lines="4" -{!../../../docs_src/templates/templates/item.html!} +{!../../docs_src/templates/templates/item.html!} ``` In this example, it would link to a CSS file at `static/styles.css` with: ```CSS hl_lines="4" -{!../../../docs_src/templates/static/styles.css!} +{!../../docs_src/templates/static/styles.css!} ``` And because you are using `StaticFiles`, that CSS file would be served automatically by your **FastAPI** application at the URL `/static/styles.css`. diff --git a/docs/en/docs/advanced/testing-database.md b/docs/en/docs/advanced/testing-database.md deleted file mode 100644 index 1c0669b9c..000000000 --- a/docs/en/docs/advanced/testing-database.md +++ /dev/null @@ -1,102 +0,0 @@ -# Testing a Database - -!!! info - These docs are about to be updated. 🎉 - - The current version assumes Pydantic v1, and SQLAlchemy versions less than 2.0. - - The new docs will include Pydantic v2 and will use SQLModel (which is also based on SQLAlchemy) once it is updated to use Pydantic v2 as well. - -You can use the same dependency overrides from [Testing Dependencies with Overrides](testing-dependencies.md){.internal-link target=_blank} to alter a database for testing. - -You could want to set up a different database for testing, rollback the data after the tests, pre-fill it with some testing data, etc. - -The main idea is exactly the same you saw in that previous chapter. - -## Add tests for the SQL app - -Let's update the example from [SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank} to use a testing database. - -All the app code is the same, you can go back to that chapter check how it was. - -The only changes here are in the new testing file. - -Your normal dependency `get_db()` would return a database session. - -In the test, you could use a dependency override to return your *custom* database session instead of the one that would be used normally. - -In this example we'll create a temporary database only for the tests. - -## File structure - -We create a new file at `sql_app/tests/test_sql_app.py`. - -So the new file structure looks like: - -``` hl_lines="9-11" -. -└── sql_app - ├── __init__.py - ├── crud.py - ├── database.py - ├── main.py - ├── models.py - ├── schemas.py - └── tests - ├── __init__.py - └── test_sql_app.py -``` - -## Create the new database session - -First, we create a new database session with the new database. - -We'll use an in-memory database that persists during the tests instead of the local file `sql_app.db`. - -But the rest of the session code is more or less the same, we just copy it. - -```Python hl_lines="8-13" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -!!! tip - You could reduce duplication in that code by putting it in a function and using it from both `database.py` and `tests/test_sql_app.py`. - - For simplicity and to focus on the specific testing code, we are just copying it. - -## Create the database - -Because now we are going to use a new database in a new file, we need to make sure we create the database with: - -```Python -Base.metadata.create_all(bind=engine) -``` - -That is normally called in `main.py`, but the line in `main.py` uses the database file `sql_app.db`, and we need to make sure we create `test.db` for the tests. - -So we add that line here, with the new file. - -```Python hl_lines="16" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -## Dependency override - -Now we create the dependency override and add it to the overrides for our app. - -```Python hl_lines="19-24 27" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -!!! tip - The code for `override_get_db()` is almost exactly the same as for `get_db()`, but in `override_get_db()` we use the `TestingSessionLocal` for the testing database instead. - -## Test the app - -Then we can just test the app as normally. - -```Python hl_lines="32-47" -{!../../../docs_src/sql_databases/sql_app/tests/test_sql_app.py!} -``` - -And all the modifications we made in the database during the tests will be in the `test.db` database instead of the main `sql_app.db`. diff --git a/docs/en/docs/advanced/testing-dependencies.md b/docs/en/docs/advanced/testing-dependencies.md index 57dd87f56..17b4f9814 100644 --- a/docs/en/docs/advanced/testing-dependencies.md +++ b/docs/en/docs/advanced/testing-dependencies.md @@ -28,48 +28,17 @@ To override a dependency for testing, you put as a key the original dependency ( And then **FastAPI** will call that override instead of the original dependency. -=== "Python 3.10+" +{* ../../docs_src/dependency_testing/tutorial001_an_py310.py hl[26:27,30] *} - ```Python hl_lines="26-27 30" - {!> ../../../docs_src/dependency_testing/tutorial001_an_py310.py!} - ``` +/// tip -=== "Python 3.9+" +You can set a dependency override for a dependency used anywhere in your **FastAPI** application. - ```Python hl_lines="28-29 32" - {!> ../../../docs_src/dependency_testing/tutorial001_an_py39.py!} - ``` +The original dependency could be used in a *path operation function*, a *path operation decorator* (when you don't use the return value), a `.include_router()` call, etc. -=== "Python 3.8+" +FastAPI will still be able to override it. - ```Python hl_lines="29-30 33" - {!> ../../../docs_src/dependency_testing/tutorial001_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="24-25 28" - {!> ../../../docs_src/dependency_testing/tutorial001_py310.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="28-29 32" - {!> ../../../docs_src/dependency_testing/tutorial001.py!} - ``` - -!!! tip - You can set a dependency override for a dependency used anywhere in your **FastAPI** application. - - The original dependency could be used in a *path operation function*, a *path operation decorator* (when you don't use the return value), a `.include_router()` call, etc. - - FastAPI will still be able to override it. +/// Then you can reset your overrides (remove them) by setting `app.dependency_overrides` to be an empty `dict`: @@ -77,5 +46,8 @@ Then you can reset your overrides (remove them) by setting `app.dependency_overr app.dependency_overrides = {} ``` -!!! tip - If you want to override a dependency only during some tests, you can set the override at the beginning of the test (inside the test function) and reset it at the end (at the end of the test function). +/// tip + +If you want to override a dependency only during some tests, you can set the override at the beginning of the test (inside the test function) and reset it at the end (at the end of the test function). + +/// diff --git a/docs/en/docs/advanced/testing-events.md b/docs/en/docs/advanced/testing-events.md index b24a2ccfe..0c554c4ec 100644 --- a/docs/en/docs/advanced/testing-events.md +++ b/docs/en/docs/advanced/testing-events.md @@ -2,6 +2,4 @@ When you need your event handlers (`startup` and `shutdown`) to run in your tests, you can use the `TestClient` with a `with` statement: -```Python hl_lines="9-12 20-24" -{!../../../docs_src/app_testing/tutorial003.py!} -``` +{* ../../docs_src/app_testing/tutorial003.py hl[9:12,20:24] *} diff --git a/docs/en/docs/advanced/testing-websockets.md b/docs/en/docs/advanced/testing-websockets.md index 4101e5a16..60dfdc343 100644 --- a/docs/en/docs/advanced/testing-websockets.md +++ b/docs/en/docs/advanced/testing-websockets.md @@ -4,9 +4,10 @@ You can use the same `TestClient` to test WebSockets. For this, you use the `TestClient` in a `with` statement, connecting to the WebSocket: -```Python hl_lines="27-31" -{!../../../docs_src/app_testing/tutorial002.py!} -``` +{* ../../docs_src/app_testing/tutorial002.py hl[27:31] *} -!!! note - For more details, check Starlette's documentation for testing WebSockets. +/// note + +For more details, check Starlette's documentation for testing WebSockets. + +/// diff --git a/docs/en/docs/advanced/using-request-directly.md b/docs/en/docs/advanced/using-request-directly.md index 500afa34b..2f88c8f20 100644 --- a/docs/en/docs/advanced/using-request-directly.md +++ b/docs/en/docs/advanced/using-request-directly.md @@ -29,24 +29,28 @@ Let's imagine you want to get the client's IP address/host inside of your *path For that you need to access the request directly. -```Python hl_lines="1 7-8" -{!../../../docs_src/using_request_directly/tutorial001.py!} -``` +{* ../../docs_src/using_request_directly/tutorial001.py hl[1,7:8] *} By declaring a *path operation function* parameter with the type being the `Request` **FastAPI** will know to pass the `Request` in that parameter. -!!! tip - Note that in this case, we are declaring a path parameter beside the request parameter. +/// tip - So, the path parameter will be extracted, validated, converted to the specified type and annotated with OpenAPI. +Note that in this case, we are declaring a path parameter beside the request parameter. - The same way, you can declare any other parameter as normally, and additionally, get the `Request` too. +So, the path parameter will be extracted, validated, converted to the specified type and annotated with OpenAPI. + +The same way, you can declare any other parameter as normally, and additionally, get the `Request` too. + +/// ## `Request` documentation You can read more details about the `Request` object in the official Starlette documentation site. -!!! note "Technical Details" - You could also use `from starlette.requests import Request`. +/// note | Technical Details + +You could also use `from starlette.requests import Request`. + +**FastAPI** provides it directly just as a convenience for you, the developer. But it comes directly from Starlette. - **FastAPI** provides it directly just as a convenience for you, the developer. But it comes directly from Starlette. +/// diff --git a/docs/en/docs/advanced/websockets.md b/docs/en/docs/advanced/websockets.md index b8dfab1d1..ee8e901df 100644 --- a/docs/en/docs/advanced/websockets.md +++ b/docs/en/docs/advanced/websockets.md @@ -4,7 +4,7 @@ You can use @@ -38,30 +38,27 @@ In production you would have one of the options above. But it's the simplest way to focus on the server-side of WebSockets and have a working example: -```Python hl_lines="2 6-38 41-43" -{!../../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[2,6:38,41:43] *} ## Create a `websocket` In your **FastAPI** application, create a `websocket`: -```Python hl_lines="1 46-47" -{!../../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[1,46:47] *} + +/// note | Technical Details -!!! note "Technical Details" - You could also use `from starlette.websockets import WebSocket`. +You could also use `from starlette.websockets import WebSocket`. - **FastAPI** provides the same `WebSocket` directly just as a convenience for you, the developer. But it comes directly from Starlette. +**FastAPI** provides the same `WebSocket` directly just as a convenience for you, the developer. But it comes directly from Starlette. + +/// ## Await for messages and send messages In your WebSocket route you can `await` for messages and send messages. -```Python hl_lines="48-52" -{!../../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[48:52] *} You can receive and send binary, text, and JSON data. @@ -72,7 +69,7 @@ If your file is named `main.py`, run your application with:
```console -$ uvicorn main:app --reload +$ fastapi dev main.py INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` @@ -112,46 +109,15 @@ In WebSocket endpoints you can import from `fastapi` and use: They work the same way as for other FastAPI endpoints/*path operations*: -=== "Python 3.10+" - - ```Python hl_lines="68-69 82" - {!> ../../../docs_src/websockets/tutorial002_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="68-69 82" - {!> ../../../docs_src/websockets/tutorial002_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="69-70 83" - {!> ../../../docs_src/websockets/tutorial002_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" +{* ../../docs_src/websockets/tutorial002_an_py310.py hl[68:69,82] *} - !!! tip - Prefer to use the `Annotated` version if possible. +/// info - ```Python hl_lines="66-67 79" - {!> ../../../docs_src/websockets/tutorial002_py310.py!} - ``` +As this is a WebSocket it doesn't really make sense to raise an `HTTPException`, instead we raise a `WebSocketException`. -=== "Python 3.8+ non-Annotated" +You can use a closing code from the valid codes defined in the specification. - !!! tip - Prefer to use the `Annotated` version if possible. - - ```Python hl_lines="68-69 81" - {!> ../../../docs_src/websockets/tutorial002.py!} - ``` - -!!! info - As this is a WebSocket it doesn't really make sense to raise an `HTTPException`, instead we raise a `WebSocketException`. - - You can use a closing code from the valid codes defined in the specification. +/// ### Try the WebSockets with dependencies @@ -160,7 +126,7 @@ If your file is named `main.py`, run your application with:
```console -$ uvicorn main:app --reload +$ fastapi dev main.py INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` @@ -174,8 +140,11 @@ There you can set: * The "Item ID", used in the path. * The "Token" used as a query parameter. -!!! tip - Notice that the query `token` will be handled by a dependency. +/// tip + +Notice that the query `token` will be handled by a dependency. + +/// With that you can connect the WebSocket and then send and receive messages: @@ -185,17 +154,7 @@ With that you can connect the WebSocket and then send and receive messages: When a WebSocket connection is closed, the `await websocket.receive_text()` will raise a `WebSocketDisconnect` exception, which you can then catch and handle like in this example. -=== "Python 3.9+" - - ```Python hl_lines="79-81" - {!> ../../../docs_src/websockets/tutorial003_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="81-83" - {!> ../../../docs_src/websockets/tutorial003.py!} - ``` +{* ../../docs_src/websockets/tutorial003_py39.py hl[79:81] *} To try it out: @@ -209,12 +168,15 @@ That will raise the `WebSocketDisconnect` exception, and all the other clients w Client #1596980209979 left the chat ``` -!!! tip - The app above is a minimal and simple example to demonstrate how to handle and broadcast messages to several WebSocket connections. +/// tip + +The app above is a minimal and simple example to demonstrate how to handle and broadcast messages to several WebSocket connections. + +But keep in mind that, as everything is handled in memory, in a single list, it will only work while the process is running, and will only work with a single process. - But keep in mind that, as everything is handled in memory, in a single list, it will only work while the process is running, and will only work with a single process. +If you need something easy to integrate with FastAPI but that is more robust, supported by Redis, PostgreSQL or others, check encode/broadcaster. - If you need something easy to integrate with FastAPI but that is more robust, supported by Redis, PostgreSQL or others, check encode/broadcaster. +/// ## More info diff --git a/docs/en/docs/advanced/wsgi.md b/docs/en/docs/advanced/wsgi.md index cfe3c78c1..296eb1364 100644 --- a/docs/en/docs/advanced/wsgi.md +++ b/docs/en/docs/advanced/wsgi.md @@ -1,6 +1,6 @@ # Including WSGI - Flask, Django, others -You can mount WSGI applications as you saw with [Sub Applications - Mounts](./sub-applications.md){.internal-link target=_blank}, [Behind a Proxy](./behind-a-proxy.md){.internal-link target=_blank}. +You can mount WSGI applications as you saw with [Sub Applications - Mounts](sub-applications.md){.internal-link target=_blank}, [Behind a Proxy](behind-a-proxy.md){.internal-link target=_blank}. For that, you can use the `WSGIMiddleware` and use it to wrap your WSGI application, for example, Flask, Django, etc. @@ -12,9 +12,7 @@ Then wrap the WSGI (e.g. Flask) app with the middleware. And then mount that under a path. -```Python hl_lines="2-3 23" -{!../../../docs_src/wsgi/tutorial001.py!} -``` +{* ../../docs_src/wsgi/tutorial001.py hl[2:3,3] *} ## Check it @@ -22,7 +20,7 @@ Now, every request under the path `/v1/` will be handled by the Flask applicatio And the rest will be handled by **FastAPI**. -If you run it with Uvicorn and go to http://localhost:8000/v1/ you will see the response from Flask: +If you run it and go to http://localhost:8000/v1/ you will see the response from Flask: ```txt Hello, World from Flask! diff --git a/docs/en/docs/alternatives.md b/docs/en/docs/alternatives.md index 70bbcac91..326f0dbe1 100644 --- a/docs/en/docs/alternatives.md +++ b/docs/en/docs/alternatives.md @@ -1,6 +1,6 @@ # Alternatives, Inspiration and Comparisons -What inspired **FastAPI**, how it compares to other alternatives and what it learned from them. +What inspired **FastAPI**, how it compares to alternatives and what it learned from them. ## Intro @@ -30,12 +30,17 @@ It is used by many companies including Mozilla, Red Hat and Eventbrite. It was one of the first examples of **automatic API documentation**, and this was specifically one of the first ideas that inspired "the search for" **FastAPI**. -!!! note - Django REST Framework was created by Tom Christie. The same creator of Starlette and Uvicorn, on which **FastAPI** is based. +/// note +Django REST Framework was created by Tom Christie. The same creator of Starlette and Uvicorn, on which **FastAPI** is based. -!!! check "Inspired **FastAPI** to" - Have an automatic API documentation web user interface. +/// + +/// check | Inspired **FastAPI** to + +Have an automatic API documentation web user interface. + +/// ### Flask @@ -51,11 +56,13 @@ This decoupling of parts, and being a "microframework" that could be extended to Given the simplicity of Flask, it seemed like a good match for building APIs. The next thing to find was a "Django REST Framework" for Flask. -!!! check "Inspired **FastAPI** to" - Be a micro-framework. Making it easy to mix and match the tools and parts needed. +/// check | Inspired **FastAPI** to - Have a simple and easy to use routing system. +Be a micro-framework. Making it easy to mix and match the tools and parts needed. +Have a simple and easy to use routing system. + +/// ### Requests @@ -91,11 +98,13 @@ def read_url(): See the similarities in `requests.get(...)` and `@app.get(...)`. -!!! check "Inspired **FastAPI** to" - * Have a simple and intuitive API. - * Use HTTP method names (operations) directly, in a straightforward and intuitive way. - * Have sensible defaults, but powerful customizations. +/// check | Inspired **FastAPI** to + +* Have a simple and intuitive API. +* Use HTTP method names (operations) directly, in a straightforward and intuitive way. +* Have sensible defaults, but powerful customizations. +/// ### Swagger / OpenAPI @@ -109,15 +118,18 @@ At some point, Swagger was given to the Linux Foundation, to be renamed OpenAPI. That's why when talking about version 2.0 it's common to say "Swagger", and for version 3+ "OpenAPI". -!!! check "Inspired **FastAPI** to" - Adopt and use an open standard for API specifications, instead of a custom schema. +/// check | Inspired **FastAPI** to + +Adopt and use an open standard for API specifications, instead of a custom schema. - And integrate standards-based user interface tools: +And integrate standards-based user interface tools: - * Swagger UI - * ReDoc +* Swagger UI +* ReDoc - These two were chosen for being fairly popular and stable, but doing a quick search, you could find dozens of additional alternative user interfaces for OpenAPI (that you can use with **FastAPI**). +These two were chosen for being fairly popular and stable, but doing a quick search, you could find dozens of alternative user interfaces for OpenAPI (that you can use with **FastAPI**). + +/// ### Flask REST frameworks @@ -135,8 +147,11 @@ These features are what Marshmallow was built to provide. It is a great library, But it was created before there existed Python type hints. So, to define every schema you need to use specific utils and classes provided by Marshmallow. -!!! check "Inspired **FastAPI** to" - Use code to define "schemas" that provide data types and validation, automatically. +/// check | Inspired **FastAPI** to + +Use code to define "schemas" that provide data types and validation, automatically. + +/// ### Webargs @@ -148,11 +163,17 @@ It uses Marshmallow underneath to do the data validation. And it was created by It's a great tool and I have used it a lot too, before having **FastAPI**. -!!! info - Webargs was created by the same Marshmallow developers. +/// info + +Webargs was created by the same Marshmallow developers. + +/// + +/// check | Inspired **FastAPI** to -!!! check "Inspired **FastAPI** to" - Have automatic validation of incoming request data. +Have automatic validation of incoming request data. + +/// ### APISpec @@ -172,12 +193,17 @@ But then, we have again the problem of having a micro-syntax, inside of a Python The editor can't help much with that. And if we modify parameters or Marshmallow schemas and forget to also modify that YAML docstring, the generated schema would be obsolete. -!!! info - APISpec was created by the same Marshmallow developers. +/// info + +APISpec was created by the same Marshmallow developers. + +/// +/// check | Inspired **FastAPI** to -!!! check "Inspired **FastAPI** to" - Support the open standard for APIs, OpenAPI. +Support the open standard for APIs, OpenAPI. + +/// ### Flask-apispec @@ -199,11 +225,17 @@ Using it led to the creation of several Flask full-stack generators. These are t And these same full-stack generators were the base of the [**FastAPI** Project Generators](project-generation.md){.internal-link target=_blank}. -!!! info - Flask-apispec was created by the same Marshmallow developers. +/// info + +Flask-apispec was created by the same Marshmallow developers. + +/// -!!! check "Inspired **FastAPI** to" - Generate the OpenAPI schema automatically, from the same code that defines serialization and validation. +/// check | Inspired **FastAPI** to + +Generate the OpenAPI schema automatically, from the same code that defines serialization and validation. + +/// ### NestJS (and Angular) @@ -219,24 +251,33 @@ But as TypeScript data is not preserved after compilation to JavaScript, it cann It can't handle nested models very well. So, if the JSON body in the request is a JSON object that has inner fields that in turn are nested JSON objects, it cannot be properly documented and validated. -!!! check "Inspired **FastAPI** to" - Use Python types to have great editor support. +/// check | Inspired **FastAPI** to + +Use Python types to have great editor support. - Have a powerful dependency injection system. Find a way to minimize code repetition. +Have a powerful dependency injection system. Find a way to minimize code repetition. + +/// ### Sanic It was one of the first extremely fast Python frameworks based on `asyncio`. It was made to be very similar to Flask. -!!! note "Technical Details" - It used `uvloop` instead of the default Python `asyncio` loop. That's what made it so fast. +/// note | Technical Details + +It used `uvloop` instead of the default Python `asyncio` loop. That's what made it so fast. - It clearly inspired Uvicorn and Starlette, that are currently faster than Sanic in open benchmarks. +It clearly inspired Uvicorn and Starlette, that are currently faster than Sanic in open benchmarks. -!!! check "Inspired **FastAPI** to" - Find a way to have a crazy performance. +/// - That's why **FastAPI** is based on Starlette, as it is the fastest framework available (tested by third-party benchmarks). +/// check | Inspired **FastAPI** to + +Find a way to have a crazy performance. + +That's why **FastAPI** is based on Starlette, as it is the fastest framework available (tested by third-party benchmarks). + +/// ### Falcon @@ -246,12 +287,15 @@ It is designed to have functions that receive two parameters, one "request" and So, data validation, serialization, and documentation, have to be done in code, not automatically. Or they have to be implemented as a framework on top of Falcon, like Hug. This same distinction happens in other frameworks that are inspired by Falcon's design, of having one request object and one response object as parameters. -!!! check "Inspired **FastAPI** to" - Find ways to get great performance. +/// check | Inspired **FastAPI** to - Along with Hug (as Hug is based on Falcon) inspired **FastAPI** to declare a `response` parameter in functions. +Find ways to get great performance. - Although in FastAPI it's optional, and is used mainly to set headers, cookies, and alternative status codes. +Along with Hug (as Hug is based on Falcon) inspired **FastAPI** to declare a `response` parameter in functions. + +Although in FastAPI it's optional, and is used mainly to set headers, cookies, and alternative status codes. + +/// ### Molten @@ -269,12 +313,15 @@ The dependency injection system requires pre-registration of the dependencies an Routes are declared in a single place, using functions declared in other places (instead of using decorators that can be placed right on top of the function that handles the endpoint). This is closer to how Django does it than to how Flask (and Starlette) does it. It separates in the code things that are relatively tightly coupled. -!!! check "Inspired **FastAPI** to" - Define extra validations for data types using the "default" value of model attributes. This improves editor support, and it was not available in Pydantic before. +/// check | Inspired **FastAPI** to + +Define extra validations for data types using the "default" value of model attributes. This improves editor support, and it was not available in Pydantic before. - This actually inspired updating parts of Pydantic, to support the same validation declaration style (all this functionality is now already available in Pydantic). +This actually inspired updating parts of Pydantic, to support the same validation declaration style (all this functionality is now already available in Pydantic). -### Hug +/// + +### Hug Hug was one of the first frameworks to implement the declaration of API parameter types using Python type hints. This was a great idea that inspired other tools to do the same. @@ -288,15 +335,21 @@ It has an interesting, uncommon feature: using the same framework, it's possible As it is based on the previous standard for synchronous Python web frameworks (WSGI), it can't handle Websockets and other things, although it still has high performance too. -!!! info - Hug was created by Timothy Crosley, the same creator of `isort`, a great tool to automatically sort imports in Python files. +/// info + +Hug was created by Timothy Crosley, the same creator of `isort`, a great tool to automatically sort imports in Python files. + +/// -!!! check "Ideas inspired in **FastAPI**" - Hug inspired parts of APIStar, and was one of the tools I found most promising, alongside APIStar. +/// check | Ideas inspiring **FastAPI** - Hug helped inspiring **FastAPI** to use Python type hints to declare parameters, and to generate a schema defining the API automatically. +Hug inspired parts of APIStar, and was one of the tools I found most promising, alongside APIStar. - Hug inspired **FastAPI** to declare a `response` parameter in functions to set headers and cookies. +Hug helped inspiring **FastAPI** to use Python type hints to declare parameters, and to generate a schema defining the API automatically. + +Hug inspired **FastAPI** to declare a `response` parameter in functions to set headers and cookies. + +/// ### APIStar (<= 0.5) @@ -322,27 +375,33 @@ It was no longer an API web framework, as the creator needed to focus on Starlet Now APIStar is a set of tools to validate OpenAPI specifications, not a web framework. -!!! info - APIStar was created by Tom Christie. The same guy that created: +/// info + +APIStar was created by Tom Christie. The same guy that created: - * Django REST Framework - * Starlette (in which **FastAPI** is based) - * Uvicorn (used by Starlette and **FastAPI**) +* Django REST Framework +* Starlette (in which **FastAPI** is based) +* Uvicorn (used by Starlette and **FastAPI**) -!!! check "Inspired **FastAPI** to" - Exist. +/// - The idea of declaring multiple things (data validation, serialization and documentation) with the same Python types, that at the same time provided great editor support, was something I considered a brilliant idea. +/// check | Inspired **FastAPI** to - And after searching for a long time for a similar framework and testing many different alternatives, APIStar was the best option available. +Exist. - Then APIStar stopped to exist as a server and Starlette was created, and was a new better foundation for such a system. That was the final inspiration to build **FastAPI**. +The idea of declaring multiple things (data validation, serialization and documentation) with the same Python types, that at the same time provided great editor support, was something I considered a brilliant idea. - I consider **FastAPI** a "spiritual successor" to APIStar, while improving and increasing the features, typing system, and other parts, based on the learnings from all these previous tools. +And after searching for a long time for a similar framework and testing many different alternatives, APIStar was the best option available. + +Then APIStar stopped to exist as a server and Starlette was created, and was a new better foundation for such a system. That was the final inspiration to build **FastAPI**. + +I consider **FastAPI** a "spiritual successor" to APIStar, while improving and increasing the features, typing system, and other parts, based on the learnings from all these previous tools. + +/// ## Used by **FastAPI** -### Pydantic +### Pydantic Pydantic is a library to define data validation, serialization and documentation (using JSON Schema) based on Python type hints. @@ -350,10 +409,13 @@ That makes it extremely intuitive. It is comparable to Marshmallow. Although it's faster than Marshmallow in benchmarks. And as it is based on the same Python type hints, the editor support is great. -!!! check "**FastAPI** uses it to" - Handle all the data validation, data serialization and automatic model documentation (based on JSON Schema). +/// check | **FastAPI** uses it to - **FastAPI** then takes that JSON Schema data and puts it in OpenAPI, apart from all the other things it does. +Handle all the data validation, data serialization and automatic model documentation (based on JSON Schema). + +**FastAPI** then takes that JSON Schema data and puts it in OpenAPI, apart from all the other things it does. + +/// ### Starlette @@ -382,17 +444,23 @@ But it doesn't provide automatic data validation, serialization or documentation That's one of the main things that **FastAPI** adds on top, all based on Python type hints (using Pydantic). That, plus the dependency injection system, security utilities, OpenAPI schema generation, etc. -!!! note "Technical Details" - ASGI is a new "standard" being developed by Django core team members. It is still not a "Python standard" (a PEP), although they are in the process of doing that. +/// note | Technical Details + +ASGI is a new "standard" being developed by Django core team members. It is still not a "Python standard" (a PEP), although they are in the process of doing that. - Nevertheless, it is already being used as a "standard" by several tools. This greatly improves interoperability, as you could switch Uvicorn for any other ASGI server (like Daphne or Hypercorn), or you could add ASGI compatible tools, like `python-socketio`. +Nevertheless, it is already being used as a "standard" by several tools. This greatly improves interoperability, as you could switch Uvicorn for any other ASGI server (like Daphne or Hypercorn), or you could add ASGI compatible tools, like `python-socketio`. -!!! check "**FastAPI** uses it to" - Handle all the core web parts. Adding features on top. +/// - The class `FastAPI` itself inherits directly from the class `Starlette`. +/// check | **FastAPI** uses it to - So, anything that you can do with Starlette, you can do it directly with **FastAPI**, as it is basically Starlette on steroids. +Handle all the core web parts. Adding features on top. + +The class `FastAPI` itself inherits directly from the class `Starlette`. + +So, anything that you can do with Starlette, you can do it directly with **FastAPI**, as it is basically Starlette on steroids. + +/// ### Uvicorn @@ -402,12 +470,15 @@ It is not a web framework, but a server. For example, it doesn't provide tools f It is the recommended server for Starlette and **FastAPI**. -!!! check "**FastAPI** recommends it as" - The main web server to run **FastAPI** applications. +/// check | **FastAPI** recommends it as + +The main web server to run **FastAPI** applications. + +You can also use the `--workers` command line option to have an asynchronous multi-process server. - You can combine it with Gunicorn, to have an asynchronous multi-process server. +Check more details in the [Deployment](deployment/index.md){.internal-link target=_blank} section. - Check more details in the [Deployment](deployment/index.md){.internal-link target=_blank} section. +/// ## Benchmarks and speed diff --git a/docs/en/docs/async.md b/docs/en/docs/async.md index 2ead1f2db..63bd8ca68 100644 --- a/docs/en/docs/async.md +++ b/docs/en/docs/async.md @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! note - You can only use `await` inside of functions created with `async def`. +/// note + +You can only use `await` inside of functions created with `async def`. + +/// --- @@ -136,8 +139,11 @@ You and your crush eat the burgers and have a nice time. ✨ -!!! info - Beautiful illustrations by Ketrina Thompson. 🎨 +/// info + +Beautiful illustrations by Ketrina Thompson. 🎨 + +/// --- @@ -199,8 +205,11 @@ 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. 🎨 +/// info + +Beautiful illustrations by Ketrina Thompson. 🎨 + +/// --- @@ -222,7 +231,7 @@ All of the cashiers doing all the work with one client after the other 👨‍ And you have to wait 🕙 in the line for a long time or you lose your turn. -You probably wouldn't want to take your crush 😍 with you to do errands at the bank 🏦. +You probably wouldn't want to take your crush 😍 with you to run errands at the bank 🏦. ### Burger Conclusion @@ -283,7 +292,7 @@ For example: ### Concurrency + Parallelism: Web + Machine Learning -With **FastAPI** you can take the advantage of concurrency that is very common for web development (the same main attraction of NodeJS). +With **FastAPI** you can take advantage of concurrency that is very common for web development (the same main attraction of NodeJS). But you can also exploit the benefits of parallelism and multiprocessing (having multiple processes running in parallel) for **CPU bound** workloads like those in Machine Learning systems. @@ -360,6 +369,8 @@ In particular, you can directly use AnyIO to be highly compatible and get its benefits (e.g. *structured concurrency*). +I created another library on top of AnyIO, as a thin layer on top, to improve a bit the type annotations and get better **autocompletion**, **inline errors**, etc. It also has a friendly introduction and tutorial to help you **understand** and write **your own async code**: Asyncer. It would be particularly useful if you need to **combine async code with regular** (blocking/synchronous) code. + ### Other forms of asynchronous code This style of using `async` and `await` is relatively new in the language. @@ -376,7 +387,7 @@ In previous versions of NodeJS / Browser JavaScript, you would have used "callba ## Coroutines -**Coroutine** is just the very fancy term for the thing returned by an `async def` function. Python knows that it is something like a function that it can start and that it will end at some point, but that it might be paused ⏸ internally too, whenever there is an `await` inside of it. +**Coroutine** is just the very fancy term for the thing returned by an `async def` function. Python knows that it is something like a function, that it can start and that it will end at some point, but that it might be paused ⏸ internally too, whenever there is an `await` inside of it. But all this functionality of using asynchronous code with `async` and `await` is many times summarized as using "coroutines". It is comparable to the main key feature of Go, the "Goroutines". @@ -392,12 +403,15 @@ All that is what powers FastAPI (through Starlette) and what makes it have such ## Very Technical Details -!!! warning - You can probably skip this. +/// warning + +You can probably skip this. + +These are very technical details of how **FastAPI** works underneath. - These are very technical details of how **FastAPI** works underneath. +If you have quite some technical knowledge (coroutines, 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 @@ -405,15 +419,15 @@ When you declare a *path operation function* with normal `def` instead of `async If you are coming from another async framework that does not work in the way described above and you are used to defining trivial compute-only *path operation functions* with plain `def` for a tiny performance gain (about 100 nanoseconds), please note that in **FastAPI** the effect would be quite opposite. In these cases, it's better to use `async def` unless your *path operation functions* use code that performs blocking I/O. -Still, in both situations, chances are that **FastAPI** will [still be faster](/#performance){.internal-link target=_blank} than (or at least comparable to) your previous framework. +Still, in both situations, chances are that **FastAPI** will [still be faster](index.md#performance){.internal-link target=_blank} than (or at least comparable to) your previous framework. ### Dependencies -The same applies for [dependencies](./tutorial/dependencies/index.md){.internal-link target=_blank}. If a dependency is a standard `def` function instead of `async def`, it is run in the external threadpool. +The same applies for [dependencies](tutorial/dependencies/index.md){.internal-link target=_blank}. If a dependency is a standard `def` function instead of `async def`, it is run in the external threadpool. ### Sub-dependencies -You can have multiple dependencies and [sub-dependencies](./tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} requiring each other (as parameters of the function definitions), some of them might be created with `async def` and some with normal `def`. It would still work, and the ones created with normal `def` would be called on an external thread (from the threadpool) instead of being "awaited". +You can have multiple dependencies and [sub-dependencies](tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} requiring each other (as parameters of the function definitions), some of them might be created with `async def` and some with normal `def`. It would still work, and the ones created with normal `def` would be called on an external thread (from the threadpool) instead of being "awaited". ### Other utility functions diff --git a/docs/en/docs/benchmarks.md b/docs/en/docs/benchmarks.md index d746b6d7c..62266c449 100644 --- a/docs/en/docs/benchmarks.md +++ b/docs/en/docs/benchmarks.md @@ -1,6 +1,6 @@ # Benchmarks -Independent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as one of the fastest Python frameworks available, only below Starlette and Uvicorn themselves (used internally by FastAPI). (*) +Independent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as one of the fastest Python frameworks available, only below Starlette and Uvicorn themselves (used internally by FastAPI). But when checking benchmarks and comparisons you should keep the following in mind. diff --git a/docs/en/docs/contributing.md b/docs/en/docs/contributing.md index 2d308a9db..1b70a0ea9 100644 --- a/docs/en/docs/contributing.md +++ b/docs/en/docs/contributing.md @@ -4,106 +4,15 @@ First, you might want to see the basic ways to [help FastAPI and get help](help- ## Developing -If you already cloned the fastapi repository and you want to deep dive in the code, here are some guidelines to set up your environment. +If you already cloned the fastapi repository and you want to deep dive in the code, here are some guidelines to set up your environment. -### Virtual environment with `venv` +### Virtual environment -You can create an isolated virtual local environment in a directory using Python's `venv` module. Let's do this in the cloned repository (where the `requirements.txt` is): - -
- -```console -$ python -m venv env -``` - -
- -That will create a directory `./env/` with the Python binaries, and then you will be able to install packages for that local environment. - -### Activate the environment - -Activate the new environment with: - -=== "Linux, macOS" - -
- - ```console - $ source ./env/bin/activate - ``` - -
- -=== "Windows PowerShell" - -
- - ```console - $ .\env\Scripts\Activate.ps1 - ``` - -
- -=== "Windows Bash" - - Or if you use Bash for Windows (e.g. Git Bash): - -
- - ```console - $ source ./env/Scripts/activate - ``` - -
- -To check it worked, use: - -=== "Linux, macOS, Windows Bash" - -
- - ```console - $ which pip - - some/directory/fastapi/env/bin/pip - ``` - -
- -=== "Windows PowerShell" - -
- - ```console - $ Get-Command pip - - some/directory/fastapi/env/bin/pip - ``` - -
- -If it shows the `pip` binary at `env/bin/pip` then it worked. 🎉 - -Make sure you have the latest pip version on your local environment to avoid errors on the next steps: - -
- -```console -$ python -m pip install --upgrade pip - ----> 100% -``` - -
- -!!! tip - Every time you install a new package with `pip` under that environment, activate the environment again. - - This makes sure that if you use a terminal program installed by that package, you use the one from your local environment and not any other that could be installed globally. +Follow the instructions to create and activate a [virtual environment](virtual-environments.md){.internal-link target=_blank} for the internal code of `fastapi`. ### Install requirements using pip -After activating the environment as described above: +After activating the environment, install the required packages:
@@ -125,10 +34,13 @@ And if you update that local FastAPI source code when you run that Python file a That way, you don't have to "install" your local version to be able to test every change. -!!! note "Technical Details" - This only happens when you install using this included `requirements.txt` instead of running `pip install fastapi` directly. +/// note | Technical Details + +This only happens when you install using this included `requirements.txt` instead of running `pip install fastapi` directly. - That is because inside the `requirements.txt` file, the local version of FastAPI is marked to be installed in "editable" mode, with the `-e` option. +That is because inside the `requirements.txt` file, the local version of FastAPI is marked to be installed in "editable" mode, with the `-e` option. + +/// ### Format the code @@ -144,7 +56,19 @@ $ bash scripts/format.sh It will also auto-sort all your imports. -For it to sort them correctly, you need to have FastAPI installed locally in your environment, with the command in the section above using `-e`. +## Tests + +There is a script that you can run locally to test all the code and generate coverage reports in HTML: + +
+ +```console +$ bash scripts/test-cov-html.sh +``` + +
+ +This command generates a directory `./htmlcov/`, if you open the file `./htmlcov/index.html` in your browser, you can explore interactively the regions of code that are covered by the tests, and notice if there is any region missing. ## Docs @@ -170,20 +94,23 @@ It will serve the documentation on `http://127.0.0.1:8008`. That way, you can edit the documentation/source files and see the changes live. -!!! tip - Alternatively, you can perform the same steps that scripts does manually. +/// tip + +Alternatively, you can perform the same steps that scripts does manually. + +Go into the language directory, for the main docs in English it's at `docs/en/`: - Go into the language directory, for the main docs in English it's at `docs/en/`: +```console +$ cd docs/en/ +``` - ```console - $ cd docs/en/ - ``` +Then run `mkdocs` in that directory: - Then run `mkdocs` in that directory: +```console +$ mkdocs serve --dev-addr 127.0.0.1:8008 +``` - ```console - $ mkdocs serve --dev-addr 8008 - ``` +/// #### Typer CLI (optional) @@ -210,8 +137,11 @@ The documentation uses ```console -$ uvicorn tutorial001:app --reload +$ fastapi dev tutorial001.py INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` @@ -257,16 +187,19 @@ Here are the steps to help with translations. #### Tips and guidelines -* Check the currently existing pull requests for your language. You can filter the pull requests by the ones with the label for your language. For example, for Spanish, the label is `lang-es`. +* Check the currently existing pull requests for your language. You can filter the pull requests by the ones with the label for your language. For example, for Spanish, the label is `lang-es`. * Review those pull requests, requesting changes or approving them. For the languages I don't speak, I'll wait for several others to review the translation before merging. -!!! tip - You can add comments with change suggestions to existing pull requests. +/// tip + +You can add comments with change suggestions to existing pull requests. - Check the docs about adding a pull request review to approve it or request changes. +Check the docs about adding a pull request review to approve it or request changes. -* Check if there's a GitHub Discussion to coordinate translations for your language. You can subscribe to it, and when there's a new pull request to review, an automatic comment will be added to the discussion. +/// + +* Check if there's a GitHub Discussion to coordinate translations for your language. You can subscribe to it, and when there's a new pull request to review, an automatic comment will be added to the discussion. * If you translate pages, add a single pull request per page translated. That will make it much easier for others to review it. @@ -278,8 +211,11 @@ Let's say you want to translate a page for a language that already has translati In the case of Spanish, the 2-letter code is `es`. So, the directory for Spanish translations is located at `docs/es/`. -!!! tip - The main ("official") language is English, located at `docs/en/`. +/// tip + +The main ("official") language is English, located at `docs/en/`. + +/// Now run the live server for the docs in Spanish: @@ -296,20 +232,23 @@ $ python ./scripts/docs.py live es
-!!! tip - Alternatively, you can perform the same steps that scripts does manually. +/// tip - Go into the language directory, for the Spanish translations it's at `docs/es/`: +Alternatively, you can perform the same steps that scripts does manually. - ```console - $ cd docs/es/ - ``` +Go into the language directory, for the Spanish translations it's at `docs/es/`: - Then run `mkdocs` in that directory: +```console +$ cd docs/es/ +``` - ```console - $ mkdocs serve --dev-addr 8008 - ``` +Then run `mkdocs` in that directory: + +```console +$ mkdocs serve --dev-addr 127.0.0.1:8008 +``` + +/// Now you can go to http://127.0.0.1:8008 and see your changes live. @@ -329,13 +268,31 @@ docs/en/docs/features.md docs/es/docs/features.md ``` -!!! tip - Notice that the only change in the path and file name is the language code, from `en` to `es`. +/// tip + +Notice that the only change in the path and file name is the language code, from `en` to `es`. + +/// If you go to your browser you will see that now the docs show your new section (the info box at the top is gone). 🎉 Now you can translate it all and see how it looks as you save the file. +#### Don't Translate these Pages + +🚨 Don't translate: + +* Files under `reference/` +* `release-notes.md` +* `fastapi-people.md` +* `external-links.md` +* `newsletter.md` +* `management-tasks.md` +* `management.md` +* `contributing.md` + +Some of these files are updated very frequently and a translation would always be behind, or they include the main content from English source files, etc. + #### New Language Let's say that you want to add translations for a language that is not yet translated, not even some pages. @@ -365,8 +322,11 @@ That command created a file `docs/ht/mkdocs.yml` with a simple config that inher INHERIT: ../en/mkdocs.yml ``` -!!! tip - You could also simply create that file with those contents manually. +/// tip + +You could also simply create that file with those contents manually. + +/// That command also created a dummy file `docs/ht/index.md` for the main page, you can start by translating that one. @@ -421,9 +381,9 @@ Serving at: http://127.0.0.1:8008 * Do not change anything enclosed in "``" (inline code). -* In lines starting with `===` or `!!!`, translate only the ` "... Text ..."` part. Leave the rest unchanged. +* In lines starting with `///` translate only the text part after `|`. Leave the rest unchanged. -* You can translate info boxes like `!!! warning` with for example `!!! warning "Achtung"`. But do not change the word immediately after the `!!!`, it determines the color of the info box. +* You can translate info boxes like `/// warning` with for example `/// warning | Achtung`. But do not change the word immediately after the `///`, it determines the color of the info box. * Do not change the paths in links to images, code files, Markdown documents. @@ -431,17 +391,3 @@ Serving at: http://127.0.0.1:8008 * Search for such links in the translated document using the regex `#[^# ]`. * Search in all documents already translated into your language for `your-translated-document.md`. For example VS Code has an option "Edit" -> "Find in Files". * When translating a document, do not "pre-translate" `#hash-parts` that link to headings in untranslated documents. - -## Tests - -There is a script that you can run locally to test all the code and generate coverage reports in HTML: - -
- -```console -$ bash scripts/test-cov-html.sh -``` - -
- -This command generates a directory `./htmlcov/`, if you open the file `./htmlcov/index.html` in your browser, you can explore interactively the regions of code that are covered by the tests, and notice if there is any region missing. diff --git a/docs/en/docs/css/custom.css b/docs/en/docs/css/custom.css index 187040792..b192f6123 100644 --- a/docs/en/docs/css/custom.css +++ b/docs/en/docs/css/custom.css @@ -13,6 +13,10 @@ white-space: pre-wrap; } +.termy .linenos { + display: none; +} + a.external-link { /* For right to left languages */ direction: ltr; @@ -136,10 +140,6 @@ code { display: inline-block; } -.md-content__inner h1 { - direction: ltr !important; -} - .illustration { margin-top: 2em; margin-bottom: 2em; diff --git a/docs/en/docs/css/termynal.css b/docs/en/docs/css/termynal.css index 406c00897..8534f9102 100644 --- a/docs/en/docs/css/termynal.css +++ b/docs/en/docs/css/termynal.css @@ -26,6 +26,8 @@ position: relative; -webkit-box-sizing: border-box; box-sizing: border-box; + /* Custom line-height */ + line-height: 1.2; } [data-termynal]:before { diff --git a/docs/en/docs/deployment/cloud.md b/docs/en/docs/deployment/cloud.md index b2836aeb4..471808851 100644 --- a/docs/en/docs/deployment/cloud.md +++ b/docs/en/docs/deployment/cloud.md @@ -14,4 +14,5 @@ You might want to try their services and follow their guides: * Platform.sh * Porter -* Deta +* Coherence +* Render diff --git a/docs/en/docs/deployment/concepts.md b/docs/en/docs/deployment/concepts.md index cc01fb24e..e71a7487a 100644 --- a/docs/en/docs/deployment/concepts.md +++ b/docs/en/docs/deployment/concepts.md @@ -25,7 +25,7 @@ But for now, let's check these important **conceptual ideas**. These concepts al ## Security - HTTPS -In the [previous chapter about HTTPS](./https.md){.internal-link target=_blank} we learned about how HTTPS provides encryption for your API. +In the [previous chapter about HTTPS](https.md){.internal-link target=_blank} we learned about how HTTPS provides encryption for your API. We also saw that HTTPS is normally provided by a component **external** to your application server, a **TLS Termination Proxy**. @@ -94,7 +94,7 @@ In most cases, when you create a web API, you want it to be **always running**, ### In a Remote Server -When you set up a remote server (a cloud server, a virtual machine, etc.) the simplest thing you can do is to run Uvicorn (or similar) manually, the same way you do when developing locally. +When you set up a remote server (a cloud server, a virtual machine, etc.) the simplest thing you can do is use `fastapi run` (which uses Uvicorn) or something similar, manually, the same way you do when developing locally. And it will work and will be useful **during development**. @@ -151,10 +151,13 @@ And still, you would probably not want the application to stay dead because ther But in those cases with really bad errors that crash the running **process**, you would want an external component that is in charge of **restarting** the process, at least a couple of times... -!!! tip - ...Although if the whole application is just **crashing immediately** it probably doesn't make sense to keep restarting it forever. But in those cases, you will probably notice it during development, or at least right after deployment. +/// tip - So let's focus on the main cases, where it could crash entirely in some particular cases **in the future**, and it still makes sense to restart it. +...Although if the whole application is just **crashing immediately** it probably doesn't make sense to keep restarting it forever. But in those cases, you will probably notice it during development, or at least right after deployment. + +So let's focus on the main cases, where it could crash entirely in some particular cases **in the future**, and it still makes sense to restart it. + +/// You would probably want to have the thing in charge of restarting your application as an **external component**, because by that point, the same application with Uvicorn and Python already crashed, so there's nothing in the same code of the same app that could do anything about it. @@ -175,7 +178,7 @@ For example, this could be handled by: ## Replication - Processes and Memory -With a FastAPI application, using a server program like Uvicorn, running it once in **one process** can serve multiple clients concurrently. +With a FastAPI application, using a server program like the `fastapi` command that runs Uvicorn, running it once in **one process** can serve multiple clients concurrently. But in many cases, you will want to run several worker processes at the same time. @@ -187,7 +190,7 @@ When you run **multiple processes** of the same API program, they are commonly c ### Worker Processes and Ports -Remember from the docs [About HTTPS](./https.md){.internal-link target=_blank} that only one process can be listening on one combination of port and IP address in a server? +Remember from the docs [About HTTPS](https.md){.internal-link target=_blank} that only one process can be listening on one combination of port and IP address in a server? This is still true. @@ -229,19 +232,20 @@ The main constraint to consider is that there has to be a **single** component h Here are some possible combinations and strategies: -* **Gunicorn** managing **Uvicorn workers** - * Gunicorn would be the **process manager** listening on the **IP** and **port**, the replication would be by having **multiple Uvicorn worker processes** -* **Uvicorn** managing **Uvicorn workers** - * One Uvicorn **process manager** would listen on the **IP** and **port**, and it would start **multiple Uvicorn worker processes** +* **Uvicorn** with `--workers` + * One Uvicorn **process manager** would listen on the **IP** and **port**, and it would start **multiple Uvicorn worker processes**. * **Kubernetes** and other distributed **container systems** - * Something in the **Kubernetes** layer would listen on the **IP** and **port**. The replication would be by having **multiple containers**, each with **one Uvicorn process** running + * Something in the **Kubernetes** layer would listen on the **IP** and **port**. The replication would be by having **multiple containers**, each with **one Uvicorn process** running. * **Cloud services** that handle this for you * The cloud service will probably **handle replication for you**. It would possibly let you define **a process to run**, or a **container image** to use, in any case, it would most probably be **a single Uvicorn process**, and the cloud service would be in charge of replicating it. -!!! tip - Don't worry if some of these items about **containers**, Docker, or Kubernetes don't make a lot of sense yet. +/// tip + +Don't worry if some of these items about **containers**, Docker, or Kubernetes don't make a lot of sense yet. + +I'll tell you more about container images, Docker, Kubernetes, etc. in a future chapter: [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank}. - I'll tell you more about container images, Docker, Kubernetes, etc. in a future chapter: [FastAPI in Containers - Docker](./docker.md){.internal-link target=_blank}. +/// ## Previous Steps Before Starting @@ -253,14 +257,17 @@ But in most cases, you will want to perform these steps only **once**. So, you will want to have a **single process** to perform those **previous steps**, before starting the application. -And you will have to make sure that it's a single process running those previous steps *even* if afterwards, you start **multiple processes** (multiple workers) for the application itself. If those steps were run by **multiple processes**, they would **duplicate** the work by running it on **parallel**, and if the steps were something delicate like a database migration, they could cause conflicts with each other. +And you will have to make sure that it's a single process running those previous steps *even* if afterwards, you start **multiple processes** (multiple workers) for the application itself. If those steps were run by **multiple processes**, they would **duplicate** the work by running it in **parallel**, and if the steps were something delicate like a database migration, they could cause conflicts with each other. Of course, there are some cases where there's no problem in running the previous steps multiple times, in that case, it's a lot easier to handle. -!!! tip - Also, keep in mind that depending on your setup, in some cases you **might not even need any previous steps** before starting your application. +/// tip - In that case, you wouldn't have to worry about any of this. 🤷 +Also, keep in mind that depending on your setup, in some cases you **might not even need any previous steps** before starting your application. + +In that case, you wouldn't have to worry about any of this. 🤷 + +/// ### Examples of Previous Steps Strategies @@ -272,8 +279,11 @@ Here are some possible ideas: * A bash script that runs the previous steps and then starts your application * You would still need a way to start/restart *that* bash script, detect errors, etc. -!!! tip - I'll give you more concrete examples for doing this with containers in a future chapter: [FastAPI in Containers - Docker](./docker.md){.internal-link target=_blank}. +/// tip + +I'll give you more concrete examples for doing this with containers in a future chapter: [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank}. + +/// ## Resource Utilization diff --git a/docs/en/docs/deployment/docker.md b/docs/en/docs/deployment/docker.md index 8a542622e..b106f7ac3 100644 --- a/docs/en/docs/deployment/docker.md +++ b/docs/en/docs/deployment/docker.md @@ -4,8 +4,11 @@ When deploying FastAPI applications a common approach is to build a **Linux cont Using Linux containers has several advantages including **security**, **replicability**, **simplicity**, and others. -!!! tip - In a hurry and already know this stuff? Jump to the [`Dockerfile` below 👇](#build-a-docker-image-for-fastapi). +/// tip + +In a hurry and already know this stuff? Jump to the [`Dockerfile` below 👇](#build-a-docker-image-for-fastapi). + +///
Dockerfile Preview 👀 @@ -21,10 +24,10 @@ RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt COPY ./app /code/app -CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] +CMD ["fastapi", "run", "app/main.py", "--port", "80"] # If running behind a proxy like Nginx or Traefik add --proxy-headers -# CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80", "--proxy-headers"] +# CMD ["fastapi", "run", "app/main.py", "--port", "80", "--proxy-headers"] ```
@@ -70,7 +73,7 @@ And there are many other images for different things like databases, for example By using a pre-made container image it's very easy to **combine** and use different tools. For example, to try out a new database. In most cases, you can use the **official images**, and just configure them with environment variables. -That way, in many cases you can learn about containers and Docker and re-use that knowledge with many different tools and components. +That way, in many cases you can learn about containers and Docker and reuse that knowledge with many different tools and components. So, you would run **multiple containers** with different things, like a database, a Python application, a web server with a React frontend application, and connect them together via their internal network. @@ -108,14 +111,13 @@ It would depend mainly on the tool you use to **install** those requirements. The most common way to do it is to have a file `requirements.txt` with the package names and their versions, one per line. -You would of course use the same ideas you read in [About FastAPI versions](./versions.md){.internal-link target=_blank} to set the ranges of versions. +You would of course use the same ideas you read in [About FastAPI versions](versions.md){.internal-link target=_blank} to set the ranges of versions. For example, your `requirements.txt` could look like: ``` -fastapi>=0.68.0,<0.69.0 -pydantic>=1.8.0,<2.0.0 -uvicorn>=0.15.0,<0.16.0 +fastapi[standard]>=0.113.0,<0.114.0 +pydantic>=2.7.0,<3.0.0 ``` And you would normally install those package dependencies with `pip`, for example: @@ -125,15 +127,16 @@ And you would normally install those package dependencies with `pip`, for exampl ```console $ pip install -r requirements.txt ---> 100% -Successfully installed fastapi pydantic uvicorn +Successfully installed fastapi pydantic ```
-!!! info - There are other formats and tools to define and install package dependencies. +/// info - I'll show you an example using Poetry later in a section below. 👇 +There are other formats and tools to define and install package dependencies. + +/// ### Create the **FastAPI** Code @@ -164,23 +167,23 @@ def read_item(item_id: int, q: Union[str, None] = None): Now in the same project directory create a file `Dockerfile` with: ```{ .dockerfile .annotate } -# (1) +# (1)! FROM python:3.9 -# (2) +# (2)! WORKDIR /code -# (3) +# (3)! COPY ./requirements.txt /code/requirements.txt -# (4) +# (4)! RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt -# (5) +# (5)! COPY ./app /code/app -# (6) -CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] +# (6)! +CMD ["fastapi", "run", "app/main.py", "--port", "80"] ``` 1. Start from the official Python base image. @@ -199,8 +202,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] The `--no-cache-dir` option tells `pip` to not save the downloaded packages locally, as that is only if `pip` was going to be run again to install the same packages, but that's not the case when working with containers. - !!! note - The `--no-cache-dir` is only related to `pip`, it has nothing to do with Docker or containers. + /// note + + The `--no-cache-dir` is only related to `pip`, it has nothing to do with Docker or containers. + + /// The `--upgrade` option tells `pip` to upgrade the packages if they are already installed. @@ -214,16 +220,49 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] So, it's important to put this **near the end** of the `Dockerfile`, to optimize the container image build times. -6. Set the **command** to run the `uvicorn` server. +6. Set the **command** to use `fastapi run`, which uses Uvicorn underneath. `CMD` takes a list of strings, each of these strings is what you would type in the command line separated by spaces. This command will be run from the **current working directory**, the same `/code` directory you set above with `WORKDIR /code`. - Because the program will be started at `/code` and inside of it is the directory `./app` with your code, **Uvicorn** will be able to see and **import** `app` from `app.main`. +/// tip + +Review what each line does by clicking each number bubble in the code. 👆 + +/// + +/// warning + +Make sure to **always** use the **exec form** of the `CMD` instruction, as explained below. + +/// + +#### Use `CMD` - Exec Form + +The `CMD` Docker instruction can be written using two forms: + +✅ **Exec** form: + +```Dockerfile +# ✅ Do this +CMD ["fastapi", "run", "app/main.py", "--port", "80"] +``` + +⛔️ **Shell** form: + +```Dockerfile +# ⛔️ Don't do this +CMD fastapi run app/main.py --port 80 +``` + +Make sure to always use the **exec** form to ensure that FastAPI can shutdown gracefully and [lifespan events](../advanced/events.md){.internal-link target=_blank} are triggered. + +You can read more about it in the Docker docs for shell and exec form. + +This can be quite noticeable when using `docker compose`. See this Docker Compose FAQ section for more technical details: Why do my services take 10 seconds to recreate or stop?. -!!! tip - Review what each line does by clicking each number bubble in the code. 👆 +#### Directory Structure You should now have a directory structure like: @@ -238,10 +277,10 @@ You should now have a directory structure like: #### Behind a TLS Termination Proxy -If you are running your container behind a TLS Termination Proxy (load balancer) like Nginx or Traefik, add the option `--proxy-headers`, this will tell Uvicorn to trust the headers sent by that proxy telling it that the application is running behind HTTPS, etc. +If you are running your container behind a TLS Termination Proxy (load balancer) like Nginx or Traefik, add the option `--proxy-headers`, this will tell Uvicorn (through the FastAPI CLI) to trust the headers sent by that proxy telling it that the application is running behind HTTPS, etc. ```Dockerfile -CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"] +CMD ["fastapi", "run", "app/main.py", "--proxy-headers", "--port", "80"] ``` #### Docker Cache @@ -254,7 +293,7 @@ COPY ./requirements.txt /code/requirements.txt Docker and other tools **build** these container images **incrementally**, adding **one layer on top of the other**, starting from the top of the `Dockerfile` and adding any files created by each of the instructions of the `Dockerfile`. -Docker and similar tools also use an **internal cache** when building the image, if a file hasn't changed since the last time building the container image, then it will **re-use the same layer** created the last time, instead of copying the file again and creating a new layer from scratch. +Docker and similar tools also use an **internal cache** when building the image, if a file hasn't changed since the last time building the container image, then it will **reuse the same layer** created the last time, instead of copying the file again and creating a new layer from scratch. Just avoiding the copy of files doesn't necessarily improve things too much, but because it used the cache for that step, it can **use the cache for the next step**. For example, it could use the cache for the instruction that installs dependencies with: @@ -293,10 +332,13 @@ $ docker build -t myimage .
-!!! tip - Notice the `.` at the end, it's equivalent to `./`, it tells Docker the directory to use to build the container image. +/// tip - In this case, it's the same current directory (`.`). +Notice the `.` at the end, it's equivalent to `./`, it tells Docker the directory to use to build the container image. + +In this case, it's the same current directory (`.`). + +/// ### Start the Docker Container @@ -358,22 +400,22 @@ COPY ./requirements.txt /code/requirements.txt RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt -# (1) +# (1)! COPY ./main.py /code/ -# (2) -CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] +# (2)! +CMD ["fastapi", "run", "main.py", "--port", "80"] ``` 1. Copy the `main.py` file to the `/code` directory directly (without any `./app` directory). -2. Run Uvicorn and tell it to import the `app` object from `main` (instead of importing from `app.main`). +2. Use `fastapi run` to serve your application in the single file `main.py`. -Then adjust the Uvicorn command to use the new module `main` instead of `app.main` to import the FastAPI object `app`. +When you pass the file to `fastapi run` it will detect automatically that it is a single file and not part of a package and will know how to import it and serve your FastAPI app. 😎 ## Deployment Concepts -Let's talk again about some of the same [Deployment Concepts](./concepts.md){.internal-link target=_blank} in terms of containers. +Let's talk again about some of the same [Deployment Concepts](concepts.md){.internal-link target=_blank} in terms of containers. Containers are mainly a tool to simplify the process of **building and deploying** an application, but they don't enforce a particular approach to handle these **deployment concepts**, and there are several possible strategies. @@ -394,8 +436,11 @@ If we focus just on the **container image** for a FastAPI application (and later It could be another container, for example with Traefik, handling **HTTPS** and **automatic** acquisition of **certificates**. -!!! tip - Traefik has integrations with Docker, Kubernetes, and others, so it's very easy to set up and configure HTTPS for your containers with it. +/// tip + +Traefik has integrations with Docker, Kubernetes, and others, so it's very easy to set up and configure HTTPS for your containers with it. + +/// Alternatively, HTTPS could be handled by a cloud provider as one of their services (while still running the application in a container). @@ -411,11 +456,11 @@ Without using containers, making applications run on startup and with restarts c ## Replication - Number of Processes -If you have a cluster of machines with **Kubernetes**, Docker Swarm Mode, Nomad, or another similar complex system to manage distributed containers on multiple machines, then you will probably want to **handle replication** at the **cluster level** instead of using a **process manager** (like Gunicorn with workers) in each container. +If you have a cluster of machines with **Kubernetes**, Docker Swarm Mode, Nomad, or another similar complex system to manage distributed containers on multiple machines, then you will probably want to **handle replication** at the **cluster level** instead of using a **process manager** (like Uvicorn with workers) in each container. One of those distributed container management systems like Kubernetes normally has some integrated way of handling **replication of containers** while still supporting **load balancing** for the incoming requests. All at the **cluster level**. -In those cases, you would probably want to build a **Docker image from scratch** as [explained above](#dockerfile), installing your dependencies, and running **a single Uvicorn process** instead of running something like Gunicorn with Uvicorn workers. +In those cases, you would probably want to build a **Docker image from scratch** as [explained above](#dockerfile), installing your dependencies, and running **a single Uvicorn process** instead of using multiple Uvicorn workers. ### Load Balancer @@ -423,8 +468,11 @@ When using containers, you would normally have some component **listening on the As this component would take the **load** of requests and distribute that among the workers in a (hopefully) **balanced** way, it is also commonly called a **Load Balancer**. -!!! tip - The same **TLS Termination Proxy** component used for HTTPS would probably also be a **Load Balancer**. +/// tip + +The same **TLS Termination Proxy** component used for HTTPS would probably also be a **Load Balancer**. + +/// And when working with containers, the same system you use to start and manage them would already have internal tools to transmit the **network communication** (e.g. HTTP requests) from that **load balancer** (that could also be a **TLS Termination Proxy**) to the container(s) with your app. @@ -442,37 +490,44 @@ And normally this **load balancer** would be able to handle requests that go to In this type of scenario, you probably would want to have **a single (Uvicorn) process per container**, as you would already be handling replication at the cluster level. -So, in this case, you **would not** want to have a process manager like Gunicorn with Uvicorn workers, or Uvicorn using its own Uvicorn workers. You would want to have just a **single Uvicorn process** per container (but probably multiple containers). +So, in this case, you **would not** want to have a multiple workers in the container, for example with the `--workers` command line option.You would want to have just a **single Uvicorn process** per container (but probably multiple containers). -Having another process manager inside the container (as would be with Gunicorn or Uvicorn managing Uvicorn workers) would only add **unnecessary complexity** that you are most probably already taking care of with your cluster system. +Having another process manager inside the container (as would be with multiple workers) would only add **unnecessary complexity** that you are most probably already taking care of with your cluster system. ### Containers with Multiple Processes and Special Cases -Of course, there are **special cases** where you could want to have **a container** with a **Gunicorn process manager** starting several **Uvicorn worker processes** inside. +Of course, there are **special cases** where you could want to have **a container** with several **Uvicorn worker processes** inside. -In those cases, you can use the **official Docker image** that includes **Gunicorn** as a process manager running multiple **Uvicorn worker processes**, and some default settings to adjust the number of workers based on the current CPU cores automatically. I'll tell you more about it below in [Official Docker Image with Gunicorn - Uvicorn](#official-docker-image-with-gunicorn-uvicorn). +In those cases, you can use the `--workers` command line option to set the number of workers that you want to run: -Here are some examples of when that could make sense: +```{ .dockerfile .annotate } +FROM python:3.9 -#### A Simple App +WORKDIR /code -You could want a process manager in the container if your application is **simple enough** that you don't need (at least not yet) to fine-tune the number of processes too much, and you can just use an automated default (with the official Docker image), and you are running it on a **single server**, not a cluster. +COPY ./requirements.txt /code/requirements.txt -#### Docker Compose +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt -You could be deploying to a **single server** (not a cluster) with **Docker Compose**, so you wouldn't have an easy way to manage replication of containers (with Docker Compose) while preserving the shared network and **load balancing**. +COPY ./app /code/app -Then you could want to have **a single container** with a **process manager** starting **several worker processes** inside. +# (1)! +CMD ["fastapi", "run", "app/main.py", "--port", "80", "--workers", "4"] +``` -#### Prometheus and Other Reasons +1. Here we use the `--workers` command line option to set the number of workers to 4. -You could also have **other reasons** that would make it easier to have a **single container** with **multiple processes** instead of having **multiple containers** with **a single process** in each of them. +Here are some examples of when that could make sense: -For example (depending on your setup) you could have some tool like a Prometheus exporter in the same container that should have access to **each of the requests** that come. +#### A Simple App -In this case, if you had **multiple containers**, by default, when Prometheus came to **read the metrics**, it would get the ones for **a single container each time** (for the container that handled that particular request), instead of getting the **accumulated metrics** for all the replicated containers. +You could want a process manager in the container if your application is **simple enough** that can run it on a **single server**, not a cluster. -Then, in that case, it could be simpler to have **one container** with **multiple processes**, and a local tool (e.g. a Prometheus exporter) on the same container collecting Prometheus metrics for all the internal processes and exposing those metrics on that single container. +#### Docker Compose + +You could be deploying to a **single server** (not a cluster) with **Docker Compose**, so you wouldn't have an easy way to manage replication of containers (with Docker Compose) while preserving the shared network and **load balancing**. + +Then you could want to have **a single container** with a **process manager** starting **several worker processes** inside. --- @@ -493,7 +548,7 @@ And then you can set those same memory limits and requirements in your configura If your application is **simple**, this will probably **not be a problem**, and you might not need to specify hard memory limits. But if you are **using a lot of memory** (for example with **machine learning** models), you should check how much memory you are consuming and adjust the **number of containers** that runs in **each machine** (and maybe add more machines to your cluster). -If you run **multiple processes per container** (for example with the official Docker image) you will have to make sure that the number of processes started doesn't **consume more memory** than what is available. +If you run **multiple processes per container** you will have to make sure that the number of processes started doesn't **consume more memory** than what is available. ## Previous Steps Before Starting and Containers @@ -503,80 +558,35 @@ If you are using containers (e.g. Docker, Kubernetes), then there are two main a If you have **multiple containers**, probably each one running a **single process** (for example, in a **Kubernetes** cluster), then you would probably want to have a **separate container** doing the work of the **previous steps** in a single container, running a single process, **before** running the replicated worker containers. -!!! info - If you are using Kubernetes, this would probably be an Init Container. - -If in your use case there's no problem in running those previous steps **multiple times in parallel** (for example if you are not running database migrations, but just checking if the database is ready yet), then you could also just put them in each container right before starting the main process. - -### Single Container - -If you have a simple setup, with a **single container** that then starts multiple **worker processes** (or also just one process), then you could run those previous steps in the same container, right before starting the process with the app. The official Docker image supports this internally. - -## Official Docker Image with Gunicorn - Uvicorn - -There is an official Docker image that includes Gunicorn running with Uvicorn workers, as detailed in a previous chapter: [Server Workers - Gunicorn with Uvicorn](./server-workers.md){.internal-link target=_blank}. - -This image would be useful mainly in the situations described above in: [Containers with Multiple Processes and Special Cases](#containers-with-multiple-processes-and-special-cases). - -* tiangolo/uvicorn-gunicorn-fastapi. - -!!! warning - There's a high chance that you **don't** need this base image or any other similar one, and would be better off by building the image from scratch as [described above in: Build a Docker Image for FastAPI](#build-a-docker-image-for-fastapi). - -This image has an **auto-tuning** mechanism included to set the **number of worker processes** based on the CPU cores available. +/// info -It has **sensible defaults**, but you can still change and update all the configurations with **environment variables** or configuration files. +If you are using Kubernetes, this would probably be an Init Container. -It also supports running **previous steps before starting** with a script. +/// -!!! tip - To see all the configurations and options, go to the Docker image page: tiangolo/uvicorn-gunicorn-fastapi. - -### Number of Processes on the Official Docker Image - -The **number of processes** on this image is **computed automatically** from the CPU **cores** available. - -This means that it will try to **squeeze** as much **performance** from the CPU as possible. - -You can also adjust it with the configurations using **environment variables**, etc. - -But it also means that as the number of processes depends on the CPU the container is running, the **amount of memory consumed** will also depend on that. - -So, if your application consumes a lot of memory (for example with machine learning models), and your server has a lot of CPU cores **but little memory**, then your container could end up trying to use more memory than what is available, and degrading performance a lot (or even crashing). 🚨 - -### Create a `Dockerfile` - -Here's how you would create a `Dockerfile` based on this image: - -```Dockerfile -FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9 - -COPY ./requirements.txt /app/requirements.txt +If in your use case there's no problem in running those previous steps **multiple times in parallel** (for example if you are not running database migrations, but just checking if the database is ready yet), then you could also just put them in each container right before starting the main process. -RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt +### Single Container -COPY ./app /app -``` +If you have a simple setup, with a **single container** that then starts multiple **worker processes** (or also just one process), then you could run those previous steps in the same container, right before starting the process with the app. -### Bigger Applications +### Base Docker Image -If you followed the section about creating [Bigger Applications with Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}, your `Dockerfile` might instead look like: +There used to be an official FastAPI Docker image: tiangolo/uvicorn-gunicorn-fastapi. But it is now deprecated. ⛔️ -```Dockerfile hl_lines="7" -FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9 +You should probably **not** use this base Docker image (or any other similar one). -COPY ./requirements.txt /app/requirements.txt +If you are using **Kubernetes** (or others) and you are already setting **replication** at the cluster level, with multiple **containers**. In those cases, you are better off **building an image from scratch** as described above: [Build a Docker Image for FastAPI](#build-a-docker-image-for-fastapi). -RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt +And if you need to have multiple workers, you can simply use the `--workers` command line option. -COPY ./app /app/app -``` +/// note | Technical Details -### When to Use +The Docker image was created when Uvicorn didn't support managing and restarting dead workers, so it was needed to use Gunicorn with Uvicorn, which added quite some complexity, just to have Gunicorn manage and restart the Uvicorn worker processes. -You should probably **not** use this official base image (or any other similar one) if you are using **Kubernetes** (or others) and you are already setting **replication** at the cluster level, with multiple **containers**. In those cases, you are better off **building an image from scratch** as described above: [Build a Docker Image for FastAPI](#build-a-docker-image-for-fastapi). +But now that Uvicorn (and the `fastapi` command) support using `--workers`, there's no reason to use a base Docker image instead of building your own (it's pretty much the same amount of code 😅). -This image would be useful mainly in the special cases described above in [Containers with Multiple Processes and Special Cases](#containers-with-multiple-processes-and-special-cases). For example, if your application is **simple enough** that setting a default number of processes based on the CPU works well, you don't want to bother with manually configuring the replication at the cluster level, and you are not running more than one container with your app. Or if you are deploying with **Docker Compose**, running on a single server, etc. +/// ## Deploy the Container Image @@ -590,95 +600,9 @@ For example: * With another tool like Nomad * With a cloud service that takes your container image and deploys it -## Docker Image with Poetry +## Docker Image with `uv` -If you use Poetry to manage your project's dependencies, you could use Docker multi-stage building: - -```{ .dockerfile .annotate } -# (1) -FROM python:3.9 as requirements-stage - -# (2) -WORKDIR /tmp - -# (3) -RUN pip install poetry - -# (4) -COPY ./pyproject.toml ./poetry.lock* /tmp/ - -# (5) -RUN poetry export -f requirements.txt --output requirements.txt --without-hashes - -# (6) -FROM python:3.9 - -# (7) -WORKDIR /code - -# (8) -COPY --from=requirements-stage /tmp/requirements.txt /code/requirements.txt - -# (9) -RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt - -# (10) -COPY ./app /code/app - -# (11) -CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] -``` - -1. This is the first stage, it is named `requirements-stage`. - -2. Set `/tmp` as the current working directory. - - Here's where we will generate the file `requirements.txt` - -3. Install Poetry in this Docker stage. - -4. Copy the `pyproject.toml` and `poetry.lock` files to the `/tmp` directory. - - Because it uses `./poetry.lock*` (ending with a `*`), it won't crash if that file is not available yet. - -5. Generate the `requirements.txt` file. - -6. This is the final stage, anything here will be preserved in the final container image. - -7. Set the current working directory to `/code`. - -8. Copy the `requirements.txt` file to the `/code` directory. - - This file only lives in the previous Docker stage, that's why we use `--from-requirements-stage` to copy it. - -9. Install the package dependencies in the generated `requirements.txt` file. - -10. Copy the `app` directory to the `/code` directory. - -11. Run the `uvicorn` command, telling it to use the `app` object imported from `app.main`. - -!!! tip - Click the bubble numbers to see what each line does. - -A **Docker stage** is a part of a `Dockerfile` that works as a **temporary container image** that is only used to generate some files to be used later. - -The first stage will only be used to **install Poetry** and to **generate the `requirements.txt`** with your project dependencies from Poetry's `pyproject.toml` file. - -This `requirements.txt` file will be used with `pip` later in the **next stage**. - -In the final container image **only the final stage** is preserved. The previous stage(s) will be discarded. - -When using Poetry, it would make sense to use **Docker multi-stage builds** because you don't really need to have Poetry and its dependencies installed in the final container image, you **only need** to have the generated `requirements.txt` file to install your project dependencies. - -Then in the next (and final) stage you would build the image more or less in the same way as described before. - -### Behind a TLS Termination Proxy - Poetry - -Again, if you are running your container behind a TLS Termination Proxy (load balancer) like Nginx or Traefik, add the option `--proxy-headers` to the command: - -```Dockerfile -CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"] -``` +If you are using uv to install and manage your project, you can follow their uv Docker guide. ## Recap @@ -691,8 +615,6 @@ Using container systems (e.g. with **Docker** and **Kubernetes**) it becomes fai * Memory * Previous steps before starting -In most cases, you probably won't want to use any base image, and instead **build a container image from scratch** one based on the official Python Docker image. +In most cases, you probably won't want to use any base image, and instead **build a container image from scratch** based on the official Python Docker image. Taking care of the **order** of instructions in the `Dockerfile` and the **Docker cache** you can **minimize build times**, to maximize your productivity (and avoid boredom). 😎 - -In certain special cases, you might want to use the official Docker image for FastAPI. 🤓 diff --git a/docs/en/docs/deployment/https.md b/docs/en/docs/deployment/https.md index 5cf76c111..46eda791e 100644 --- a/docs/en/docs/deployment/https.md +++ b/docs/en/docs/deployment/https.md @@ -4,8 +4,11 @@ It is easy to assume that HTTPS is something that is just "enabled" or not. But it is way more complex than that. -!!! tip - If you are in a hurry or don't care, continue with the next sections for step by step instructions to set everything up with different techniques. +/// tip + +If you are in a hurry or don't care, continue with the next sections for step by step instructions to set everything up with different techniques. + +/// To **learn the basics of HTTPS**, from a consumer perspective, check https://howhttps.works/. @@ -68,8 +71,11 @@ In the DNS server(s) you would configure a record (an "`A record`") to point **y You would probably do this just once, the first time, when setting everything up. -!!! tip - This Domain Name part is way before HTTPS, but as everything depends on the domain and the IP address, it's worth mentioning it here. +/// tip + +This Domain Name part is way before HTTPS, but as everything depends on the domain and the IP address, it's worth mentioning it here. + +/// ### DNS @@ -115,8 +121,11 @@ After this, the client and the server have an **encrypted TCP connection**, this And that's what **HTTPS** is, it's just plain **HTTP** inside a **secure TLS connection** instead of a pure (unencrypted) TCP connection. -!!! tip - Notice that the encryption of the communication happens at the **TCP level**, not at the HTTP level. +/// tip + +Notice that the encryption of the communication happens at the **TCP level**, not at the HTTP level. + +/// ### HTTPS Request diff --git a/docs/en/docs/deployment/manually.md b/docs/en/docs/deployment/manually.md index b10a3686d..19ba98075 100644 --- a/docs/en/docs/deployment/manually.md +++ b/docs/en/docs/deployment/manually.md @@ -1,133 +1,145 @@ -# Run a Server Manually - Uvicorn +# Run a Server Manually -The main thing you need to run a **FastAPI** application in a remote server machine is an ASGI server program like **Uvicorn**. +## Use the `fastapi run` Command -There are 3 main alternatives: +In short, use `fastapi run` to serve your FastAPI application: -* Uvicorn: a high performance ASGI server. -* Hypercorn: an ASGI server compatible with HTTP/2 and Trio among other features. -* Daphne: the ASGI server built for Django Channels. - -## Server Machine and Server Program - -There's a small detail about names to keep in mind. 💡 +
-The word "**server**" is commonly used to refer to both the remote/cloud computer (the physical or virtual machine) and also the program that is running on that machine (e.g. Uvicorn). +```console +$ fastapi run main.py -Just keep in mind that when you read "server" in general, it could refer to one of those two things. + FastAPI Starting production server 🚀 -When referring to the remote machine, it's common to call it **server**, but also **machine**, **VM** (virtual machine), **node**. Those all refer to some type of remote machine, normally running Linux, where you run programs. + Searching for package file structure from directories + with __init__.py files + Importing from /home/user/code/awesomeapp -## Install the Server Program + module 🐍 main.py -You can install an ASGI compatible server with: + code Importing the FastAPI app object from the module with + the following code: -=== "Uvicorn" + from main import app - * Uvicorn, a lightning-fast ASGI server, built on uvloop and httptools. + app Using import string: main:app -
+ server Server started at http://0.0.0.0:8000 + server Documentation at http://0.0.0.0:8000/docs - ```console - $ pip install "uvicorn[standard]" + Logs: - ---> 100% - ``` + INFO Started server process [2306215] + INFO Waiting for application startup. + INFO Application startup complete. + INFO Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C + to quit) +``` -
+
- !!! tip - By adding the `standard`, Uvicorn will install and use some recommended extra dependencies. +That would work for most of the cases. 😎 - That including `uvloop`, the high-performance drop-in replacement for `asyncio`, that provides the big concurrency performance boost. +You could use that command for example to start your **FastAPI** app in a container, in a server, etc. -=== "Hypercorn" +## ASGI Servers - * Hypercorn, an ASGI server also compatible with HTTP/2. +Let's go a little deeper into the details. -
+FastAPI uses a standard for building Python web frameworks and servers called ASGI. FastAPI is an ASGI web framework. - ```console - $ pip install hypercorn +The main thing you need to run a **FastAPI** application (or any other ASGI application) in a remote server machine is an ASGI server program like **Uvicorn**, this is the one that comes by default in the `fastapi` command. - ---> 100% - ``` +There are several alternatives, including: -
+* Uvicorn: a high performance ASGI server. +* Hypercorn: an ASGI server compatible with HTTP/2 and Trio among other features. +* Daphne: the ASGI server built for Django Channels. +* Granian: A Rust HTTP server for Python applications. +* NGINX Unit: NGINX Unit is a lightweight and versatile web application runtime. - ...or any other ASGI server. +## Server Machine and Server Program -## Run the Server Program +There's a small detail about names to keep in mind. 💡 -You can then run your application the same way you have done in the tutorials, but without the `--reload` option, e.g.: +The word "**server**" is commonly used to refer to both the remote/cloud computer (the physical or virtual machine) and also the program that is running on that machine (e.g. Uvicorn). -=== "Uvicorn" +Just keep in mind that when you read "server" in general, it could refer to one of those two things. -
+When referring to the remote machine, it's common to call it **server**, but also **machine**, **VM** (virtual machine), **node**. Those all refer to some type of remote machine, normally running Linux, where you run programs. - ```console - $ uvicorn main:app --host 0.0.0.0 --port 80 +## Install the Server Program - INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) - ``` +When you install FastAPI, it comes with a production server, Uvicorn, and you can start it with the `fastapi run` command. -
+But you can also install an ASGI server manually. -=== "Hypercorn" +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then you can install the server application. -
+For example, to install Uvicorn: - ```console - $ hypercorn main:app --bind 0.0.0.0:80 +
- Running on 0.0.0.0:8080 over http (CTRL + C to quit) - ``` +```console +$ pip install "uvicorn[standard]" -
+---> 100% +``` -!!! warning - Remember to remove the `--reload` option if you were using it. +
- The `--reload` option consumes much more resources, is more unstable, etc. +A similar process would apply to any other ASGI server program. - It helps a lot during **development**, but you **shouldn't** use it in **production**. +/// tip -## Hypercorn with Trio +By adding the `standard`, Uvicorn will install and use some recommended extra dependencies. -Starlette and **FastAPI** are based on AnyIO, which makes them compatible with both Python's standard library asyncio and Trio. +That including `uvloop`, the high-performance drop-in replacement for `asyncio`, that provides the big concurrency performance boost. -Nevertheless, Uvicorn is currently only compatible with asyncio, and it normally uses `uvloop`, the high-performance drop-in replacement for `asyncio`. +When you install FastAPI with something like `pip install "fastapi[standard]"` you already get `uvicorn[standard]` as well. -But if you want to directly use **Trio**, then you can use **Hypercorn** as it supports it. ✨ +/// -### Install Hypercorn with Trio +## Run the Server Program -First you need to install Hypercorn with Trio support: +If you installed an ASGI server manually, you would normally need to pass an import string in a special format for it to import your FastAPI application:
```console -$ pip install "hypercorn[trio]" ----> 100% +$ uvicorn main:app --host 0.0.0.0 --port 80 + +INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) ```
-### Run with Trio +/// note -Then you can pass the command line option `--worker-class` with the value `trio`: +The command `uvicorn main:app` refers to: -
+* `main`: the file `main.py` (the Python "module"). +* `app`: the object created inside of `main.py` with the line `app = FastAPI()`. -```console -$ hypercorn main:app --worker-class trio +It is equivalent to: + +```Python +from main import app ``` -
+/// + +Each alternative ASGI server program would have a similar command, you can read more in their respective documentation. + +/// warning + +Uvicorn and other servers support a `--reload` option that is useful during development. + +The `--reload` option consumes much more resources, is more unstable, etc. -And that will start Hypercorn with your app using Trio as the backend. +It helps a lot during **development**, but you **shouldn't** use it in **production**. -Now you can use Trio internally in your app. Or even better, you can use AnyIO, to keep your code compatible with both Trio and asyncio. 🎉 +/// ## Deployment Concepts diff --git a/docs/en/docs/deployment/server-workers.md b/docs/en/docs/deployment/server-workers.md index 2df9f3d43..5d6b0d00a 100644 --- a/docs/en/docs/deployment/server-workers.md +++ b/docs/en/docs/deployment/server-workers.md @@ -1,4 +1,4 @@ -# Server Workers - Gunicorn with Uvicorn +# Server Workers - Uvicorn with Workers Let's check back those deployment concepts from before: @@ -9,120 +9,79 @@ Let's check back those deployment concepts from before: * Memory * Previous steps before starting -Up to this point, with all the tutorials in the docs, you have probably been running a **server program** like Uvicorn, running a **single process**. +Up to this point, with all the tutorials in the docs, you have probably been running a **server program**, for example, using the `fastapi` command, that runs Uvicorn, running a **single process**. When deploying applications you will probably want to have some **replication of processes** to take advantage of **multiple cores** and to be able to handle more requests. -As you saw in the previous chapter about [Deployment Concepts](./concepts.md){.internal-link target=_blank}, there are multiple strategies you can use. +As you saw in the previous chapter about [Deployment Concepts](concepts.md){.internal-link target=_blank}, there are multiple strategies you can use. -Here I'll show you how to use **Gunicorn** with **Uvicorn worker processes**. +Here I'll show you how to use **Uvicorn** with **worker processes** using the `fastapi` command or the `uvicorn` command directly. -!!! info - If you are using containers, for example with Docker or Kubernetes, I'll tell you more about that in the next chapter: [FastAPI in Containers - Docker](./docker.md){.internal-link target=_blank}. +/// info - In particular, when running on **Kubernetes** you will probably **not** want to use Gunicorn and instead run **a single Uvicorn process per container**, but I'll tell you about it later in that chapter. +If you are using containers, for example with Docker or Kubernetes, I'll tell you more about that in the next chapter: [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank}. -## Gunicorn with Uvicorn Workers +In particular, when running on **Kubernetes** you will probably **not** want to use workers and instead run **a single Uvicorn process per container**, but I'll tell you about it later in that chapter. -**Gunicorn** is mainly an application server using the **WSGI standard**. That means that Gunicorn can serve applications like Flask and Django. Gunicorn by itself is not compatible with **FastAPI**, as FastAPI uses the newest **ASGI standard**. +/// -But Gunicorn supports working as a **process manager** and allowing users to tell it which specific **worker process class** to use. Then Gunicorn would start one or more **worker processes** using that class. +## Multiple Workers -And **Uvicorn** has a **Gunicorn-compatible worker class**. +You can start multiple workers with the `--workers` command line option: -Using that combination, Gunicorn would act as a **process manager**, listening on the **port** and the **IP**. And it would **transmit** the communication to the worker processes running the **Uvicorn class**. +//// tab | `fastapi` -And then the Gunicorn-compatible **Uvicorn worker** class would be in charge of converting the data sent by Gunicorn to the ASGI standard for FastAPI to use it. - -## Install Gunicorn and Uvicorn +If you use the `fastapi` command:
```console -$ pip install "uvicorn[standard]" gunicorn - ----> 100% -``` - -
- -That will install both Uvicorn with the `standard` extra packages (to get high performance) and Gunicorn. +$ fastapi run --workers 4 main.py -## Run Gunicorn with Uvicorn Workers + FastAPI Starting production server 🚀 -Then you can run Gunicorn with: + Searching for package file structure from directories with + __init__.py files + Importing from /home/user/code/awesomeapp -
- -```console -$ gunicorn main:app --workers 4 --worker-class uvicorn.workers.UvicornWorker --bind 0.0.0.0:80 - -[19499] [INFO] Starting gunicorn 20.1.0 -[19499] [INFO] Listening at: http://0.0.0.0:80 (19499) -[19499] [INFO] Using worker: uvicorn.workers.UvicornWorker -[19511] [INFO] Booting worker with pid: 19511 -[19513] [INFO] Booting worker with pid: 19513 -[19514] [INFO] Booting worker with pid: 19514 -[19515] [INFO] Booting worker with pid: 19515 -[19511] [INFO] Started server process [19511] -[19511] [INFO] Waiting for application startup. -[19511] [INFO] Application startup complete. -[19513] [INFO] Started server process [19513] -[19513] [INFO] Waiting for application startup. -[19513] [INFO] Application startup complete. -[19514] [INFO] Started server process [19514] -[19514] [INFO] Waiting for application startup. -[19514] [INFO] Application startup complete. -[19515] [INFO] Started server process [19515] -[19515] [INFO] Waiting for application startup. -[19515] [INFO] Application startup complete. -``` - -
+ module 🐍 main.py -Let's see what each of those options mean: + code Importing the FastAPI app object from the module with the + following code: -* `main:app`: This is the same syntax used by Uvicorn, `main` means the Python module named "`main`", so, a file `main.py`. And `app` is the name of the variable that is the **FastAPI** application. - * You can imagine that `main:app` is equivalent to a Python `import` statement like: + from main import app - ```Python - from main import app - ``` + app Using import string: main:app - * So, the colon in `main:app` would be equivalent to the Python `import` part in `from main import app`. + server Server started at http://0.0.0.0:8000 + server Documentation at http://0.0.0.0:8000/docs -* `--workers`: The number of worker processes to use, each will run a Uvicorn worker, in this case, 4 workers. + Logs: -* `--worker-class`: The Gunicorn-compatible worker class to use in the worker processes. - * Here we pass the class that Gunicorn can import and use with: - - ```Python - import uvicorn.workers.UvicornWorker - ``` - -* `--bind`: This tells Gunicorn the IP and the port to listen to, using a colon (`:`) to separate the IP and the port. - * If you were running Uvicorn directly, instead of `--bind 0.0.0.0:80` (the Gunicorn option) you would use `--host 0.0.0.0` and `--port 80`. - -In the output, you can see that it shows the **PID** (process ID) of each process (it's just a number). - -You can see that: - -* The Gunicorn **process manager** starts with PID `19499` (in your case it will be a different number). -* Then it starts `Listening at: http://0.0.0.0:80`. -* Then it detects that it has to use the worker class at `uvicorn.workers.UvicornWorker`. -* And then it starts **4 workers**, each with its own PID: `19511`, `19513`, `19514`, and `19515`. - -Gunicorn would also take care of managing **dead processes** and **restarting** new ones if needed to keep the number of workers. So that helps in part with the **restart** concept from the list above. - -Nevertheless, you would probably also want to have something outside making sure to **restart Gunicorn** if necessary, and also to **run it on startup**, etc. + INFO Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to + quit) + INFO Started parent process [27365] + INFO Started server process [27368] + INFO Started server process [27369] + INFO Started server process [27370] + INFO Started server process [27367] + INFO Waiting for application startup. + INFO Waiting for application startup. + INFO Waiting for application startup. + INFO Waiting for application startup. + INFO Application startup complete. + INFO Application startup complete. + INFO Application startup complete. + INFO Application startup complete. +``` -## Uvicorn with Workers +
-Uvicorn also has an option to start and run several **worker processes**. +//// -Nevertheless, as of now, Uvicorn's capabilities for handling worker processes are more limited than Gunicorn's. So, if you want to have a process manager at this level (at the Python level), then it might be better to try with Gunicorn as the process manager. +//// tab | `uvicorn` -In any case, you would run it like this: +If you prefer to use the `uvicorn` command directly:
@@ -146,13 +105,15 @@ $ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4
+//// + The only new option here is `--workers` telling Uvicorn to start 4 worker processes. You can also see that it shows the **PID** of each process, `27365` for the parent process (this is the **process manager**) and one for each worker process: `27368`, `27369`, `27370`, and `27367`. ## Deployment Concepts -Here you saw how to use **Gunicorn** (or Uvicorn) managing **Uvicorn worker processes** to **parallelize** the execution of the application, take advantage of **multiple cores** in the CPU, and be able to serve **more requests**. +Here you saw how to use multiple **workers** to **parallelize** the execution of the application, take advantage of **multiple cores** in the CPU, and be able to serve **more requests**. From the list of deployment concepts from above, using workers would mainly help with the **replication** part, and a little bit with the **restarts**, but you still need to take care of the others: @@ -165,15 +126,13 @@ From the list of deployment concepts from above, using workers would mainly help ## Containers and Docker -In the next chapter about [FastAPI in Containers - Docker](./docker.md){.internal-link target=_blank} I'll tell some strategies you could use to handle the other **deployment concepts**. - -I'll also show you the **official Docker image** that includes **Gunicorn with Uvicorn workers** and some default configurations that can be useful for simple cases. +In the next chapter about [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank} I'll explain some strategies you could use to handle the other **deployment concepts**. -There I'll also show you how to **build your own image from scratch** to run a single Uvicorn process (without Gunicorn). It is a simple process and is probably what you would want to do when using a distributed container management system like **Kubernetes**. +I'll show you how to **build your own image from scratch** to run a single Uvicorn process. It is a simple process and is probably what you would want to do when using a distributed container management system like **Kubernetes**. ## Recap -You can use **Gunicorn** (or also Uvicorn) as a process manager with Uvicorn workers to take advantage of **multi-core CPUs**, to run **multiple processes in parallel**. +You can use multiple worker processes with the `--workers` CLI option with the `fastapi` or `uvicorn` commands to take advantage of **multi-core CPUs**, to run **multiple processes in parallel**. You could use these tools and ideas if you are setting up **your own deployment system** while taking care of the other deployment concepts yourself. diff --git a/docs/en/docs/deployment/versions.md b/docs/en/docs/deployment/versions.md index 4be9385dd..23f49cf99 100644 --- a/docs/en/docs/deployment/versions.md +++ b/docs/en/docs/deployment/versions.md @@ -12,25 +12,25 @@ You can create production applications with **FastAPI** right now (and you have The first thing you should do is to "pin" the version of **FastAPI** you are using to the specific latest version that you know works correctly for your application. -For example, let's say you are using version `0.45.0` in your app. +For example, let's say you are using version `0.112.0` in your app. If you use a `requirements.txt` file you could specify the version with: ```txt -fastapi==0.45.0 +fastapi[standard]==0.112.0 ``` -that would mean that you would use exactly the version `0.45.0`. +that would mean that you would use exactly the version `0.112.0`. Or you could also pin it with: ```txt -fastapi>=0.45.0,<0.46.0 +fastapi[standard]>=0.112.0,<0.113.0 ``` -that would mean that you would use the versions `0.45.0` or above, but less than `0.46.0`, for example, a version `0.45.2` would still be accepted. +that would mean that you would use the versions `0.112.0` or above, but less than `0.113.0`, for example, a version `0.112.2` would still be accepted. -If you use any other tool to manage your installations, like Poetry, Pipenv, or others, they all have a way that you can use to define specific versions for your packages. +If you use any other tool to manage your installations, like `uv`, Poetry, Pipenv, or others, they all have a way that you can use to define specific versions for your packages. ## Available versions @@ -42,8 +42,11 @@ Following the Semantic Versioning conventions, any version below `1.0.0` could p FastAPI also follows the convention that any "PATCH" version change is for bug fixes and non-breaking changes. -!!! tip - The "PATCH" is the last number, for example, in `0.2.3`, the PATCH version is `3`. +/// tip + +The "PATCH" is the last number, for example, in `0.2.3`, the PATCH version is `3`. + +/// So, you should be able to pin to a version like: @@ -53,8 +56,11 @@ fastapi>=0.45.0,<0.46.0 Breaking changes and new features are added in "MINOR" versions. -!!! tip - The "MINOR" is the number in the middle, for example, in `0.2.3`, the MINOR version is `2`. +/// tip + +The "MINOR" is the number in the middle, for example, in `0.2.3`, the MINOR version is `2`. + +/// ## Upgrading the FastAPI versions @@ -78,10 +84,10 @@ So, you can just let **FastAPI** use the correct Starlette version. Pydantic includes the tests for **FastAPI** with its own tests, so new versions of Pydantic (above `1.0.0`) are always compatible with FastAPI. -You can pin Pydantic to any version above `1.0.0` that works for you and below `2.0.0`. +You can pin Pydantic to any version above `1.0.0` that works for you. For example: ```txt -pydantic>=1.2.0,<2.0.0 +pydantic>=2.7.0,<3.0.0 ``` diff --git a/docs/en/docs/environment-variables.md b/docs/en/docs/environment-variables.md new file mode 100644 index 000000000..43dd06add --- /dev/null +++ b/docs/en/docs/environment-variables.md @@ -0,0 +1,298 @@ +# Environment Variables + +/// tip + +If you already know what "environment variables" are and how to use them, feel free to skip this. + +/// + +An environment variable (also known as "**env var**") is a variable that lives **outside** of the Python code, in the **operating system**, and could be read by your Python code (or by other programs as well). + +Environment variables could be useful for handling application **settings**, as part of the **installation** of Python, etc. + +## Create and Use Env Vars + +You can **create** and use environment variables in the **shell (terminal)**, without needing Python: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// You could create an env var MY_NAME with +$ export MY_NAME="Wade Wilson" + +// Then you could use it with other programs, like +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// Create an env var MY_NAME +$ $Env:MY_NAME = "Wade Wilson" + +// Use it with other programs, like +$ echo "Hello $Env:MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +## Read env vars in Python + +You could also create environment variables **outside** of Python, in the terminal (or with any other method), and then **read them in Python**. + +For example you could have a file `main.py` with: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// tip + +The second argument to `os.getenv()` is the default value to return. + +If not provided, it's `None` by default, here we provide `"World"` as the default value to use. + +/// + +Then you could call that Python program: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// Here we don't set the env var yet +$ python main.py + +// As we didn't set the env var, we get the default value + +Hello World from Python + +// But if we create an environment variable first +$ export MY_NAME="Wade Wilson" + +// And then call the program again +$ python main.py + +// Now it can read the environment variable + +Hello Wade Wilson from Python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// Here we don't set the env var yet +$ python main.py + +// As we didn't set the env var, we get the default value + +Hello World from Python + +// But if we create an environment variable first +$ $Env:MY_NAME = "Wade Wilson" + +// And then call the program again +$ python main.py + +// Now it can read the environment variable + +Hello Wade Wilson from Python +``` + +
+ +//// + +As environment variables can be set outside of the code, but can be read by the code, and don't have to be stored (committed to `git`) with the rest of the files, it's common to use them for configurations or **settings**. + +You can also create an environment variable only for a **specific program invocation**, that is only available to that program, and only for its duration. + +To do that, create it right before the program itself, on the same line: + +
+ +```console +// Create an env var MY_NAME in line for this program call +$ MY_NAME="Wade Wilson" python main.py + +// Now it can read the environment variable + +Hello Wade Wilson from Python + +// The env var no longer exists afterwards +$ python main.py + +Hello World from Python +``` + +
+ +/// tip + +You can read more about it at The Twelve-Factor App: Config. + +/// + +## Types and Validation + +These environment variables can only handle **text strings**, as they are external to Python and have to be compatible with other programs and the rest of the system (and even with different operating systems, as Linux, Windows, macOS). + +That means that **any value** read in Python from an environment variable **will be a `str`**, and any conversion to a different type or any validation has to be done in code. + +You will learn more about using environment variables for handling **application settings** in the [Advanced User Guide - Settings and Environment Variables](./advanced/settings.md){.internal-link target=_blank}. + +## `PATH` Environment Variable + +There is a **special** environment variable called **`PATH`** that is used by the operating systems (Linux, macOS, Windows) to find programs to run. + +The value of the variable `PATH` is a long string that is made of directories separated by a colon `:` on Linux and macOS, and by a semicolon `;` on Windows. + +For example, the `PATH` environment variable could look like this: + +//// tab | Linux, macOS + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +This means that the system should look for programs in the directories: + +* `/usr/local/bin` +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32 +``` + +This means that the system should look for programs in the directories: + +* `C:\Program Files\Python312\Scripts` +* `C:\Program Files\Python312` +* `C:\Windows\System32` + +//// + +When you type a **command** in the terminal, the operating system **looks for** the program in **each of those directories** listed in the `PATH` environment variable. + +For example, when you type `python` in the terminal, the operating system looks for a program called `python` in the **first directory** in that list. + +If it finds it, then it will **use it**. Otherwise it keeps looking in the **other directories**. + +### Installing Python and Updating the `PATH` + +When you install Python, you might be asked if you want to update the `PATH` environment variable. + +//// tab | Linux, macOS + +Let's say you install Python and it ends up in a directory `/opt/custompython/bin`. + +If you say yes to update the `PATH` environment variable, then the installer will add `/opt/custompython/bin` to the `PATH` environment variable. + +It could look like this: + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin +``` + +This way, when you type `python` in the terminal, the system will find the Python program in `/opt/custompython/bin` (the last directory) and use that one. + +//// + +//// tab | Windows + +Let's say you install Python and it ends up in a directory `C:\opt\custompython\bin`. + +If you say yes to update the `PATH` environment variable, then the installer will add `C:\opt\custompython\bin` to the `PATH` environment variable. + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin +``` + +This way, when you type `python` in the terminal, the system will find the Python program in `C:\opt\custompython\bin` (the last directory) and use that one. + +//// + +So, if you type: + +
+ +```console +$ python +``` + +
+ +//// tab | Linux, macOS + +The system will **find** the `python` program in `/opt/custompython/bin` and run it. + +It would be roughly equivalent to typing: + +
+ +```console +$ /opt/custompython/bin/python +``` + +
+ +//// + +//// tab | Windows + +The system will **find** the `python` program in `C:\opt\custompython\bin\python` and run it. + +It would be roughly equivalent to typing: + +
+ +```console +$ C:\opt\custompython\bin\python +``` + +
+ +//// + +This information will be useful when learning about [Virtual Environments](virtual-environments.md){.internal-link target=_blank}. + +## Conclusion + +With this you should have a basic understanding of what **environment variables** are and how to use them in Python. + +You can also read more about them in the Wikipedia for Environment Variable. + +In many cases it's not very obvious how environment variables would be useful and applicable right away. But they keep showing up in many different scenarios when you are developing, so it's good to know about them. + +For example, you will need this information in the next section, about [Virtual Environments](virtual-environments.md). diff --git a/docs/en/docs/external-links.md b/docs/en/docs/external-links.md index b89021ee2..3ed04e5c5 100644 --- a/docs/en/docs/external-links.md +++ b/docs/en/docs/external-links.md @@ -6,8 +6,11 @@ There are many posts, articles, tools, and projects, related to **FastAPI**. Here's an incomplete list of some of them. -!!! tip - If you have an article, project, tool, or anything related to **FastAPI** that is not yet listed here, create a Pull Request adding it. +/// tip + +If you have an article, project, tool, or anything related to **FastAPI** that is not yet listed here, create a Pull Request adding it. + +/// {% for section_name, section_content in external_links.items() %} @@ -25,9 +28,12 @@ Here's an incomplete list of some of them. {% endfor %} {% endfor %} -## Projects +## GitHub Repositories + +Most starred GitHub repositories with the topic `fastapi`: -Latest GitHub projects with the topic `fastapi`: +{% for repo in topic_repos %} -
-
+★ {{repo.stars}} - {{repo.name}} by @{{repo.owner_login}}. + +{% endfor %} diff --git a/docs/en/docs/fastapi-cli.md b/docs/en/docs/fastapi-cli.md new file mode 100644 index 000000000..654d2fe91 --- /dev/null +++ b/docs/en/docs/fastapi-cli.md @@ -0,0 +1,75 @@ +# FastAPI CLI + +**FastAPI CLI** is a command line program that you can use to serve your FastAPI app, manage your FastAPI project, and more. + +When you install FastAPI (e.g. with `pip install "fastapi[standard]"`), it includes a package called `fastapi-cli`, this package provides the `fastapi` command in the terminal. + +To run your FastAPI app for development, you can use the `fastapi dev` command: + +
+ +```console +$ fastapi dev main.py + + FastAPI Starting development server 🚀 + + Searching for package file structure from directories with + __init__.py files + Importing from /home/user/code/awesomeapp + + module 🐍 main.py + + code Importing the FastAPI app object from the module with the + following code: + + from main import app + + app Using import string: main:app + + server Server started at http://127.0.0.1:8000 + server Documentation at http://127.0.0.1:8000/docs + + tip Running in development mode, for production use: + fastapi run + + Logs: + + INFO Will watch for changes in these directories: + ['/home/user/code/awesomeapp'] + INFO Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to + quit) + INFO Started reloader process [383138] using WatchFiles + INFO Started server process [383153] + INFO Waiting for application startup. + INFO Application startup complete. +``` + +
+ +The command line program called `fastapi` is **FastAPI CLI**. + +FastAPI CLI takes the path to your Python program (e.g. `main.py`) and automatically detects the `FastAPI` instance (commonly named `app`), determines the correct import process, and then serves it. + +For production you would use `fastapi run` instead. 🚀 + +Internally, **FastAPI CLI** uses Uvicorn, a high-performance, production-ready, ASGI server. 😎 + +## `fastapi dev` + +Running `fastapi dev` initiates development mode. + +By default, **auto-reload** is enabled, automatically reloading the server when you make changes to your code. This is resource-intensive and could be less stable than when it's disabled. You should only use it for development. It also listens on the IP address `127.0.0.1`, which is the IP for your machine to communicate with itself alone (`localhost`). + +## `fastapi run` + +Executing `fastapi run` starts FastAPI in production mode by default. + +By default, **auto-reload** is disabled. It also listens on the IP address `0.0.0.0`, which means all the available IP addresses, this way it will be publicly accessible to anyone that can communicate with the machine. This is how you would normally run it in production, for example, in a container. + +In most cases you would (and should) have a "termination proxy" handling HTTPS for you on top, this will depend on how you deploy your application, your provider might do this for you, or you might need to set it up yourself. + +/// tip + +You can learn more about it in the [deployment documentation](deployment/index.md){.internal-link target=_blank}. + +/// diff --git a/docs/en/docs/fastapi-people.md b/docs/en/docs/fastapi-people.md index 7e26358d8..f2ca26013 100644 --- a/docs/en/docs/fastapi-people.md +++ b/docs/en/docs/fastapi-people.md @@ -7,23 +7,21 @@ hide: FastAPI has an amazing community that welcomes people from all backgrounds. -## Creator - Maintainer +## Creator Hey! 👋 This is me: -{% if people %}
{% for user in people.maintainers %} -
@{{ user.login }}
Answers: {{ user.answers }}
Pull Requests: {{ user.prs }}
+
@{{ contributors.tiangolo.login }}
Answers: {{ user.answers }}
Pull Requests: {{ contributors.tiangolo.count }}
{% endfor %}
-{% endif %} -I'm the creator and maintainer of **FastAPI**. You can read more about that in [Help FastAPI - Get Help - Connect with the author](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. +I'm the creator of **FastAPI**. You can read more about that in [Help FastAPI - Get Help - Connect with the author](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. ...But here I want to show you the community. @@ -36,82 +34,206 @@ These are the people that: * [Help others with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. * [Create Pull Requests](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. * Review Pull Requests, [especially important for translations](contributing.md#translations){.internal-link target=_blank}. +* Help [manage the repository](management-tasks.md){.internal-link target=_blank} (team members). + +All these tasks help maintain the repository. A round of applause to them. 👏 🙇 -## Most active users last month +## Team -These are the users that have been [helping others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} during the last month. ☕ +This is the current list of team members. 😎 + +They have different levels of involvement and permissions, they can perform [repository management tasks](./management-tasks.md){.internal-link target=_blank} and together we [manage the FastAPI repository](./management.md){.internal-link target=_blank}. -{% if people %}
-{% for user in people.last_month_active %} + +{% for user in members["members"] %} + + + +{% endfor %} + +
+ +Although the team members have the permissions to perform privileged tasks, all the [help from others maintaining FastAPI](./help-fastapi.md#help-maintain-fastapi){.internal-link target=_blank} is very much appreciated! 🙇‍♂️ + +## FastAPI Experts + +These are the users that have been [helping others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. 🙇 + +They have proven to be **FastAPI Experts** by helping many others. ✨ + +/// tip + +You could become an official FastAPI Expert too! + +Just [help others with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. 🤓 + +/// + +You can see the **FastAPI Experts** for: + +* [Last Month](#fastapi-experts-last-month) 🤓 +* [3 Months](#fastapi-experts-3-months) 😎 +* [6 Months](#fastapi-experts-6-months) 🧐 +* [1 Year](#fastapi-experts-1-year) 🧑‍🔬 +* [**All Time**](#fastapi-experts-all-time) 🧙 + +### FastAPI Experts - Last Month + +These are the users that have been [helping others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} during the last month. 🤓 + +
+ +{% for user in people.last_month_experts[:10] %} + +{% if user.login not in skip_users %}
@{{ user.login }}
Questions replied: {{ user.count }}
+ +{% endif %} + {% endfor %}
+ +### FastAPI Experts - 3 Months + +These are the users that have been [helping others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} during the last 3 months. 😎 + +
+ +{% for user in people.three_months_experts[:10] %} + +{% if user.login not in skip_users %} + +
@{{ user.login }}
Questions replied: {{ user.count }}
+ {% endif %} -## Experts +{% endfor %} -Here are the **FastAPI Experts**. 🤓 +
-These are the users that have [helped others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} through *all time*. +### FastAPI Experts - 6 Months -They have proven to be experts by helping many others. ✨ +These are the users that have been [helping others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} during the last 6 months. 🧐 -{% if people %}
-{% for user in people.experts %} + +{% for user in people.six_months_experts[:10] %} + +{% if user.login not in skip_users %}
@{{ user.login }}
Questions replied: {{ user.count }}
+ +{% endif %} + {% endfor %}
+ +### FastAPI Experts - 1 Year + +These are the users that have been [helping others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} during the last year. 🧑‍🔬 + +
+ +{% for user in people.one_year_experts[:20] %} + +{% if user.login not in skip_users %} + +
@{{ user.login }}
Questions replied: {{ user.count }}
+ +{% endif %} + +{% endfor %} + +
+ +### FastAPI Experts - All Time + +Here are the all time **FastAPI Experts**. 🤓🤯 + +These are the users that have [helped others the most with questions in GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} through *all time*. 🧙 + +
+ +{% for user in people.experts[:50] %} + +{% if user.login not in skip_users %} + +
@{{ user.login }}
Questions replied: {{ user.count }}
+ {% endif %} +{% endfor %} + +
+ ## Top Contributors Here are the **Top Contributors**. 👷 These users have [created the most Pull Requests](help-fastapi.md#create-a-pull-request){.internal-link target=_blank} that have been *merged*. -They have contributed source code, documentation, translations, etc. 📦 +They have contributed source code, documentation, etc. 📦 -{% if people %}
-{% for user in people.top_contributors %} + +{% for user in (contributors.values() | list)[:50] %} + +{% if user.login not in skip_users %}
@{{ user.login }}
Pull Requests: {{ user.count }}
+ +{% endif %} + {% endfor %}
-{% endif %} -There are many other contributors (more than a hundred), you can see them all in the FastAPI GitHub Contributors page. 👷 +There are hundreds of other contributors, you can see them all in the FastAPI GitHub Contributors page. 👷 -## Top Reviewers +## Top Translators -These users are the **Top Reviewers**. 🕵️ +These are the **Top Translators**. 🌐 -### Reviews for Translations +These users have created the most Pull Requests with [translations to other languages](contributing.md#translations){.internal-link target=_blank} that have been *merged*. -I only speak a few languages (and not very well 😅). So, the reviewers are the ones that have the [**power to approve translations**](contributing.md#translations){.internal-link target=_blank} of the documentation. Without them, there wouldn't be documentation in several other languages. +
---- +{% for user in (translators.values() | list)[:50] %} + +{% if user.login not in skip_users %} + +
@{{ user.login }}
Translations: {{ user.count }}
+ +{% endif %} -The **Top Reviewers** 🕵️ have reviewed the most Pull Requests from others, ensuring the quality of the code, documentation, and especially, the **translations**. +{% endfor %} + +
+ +## Top Translation Reviewers + +These users are the **Top Translation Reviewers**. 🕵️ + +I only speak a few languages (and not very well 😅). So, the reviewers are the ones that have the [**power to approve translations**](contributing.md#translations){.internal-link target=_blank} of the documentation. Without them, there wouldn't be documentation in several other languages. -{% if people %}
-{% for user in people.top_reviewers %} +{% for user in (translation_reviewers.values() | list)[:50] %} + +{% if user.login not in skip_users %}
@{{ user.login }}
Reviews: {{ user.count }}
+ +{% endif %} + {% endfor %}
-{% endif %} ## Sponsors @@ -176,7 +298,7 @@ The main intention of this page is to highlight the effort of the community to h Especially including efforts that are normally less visible, and in many cases more arduous, like helping others with questions and reviewing Pull Requests with translations. -The data is calculated each month, you can read the source code here. +The data is calculated each month, you can read the source code here. Here I'm also highlighting contributions from sponsors. diff --git a/docs/en/docs/features.md b/docs/en/docs/features.md index 6f13b03bb..9c38a4bd2 100644 --- a/docs/en/docs/features.md +++ b/docs/en/docs/features.md @@ -1,8 +1,3 @@ ---- -hide: - - navigation ---- - # Features ## FastAPI features @@ -11,7 +6,7 @@ hide: ### Based on open standards -* OpenAPI for API creation, including declarations of path operations, parameters, body requests, security, etc. +* OpenAPI for API creation, including declarations of path operations, parameters, request bodies, security, etc. * Automatic data model documentation with JSON Schema (as OpenAPI itself is based on JSON Schema). * Designed around these standards, after a meticulous study. Instead of an afterthought layer on top. * This also allows using automatic **client code generation** in many languages. @@ -30,7 +25,7 @@ Interactive API documentation and exploration web user interfaces. As the framew ### Just Modern Python -It's all based on standard **Python 3.6 type** declarations (thanks to Pydantic). No new syntax to learn. Just standard modern Python. +It's all based on standard **Python type** declarations (thanks to Pydantic). No new syntax to learn. Just standard modern Python. If you need a 2 minute refresher of how to use Python types (even if you don't use FastAPI), check the short tutorial: [Python Types](python-types.md){.internal-link target=_blank}. @@ -68,16 +63,19 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` means: +/// info + +`**second_user_data` means: + +Pass the keys and values of the `second_user_data` dict directly as key-value arguments, equivalent to: `User(id=4, name="Mary", joined="2018-11-30")` - Pass the keys and values of the `second_user_data` dict directly as key-value arguments, equivalent to: `User(id=4, name="Mary", joined="2018-11-30")` +/// ### Editor support All the framework was designed to be easy and intuitive to use, all the decisions were tested on multiple editors even before starting development, to ensure the best development experience. -In the last Python developer survey it was clear that the most used feature is "autocompletion". +In the Python developer surveys, it's clear that one of the most used features is "autocompletion". The whole **FastAPI** framework is based to satisfy that. Autocompletion works everywhere. @@ -179,7 +177,7 @@ With **FastAPI** you get all of **Starlette**'s features (as FastAPI is just Sta ## Pydantic features -**FastAPI** is fully compatible with (and based on) Pydantic. So, any additional Pydantic code you have, will also work. +**FastAPI** is fully compatible with (and based on) Pydantic. So, any additional Pydantic code you have, will also work. Including external libraries also based on Pydantic, as ORMs, ODMs for databases. diff --git a/docs/en/docs/help-fastapi.md b/docs/en/docs/help-fastapi.md index 71c580409..81151032f 100644 --- a/docs/en/docs/help-fastapi.md +++ b/docs/en/docs/help-fastapi.md @@ -12,7 +12,7 @@ And there are several ways to get help too. ## Subscribe to the newsletter -You can subscribe to the (infrequent) [**FastAPI and friends** newsletter](/newsletter/){.internal-link target=_blank} to stay updated about: +You can subscribe to the (infrequent) [**FastAPI and friends** newsletter](newsletter.md){.internal-link target=_blank} to stay updated about: * News about FastAPI and friends 🚀 * Guides 📝 @@ -26,13 +26,13 @@ You can subscribe to the (infrequent) [**FastAPI and friends** newsletter](/news ## Star **FastAPI** in GitHub -You can "star" FastAPI in GitHub (clicking the star button at the top right): https://github.com/tiangolo/fastapi. ⭐️ +You can "star" FastAPI in GitHub (clicking the star button at the top right): https://github.com/fastapi/fastapi. ⭐️ By adding a star, other users will be able to find it more easily and see that it has been already useful for others. ## Watch the GitHub repository for releases -You can "watch" FastAPI in GitHub (clicking the "watch" button at the top right): https://github.com/tiangolo/fastapi. 👀 +You can "watch" FastAPI in GitHub (clicking the "watch" button at the top right): https://github.com/fastapi/fastapi. 👀 There you can select "Releases only". @@ -51,7 +51,7 @@ You can: * Tell me how you use FastAPI (I love to hear that). * Hear when I make announcements or release new tools. * You can also follow @fastapi on Twitter (a separate account). -* Connect with me on **Linkedin**. +* Follow me on **LinkedIn**. * Hear when I make announcements or release new tools (although I use Twitter more often 🤷‍♂). * Read what I write (or follow me) on **Dev.to** or **Medium**. * Read other ideas, articles, and read about tools I have created. @@ -59,26 +59,26 @@ You can: ## Tweet about **FastAPI** -Tweet about **FastAPI** and let me and others know why you like it. 🎉 +Tweet about **FastAPI** and let me and others know why you like it. 🎉 I love to hear about how **FastAPI** is being used, what you have liked in it, in which project/company are you using it, etc. ## Vote for FastAPI * Vote for **FastAPI** in Slant. -* Vote for **FastAPI** in AlternativeTo. +* Vote for **FastAPI** in AlternativeTo. * Say you use **FastAPI** on StackShare. ## Help others with questions in GitHub You can try and help others with their questions in: -* GitHub Discussions -* GitHub Issues +* GitHub Discussions +* GitHub Issues In many cases you might already know the answer for those questions. 🤓 -If you are helping a lot of people with their questions, you will become an official [FastAPI Expert](fastapi-people.md#experts){.internal-link target=_blank}. 🎉 +If you are helping a lot of people with their questions, you will become an official [FastAPI Expert](fastapi-people.md#fastapi-experts){.internal-link target=_blank}. 🎉 Just remember, the most important point is: try to be kind. People come with their frustrations and in many cases don't ask in the best way, but try as best as you can to be kind. 🤗 @@ -125,7 +125,7 @@ If they reply, there's a high chance you would have solved their problem, congra ## Watch the GitHub repository -You can "watch" FastAPI in GitHub (clicking the "watch" button at the top right): https://github.com/tiangolo/fastapi. 👀 +You can "watch" FastAPI in GitHub (clicking the "watch" button at the top right): https://github.com/fastapi/fastapi. 👀 If you select "Watching" instead of "Releases only" you will receive notifications when someone creates a new issue or question. You can also specify that you only want to be notified about new issues, or discussions, or PRs, etc. @@ -133,7 +133,7 @@ Then you can try and help them solve those questions. ## Ask Questions -You can create a new question in the GitHub repository, for example to: +You can create a new question in the GitHub repository, for example to: * Ask a **question** or ask about a **problem**. * Suggest a new **feature**. @@ -170,12 +170,15 @@ And if there's any other style or consistency need, I'll ask directly for that, * Then **comment** saying that you did that, that's how I will know you really checked it. -!!! info - Unfortunately, I can't simply trust PRs that just have several approvals. +/// info - Several times it has happened that there are PRs with 3, 5 or more approvals, probably because the description is appealing, but when I check the PRs, they are actually broken, have a bug, or don't solve the problem they claim to solve. 😅 +Unfortunately, I can't simply trust PRs that just have several approvals. - So, it's really important that you actually read and run the code, and let me know in the comments that you did. 🤓 +Several times it has happened that there are PRs with 3, 5 or more approvals, probably because the description is appealing, but when I check the PRs, they are actually broken, have a bug, or don't solve the problem they claim to solve. 😅 + +So, it's really important that you actually read and run the code, and let me know in the comments that you did. 🤓 + +/// * If the PR can be simplified in a way, you can ask for that, but there's no need to be too picky, there might be a lot of subjective points of view (and I will have my own as well 🙈), so it's better if you can focus on the fundamental things. @@ -196,7 +199,7 @@ And if there's any other style or consistency need, I'll ask directly for that, You can [contribute](contributing.md){.internal-link target=_blank} to the source code with Pull Requests, for example: * To fix a typo you found on the documentation. -* To share an article, video, or podcast you created or found about FastAPI by editing this file. +* To share an article, video, or podcast you created or found about FastAPI by editing this file. * Make sure you add your link to the start of the corresponding section. * To help [translate the documentation](contributing.md#translations){.internal-link target=_blank} to your language. * You can also help to review the translations created by others. @@ -226,10 +229,13 @@ If you can help me with that, **you are helping me maintain FastAPI** and making Join the 👥 Discord chat server 👥 and hang out with others in the FastAPI community. -!!! tip - For questions, ask them in GitHub Discussions, there's a much better chance you will receive help by the [FastAPI Experts](fastapi-people.md#experts){.internal-link target=_blank}. +/// tip + +For questions, ask them in GitHub Discussions, there's a much better chance you will receive help by the [FastAPI Experts](fastapi-people.md#fastapi-experts){.internal-link target=_blank}. + +Use the chat only for other general conversations. - Use the chat only for other general conversations. +/// ### Don't use the chat for questions @@ -237,7 +243,7 @@ Keep in mind that as chats allow more "free conversation", it's easy to ask ques In GitHub, the template will guide you to write the right question so that you can more easily get a good answer, or even solve the problem yourself even before asking. And in GitHub I can make sure I always answer everything, even if it takes some time. I can't personally do that with the chat systems. 😅 -Conversations in the chat systems are also not as easily searchable as in GitHub, so questions and answers might get lost in the conversation. And only the ones in GitHub count to become a [FastAPI Expert](fastapi-people.md#experts){.internal-link target=_blank}, so you will most probably receive more attention in GitHub. +Conversations in the chat systems are also not as easily searchable as in GitHub, so questions and answers might get lost in the conversation. And only the ones in GitHub count to become a [FastAPI Expert](fastapi-people.md#fastapi-experts){.internal-link target=_blank}, so you will most probably receive more attention in GitHub. On the other side, there are thousands of users in the chat systems, so there's a high chance you'll find someone to talk to there, almost all the time. 😄 diff --git a/docs/en/docs/help/index.md b/docs/en/docs/help/index.md deleted file mode 100644 index 5ee7df2fe..000000000 --- a/docs/en/docs/help/index.md +++ /dev/null @@ -1,3 +0,0 @@ -# Help - -Help and get help, contribute, get involved. 🤝 diff --git a/docs/en/docs/history-design-future.md b/docs/en/docs/history-design-future.md index 9db1027c2..b4a744d64 100644 --- a/docs/en/docs/history-design-future.md +++ b/docs/en/docs/history-design-future.md @@ -1,6 +1,6 @@ # History, Design and Future -Some time ago, a **FastAPI** user asked: +Some time ago, a **FastAPI** user asked: > What’s the history of this project? It seems to have come from nowhere to awesome in a few weeks [...] @@ -54,7 +54,7 @@ All in a way that provided the best development experience for all the developer ## Requirements -After testing several alternatives, I decided that I was going to use **Pydantic** for its advantages. +After testing several alternatives, I decided that I was going to use **Pydantic** for its advantages. Then I contributed to it, to make it fully compliant with JSON Schema, to support different ways to define constraint declarations, and to improve editor support (type checks, autocompletion) based on the tests in several editors. diff --git a/docs/en/docs/how-to/async-sql-encode-databases.md b/docs/en/docs/how-to/async-sql-encode-databases.md deleted file mode 100644 index 0e2ccce78..000000000 --- a/docs/en/docs/how-to/async-sql-encode-databases.md +++ /dev/null @@ -1,174 +0,0 @@ -# Async SQL (Relational) Databases with Encode/Databases - -!!! info - These docs are about to be updated. 🎉 - - The current version assumes Pydantic v1. - - The new docs will include Pydantic v2 and will use SQLModel once it is updated to use Pydantic v2 as well. - -You can also use `encode/databases` with **FastAPI** to connect to databases using `async` and `await`. - -It is compatible with: - -* PostgreSQL -* MySQL -* SQLite - -In this example, we'll use **SQLite**, because it uses a single file and Python has integrated support. So, you can copy this example and run it as is. - -Later, for your production application, you might want to use a database server like **PostgreSQL**. - -!!! tip - You could adopt ideas from the section about SQLAlchemy ORM ([SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank}), like using utility functions to perform operations in the database, independent of your **FastAPI** code. - - This section doesn't apply those ideas, to be equivalent to the counterpart in Starlette. - -## Import and set up `SQLAlchemy` - -* Import `SQLAlchemy`. -* Create a `metadata` object. -* Create a table `notes` using the `metadata` object. - -```Python hl_lines="4 14 16-22" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -!!! tip - Notice that all this code is pure SQLAlchemy Core. - - `databases` is not doing anything here yet. - -## Import and set up `databases` - -* Import `databases`. -* Create a `DATABASE_URL`. -* Create a `database` object. - -```Python hl_lines="3 9 12" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -!!! tip - If you were connecting to a different database (e.g. PostgreSQL), you would need to change the `DATABASE_URL`. - -## Create the tables - -In this case, we are creating the tables in the same Python file, but in production, you would probably want to create them with Alembic, integrated with migrations, etc. - -Here, this section would run directly, right before starting your **FastAPI** application. - -* Create an `engine`. -* Create all the tables from the `metadata` object. - -```Python hl_lines="25-28" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -## Create models - -Create Pydantic models for: - -* Notes to be created (`NoteIn`). -* Notes to be returned (`Note`). - -```Python hl_lines="31-33 36-39" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -By creating these Pydantic models, the input data will be validated, serialized (converted), and annotated (documented). - -So, you will be able to see it all in the interactive API docs. - -## Connect and disconnect - -* Create your `FastAPI` application. -* Create event handlers to connect and disconnect from the database. - -```Python hl_lines="42 45-47 50-52" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -## Read notes - -Create the *path operation function* to read notes: - -```Python hl_lines="55-58" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -!!! Note - Notice that as we communicate with the database using `await`, the *path operation function* is declared with `async`. - -### Notice the `response_model=List[Note]` - -It uses `typing.List`. - -That documents (and validates, serializes, filters) the output data, as a `list` of `Note`s. - -## Create notes - -Create the *path operation function* to create notes: - -```Python hl_lines="61-65" -{!../../../docs_src/async_sql_databases/tutorial001.py!} -``` - -!!! info - In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. - - The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. - -!!! Note - Notice that as we communicate with the database using `await`, the *path operation function* is declared with `async`. - -### About `{**note.dict(), "id": last_record_id}` - -`note` is a Pydantic `Note` object. - -`note.dict()` returns a `dict` with its data, something like: - -```Python -{ - "text": "Some note", - "completed": False, -} -``` - -but it doesn't have the `id` field. - -So we create a new `dict`, that contains the key-value pairs from `note.dict()` with: - -```Python -{**note.dict()} -``` - -`**note.dict()` "unpacks" the key value pairs directly, so, `{**note.dict()}` would be, more or less, a copy of `note.dict()`. - -And then, we extend that copy `dict`, adding another key-value pair: `"id": last_record_id`: - -```Python -{**note.dict(), "id": last_record_id} -``` - -So, the final result returned would be something like: - -```Python -{ - "id": 1, - "text": "Some note", - "completed": False, -} -``` - -## Check it - -You can copy this code as is, and see the docs at http://127.0.0.1:8000/docs. - -There you can see all your API documented and interact with it: - - - -## More info - -You can read more about `encode/databases` at its GitHub page. diff --git a/docs/en/docs/how-to/conditional-openapi.md b/docs/en/docs/how-to/conditional-openapi.md index add16fbec..bd6cad9a8 100644 --- a/docs/en/docs/how-to/conditional-openapi.md +++ b/docs/en/docs/how-to/conditional-openapi.md @@ -29,9 +29,7 @@ You can easily use the same Pydantic settings to configure your generated OpenAP For example: -```Python hl_lines="6 11" -{!../../../docs_src/conditional_openapi/tutorial001.py!} -``` +{* ../../docs_src/conditional_openapi/tutorial001.py hl[6,11] *} Here we declare the setting `openapi_url` with the same default of `"/openapi.json"`. diff --git a/docs/en/docs/how-to/configure-swagger-ui.md b/docs/en/docs/how-to/configure-swagger-ui.md index f36ba5ba8..a8a8de48f 100644 --- a/docs/en/docs/how-to/configure-swagger-ui.md +++ b/docs/en/docs/how-to/configure-swagger-ui.md @@ -1,6 +1,6 @@ # Configure Swagger UI -You can configure some extra Swagger UI parameters. +You can configure some extra Swagger UI parameters. To configure them, pass the `swagger_ui_parameters` argument when creating the `FastAPI()` app object or to the `get_swagger_ui_html()` function. @@ -18,9 +18,7 @@ Without changing the settings, syntax highlighting is enabled by default: But you can disable it by setting `syntaxHighlight` to `False`: -```Python hl_lines="3" -{!../../../docs_src/configure_swagger_ui/tutorial001.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial001.py hl[3] *} ...and then Swagger UI won't show the syntax highlighting anymore: @@ -30,9 +28,7 @@ But you can disable it by setting `syntaxHighlight` to `False`: The same way you could set the syntax highlighting theme with the key `"syntaxHighlight.theme"` (notice that it has a dot in the middle): -```Python hl_lines="3" -{!../../../docs_src/configure_swagger_ui/tutorial002.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial002.py hl[3] *} That configuration would change the syntax highlighting color theme: @@ -44,21 +40,17 @@ FastAPI includes some default configuration parameters appropriate for most of t It includes these default configurations: -```Python -{!../../../fastapi/openapi/docs.py[ln:7-13]!} -``` +{* ../../fastapi/openapi/docs.py ln[8:23] hl[17:23] *} You can override any of them by setting a different value in the argument `swagger_ui_parameters`. For example, to disable `deepLinking` you could pass these settings to `swagger_ui_parameters`: -```Python hl_lines="3" -{!../../../docs_src/configure_swagger_ui/tutorial003.py!} -``` +{* ../../docs_src/configure_swagger_ui/tutorial003.py hl[3] *} ## Other Swagger UI Parameters -To see all the other possible configurations you can use, read the official docs for Swagger UI parameters. +To see all the other possible configurations you can use, read the official docs for Swagger UI parameters. ## JavaScript-only settings diff --git a/docs/en/docs/how-to/custom-docs-ui-assets.md b/docs/en/docs/how-to/custom-docs-ui-assets.md index 9726be2c7..f717c98fa 100644 --- a/docs/en/docs/how-to/custom-docs-ui-assets.md +++ b/docs/en/docs/how-to/custom-docs-ui-assets.md @@ -18,15 +18,13 @@ The first step is to disable the automatic docs, as by default, those use the de To disable them, set their URLs to `None` when creating your `FastAPI` app: -```Python hl_lines="8" -{!../../../docs_src/custom_docs_ui/tutorial001.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[8] *} ### Include the custom docs Now you can create the *path operations* for the custom docs. -You can re-use FastAPI's internal functions to create the HTML pages for the docs, and pass them the needed arguments: +You can reuse FastAPI's internal functions to create the HTML pages for the docs, and pass them the needed arguments: * `openapi_url`: the URL where the HTML page for the docs can get the OpenAPI schema for your API. You can use here the attribute `app.openapi_url`. * `title`: the title of your API. @@ -36,24 +34,23 @@ You can re-use FastAPI's internal functions to create the HTML pages for the doc And similarly for ReDoc... -```Python hl_lines="2-6 11-19 22-24 27-33" -{!../../../docs_src/custom_docs_ui/tutorial001.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[2:6,11:19,22:24,27:33] *} + +/// tip -!!! tip - The *path operation* for `swagger_ui_redirect` is a helper for when you use OAuth2. +The *path operation* for `swagger_ui_redirect` is a helper for when you use OAuth2. - If you integrate your API with an OAuth2 provider, you will be able to authenticate and come back to the API docs with the acquired credentials. And interact with it using the real OAuth2 authentication. +If you integrate your API with an OAuth2 provider, you will be able to authenticate and come back to the API docs with the acquired credentials. And interact with it using the real OAuth2 authentication. - Swagger UI will handle it behind the scenes for you, but it needs this "redirect" helper. +Swagger UI will handle it behind the scenes for you, but it needs this "redirect" helper. + +/// ### Create a *path operation* to test it Now, to be able to test that everything works, create a *path operation*: -```Python hl_lines="36-38" -{!../../../docs_src/custom_docs_ui/tutorial001.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[36:38] *} ### Test it @@ -96,8 +93,8 @@ You can probably right-click each link and select an option similar to `Save lin **Swagger UI** uses the files: -* `swagger-ui-bundle.js` -* `swagger-ui.css` +* `swagger-ui-bundle.js` +* `swagger-ui.css` And **ReDoc** uses the file: @@ -121,9 +118,7 @@ After that, your file structure could look like: * Import `StaticFiles`. * "Mount" a `StaticFiles()` instance in a specific path. -```Python hl_lines="7 11" -{!../../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[7,11] *} ### Test the static files @@ -155,15 +150,13 @@ The same as when using a custom CDN, the first step is to disable the automatic To disable them, set their URLs to `None` when creating your `FastAPI` app: -```Python hl_lines="9" -{!../../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[9] *} ### Include the custom docs for static files And the same way as with a custom CDN, now you can create the *path operations* for the custom docs. -Again, you can re-use FastAPI's internal functions to create the HTML pages for the docs, and pass them the needed arguments: +Again, you can reuse FastAPI's internal functions to create the HTML pages for the docs, and pass them the needed arguments: * `openapi_url`: the URL where the HTML page for the docs can get the OpenAPI schema for your API. You can use here the attribute `app.openapi_url`. * `title`: the title of your API. @@ -173,24 +166,23 @@ Again, you can re-use FastAPI's internal functions to create the HTML pages for And similarly for ReDoc... -```Python hl_lines="2-6 14-22 25-27 30-36" -{!../../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[2:6,14:22,25:27,30:36] *} + +/// tip -!!! tip - The *path operation* for `swagger_ui_redirect` is a helper for when you use OAuth2. +The *path operation* for `swagger_ui_redirect` is a helper for when you use OAuth2. - If you integrate your API with an OAuth2 provider, you will be able to authenticate and come back to the API docs with the acquired credentials. And interact with it using the real OAuth2 authentication. +If you integrate your API with an OAuth2 provider, you will be able to authenticate and come back to the API docs with the acquired credentials. And interact with it using the real OAuth2 authentication. - Swagger UI will handle it behind the scenes for you, but it needs this "redirect" helper. +Swagger UI will handle it behind the scenes for you, but it needs this "redirect" helper. + +/// ### Create a *path operation* to test static files Now, to be able to test that everything works, create a *path operation*: -```Python hl_lines="39-41" -{!../../../docs_src/custom_docs_ui/tutorial002.py!} -``` +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[39:41] *} ### Test Static Files UI diff --git a/docs/en/docs/how-to/custom-request-and-route.md b/docs/en/docs/how-to/custom-request-and-route.md index bca0c7603..9b4160d75 100644 --- a/docs/en/docs/how-to/custom-request-and-route.md +++ b/docs/en/docs/how-to/custom-request-and-route.md @@ -6,10 +6,13 @@ In particular, this may be a good alternative to logic in a middleware. For example, if you want to read or manipulate the request body before it is processed by your application. -!!! danger - This is an "advanced" feature. +/// danger - If you are just starting with **FastAPI** you might want to skip this section. +This is an "advanced" feature. + +If you are just starting with **FastAPI** you might want to skip this section. + +/// ## Use cases @@ -27,8 +30,11 @@ And an `APIRoute` subclass to use that custom request class. ### Create a custom `GzipRequest` class -!!! tip - This is a toy example to demonstrate how it works, if you need Gzip support, you can use the provided [`GzipMiddleware`](./middleware.md#gzipmiddleware){.internal-link target=_blank}. +/// tip + +This is a toy example to demonstrate how it works, if you need Gzip support, you can use the provided [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank}. + +/// First, we create a `GzipRequest` class, which will overwrite the `Request.body()` method to decompress the body in the presence of an appropriate header. @@ -36,9 +42,7 @@ If there's no `gzip` in the header, it will not try to decompress the body. That way, the same route class can handle gzip compressed or uncompressed requests. -```Python hl_lines="8-15" -{!../../../docs_src/custom_request_and_route/tutorial001.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial001.py hl[8:15] *} ### Create a custom `GzipRoute` class @@ -50,20 +54,21 @@ This method returns a function. And that function is what will receive a request Here we use it to create a `GzipRequest` from the original request. -```Python hl_lines="18-26" -{!../../../docs_src/custom_request_and_route/tutorial001.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial001.py hl[18:26] *} -!!! note "Technical Details" - A `Request` has a `request.scope` attribute, that's just a Python `dict` containing the metadata related to the request. +/// note | Technical Details - A `Request` also has a `request.receive`, that's a function to "receive" the body of the request. +A `Request` has a `request.scope` attribute, that's just a Python `dict` containing the metadata related to the request. - The `scope` `dict` and `receive` function are both part of the ASGI specification. +A `Request` also has a `request.receive`, that's a function to "receive" the body of the request. - And those two things, `scope` and `receive`, are what is needed to create a new `Request` instance. +The `scope` `dict` and `receive` function are both part of the ASGI specification. - To learn more about the `Request` check Starlette's docs about Requests. +And those two things, `scope` and `receive`, are what is needed to create a new `Request` instance. + +To learn more about the `Request` check Starlette's docs about Requests. + +/// The only thing the function returned by `GzipRequest.get_route_handler` does differently is convert the `Request` to a `GzipRequest`. @@ -75,35 +80,30 @@ But because of our changes in `GzipRequest.body`, the request body will be autom ## Accessing the request body in an exception handler -!!! tip - To solve this same problem, it's probably a lot easier to use the `body` in a custom handler for `RequestValidationError` ([Handling Errors](../tutorial/handling-errors.md#use-the-requestvalidationerror-body){.internal-link target=_blank}). +/// tip + +To solve this same problem, it's probably a lot easier to use the `body` in a custom handler for `RequestValidationError` ([Handling Errors](../tutorial/handling-errors.md#use-the-requestvalidationerror-body){.internal-link target=_blank}). + +But this example is still valid and it shows how to interact with the internal components. - But this example is still valid and it shows how to interact with the internal components. +/// We can also use this same approach to access the request body in an exception handler. All we need to do is handle the request inside a `try`/`except` block: -```Python hl_lines="13 15" -{!../../../docs_src/custom_request_and_route/tutorial002.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial002.py hl[13,15] *} If an exception occurs, the`Request` instance will still be in scope, so we can read and make use of the request body when handling the error: -```Python hl_lines="16-18" -{!../../../docs_src/custom_request_and_route/tutorial002.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial002.py hl[16:18] *} ## Custom `APIRoute` class in a router You can also set the `route_class` parameter of an `APIRouter`: -```Python hl_lines="26" -{!../../../docs_src/custom_request_and_route/tutorial003.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial003.py hl[26] *} In this example, the *path operations* under the `router` will use the custom `TimedRoute` class, and will have an extra `X-Response-Time` header in the response with the time it took to generate the response: -```Python hl_lines="13-20" -{!../../../docs_src/custom_request_and_route/tutorial003.py!} -``` +{* ../../docs_src/custom_request_and_route/tutorial003.py hl[13:20] *} diff --git a/docs/en/docs/how-to/extending-openapi.md b/docs/en/docs/how-to/extending-openapi.md index a18fd737e..26c742c20 100644 --- a/docs/en/docs/how-to/extending-openapi.md +++ b/docs/en/docs/how-to/extending-openapi.md @@ -27,8 +27,11 @@ And that function `get_openapi()` receives as parameters: * `description`: The description of your API, this can include markdown and will be shown in the docs. * `routes`: A list of routes, these are each of the registered *path operations*. They are taken from `app.routes`. -!!! info - The parameter `summary` is available in OpenAPI 3.1.0 and above, supported by FastAPI 0.99.0 and above. +/// info + +The parameter `summary` is available in OpenAPI 3.1.0 and above, supported by FastAPI 0.99.0 and above. + +/// ## Overriding the defaults @@ -40,25 +43,19 @@ For example, let's add Strawberry 🍓 * With docs for FastAPI * Ariadne - * With docs for Starlette (that also apply to FastAPI) + * With docs for FastAPI * Tartiflette * With Tartiflette ASGI to provide ASGI integration * Graphene @@ -32,9 +35,7 @@ Depending on your use case, you might prefer to use a different library, but if Here's a small preview of how you could integrate Strawberry with FastAPI: -```Python hl_lines="3 22 25-26" -{!../../../docs_src/graphql/tutorial001.py!} -``` +{* ../../docs_src/graphql/tutorial001.py hl[3,22,25] *} You can learn more about Strawberry in the Strawberry documentation. @@ -46,8 +47,11 @@ Previous versions of Starlette included a `GraphQLApp` class to integrate with < It was deprecated from Starlette, but if you have code that used it, you can easily **migrate** to starlette-graphene3, that covers the same use case and has an **almost identical interface**. -!!! tip - If you need GraphQL, I still would recommend you check out Strawberry, as it's based on type annotations instead of custom classes and types. +/// tip + +If you need GraphQL, I still would recommend you check out Strawberry, as it's based on type annotations instead of custom classes and types. + +/// ## Learn More diff --git a/docs/en/docs/how-to/index.md b/docs/en/docs/how-to/index.md index ec7fd38f8..730dce5d5 100644 --- a/docs/en/docs/how-to/index.md +++ b/docs/en/docs/how-to/index.md @@ -6,6 +6,8 @@ Most of these ideas would be more or less **independent**, and in most cases you If something seems interesting and useful to your project, go ahead and check it, but otherwise, you might probably just skip them. -!!! tip +/// tip - If you want to **learn FastAPI** in a structured way (recommended), go and read the [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} chapter by chapter instead. +If you want to **learn FastAPI** in a structured way (recommended), go and read the [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} chapter by chapter instead. + +/// diff --git a/docs/en/docs/how-to/nosql-databases-couchbase.md b/docs/en/docs/how-to/nosql-databases-couchbase.md deleted file mode 100644 index ae6ad604b..000000000 --- a/docs/en/docs/how-to/nosql-databases-couchbase.md +++ /dev/null @@ -1,163 +0,0 @@ -# NoSQL (Distributed / Big Data) Databases with Couchbase - -!!! info - These docs are about to be updated. 🎉 - - The current version assumes Pydantic v1. - - The new docs will hopefully use Pydantic v2 and will use ODMantic with MongoDB. - -**FastAPI** can also be integrated with any NoSQL. - -Here we'll see an example using **Couchbase**, a document based NoSQL database. - -You can adapt it to any other NoSQL database like: - -* **MongoDB** -* **Cassandra** -* **CouchDB** -* **ArangoDB** -* **ElasticSearch**, etc. - -!!! tip - There is an official project generator with **FastAPI** and **Couchbase**, all based on **Docker**, including a frontend and more tools: https://github.com/tiangolo/full-stack-fastapi-couchbase - -## Import Couchbase components - -For now, don't pay attention to the rest, only the imports: - -```Python hl_lines="3-5" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -## Define a constant to use as a "document type" - -We will use it later as a fixed field `type` in our documents. - -This is not required by Couchbase, but is a good practice that will help you afterwards. - -```Python hl_lines="9" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -## Add a function to get a `Bucket` - -In **Couchbase**, a bucket is a set of documents, that can be of different types. - -They are generally all related to the same application. - -The analogy in the relational database world would be a "database" (a specific database, not the database server). - -The analogy in **MongoDB** would be a "collection". - -In the code, a `Bucket` represents the main entrypoint of communication with the database. - -This utility function will: - -* Connect to a **Couchbase** cluster (that might be a single machine). - * Set defaults for timeouts. -* Authenticate in the cluster. -* Get a `Bucket` instance. - * Set defaults for timeouts. -* Return it. - -```Python hl_lines="12-21" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -## Create Pydantic models - -As **Couchbase** "documents" are actually just "JSON objects", we can model them with Pydantic. - -### `User` model - -First, let's create a `User` model: - -```Python hl_lines="24-28" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -We will use this model in our *path operation function*, so, we don't include in it the `hashed_password`. - -### `UserInDB` model - -Now, let's create a `UserInDB` model. - -This will have the data that is actually stored in the database. - -We don't create it as a subclass of Pydantic's `BaseModel` but as a subclass of our own `User`, because it will have all the attributes in `User` plus a couple more: - -```Python hl_lines="31-33" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -!!! note - Notice that we have a `hashed_password` and a `type` field that will be stored in the database. - - But it is not part of the general `User` model (the one we will return in the *path operation*). - -## Get the user - -Now create a function that will: - -* Take a username. -* Generate a document ID from it. -* Get the document with that ID. -* Put the contents of the document in a `UserInDB` model. - -By creating a function that is only dedicated to getting your user from a `username` (or any other parameter) independent of your *path operation function*, you can more easily re-use it in multiple parts and also add unit tests for it: - -```Python hl_lines="36-42" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -### f-strings - -If you are not familiar with the `f"userprofile::{username}"`, it is a Python "f-string". - -Any variable that is put inside of `{}` in an f-string will be expanded / injected in the string. - -### `dict` unpacking - -If you are not familiar with the `UserInDB(**result.value)`, it is using `dict` "unpacking". - -It will take the `dict` at `result.value`, and take each of its keys and values and pass them as key-values to `UserInDB` as keyword arguments. - -So, if the `dict` contains: - -```Python -{ - "username": "johndoe", - "hashed_password": "some_hash", -} -``` - -It will be passed to `UserInDB` as: - -```Python -UserInDB(username="johndoe", hashed_password="some_hash") -``` - -## Create your **FastAPI** code - -### Create the `FastAPI` app - -```Python hl_lines="46" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -### Create the *path operation function* - -As our code is calling Couchbase and we are not using the experimental Python await support, we should declare our function with normal `def` instead of `async def`. - -Also, Couchbase recommends not using a single `Bucket` object in multiple "threads", so, we can just get the bucket directly and pass it to our utility functions: - -```Python hl_lines="49-53" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -## Recap - -You can integrate any third party NoSQL database, just using their standard packages. - -The same applies to any other external tool, system or API. diff --git a/docs/en/docs/how-to/separate-openapi-schemas.md b/docs/en/docs/how-to/separate-openapi-schemas.md index 10be1071a..9a27638fe 100644 --- a/docs/en/docs/how-to/separate-openapi-schemas.md +++ b/docs/en/docs/how-to/separate-openapi-schemas.md @@ -10,111 +10,13 @@ Let's see how that works and how to change it if you need to do that. Let's say you have a Pydantic model with default values, like this one: -=== "Python 3.10+" - - ```Python hl_lines="7" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-7]!} - - # Code below omitted 👇 - ``` - -
- 👀 Full file preview - - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} - ``` - -
- -=== "Python 3.9+" - - ```Python hl_lines="9" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-9]!} - - # Code below omitted 👇 - ``` - -
- 👀 Full file preview - - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} - ``` - -
- -=== "Python 3.8+" - - ```Python hl_lines="9" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-9]!} - - # Code below omitted 👇 - ``` - -
- 👀 Full file preview - - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} - ``` - -
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:7] hl[7] *} ### Model for Input If you use this model as an input like here: -=== "Python 3.10+" - - ```Python hl_lines="14" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py[ln:1-15]!} - - # Code below omitted 👇 - ``` - -
- 👀 Full file preview - - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} - ``` - -
- -=== "Python 3.9+" - - ```Python hl_lines="16" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py[ln:1-17]!} - - # Code below omitted 👇 - ``` - -
- 👀 Full file preview - - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} - ``` - -
- -=== "Python 3.8+" - - ```Python hl_lines="16" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py[ln:1-17]!} - - # Code below omitted 👇 - ``` - -
- 👀 Full file preview - - ```Python - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} - ``` - -
+{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:15] hl[14] *} ...then the `description` field will **not be required**. Because it has a default value of `None`. @@ -130,23 +32,7 @@ You can confirm that in the docs, the `description` field doesn't have a **red a But if you use the same model as an output, like here: -=== "Python 3.10+" - - ```Python hl_lines="19" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="21" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="21" - {!> ../../../docs_src/separate_openapi_schemas/tutorial001.py!} - ``` +{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py hl[19] *} ...then because `description` has a default value, if you **don't return anything** for that field, it will still have that **default value**. @@ -199,26 +85,13 @@ Probably the main use case for this is if you already have some autogenerated cl In that case, you can disable this feature in **FastAPI**, with the parameter `separate_input_output_schemas=False`. -!!! info - Support for `separate_input_output_schemas` was added in FastAPI `0.102.0`. 🤓 - -=== "Python 3.10+" - - ```Python hl_lines="10" - {!> ../../../docs_src/separate_openapi_schemas/tutorial002_py310.py!} - ``` - -=== "Python 3.9+" +/// info - ```Python hl_lines="12" - {!> ../../../docs_src/separate_openapi_schemas/tutorial002_py39.py!} - ``` +Support for `separate_input_output_schemas` was added in FastAPI `0.102.0`. 🤓 -=== "Python 3.8+" +/// - ```Python hl_lines="12" - {!> ../../../docs_src/separate_openapi_schemas/tutorial002.py!} - ``` +{* ../../docs_src/separate_openapi_schemas/tutorial002_py310.py hl[10] *} ### Same Schema for Input and Output Models in Docs diff --git a/docs/en/docs/how-to/sql-databases-peewee.md b/docs/en/docs/how-to/sql-databases-peewee.md deleted file mode 100644 index 74a28b170..000000000 --- a/docs/en/docs/how-to/sql-databases-peewee.md +++ /dev/null @@ -1,538 +0,0 @@ -# SQL (Relational) Databases with Peewee - -!!! warning - If you are just starting, the tutorial [SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank} that uses SQLAlchemy should be enough. - - Feel free to skip this. - - Peewee is not recommended with FastAPI as it doesn't play well with anything async Python. There are several better alternatives. - -!!! info - These docs assume Pydantic v1. - - Because Pewee doesn't play well with anything async and there are better alternatives, I won't update these docs for Pydantic v2, they are kept for now only for historical purposes. - - The examples here are no longer tested in CI (as they were before). - -If you are starting a project from scratch, you are probably better off with SQLAlchemy ORM ([SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank}), or any other async ORM. - -If you already have a code base that uses Peewee ORM, you can check here how to use it with **FastAPI**. - -!!! warning "Python 3.7+ required" - You will need Python 3.7 or above to safely use Peewee with FastAPI. - -## Peewee for async - -Peewee was not designed for async frameworks, or with them in mind. - -Peewee has some heavy assumptions about its defaults and about how it should be used. - -If you are developing an application with an older non-async framework, and can work with all its defaults, **it can be a great tool**. - -But if you need to change some of the defaults, support more than one predefined database, work with an async framework (like FastAPI), etc, you will need to add quite some complex extra code to override those defaults. - -Nevertheless, it's possible to do it, and here you'll see exactly what code you have to add to be able to use Peewee with FastAPI. - -!!! note "Technical Details" - You can read more about Peewee's stand about async in Python in the docs, an issue, a PR. - -## The same app - -We are going to create the same application as in the SQLAlchemy tutorial ([SQL (Relational) Databases](../tutorial/sql-databases.md){.internal-link target=_blank}). - -Most of the code is actually the same. - -So, we are going to focus only on the differences. - -## File structure - -Let's say you have a directory named `my_super_project` that contains a sub-directory called `sql_app` with a structure like this: - -``` -. -└── sql_app - ├── __init__.py - ├── crud.py - ├── database.py - ├── main.py - └── schemas.py -``` - -This is almost the same structure as we had for the SQLAlchemy tutorial. - -Now let's see what each file/module does. - -## Create the Peewee parts - -Let's refer to the file `sql_app/database.py`. - -### The standard Peewee code - -Let's first check all the normal Peewee code, create a Peewee database: - -```Python hl_lines="3 5 22" -{!../../../docs_src/sql_databases_peewee/sql_app/database.py!} -``` - -!!! tip - Keep in mind that if you wanted to use a different database, like PostgreSQL, you couldn't just change the string. You would need to use a different Peewee database class. - -#### Note - -The argument: - -```Python -check_same_thread=False -``` - -is equivalent to the one in the SQLAlchemy tutorial: - -```Python -connect_args={"check_same_thread": False} -``` - -...it is needed only for `SQLite`. - -!!! info "Technical Details" - - Exactly the same technical details as in [SQL (Relational) Databases](../tutorial/sql-databases.md#note){.internal-link target=_blank} apply. - -### Make Peewee async-compatible `PeeweeConnectionState` - -The main issue with Peewee and FastAPI is that Peewee relies heavily on Python's `threading.local`, and it doesn't have a direct way to override it or let you handle connections/sessions directly (as is done in the SQLAlchemy tutorial). - -And `threading.local` is not compatible with the new async features of modern Python. - -!!! note "Technical Details" - `threading.local` is used to have a "magic" variable that has a different value for each thread. - - This was useful in older frameworks designed to have one single thread per request, no more, no less. - - Using this, each request would have its own database connection/session, which is the actual final goal. - - But FastAPI, using the new async features, could handle more than one request on the same thread. And at the same time, for a single request, it could run multiple things in different threads (in a threadpool), depending on if you use `async def` or normal `def`. This is what gives all the performance improvements to FastAPI. - -But Python 3.7 and above provide a more advanced alternative to `threading.local`, that can also be used in the places where `threading.local` would be used, but is compatible with the new async features. - -We are going to use that. It's called `contextvars`. - -We are going to override the internal parts of Peewee that use `threading.local` and replace them with `contextvars`, with the corresponding updates. - -This might seem a bit complex (and it actually is), you don't really need to completely understand how it works to use it. - -We will create a `PeeweeConnectionState`: - -```Python hl_lines="10-19" -{!../../../docs_src/sql_databases_peewee/sql_app/database.py!} -``` - -This class inherits from a special internal class used by Peewee. - -It has all the logic to make Peewee use `contextvars` instead of `threading.local`. - -`contextvars` works a bit differently than `threading.local`. But the rest of Peewee's internal code assumes that this class works with `threading.local`. - -So, we need to do some extra tricks to make it work as if it was just using `threading.local`. The `__init__`, `__setattr__`, and `__getattr__` implement all the required tricks for this to be used by Peewee without knowing that it is now compatible with FastAPI. - -!!! tip - This will just make Peewee behave correctly when used with FastAPI. Not randomly opening or closing connections that are being used, creating errors, etc. - - But it doesn't give Peewee async super-powers. You should still use normal `def` functions and not `async def`. - -### Use the custom `PeeweeConnectionState` class - -Now, overwrite the `._state` internal attribute in the Peewee database `db` object using the new `PeeweeConnectionState`: - -```Python hl_lines="24" -{!../../../docs_src/sql_databases_peewee/sql_app/database.py!} -``` - -!!! tip - Make sure you overwrite `db._state` *after* creating `db`. - -!!! tip - You would do the same for any other Peewee database, including `PostgresqlDatabase`, `MySQLDatabase`, etc. - -## Create the database models - -Let's now see the file `sql_app/models.py`. - -### Create Peewee models for our data - -Now create the Peewee models (classes) for `User` and `Item`. - -This is the same you would do if you followed the Peewee tutorial and updated the models to have the same data as in the SQLAlchemy tutorial. - -!!! tip - Peewee also uses the term "**model**" to refer to these classes and instances that interact with the database. - - But Pydantic also uses the term "**model**" to refer to something different, the data validation, conversion, and documentation classes and instances. - -Import `db` from `database` (the file `database.py` from above) and use it here. - -```Python hl_lines="3 6-12 15-21" -{!../../../docs_src/sql_databases_peewee/sql_app/models.py!} -``` - -!!! tip - Peewee creates several magic attributes. - - It will automatically add an `id` attribute as an integer to be the primary key. - - It will chose the name of the tables based on the class names. - - For the `Item`, it will create an attribute `owner_id` with the integer ID of the `User`. But we don't declare it anywhere. - -## Create the Pydantic models - -Now let's check the file `sql_app/schemas.py`. - -!!! tip - To avoid confusion between the Peewee *models* and the Pydantic *models*, we will have the file `models.py` with the Peewee models, and the file `schemas.py` with the Pydantic models. - - These Pydantic models define more or less a "schema" (a valid data shape). - - So this will help us avoiding confusion while using both. - -### Create the Pydantic *models* / schemas - -Create all the same Pydantic models as in the SQLAlchemy tutorial: - -```Python hl_lines="16-18 21-22 25-30 34-35 38-39 42-48" -{!../../../docs_src/sql_databases_peewee/sql_app/schemas.py!} -``` - -!!! tip - Here we are creating the models with an `id`. - - We didn't explicitly specify an `id` attribute in the Peewee models, but Peewee adds one automatically. - - We are also adding the magic `owner_id` attribute to `Item`. - -### Create a `PeeweeGetterDict` for the Pydantic *models* / schemas - -When you access a relationship in a Peewee object, like in `some_user.items`, Peewee doesn't provide a `list` of `Item`. - -It provides a special custom object of class `ModelSelect`. - -It's possible to create a `list` of its items with `list(some_user.items)`. - -But the object itself is not a `list`. And it's also not an actual Python generator. Because of this, Pydantic doesn't know by default how to convert it to a `list` of Pydantic *models* / schemas. - -But recent versions of Pydantic allow providing a custom class that inherits from `pydantic.utils.GetterDict`, to provide the functionality used when using the `orm_mode = True` to retrieve the values for ORM model attributes. - -We are going to create a custom `PeeweeGetterDict` class and use it in all the same Pydantic *models* / schemas that use `orm_mode`: - -```Python hl_lines="3 8-13 31 49" -{!../../../docs_src/sql_databases_peewee/sql_app/schemas.py!} -``` - -Here we are checking if the attribute that is being accessed (e.g. `.items` in `some_user.items`) is an instance of `peewee.ModelSelect`. - -And if that's the case, just return a `list` with it. - -And then we use it in the Pydantic *models* / schemas that use `orm_mode = True`, with the configuration variable `getter_dict = PeeweeGetterDict`. - -!!! tip - We only need to create one `PeeweeGetterDict` class, and we can use it in all the Pydantic *models* / schemas. - -## CRUD utils - -Now let's see the file `sql_app/crud.py`. - -### Create all the CRUD utils - -Create all the same CRUD utils as in the SQLAlchemy tutorial, all the code is very similar: - -```Python hl_lines="1 4-5 8-9 12-13 16-20 23-24 27-30" -{!../../../docs_src/sql_databases_peewee/sql_app/crud.py!} -``` - -There are some differences with the code for the SQLAlchemy tutorial. - -We don't pass a `db` attribute around. Instead we use the models directly. This is because the `db` object is a global object, that includes all the connection logic. That's why we had to do all the `contextvars` updates above. - -Aso, when returning several objects, like in `get_users`, we directly call `list`, like in: - -```Python -list(models.User.select()) -``` - -This is for the same reason that we had to create a custom `PeeweeGetterDict`. But by returning something that is already a `list` instead of the `peewee.ModelSelect` the `response_model` in the *path operation* with `List[models.User]` (that we'll see later) will work correctly. - -## Main **FastAPI** app - -And now in the file `sql_app/main.py` let's integrate and use all the other parts we created before. - -### Create the database tables - -In a very simplistic way create the database tables: - -```Python hl_lines="9-11" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -### Create a dependency - -Create a dependency that will connect the database right at the beginning of a request and disconnect it at the end: - -```Python hl_lines="23-29" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -Here we have an empty `yield` because we are actually not using the database object directly. - -It is connecting to the database and storing the connection data in an internal variable that is independent for each request (using the `contextvars` tricks from above). - -Because the database connection is potentially I/O blocking, this dependency is created with a normal `def` function. - -And then, in each *path operation function* that needs to access the database we add it as a dependency. - -But we are not using the value given by this dependency (it actually doesn't give any value, as it has an empty `yield`). So, we don't add it to the *path operation function* but to the *path operation decorator* in the `dependencies` parameter: - -```Python hl_lines="32 40 47 59 65 72" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -### Context variable sub-dependency - -For all the `contextvars` parts to work, we need to make sure we have an independent value in the `ContextVar` for each request that uses the database, and that value will be used as the database state (connection, transactions, etc) for the whole request. - -For that, we need to create another `async` dependency `reset_db_state()` that is used as a sub-dependency in `get_db()`. It will set the value for the context variable (with just a default `dict`) that will be used as the database state for the whole request. And then the dependency `get_db()` will store in it the database state (connection, transactions, etc). - -```Python hl_lines="18-20" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -For the **next request**, as we will reset that context variable again in the `async` dependency `reset_db_state()` and then create a new connection in the `get_db()` dependency, that new request will have its own database state (connection, transactions, etc). - -!!! tip - As FastAPI is an async framework, one request could start being processed, and before finishing, another request could be received and start processing as well, and it all could be processed in the same thread. - - But context variables are aware of these async features, so, a Peewee database state set in the `async` dependency `reset_db_state()` will keep its own data throughout the entire request. - - And at the same time, the other concurrent request will have its own database state that will be independent for the whole request. - -#### Peewee Proxy - -If you are using a Peewee Proxy, the actual database is at `db.obj`. - -So, you would reset it with: - -```Python hl_lines="3-4" -async def reset_db_state(): - database.db.obj._state._state.set(db_state_default.copy()) - database.db.obj._state.reset() -``` - -### Create your **FastAPI** *path operations* - -Now, finally, here's the standard **FastAPI** *path operations* code. - -```Python hl_lines="32-37 40-43 46-53 56-62 65-68 71-79" -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -### About `def` vs `async def` - -The same as with SQLAlchemy, we are not doing something like: - -```Python -user = await models.User.select().first() -``` - -...but instead we are using: - -```Python -user = models.User.select().first() -``` - -So, again, we should declare the *path operation functions* and the dependency without `async def`, just with a normal `def`, as: - -```Python hl_lines="2" -# Something goes here -def read_users(skip: int = 0, limit: int = 100): - # Something goes here -``` - -## Testing Peewee with async - -This example includes an extra *path operation* that simulates a long processing request with `time.sleep(sleep_time)`. - -It will have the database connection open at the beginning and will just wait some seconds before replying back. And each new request will wait one second less. - -This will easily let you test that your app with Peewee and FastAPI is behaving correctly with all the stuff about threads. - -If you want to check how Peewee would break your app if used without modification, go the `sql_app/database.py` file and comment the line: - -```Python -# db._state = PeeweeConnectionState() -``` - -And in the file `sql_app/main.py` file, comment the body of the `async` dependency `reset_db_state()` and replace it with a `pass`: - -```Python -async def reset_db_state(): -# database.db._state._state.set(db_state_default.copy()) -# database.db._state.reset() - pass -``` - -Then run your app with Uvicorn: - -
- -```console -$ uvicorn sql_app.main:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -Open your browser at http://127.0.0.1:8000/docs and create a couple of users. - -Then open 10 tabs at http://127.0.0.1:8000/docs#/default/read_slow_users_slowusers__get at the same time. - -Go to the *path operation* "Get `/slowusers/`" in all of the tabs. Use the "Try it out" button and execute the request in each tab, one right after the other. - -The tabs will wait for a bit and then some of them will show `Internal Server Error`. - -### What happens - -The first tab will make your app create a connection to the database and wait for some seconds before replying back and closing the database connection. - -Then, for the request in the next tab, your app will wait for one second less, and so on. - -This means that it will end up finishing some of the last tabs' requests earlier than some of the previous ones. - -Then one the last requests that wait less seconds will try to open a database connection, but as one of those previous requests for the other tabs will probably be handled in the same thread as the first one, it will have the same database connection that is already open, and Peewee will throw an error and you will see it in the terminal, and the response will have an `Internal Server Error`. - -This will probably happen for more than one of those tabs. - -If you had multiple clients talking to your app exactly at the same time, this is what could happen. - -And as your app starts to handle more and more clients at the same time, the waiting time in a single request needs to be shorter and shorter to trigger the error. - -### Fix Peewee with FastAPI - -Now go back to the file `sql_app/database.py`, and uncomment the line: - -```Python -db._state = PeeweeConnectionState() -``` - -And in the file `sql_app/main.py` file, uncomment the body of the `async` dependency `reset_db_state()`: - -```Python -async def reset_db_state(): - database.db._state._state.set(db_state_default.copy()) - database.db._state.reset() -``` - -Terminate your running app and start it again. - -Repeat the same process with the 10 tabs. This time all of them will wait and you will get all the results without errors. - -...You fixed it! - -## Review all the files - - Remember you should have a directory named `my_super_project` (or however you want) that contains a sub-directory called `sql_app`. - -`sql_app` should have the following files: - -* `sql_app/__init__.py`: is an empty file. - -* `sql_app/database.py`: - -```Python -{!../../../docs_src/sql_databases_peewee/sql_app/database.py!} -``` - -* `sql_app/models.py`: - -```Python -{!../../../docs_src/sql_databases_peewee/sql_app/models.py!} -``` - -* `sql_app/schemas.py`: - -```Python -{!../../../docs_src/sql_databases_peewee/sql_app/schemas.py!} -``` - -* `sql_app/crud.py`: - -```Python -{!../../../docs_src/sql_databases_peewee/sql_app/crud.py!} -``` - -* `sql_app/main.py`: - -```Python -{!../../../docs_src/sql_databases_peewee/sql_app/main.py!} -``` - -## Technical Details - -!!! warning - These are very technical details that you probably don't need. - -### The problem - -Peewee uses `threading.local` by default to store it's database "state" data (connection, transactions, etc). - -`threading.local` creates a value exclusive to the current thread, but an async framework would run all the code (e.g. for each request) in the same thread, and possibly not in order. - -On top of that, an async framework could run some sync code in a threadpool (using `asyncio.run_in_executor`), but belonging to the same request. - -This means that, with Peewee's current implementation, multiple tasks could be using the same `threading.local` variable and end up sharing the same connection and data (that they shouldn't), and at the same time, if they execute sync I/O-blocking code in a threadpool (as with normal `def` functions in FastAPI, in *path operations* and dependencies), that code won't have access to the database state variables, even while it's part of the same request and it should be able to get access to the same database state. - -### Context variables - -Python 3.7 has `contextvars` that can create a local variable very similar to `threading.local`, but also supporting these async features. - -There are several things to keep in mind. - -The `ContextVar` has to be created at the top of the module, like: - -```Python -some_var = ContextVar("some_var", default="default value") -``` - -To set a value used in the current "context" (e.g. for the current request) use: - -```Python -some_var.set("new value") -``` - -To get a value anywhere inside of the context (e.g. in any part handling the current request) use: - -```Python -some_var.get() -``` - -### Set context variables in the `async` dependency `reset_db_state()` - -If some part of the async code sets the value with `some_var.set("updated in function")` (e.g. like the `async` dependency), the rest of the code in it and the code that goes after (including code inside of `async` functions called with `await`) will see that new value. - -So, in our case, if we set the Peewee state variable (with a default `dict`) in the `async` dependency, all the rest of the internal code in our app will see this value and will be able to reuse it for the whole request. - -And the context variable would be set again for the next request, even if they are concurrent. - -### Set database state in the dependency `get_db()` - -As `get_db()` is a normal `def` function, **FastAPI** will make it run in a threadpool, with a *copy* of the "context", holding the same value for the context variable (the `dict` with the reset database state). Then it can add database state to that `dict`, like the connection, etc. - -But if the value of the context variable (the default `dict`) was set in that normal `def` function, it would create a new value that would stay only in that thread of the threadpool, and the rest of the code (like the *path operation functions*) wouldn't have access to it. In `get_db()` we can only set values in the `dict`, but not the entire `dict` itself. - -So, we need to have the `async` dependency `reset_db_state()` to set the `dict` in the context variable. That way, all the code has access to the same `dict` for the database state for a single request. - -### Connect and disconnect in the dependency `get_db()` - -Then the next question would be, why not just connect and disconnect the database in the `async` dependency itself, instead of in `get_db()`? - -The `async` dependency has to be `async` for the context variable to be preserved for the rest of the request, but creating and closing the database connection is potentially blocking, so it could degrade performance if it was there. - -So we also need the normal `def` dependency `get_db()`. diff --git a/docs/en/docs/how-to/testing-database.md b/docs/en/docs/how-to/testing-database.md new file mode 100644 index 000000000..d0ed15bca --- /dev/null +++ b/docs/en/docs/how-to/testing-database.md @@ -0,0 +1,7 @@ +# Testing a Database + +You can study about databases, SQL, and SQLModel in the SQLModel docs. 🤓 + +There's a mini tutorial on using SQLModel with FastAPI. ✨ + +That tutorial includes a section about testing SQL databases. 😎 diff --git a/docs/en/docs/img/favicon.png b/docs/en/docs/img/favicon.png old mode 100755 new mode 100644 index b3dcdd309..e5b7c3ada Binary files a/docs/en/docs/img/favicon.png and b/docs/en/docs/img/favicon.png differ diff --git a/docs/en/docs/img/github-social-preview.png b/docs/en/docs/img/github-social-preview.png index a12cbcda5..4c299c1d6 100644 Binary files a/docs/en/docs/img/github-social-preview.png and b/docs/en/docs/img/github-social-preview.png differ diff --git a/docs/en/docs/img/github-social-preview.svg b/docs/en/docs/img/github-social-preview.svg index 08450929e..f03a0eefd 100644 --- a/docs/en/docs/img/github-social-preview.svg +++ b/docs/en/docs/img/github-social-preview.svg @@ -1,42 +1,15 @@ - + xmlns="http://www.w3.org/2000/svg" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:dc="http://purl.org/dc/elements/1.1/"> image/svg+xml - @@ -57,42 +29,47 @@ width="338.66666" height="169.33333" x="-1.0833333e-05" - y="0.71613133" - inkscape:export-xdpi="96" - inkscape:export-ydpi="96" /> + y="0.71613133" /> - + id="g2" + transform="matrix(0.73293148,0,0,0.73293148,42.286898,36.073041)"> + + + + FastAPI + style="font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-family:Ubuntu;-inkscape-font-specification:Ubuntu;fill:#009688;fill-opacity:1;stroke-width:1.99288" + y="59.410606" + x="82.667519" + id="tspan977-7">FastAPI High performance, easy to learn,High performance, easy to learn,fast to code, ready for production diff --git a/docs/en/docs/img/icon-transparent-bg.png b/docs/en/docs/img/icon-transparent-bg.png deleted file mode 100644 index c3481da4a..000000000 Binary files a/docs/en/docs/img/icon-transparent-bg.png and /dev/null differ diff --git a/docs/en/docs/img/icon-white-bg.png b/docs/en/docs/img/icon-white-bg.png deleted file mode 100644 index 00888b522..000000000 Binary files a/docs/en/docs/img/icon-white-bg.png and /dev/null differ diff --git a/docs/en/docs/img/icon-white.svg b/docs/en/docs/img/icon-white.svg index cf7c0c7ec..19f0825cc 100644 --- a/docs/en/docs/img/icon-white.svg +++ b/docs/en/docs/img/icon-white.svg @@ -1,15 +1,15 @@ + width="6.3499999mm" + xmlns="http://www.w3.org/2000/svg" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:dc="http://purl.org/dc/elements/1.1/"> image/svg+xml - - - - - + + diff --git a/docs/en/docs/img/logo-margin/logo-teal-vector.svg b/docs/en/docs/img/logo-margin/logo-teal-vector.svg index 02183293c..3eb945c7e 100644 --- a/docs/en/docs/img/logo-margin/logo-teal-vector.svg +++ b/docs/en/docs/img/logo-margin/logo-teal-vector.svg @@ -1,15 +1,15 @@ + id="svg8" + xmlns="http://www.w3.org/2000/svg" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:dc="http://purl.org/dc/elements/1.1/"> image/svg+xml - + + + + + - - - - - - - - - - - + transform="translate(83.131114,-6.0791148)" /> diff --git a/docs/en/docs/img/logo-margin/logo-teal.png b/docs/en/docs/img/logo-margin/logo-teal.png index 57d9eec13..f08144cd9 100644 Binary files a/docs/en/docs/img/logo-margin/logo-teal.png and b/docs/en/docs/img/logo-margin/logo-teal.png differ diff --git a/docs/en/docs/img/logo-margin/logo-teal.svg b/docs/en/docs/img/logo-margin/logo-teal.svg index 2fad25ef7..ce9db533b 100644 --- a/docs/en/docs/img/logo-margin/logo-teal.svg +++ b/docs/en/docs/img/logo-margin/logo-teal.svg @@ -1,15 +1,15 @@ + id="svg8" + xmlns="http://www.w3.org/2000/svg" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:dc="http://purl.org/dc/elements/1.1/"> image/svg+xml - + + + + + + + - - FastAPI - + transform="translate(83.131114,-6.0791148)" /> diff --git a/docs/en/docs/img/logo-margin/logo-white-bg.png b/docs/en/docs/img/logo-margin/logo-white-bg.png index 89256db06..b84fd285e 100644 Binary files a/docs/en/docs/img/logo-margin/logo-white-bg.png and b/docs/en/docs/img/logo-margin/logo-white-bg.png differ diff --git a/docs/en/docs/img/logo-teal-vector.svg b/docs/en/docs/img/logo-teal-vector.svg index c1d1b72e4..d3dad4bec 100644 --- a/docs/en/docs/img/logo-teal-vector.svg +++ b/docs/en/docs/img/logo-teal-vector.svg @@ -1,15 +1,15 @@ + viewBox="0 0 346.52395 63.977134" + height="63.977139mm" + width="346.52396mm" + xmlns="http://www.w3.org/2000/svg" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:dc="http://purl.org/dc/elements/1.1/"> image/svg+xml - - + id="g2149"> - - - - - - + id="g2141"> + + + + + style="font-size:79.7151px;line-height:1.25;font-family:Ubuntu;-inkscape-font-specification:Ubuntu;letter-spacing:0px;word-spacing:0px;fill:#009688;stroke-width:1.99288" + d="M 89.523017,59.410606 V 4.1680399 H 122.84393 V 10.784393 H 97.255382 V 27.44485 h 22.718808 v 6.536638 H 97.255382 v 25.429118 z m 52.292963,-5.340912 q 2.6306,0 4.62348,-0.07972 2.07259,-0.15943 3.42774,-0.47829 V 41.155848 q -0.79715,-0.398576 -2.63059,-0.637721 -1.75374,-0.31886 -4.30462,-0.31886 -1.67402,0 -3.58718,0.239145 -1.83345,0.239145 -3.42775,1.036296 -1.51459,0.717436 -2.55088,2.072593 -1.0363,1.275442 -1.0363,3.427749 0,3.985755 2.55089,5.580058 2.55088,1.514586 6.93521,1.514586 z m -0.63772,-37.147238 q 4.46404,0 7.49322,1.195727 3.10889,1.116011 4.94233,3.268319 1.91317,2.072593 2.71032,5.022052 0.79715,2.869743 0.79715,6.377208 V 58.69317 q -0.95658,0.159431 -2.71031,0.478291 -1.67402,0.239145 -3.82633,0.478291 -2.15231,0.239145 -4.70319,0.398575 -2.47117,0.239146 -4.94234,0.239146 -3.50746,0 -6.45692,-0.717436 -2.94946,-0.717436 -5.10177,-2.232023 -2.1523,-1.594302 -3.34803,-4.145186 -1.19573,-2.550883 -1.19573,-6.138063 0,-3.427749 1.35516,-5.898917 1.43487,-2.471168 3.82632,-3.985755 2.39146,-1.514587 5.58006,-2.232023 3.18861,-0.717436 6.69607,-0.717436 1.11601,0 2.31174,0.15943 1.19572,0.07972 2.23202,0.31886 1.11601,0.159431 1.91316,0.318861 0.79715,0.15943 1.11601,0.239145 v -2.072593 q 0,-1.833447 -0.39857,-3.587179 -0.39858,-1.833448 -1.43487,-3.188604 -1.0363,-1.434872 -2.86975,-2.232023 -1.75373,-0.876866 -4.62347,-0.876866 -3.6669,0 -6.45693,0.558005 -2.71031,0.478291 -4.06547,1.036297 l -0.87686,-6.138063 q 1.43487,-0.637721 4.7829,-1.195727 3.34804,-0.637721 7.25408,-0.637721 z m 37.86462,37.147238 q 4.54377,0 6.69607,-1.195726 2.23203,-1.195727 2.23203,-3.826325 0,-2.710314 -2.15231,-4.304616 -2.15231,-1.594302 -7.09465,-3.587179 -2.39145,-0.956581 -4.62347,-1.913163 -2.15231,-1.036296 -3.74661,-2.391453 -1.5943,-1.355157 -2.55088,-3.268319 -0.95659,-1.913163 -0.95659,-4.703191 0,-5.500342 4.06547,-8.688946 4.06547,-3.26832 11.0804,-3.26832 1.75374,0 3.50747,0.239146 1.75373,0.15943 3.26832,0.47829 1.51458,0.239146 2.6306,0.558006 1.19572,0.31886 1.83344,0.558006 l -1.35515,6.377208 q -1.19573,-0.637721 -3.74661,-1.275442 -2.55089,-0.717436 -6.13807,-0.717436 -3.10889,0 -5.42062,1.275442 -2.31174,1.195727 -2.31174,3.826325 0,1.355157 0.47829,2.391453 0.55801,1.036296 1.5943,1.913163 1.11601,0.797151 2.71031,1.514587 1.59431,0.717436 3.82633,1.514587 2.94946,1.116011 5.2612,2.232022 2.31173,1.036297 3.90604,2.471169 1.67401,1.434871 2.55088,3.507464 0.87687,1.992878 0.87687,4.942337 0,5.739487 -4.30462,8.688946 -4.2249,2.949459 -12.1167,2.949459 -5.50034,0 -8.60923,-0.956582 -3.10889,-0.876866 -4.2249,-1.355156 l 1.35516,-6.377209 q 1.27544,0.478291 4.06547,1.434872 2.79003,0.956581 7.4135,0.956581 z m 32.84256,-36.110941 h 15.70387 v 6.217778 h -15.70387 v 19.131625 q 0,3.108889 0.47829,5.181481 0.47829,1.992878 1.43487,3.188604 0.95658,1.116012 2.39145,1.594302 1.43487,0.478291 3.34804,0.478291 3.34803,0 5.34091,-0.717436 2.07259,-0.797151 2.86974,-1.116011 l 1.43487,6.138063 q -1.11601,0.558005 -3.90604,1.355156 -2.79003,0.876867 -6.37721,0.876867 -4.2249,0 -7.01492,-1.036297 -2.71032,-1.116011 -4.38434,-3.268319 -1.67401,-2.152308 -2.39145,-5.261197 -0.63772,-3.188604 -0.63772,-7.333789 V 6.4000628 l 7.41351,-1.2754417 z m 62.49652,41.451853 q -1.35516,-3.587179 -2.55088,-7.014929 -1.19573,-3.507464 -2.47117,-7.094644 h -25.03054 l -5.02205,14.109573 h -8.05123 q 3.18861,-8.768661 5.97863,-16.182166 2.79003,-7.493219 5.42063,-14.189288 2.71031,-6.696069 5.34091,-12.754416 2.6306,-6.138063 5.50034,-12.1166961 h 7.09465 q 2.86974,5.9786331 5.50034,12.1166961 2.6306,6.058347 5.2612,12.754416 2.71031,6.696069 5.50034,14.189288 2.79003,7.413505 5.97863,16.182166 z m -7.25407,-20.486781 q -2.55089,-6.935214 -5.10177,-13.392137 -2.47117,-6.536639 -5.18148,-12.515272 -2.79003,5.978633 -5.34091,12.515272 -2.47117,6.456923 -4.94234,13.392137 z M 304.99242,3.6100342 q 11.6384,0 17.85618,4.4640458 6.29749,4.384331 6.29749,13.152992 0,4.782906 -1.75373,8.210656 -1.67402,3.348034 -4.94234,5.500342 -3.1886,2.072592 -7.81208,3.029174 -4.62347,0.956581 -10.44268,0.956581 h -6.13806 v 20.486781 h -7.73236 V 4.9651909 q 3.26832,-0.797151 7.25407,-1.0362963 4.06547,-0.3188604 7.41351,-0.3188604 z m 0.63772,6.7757838 q -4.94234,0 -7.57294,0.239145 v 21.682508 h 5.8192 q 3.98576,0 7.17436,-0.47829 3.18861,-0.558006 5.34092,-1.753733 2.23202,-1.275441 3.42774,-3.427749 1.19573,-2.152308 1.19573,-5.500342 0,-3.188604 -1.27544,-5.261197 -1.19573,-2.072593 -3.34803,-3.268319 -2.0726,-1.275442 -4.86263,-1.753732 -2.79002,-0.478291 -5.89891,-0.478291 z M 338.7916,4.1680399 h 7.73237 V 59.410606 h -7.73237 z" + id="text979" + aria-label="FastAPI" /> diff --git a/docs/en/docs/img/logo-teal.svg b/docs/en/docs/img/logo-teal.svg index 0d1136eb4..bc699860f 100644 --- a/docs/en/docs/img/logo-teal.svg +++ b/docs/en/docs/img/logo-teal.svg @@ -1,15 +1,15 @@ + width="346.52396mm" + xmlns="http://www.w3.org/2000/svg" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:dc="http://purl.org/dc/elements/1.1/"> image/svg+xml - - - FastAPI + id="g2149"> + + + + + + FastAPI + diff --git a/docs/en/docs/img/sponsors/blockbee-banner.png b/docs/en/docs/img/sponsors/blockbee-banner.png new file mode 100644 index 000000000..074b36031 Binary files /dev/null and b/docs/en/docs/img/sponsors/blockbee-banner.png differ diff --git a/docs/en/docs/img/sponsors/blockbee.png b/docs/en/docs/img/sponsors/blockbee.png new file mode 100644 index 000000000..6d2fcf701 Binary files /dev/null and b/docs/en/docs/img/sponsors/blockbee.png differ diff --git a/docs/en/docs/img/sponsors/coderabbit-banner.png b/docs/en/docs/img/sponsors/coderabbit-banner.png new file mode 100644 index 000000000..da3bb3482 Binary files /dev/null and b/docs/en/docs/img/sponsors/coderabbit-banner.png differ diff --git a/docs/en/docs/img/sponsors/coderabbit.png b/docs/en/docs/img/sponsors/coderabbit.png new file mode 100644 index 000000000..1fb74569b Binary files /dev/null and b/docs/en/docs/img/sponsors/coderabbit.png differ diff --git a/docs/en/docs/img/sponsors/coherence-banner.png b/docs/en/docs/img/sponsors/coherence-banner.png new file mode 100644 index 000000000..1d4959659 Binary files /dev/null and b/docs/en/docs/img/sponsors/coherence-banner.png differ diff --git a/docs/en/docs/img/sponsors/coherence.png b/docs/en/docs/img/sponsors/coherence.png new file mode 100644 index 000000000..d48c4edc4 Binary files /dev/null and b/docs/en/docs/img/sponsors/coherence.png differ diff --git a/docs/en/docs/img/sponsors/fine-banner.png b/docs/en/docs/img/sponsors/fine-banner.png new file mode 100644 index 000000000..57d8e52c7 Binary files /dev/null and b/docs/en/docs/img/sponsors/fine-banner.png differ diff --git a/docs/en/docs/img/sponsors/fine.png b/docs/en/docs/img/sponsors/fine.png new file mode 100644 index 000000000..ed770f212 Binary files /dev/null and b/docs/en/docs/img/sponsors/fine.png differ diff --git a/docs/en/docs/img/sponsors/kong-banner.png b/docs/en/docs/img/sponsors/kong-banner.png new file mode 100644 index 000000000..9f5b55a0f Binary files /dev/null and b/docs/en/docs/img/sponsors/kong-banner.png differ diff --git a/docs/en/docs/img/sponsors/kong.png b/docs/en/docs/img/sponsors/kong.png new file mode 100644 index 000000000..e54cdac2c Binary files /dev/null and b/docs/en/docs/img/sponsors/kong.png differ diff --git a/docs/en/docs/img/sponsors/lambdatest.png b/docs/en/docs/img/sponsors/lambdatest.png new file mode 100644 index 000000000..674cbcb89 Binary files /dev/null and b/docs/en/docs/img/sponsors/lambdatest.png differ diff --git a/docs/en/docs/img/sponsors/liblab-banner.png b/docs/en/docs/img/sponsors/liblab-banner.png new file mode 100644 index 000000000..299ff816b Binary files /dev/null and b/docs/en/docs/img/sponsors/liblab-banner.png differ diff --git a/docs/en/docs/img/sponsors/liblab.png b/docs/en/docs/img/sponsors/liblab.png new file mode 100644 index 000000000..ee461d7bc Binary files /dev/null and b/docs/en/docs/img/sponsors/liblab.png differ diff --git a/docs/en/docs/img/sponsors/mongodb-banner.png b/docs/en/docs/img/sponsors/mongodb-banner.png new file mode 100755 index 000000000..25bc85eaa Binary files /dev/null and b/docs/en/docs/img/sponsors/mongodb-banner.png differ diff --git a/docs/en/docs/img/sponsors/mongodb.png b/docs/en/docs/img/sponsors/mongodb.png new file mode 100755 index 000000000..113ca4785 Binary files /dev/null and b/docs/en/docs/img/sponsors/mongodb.png differ diff --git a/docs/en/docs/img/sponsors/permit.png b/docs/en/docs/img/sponsors/permit.png new file mode 100644 index 000000000..4f07f22e2 Binary files /dev/null and b/docs/en/docs/img/sponsors/permit.png differ diff --git a/docs/en/docs/img/sponsors/render-banner.svg b/docs/en/docs/img/sponsors/render-banner.svg new file mode 100644 index 000000000..b8b1ed2e9 --- /dev/null +++ b/docs/en/docs/img/sponsors/render-banner.svg @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/en/docs/img/sponsors/render.svg b/docs/en/docs/img/sponsors/render.svg new file mode 100644 index 000000000..4a830482d --- /dev/null +++ b/docs/en/docs/img/sponsors/render.svg @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/en/docs/img/sponsors/speakeasy.png b/docs/en/docs/img/sponsors/speakeasy.png index 001b4b4ca..5ddc25487 100644 Binary files a/docs/en/docs/img/sponsors/speakeasy.png and b/docs/en/docs/img/sponsors/speakeasy.png differ diff --git a/docs/en/docs/img/sponsors/stainless.png b/docs/en/docs/img/sponsors/stainless.png new file mode 100644 index 000000000..0f99c1d32 Binary files /dev/null and b/docs/en/docs/img/sponsors/stainless.png differ diff --git a/docs/en/docs/img/sponsors/talkpython-v2.jpg b/docs/en/docs/img/sponsors/talkpython-v2.jpg new file mode 100644 index 000000000..adb015248 Binary files /dev/null and b/docs/en/docs/img/sponsors/talkpython-v2.jpg differ diff --git a/docs/en/docs/img/sponsors/zuplo-banner.png b/docs/en/docs/img/sponsors/zuplo-banner.png new file mode 100644 index 000000000..a730f2cf2 Binary files /dev/null and b/docs/en/docs/img/sponsors/zuplo-banner.png differ diff --git a/docs/en/docs/img/sponsors/zuplo.png b/docs/en/docs/img/sponsors/zuplo.png new file mode 100644 index 000000000..7a7c16862 Binary files /dev/null and b/docs/en/docs/img/sponsors/zuplo.png differ diff --git a/docs/en/docs/img/tutorial/body-nested-models/image01.png b/docs/en/docs/img/tutorial/body-nested-models/image01.png index f3644ce79..1f7e07cfe 100644 Binary files a/docs/en/docs/img/tutorial/body-nested-models/image01.png and b/docs/en/docs/img/tutorial/body-nested-models/image01.png differ diff --git a/docs/en/docs/img/tutorial/cookie-param-models/image01.png b/docs/en/docs/img/tutorial/cookie-param-models/image01.png new file mode 100644 index 000000000..85c370f80 Binary files /dev/null and b/docs/en/docs/img/tutorial/cookie-param-models/image01.png differ diff --git a/docs/en/docs/img/tutorial/header-param-models/image01.png b/docs/en/docs/img/tutorial/header-param-models/image01.png new file mode 100644 index 000000000..849dea3d8 Binary files /dev/null and b/docs/en/docs/img/tutorial/header-param-models/image01.png differ diff --git a/docs/en/docs/img/tutorial/query-param-models/image01.png b/docs/en/docs/img/tutorial/query-param-models/image01.png new file mode 100644 index 000000000..e7a61b61f Binary files /dev/null and b/docs/en/docs/img/tutorial/query-param-models/image01.png differ diff --git a/docs/en/docs/img/tutorial/request-form-models/image01.png b/docs/en/docs/img/tutorial/request-form-models/image01.png new file mode 100644 index 000000000..3fe32c03d Binary files /dev/null and b/docs/en/docs/img/tutorial/request-form-models/image01.png differ diff --git a/docs/en/docs/img/tutorial/sql-databases/image01.png b/docs/en/docs/img/tutorial/sql-databases/image01.png index 8e575abd6..bfcdb57a0 100644 Binary files a/docs/en/docs/img/tutorial/sql-databases/image01.png and b/docs/en/docs/img/tutorial/sql-databases/image01.png differ diff --git a/docs/en/docs/img/tutorial/sql-databases/image02.png b/docs/en/docs/img/tutorial/sql-databases/image02.png index ee59fc939..7bcad8378 100644 Binary files a/docs/en/docs/img/tutorial/sql-databases/image02.png and b/docs/en/docs/img/tutorial/sql-databases/image02.png differ diff --git a/docs/en/docs/index.md b/docs/en/docs/index.md index 3660e74e3..4a2777f25 100644 --- a/docs/en/docs/index.md +++ b/docs/en/docs/index.md @@ -1,7 +1,4 @@ ---- -hide: - - navigation ---- +# FastAPI +

FastAPI

- FastAPI framework, alto desempeño, fácil de aprender, rápido de programar, listo para producción + FastAPI framework, alto rendimiento, fácil de aprender, rápido de programar, listo para producción

- - Test + + Test - - Coverage + + Coverage Package version + + Supported Python versions +

--- **Documentación**: https://fastapi.tiangolo.com -**Código Fuente**: https://github.com/tiangolo/fastapi +**Código Fuente**: https://github.com/fastapi/fastapi --- -FastAPI es un web framework moderno y rápido (de alto rendimiento) para construir APIs con Python 3.8+ basado en las anotaciones de tipos estándar de Python. -Sus características principales son: +FastAPI es un framework web moderno, rápido (de alto rendimiento), para construir APIs con Python basado en las anotaciones de tipos estándar de Python. -* **Rapidez**: Alto rendimiento, a la par con **NodeJS** y **Go** (gracias a Starlette y Pydantic). [Uno de los frameworks de Python más rápidos](#rendimiento). +Las características clave son: -* **Rápido de programar**: Incrementa la velocidad de desarrollo entre 200% y 300%. * -* **Menos errores**: Reduce los errores humanos (de programador) aproximadamente un 40%. * -* **Intuitivo**: Gran soporte en los editores con auto completado en todas partes. Gasta menos tiempo debugging. -* **Fácil**: Está diseñado para ser fácil de usar y aprender. Gastando menos tiempo leyendo documentación. -* **Corto**: Minimiza la duplicación de código. Múltiples funcionalidades con cada declaración de parámetros. Menos errores. -* **Robusto**: Crea código listo para producción con documentación automática interactiva. -* **Basado en estándares**: Basado y totalmente compatible con los estándares abiertos para APIs: OpenAPI (conocido previamente como Swagger) y JSON Schema. +* **Rápido**: Muy alto rendimiento, a la par con **NodeJS** y **Go** (gracias a Starlette y Pydantic). [Uno de los frameworks Python más rápidos disponibles](#performance). +* **Rápido de programar**: Aumenta la velocidad para desarrollar funcionalidades en aproximadamente un 200% a 300%. * +* **Menos bugs**: Reduce en aproximadamente un 40% los errores inducidos por humanos (desarrolladores). * +* **Intuitivo**: Gran soporte para editores. Autocompletado en todas partes. Menos tiempo depurando. +* **Fácil**: Diseñado para ser fácil de usar y aprender. Menos tiempo leyendo documentación. +* **Corto**: Minimiza la duplicación de código. Múltiples funcionalidades desde cada declaración de parámetro. Menos bugs. +* **Robusto**: Obtén código listo para producción. Con documentación interactiva automática. +* **Basado en estándares**: Basado (y completamente compatible) con los estándares abiertos para APIs: OpenAPI (anteriormente conocido como Swagger) y JSON Schema. -* Esta estimación está basada en pruebas con un equipo de desarrollo interno construyendo aplicaciones listas para producción. +* estimación basada en pruebas con un equipo de desarrollo interno, construyendo aplicaciones de producción. ## Sponsors @@ -58,41 +67,47 @@ Sus características principales son: ## Opiniones -"_[...] 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._" +"_[...] Estoy usando **FastAPI** un montón estos días. [...] De hecho, estoy planeando usarlo para todos los servicios de **ML de mi equipo en Microsoft**. Algunos de ellos se están integrando en el núcleo del producto **Windows** y algunos productos de **Office**._" -
Kabir Khan - Microsoft (ref)
+
Kabir Khan - Microsoft (ref)
--- -"_We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]_" +"_Adoptamos el paquete **FastAPI** para crear un servidor **REST** que pueda ser consultado para obtener **predicciones**. [para Ludwig]_" -
Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber (ref)
+
Piero Molino, Yaroslav Dudin, y Sai Sumanth Miryala - Uber (ref)
--- -"_**Netflix** is pleased to announce the open-source release of our **crisis management** orchestration framework: **Dispatch**! [built with **FastAPI**]_" +"_**Netflix** se complace en anunciar el lanzamiento de código abierto de nuestro framework de orquestación de **gestión de crisis**: **Dispatch**! [construido con **FastAPI**]_"
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (ref)
--- -"_I’m over the moon excited about **FastAPI**. It’s so fun!_" +"_Estoy súper emocionado con **FastAPI**. ¡Es tan divertido!_" -
Brian Okken - Python Bytes podcast host (ref)
+ --- -"_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._" +"_Honestamente, lo que has construido parece súper sólido y pulido. En muchos aspectos, es lo que quería que **Hug** fuera; es realmente inspirador ver a alguien construir eso._" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - creador de Hug (ref)
--- -"_If you're looking to learn one **modern framework** for building REST APIs, check out **FastAPI** [...] It's fast, easy to use and easy to learn [...]_" +"_Si estás buscando aprender un **framework moderno** para construir APIs REST, échale un vistazo a **FastAPI** [...] Es rápido, fácil de usar y fácil de aprender [...]_" + +"_Nos hemos cambiado a **FastAPI** para nuestras **APIs** [...] Creo que te gustará [...]_" -"_We've switched over to **FastAPI** for our **APIs** [...] I think you'll like it [...]_" +
Ines Montani - Matthew Honnibal - fundadores de Explosion AI - creadores de spaCy (ref) - (ref)
-
Ines Montani - Matthew Honnibal - Explosion AI founders - spaCy creators (ref) - (ref)
+--- + +"_Si alguien está buscando construir una API de Python para producción, altamente recomendaría **FastAPI**. Está **hermosamente diseñado**, es **simple de usar** y **altamente escalable**, se ha convertido en un **componente clave** en nuestra estrategia de desarrollo API primero y está impulsando muchas automatizaciones y servicios como nuestro Ingeniero Virtual TAC._" + +
Deon Pillsbury - Cisco (ref)
--- @@ -100,43 +115,33 @@ Sus características principales son: -Si estás construyendo un app de CLI para ser usada en la terminal en vez de una API web, fíjate en **Typer**. +Si estás construyendo una aplicación de CLI para ser usada en el terminal en lugar de una API web, revisa **Typer**. -**Typer** es el hermano menor de FastAPI. La intención es que sea el **FastAPI de las CLIs**. ⌨️ 🚀 +**Typer** es el hermano pequeño de FastAPI. Y está destinado a ser el **FastAPI de las CLIs**. ⌨️ 🚀 ## Requisitos -Python 3.8+ - -FastAPI está sobre los hombros de gigantes: +FastAPI se apoya en hombros de gigantes: * Starlette para las partes web. -* Pydantic para las partes de datos. +* Pydantic para las partes de datos. ## Instalación -
- -```console -$ pip install fastapi - ----> 100% -``` - -
- -También vas a necesitar un servidor ASGI para producción cómo Uvicorn o Hypercorn. +Crea y activa un entorno virtual y luego instala FastAPI:
```console -$ pip install "uvicorn[standard]" +$ pip install "fastapi[standard]" ---> 100% ```
+**Nota**: Asegúrate de poner `"fastapi[standard]"` entre comillas para asegurar que funcione en todas las terminales. + ## Ejemplo ### Créalo @@ -144,9 +149,10 @@ $ pip install "uvicorn[standard]" * Crea un archivo `main.py` con: ```Python -from fastapi import FastAPI from typing import Union +from fastapi import FastAPI + app = FastAPI() @@ -165,10 +171,11 @@ def read_item(item_id: int, q: Union[str, None] = None): Si tu código usa `async` / `await`, usa `async def`: -```Python hl_lines="7 12" -from fastapi import FastAPI +```Python hl_lines="9 14" from typing import Union +from fastapi import FastAPI + app = FastAPI() @@ -184,7 +191,7 @@ async def read_item(item_id: int, q: Union[str, None] = None): **Nota**: -Si no lo sabes, revisa la sección _"¿Con prisa?"_ sobre `async` y `await` en la documentación. +Si no lo sabes, revisa la sección _"¿Con prisa?"_ sobre `async` y `await` en la documentación.
@@ -195,11 +202,24 @@ Corre el servidor con:
```console -$ uvicorn main:app --reload - +$ fastapi dev main.py + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + │ fastapi run │ + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -INFO: Started reloader process [28720] -INFO: Started server process [28722] +INFO: Started reloader process [2248755] using WatchFiles +INFO: Started server process [2248757] INFO: Waiting for application startup. INFO: Application startup complete. ``` @@ -207,13 +227,13 @@ INFO: Application startup complete.
-Sobre el comando uvicorn main:app --reload... +Acerca del comando fastapi dev main.py... + +El comando `fastapi dev` lee tu archivo `main.py`, detecta la app **FastAPI** en él y arranca un servidor usando Uvicorn. -El comando `uvicorn main:app` se refiere a: +Por defecto, `fastapi dev` comenzará con auto-recarga habilitada para el desarrollo local. -* `main`: el archivo `main.py` (el"modulo" de Python). -* `app`: el objeto creado dentro de `main.py` con la línea `app = FastAPI()`. -* `--reload`: hace que el servidor se reinicie después de cambios en el código. Esta opción solo debe ser usada en desarrollo. +Puedes leer más sobre esto en la documentación del CLI de FastAPI.
@@ -221,7 +241,7 @@ El comando `uvicorn main:app` se refiere a: Abre tu navegador en http://127.0.0.1:8000/items/5?q=somequery. -Verás la respuesta de JSON cómo: +Verás el response JSON como: ```JSON {"item_id": 5, "q": "somequery"} @@ -229,37 +249,38 @@ Verás la respuesta de JSON cómo: Ya creaste una API que: -* Recibe HTTP requests en los _paths_ `/` y `/items/{item_id}`. -* Ambos _paths_ toman operaciones `GET` (también conocido como HTTP _methods_). -* El _path_ `/items/{item_id}` tiene un _path parameter_ `item_id` que debería ser un `int`. -* El _path_ `/items/{item_id}` tiene un `str` _query parameter_ `q` opcional. +* Recibe requests HTTP en los _paths_ `/` y `/items/{item_id}`. +* Ambos _paths_ toman _operaciones_ `GET` (también conocidas como métodos HTTP). +* El _path_ `/items/{item_id}` tiene un _parámetro de path_ `item_id` que debe ser un `int`. +* El _path_ `/items/{item_id}` tiene un _parámetro de query_ `q` opcional que es un `str`. -### Documentación interactiva de APIs +### Documentación interactiva de la API Ahora ve a http://127.0.0.1:8000/docs. -Verás la documentación automática e interactiva de la API (proveída por Swagger UI): +Verás la documentación interactiva automática de la API (proporcionada por Swagger UI): ![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) -### Documentación alternativa de la API +### Documentación de API Alternativa -Ahora, ve a http://127.0.0.1:8000/redoc. +Y ahora, ve a http://127.0.0.1:8000/redoc. -Ahora verás la documentación automática alternativa (proveída por ReDoc): +Verás la documentación alternativa automática (proporcionada por ReDoc): ![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) -## Mejora al ejemplo +## Actualización del Ejemplo -Ahora modifica el archivo `main.py` para recibir un body del `PUT` request. +Ahora modifica el archivo `main.py` para recibir un body desde un request `PUT`. -Declara el body usando las declaraciones de tipo estándares de Python gracias a Pydantic. +Declara el body usando tipos estándar de Python, gracias a Pydantic. + +```Python hl_lines="4 9-12 25-27" +from typing import Union -```Python hl_lines="2 7-10 23-25" from fastapi import FastAPI from pydantic import BaseModel -from typing import Union app = FastAPI() @@ -285,9 +306,9 @@ def update_item(item_id: int, item: Item): return {"item_name": item.name, "item_id": item_id} ``` -El servidor debería recargar automáticamente (porque añadiste `--reload` al comando `uvicorn` que está más arriba). +El servidor `fastapi dev` debería recargarse automáticamente. -### Mejora a la documentación interactiva de APIs +### Actualización de la Documentación Interactiva de la API Ahora ve a http://127.0.0.1:8000/docs. @@ -295,31 +316,31 @@ Ahora ve a http://127.0.0.1:8000/redoc. +Y ahora, ve a http://127.0.0.1:8000/redoc. -* La documentación alternativa también reflejará el nuevo parámetro de query y el body: +* La documentación alternativa también reflejará el nuevo parámetro de query y body: ![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) ### Resumen -En resumen, declaras los tipos de parámetros, body, etc. **una vez** como parámetros de la función. +En resumen, declaras **una vez** los tipos de parámetros, body, etc. como parámetros de función. -Lo haces con tipos modernos estándar de Python. +Lo haces con tipos estándar modernos de Python. -No tienes que aprender una sintaxis nueva, los métodos o clases de una library específica, etc. +No tienes que aprender una nueva sintaxis, los métodos o clases de un paquete específico, etc. -Solo **Python 3.8+** estándar. +Solo **Python** estándar. Por ejemplo, para un `int`: @@ -327,7 +348,7 @@ Por ejemplo, para un `int`: item_id: int ``` -o para un modelo más complejo de `Item`: +o para un modelo `Item` más complejo: ```Python item: Item @@ -335,62 +356,62 @@ item: Item ...y con esa única declaración obtienes: -* Soporte del editor incluyendo: - * Auto completado. - * Anotaciones de tipos. +* Soporte para editores, incluyendo: + * Autocompletado. + * Chequeo de tipos. * Validación de datos: - * Errores automáticos y claros cuándo los datos son inválidos. - * Validación, incluso para objetos JSON profundamente anidados. -* Conversión de datos de input: viniendo de la red a datos y tipos de Python. Leyendo desde: + * Errores automáticos y claros cuando los datos son inválidos. + * Validación incluso para objetos JSON profundamente anidados. +* Conversión de datos de entrada: de la red a los datos y tipos de Python. Leyendo desde: * JSON. - * Path parameters. - * Query parameters. + * Parámetros de path. + * Parámetros de query. * Cookies. * Headers. - * Formularios. + * Forms. * Archivos. -* Conversión de datos de output: convirtiendo de datos y tipos de Python a datos para la red (como JSON): +* Conversión de datos de salida: convirtiendo de datos y tipos de Python a datos de red (como JSON): * Convertir tipos de Python (`str`, `int`, `float`, `bool`, `list`, etc). * Objetos `datetime`. * Objetos `UUID`. - * Modelos de bases de datos. + * Modelos de base de datos. * ...y muchos más. -* Documentación automática e interactiva incluyendo 2 interfaces de usuario alternativas: +* Documentación interactiva automática de la API, incluyendo 2 interfaces de usuario alternativas: * Swagger UI. * ReDoc. --- -Volviendo al ejemplo de código anterior, **FastAPI** va a: - -* Validar que existe un `item_id` en el path para requests usando `GET` y `PUT`. -* Validar que el `item_id` es del tipo `int` para requests de tipo `GET` y `PUT`. - * Si no lo es, el cliente verá un mensaje de error útil y claro. -* Revisar si existe un query parameter opcional llamado `q` (cómo en `http://127.0.0.1:8000/items/foo?q=somequery`) para requests de tipo `GET`. - * Como el parámetro `q` fue declarado con `= None` es opcional. - * Sin el `None` sería obligatorio (cómo lo es el body en el caso con `PUT`). -* Para requests de tipo `PUT` a `/items/{item_id}` leer el body como JSON: - * Revisar si tiene un atributo requerido `name` que debe ser un `str`. - * Revisar si tiene un atributo requerido `price` que debe ser un `float`. - * Revisar si tiene un atributo opcional `is_offer`, que debe ser un `bool`si está presente. - * Todo esto funcionaría para objetos JSON profundamente anidados. -* Convertir de y a JSON automáticamente. -* Documentar todo con OpenAPI que puede ser usado por: +Volviendo al ejemplo de código anterior, **FastAPI**: + +* Validará que haya un `item_id` en el path para requests `GET` y `PUT`. +* Validará que el `item_id` sea del tipo `int` para requests `GET` y `PUT`. + * Si no lo es, el cliente verá un error útil y claro. +* Comprobará si hay un parámetro de query opcional llamado `q` (como en `http://127.0.0.1:8000/items/foo?q=somequery`) para requests `GET`. + * Como el parámetro `q` está declarado con `= None`, es opcional. + * Sin el `None` sería requerido (como lo es el body en el caso con `PUT`). +* Para requests `PUT` a `/items/{item_id}`, leerá el body como JSON: + * Comprobará que tiene un atributo requerido `name` que debe ser un `str`. + * Comprobará que tiene un atributo requerido `price` que debe ser un `float`. + * Comprobará que tiene un atributo opcional `is_offer`, que debe ser un `bool`, si está presente. + * Todo esto también funcionaría para objetos JSON profundamente anidados. +* Convertirá de y a JSON automáticamente. +* Documentará todo con OpenAPI, que puede ser usado por: * Sistemas de documentación interactiva. - * Sistemas de generación automática de código de cliente para muchos lenguajes. -* Proveer directamente 2 interfaces de documentación web interactivas. + * Sistemas de generación automática de código cliente, para muchos lenguajes. +* Proporcionará 2 interfaces web de documentación interactiva directamente. --- -Hasta ahora, escasamente vimos lo básico pero ya tienes una idea de cómo funciona. +Solo tocamos los conceptos básicos, pero ya te haces una idea de cómo funciona todo. -Intenta cambiando la línea a: +Intenta cambiar la línea con: ```Python return {"item_name": item.name, "item_id": item_id} ``` -...de: +...desde: ```Python ... "item_name": item.name ... @@ -402,56 +423,74 @@ Intenta cambiando la línea a: ... "item_price": item.price ... ``` -... y mira como el editor va a auto-completar los atributos y sabrá sus tipos: +...y observa cómo tu editor autocompleta los atributos y conoce sus tipos: -![soporte de editor](https://fastapi.tiangolo.com/img/vscode-completion.png) +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) -Para un ejemplo más completo que incluye más características ve el Tutorial - Guía de Usuario. +Para un ejemplo más completo incluyendo más funcionalidades, ve al Tutorial - Guía del Usuario. -**Spoiler alert**: el Tutorial - Guía de Usuario incluye: +**Alerta de spoilers**: el tutorial - guía del usuario incluye: -* Declaración de **parámetros** en otros lugares diferentes cómo los: **headers**, **cookies**, **formularios** y **archivos**. -* Cómo agregar **requisitos de validación** cómo `maximum_length` o `regex`. -* Un sistema de **Dependency Injection** poderoso y fácil de usar. -* Seguridad y autenticación incluyendo soporte para **OAuth2** con **JWT tokens** y **HTTP Basic** auth. -* Técnicas más avanzadas, pero igual de fáciles, para declarar **modelos de JSON profundamente anidados** (gracias a Pydantic). -* Muchas características extra (gracias a Starlette) como: +* Declaración de **parámetros** desde otros lugares diferentes como: **headers**, **cookies**, **campos de formulario** y **archivos**. +* Cómo establecer **restricciones de validación** como `maximum_length` o `regex`. +* Un sistema de **Inyección de Dependencias** muy poderoso y fácil de usar. +* Seguridad y autenticación, incluyendo soporte para **OAuth2** con **tokens JWT** y autenticación **HTTP Basic**. +* Técnicas más avanzadas (pero igualmente fáciles) para declarar **modelos JSON profundamente anidados** (gracias a Pydantic). +* Integración con **GraphQL** usando Strawberry y otros paquetes. +* Muchas funcionalidades extra (gracias a Starlette) como: * **WebSockets** - * **GraphQL** - * pruebas extremadamente fáciles con HTTPX y `pytest` + * pruebas extremadamente fáciles basadas en HTTPX y `pytest` * **CORS** - * **Cookie Sessions** - * ...y mucho más. + * **Sesiones de Cookies** + * ...y más. ## Rendimiento -Benchmarks independientes de TechEmpower muestran que aplicaciones de **FastAPI** corriendo con Uvicorn cómo uno de los frameworks de Python más rápidos, únicamente debajo de Starlette y Uvicorn (usados internamente por FastAPI). (*) +Benchmarks independientes de TechEmpower muestran aplicaciones **FastAPI** ejecutándose bajo Uvicorn como uno de los frameworks Python más rápidos disponibles, solo por debajo de Starlette y Uvicorn (usados internamente por FastAPI). (*) -Para entender más al respecto revisa la sección Benchmarks. +Para entender más sobre esto, ve la sección Benchmarks. -## Dependencias Opcionales +## Dependencias + +FastAPI depende de Pydantic y Starlette. + +### Dependencias `standard` + +Cuando instalas FastAPI con `pip install "fastapi[standard]"` viene con el grupo `standard` de dependencias opcionales: Usadas por Pydantic: -* email_validator - para validación de emails. +* email-validator - para validación de correos electrónicos. + +Usadas por Starlette: + +* httpx - Requerido si deseas usar el `TestClient`. +* jinja2 - Requerido si deseas usar la configuración de plantilla predeterminada. +* python-multipart - Requerido si deseas soportar "parsing" de forms, con `request.form()`. + +Usadas por FastAPI / Starlette: + +* uvicorn - para el servidor que carga y sirve tu aplicación. Esto incluye `uvicorn[standard]`, que incluye algunas dependencias (por ejemplo, `uvloop`) necesarias para servir con alto rendimiento. +* `fastapi-cli` - para proporcionar el comando `fastapi`. + +### Sin Dependencias `standard` + +Si no deseas incluir las dependencias opcionales `standard`, puedes instalar con `pip install fastapi` en lugar de `pip install "fastapi[standard]"`. + +### Dependencias Opcionales Adicionales -Usados por Starlette: +Existen algunas dependencias adicionales que podrías querer instalar. -* httpx - Requerido si quieres usar el `TestClient`. -* jinja2 - Requerido si quieres usar la configuración por defecto de templates. -* python-multipart - Requerido si quieres dar soporte a "parsing" de formularios, con `request.form()`. -* itsdangerous - Requerido para dar soporte a `SessionMiddleware`. -* pyyaml - Requerido para dar soporte al `SchemaGenerator` de Starlette (probablemente no lo necesites con FastAPI). -* graphene - Requerido para dar soporte a `GraphQLApp`. -* ujson - Requerido si quieres usar `UJSONResponse`. +Dependencias opcionales adicionales de Pydantic: -Usado por FastAPI / Starlette: +* pydantic-settings - para la gestión de configuraciones. +* pydantic-extra-types - para tipos extra para ser usados con Pydantic. -* uvicorn - para el servidor que carga y sirve tu aplicación. -* orjson - Requerido si quieres usar `ORJSONResponse`. +Dependencias opcionales adicionales de FastAPI: -Puedes instalarlos con `pip install fastapi[all]`. +* orjson - Requerido si deseas usar `ORJSONResponse`. +* ujson - Requerido si deseas usar `UJSONResponse`. ## Licencia -Este proyecto está licenciado bajo los términos de la licencia del MIT. +Este proyecto tiene licencia bajo los términos de la licencia MIT. diff --git a/docs/es/docs/learn/index.md b/docs/es/docs/learn/index.md index b8d26cf34..cc6c7cc3f 100644 --- a/docs/es/docs/learn/index.md +++ b/docs/es/docs/learn/index.md @@ -1,5 +1,5 @@ -# Aprender +# Aprende Aquí están las secciones introductorias y los tutoriales para aprender **FastAPI**. -Podrías considerar esto como un **libro**, un **curso**, la forma **oficial** y recomendada de aprender FastAPI. 😎 +Podrías considerar esto un **libro**, un **curso**, la forma **oficial** y recomendada de aprender FastAPI. 😎 diff --git a/docs/es/docs/project-generation.md b/docs/es/docs/project-generation.md new file mode 100644 index 000000000..559995151 --- /dev/null +++ b/docs/es/docs/project-generation.md @@ -0,0 +1,28 @@ +# Plantilla Full Stack FastAPI + +Las plantillas, aunque normalmente vienen con una configuración específica, están diseñadas para ser flexibles y personalizables. Esto te permite modificarlas y adaptarlas a los requisitos de tu proyecto, haciéndolas un excelente punto de partida. 🏁 + +Puedes usar esta plantilla para comenzar, ya que incluye gran parte de la configuración inicial, seguridad, base de datos y algunos endpoints de API ya hechos para ti. + +Repositorio de GitHub: Plantilla Full Stack FastAPI + +## Plantilla Full Stack FastAPI - Tecnología y Funcionalidades + +- ⚡ [**FastAPI**](https://fastapi.tiangolo.com) para la API del backend en Python. + - 🧰 [SQLModel](https://sqlmodel.tiangolo.com) para las interacciones con bases de datos SQL en Python (ORM). + - 🔍 [Pydantic](https://docs.pydantic.dev), utilizado por FastAPI, para la validación de datos y gestión de configuraciones. + - 💾 [PostgreSQL](https://www.postgresql.org) como base de datos SQL. +- 🚀 [React](https://react.dev) para el frontend. + - 💃 Usando TypeScript, hooks, [Vite](https://vitejs.dev), y otras partes de una stack moderna de frontend. + - 🎨 [Chakra UI](https://chakra-ui.com) para los componentes del frontend. + - 🤖 Un cliente de frontend generado automáticamente. + - 🧪 [Playwright](https://playwright.dev) para pruebas End-to-End. + - 🦇 Soporte para modo oscuro. +- 🐋 [Docker Compose](https://www.docker.com) para desarrollo y producción. +- 🔒 Hashing seguro de contraseñas por defecto. +- 🔑 Autenticación con tokens JWT. +- 📫 Recuperación de contraseñas basada en email. +- ✅ Pruebas con [Pytest](https://pytest.org). +- 📞 [Traefik](https://traefik.io) como proxy inverso / balanceador de carga. +- 🚢 Instrucciones de despliegue usando Docker Compose, incluyendo cómo configurar un proxy Traefik frontend para manejar certificados HTTPS automáticos. +- 🏭 CI (integración continua) y CD (despliegue continuo) basados en GitHub Actions. diff --git a/docs/es/docs/python-types.md b/docs/es/docs/python-types.md index b83cbe3f5..769204f8f 100644 --- a/docs/es/docs/python-types.md +++ b/docs/es/docs/python-types.md @@ -1,29 +1,30 @@ -# Introducción a los Tipos de Python +# Introducción a Tipos en Python -**Python 3.6+** tiene soporte para "type hints" opcionales. +Python tiene soporte para "anotaciones de tipos" opcionales (también llamadas "type hints"). -Estos **type hints** son una nueva sintaxis, desde Python 3.6+, que permite declarar el tipo de una variable. +Estas **"anotaciones de tipos"** o type hints son una sintaxis especial que permite declarar el tipo de una variable. -Usando las declaraciones de tipos para tus variables, los editores y otras herramientas pueden proveerte un soporte mejor. +Al declarar tipos para tus variables, los editores y herramientas te pueden proporcionar un mejor soporte. -Este es solo un **tutorial corto** sobre los Python type hints. Solo cubre lo mínimo necesario para usarlos con **FastAPI**... realmente es muy poco lo que necesitas. +Este es solo un **tutorial rápido / recordatorio** sobre las anotaciones de tipos en Python. Cubre solo lo mínimo necesario para usarlas con **FastAPI**... que en realidad es muy poco. -Todo **FastAPI** está basado en estos type hints, lo que le da muchas ventajas y beneficios. +**FastAPI** se basa completamente en estas anotaciones de tipos, dándole muchas ventajas y beneficios. -Pero, así nunca uses **FastAPI** te beneficiarás de aprender un poco sobre los type hints. +Pero incluso si nunca usas **FastAPI**, te beneficiaría aprender un poco sobre ellas. -!!! note "Nota" - Si eres un experto en Python y ya lo sabes todo sobre los type hints, salta al siguiente capítulo. +/// note | Nota + +Si eres un experto en Python, y ya sabes todo sobre las anotaciones de tipos, salta al siguiente capítulo. + +/// ## Motivación Comencemos con un ejemplo simple: -```Python -{!../../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} -Llamar este programa nos muestra el siguiente output: +Llamar a este programa genera: ``` John Doe @@ -31,39 +32,37 @@ John Doe La función hace lo siguiente: -* Toma un `first_name` y un `last_name`. -* Convierte la primera letra de cada uno en una letra mayúscula con `title()`. -* Las concatena con un espacio en la mitad. +* Toma un `first_name` y `last_name`. +* Convierte la primera letra de cada uno a mayúsculas con `title()`. +* Concatena ambos con un espacio en el medio. -```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} ### Edítalo Es un programa muy simple. -Ahora, imagina que lo estás escribiendo desde ceros. +Pero ahora imagina que lo escribieras desde cero. -En algún punto habrías comenzado con la definición de la función, tenías los parámetros listos... +En algún momento habrías empezado la definición de la función, tenías los parámetros listos... -Pero, luego tienes que llamar "ese método que convierte la primera letra en una mayúscula". +Pero luego tienes que llamar "ese método que convierte la primera letra a mayúscula". -Era `upper`? O era `uppercase`? `first_uppercase`? `capitalize`? +¿Era `upper`? ¿Era `uppercase`? `first_uppercase`? `capitalize`? -Luego lo intentas con el viejo amigo de los programadores, el auto-completado del editor. +Entonces, pruebas con el amigo del viejo programador, el autocompletado del editor. -Escribes el primer parámetro de la función `first_name`, luego un punto (`.`) y luego presionas `Ctrl+Space` para iniciar el auto-completado. +Escribes el primer parámetro de la función, `first_name`, luego un punto (`.`) y luego presionas `Ctrl+Espacio` para activar el autocompletado. -Tristemente, no obtienes nada útil: +Pero, tristemente, no obtienes nada útil: - + -### Añade tipos +### Añadir tipos -Vamos a modificar una única línea de la versión previa. +Modifiquemos una sola línea de la versión anterior. -Vamos a cambiar exactamente este fragmento, los parámetros de la función, de: +Cambiaremos exactamente este fragmento, los parámetros de la función, de: ```Python first_name, last_name @@ -77,210 +76,501 @@ a: Eso es todo. -Esos son los "type hints": +Esas son las "anotaciones de tipos": -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} -No es lo mismo a declarar valores por defecto, como sería con: +Eso no es lo mismo que declarar valores predeterminados como sería con: ```Python first_name="john", last_name="doe" ``` -Es algo diferente. +Es una cosa diferente. -Estamos usando los dos puntos (`:`), no un símbolo de igual (`=`). +Estamos usando dos puntos (`:`), no igualdades (`=`). -Añadir los type hints normalmente no cambia lo que sucedería si ellos no estuviesen presentes. +Y agregar anotaciones de tipos normalmente no cambia lo que sucede de lo que ocurriría sin ellas. -Pero ahora imagina que nuevamente estás creando la función, pero con los type hints. +Pero ahora, imagina que nuevamente estás en medio de la creación de esa función, pero con anotaciones de tipos. -En el mismo punto intentas iniciar el auto-completado con `Ctrl+Space` y ves: +En el mismo punto, intentas activar el autocompletado con `Ctrl+Espacio` y ves: - + -Con esto puedes moverte hacia abajo viendo las opciones hasta que encuentras una que te suene: +Con eso, puedes desplazarte, viendo las opciones, hasta que encuentres la que "te suene": - + ## Más motivación -Mira esta función que ya tiene type hints: +Revisa esta función, ya tiene anotaciones de tipos: -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} -Como el editor conoce el tipo de las variables no solo obtienes auto-completado, si no que también obtienes chequeo de errores: +Porque el editor conoce los tipos de las variables, no solo obtienes autocompletado, también obtienes chequeo de errores: - + -Ahora que sabes que tienes que arreglarlo convierte `age` a un string con `str(age)`: +Ahora sabes que debes corregirlo, convertir `age` a un string con `str(age)`: -```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} -## Declarando tipos +## Declaración de tipos -Acabas de ver el lugar principal para declarar los type hints. Como parámetros de las funciones. +Acabas de ver el lugar principal para declarar anotaciones de tipos. Como parámetros de función. -Este es también el lugar principal en que los usarías con **FastAPI**. +Este también es el lugar principal donde los utilizarías con **FastAPI**. ### Tipos simples -Puedes declarar todos los tipos estándar de Python, no solamente `str`. +Puedes declarar todos los tipos estándar de Python, no solo `str`. -Por ejemplo, puedes usar: +Puedes usar, por ejemplo: * `int` * `float` * `bool` * `bytes` -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + +### Tipos genéricos con parámetros de tipo + +Hay algunas estructuras de datos que pueden contener otros valores, como `dict`, `list`, `set` y `tuple`. Y los valores internos también pueden tener su propio tipo. + +Estos tipos que tienen tipos internos se denominan tipos "**genéricos**". Y es posible declararlos, incluso con sus tipos internos. + +Para declarar esos tipos y los tipos internos, puedes usar el módulo estándar de Python `typing`. Existe específicamente para soportar estas anotaciones de tipos. + +#### Versiones más recientes de Python + +La sintaxis que utiliza `typing` es **compatible** con todas las versiones, desde Python 3.6 hasta las versiones más recientes, incluyendo Python 3.9, Python 3.10, etc. + +A medida que avanza Python, las **versiones más recientes** vienen con soporte mejorado para estas anotaciones de tipos y en muchos casos ni siquiera necesitarás importar y usar el módulo `typing` para declarar las anotaciones de tipos. + +Si puedes elegir una versión más reciente de Python para tu proyecto, podrás aprovechar esa simplicidad adicional. + +En toda la documentación hay ejemplos compatibles con cada versión de Python (cuando hay una diferencia). + +Por ejemplo, "**Python 3.6+**" significa que es compatible con Python 3.6 o superior (incluyendo 3.7, 3.8, 3.9, 3.10, etc). Y "**Python 3.9+**" significa que es compatible con Python 3.9 o superior (incluyendo 3.10, etc). -### Tipos con sub-tipos +Si puedes usar las **últimas versiones de Python**, utiliza los ejemplos para la última versión, esos tendrán la **mejor y más simple sintaxis**, por ejemplo, "**Python 3.10+**". -Existen algunas estructuras de datos que pueden contener otros valores, como `dict`, `list`, `set` y `tuple`. Los valores internos pueden tener su propio tipo también. +#### Lista -Para declarar esos tipos y sub-tipos puedes usar el módulo estándar de Python `typing`. +Por ejemplo, vamos a definir una variable para ser una `list` de `str`. -Él existe específicamente para dar soporte a este tipo de type hints. +//// tab | Python 3.9+ -#### Listas +Declara la variable, con la misma sintaxis de dos puntos (`:`). -Por ejemplo, vamos a definir una variable para que sea una `list` compuesta de `str`. +Como tipo, pon `list`. + +Como la lista es un tipo que contiene algunos tipos internos, los pones entre corchetes: + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial006_py39.py!} +``` + +//// + +//// tab | Python 3.8+ De `typing`, importa `List` (con una `L` mayúscula): ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` -Declara la variable con la misma sintaxis de los dos puntos (`:`). +Declara la variable, con la misma sintaxis de dos puntos (`:`). -Pon `List` como el tipo. +Como tipo, pon el `List` que importaste de `typing`. -Como la lista es un tipo que permite tener un "sub-tipo" pones el sub-tipo en corchetes `[]`: +Como la lista es un tipo que contiene algunos tipos internos, los pones entre corchetes: ```Python hl_lines="4" -{!../../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` -Esto significa: la variable `items` es una `list` y cada uno de los ítems en esta lista es un `str`. +//// + +/// info | Información + +Esos tipos internos en los corchetes se denominan "parámetros de tipo". + +En este caso, `str` es el parámetro de tipo pasado a `List` (o `list` en Python 3.9 y superior). + +/// + +Eso significa: "la variable `items` es una `list`, y cada uno de los ítems en esta lista es un `str`". -Con esta declaración tu editor puede proveerte soporte inclusive mientras está procesando ítems de la lista. +/// tip | Consejo -Sin tipos el auto-completado en este tipo de estructura es casi imposible de lograr: +Si usas Python 3.9 o superior, no tienes que importar `List` de `typing`, puedes usar el mismo tipo `list` regular en su lugar. - +/// -Observa que la variable `item` es unos de los elementos en la lista `items`. +Al hacer eso, tu editor puede proporcionar soporte incluso mientras procesa elementos de la lista: -El editor aún sabe que es un `str` y provee soporte para ello. + -#### Tuples y Sets +Sin tipos, eso es casi imposible de lograr. + +Nota que la variable `item` es uno de los elementos en la lista `items`. + +Y aún así, el editor sabe que es un `str` y proporciona soporte para eso. + +#### Tuple y Set Harías lo mismo para declarar `tuple`s y `set`s: +//// tab | Python 3.9+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial007_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial007.py!} +{!> ../../docs_src/python_types/tutorial007.py!} ``` +//// + Esto significa: * La variable `items_t` es un `tuple` con 3 ítems, un `int`, otro `int`, y un `str`. -* La variable `items_s` es un `set` y cada uno de sus ítems es de tipo `bytes`. +* La variable `items_s` es un `set`, y cada uno de sus ítems es del tipo `bytes`. -#### Diccionarios (Dicts) +#### Dict -Para definir un `dict` le pasas 2 sub-tipos separados por comas. +Para definir un `dict`, pasas 2 parámetros de tipo, separados por comas. -El primer sub-tipo es para los keys del `dict`. +El primer parámetro de tipo es para las claves del `dict`. -El segundo sub-tipo es para los valores del `dict`: +El segundo parámetro de tipo es para los valores del `dict`: + +//// tab | Python 3.9+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial008_py39.py!} +``` + +//// + +//// tab | Python 3.8+ ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial008.py!} +{!> ../../docs_src/python_types/tutorial008.py!} ``` +//// + Esto significa: * La variable `prices` es un `dict`: - * Los keys de este `dict` son de tipo `str` (Digamos que son el nombre de cada ítem). - * Los valores de este `dict` son de tipo `float` (Digamos que son el precio de cada ítem). + * Las claves de este `dict` son del tipo `str` (digamos, el nombre de cada ítem). + * Los valores de este `dict` son del tipo `float` (digamos, el precio de cada ítem). + +#### Union + +Puedes declarar que una variable puede ser cualquier de **varios tipos**, por ejemplo, un `int` o un `str`. + +En Python 3.6 y posterior (incluyendo Python 3.10) puedes usar el tipo `Union` de `typing` y poner dentro de los corchetes los posibles tipos a aceptar. + +En Python 3.10 también hay una **nueva sintaxis** donde puedes poner los posibles tipos separados por una barra vertical (`|`). + +//// tab | Python 3.10+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial008b_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial008b.py!} +``` + +//// + +En ambos casos, esto significa que `item` podría ser un `int` o un `str`. + +#### Posiblemente `None` + +Puedes declarar que un valor podría tener un tipo, como `str`, pero que también podría ser `None`. + +En Python 3.6 y posteriores (incluyendo Python 3.10) puedes declararlo importando y usando `Optional` del módulo `typing`. + +```Python hl_lines="1 4" +{!../../docs_src/python_types/tutorial009.py!} +``` + +Usar `Optional[str]` en lugar de solo `str` te permitirá al editor ayudarte a detectar errores donde podrías estar asumiendo que un valor siempre es un `str`, cuando en realidad también podría ser `None`. + +`Optional[Something]` es realmente un atajo para `Union[Something, None]`, son equivalentes. + +Esto también significa que en Python 3.10, puedes usar `Something | None`: + +//// tab | Python 3.10+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial009_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial009.py!} +``` + +//// + +//// tab | Python 3.8+ alternative + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial009b.py!} +``` + +//// + +#### Uso de `Union` u `Optional` + +Si estás usando una versión de Python inferior a 3.10, aquí tienes un consejo desde mi punto de vista muy **subjetivo**: + +* 🚨 Evita usar `Optional[SomeType]` +* En su lugar ✨ **usa `Union[SomeType, None]`** ✨. + +Ambos son equivalentes y debajo son lo mismo, pero recomendaría `Union` en lugar de `Optional` porque la palabra "**opcional**" parecería implicar que el valor es opcional, y en realidad significa "puede ser `None`", incluso si no es opcional y aún es requerido. + +Creo que `Union[SomeType, None]` es más explícito sobre lo que significa. + +Se trata solo de las palabras y nombres. Pero esas palabras pueden afectar cómo tú y tus compañeros de equipo piensan sobre el código. + +Como ejemplo, tomemos esta función: + +{* ../../docs_src/python_types/tutorial009c.py hl[1,4] *} + +El parámetro `name` está definido como `Optional[str]`, pero **no es opcional**, no puedes llamar a la función sin el parámetro: + +```Python +say_hi() # ¡Oh, no, esto lanza un error! 😱 +``` + +El parámetro `name` sigue siendo **requerido** (no *opcional*) porque no tiene un valor predeterminado. Aún así, `name` acepta `None` como valor: + +```Python +say_hi(name=None) # Esto funciona, None es válido 🎉 +``` + +La buena noticia es que, una vez que estés en Python 3.10, no tendrás que preocuparte por eso, ya que podrás simplemente usar `|` para definir uniones de tipos: + +{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *} + +Y entonces no tendrás que preocuparte por nombres como `Optional` y `Union`. 😎 + +#### Tipos genéricos + +Estos tipos que toman parámetros de tipo en corchetes se llaman **Tipos Genéricos** o **Genéricos**, por ejemplo: + +//// tab | Python 3.10+ + +Puedes usar los mismos tipos integrados como genéricos (con corchetes y tipos dentro): + +* `list` +* `tuple` +* `set` +* `dict` + +Y lo mismo que con Python 3.8, desde el módulo `typing`: + +* `Union` +* `Optional` (lo mismo que con Python 3.8) +* ...y otros. + +En Python 3.10, como alternativa a usar los genéricos `Union` y `Optional`, puedes usar la barra vertical (`|`) para declarar uniones de tipos, eso es mucho mejor y más simple. + +//// + +//// tab | Python 3.9+ + +Puedes usar los mismos tipos integrados como genéricos (con corchetes y tipos dentro): + +* `list` +* `tuple` +* `set` +* `dict` + +Y lo mismo que con Python 3.8, desde el módulo `typing`: + +* `Union` +* `Optional` +* ...y otros. + +//// + +//// tab | Python 3.8+ + +* `List` +* `Tuple` +* `Set` +* `Dict` +* `Union` +* `Optional` +* ...y otros. + +//// ### Clases como tipos También puedes declarar una clase como el tipo de una variable. -Digamos que tienes una clase `Person`con un nombre: +Digamos que tienes una clase `Person`, con un nombre: + +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + +Luego puedes declarar una variable para que sea de tipo `Person`: + +{* ../../docs_src/python_types/tutorial010.py hl[6] *} -```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial009.py!} +Y luego, nuevamente, obtienes todo el soporte del editor: + + + +Nota que esto significa "`one_person` es una **instance** de la clase `Person`". + +No significa "`one_person` es la **clase** llamada `Person`". + +## Modelos Pydantic + +Pydantic es un paquete de Python para realizar la validación de datos. + +Declaras la "forma" de los datos como clases con atributos. + +Y cada atributo tiene un tipo. + +Entonces creas un instance de esa clase con algunos valores y validará los valores, los convertirá al tipo adecuado (si es el caso) y te dará un objeto con todos los datos. + +Y obtienes todo el soporte del editor con ese objeto resultante. + +Un ejemplo de la documentación oficial de Pydantic: + +//// tab | Python 3.10+ + +```Python +{!> ../../docs_src/python_types/tutorial011_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python +{!> ../../docs_src/python_types/tutorial011_py39.py!} ``` -Entonces puedes declarar una variable que sea de tipo `Person`: +//// + +//// tab | Python 3.8+ -```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial009.py!} +```Python +{!> ../../docs_src/python_types/tutorial011.py!} ``` -Una vez más tendrás todo el soporte del editor: +//// - +/// info | Información -## Modelos de Pydantic +Para saber más sobre Pydantic, revisa su documentación. -Pydantic es una library de Python para llevar a cabo validación de datos. +/// -Tú declaras la "forma" de los datos mediante clases con atributos. +**FastAPI** está completamente basado en Pydantic. -Cada atributo tiene un tipo. +Verás mucho más de todo esto en práctica en el [Tutorial - Guía del Usuario](tutorial/index.md){.internal-link target=_blank}. -Luego creas un instance de esa clase con algunos valores y Pydantic validará los valores, los convertirá al tipo apropiado (si ese es el caso) y te dará un objeto con todos los datos. +/// tip | Consejo -Y obtienes todo el soporte del editor con el objeto resultante. +Pydantic tiene un comportamiento especial cuando utilizas `Optional` o `Union[Something, None]` sin un valor por defecto, puedes leer más sobre ello en la documentación de Pydantic sobre Required Optional fields. -Tomado de la documentación oficial de Pydantic: +/// -```Python -{!../../../docs_src/python_types/tutorial010.py!} +## Anotaciones de tipos con metadata + +Python también tiene una funcionalidad que permite poner **metadata adicional** en estas anotaciones de tipos usando `Annotated`. + +//// tab | Python 3.9+ + +En Python 3.9, `Annotated` es parte de la librería estándar, así que puedes importarlo desde `typing`. + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial013_py39.py!} ``` -!!! info "Información" - Para aprender más sobre Pydantic mira su documentación. +//// + +//// tab | Python 3.8+ + +En versiones por debajo de Python 3.9, importas `Annotated` de `typing_extensions`. + +Ya estará instalado con **FastAPI**. + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial013.py!} +``` -**FastAPI** está todo basado en Pydantic. +//// -Vas a ver mucho más de esto en práctica en el [Tutorial - User Guide](tutorial/index.md){.internal-link target=_blank}. +Python en sí no hace nada con este `Annotated`. Y para los editores y otras herramientas, el tipo sigue siendo `str`. -## Type hints en **FastAPI** +Pero puedes usar este espacio en `Annotated` para proporcionar a **FastAPI** metadata adicional sobre cómo quieres que se comporte tu aplicación. -**FastAPI** aprovecha estos type hints para hacer varias cosas. +Lo importante a recordar es que **el primer *parámetro de tipo*** que pasas a `Annotated` es el **tipo real**. El resto es solo metadata para otras herramientas. -Con **FastAPI** declaras los parámetros con type hints y obtienes: +Por ahora, solo necesitas saber que `Annotated` existe, y que es Python estándar. 😎 -* **Soporte en el editor**. -* **Type checks**. +Luego verás lo **poderoso** que puede ser. + +/// tip | Consejo + +El hecho de que esto sea **Python estándar** significa que seguirás obteniendo la **mejor experiencia de desarrollador posible** en tu editor, con las herramientas que usas para analizar y refactorizar tu código, etc. ✨ + +Y también que tu código será muy compatible con muchas otras herramientas y paquetes de Python. 🚀 + +/// + +## Anotaciones de tipos en **FastAPI** + +**FastAPI** aprovecha estas anotaciones de tipos para hacer varias cosas. + +Con **FastAPI** declaras parámetros con anotaciones de tipos y obtienes: + +* **Soporte del editor**. +* **Chequeo de tipos**. ...y **FastAPI** usa las mismas declaraciones para: -* **Definir requerimientos**: desde request path parameters, query parameters, headers, bodies, dependencies, etc. -* **Convertir datos**: desde el request al tipo requerido. -* **Validar datos**: viniendo de cada request: +* **Definir requerimientos**: de parámetros de path de la request, parámetros de query, headers, bodies, dependencias, etc. +* **Convertir datos**: de la request al tipo requerido. +* **Validar datos**: provenientes de cada request: * Generando **errores automáticos** devueltos al cliente cuando los datos son inválidos. * **Documentar** la API usando OpenAPI: - * que en su caso es usada por las interfaces de usuario de la documentación automática e interactiva. + * Que luego es usada por las interfaces de documentación interactiva automática. + +Todo esto puede sonar abstracto. No te preocupes. Verás todo esto en acción en el [Tutorial - Guía del Usuario](tutorial/index.md){.internal-link target=_blank}. + +Lo importante es que al usar tipos estándar de Python, en un solo lugar (en lugar de agregar más clases, decoradores, etc.), **FastAPI** hará gran parte del trabajo por ti. -Puede que todo esto suene abstracto. Pero no te preocupes que todo lo verás en acción en el [Tutorial - User Guide](tutorial/index.md){.internal-link target=_blank}. +/// info | Información -Lo importante es que usando los tipos de Python estándar en un único lugar (en vez de añadir más clases, decorator, etc.) **FastAPI** hará mucho del trabajo por ti. +Si ya revisaste todo el tutorial y volviste para ver más sobre tipos, un buen recurso es la "cheat sheet" de `mypy`. -!!! info "Información" - Si ya pasaste por todo el tutorial y volviste a la sección de los tipos, una buena referencia es la "cheat sheet" de `mypy`. +/// diff --git a/docs/es/docs/tutorial/background-tasks.md b/docs/es/docs/tutorial/background-tasks.md new file mode 100644 index 000000000..3fe961e41 --- /dev/null +++ b/docs/es/docs/tutorial/background-tasks.md @@ -0,0 +1,84 @@ +# Tareas en Segundo Plano + +Puedes definir tareas en segundo plano para que se ejecuten *después* de devolver un response. + +Esto es útil para operaciones que necesitan ocurrir después de un request, pero para las que el cliente realmente no necesita esperar a que la operación termine antes de recibir el response. + +Esto incluye, por ejemplo: + +* Notificaciones por email enviadas después de realizar una acción: + * Como conectarse a un servidor de email y enviar un email tiende a ser "lento" (varios segundos), puedes devolver el response de inmediato y enviar la notificación por email en segundo plano. +* Procesamiento de datos: + * Por ejemplo, supongamos que recibes un archivo que debe pasar por un proceso lento, puedes devolver un response de "Accepted" (HTTP 202) y procesar el archivo en segundo plano. + +## Usando `BackgroundTasks` + +Primero, importa `BackgroundTasks` y define un parámetro en tu *path operation function* con una declaración de tipo de `BackgroundTasks`: + +{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *} + +**FastAPI** creará el objeto de tipo `BackgroundTasks` por ti y lo pasará como ese parámetro. + +## Crear una función de tarea + +Crea una función para que se ejecute como la tarea en segundo plano. + +Es solo una función estándar que puede recibir parámetros. + +Puede ser una función `async def` o una función normal `def`, **FastAPI** sabrá cómo manejarla correctamente. + +En este caso, la función de tarea escribirá en un archivo (simulando el envío de un email). + +Y como la operación de escritura no usa `async` y `await`, definimos la función con un `def` normal: + +{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *} + +## Agregar la tarea en segundo plano + +Dentro de tu *path operation function*, pasa tu función de tarea al objeto de *background tasks* con el método `.add_task()`: + +{* ../../docs_src/background_tasks/tutorial001.py hl[14] *} + +`.add_task()` recibe como argumentos: + +* Una función de tarea para ejecutar en segundo plano (`write_notification`). +* Cualquier secuencia de argumentos que deba pasarse a la función de tarea en orden (`email`). +* Cualquier argumento de palabras clave que deba pasarse a la función de tarea (`message="some notification"`). + +## Inyección de Dependencias + +Usar `BackgroundTasks` también funciona con el sistema de inyección de dependencias, puedes declarar un parámetro de tipo `BackgroundTasks` en varios niveles: en una *path operation function*, en una dependencia (dependable), en una sub-dependencia, etc. + +**FastAPI** sabe qué hacer en cada caso y cómo reutilizar el mismo objeto, de modo que todas las tareas en segundo plano se combinan y ejecutan en segundo plano después: + +{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13,15,22,25] *} + +En este ejemplo, los mensajes se escribirán en el archivo `log.txt` *después* de que se envíe el response. + +Si hay un query en el request, se escribirá en el log en una tarea en segundo plano. + +Y luego otra tarea en segundo plano generada en la *path operation function* escribirá un mensaje usando el parámetro de path `email`. + +## Detalles Técnicos + +La clase `BackgroundTasks` proviene directamente de `starlette.background`. + +Se importa/incluye directamente en FastAPI para que puedas importarla desde `fastapi` y evitar importar accidentalmente la alternativa `BackgroundTask` (sin la `s` al final) de `starlette.background`. + +Al usar solo `BackgroundTasks` (y no `BackgroundTask`), es posible usarla como un parámetro de *path operation function* y dejar que **FastAPI** maneje el resto por ti, tal como cuando usas el objeto `Request` directamente. + +Todavía es posible usar `BackgroundTask` solo en FastAPI, pero debes crear el objeto en tu código y devolver una `Response` de Starlette incluyéndolo. + +Puedes ver más detalles en la documentación oficial de Starlette sobre Background Tasks. + +## Advertencia + +Si necesitas realizar una computación intensa en segundo plano y no necesariamente necesitas que se ejecute por el mismo proceso (por ejemplo, no necesitas compartir memoria, variables, etc.), podrías beneficiarte del uso de otras herramientas más grandes como Celery. + +Tienden a requerir configuraciones más complejas, un gestor de cola de mensajes/trabajos, como RabbitMQ o Redis, pero te permiten ejecutar tareas en segundo plano en múltiples procesos, y especialmente, en múltiples servidores. + +Pero si necesitas acceder a variables y objetos de la misma app de **FastAPI**, o necesitas realizar pequeñas tareas en segundo plano (como enviar una notificación por email), simplemente puedes usar `BackgroundTasks`. + +## Resumen + +Importa y usa `BackgroundTasks` con parámetros en *path operation functions* y dependencias para agregar tareas en segundo plano. diff --git a/docs/es/docs/tutorial/bigger-applications.md b/docs/es/docs/tutorial/bigger-applications.md new file mode 100644 index 000000000..78165ef05 --- /dev/null +++ b/docs/es/docs/tutorial/bigger-applications.md @@ -0,0 +1,554 @@ +# Aplicaciones más grandes - Múltiples archivos + +Si estás construyendo una aplicación o una API web, rara vez podrás poner todo en un solo archivo. + +**FastAPI** proporciona una herramienta conveniente para estructurar tu aplicación manteniendo toda la flexibilidad. + +/// info | Información + +Si vienes de Flask, esto sería el equivalente a los Blueprints de Flask. + +/// + +## Un ejemplo de estructura de archivos + +Digamos que tienes una estructura de archivos como esta: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   ├── dependencies.py +│   └── routers +│   │ ├── __init__.py +│   │ ├── items.py +│   │ └── users.py +│   └── internal +│   ├── __init__.py +│   └── admin.py +``` + +/// tip | Consejo + +Hay varios archivos `__init__.py`: uno en cada directorio o subdirectorio. + +Esto es lo que permite importar código de un archivo a otro. + +Por ejemplo, en `app/main.py` podrías tener una línea como: + +``` +from app.routers import items +``` + +/// + +* El directorio `app` contiene todo. Y tiene un archivo vacío `app/__init__.py`, por lo que es un "paquete de Python" (una colección de "módulos de Python"): `app`. +* Contiene un archivo `app/main.py`. Como está dentro de un paquete de Python (un directorio con un archivo `__init__.py`), es un "módulo" de ese paquete: `app.main`. +* También hay un archivo `app/dependencies.py`, al igual que `app/main.py`, es un "módulo": `app.dependencies`. +* Hay un subdirectorio `app/routers/` con otro archivo `__init__.py`, por lo que es un "subpaquete de Python": `app.routers`. +* El archivo `app/routers/items.py` está dentro de un paquete, `app/routers/`, por lo que es un submódulo: `app.routers.items`. +* Lo mismo con `app/routers/users.py`, es otro submódulo: `app.routers.users`. +* También hay un subdirectorio `app/internal/` con otro archivo `__init__.py`, por lo que es otro "subpaquete de Python": `app.internal`. +* Y el archivo `app/internal/admin.py` es otro submódulo: `app.internal.admin`. + + + +La misma estructura de archivos con comentarios: + +``` +. +├── app # "app" es un paquete de Python +│   ├── __init__.py # este archivo hace que "app" sea un "paquete de Python" +│   ├── main.py # módulo "main", por ejemplo import app.main +│   ├── dependencies.py # módulo "dependencies", por ejemplo import app.dependencies +│   └── routers # "routers" es un "subpaquete de Python" +│   │ ├── __init__.py # hace que "routers" sea un "subpaquete de Python" +│   │ ├── items.py # submódulo "items", por ejemplo import app.routers.items +│   │ └── users.py # submódulo "users", por ejemplo import app.routers.users +│   └── internal # "internal" es un "subpaquete de Python" +│   ├── __init__.py # hace que "internal" sea un "subpaquete de Python" +│   └── admin.py # submódulo "admin", por ejemplo import app.internal.admin +``` + +## `APIRouter` + +Digamos que el archivo dedicado solo a manejar usuarios es el submódulo en `/app/routers/users.py`. + +Quieres tener las *path operations* relacionadas con tus usuarios separadas del resto del código, para mantenerlo organizado. + +Pero todavía es parte de la misma aplicación/web API de **FastAPI** (es parte del mismo "paquete de Python"). + +Puedes crear las *path operations* para ese módulo usando `APIRouter`. + +### Importar `APIRouter` + +Lo importas y creas una "instance" de la misma manera que lo harías con la clase `FastAPI`: + +```Python hl_lines="1 3" title="app/routers/users.py" +{!../../docs_src/bigger_applications/app/routers/users.py!} +``` + +### *Path operations* con `APIRouter` + +Y luego lo usas para declarar tus *path operations*. + +Úsalo de la misma manera que usarías la clase `FastAPI`: + +```Python hl_lines="6 11 16" title="app/routers/users.py" +{!../../docs_src/bigger_applications/app/routers/users.py!} +``` + +Puedes pensar en `APIRouter` como una clase "mini `FastAPI`". + +Se soportan todas las mismas opciones. + +Todos los mismos `parameters`, `responses`, `dependencies`, `tags`, etc. + +/// tip | Consejo + +En este ejemplo, la variable se llama `router`, pero puedes nombrarla como quieras. + +/// + +Vamos a incluir este `APIRouter` en la aplicación principal de `FastAPI`, pero primero, revisemos las dependencias y otro `APIRouter`. + +## Dependencias + +Vemos que vamos a necesitar algunas dependencias usadas en varios lugares de la aplicación. + +Así que las ponemos en su propio módulo `dependencies` (`app/dependencies.py`). + +Ahora utilizaremos una dependencia simple para leer un encabezado `X-Token` personalizado: + +//// tab | Python 3.9+ + +```Python hl_lines="3 6-8" title="app/dependencies.py" +{!> ../../docs_src/bigger_applications/app_an_py39/dependencies.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 5-7" title="app/dependencies.py" +{!> ../../docs_src/bigger_applications/app_an/dependencies.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Consejo + +Preferiblemente usa la versión `Annotated` si es posible. + +/// + +```Python hl_lines="1 4-6" title="app/dependencies.py" +{!> ../../docs_src/bigger_applications/app/dependencies.py!} +``` + +//// + +/// tip | Consejo + +Estamos usando un encabezado inventado para simplificar este ejemplo. + +Pero en casos reales obtendrás mejores resultados usando las [utilidades de Seguridad](security/index.md){.internal-link target=_blank} integradas. + +/// + +## Otro módulo con `APIRouter` + +Digamos que también tienes los endpoints dedicados a manejar "items" de tu aplicación en el módulo `app/routers/items.py`. + +Tienes *path operations* para: + +* `/items/` +* `/items/{item_id}` + +Es toda la misma estructura que con `app/routers/users.py`. + +Pero queremos ser más inteligentes y simplificar un poco el código. + +Sabemos que todas las *path operations* en este módulo tienen el mismo: + +* Prefijo de path: `/items`. +* `tags`: (solo una etiqueta: `items`). +* `responses` extra. +* `dependencies`: todas necesitan esa dependencia `X-Token` que creamos. + +Entonces, en lugar de agregar todo eso a cada *path operation*, podemos agregarlo al `APIRouter`. + +```Python hl_lines="5-10 16 21" title="app/routers/items.py" +{!../../docs_src/bigger_applications/app/routers/items.py!} +``` + +Como el path de cada *path operation* tiene que empezar con `/`, como en: + +```Python hl_lines="1" +@router.get("/{item_id}") +async def read_item(item_id: str): + ... +``` + +...el prefijo no debe incluir un `/` final. + +Así que, el prefijo en este caso es `/items`. + +También podemos agregar una lista de `tags` y `responses` extra que se aplicarán a todas las *path operations* incluidas en este router. + +Y podemos agregar una lista de `dependencies` que se añadirá a todas las *path operations* en el router y se ejecutarán/solucionarán por cada request que les haga. + +/// tip | Consejo + +Nota que, al igual que [dependencias en decoradores de *path operations*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, ningún valor será pasado a tu *path operation function*. + +/// + +El resultado final es que los paths de item son ahora: + +* `/items/` +* `/items/{item_id}` + +...como pretendíamos. + +* Serán marcados con una lista de tags que contiene un solo string `"items"`. + * Estos "tags" son especialmente útiles para los sistemas de documentación interactiva automática (usando OpenAPI). +* Todos incluirán las `responses` predefinidas. +* Todas estas *path operations* tendrán la lista de `dependencies` evaluadas/ejecutadas antes de ellas. + * Si también declaras dependencias en una *path operation* específica, **también se ejecutarán**. + * Las dependencias del router se ejecutan primero, luego las [dependencias en el decorador](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, y luego las dependencias de parámetros normales. + * También puedes agregar [dependencias de `Security` con `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}. + +/// tip | Consejo + +Tener `dependencies` en el `APIRouter` puede ser usado, por ejemplo, para requerir autenticación para un grupo completo de *path operations*. Incluso si las dependencias no son añadidas individualmente a cada una de ellas. + +/// + +/// check | Revisa + +Los parámetros `prefix`, `tags`, `responses`, y `dependencies` son (como en muchos otros casos) solo una funcionalidad de **FastAPI** para ayudarte a evitar la duplicación de código. + +/// + +### Importar las dependencias + +Este código vive en el módulo `app.routers.items`, el archivo `app/routers/items.py`. + +Y necesitamos obtener la función de dependencia del módulo `app.dependencies`, el archivo `app/dependencies.py`. + +Así que usamos un import relativo con `..` para las dependencias: + +```Python hl_lines="3" title="app/routers/items.py" +{!../../docs_src/bigger_applications/app/routers/items.py!} +``` + +#### Cómo funcionan los imports relativos + +/// tip | Consejo + +Si sabes perfectamente cómo funcionan los imports, continúa a la siguiente sección. + +/// + +Un solo punto `.`, como en: + +```Python +from .dependencies import get_token_header +``` + +significaría: + +* Partiendo en el mismo paquete en el que este módulo (el archivo `app/routers/items.py`) habita (el directorio `app/routers/`)... +* busca el módulo `dependencies` (un archivo imaginario en `app/routers/dependencies.py`)... +* y de él, importa la función `get_token_header`. + +Pero ese archivo no existe, nuestras dependencias están en un archivo en `app/dependencies.py`. + +Recuerda cómo se ve nuestra estructura de aplicación/archivo: + + + +--- + +Los dos puntos `..`, como en: + +```Python +from ..dependencies import get_token_header +``` + +significan: + +* Partiendo en el mismo paquete en el que este módulo (el archivo `app/routers/items.py`) habita (el directorio `app/routers/`)... +* ve al paquete padre (el directorio `app/`)... +* y allí, busca el módulo `dependencies` (el archivo en `app/dependencies.py`)... +* y de él, importa la función `get_token_header`. + +¡Eso funciona correctamente! 🎉 + +--- + +De la misma manera, si hubiéramos usado tres puntos `...`, como en: + +```Python +from ...dependencies import get_token_header +``` + +eso significaría: + +* Partiendo en el mismo paquete en el que este módulo (el archivo `app/routers/items.py`) habita (el directorio `app/routers/`)... +* ve al paquete padre (el directorio `app/`)... +* luego ve al paquete padre de ese paquete (no hay paquete padre, `app` es el nivel superior 😱)... +* y allí, busca el módulo `dependencies` (el archivo en `app/dependencies.py`)... +* y de él, importa la función `get_token_header`. + +Eso se referiría a algún paquete arriba de `app/`, con su propio archivo `__init__.py`, etc. Pero no tenemos eso. Así que, eso lanzaría un error en nuestro ejemplo. 🚨 + +Pero ahora sabes cómo funciona, para que puedas usar imports relativos en tus propias aplicaciones sin importar cuán complejas sean. 🤓 + +### Agregar algunos `tags`, `responses`, y `dependencies` personalizados + +No estamos agregando el prefijo `/items` ni los `tags=["items"]` a cada *path operation* porque los hemos añadido al `APIRouter`. + +Pero aún podemos agregar _más_ `tags` que se aplicarán a una *path operation* específica, y también algunas `responses` extra específicas para esa *path operation*: + +```Python hl_lines="30-31" title="app/routers/items.py" +{!../../docs_src/bigger_applications/app/routers/items.py!} +``` + +/// tip | Consejo + +Esta última *path operation* tendrá la combinación de tags: `["items", "custom"]`. + +Y también tendrá ambas responses en la documentación, una para `404` y otra para `403`. + +/// + +## El `FastAPI` principal + +Ahora, veamos el módulo en `app/main.py`. + +Aquí es donde importas y usas la clase `FastAPI`. + +Este será el archivo principal en tu aplicación que conecta todo. + +### Importar `FastAPI` + +Importas y creas una clase `FastAPI` como de costumbre. + +Y podemos incluso declarar [dependencias globales](dependencies/global-dependencies.md){.internal-link target=_blank} que se combinarán con las dependencias para cada `APIRouter`: + +```Python hl_lines="1 3 7" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +### Importar el `APIRouter` + +Ahora importamos los otros submódulos que tienen `APIRouter`s: + +```Python hl_lines="4-5" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +Como los archivos `app/routers/users.py` y `app/routers/items.py` son submódulos que son parte del mismo paquete de Python `app`, podemos usar un solo punto `.` para importarlos usando "imports relativos". + +### Cómo funciona la importación + +La sección: + +```Python +from .routers import items, users +``` + +significa: + +* Partiendo en el mismo paquete en el que este módulo (el archivo `app/main.py`) habita (el directorio `app/`)... +* busca el subpaquete `routers` (el directorio en `app/routers/`)... +* y de él, importa el submódulo `items` (el archivo en `app/routers/items.py`) y `users` (el archivo en `app/routers/users.py`)... + +El módulo `items` tendrá una variable `router` (`items.router`). Este es el mismo que creamos en el archivo `app/routers/items.py`, es un objeto `APIRouter`. + +Y luego hacemos lo mismo para el módulo `users`. + +También podríamos importarlos así: + +```Python +from app.routers import items, users +``` + +/// info | Información + +La primera versión es un "import relativo": + +```Python +from .routers import items, users +``` + +La segunda versión es un "import absoluto": + +```Python +from app.routers import items, users +``` + +Para aprender más sobre Paquetes y Módulos de Python, lee la documentación oficial de Python sobre Módulos. + +/// + +### Evitar colisiones de nombres + +Estamos importando el submódulo `items` directamente, en lugar de importar solo su variable `router`. + +Esto se debe a que también tenemos otra variable llamada `router` en el submódulo `users`. + +Si hubiéramos importado uno después del otro, como: + +```Python +from .routers.items import router +from .routers.users import router +``` + +el `router` de `users` sobrescribiría el de `items` y no podríamos usarlos al mismo tiempo. + +Así que, para poder usar ambos en el mismo archivo, importamos los submódulos directamente: + +```Python hl_lines="5" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +### Incluir los `APIRouter`s para `users` y `items` + +Ahora, incluyamos los `router`s de los submódulos `users` y `items`: + +```Python hl_lines="10-11" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +/// info | Información + +`users.router` contiene el `APIRouter` dentro del archivo `app/routers/users.py`. + +Y `items.router` contiene el `APIRouter` dentro del archivo `app/routers/items.py`. + +/// + +Con `app.include_router()` podemos agregar cada `APIRouter` a la aplicación principal de `FastAPI`. + +Incluirá todas las rutas de ese router como parte de ella. + +/// note | Detalles Técnicos + +En realidad creará internamente una *path operation* para cada *path operation* que fue declarada en el `APIRouter`. + +Así, detrás de escena, funcionará como si todo fuera la misma única aplicación. + +/// + +/// check | Revisa + +No tienes que preocuparte por el rendimiento al incluir routers. + +Esto tomará microsegundos y solo sucederá al inicio. + +Así que no afectará el rendimiento. ⚡ + +/// + +### Incluir un `APIRouter` con un `prefix`, `tags`, `responses`, y `dependencies` personalizados + +Ahora, imaginemos que tu organización te dio el archivo `app/internal/admin.py`. + +Contiene un `APIRouter` con algunas *path operations* de administración que tu organización comparte entre varios proyectos. + +Para este ejemplo será súper simple. Pero digamos que porque está compartido con otros proyectos en la organización, no podemos modificarlo y agregar un `prefix`, `dependencies`, `tags`, etc. directamente al `APIRouter`: + +```Python hl_lines="3" title="app/internal/admin.py" +{!../../docs_src/bigger_applications/app/internal/admin.py!} +``` + +Pero aún queremos configurar un `prefix` personalizado al incluir el `APIRouter` para que todas sus *path operations* comiencen con `/admin`, queremos asegurarlo con las `dependencies` que ya tenemos para este proyecto, y queremos incluir `tags` y `responses`. + +Podemos declarar todo eso sin tener que modificar el `APIRouter` original pasando esos parámetros a `app.include_router()`: + +```Python hl_lines="14-17" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +De esa manera, el `APIRouter` original permanecerá sin modificar, por lo que aún podemos compartir ese mismo archivo `app/internal/admin.py` con otros proyectos en la organización. + +El resultado es que, en nuestra aplicación, cada una de las *path operations* del módulo `admin` tendrá: + +* El prefix `/admin`. +* El tag `admin`. +* La dependencia `get_token_header`. +* La response `418`. 🍵 + +Pero eso solo afectará a ese `APIRouter` en nuestra aplicación, no en ningún otro código que lo utilice. + +Así, por ejemplo, otros proyectos podrían usar el mismo `APIRouter` con un método de autenticación diferente. + +### Incluir una *path operation* + +También podemos agregar *path operations* directamente a la aplicación de `FastAPI`. + +Aquí lo hacemos... solo para mostrar que podemos 🤷: + +```Python hl_lines="21-23" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +y funcionará correctamente, junto con todas las otras *path operations* añadidas con `app.include_router()`. + +/// info | Detalles Muy Técnicos + +**Nota**: este es un detalle muy técnico que probablemente puedes **simplemente omitir**. + +--- + +Los `APIRouter`s no están "montados", no están aislados del resto de la aplicación. + +Esto se debe a que queremos incluir sus *path operations* en el esquema de OpenAPI y las interfaces de usuario. + +Como no podemos simplemente aislarlos y "montarlos" independientemente del resto, se "clonan" las *path operations* (se vuelven a crear), no se incluyen directamente. + +/// + +## Revisa la documentación automática de la API + +Ahora, ejecuta tu aplicación: + +
+ +```console +$ fastapi dev app/main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Y abre la documentación en http://127.0.0.1:8000/docs. + +Verás la documentación automática de la API, incluyendo los paths de todos los submódulos, usando los paths correctos (y prefijos) y las tags correctas: + + + +## Incluir el mismo router múltiples veces con diferentes `prefix` + +También puedes usar `.include_router()` múltiples veces con el *mismo* router usando diferentes prefijos. + +Esto podría ser útil, por ejemplo, para exponer la misma API bajo diferentes prefijos, por ejemplo, `/api/v1` y `/api/latest`. + +Este es un uso avanzado que quizás no necesites realmente, pero está allí en caso de que lo necesites. + +## Incluir un `APIRouter` en otro + +De la misma manera que puedes incluir un `APIRouter` en una aplicación `FastAPI`, puedes incluir un `APIRouter` en otro `APIRouter` usando: + +```Python +router.include_router(other_router) +``` + +Asegúrate de hacerlo antes de incluir `router` en la aplicación de `FastAPI`, para que las *path operations* de `other_router` también se incluyan. diff --git a/docs/es/docs/tutorial/body-fields.md b/docs/es/docs/tutorial/body-fields.md new file mode 100644 index 000000000..d07d214ec --- /dev/null +++ b/docs/es/docs/tutorial/body-fields.md @@ -0,0 +1,60 @@ +# Body - Campos + +De la misma manera que puedes declarar validaciones adicionales y metadatos en los parámetros de las *path operation function* con `Query`, `Path` y `Body`, puedes declarar validaciones y metadatos dentro de los modelos de Pydantic usando `Field` de Pydantic. + +## Importar `Field` + +Primero, tienes que importarlo: + +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *} + +/// warning | Advertencia + +Fíjate que `Field` se importa directamente desde `pydantic`, no desde `fastapi` como el resto (`Query`, `Path`, `Body`, etc). + +/// + +## Declarar atributos del modelo + +Después puedes utilizar `Field` con los atributos del modelo: + +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *} + +`Field` funciona de la misma manera que `Query`, `Path` y `Body`, tiene todos los mismos parámetros, etc. + +/// note | Detalles técnicos + +En realidad, `Query`, `Path` y otros que verás a continuación crean objetos de subclases de una clase común `Param`, que es a su vez una subclase de la clase `FieldInfo` de Pydantic. + +Y `Field` de Pydantic también regresa una instance de `FieldInfo`. + +`Body` también devuelve objetos de una subclase de `FieldInfo` directamente. Y hay otros que verás más adelante que son subclases de la clase `Body`. + +Recuerda que cuando importas `Query`, `Path`, y otros desde `fastapi`, en realidad son funciones que devuelven clases especiales. + +/// + +/// tip | Consejo + +Observa cómo cada atributo del modelo con un tipo, un valor por defecto y `Field` tiene la misma estructura que un parámetro de una *path operation function*, con `Field` en lugar de `Path`, `Query` y `Body`. + +/// + +## Agregar información extra + +Puedes declarar información extra en `Field`, `Query`, `Body`, etc. Y será incluida en el JSON Schema generado. + +Aprenderás más sobre cómo agregar información extra más adelante en la documentación, cuando aprendamos a declarar ejemplos. + +/// warning | Advertencia + +Las claves extra pasadas a `Field` también estarán presentes en el esquema de OpenAPI resultante para tu aplicación. +Como estas claves no necesariamente tienen que ser parte de la especificación de OpenAPI, algunas herramientas de OpenAPI, por ejemplo [el validador de OpenAPI](https://validator.swagger.io/), podrían no funcionar con tu esquema generado. + +/// + +## Resumen + +Puedes utilizar `Field` de Pydantic para declarar validaciones adicionales y metadatos para los atributos del modelo. + +También puedes usar los argumentos de palabra clave extra para pasar metadatos adicionales del JSON Schema. diff --git a/docs/es/docs/tutorial/body-multiple-params.md b/docs/es/docs/tutorial/body-multiple-params.md new file mode 100644 index 000000000..df6560b62 --- /dev/null +++ b/docs/es/docs/tutorial/body-multiple-params.md @@ -0,0 +1,173 @@ +# Cuerpo - Múltiples Parámetros + +Ahora que hemos visto cómo usar `Path` y `Query`, veamos usos más avanzados de las declaraciones del request body. + +## Mezclar `Path`, `Query` y parámetros del cuerpo + +Primero, por supuesto, puedes mezclar las declaraciones de parámetros de `Path`, `Query` y del request body libremente y **FastAPI** sabrá qué hacer. + +Y también puedes declarar parámetros del cuerpo como opcionales, estableciendo el valor predeterminado a `None`: + +{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *} + +## Múltiples parámetros del cuerpo + +/// note | Nota + +Ten en cuenta que, en este caso, el `item` que se tomaría del cuerpo es opcional. Ya que tiene un valor por defecto de `None`. + +/// + +## Múltiples parámetros del cuerpo + +En el ejemplo anterior, las *path operations* esperarían un cuerpo JSON con los atributos de un `Item`, como: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +Pero también puedes declarar múltiples parámetros del cuerpo, por ejemplo `item` y `user`: + +{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *} + +En este caso, **FastAPI** notará que hay más de un parámetro del cuerpo en la función (hay dos parámetros que son modelos de Pydantic). + +Entonces, usará los nombres de los parámetros como claves (nombres de campo) en el cuerpo, y esperará un cuerpo como: + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + } +} +``` + +/// note | Nota + +Ten en cuenta que aunque el `item` se declaró de la misma manera que antes, ahora se espera que esté dentro del cuerpo con una clave `item`. + +/// + +**FastAPI** hará la conversión automática del request, de modo que el parámetro `item` reciba su contenido específico y lo mismo para `user`. + +Realizará la validación de los datos compuestos, y los documentará así para el esquema de OpenAPI y la documentación automática. + +## Valores singulares en el cuerpo + +De la misma manera que hay un `Query` y `Path` para definir datos extra para parámetros de query y path, **FastAPI** proporciona un equivalente `Body`. + +Por ejemplo, ampliando el modelo anterior, podrías decidir que deseas tener otra clave `importance` en el mismo cuerpo, además de `item` y `user`. + +Si lo declaras tal cual, debido a que es un valor singular, **FastAPI** asumirá que es un parámetro de query. + +Pero puedes instruir a **FastAPI** para que lo trate como otra clave del cuerpo usando `Body`: + +{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *} + +En este caso, **FastAPI** esperará un cuerpo como: + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + }, + "importance": 5 +} +``` + +Nuevamente, convertirá los tipos de datos, validará, documentará, etc. + +## Múltiples parámetros de cuerpo y query + +Por supuesto, también puedes declarar parámetros adicionales de query siempre que lo necesites, además de cualquier parámetro del cuerpo. + +Como, por defecto, los valores singulares se interpretan como parámetros de query, no tienes que añadir explícitamente un `Query`, solo puedes hacer: + +```Python +q: Union[str, None] = None +``` + +O en Python 3.10 y superior: + +```Python +q: str | None = None +``` + +Por ejemplo: + +{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *} + +/// info | Información + +`Body` también tiene todos los mismos parámetros de validación y metadatos extras que `Query`, `Path` y otros que verás luego. + +/// + +## Embeber un solo parámetro de cuerpo + +Supongamos que solo tienes un único parámetro de cuerpo `item` de un modelo Pydantic `Item`. + +Por defecto, **FastAPI** esperará su cuerpo directamente. + +Pero si deseas que espere un JSON con una clave `item` y dentro de ella los contenidos del modelo, como lo hace cuando declaras parámetros de cuerpo extra, puedes usar el parámetro especial `Body` `embed`: + +```Python +item: Item = Body(embed=True) +``` + +como en: + +{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *} + +En este caso, **FastAPI** esperará un cuerpo como: + +```JSON hl_lines="2" +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + } +} +``` + +en lugar de: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +## Resumen + +Puedes añadir múltiples parámetros de cuerpo a tu *path operation function*, aunque un request solo puede tener un único cuerpo. + +Pero **FastAPI** lo manejará, te dará los datos correctos en tu función, y validará y documentará el esquema correcto en la *path operation*. + +También puedes declarar valores singulares para ser recibidos como parte del cuerpo. + +Y puedes instruir a **FastAPI** para embeber el cuerpo en una clave incluso cuando solo hay un único parámetro declarado. diff --git a/docs/es/docs/tutorial/body-nested-models.md b/docs/es/docs/tutorial/body-nested-models.md new file mode 100644 index 000000000..5b4cfc14c --- /dev/null +++ b/docs/es/docs/tutorial/body-nested-models.md @@ -0,0 +1,247 @@ +# Cuerpo - Modelos Anidados + +Con **FastAPI**, puedes definir, validar, documentar y usar modelos anidados de manera arbitraria (gracias a Pydantic). + +## Campos de lista + +Puedes definir un atributo como un subtipo. Por ejemplo, una `list` en Python: + +{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *} + +Esto hará que `tags` sea una lista, aunque no declare el tipo de los elementos de la lista. + +## Campos de lista con parámetro de tipo + +Pero Python tiene una forma específica de declarar listas con tipos internos, o "parámetros de tipo": + +### Importar `List` de typing + +En Python 3.9 y superior, puedes usar el `list` estándar para declarar estas anotaciones de tipo como veremos a continuación. 💡 + +Pero en versiones de Python anteriores a 3.9 (desde 3.6 en adelante), primero necesitas importar `List` del módulo `typing` estándar de Python: + +{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *} + +### Declarar una `list` con un parámetro de tipo + +Para declarar tipos que tienen parámetros de tipo (tipos internos), como `list`, `dict`, `tuple`: + +* Si estás en una versión de Python inferior a 3.9, importa su versión equivalente del módulo `typing` +* Pasa el/los tipo(s) interno(s) como "parámetros de tipo" usando corchetes: `[` y `]` + +En Python 3.9 sería: + +```Python +my_list: list[str] +``` + +En versiones de Python anteriores a 3.9, sería: + +```Python +from typing import List + +my_list: List[str] +``` + +Eso es toda la sintaxis estándar de Python para declaraciones de tipo. + +Usa esa misma sintaxis estándar para atributos de modelos con tipos internos. + +Así, en nuestro ejemplo, podemos hacer que `tags` sea específicamente una "lista de strings": + +{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *} + +## Tipos de conjunto + +Pero luego pensamos en ello, y nos damos cuenta de que los tags no deberían repetirse, probablemente serían strings únicos. + +Y Python tiene un tipo de datos especial para conjuntos de elementos únicos, el `set`. + +Entonces podemos declarar `tags` como un conjunto de strings: + +{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *} + +Con esto, incluso si recibes un request con datos duplicados, se convertirá en un conjunto de elementos únicos. + +Y siempre que emitas esos datos, incluso si la fuente tenía duplicados, se emitirá como un conjunto de elementos únicos. + +Y también se anotará/documentará en consecuencia. + +## Modelos Anidados + +Cada atributo de un modelo Pydantic tiene un tipo. + +Pero ese tipo puede ser en sí mismo otro modelo Pydantic. + +Así que, puedes declarar "objetos" JSON anidados profundamente con nombres de atributos específicos, tipos y validaciones. + +Todo eso, de manera arbitraria. + +### Definir un submodelo + +Por ejemplo, podemos definir un modelo `Image`: + +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *} + +### Usar el submodelo como tipo + +Y luego podemos usarlo como el tipo de un atributo: + +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *} + +Esto significaría que **FastAPI** esperaría un cuerpo similar a: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2, + "tags": ["rock", "metal", "bar"], + "image": { + "url": "http://example.com/baz.jpg", + "name": "The Foo live" + } +} +``` + +Nuevamente, haciendo solo esa declaración, con **FastAPI** obtienes: + +* Soporte de editor (autocompletado, etc.), incluso para modelos anidados +* Conversión de datos +* Validación de datos +* Documentación automática + +## Tipos especiales y validación + +Además de tipos singulares normales como `str`, `int`, `float`, etc., puedes usar tipos singulares más complejos que heredan de `str`. + +Para ver todas las opciones que tienes, revisa el Overview de Tipos de Pydantic. Verás algunos ejemplos en el siguiente capítulo. + +Por ejemplo, como en el modelo `Image` tenemos un campo `url`, podemos declararlo como una instance de `HttpUrl` de Pydantic en lugar de un `str`: + +{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *} + +El string será verificado para ser una URL válida, y documentado en JSON Schema / OpenAPI como tal. + +## Atributos con listas de submodelos + +También puedes usar modelos Pydantic como subtipos de `list`, `set`, etc.: + +{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *} + +Esto esperará (convertirá, validará, documentará, etc.) un cuerpo JSON como: + +```JSON hl_lines="11" +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2, + "tags": [ + "rock", + "metal", + "bar" + ], + "images": [ + { + "url": "http://example.com/baz.jpg", + "name": "The Foo live" + }, + { + "url": "http://example.com/dave.jpg", + "name": "The Baz" + } + ] +} +``` + +/// info | Información + +Nota cómo la clave `images` ahora tiene una lista de objetos de imagen. + +/// + +## Modelos anidados profundamente + +Puedes definir modelos anidados tan profundamente como desees: + +{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *} + +/// info | Información + +Observa cómo `Offer` tiene una lista de `Item`s, que a su vez tienen una lista opcional de `Image`s + +/// + +## Cuerpos de listas puras + +Si el valor superior del cuerpo JSON que esperas es un `array` JSON (una `list` en Python), puedes declarar el tipo en el parámetro de la función, al igual que en los modelos Pydantic: + +```Python +images: List[Image] +``` + +o en Python 3.9 y superior: + +```Python +images: list[Image] +``` + +como en: + +{* ../../docs_src/body_nested_models/tutorial008_py39.py hl[13] *} + +## Soporte de editor en todas partes + +Y obtienes soporte de editor en todas partes. + +Incluso para elementos dentro de listas: + + + +No podrías obtener este tipo de soporte de editor si estuvieras trabajando directamente con `dict` en lugar de modelos Pydantic. + +Pero tampoco tienes que preocuparte por ellos, los `dicts` entrantes se convierten automáticamente y tu salida se convierte automáticamente a JSON también. + +## Cuerpos de `dict`s arbitrarios + +También puedes declarar un cuerpo como un `dict` con claves de algún tipo y valores de algún otro tipo. + +De esta manera, no tienes que saber de antemano cuáles son los nombres válidos de campo/atributo (como sería el caso con modelos Pydantic). + +Esto sería útil si deseas recibir claves que aún no conoces. + +--- + +Otro caso útil es cuando deseas tener claves de otro tipo (por ejemplo, `int`). + +Eso es lo que vamos a ver aquí. + +En este caso, aceptarías cualquier `dict` siempre que tenga claves `int` con valores `float`: + +{* ../../docs_src/body_nested_models/tutorial009_py39.py hl[7] *} + +/// tip | Consejo + +Ten en cuenta que JSON solo admite `str` como claves. + +Pero Pydantic tiene conversión automática de datos. + +Esto significa que, aunque tus clientes de API solo pueden enviar strings como claves, mientras esos strings contengan enteros puros, Pydantic los convertirá y validará. + +Y el `dict` que recibas como `weights` tendrá realmente claves `int` y valores `float`. + +/// + +## Resumen + +Con **FastAPI** tienes la máxima flexibilidad proporcionada por los modelos Pydantic, manteniendo tu código simple, corto y elegante. + +Pero con todos los beneficios: + +* Soporte de editor (¡autocompletado en todas partes!) +* Conversión de datos (también conocido como parsing/serialización) +* Validación de datos +* Documentación del esquema +* Documentación automática diff --git a/docs/es/docs/tutorial/body-updates.md b/docs/es/docs/tutorial/body-updates.md new file mode 100644 index 000000000..26cd3345f --- /dev/null +++ b/docs/es/docs/tutorial/body-updates.md @@ -0,0 +1,116 @@ +# Cuerpo - Actualizaciones + +## Actualización reemplazando con `PUT` + +Para actualizar un ítem puedes utilizar la operación de HTTP `PUT`. + +Puedes usar el `jsonable_encoder` para convertir los datos de entrada en datos que se puedan almacenar como JSON (por ejemplo, con una base de datos NoSQL). Por ejemplo, convirtiendo `datetime` a `str`. + +{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *} + +`PUT` se usa para recibir datos que deben reemplazar los datos existentes. + +### Advertencia sobre el reemplazo + +Esto significa que si quieres actualizar el ítem `bar` usando `PUT` con un body que contenga: + +```Python +{ + "name": "Barz", + "price": 3, + "description": None, +} +``` + +debido a que no incluye el atributo ya almacenado `"tax": 20.2`, el modelo de entrada tomaría el valor por defecto de `"tax": 10.5`. + +Y los datos se guardarían con ese "nuevo" `tax` de `10.5`. + +## Actualizaciones parciales con `PATCH` + +También puedes usar la operación de HTTP `PATCH` para actualizar *parcialmente* datos. + +Esto significa que puedes enviar solo los datos que deseas actualizar, dejando el resto intacto. + +/// note | Nota + +`PATCH` es menos usado y conocido que `PUT`. + +Y muchos equipos utilizan solo `PUT`, incluso para actualizaciones parciales. + +Eres **libre** de usarlos como desees, **FastAPI** no impone ninguna restricción. + +Pero esta guía te muestra, más o menos, cómo se pretende que se usen. + +/// + +### Uso del parámetro `exclude_unset` de Pydantic + +Si quieres recibir actualizaciones parciales, es muy útil usar el parámetro `exclude_unset` en el `.model_dump()` del modelo de Pydantic. + +Como `item.model_dump(exclude_unset=True)`. + +/// info | Información + +En Pydantic v1 el método se llamaba `.dict()`, fue deprecado (pero aún soportado) en Pydantic v2, y renombrado a `.model_dump()`. + +Los ejemplos aquí usan `.dict()` para compatibilidad con Pydantic v1, pero deberías usar `.model_dump()` si puedes usar Pydantic v2. + +/// + +Eso generaría un `dict` solo con los datos que se establecieron al crear el modelo `item`, excluyendo los valores por defecto. + +Luego puedes usar esto para generar un `dict` solo con los datos que se establecieron (enviados en el request), omitiendo los valores por defecto: + +{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *} + +### Uso del parámetro `update` de Pydantic + +Ahora, puedes crear una copia del modelo existente usando `.model_copy()`, y pasar el parámetro `update` con un `dict` que contenga los datos a actualizar. + +/// info | Información + +En Pydantic v1 el método se llamaba `.copy()`, fue deprecado (pero aún soportado) en Pydantic v2, y renombrado a `.model_copy()`. + +Los ejemplos aquí usan `.copy()` para compatibilidad con Pydantic v1, pero deberías usar `.model_copy()` si puedes usar Pydantic v2. + +/// + +Como `stored_item_model.model_copy(update=update_data)`: + +{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *} + +### Resumen de actualizaciones parciales + +En resumen, para aplicar actualizaciones parciales deberías: + +* (Opcionalmente) usar `PATCH` en lugar de `PUT`. +* Recuperar los datos almacenados. +* Poner esos datos en un modelo de Pydantic. +* Generar un `dict` sin valores por defecto del modelo de entrada (usando `exclude_unset`). + * De esta manera puedes actualizar solo los valores realmente establecidos por el usuario, en lugar de sobrescribir valores ya almacenados con valores por defecto en tu modelo. +* Crear una copia del modelo almacenado, actualizando sus atributos con las actualizaciones parciales recibidas (usando el parámetro `update`). +* Convertir el modelo copiado en algo que pueda almacenarse en tu base de datos (por ejemplo, usando el `jsonable_encoder`). + * Esto es comparable a usar el método `.model_dump()` del modelo de nuevo, pero asegura (y convierte) los valores a tipos de datos que pueden convertirse a JSON, por ejemplo, `datetime` a `str`. +* Guardar los datos en tu base de datos. +* Devolver el modelo actualizado. + +{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *} + +/// tip | Consejo + +Puedes realmente usar esta misma técnica con una operación HTTP `PUT`. + +Pero el ejemplo aquí usa `PATCH` porque fue creado para estos casos de uso. + +/// + +/// note | Nota + +Observa que el modelo de entrada sigue siendo validado. + +Entonces, si deseas recibir actualizaciones parciales que puedan omitir todos los atributos, necesitas tener un modelo con todos los atributos marcados como opcionales (con valores por defecto o `None`). + +Para distinguir entre los modelos con todos los valores opcionales para **actualizaciones** y modelos con valores requeridos para **creación**, puedes utilizar las ideas descritas en [Modelos Extra](extra-models.md){.internal-link target=_blank}. + +/// diff --git a/docs/es/docs/tutorial/body.md b/docs/es/docs/tutorial/body.md new file mode 100644 index 000000000..6d0aa7c60 --- /dev/null +++ b/docs/es/docs/tutorial/body.md @@ -0,0 +1,164 @@ +# Request Body + +Cuando necesitas enviar datos desde un cliente (digamos, un navegador) a tu API, los envías como un **request body**. + +Un **request** body es un dato enviado por el cliente a tu API. Un **response** body es el dato que tu API envía al cliente. + +Tu API casi siempre tiene que enviar un **response** body. Pero los clientes no necesariamente necesitan enviar **request bodies** todo el tiempo, a veces solo solicitan un path, quizás con algunos parámetros de query, pero no envían un body. + +Para declarar un **request** body, usas modelos de Pydantic con todo su poder y beneficios. + +/// info | Información + +Para enviar datos, deberías usar uno de estos métodos: `POST` (el más común), `PUT`, `DELETE` o `PATCH`. + +Enviar un body con un request `GET` tiene un comportamiento indefinido en las especificaciones, no obstante, es soportado por FastAPI, solo para casos de uso muy complejos/extremos. + +Como no se recomienda, la documentación interactiva con Swagger UI no mostrará la documentación para el body cuando se usa `GET`, y los proxies intermedios podrían no soportarlo. + +/// + +## Importar `BaseModel` de Pydantic + +Primero, necesitas importar `BaseModel` de `pydantic`: + +{* ../../docs_src/body/tutorial001_py310.py hl[2] *} + +## Crea tu modelo de datos + +Luego, declaras tu modelo de datos como una clase que hereda de `BaseModel`. + +Usa tipos estándar de Python para todos los atributos: + +{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *} + +Al igual que al declarar parámetros de query, cuando un atributo del modelo tiene un valor por defecto, no es obligatorio. De lo contrario, es obligatorio. Usa `None` para hacerlo opcional. + +Por ejemplo, el modelo anterior declara un “`object`” JSON (o `dict` en Python) como: + +```JSON +{ + "name": "Foo", + "description": "An optional description", + "price": 45.2, + "tax": 3.5 +} +``` + +...dado que `description` y `tax` son opcionales (con un valor por defecto de `None`), este “`object`” JSON también sería válido: + +```JSON +{ + "name": "Foo", + "price": 45.2 +} +``` + +## Decláralo como un parámetro + +Para añadirlo a tu *path operation*, decláralo de la misma manera que declaraste parámetros de path y query: + +{* ../../docs_src/body/tutorial001_py310.py hl[16] *} + +...y declara su tipo como el modelo que creaste, `Item`. + +## Resultados + +Con solo esa declaración de tipo en Python, **FastAPI** hará lo siguiente: + +* Leer el body del request como JSON. +* Convertir los tipos correspondientes (si es necesario). +* Validar los datos. + * Si los datos son inválidos, devolverá un error claro e indicado, señalando exactamente dónde y qué fue lo incorrecto. +* Proporcionar los datos recibidos en el parámetro `item`. + * Como lo declaraste en la función como de tipo `Item`, también tendrás todo el soporte del editor (autocompletado, etc.) para todos los atributos y sus tipos. +* Generar definiciones de JSON Schema para tu modelo, que también puedes usar en cualquier otro lugar si tiene sentido para tu proyecto. +* Esquemas que serán parte del esquema de OpenAPI generado y usados por la UIs de documentación automática. + +## Documentación automática + +Los JSON Schemas de tus modelos serán parte del esquema OpenAPI generado y se mostrarán en la documentación API interactiva: + + + +Y también se utilizarán en la documentación API dentro de cada *path operation* que los necesite: + + + +## Soporte del editor + +En tu editor, dentro de tu función, obtendrás anotaciones de tipos y autocompletado en todas partes (esto no sucedería si recibieras un `dict` en lugar de un modelo de Pydantic): + + + +También recibirás chequeos de errores para operaciones de tipo incorrecto: + + + +No es por casualidad, todo el framework fue construido alrededor de ese diseño. + +Y fue rigurosamente probado en la fase de diseño, antes de cualquier implementación, para garantizar que funcionaría con todos los editores. + +Incluso se hicieron algunos cambios en Pydantic para admitir esto. + +Las capturas de pantalla anteriores se tomaron con Visual Studio Code. + +Pero obtendrías el mismo soporte en el editor con PyCharm y la mayoría de los otros editores de Python: + + + +/// tip | Consejo + +Si usas PyCharm como tu editor, puedes usar el Pydantic PyCharm Plugin. + +Mejora el soporte del editor para modelos de Pydantic, con: + +* autocompletado +* chequeo de tipos +* refactorización +* búsqueda +* inspecciones + +/// + +## Usa el modelo + +Dentro de la función, puedes acceder a todos los atributos del objeto modelo directamente: + +{* ../../docs_src/body/tutorial002_py310.py *} + +## Request body + parámetros de path + +Puedes declarar parámetros de path y request body al mismo tiempo. + +**FastAPI** reconocerá que los parámetros de función que coinciden con los parámetros de path deben ser **tomados del path**, y que los parámetros de función que se declaran como modelos de Pydantic deben ser **tomados del request body**. + +{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *} + +## Request body + path + parámetros de query + +También puedes declarar parámetros de **body**, **path** y **query**, todos al mismo tiempo. + +**FastAPI** reconocerá cada uno de ellos y tomará los datos del lugar correcto. + +{* ../../docs_src/body/tutorial004_py310.py hl[16] *} + +Los parámetros de la función se reconocerán de la siguiente manera: + +* Si el parámetro también se declara en el **path**, se utilizará como un parámetro de path. +* Si el parámetro es de un **tipo singular** (como `int`, `float`, `str`, `bool`, etc.), se interpretará como un parámetro de **query**. +* Si el parámetro se declara como del tipo de un **modelo de Pydantic**, se interpretará como un **request body**. + +/// note | Nota + +FastAPI sabrá que el valor de `q` no es requerido debido al valor por defecto `= None`. + +El `str | None` (Python 3.10+) o `Union` en `Union[str, None]` (Python 3.8+) no es utilizado por FastAPI para determinar que el valor no es requerido, sabrá que no es requerido porque tiene un valor por defecto de `= None`. + +Pero agregar las anotaciones de tipos permitirá que tu editor te brinde un mejor soporte y detecte errores. + +/// + +## Sin Pydantic + +Si no quieres usar modelos de Pydantic, también puedes usar parámetros **Body**. Consulta la documentación para [Body - Multiples Parametros: Valores singulares en body](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}. diff --git a/docs/es/docs/tutorial/cookie-param-models.md b/docs/es/docs/tutorial/cookie-param-models.md new file mode 100644 index 000000000..ebdb59265 --- /dev/null +++ b/docs/es/docs/tutorial/cookie-param-models.md @@ -0,0 +1,76 @@ +# Modelos de Cookies + +Si tienes un grupo de **cookies** que están relacionadas, puedes crear un **modelo de Pydantic** para declararlas. 🍪 + +Esto te permitirá **reutilizar el modelo** en **múltiples lugares** y también declarar validaciones y metadatos para todos los parámetros a la vez. 😎 + +/// note | Nota + +Esto es compatible desde la versión `0.115.0` de FastAPI. 🤓 + +/// + +/// tip | Consejo + +Esta misma técnica se aplica a `Query`, `Cookie`, y `Header`. 😎 + +/// + +## Cookies con un Modelo de Pydantic + +Declara los parámetros de **cookie** que necesites en un **modelo de Pydantic**, y luego declara el parámetro como `Cookie`: + +{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *} + +**FastAPI** **extraerá** los datos para **cada campo** de las **cookies** recibidas en el request y te entregará el modelo de Pydantic que definiste. + +## Revisa la Documentación + +Puedes ver las cookies definidas en la UI de la documentación en `/docs`: + +
+ +
+ +/// info | Información + +Ten en cuenta que, como los **navegadores manejan las cookies** de maneras especiales y detrás de escenas, **no** permiten fácilmente que **JavaScript** las toque. + +Si vas a la **UI de la documentación de la API** en `/docs` podrás ver la **documentación** de las cookies para tus *path operations*. + +Pero incluso si **rellenas los datos** y haces clic en "Execute", como la UI de la documentación funciona con **JavaScript**, las cookies no serán enviadas y verás un **mensaje de error** como si no hubieras escrito ningún valor. + +/// + +## Prohibir Cookies Extra + +En algunos casos de uso especiales (probablemente no muy comunes), podrías querer **restringir** las cookies que deseas recibir. + +Tu API ahora tiene el poder de controlar su propio consentimiento de cookies. 🤪🍪 + +Puedes usar la configuración del modelo de Pydantic para `prohibir` cualquier campo `extra`: + +{* ../../docs_src/cookie_param_models/tutorial002_an_py39.py hl[10] *} + +Si un cliente intenta enviar algunas **cookies extra**, recibirán un response de **error**. + +Pobres banners de cookies con todo su esfuerzo para obtener tu consentimiento para que la API lo rechace. 🍪 + +Por ejemplo, si el cliente intenta enviar una cookie `santa_tracker` con un valor de `good-list-please`, el cliente recibirá un response de **error** que le informa que la cookie `santa_tracker` no está permitida: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["cookie", "santa_tracker"], + "msg": "Extra inputs are not permitted", + "input": "good-list-please", + } + ] +} +``` + +## Resumen + +Puedes usar **modelos de Pydantic** para declarar **cookies** en **FastAPI**. 😎 diff --git a/docs/es/docs/tutorial/cookie-params.md b/docs/es/docs/tutorial/cookie-params.md new file mode 100644 index 000000000..45b113ff9 --- /dev/null +++ b/docs/es/docs/tutorial/cookie-params.md @@ -0,0 +1,35 @@ +# Parámetros de Cookie + +Puedes definir parámetros de Cookie de la misma manera que defines los parámetros `Query` y `Path`. + +## Importar `Cookie` + +Primero importa `Cookie`: + +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[3] *} + +## Declarar parámetros de `Cookie` + +Luego declara los parámetros de cookie usando la misma estructura que con `Path` y `Query`. + +Puedes definir el valor por defecto así como toda la validación extra o los parámetros de anotación: + +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9] *} + +/// note | Detalles Técnicos + +`Cookie` es una clase "hermana" de `Path` y `Query`. También hereda de la misma clase común `Param`. + +Pero recuerda que cuando importas `Query`, `Path`, `Cookie` y otros desde `fastapi`, en realidad son funciones que devuelven clases especiales. + +/// + +/// info | Información + +Para declarar cookies, necesitas usar `Cookie`, porque de lo contrario los parámetros serían interpretados como parámetros de query. + +/// + +## Resumen + +Declara cookies con `Cookie`, usando el mismo patrón común que `Query` y `Path`. diff --git a/docs/es/docs/tutorial/cors.md b/docs/es/docs/tutorial/cors.md new file mode 100644 index 000000000..e493d4431 --- /dev/null +++ b/docs/es/docs/tutorial/cors.md @@ -0,0 +1,85 @@ +# CORS (Cross-Origin Resource Sharing) + +CORS o "Cross-Origin Resource Sharing" se refiere a situaciones en las que un frontend que se ejecuta en un navegador tiene código JavaScript que se comunica con un backend, y el backend está en un "origen" diferente al frontend. + +## Origen + +Un origen es la combinación de protocolo (`http`, `https`), dominio (`myapp.com`, `localhost`, `localhost.tiangolo.com`) y puerto (`80`, `443`, `8080`). + +Así que, todos estos son orígenes diferentes: + +* `http://localhost` +* `https://localhost` +* `http://localhost:8080` + +Aunque todos están en `localhost`, usan protocolos o puertos diferentes, por lo tanto, son "orígenes" diferentes. + +## Pasos + +Entonces, digamos que tienes un frontend corriendo en tu navegador en `http://localhost:8080`, y su JavaScript está tratando de comunicarse con un backend corriendo en `http://localhost` (porque no especificamos un puerto, el navegador asumirá el puerto por defecto `80`). + +Entonces, el navegador enviará un request HTTP `OPTIONS` al backend `:80`, y si el backend envía los headers apropiados autorizando la comunicación desde este origen diferente (`http://localhost:8080`), entonces el navegador `:8080` permitirá que el JavaScript en el frontend envíe su request al backend `:80`. + +Para lograr esto, el backend `:80` debe tener una lista de "orígenes permitidos". + +En este caso, la lista tendría que incluir `http://localhost:8080` para que el frontend `:8080` funcione correctamente. + +## Comodines + +También es posible declarar la lista como `"*"` (un "comodín") para decir que todos están permitidos. + +Pero eso solo permitirá ciertos tipos de comunicación, excluyendo todo lo que implique credenciales: Cookies, headers de autorización como los utilizados con Bearer Tokens, etc. + +Así que, para que todo funcione correctamente, es mejor especificar explícitamente los orígenes permitidos. + +## Usa `CORSMiddleware` + +Puedes configurarlo en tu aplicación **FastAPI** usando el `CORSMiddleware`. + +* Importa `CORSMiddleware`. +* Crea una lista de orígenes permitidos (como strings). +* Agrégalo como un "middleware" a tu aplicación **FastAPI**. + +También puedes especificar si tu backend permite: + +* Credenciales (headers de autorización, cookies, etc). +* Métodos HTTP específicos (`POST`, `PUT`) o todos ellos con el comodín `"*"`. +* Headers HTTP específicos o todos ellos con el comodín `"*"`. + +{* ../../docs_src/cors/tutorial001.py hl[2,6:11,13:19] *} + +Los parámetros predeterminados utilizados por la implementación de `CORSMiddleware` son restrictivos por defecto, por lo que necesitarás habilitar explícitamente orígenes, métodos o headers particulares para que los navegadores estén permitidos de usarlos en un contexto de Cross-Domain. + +Se admiten los siguientes argumentos: + +* `allow_origins` - Una lista de orígenes que deberían estar permitidos para hacer requests cross-origin. Por ejemplo, `['https://example.org', 'https://www.example.org']`. Puedes usar `['*']` para permitir cualquier origen. +* `allow_origin_regex` - Una cadena regex para coincidir con orígenes que deberían estar permitidos para hacer requests cross-origin. por ejemplo, `'https://.*\.example\.org'`. +* `allow_methods` - Una lista de métodos HTTP que deberían estar permitidos para requests cross-origin. Por defecto es `['GET']`. Puedes usar `['*']` para permitir todos los métodos estándar. +* `allow_headers` - Una lista de headers de request HTTP que deberían estar soportados para requests cross-origin. Por defecto es `[]`. Puedes usar `['*']` para permitir todos los headers. Los headers `Accept`, `Accept-Language`, `Content-Language` y `Content-Type` siempre están permitidos para requests CORS simples. +* `allow_credentials` - Indica que las cookies deberían estar soportadas para requests cross-origin. Por defecto es `False`. Además, `allow_origins` no puede ser configurado a `['*']` para que las credenciales estén permitidas, los orígenes deben ser especificados. +* `expose_headers` - Indica cualquier header de response que debería ser accesible para el navegador. Por defecto es `[]`. +* `max_age` - Establece un tiempo máximo en segundos para que los navegadores almacenen en caché los responses CORS. Por defecto es `600`. + +El middleware responde a dos tipos particulares de request HTTP... + +### Requests de preflight CORS + +Estos son cualquier request `OPTIONS` con headers `Origin` y `Access-Control-Request-Method`. + +En este caso, el middleware interceptará el request entrante y responderá con los headers CORS adecuados, y un response `200` o `400` con fines informativos. + +### Requests simples + +Cualquier request con un header `Origin`. En este caso, el middleware pasará el request a través de lo normal, pero incluirá los headers CORS adecuados en el response. + +## Más info + +Para más información sobre CORS, revisa la documentación de CORS de Mozilla. + +/// note | Detalles Técnicos + +También podrías usar `from starlette.middleware.cors import CORSMiddleware`. + +**FastAPI** proporciona varios middlewares en `fastapi.middleware` como una conveniencia para ti, el desarrollador. Pero la mayoría de los middlewares disponibles provienen directamente de Starlette. + +/// diff --git a/docs/es/docs/tutorial/debugging.md b/docs/es/docs/tutorial/debugging.md new file mode 100644 index 000000000..2a7544e83 --- /dev/null +++ b/docs/es/docs/tutorial/debugging.md @@ -0,0 +1,113 @@ +# Depuración + +Puedes conectar el depurador en tu editor, por ejemplo con Visual Studio Code o PyCharm. + +## Llama a `uvicorn` + +En tu aplicación de FastAPI, importa y ejecuta `uvicorn` directamente: + +{* ../../docs_src/debugging/tutorial001.py hl[1,15] *} + +### Acerca de `__name__ == "__main__"` + +El objetivo principal de `__name__ == "__main__"` es tener algo de código que se ejecute cuando tu archivo es llamado con: + +
+ +```console +$ python myapp.py +``` + +
+ +pero no es llamado cuando otro archivo lo importa, como en: + +```Python +from myapp import app +``` + +#### Más detalles + +Supongamos que tu archivo se llama `myapp.py`. + +Si lo ejecutas con: + +
+ +```console +$ python myapp.py +``` + +
+ +entonces la variable interna `__name__` en tu archivo, creada automáticamente por Python, tendrá como valor el string `"__main__"`. + +Así que, la sección: + +```Python + uvicorn.run(app, host="0.0.0.0", port=8000) +``` + +se ejecutará. + +--- + +Esto no ocurrirá si importas ese módulo (archivo). + +Entonces, si tienes otro archivo `importer.py` con: + +```Python +from myapp import app + +# Algún código adicional +``` + +en ese caso, la variable creada automáticamente dentro de `myapp.py` no tendrá la variable `__name__` con un valor de `"__main__"`. + +Así que, la línea: + +```Python + uvicorn.run(app, host="0.0.0.0", port=8000) +``` + +no se ejecutará. + +/// info | Información + +Para más información, revisa la documentación oficial de Python. + +/// + +## Ejecuta tu código con tu depurador + +Dado que estás ejecutando el servidor Uvicorn directamente desde tu código, puedes llamar a tu programa de Python (tu aplicación FastAPI) directamente desde el depurador. + +--- + +Por ejemplo, en Visual Studio Code, puedes: + +* Ir al panel de "Debug". +* "Add configuration...". +* Seleccionar "Python". +* Ejecutar el depurador con la opción "`Python: Current File (Integrated Terminal)`". + +Luego, iniciará el servidor con tu código **FastAPI**, deteniéndose en tus puntos de interrupción, etc. + +Así es como podría verse: + + + +--- + +Si usas PyCharm, puedes: + +* Abrir el menú "Run". +* Seleccionar la opción "Debug...". +* Luego aparece un menú contextual. +* Selecciona el archivo para depurar (en este caso, `main.py`). + +Luego, iniciará el servidor con tu código **FastAPI**, deteniéndose en tus puntos de interrupción, etc. + +Así es como podría verse: + + diff --git a/docs/es/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/es/docs/tutorial/dependencies/classes-as-dependencies.md new file mode 100644 index 000000000..d0868240e --- /dev/null +++ b/docs/es/docs/tutorial/dependencies/classes-as-dependencies.md @@ -0,0 +1,288 @@ +# Clases como dependencias + +Antes de profundizar en el sistema de **Inyección de Dependencias**, vamos a mejorar el ejemplo anterior. + +## Un `dict` del ejemplo anterior + +En el ejemplo anterior, estábamos devolviendo un `dict` de nuestra dependencia ("dependable"): + +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[9] *} + +Pero luego obtenemos un `dict` en el parámetro `commons` de la *path operation function*. + +Y sabemos que los editores no pueden proporcionar mucho soporte (como autocompletado) para `dict`s, porque no pueden conocer sus claves y tipos de valor. + +Podemos hacerlo mejor... + +## Qué hace a una dependencia + +Hasta ahora has visto dependencias declaradas como funciones. + +Pero esa no es la única forma de declarar dependencias (aunque probablemente sea la más común). + +El factor clave es que una dependencia debe ser un "callable". + +Un "**callable**" en Python es cualquier cosa que Python pueda "llamar" como una función. + +Entonces, si tienes un objeto `something` (que podría _no_ ser una función) y puedes "llamarlo" (ejecutarlo) como: + +```Python +something() +``` + +o + +```Python +something(some_argument, some_keyword_argument="foo") +``` + +entonces es un "callable". + +## Clases como dependencias + +Puedes notar que para crear una instance de una clase en Python, utilizas esa misma sintaxis. + +Por ejemplo: + +```Python +class Cat: + def __init__(self, name: str): + self.name = name + + +fluffy = Cat(name="Mr Fluffy") +``` + +En este caso, `fluffy` es una instance de la clase `Cat`. + +Y para crear `fluffy`, estás "llamando" a `Cat`. + +Entonces, una clase en Python también es un **callable**. + +Entonces, en **FastAPI**, podrías usar una clase de Python como una dependencia. + +Lo que **FastAPI** realmente comprueba es que sea un "callable" (función, clase o cualquier otra cosa) y los parámetros definidos. + +Si pasas un "callable" como dependencia en **FastAPI**, analizará los parámetros de ese "callable", y los procesará de la misma manera que los parámetros de una *path operation function*. Incluyendo sub-dependencias. + +Eso también se aplica a los callables sin parámetros. Igual que sería para *path operation functions* sin parámetros. + +Entonces, podemos cambiar la dependencia "dependable" `common_parameters` de arriba a la clase `CommonQueryParams`: + +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[11:15] *} + +Presta atención al método `__init__` usado para crear la instance de la clase: + +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[12] *} + +...tiene los mismos parámetros que nuestros `common_parameters` anteriores: + +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8] *} + +Esos parámetros son los que **FastAPI** usará para "resolver" la dependencia. + +En ambos casos, tendrá: + +* Un parámetro de query `q` opcional que es un `str`. +* Un parámetro de query `skip` que es un `int`, con un valor por defecto de `0`. +* Un parámetro de query `limit` que es un `int`, con un valor por defecto de `100`. + +En ambos casos, los datos serán convertidos, validados, documentados en el esquema de OpenAPI, etc. + +## Úsalo + +Ahora puedes declarar tu dependencia usando esta clase. + +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[19] *} + +**FastAPI** llama a la clase `CommonQueryParams`. Esto crea una "instance" de esa clase y la instance será pasada como el parámetro `commons` a tu función. + +## Anotación de tipos vs `Depends` + +Nota cómo escribimos `CommonQueryParams` dos veces en el código anterior: + +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// + +//// tab | Python 3.8+ sin `Annotated` + +/// tip | Consejo + +Prefiere usar la versión `Annotated` si es posible. + +/// + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// + +El último `CommonQueryParams`, en: + +```Python +... Depends(CommonQueryParams) +``` + +...es lo que **FastAPI** utilizará realmente para saber cuál es la dependencia. + +Es a partir de este que **FastAPI** extraerá los parámetros declarados y es lo que **FastAPI** realmente llamará. + +--- + +En este caso, el primer `CommonQueryParams`, en: + +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, ... +``` + +//// + +//// tab | Python 3.8+ sin `Annotated` + +/// tip | Consejo + +Prefiere usar la versión `Annotated` si es posible. + +/// + +```Python +commons: CommonQueryParams ... +``` + +//// + +...no tiene ningún significado especial para **FastAPI**. **FastAPI** no lo usará para la conversión de datos, validación, etc. (ya que está usando `Depends(CommonQueryParams)` para eso). + +De hecho, podrías escribir simplemente: + +//// tab | Python 3.8+ + +```Python +commons: Annotated[Any, Depends(CommonQueryParams)] +``` + +//// + +//// tab | Python 3.8+ sin `Annotated` + +/// tip | Consejo + +Prefiere usar la versión `Annotated` si es posible. + +/// + +```Python +commons = Depends(CommonQueryParams) +``` + +//// + +...como en: + +{* ../../docs_src/dependencies/tutorial003_an_py310.py hl[19] *} + +Pero declarar el tipo es recomendable, ya que de esa manera tu editor sabrá lo que se pasará como el parámetro `commons`, y entonces podrá ayudarte con el autocompletado, chequeo de tipos, etc: + + + +## Atajo + +Pero ves que estamos teniendo algo de repetición de código aquí, escribiendo `CommonQueryParams` dos veces: + +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// + +//// tab | Python 3.8+ sin `Annotated` + +/// tip | Consejo + +Prefiere usar la versión `Annotated` si es posible. + +/// + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// + +**FastAPI** proporciona un atajo para estos casos, en donde la dependencia es *específicamente* una clase que **FastAPI** "llamará" para crear una instance de la clase misma. + +Para esos casos específicos, puedes hacer lo siguiente: + +En lugar de escribir: + +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// + +//// tab | Python 3.8+ sin `Annotated` + +/// tip | Consejo + +Prefiere usar la versión `Annotated` si es posible. + +/// + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// + +...escribes: + +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, Depends()] +``` + +//// + +//// tab | Python 3.8 sin `Annotated` + +/// tip | Consejo + +Prefiere usar la versión `Annotated` si es posible. + +/// + +```Python +commons: CommonQueryParams = Depends() +``` + +//// + +Declaras la dependencia como el tipo del parámetro, y usas `Depends()` sin ningún parámetro, en lugar de tener que escribir la clase completa *otra vez* dentro de `Depends(CommonQueryParams)`. + +El mismo ejemplo se vería entonces así: + +{* ../../docs_src/dependencies/tutorial004_an_py310.py hl[19] *} + +...y **FastAPI** sabrá qué hacer. + +/// tip | Consejo + +Si eso parece más confuso que útil, ignóralo, no lo *necesitas*. + +Es solo un atajo. Porque a **FastAPI** le importa ayudarte a minimizar la repetición de código. + +/// diff --git a/docs/es/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/es/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md new file mode 100644 index 000000000..fbe17c67a --- /dev/null +++ b/docs/es/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -0,0 +1,69 @@ +# Dependencias en decoradores de *path operation* + +En algunos casos realmente no necesitas el valor de retorno de una dependencia dentro de tu *path operation function*. + +O la dependencia no devuelve un valor. + +Pero aún necesitas que sea ejecutada/resuelta. + +Para esos casos, en lugar de declarar un parámetro de *path operation function* con `Depends`, puedes añadir una `list` de `dependencies` al decorador de *path operation*. + +## Agregar `dependencies` al decorador de *path operation* + +El decorador de *path operation* recibe un argumento opcional `dependencies`. + +Debe ser una `list` de `Depends()`: + +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[19] *} + +Estas dependencias serán ejecutadas/resueltas de la misma manera que las dependencias normales. Pero su valor (si devuelven alguno) no será pasado a tu *path operation function*. + +/// tip | Consejo + +Algunos editores revisan los parámetros de función no usados y los muestran como errores. + +Usando estas `dependencies` en el decorador de *path operation* puedes asegurarte de que se ejecutan mientras evitas errores en editores/herramientas. + +También puede ayudar a evitar confusiones para nuevos desarrolladores que vean un parámetro no usado en tu código y puedan pensar que es innecesario. + +/// + +/// info | Información + +En este ejemplo usamos headers personalizados inventados `X-Key` y `X-Token`. + +Pero en casos reales, al implementar seguridad, obtendrías más beneficios usando las [Utilidades de Seguridad integradas (el próximo capítulo)](../security/index.md){.internal-link target=_blank}. + +/// + +## Errores de dependencias y valores de retorno + +Puedes usar las mismas *funciones* de dependencia que usas normalmente. + +### Requisitos de dependencia + +Pueden declarar requisitos de request (como headers) u otras sub-dependencias: + +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[8,13] *} + +### Lanzar excepciones + +Estas dependencias pueden `raise` excepciones, igual que las dependencias normales: + +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[10,15] *} + +### Valores de retorno + +Y pueden devolver valores o no, los valores no serán usados. + +Así que, puedes reutilizar una dependencia normal (que devuelve un valor) que ya uses en otro lugar, y aunque el valor no se use, la dependencia será ejecutada: + +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[11,16] *} + +## Dependencias para un grupo de *path operations* + +Más adelante, cuando leas sobre cómo estructurar aplicaciones más grandes ([Aplicaciones Más Grandes - Múltiples Archivos](../../tutorial/bigger-applications.md){.internal-link target=_blank}), posiblemente con múltiples archivos, aprenderás cómo declarar un único parámetro `dependencies` para un grupo de *path operations*. + +## Dependencias Globales + +A continuación veremos cómo añadir dependencias a toda la aplicación `FastAPI`, de modo que se apliquen a cada *path operation*. diff --git a/docs/es/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/es/docs/tutorial/dependencies/dependencies-with-yield.md new file mode 100644 index 000000000..94290443a --- /dev/null +++ b/docs/es/docs/tutorial/dependencies/dependencies-with-yield.md @@ -0,0 +1,275 @@ +# Dependencias con yield + +FastAPI admite dependencias que realizan algunos pasos adicionales después de finalizar. + +Para hacer esto, usa `yield` en lugar de `return` y escribe los pasos adicionales (código) después. + +/// tip | Consejo + +Asegúrate de usar `yield` una sola vez por dependencia. + +/// + +/// note | Nota técnica + +Cualquier función que sea válida para usar con: + +* `@contextlib.contextmanager` o +* `@contextlib.asynccontextmanager` + +sería válida para usar como una dependencia en **FastAPI**. + +De hecho, FastAPI usa esos dos decoradores internamente. + +/// + +## Una dependencia de base de datos con `yield` + +Por ejemplo, podrías usar esto para crear una sesión de base de datos y cerrarla después de finalizar. + +Solo el código anterior e incluyendo la declaración `yield` se ejecuta antes de crear un response: + +{* ../../docs_src/dependencies/tutorial007.py hl[2:4] *} + +El valor generado es lo que se inyecta en *path operations* y otras dependencias: + +{* ../../docs_src/dependencies/tutorial007.py hl[4] *} + +El código posterior a la declaración `yield` se ejecuta después de crear el response pero antes de enviarla: + +{* ../../docs_src/dependencies/tutorial007.py hl[5:6] *} + +/// tip | Consejo + +Puedes usar funciones `async` o regulares. + +**FastAPI** hará lo correcto con cada una, igual que con dependencias normales. + +/// + +## Una dependencia con `yield` y `try` + +Si usas un bloque `try` en una dependencia con `yield`, recibirás cualquier excepción que se haya lanzado al usar la dependencia. + +Por ejemplo, si algún código en algún punto intermedio, en otra dependencia o en una *path operation*, realiza un "rollback" en una transacción de base de datos o crea cualquier otro error, recibirás la excepción en tu dependencia. + +Por lo tanto, puedes buscar esa excepción específica dentro de la dependencia con `except SomeException`. + +Del mismo modo, puedes usar `finally` para asegurarte de que los pasos de salida se ejecuten, sin importar si hubo una excepción o no. + +{* ../../docs_src/dependencies/tutorial007.py hl[3,5] *} + +## Sub-dependencias con `yield` + +Puedes tener sub-dependencias y "árboles" de sub-dependencias de cualquier tamaño y forma, y cualquiera o todas ellas pueden usar `yield`. + +**FastAPI** se asegurará de que el "código de salida" en cada dependencia con `yield` se ejecute en el orden correcto. + +Por ejemplo, `dependency_c` puede tener una dependencia de `dependency_b`, y `dependency_b` de `dependency_a`: + +{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[6,14,22] *} + +Y todas ellas pueden usar `yield`. + +En este caso, `dependency_c`, para ejecutar su código de salida, necesita que el valor de `dependency_b` (aquí llamado `dep_b`) todavía esté disponible. + +Y, a su vez, `dependency_b` necesita que el valor de `dependency_a` (aquí llamado `dep_a`) esté disponible para su código de salida. + +{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[18:19,26:27] *} + +De la misma manera, podrías tener algunas dependencias con `yield` y otras dependencias con `return`, y hacer que algunas de esas dependan de algunas de las otras. + +Y podrías tener una sola dependencia que requiera varias otras dependencias con `yield`, etc. + +Puedes tener cualquier combinación de dependencias que quieras. + +**FastAPI** se asegurará de que todo se ejecute en el orden correcto. + +/// note | Nota técnica + +Esto funciona gracias a los Context Managers de Python. + +**FastAPI** los utiliza internamente para lograr esto. + +/// + +## Dependencias con `yield` y `HTTPException` + +Viste que puedes usar dependencias con `yield` y tener bloques `try` que capturen excepciones. + +De la misma manera, podrías lanzar una `HTTPException` o similar en el código de salida, después del `yield`. + +/// tip | Consejo + +Esta es una técnica algo avanzada, y en la mayoría de los casos realmente no lo necesitarás, ya que puedes lanzar excepciones (incluyendo `HTTPException`) desde dentro del resto del código de tu aplicación, por ejemplo, en la *path operation function*. + +Pero está ahí para ti si la necesitas. 🤓 + +/// + +{* ../../docs_src/dependencies/tutorial008b_an_py39.py hl[18:22,31] *} + +Una alternativa que podrías usar para capturar excepciones (y posiblemente también lanzar otra `HTTPException`) es crear un [Manejador de Excepciones Personalizado](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. + +## Dependencias con `yield` y `except` + +Si capturas una excepción usando `except` en una dependencia con `yield` y no la lanzas nuevamente (o lanzas una nueva excepción), FastAPI no podrá notar que hubo una excepción, al igual que sucedería con Python normal: + +{* ../../docs_src/dependencies/tutorial008c_an_py39.py hl[15:16] *} + +En este caso, el cliente verá un response *HTTP 500 Internal Server Error* como debería, dado que no estamos lanzando una `HTTPException` o similar, pero el servidor **no tendrá ningún registro** ni ninguna otra indicación de cuál fue el error. 😱 + +### Siempre `raise` en Dependencias con `yield` y `except` + +Si capturas una excepción en una dependencia con `yield`, a menos que estés lanzando otra `HTTPException` o similar, deberías volver a lanzar la excepción original. + +Puedes volver a lanzar la misma excepción usando `raise`: + +{* ../../docs_src/dependencies/tutorial008d_an_py39.py hl[17] *} + +Ahora el cliente obtendrá el mismo response *HTTP 500 Internal Server Error*, pero el servidor tendrá nuestro `InternalError` personalizado en los registros. 😎 + +## Ejecución de dependencias con `yield` + +La secuencia de ejecución es más o menos como este diagrama. El tiempo fluye de arriba a abajo. Y cada columna es una de las partes que interactúa o ejecuta código. + +```mermaid +sequenceDiagram + +participant client as Client +participant handler as Exception handler +participant dep as Dep with yield +participant operation as Path Operation +participant tasks as Background tasks + + Note over client,operation: Puede lanzar excepciones, incluyendo HTTPException + client ->> dep: Iniciar request + Note over dep: Ejecutar código hasta yield + opt raise Exception + dep -->> handler: Lanzar Exception + handler -->> client: Response HTTP de error + end + dep ->> operation: Ejecutar dependencia, por ejemplo, sesión de BD + opt raise + operation -->> dep: Lanzar Exception (por ejemplo, HTTPException) + opt handle + dep -->> dep: Puede capturar excepción, lanzar una nueva HTTPException, lanzar otra excepción + end + handler -->> client: Response HTTP de error + end + + operation ->> client: Devolver response al cliente + Note over client,operation: El response ya fue enviado, no se puede cambiar + opt Tasks + operation -->> tasks: Enviar tareas en background + end + opt Lanzar otra excepción + tasks -->> tasks: Manejar excepciones en el código de la tarea en background + end +``` + +/// info | Información + +Solo **un response** será enviado al cliente. Podría ser uno de los responses de error o será el response de la *path operation*. + +Después de que se envíe uno de esos responses, no se podrá enviar ningún otro response. + +/// + +/// tip | Consejo + +Este diagrama muestra `HTTPException`, pero también podrías lanzar cualquier otra excepción que captures en una dependencia con `yield` o con un [Manejador de Excepciones Personalizado](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. + +Si lanzas alguna excepción, será pasada a las dependencias con yield, incluyendo `HTTPException`. En la mayoría de los casos querrás volver a lanzar esa misma excepción o una nueva desde la dependencia con `yield` para asegurarte de que se maneje correctamente. + +/// + +## Dependencias con `yield`, `HTTPException`, `except` y Tareas en Background + +/// warning | Advertencia + +Probablemente no necesites estos detalles técnicos, puedes omitir esta sección y continuar abajo. + +Estos detalles son útiles principalmente si estabas usando una versión de FastAPI anterior a 0.106.0 y usabas recursos de dependencias con `yield` en tareas en background. + +/// + +### Dependencias con `yield` y `except`, Detalles Técnicos + +Antes de FastAPI 0.110.0, si usabas una dependencia con `yield`, y luego capturabas una excepción con `except` en esa dependencia, y no volvías a lanzar la excepción, la excepción se lanzaría automáticamente/transmitiría a cualquier manejador de excepciones o al manejador de errores interno del servidor. + +Esto se cambió en la versión 0.110.0 para corregir el consumo no gestionado de memoria de excepciones transmitidas sin un manejador (errores internos del servidor), y para que sea consistente con el comportamiento del código regular de Python. + +### Tareas en Background y Dependencias con `yield`, Detalles Técnicos + +Antes de FastAPI 0.106.0, lanzar excepciones después de `yield` no era posible, el código de salida en dependencias con `yield` se ejecutaba *después* de que el response se enviara, por lo que los [Manejadores de Excepciones](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} ya se habrían ejecutado. + +Esto se diseñó de esta manera principalmente para permitir usar los mismos objetos "extraídos" por dependencias dentro de tareas en background, porque el código de salida se ejecutaría después de que las tareas en background terminaran. + +Sin embargo, ya que esto significaría esperar a que el response viaje a través de la red mientras se retiene innecesariamente un recurso en una dependencia con yield (por ejemplo, una conexión a base de datos), esto se cambió en FastAPI 0.106.0. + +/// tip | Consejo + +Además, una tarea en background es normalmente un conjunto independiente de lógica que debería manejarse por separado, con sus propios recursos (por ejemplo, su propia conexión a base de datos). + +De esta manera probablemente tendrás un código más limpio. + +/// + +Si solías depender de este comportamiento, ahora deberías crear los recursos para tareas en background dentro de la propia tarea en background, y usar internamente solo datos que no dependan de los recursos de las dependencias con `yield`. + +Por ejemplo, en lugar de usar la misma sesión de base de datos, crearías una nueva sesión de base de datos dentro de la tarea en background, y obtendrías los objetos de la base de datos usando esta nueva sesión. Y luego, en lugar de pasar el objeto de la base de datos como parámetro a la función de tarea en background, pasarías el ID de ese objeto y luego obtendrías el objeto nuevamente dentro de la función de tarea en background. + +## Context Managers + +### Qué son los "Context Managers" + +Los "Context Managers" son aquellos objetos de Python que puedes usar en una declaración `with`. + +Por ejemplo, puedes usar `with` para leer un archivo: + +```Python +with open("./somefile.txt") as f: + contents = f.read() + print(contents) +``` + +Internamente, `open("./somefile.txt")` crea un objeto llamado "Context Manager". + +Cuando el bloque `with` termina, se asegura de cerrar el archivo, incluso si hubo excepciones. + +Cuando creas una dependencia con `yield`, **FastAPI** creará internamente un context manager para ella y lo combinará con algunas otras herramientas relacionadas. + +### Usando context managers en dependencias con `yield` + +/// warning | Advertencia + +Esto es, más o menos, una idea "avanzada". + +Si apenas estás comenzando con **FastAPI**, podrías querer omitirlo por ahora. + +/// + +En Python, puedes crear Context Managers creando una clase con dos métodos: `__enter__()` y `__exit__()`. + +También puedes usarlos dentro de las dependencias de **FastAPI** con `yield` usando +`with` o `async with` en la función de dependencia: + +{* ../../docs_src/dependencies/tutorial010.py hl[1:9,13] *} + +/// tip | Consejo + +Otra manera de crear un context manager es con: + +* `@contextlib.contextmanager` o +* `@contextlib.asynccontextmanager` + +usándolos para decorar una función con un solo `yield`. + +Eso es lo que **FastAPI** usa internamente para dependencias con `yield`. + +Pero no tienes que usar los decoradores para las dependencias de FastAPI (y no deberías). + +FastAPI lo hará por ti internamente. + +/// diff --git a/docs/es/docs/tutorial/dependencies/global-dependencies.md b/docs/es/docs/tutorial/dependencies/global-dependencies.md new file mode 100644 index 000000000..08dd3d5c5 --- /dev/null +++ b/docs/es/docs/tutorial/dependencies/global-dependencies.md @@ -0,0 +1,15 @@ +# Dependencias Globales + +Para algunos tipos de aplicaciones, podrías querer agregar dependencias a toda la aplicación. + +Similar a como puedes [agregar `dependencies` a los *path operation decorators*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, puedes agregarlos a la aplicación de `FastAPI`. + +En ese caso, se aplicarán a todas las *path operations* en la aplicación: + +{* ../../docs_src/dependencies/tutorial012_an_py39.py hl[16] *} + +Y todas las ideas en la sección sobre [agregar `dependencies` a los *path operation decorators*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} siguen aplicándose, pero en este caso, a todas las *path operations* en la app. + +## Dependencias para grupos de *path operations* + +Más adelante, al leer sobre cómo estructurar aplicaciones más grandes ([Aplicaciones Más Grandes - Múltiples Archivos](../../tutorial/bigger-applications.md){.internal-link target=_blank}), posiblemente con múltiples archivos, aprenderás cómo declarar un solo parámetro de `dependencies` para un grupo de *path operations*. diff --git a/docs/es/docs/tutorial/dependencies/index.md b/docs/es/docs/tutorial/dependencies/index.md new file mode 100644 index 000000000..2fb060177 --- /dev/null +++ b/docs/es/docs/tutorial/dependencies/index.md @@ -0,0 +1,250 @@ +# Dependencias + +**FastAPI** tiene un sistema de **Inyección de Dependencias** muy poderoso pero intuitivo. + +Está diseñado para ser muy simple de usar, y para hacer que cualquier desarrollador integre otros componentes con **FastAPI** de forma muy sencilla. + +## Qué es la "Inyección de Dependencias" + +**"Inyección de Dependencias"** significa, en programación, que hay una manera para que tu código (en este caso, tus *path operation functions*) declare las cosas que necesita para funcionar y utilizar: "dependencias". + +Y luego, ese sistema (en este caso **FastAPI**) se encargará de hacer lo que sea necesario para proporcionar a tu código esas dependencias necesarias ("inyectar" las dependencias). + +Esto es muy útil cuando necesitas: + +* Tener lógica compartida (la misma lógica de código una y otra vez). +* Compartir conexiones a bases de datos. +* Imponer seguridad, autenticación, requisitos de roles, etc. +* Y muchas otras cosas... + +Todo esto, mientras minimizas la repetición de código. + +## Primeros Pasos + +Veamos un ejemplo muy simple. Será tan simple que no es muy útil, por ahora. + +Pero de esta manera podemos enfocarnos en cómo funciona el sistema de **Inyección de Dependencias**. + +### Crear una dependencia, o "dependable" + +Primero enfoquémonos en la dependencia. + +Es solo una función que puede tomar todos los mismos parámetros que una *path operation function* puede tomar: + +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *} + +Eso es todo. + +**2 líneas**. + +Y tiene la misma forma y estructura que todas tus *path operation functions*. + +Puedes pensar en ella como una *path operation function* sin el "decorador" (sin el `@app.get("/some-path")`). + +Y puede devolver lo que quieras. + +En este caso, esta dependencia espera: + +* Un parámetro de query opcional `q` que es un `str`. +* Un parámetro de query opcional `skip` que es un `int`, y por defecto es `0`. +* Un parámetro de query opcional `limit` que es un `int`, y por defecto es `100`. + +Y luego solo devuelve un `dict` que contiene esos valores. + +/// info | Información + +FastAPI agregó soporte para `Annotated` (y comenzó a recomendarlo) en la versión 0.95.0. + +Si tienes una versión anterior, obtendrás errores al intentar usar `Annotated`. + +Asegúrate de [Actualizar la versión de FastAPI](../../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} al menos a la 0.95.1 antes de usar `Annotated`. + +/// + +### Importar `Depends` + +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *} + +### Declarar la dependencia, en el "dependant" + +De la misma forma en que usas `Body`, `Query`, etc. con los parámetros de tu *path operation function*, usa `Depends` con un nuevo parámetro: + +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *} + +Aunque usas `Depends` en los parámetros de tu función de la misma manera que usas `Body`, `Query`, etc., `Depends` funciona un poco diferente. + +Le das a `Depends` un solo parámetro. + +Este parámetro debe ser algo como una función. + +**No la llames** directamente (no agregues los paréntesis al final), solo pásala como un parámetro a `Depends()`. + +Y esa función toma parámetros de la misma manera que las *path operation functions*. + +/// tip | Consejo + +Verás qué otras "cosas", además de funciones, pueden usarse como dependencias en el próximo capítulo. + +/// + +Cada vez que llega un nuevo request, **FastAPI** se encargará de: + +* Llamar a tu función de dependencia ("dependable") con los parámetros correctos. +* Obtener el resultado de tu función. +* Asignar ese resultado al parámetro en tu *path operation function*. + +```mermaid +graph TB + +common_parameters(["common_parameters"]) +read_items["/items/"] +read_users["/users/"] + +common_parameters --> read_items +common_parameters --> read_users +``` + +De esta manera escribes código compartido una vez y **FastAPI** se encarga de llamarlo para tus *path operations*. + +/// check | Revisa + +Nota que no tienes que crear una clase especial y pasarla en algún lugar a **FastAPI** para "registrarla" o algo similar. + +Solo la pasas a `Depends` y **FastAPI** sabe cómo hacer el resto. + +/// + +## Compartir dependencias `Annotated` + +En los ejemplos anteriores, ves que hay un poquito de **duplicación de código**. + +Cuando necesitas usar la dependencia `common_parameters()`, tienes que escribir todo el parámetro con la anotación de tipo y `Depends()`: + +```Python +commons: Annotated[dict, Depends(common_parameters)] +``` + +Pero como estamos usando `Annotated`, podemos almacenar ese valor `Annotated` en una variable y usarlo en múltiples lugares: + +{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *} + +/// tip | Consejo + +Esto es solo Python estándar, se llama un "alias de tipo", en realidad no es específico de **FastAPI**. + +Pero porque **FastAPI** está basado en los estándares de Python, incluido `Annotated`, puedes usar este truco en tu código. 😎 + +/// + +Las dependencias seguirán funcionando como se esperaba, y la **mejor parte** es que la **información de tipo se preservará**, lo que significa que tu editor podrá seguir proporcionándote **autocompletado**, **errores en línea**, etc. Lo mismo para otras herramientas como `mypy`. + +Esto será especialmente útil cuando lo uses en una **gran base de código** donde uses **las mismas dependencias** una y otra vez en **muchas *path operations***. + +## Usar `async` o no usar `async` + +Como las dependencias también serán llamadas por **FastAPI** (lo mismo que tus *path operation functions*), las mismas reglas aplican al definir tus funciones. + +Puedes usar `async def` o `def` normal. + +Y puedes declarar dependencias con `async def` dentro de *path operation functions* normales `def`, o dependencias `def` dentro de *path operation functions* `async def`, etc. + +No importa. **FastAPI** sabrá qué hacer. + +/// note | Nota + +Si no lo sabes, revisa la sección [Async: *"¿Con prisa?"*](../../async.md#in-a-hurry){.internal-link target=_blank} sobre `async` y `await` en la documentación. + +/// + +## Integración con OpenAPI + +Todas las declaraciones de request, validaciones y requisitos de tus dependencias (y sub-dependencias) se integrarán en el mismo esquema de OpenAPI. + +Así, la documentación interactiva tendrá toda la información de estas dependencias también: + + + +## Uso simple + +Si lo ves, las *path operation functions* se declaran para ser usadas siempre que un *path* y una *operación* coincidan, y luego **FastAPI** se encarga de llamar la función con los parámetros correctos, extrayendo los datos del request. + +En realidad, todos (o la mayoría) de los frameworks web funcionan de esta misma manera. + +Nunca llamas directamente a esas funciones. Son llamadas por tu framework (en este caso, **FastAPI**). + +Con el sistema de Inyección de Dependencias, también puedes decirle a **FastAPI** que tu *path operation function* también "depende" de algo más que debe ejecutarse antes que tu *path operation function*, y **FastAPI** se encargará de ejecutarlo e "inyectar" los resultados. + +Otros términos comunes para esta misma idea de "inyección de dependencias" son: + +* recursos +* proveedores +* servicios +* inyectables +* componentes + +## Plug-ins de **FastAPI** + +Las integraciones y "plug-ins" pueden construirse usando el sistema de **Inyección de Dependencias**. Pero, de hecho, en realidad **no hay necesidad de crear "plug-ins"**, ya que al usar dependencias es posible declarar una cantidad infinita de integraciones e interacciones que se vuelven disponibles para tus *path operation functions*. + +Y las dependencias se pueden crear de una manera muy simple e intuitiva que te permite simplemente importar los paquetes de Python que necesitas, e integrarlos con tus funciones de API en un par de líneas de código, *literalmente*. + +Verás ejemplos de esto en los próximos capítulos, sobre bases de datos relacionales y NoSQL, seguridad, etc. + +## Compatibilidad de **FastAPI** + +La simplicidad del sistema de inyección de dependencias hace que **FastAPI** sea compatible con: + +* todas las bases de datos relacionales +* bases de datos NoSQL +* paquetes externos +* APIs externas +* sistemas de autenticación y autorización +* sistemas de monitoreo de uso de la API +* sistemas de inyección de datos de response +* etc. + +## Simple y Poderoso + +Aunque el sistema de inyección de dependencias jerárquico es muy simple de definir y usar, sigue siendo muy poderoso. + +Puedes definir dependencias que a su vez pueden definir dependencias ellas mismas. + +Al final, se construye un árbol jerárquico de dependencias, y el sistema de **Inyección de Dependencias** se encarga de resolver todas estas dependencias por ti (y sus sub-dependencias) y proporcionar (inyectar) los resultados en cada paso. + +Por ejemplo, digamos que tienes 4 endpoints de API (*path operations*): + +* `/items/public/` +* `/items/private/` +* `/users/{user_id}/activate` +* `/items/pro/` + +entonces podrías agregar diferentes requisitos de permiso para cada uno de ellos solo con dependencias y sub-dependencias: + +```mermaid +graph TB + +current_user(["current_user"]) +active_user(["active_user"]) +admin_user(["admin_user"]) +paying_user(["paying_user"]) + +public["/items/public/"] +private["/items/private/"] +activate_user["/users/{user_id}/activate"] +pro_items["/items/pro/"] + +current_user --> active_user +active_user --> admin_user +active_user --> paying_user + +current_user --> public +active_user --> private +admin_user --> activate_user +paying_user --> pro_items +``` + +## Integrado con **OpenAPI** + +Todas estas dependencias, al declarar sus requisitos, también añaden parámetros, validaciones, etc. a tus *path operations*. + +**FastAPI** se encargará de agregar todo al esquema de OpenAPI, para que se muestre en los sistemas de documentación interactiva. diff --git a/docs/es/docs/tutorial/dependencies/sub-dependencies.md b/docs/es/docs/tutorial/dependencies/sub-dependencies.md new file mode 100644 index 000000000..bba532207 --- /dev/null +++ b/docs/es/docs/tutorial/dependencies/sub-dependencies.md @@ -0,0 +1,105 @@ +# Sub-dependencias + +Puedes crear dependencias que tengan **sub-dependencias**. + +Pueden ser tan **profundas** como necesites. + +**FastAPI** se encargará de resolverlas. + +## Primera dependencia "dependable" + +Podrías crear una primera dependencia ("dependable") así: + +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *} + +Declara un parámetro de query opcional `q` como un `str`, y luego simplemente lo devuelve. + +Esto es bastante simple (no muy útil), pero nos ayudará a centrarnos en cómo funcionan las sub-dependencias. + +## Segunda dependencia, "dependable" y "dependant" + +Luego puedes crear otra función de dependencia (un "dependable") que al mismo tiempo declare una dependencia propia (por lo que también es un "dependant"): + +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *} + +Centrémonos en los parámetros declarados: + +* Aunque esta función es una dependencia ("dependable") en sí misma, también declara otra dependencia (depende de algo más). + * Depende del `query_extractor`, y asigna el valor que devuelve al parámetro `q`. +* También declara una `last_query` cookie opcional, como un `str`. + * Si el usuario no proporcionó ningún query `q`, usamos el último query utilizado, que guardamos previamente en una cookie. + +## Usa la dependencia + +Entonces podemos usar la dependencia con: + +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *} + +/// info | Información + +Fíjate que solo estamos declarando una dependencia en la *path operation function*, `query_or_cookie_extractor`. + +Pero **FastAPI** sabrá que tiene que resolver `query_extractor` primero, para pasar los resultados de eso a `query_or_cookie_extractor` al llamarlo. + +/// + +```mermaid +graph TB + +query_extractor(["query_extractor"]) +query_or_cookie_extractor(["query_or_cookie_extractor"]) + +read_query["/items/"] + +query_extractor --> query_or_cookie_extractor --> read_query +``` + +## Usando la misma dependencia múltiples veces + +Si una de tus dependencias se declara varias veces para la misma *path operation*, por ejemplo, múltiples dependencias tienen una sub-dependencia común, **FastAPI** sabrá llamar a esa sub-dependencia solo una vez por request. + +Y guardará el valor devuelto en un "cache" y lo pasará a todos los "dependants" que lo necesiten en ese request específico, en lugar de llamar a la dependencia varias veces para el mismo request. + +En un escenario avanzado donde sabes que necesitas que la dependencia se llame en cada paso (posiblemente varias veces) en el mismo request en lugar de usar el valor "cache", puedes establecer el parámetro `use_cache=False` al usar `Depends`: + +//// tab | Python 3.8+ + +```Python hl_lines="1" +async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]): + return {"fresh_value": fresh_value} +``` + +//// + +//// tab | Python 3.8+ sin Anotaciones + +/// tip | Consejo + +Prefiere usar la versión `Annotated` si es posible. + +/// + +```Python hl_lines="1" +async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)): + return {"fresh_value": fresh_value} +``` + +//// + +## Resumen + +Aparte de todas las palabras rimbombantes usadas aquí, el sistema de **Inyección de Dependencias** es bastante simple. + +Solo son funciones que se ven igual que las *path operation functions*. + +Pero aun así, es muy potente y te permite declarar "grafos" de dependencia anidados arbitrariamente profundos (árboles). + +/// tip | Consejo + +Todo esto podría no parecer tan útil con estos ejemplos simples. + +Pero verás lo útil que es en los capítulos sobre **seguridad**. + +Y también verás la cantidad de código que te ahorrará. + +/// diff --git a/docs/es/docs/tutorial/encoder.md b/docs/es/docs/tutorial/encoder.md new file mode 100644 index 000000000..9b8919d4b --- /dev/null +++ b/docs/es/docs/tutorial/encoder.md @@ -0,0 +1,35 @@ +# JSON Compatible Encoder + +Hay algunos casos en los que podrías necesitar convertir un tipo de dato (como un modelo de Pydantic) a algo compatible con JSON (como un `dict`, `list`, etc). + +Por ejemplo, si necesitas almacenarlo en una base de datos. + +Para eso, **FastAPI** proporciona una función `jsonable_encoder()`. + +## Usando el `jsonable_encoder` + +Imaginemos que tienes una base de datos `fake_db` que solo recibe datos compatibles con JSON. + +Por ejemplo, no recibe objetos `datetime`, ya que no son compatibles con JSON. + +Entonces, un objeto `datetime` tendría que ser convertido a un `str` que contenga los datos en formato ISO. + +De la misma manera, esta base de datos no recibiría un modelo de Pydantic (un objeto con atributos), solo un `dict`. + +Puedes usar `jsonable_encoder` para eso. + +Recibe un objeto, como un modelo de Pydantic, y devuelve una versión compatible con JSON: + +{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *} + +En este ejemplo, convertiría el modelo de Pydantic a un `dict`, y el `datetime` a un `str`. + +El resultado de llamarlo es algo que puede ser codificado con la función estándar de Python `json.dumps()`. + +No devuelve un gran `str` que contenga los datos en formato JSON (como una cadena de texto). Devuelve una estructura de datos estándar de Python (por ejemplo, un `dict`) con valores y sub-valores que son todos compatibles con JSON. + +/// note | Nota + +`jsonable_encoder` es utilizado internamente por **FastAPI** para convertir datos. Pero es útil en muchos otros escenarios. + +/// diff --git a/docs/es/docs/tutorial/extra-data-types.md b/docs/es/docs/tutorial/extra-data-types.md new file mode 100644 index 000000000..28775780f --- /dev/null +++ b/docs/es/docs/tutorial/extra-data-types.md @@ -0,0 +1,62 @@ +# Tipos de Datos Extra + +Hasta ahora, has estado usando tipos de datos comunes, como: + +* `int` +* `float` +* `str` +* `bool` + +Pero también puedes usar tipos de datos más complejos. + +Y seguirás teniendo las mismas funcionalidades como hasta ahora: + +* Gran soporte de editor. +* Conversión de datos de requests entrantes. +* Conversión de datos para datos de response. +* Validación de datos. +* Anotación y documentación automática. + +## Otros tipos de datos + +Aquí hay algunos de los tipos de datos adicionales que puedes usar: + +* `UUID`: + * Un "Identificador Universalmente Único" estándar, común como un ID en muchas bases de datos y sistemas. + * En requests y responses se representará como un `str`. +* `datetime.datetime`: + * Un `datetime.datetime` de Python. + * En requests y responses se representará como un `str` en formato ISO 8601, como: `2008-09-15T15:53:00+05:00`. +* `datetime.date`: + * `datetime.date` de Python. + * En requests y responses se representará como un `str` en formato ISO 8601, como: `2008-09-15`. +* `datetime.time`: + * Un `datetime.time` de Python. + * En requests y responses se representará como un `str` en formato ISO 8601, como: `14:23:55.003`. +* `datetime.timedelta`: + * Un `datetime.timedelta` de Python. + * En requests y responses se representará como un `float` de segundos totales. + * Pydantic también permite representarlo como una "codificación de diferencia horaria ISO 8601", consulta la documentación para más información. +* `frozenset`: + * En requests y responses, tratado igual que un `set`: + * En requests, se leerá una list, eliminando duplicados y convirtiéndola en un `set`. + * En responses, el `set` se convertirá en una `list`. + * El esquema generado especificará que los valores del `set` son únicos (usando `uniqueItems` de JSON Schema). +* `bytes`: + * `bytes` estándar de Python. + * En requests y responses se tratará como `str`. + * El esquema generado especificará que es un `str` con "binary" como "format". +* `Decimal`: + * `Decimal` estándar de Python. + * En requests y responses, manejado igual que un `float`. +* Puedes revisar todos los tipos de datos válidos de Pydantic aquí: Tipos de datos de Pydantic. + +## Ejemplo + +Aquí tienes un ejemplo de una *path operation* con parámetros usando algunos de los tipos anteriores. + +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *} + +Nota que los parámetros dentro de la función tienen su tipo de dato natural, y puedes, por ejemplo, realizar manipulaciones de fechas normales, como: + +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *} diff --git a/docs/es/docs/tutorial/extra-models.md b/docs/es/docs/tutorial/extra-models.md new file mode 100644 index 000000000..0380b9690 --- /dev/null +++ b/docs/es/docs/tutorial/extra-models.md @@ -0,0 +1,222 @@ +# Modelos Extra + +Continuando con el ejemplo anterior, será común tener más de un modelo relacionado. + +Esto es especialmente el caso para los modelos de usuario, porque: + +* El **modelo de entrada** necesita poder tener una contraseña. +* El **modelo de salida** no debería tener una contraseña. +* El **modelo de base de datos** probablemente necesitaría tener una contraseña hasheada. + +/// danger | Peligro + +Nunca almacenes contraseñas de usuarios en texto plano. Siempre almacena un "hash seguro" que puedas verificar luego. + +Si no lo sabes, aprenderás qué es un "hash de contraseña" en los [capítulos de seguridad](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}. + +/// + +## Múltiples modelos + +Aquí tienes una idea general de cómo podrían ser los modelos con sus campos de contraseña y los lugares donde se utilizan: + +{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *} + +/// info | Información + +En Pydantic v1 el método se llamaba `.dict()`, fue deprecado (pero aún soportado) en Pydantic v2, y renombrado a `.model_dump()`. + +Los ejemplos aquí usan `.dict()` para compatibilidad con Pydantic v1, pero deberías usar `.model_dump()` en su lugar si puedes usar Pydantic v2. + +/// + +### Acerca de `**user_in.dict()` + +#### `.dict()` de Pydantic + +`user_in` es un modelo Pydantic de la clase `UserIn`. + +Los modelos Pydantic tienen un método `.dict()` que devuelve un `dict` con los datos del modelo. + +Así que, si creamos un objeto Pydantic `user_in` como: + +```Python +user_in = UserIn(username="john", password="secret", email="john.doe@example.com") +``` + +y luego llamamos a: + +```Python +user_dict = user_in.dict() +``` + +ahora tenemos un `dict` con los datos en la variable `user_dict` (es un `dict` en lugar de un objeto modelo Pydantic). + +Y si llamamos a: + +```Python +print(user_dict) +``` + +obtendremos un `dict` de Python con: + +```Python +{ + 'username': 'john', + 'password': 'secret', + 'email': 'john.doe@example.com', + 'full_name': None, +} +``` + +#### Desempaquetando un `dict` + +Si tomamos un `dict` como `user_dict` y lo pasamos a una función (o clase) con `**user_dict`, Python lo "desempaquetará". Pasará las claves y valores del `user_dict` directamente como argumentos clave-valor. + +Así que, continuando con el `user_dict` anterior, escribir: + +```Python +UserInDB(**user_dict) +``` + +sería equivalente a algo como: + +```Python +UserInDB( + username="john", + password="secret", + email="john.doe@example.com", + full_name=None, +) +``` + +O más exactamente, usando `user_dict` directamente, con cualquier contenido que pueda tener en el futuro: + +```Python +UserInDB( + username = user_dict["username"], + password = user_dict["password"], + email = user_dict["email"], + full_name = user_dict["full_name"], +) +``` + +#### Un modelo Pydantic a partir del contenido de otro + +Como en el ejemplo anterior obtuvimos `user_dict` de `user_in.dict()`, este código: + +```Python +user_dict = user_in.dict() +UserInDB(**user_dict) +``` + +sería equivalente a: + +```Python +UserInDB(**user_in.dict()) +``` + +...porque `user_in.dict()` es un `dict`, y luego hacemos que Python lo "desempaquete" al pasarlo a `UserInDB` con el prefijo `**`. + +Así, obtenemos un modelo Pydantic a partir de los datos en otro modelo Pydantic. + +#### Desempaquetando un `dict` y palabras clave adicionales + +Y luego agregando el argumento de palabra clave adicional `hashed_password=hashed_password`, como en: + +```Python +UserInDB(**user_in.dict(), hashed_password=hashed_password) +``` + +...termina siendo como: + +```Python +UserInDB( + username = user_dict["username"], + password = user_dict["password"], + email = user_dict["email"], + full_name = user_dict["full_name"], + hashed_password = hashed_password, +) +``` + +/// warning | Advertencia + +Las funciones adicionales de soporte `fake_password_hasher` y `fake_save_user` son solo para demostrar un posible flujo de datos, pero por supuesto no proporcionan ninguna seguridad real. + +/// + +## Reducir duplicación + +Reducir la duplicación de código es una de las ideas centrales en **FastAPI**. + +Ya que la duplicación de código incrementa las posibilidades de bugs, problemas de seguridad, problemas de desincronización de código (cuando actualizas en un lugar pero no en los otros), etc. + +Y estos modelos están compartiendo muchos de los datos y duplicando nombres y tipos de atributos. + +Podríamos hacerlo mejor. + +Podemos declarar un modelo `UserBase` que sirva como base para nuestros otros modelos. Y luego podemos hacer subclases de ese modelo que heredan sus atributos (declaraciones de tipo, validación, etc). + +Toda la conversión de datos, validación, documentación, etc. seguirá funcionando normalmente. + +De esa manera, podemos declarar solo las diferencias entre los modelos (con `password` en texto plano, con `hashed_password` y sin contraseña): + +{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *} + +## `Union` o `anyOf` + +Puedes declarar un response que sea la `Union` de dos o más tipos, eso significa que el response sería cualquiera de ellos. + +Se definirá en OpenAPI con `anyOf`. + +Para hacerlo, usa el type hint estándar de Python `typing.Union`: + +/// note | Nota + +Al definir una `Union`, incluye el tipo más específico primero, seguido por el tipo menos específico. En el ejemplo a continuación, el más específico `PlaneItem` viene antes de `CarItem` en `Union[PlaneItem, CarItem]`. + +/// + +{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *} + + +### `Union` en Python 3.10 + +En este ejemplo pasamos `Union[PlaneItem, CarItem]` como el valor del argumento `response_model`. + +Porque lo estamos pasando como un **valor a un argumento** en lugar de ponerlo en una **anotación de tipo**, tenemos que usar `Union` incluso en Python 3.10. + +Si estuviera en una anotación de tipo podríamos haber usado la barra vertical, como: + +```Python +some_variable: PlaneItem | CarItem +``` + +Pero si ponemos eso en la asignación `response_model=PlaneItem | CarItem` obtendríamos un error, porque Python intentaría realizar una **operación inválida** entre `PlaneItem` y `CarItem` en lugar de interpretar eso como una anotación de tipo. + +## Lista de modelos + +De la misma manera, puedes declarar responses de listas de objetos. + +Para eso, usa el `typing.List` estándar de Python (o simplemente `list` en Python 3.9 y posteriores): + +{* ../../docs_src/extra_models/tutorial004_py39.py hl[18] *} + + +## Response con `dict` arbitrario + +También puedes declarar un response usando un `dict` arbitrario plano, declarando solo el tipo de las claves y valores, sin usar un modelo Pydantic. + +Esto es útil si no conoces los nombres de los campos/atributos válidos (que serían necesarios para un modelo Pydantic) de antemano. + +En este caso, puedes usar `typing.Dict` (o solo `dict` en Python 3.9 y posteriores): + +{* ../../docs_src/extra_models/tutorial005_py39.py hl[6] *} + + +## Recapitulación + +Usa múltiples modelos Pydantic y hereda libremente para cada caso. + +No necesitas tener un solo modelo de datos por entidad si esa entidad debe poder tener diferentes "estados". Como el caso con la "entidad" usuario con un estado que incluye `password`, `password_hash` y sin contraseña. diff --git a/docs/es/docs/tutorial/first-steps.md b/docs/es/docs/tutorial/first-steps.md index 2cb7e6308..5d869c22f 100644 --- a/docs/es/docs/tutorial/first-steps.md +++ b/docs/es/docs/tutorial/first-steps.md @@ -1,49 +1,74 @@ -# Primeros pasos +# Primeros Pasos -Un archivo muy simple de FastAPI podría verse así: +El archivo FastAPI más simple podría verse así: -```Python -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} -Copia eso a un archivo `main.py`. +Copia eso en un archivo `main.py`. -Corre el servidor en vivo: +Ejecuta el servidor en vivo:
```console -$ uvicorn main:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -INFO: Started reloader process [28720] -INFO: Started server process [28722] -INFO: Waiting for application startup. -INFO: Application startup complete. +$ fastapi dev main.py +INFO Using path main.py +INFO Resolved absolute path /home/user/code/awesomeapp/main.py +INFO Searching for package file structure from directories with __init__.py files +INFO Importing from /home/user/code/awesomeapp + + ╭─ Python module file ─╮ + │ │ + │ 🐍 main.py │ + │ │ + ╰──────────────────────╯ + +INFO Importing module main +INFO Found importable FastAPI app + + ╭─ Importable FastAPI app ─╮ + │ │ + │ from main import app │ + │ │ + ╰──────────────────────────╯ + +INFO Using import string main:app + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + fastapi run + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [2265862] using WatchFiles +INFO: Started server process [2265873] +INFO: Waiting for application startup. +INFO: Application startup complete. ```
-!!! note "Nota" - El comando `uvicorn main:app` se refiere a: - - * `main`: el archivo `main.py` (el "módulo" de Python). - * `app`: el objeto creado dentro de `main.py` con la línea `app = FastAPI()`. - * `--reload`: hace que el servidor se reinicie cada vez que cambia el código. Úsalo únicamente para desarrollo. - -En el output, hay una línea que dice más o menos: +En el resultado, hay una línea con algo como: ```hl_lines="4" INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` -Esa línea muestra la URL dónde se está sirviendo tu app en tu maquina local. +Esa línea muestra la URL donde tu aplicación está siendo servida, en tu máquina local. -### Revísalo +### Compruébalo Abre tu navegador en http://127.0.0.1:8000. -Verás la respuesta en JSON: +Verás el response JSON como: ```JSON {"message": "Hello World"} @@ -51,55 +76,55 @@ Verás la respuesta en JSON: ### Documentación interactiva de la API -Ahora dirígete a http://127.0.0.1:8000/docs. +Ahora ve a http://127.0.0.1:8000/docs. -Ahí verás la documentación automática e interactiva de la API (proveída por Swagger UI): +Verás la documentación interactiva automática de la API (proporcionada por Swagger UI): ![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) ### Documentación alternativa de la API -Ahora, dirígete a http://127.0.0.1:8000/redoc. +Y ahora, ve a http://127.0.0.1:8000/redoc. -Aquí verás la documentación automática alternativa (proveída por ReDoc): +Verás la documentación alternativa automática (proporcionada por ReDoc): ![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) ### OpenAPI -**FastAPI** genera un "schema" con toda tu API usando el estándar para definir APIs, **OpenAPI**. +**FastAPI** genera un "esquema" con toda tu API utilizando el estándar **OpenAPI** para definir APIs. -#### "Schema" +#### "Esquema" -Un "schema" es una definición o descripción de algo. No es el código que la implementa, sino solo una descripción abstracta. +Un "esquema" es una definición o descripción de algo. No el código que lo implementa, sino solo una descripción abstracta. -#### "Schema" de la API +#### Esquema de la API -En este caso, OpenAPI es una especificación que dicta como se debe definir el schema de tu API. +En este caso, OpenAPI es una especificación que dicta cómo definir un esquema de tu API. -La definición del schema incluye los paths de tu API, los parámetros que podría recibir, etc. +Esta definición de esquema incluye los paths de tu API, los posibles parámetros que toman, etc. -#### "Schema" de datos +#### Esquema de Datos -El concepto "schema" también se puede referir a la forma de algunos datos, como un contenido en formato JSON. +El término "esquema" también podría referirse a la forma de algunos datos, como el contenido JSON. -En ese caso haría referencia a los atributos del JSON, los tipos de datos que tiene, etc. +En ese caso, significaría los atributos del JSON, los tipos de datos que tienen, etc. #### OpenAPI y JSON Schema -OpenAPI define un schema de API para tu API. Ese schema incluye definiciones (o "schemas") de los datos enviados y recibidos por tu API usando **JSON Schema**, el estándar para los schemas de datos en JSON. +OpenAPI define un esquema de API para tu API. Y ese esquema incluye definiciones (o "esquemas") de los datos enviados y recibidos por tu API utilizando **JSON Schema**, el estándar para esquemas de datos JSON. #### Revisa el `openapi.json` -Si sientes curiosidad por saber cómo se ve el schema de OpenAPI en bruto, FastAPI genera automáticamente un (schema) JSON con la descripción de todo tu API. +Si tienes curiosidad por cómo se ve el esquema OpenAPI en bruto, FastAPI automáticamente genera un JSON (esquema) con las descripciones de toda tu API. -Lo puedes ver directamente en: http://127.0.0.1:8000/openapi.json. +Puedes verlo directamente en: http://127.0.0.1:8000/openapi.json. -Esto te mostrará un JSON que comienza con algo como: +Mostrará un JSON que empieza con algo como: ```JSON { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": { "title": "FastAPI", "version": "0.1.0" @@ -118,76 +143,45 @@ Esto te mostrará un JSON que comienza con algo como: ... ``` -#### ¿Para qué se usa OpenAPI? +#### Para qué sirve OpenAPI -El schema de OpenAPI es lo que alimenta a los dos sistemas de documentación interactiva incluidos. +El esquema OpenAPI es lo que impulsa los dos sistemas de documentación interactiva incluidos. -También hay docenas de alternativas, todas basadas en OpenAPI. Podrías añadir fácilmente cualquiera de esas alternativas a tu aplicación construida con **FastAPI**. +Y hay docenas de alternativas, todas basadas en OpenAPI. Podrías añadir fácilmente cualquiera de esas alternativas a tu aplicación construida con **FastAPI**. -También podrías usarlo para generar código automáticamente, para los clientes que se comunican con tu API. Por ejemplo, frontend, móvil o aplicaciones de IoT. +También podrías usarlo para generar código automáticamente, para clientes que se comuniquen con tu API. Por ejemplo, aplicaciones frontend, móviles o IoT. -## Repaso, paso a paso +## Recapitulación, paso a paso ### Paso 1: importa `FastAPI` -```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} -``` - -`FastAPI` es una clase de Python que provee toda la funcionalidad para tu API. +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} -!!! note "Detalles Técnicos" - `FastAPI` es una clase que hereda directamente de `Starlette`. +`FastAPI` es una clase de Python que proporciona toda la funcionalidad para tu API. - También puedes usar toda la funcionalidad de Starlette. +/// note | Detalles Técnicos -### Paso 2: crea un "instance" de `FastAPI` +`FastAPI` es una clase que hereda directamente de `Starlette`. -```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +Puedes usar toda la funcionalidad de Starlette con `FastAPI` también. -Aquí la variable `app` será un instance de la clase `FastAPI`. +/// -Este será el punto de interacción principal para crear todo tu API. +### Paso 2: crea una "instance" de `FastAPI` -Esta `app` es la misma a la que nos referimos cuando usamos el comando de `uvicorn`: +{* ../../docs_src/first_steps/tutorial001.py hl[3] *} -
+Aquí la variable `app` será una "instance" de la clase `FastAPI`. -```console -$ uvicorn main:app --reload +Este será el punto principal de interacción para crear toda tu API. -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -Si creas un app como: - -```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} -``` - -y lo guardas en un archivo `main.py`, entonces ejecutarías `uvicorn` así: - -
- -```console -$ uvicorn main:my_awesome_api --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -### Paso 3: crea una *operación de path* +### Paso 3: crea una *path operation* #### Path -"Path" aquí se refiere a la última parte de una URL comenzando desde el primer `/`. +"Path" aquí se refiere a la última parte de la URL empezando desde la primera `/`. -Entonces, en una URL como: +Así que, en una URL como: ``` https://example.com/items/foo @@ -199,16 +193,19 @@ https://example.com/items/foo /items/foo ``` -!!! info "Información" - Un "path" también se conoce habitualmente como "endpoint", "route" o "ruta". +/// info + +Un "path" también es comúnmente llamado "endpoint" o "ruta". -Cuando construyes una API, el "path" es la manera principal de separar los "intereses" y los "recursos". +/// + +Mientras construyes una API, el "path" es la forma principal de separar "concerns" y "resources". #### Operación -"Operación" aquí se refiere a uno de los "métodos" de HTTP. +"Operación" aquí se refiere a uno de los "métodos" HTTP. -Uno como: +Uno de: * `POST` * `GET` @@ -222,44 +219,45 @@ Uno como: * `PATCH` * `TRACE` -En el protocolo de HTTP, te puedes comunicar con cada path usando uno (o más) de estos "métodos". +En el protocolo HTTP, puedes comunicarte con cada path usando uno (o más) de estos "métodos". --- -Cuando construyes APIs, normalmente usas uno de estos métodos específicos de HTTP para realizar una acción específica. +Al construir APIs, normalmente usas estos métodos HTTP específicos para realizar una acción específica. Normalmente usas: * `POST`: para crear datos. * `GET`: para leer datos. * `PUT`: para actualizar datos. -* `DELETE`: para borrar datos. +* `DELETE`: para eliminar datos. -Así que en OpenAPI, cada uno de estos métodos de HTTP es referido como una "operación". +Así que, en OpenAPI, cada uno de los métodos HTTP se llama una "operation". -Nosotros también los llamaremos "**operación**". +Vamos a llamarlas "**operaciones**" también. -#### Define un *decorador de operaciones de path* +#### Define un *path operation decorator* -```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[6] *} -El `@app.get("/")` le dice a **FastAPI** que la función que tiene justo debajo está a cargo de manejar los requests que van a: +El `@app.get("/")` le dice a **FastAPI** que la función justo debajo se encarga de manejar requests que vayan a: * el path `/` -* usando una operación get +* usando una get operation -!!! info "Información sobre `@decorator`" - Esa sintaxis `@algo` se llama un "decorador" en Python. +/// info | Información sobre `@decorator` - Lo pones encima de una función. Es como un lindo sombrero decorado (creo que de ahí salió el concepto). +Esa sintaxis `@algo` en Python se llama un "decorador". - Un "decorador" toma la función que tiene debajo y hace algo con ella. +Lo pones encima de una función. Como un bonito sombrero decorativo (supongo que de ahí viene el término). - En nuestro caso, este decorador le dice a **FastAPI** que la función que está debajo corresponde al **path** `/` con una **operación** `get`. +Un "decorador" toma la función de abajo y hace algo con ella. - Es el "**decorador de operaciones de path**". +En nuestro caso, este decorador le dice a **FastAPI** que la función de abajo corresponde al **path** `/` con una **operation** `get`. + +Es el "**path operation decorator**". + +/// También puedes usar las otras operaciones: @@ -267,67 +265,67 @@ También puedes usar las otras operaciones: * `@app.put()` * `@app.delete()` -y las más exóticas: +Y los más exóticos: * `@app.options()` * `@app.head()` * `@app.patch()` * `@app.trace()` -!!! tip "Consejo" - Tienes la libertad de usar cada operación (método de HTTP) como quieras. +/// tip + +Eres libre de usar cada operación (método HTTP) como quieras. - **FastAPI** no impone ningún significado específico. +**FastAPI** no fuerza ningún significado específico. - La información que está presentada aquí es una guía, no un requerimiento. +La información aquí se presenta como una guía, no un requisito. - Por ejemplo, cuando usas GraphQL normalmente realizas todas las acciones usando únicamente operaciones `POST`. +Por ejemplo, cuando usas GraphQL normalmente realizas todas las acciones usando solo operaciones `POST`. -### Paso 4: define la **función de la operación de path** +/// -Esta es nuestra "**función de la operación de path**": +### Paso 4: define la **path operation function** + +Esta es nuestra "**path operation function**": * **path**: es `/`. -* **operación**: es `get`. -* **función**: es la función debajo del "decorador" (debajo de `@app.get("/")`). +* **operation**: es `get`. +* **function**: es la función debajo del "decorador" (debajo de `@app.get("/")`). -```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[7] *} -Esto es una función de Python. +Esta es una función de Python. -Esta función será llamada por **FastAPI** cada vez que reciba un request en la URL "`/`" usando una operación `GET`. +Será llamada por **FastAPI** cuando reciba un request en la URL "`/`" usando una operación `GET`. -En este caso es una función `async`. +En este caso, es una función `async`. --- -También podrías definirla como una función estándar en lugar de `async def`: +También podrías definirla como una función normal en lugar de `async def`: -```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} -``` +{* ../../docs_src/first_steps/tutorial003.py hl[7] *} -!!! note "Nota" - Si no sabes la diferencia, revisa el [Async: *"¿Tienes prisa?"*](../async.md#in-a-hurry){.internal-link target=_blank}. +/// note | Nota -### Paso 5: devuelve el contenido +Si no sabes la diferencia, revisa la sección [Async: *"¿Tienes prisa?"*](../async.md#in-a-hurry){.internal-link target=_blank}. -```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +/// + +### Paso 5: retorna el contenido + +{* ../../docs_src/first_steps/tutorial001.py hl[8] *} -Puedes devolver `dict`, `list`, valores singulares como un `str`, `int`, etc. +Puedes retornar un `dict`, `list`, valores singulares como `str`, `int`, etc. -También puedes devolver modelos de Pydantic (ya verás más sobre esto más adelante). +También puedes retornar modelos de Pydantic (verás más sobre eso más adelante). -Hay muchos objetos y modelos que pueden ser convertidos automáticamente a JSON (incluyendo ORMs, etc.). Intenta usar tus favoritos, es muy probable que ya tengan soporte. +Hay muchos otros objetos y modelos que serán automáticamente convertidos a JSON (incluyendo ORMs, etc). Intenta usar tus favoritos, es altamente probable que ya sean compatibles. -## Repaso +## Recapitulación * Importa `FastAPI`. -* Crea un instance de `app`. -* Escribe un **decorador de operación de path** (como `@app.get("/")`). -* Escribe una **función de la operación de path** (como `def root(): ...` arriba). -* Corre el servidor de desarrollo (como `uvicorn main:app --reload`). +* Crea una instancia `app`. +* Escribe un **path operation decorator** usando decoradores como `@app.get("/")`. +* Define una **path operation function**; por ejemplo, `def root(): ...`. +* Ejecuta el servidor de desarrollo usando el comando `fastapi dev`. diff --git a/docs/es/docs/tutorial/handling-errors.md b/docs/es/docs/tutorial/handling-errors.md new file mode 100644 index 000000000..2e4464989 --- /dev/null +++ b/docs/es/docs/tutorial/handling-errors.md @@ -0,0 +1,255 @@ +# Manejo de Errores + +Existen muchas situaciones en las que necesitas notificar un error a un cliente que está usando tu API. + +Este cliente podría ser un navegador con un frontend, un código de otra persona, un dispositivo IoT, etc. + +Podrías necesitar decirle al cliente que: + +* El cliente no tiene suficientes privilegios para esa operación. +* El cliente no tiene acceso a ese recurso. +* El ítem al que el cliente intentaba acceder no existe. +* etc. + +En estos casos, normalmente devolverías un **código de estado HTTP** en el rango de **400** (de 400 a 499). + +Esto es similar a los códigos de estado HTTP 200 (de 200 a 299). Esos códigos de estado "200" significan que de alguna manera hubo un "éxito" en el request. + +Los códigos de estado en el rango de 400 significan que hubo un error por parte del cliente. + +¿Recuerdas todos esos errores de **"404 Not Found"** (y chistes)? + +## Usa `HTTPException` + +Para devolver responses HTTP con errores al cliente, usa `HTTPException`. + +### Importa `HTTPException` + +{* ../../docs_src/handling_errors/tutorial001.py hl[1] *} + +### Lanza un `HTTPException` en tu código + +`HTTPException` es una excepción de Python normal con datos adicionales relevantes para APIs. + +Debido a que es una excepción de Python, no la `return`, sino que la `raise`. + +Esto también significa que si estás dentro de una función de utilidad que estás llamando dentro de tu *path operation function*, y lanzas el `HTTPException` desde dentro de esa función de utilidad, no se ejecutará el resto del código en la *path operation function*, terminará ese request de inmediato y enviará el error HTTP del `HTTPException` al cliente. + +El beneficio de lanzar una excepción en lugar de `return`ar un valor será más evidente en la sección sobre Dependencias y Seguridad. + +En este ejemplo, cuando el cliente solicita un ítem por un ID que no existe, lanza una excepción con un código de estado de `404`: + +{* ../../docs_src/handling_errors/tutorial001.py hl[11] *} + +### El response resultante + +Si el cliente solicita `http://example.com/items/foo` (un `item_id` `"foo"`), ese cliente recibirá un código de estado HTTP de 200, y un response JSON de: + +```JSON +{ + "item": "The Foo Wrestlers" +} +``` + +Pero si el cliente solicita `http://example.com/items/bar` (un `item_id` inexistente `"bar"`), ese cliente recibirá un código de estado HTTP de 404 (el error "no encontrado"), y un response JSON de: + +```JSON +{ + "detail": "Item not found" +} +``` + +/// tip | Consejo + +Cuando lanzas un `HTTPException`, puedes pasar cualquier valor que pueda convertirse a JSON como el parámetro `detail`, no solo `str`. + +Podrías pasar un `dict`, un `list`, etc. + +Son manejados automáticamente por **FastAPI** y convertidos a JSON. + +/// + +## Agrega headers personalizados + +Existen algunas situaciones en las que es útil poder agregar headers personalizados al error HTTP. Por ejemplo, para algunos tipos de seguridad. + +Probablemente no necesitarás usarlos directamente en tu código. + +Pero en caso de que los necesites para un escenario avanzado, puedes agregar headers personalizados: + +{* ../../docs_src/handling_errors/tutorial002.py hl[14] *} + +## Instalar manejadores de excepciones personalizados + +Puedes agregar manejadores de excepciones personalizados con las mismas utilidades de excepciones de Starlette. + +Supongamos que tienes una excepción personalizada `UnicornException` que tú (o un paquete que usas) podría lanzar. + +Y quieres manejar esta excepción globalmente con FastAPI. + +Podrías agregar un manejador de excepciones personalizado con `@app.exception_handler()`: + +{* ../../docs_src/handling_errors/tutorial003.py hl[5:7,13:18,24] *} + +Aquí, si solicitas `/unicorns/yolo`, la *path operation* lanzará un `UnicornException`. + +Pero será manejado por el `unicorn_exception_handler`. + +Así que recibirás un error limpio, con un código de estado HTTP de `418` y un contenido JSON de: + +```JSON +{"message": "Oops! yolo did something. There goes a rainbow..."} +``` + +/// note | Nota Técnica + +También podrías usar `from starlette.requests import Request` y `from starlette.responses import JSONResponse`. + +**FastAPI** ofrece las mismas `starlette.responses` como `fastapi.responses` solo como una conveniencia para ti, el desarrollador. Pero la mayoría de los responses disponibles vienen directamente de Starlette. Lo mismo con `Request`. + +/// + +## Sobrescribir los manejadores de excepciones predeterminados + +**FastAPI** tiene algunos manejadores de excepciones predeterminados. + +Estos manejadores se encargan de devolver los responses JSON predeterminadas cuando lanzas un `HTTPException` y cuando el request tiene datos inválidos. + +Puedes sobrescribir estos manejadores de excepciones con los tuyos propios. + +### Sobrescribir excepciones de validación de request + +Cuando un request contiene datos inválidos, **FastAPI** lanza internamente un `RequestValidationError`. + +Y también incluye un manejador de excepciones predeterminado para ello. + +Para sobrescribirlo, importa el `RequestValidationError` y úsalo con `@app.exception_handler(RequestValidationError)` para decorar el manejador de excepciones. + +El manejador de excepciones recibirá un `Request` y la excepción. + +{* ../../docs_src/handling_errors/tutorial004.py hl[2,14:16] *} + +Ahora, si vas a `/items/foo`, en lugar de obtener el error JSON por defecto con: + +```JSON +{ + "detail": [ + { + "loc": [ + "path", + "item_id" + ], + "msg": "value is not a valid integer", + "type": "type_error.integer" + } + ] +} +``` + +obtendrás una versión en texto, con: + +``` +1 validation error +path -> item_id + value is not a valid integer (type=type_error.integer) +``` + +#### `RequestValidationError` vs `ValidationError` + +/// warning | Advertencia + +Estos son detalles técnicos que podrías omitir si no es importante para ti en este momento. + +/// + +`RequestValidationError` es una subclase de `ValidationError` de Pydantic. + +**FastAPI** la usa para que, si usas un modelo Pydantic en `response_model`, y tus datos tienen un error, lo verás en tu log. + +Pero el cliente/usuario no lo verá. En su lugar, el cliente recibirá un "Error Interno del Servidor" con un código de estado HTTP `500`. + +Debería ser así porque si tienes un `ValidationError` de Pydantic en tu *response* o en cualquier lugar de tu código (no en el *request* del cliente), en realidad es un bug en tu código. + +Y mientras lo arreglas, tus clientes/usuarios no deberían tener acceso a información interna sobre el error, ya que eso podría exponer una vulnerabilidad de seguridad. + +### Sobrescribir el manejador de errores de `HTTPException` + +De la misma manera, puedes sobrescribir el manejador de `HTTPException`. + +Por ejemplo, podrías querer devolver un response de texto plano en lugar de JSON para estos errores: + +{* ../../docs_src/handling_errors/tutorial004.py hl[3:4,9:11,22] *} + +/// note | Nota Técnica + +También podrías usar `from starlette.responses import PlainTextResponse`. + +**FastAPI** ofrece las mismas `starlette.responses` como `fastapi.responses` solo como una conveniencia para ti, el desarrollador. Pero la mayoría de los responses disponibles vienen directamente de Starlette. + +/// + +### Usar el body de `RequestValidationError` + +El `RequestValidationError` contiene el `body` que recibió con datos inválidos. + +Podrías usarlo mientras desarrollas tu aplicación para registrar el body y depurarlo, devolverlo al usuario, etc. + +{* ../../docs_src/handling_errors/tutorial005.py hl[14] *} + +Ahora intenta enviar un ítem inválido como: + +```JSON +{ + "title": "towel", + "size": "XL" +} +``` + +Recibirás un response que te dirá que los datos son inválidos conteniendo el body recibido: + +```JSON hl_lines="12-15" +{ + "detail": [ + { + "loc": [ + "body", + "size" + ], + "msg": "value is not a valid integer", + "type": "type_error.integer" + } + ], + "body": { + "title": "towel", + "size": "XL" + } +} +``` + +#### `HTTPException` de FastAPI vs `HTTPException` de Starlette + +**FastAPI** tiene su propio `HTTPException`. + +Y la clase de error `HTTPException` de **FastAPI** hereda de la clase de error `HTTPException` de Starlette. + +La única diferencia es que el `HTTPException` de **FastAPI** acepta cualquier dato JSON-able para el campo `detail`, mientras que el `HTTPException` de Starlette solo acepta strings para ello. + +Así que puedes seguir lanzando un `HTTPException` de **FastAPI** como de costumbre en tu código. + +Pero cuando registras un manejador de excepciones, deberías registrarlo para el `HTTPException` de Starlette. + +De esta manera, si alguna parte del código interno de Starlette, o una extensión o complemento de Starlette, lanza un `HTTPException` de Starlette, tu manejador podrá capturarlo y manejarlo. + +En este ejemplo, para poder tener ambos `HTTPException` en el mismo código, las excepciones de Starlette son renombradas a `StarletteHTTPException`: + +```Python +from starlette.exceptions import HTTPException as StarletteHTTPException +``` + +### Reutilizar los manejadores de excepciones de **FastAPI** + +Si quieres usar la excepción junto con los mismos manejadores de excepciones predeterminados de **FastAPI**, puedes importar y reutilizar los manejadores de excepciones predeterminados de `fastapi.exception_handlers`: + +{* ../../docs_src/handling_errors/tutorial006.py hl[2:5,15,21] *} + +En este ejemplo solo estás `print`eando el error con un mensaje muy expresivo, pero te haces una idea. Puedes usar la excepción y luego simplemente reutilizar los manejadores de excepciones predeterminados. diff --git a/docs/es/docs/tutorial/header-param-models.md b/docs/es/docs/tutorial/header-param-models.md new file mode 100644 index 000000000..3676231e6 --- /dev/null +++ b/docs/es/docs/tutorial/header-param-models.md @@ -0,0 +1,56 @@ +# Modelos de Parámetros de Header + +Si tienes un grupo de **parámetros de header** relacionados, puedes crear un **modelo Pydantic** para declararlos. + +Esto te permitirá **reutilizar el modelo** en **múltiples lugares** y también declarar validaciones y metadatos para todos los parámetros al mismo tiempo. 😎 + +/// note | Nota + +Esto es compatible desde la versión `0.115.0` de FastAPI. 🤓 + +/// + +## Parámetros de Header con un Modelo Pydantic + +Declara los **parámetros de header** que necesitas en un **modelo Pydantic**, y luego declara el parámetro como `Header`: + +{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *} + +**FastAPI** **extraerá** los datos para **cada campo** de los **headers** en el request y te dará el modelo Pydantic que definiste. + +## Revisa la Documentación + +Puedes ver los headers requeridos en la interfaz de documentación en `/docs`: + +
+ +
+ +## Prohibir Headers Extra + +En algunos casos de uso especiales (probablemente no muy comunes), podrías querer **restringir** los headers que deseas recibir. + +Puedes usar la configuración del modelo de Pydantic para `prohibir` cualquier campo `extra`: + +{* ../../docs_src/header_param_models/tutorial002_an_py310.py hl[10] *} + +Si un cliente intenta enviar algunos **headers extra**, recibirán un response de **error**. + +Por ejemplo, si el cliente intenta enviar un header `tool` con un valor de `plumbus`, recibirán un response de **error** indicando que el parámetro de header `tool` no está permitido: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["header", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus", + } + ] +} +``` + +## Resumen + +Puedes usar **modelos Pydantic** para declarar **headers** en **FastAPI**. 😎 diff --git a/docs/es/docs/tutorial/header-params.md b/docs/es/docs/tutorial/header-params.md new file mode 100644 index 000000000..9c0112bb2 --- /dev/null +++ b/docs/es/docs/tutorial/header-params.md @@ -0,0 +1,91 @@ +# Parámetros de Header + +Puedes definir los parámetros de Header de la misma manera que defines los parámetros de `Query`, `Path` y `Cookie`. + +## Importar `Header` + +Primero importa `Header`: + +{* ../../docs_src/header_params/tutorial001_an_py310.py hl[3] *} + +## Declarar parámetros de `Header` + +Luego declara los parámetros de header usando la misma estructura que con `Path`, `Query` y `Cookie`. + +Puedes definir el valor por defecto así como toda la validación extra o los parámetros de anotaciones: + +{* ../../docs_src/header_params/tutorial001_an_py310.py hl[9] *} + +/// note | Detalles Técnicos + +`Header` es una clase "hermana" de `Path`, `Query` y `Cookie`. También hereda de la misma clase común `Param`. + +Pero recuerda que cuando importas `Query`, `Path`, `Header`, y otros de `fastapi`, en realidad son funciones que retornan clases especiales. + +/// + +/// info | Información + +Para declarar headers, necesitas usar `Header`, porque de otra forma los parámetros serían interpretados como parámetros de query. + +/// + +## Conversión automática + +`Header` tiene un poquito de funcionalidad extra además de lo que proporcionan `Path`, `Query` y `Cookie`. + +La mayoría de los headers estándar están separados por un carácter "guion", también conocido como el "símbolo menos" (`-`). + +Pero una variable como `user-agent` es inválida en Python. + +Así que, por defecto, `Header` convertirá los caracteres de los nombres de los parámetros de guion bajo (`_`) a guion (`-`) para extraer y documentar los headers. + +Además, los headers HTTP no diferencian entre mayúsculas y minúsculas, por lo que los puedes declarar con el estilo estándar de Python (también conocido como "snake_case"). + +Así que, puedes usar `user_agent` como normalmente lo harías en código Python, en lugar de necesitar capitalizar las primeras letras como `User_Agent` o algo similar. + +Si por alguna razón necesitas desactivar la conversión automática de guiones bajos a guiones, establece el parámetro `convert_underscores` de `Header` a `False`: + +{* ../../docs_src/header_params/tutorial002_an_py310.py hl[10] *} + +/// warning | Advertencia + +Antes de establecer `convert_underscores` a `False`, ten en cuenta que algunos proxies y servidores HTTP no permiten el uso de headers con guiones bajos. + +/// + +## Headers duplicados + +Es posible recibir headers duplicados. Eso significa, el mismo header con múltiples valores. + +Puedes definir esos casos usando una lista en la declaración del tipo. + +Recibirás todos los valores del header duplicado como una `list` de Python. + +Por ejemplo, para declarar un header de `X-Token` que puede aparecer más de una vez, puedes escribir: + +{* ../../docs_src/header_params/tutorial003_an_py310.py hl[9] *} + +Si te comunicas con esa *path operation* enviando dos headers HTTP como: + +``` +X-Token: foo +X-Token: bar +``` + +El response sería como: + +```JSON +{ + "X-Token values": [ + "bar", + "foo" + ] +} +``` + +## Recapitulación + +Declara headers con `Header`, usando el mismo patrón común que `Query`, `Path` y `Cookie`. + +Y no te preocupes por los guiones bajos en tus variables, **FastAPI** se encargará de convertirlos. diff --git a/docs/es/docs/tutorial/index.md b/docs/es/docs/tutorial/index.md index f0dff02b4..dcfc6cdfb 100644 --- a/docs/es/docs/tutorial/index.md +++ b/docs/es/docs/tutorial/index.md @@ -1,78 +1,102 @@ -# Tutorial - Guía de Usuario +# Tutorial - Guía del Usuario -Este tutorial te muestra cómo usar **FastAPI** con la mayoría de sus características paso a paso. +Este tutorial te muestra cómo usar **FastAPI** con la mayoría de sus funcionalidades, paso a paso. -Cada sección se basa gradualmente en las anteriores, pero está estructurada en temas separados, así puedes ir directamente a cualquier tema en concreto para resolver tus necesidades específicas sobre la API. +Cada sección se basa gradualmente en las anteriores, pero está estructurada para separar temas, de manera que puedas ir directamente a cualquier sección específica para resolver tus necesidades específicas de API. -Funciona también como una referencia futura, para que puedas volver y ver exactamente lo que necesitas. +También está diseñado para funcionar como una referencia futura para que puedas volver y ver exactamente lo que necesitas. ## Ejecuta el código -Todos los bloques de código se pueden copiar y usar directamente (en realidad son archivos Python probados). +Todos los bloques de código pueden ser copiados y usados directamente (de hecho, son archivos Python probados). -Para ejecutar cualquiera de los ejemplos, copia el código en un archivo llamado `main.py`, y ejecuta `uvicorn` de la siguiente manera en tu terminal: +Para ejecutar cualquiera de los ejemplos, copia el código a un archivo `main.py`, y comienza `fastapi dev` con:
```console -$ uvicorn main:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -INFO: Started reloader process [28720] -INFO: Started server process [28722] -INFO: Waiting for application startup. -INFO: Application startup complete. +$ fastapi dev main.py +INFO Using path main.py +INFO Resolved absolute path /home/user/code/awesomeapp/main.py +INFO Searching for package file structure from directories with __init__.py files +INFO Importing from /home/user/code/awesomeapp + + ╭─ Python module file ─╮ + │ │ + │ 🐍 main.py │ + │ │ + ╰──────────────────────╯ + +INFO Importing module main +INFO Found importable FastAPI app + + ╭─ Importable FastAPI app ─╮ + │ │ + │ from main import app │ + │ │ + ╰──────────────────────────╯ + +INFO Using import string main:app + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + fastapi run + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [2265862] using WatchFiles +INFO: Started server process [2265873] +INFO: Waiting for application startup. +INFO: Application startup complete. + ```
-Se **RECOMIENDA** que escribas o copies el código, lo edites y lo ejecutes localmente. +Es **ALTAMENTE recomendable** que escribas o copies el código, lo edites y lo ejecutes localmente. -Usarlo en tu editor de código es lo que realmente te muestra los beneficios de FastAPI, al ver la poca cantidad de código que tienes que escribir, todas las verificaciones de tipo, auto-completado, etc. +Usarlo en tu editor es lo que realmente te muestra los beneficios de FastAPI, al ver cuán poco código tienes que escribir, todos los chequeos de tipos, autocompletado, etc. --- -## Instala FastAPI +## Instalar FastAPI El primer paso es instalar FastAPI. -Para el tutorial, es posible que quieras instalarlo con todas las dependencias y características opcionales: +Asegúrate de crear un [entorno virtual](../virtual-environments.md){.internal-link target=_blank}, actívalo, y luego **instala FastAPI**:
```console -$ pip install "fastapi[all]" +$ pip install "fastapi[standard]" ---> 100% ```
-...eso también incluye `uvicorn` que puedes usar como el servidor que ejecuta tu código. - -!!! nota - También puedes instalarlo parte por parte. - - Esto es lo que probablemente harías una vez que desees implementar tu aplicación en producción: - - ``` - pip install fastapi - ``` +/// note | Nota - También debes instalar `uvicorn` para que funcione como tu servidor: +Cuando instalas con `pip install "fastapi[standard]"` viene con algunas dependencias opcionales estándar por defecto. - ``` - pip install "uvicorn[standard]" - ``` +Si no quieres tener esas dependencias opcionales, en su lugar puedes instalar `pip install fastapi`. - Y lo mismo para cada una de las dependencias opcionales que quieras utilizar. +/// -## Guía Avanzada de Usuario +## Guía Avanzada del Usuario -También hay una **Guía Avanzada de Usuario** que puedes leer luego de este **Tutorial - Guía de Usuario**. +También hay una **Guía Avanzada del Usuario** que puedes leer después de esta **Tutorial - Guía del Usuario**. -La **Guía Avanzada de Usuario**, se basa en este tutorial, utiliza los mismos conceptos y enseña algunas características adicionales. +La **Guía Avanzada del Usuario** se basa en esta, utiliza los mismos conceptos y te enseña algunas funcionalidades adicionales. -Pero primero deberías leer el **Tutorial - Guía de Usuario** (lo que estas leyendo ahora mismo). +Pero primero deberías leer la **Tutorial - Guía del Usuario** (lo que estás leyendo ahora mismo). -La guía esa diseñada para que puedas crear una aplicación completa con solo el **Tutorial - Guía de Usuario**, y luego extenderlo de diferentes maneras, según tus necesidades, utilizando algunas de las ideas adicionales de la **Guía Avanzada de Usuario**. +Está diseñada para que puedas construir una aplicación completa solo con la **Tutorial - Guía del Usuario**, y luego extenderla de diferentes maneras, dependiendo de tus necesidades, utilizando algunas de las ideas adicionales de la **Guía Avanzada del Usuario**. diff --git a/docs/es/docs/tutorial/metadata.md b/docs/es/docs/tutorial/metadata.md new file mode 100644 index 000000000..1561e4ae3 --- /dev/null +++ b/docs/es/docs/tutorial/metadata.md @@ -0,0 +1,120 @@ +# Metadata y URLs de Docs + +Puedes personalizar varias configuraciones de metadata en tu aplicación **FastAPI**. + +## Metadata para la API + +Puedes establecer los siguientes campos que se usan en la especificación OpenAPI y en las interfaces automáticas de documentación de la API: + +| Parámetro | Tipo | Descripción | +|------------|------|-------------| +| `title` | `str` | El título de la API. | +| `summary` | `str` | Un resumen corto de la API. Disponible desde OpenAPI 3.1.0, FastAPI 0.99.0. | +| `description` | `str` | Una breve descripción de la API. Puede usar Markdown. | +| `version` | `string` | La versión de la API. Esta es la versión de tu propia aplicación, no de OpenAPI. Por ejemplo, `2.5.0`. | +| `terms_of_service` | `str` | Una URL a los Términos de Servicio para la API. Si se proporciona, debe ser una URL. | +| `contact` | `dict` | La información de contacto para la API expuesta. Puede contener varios campos.
contact fields
ParámetroTipoDescripción
namestrEl nombre identificativo de la persona/organización de contacto.
urlstrLa URL que apunta a la información de contacto. DEBE tener el formato de una URL.
emailstrLa dirección de correo electrónico de la persona/organización de contacto. DEBE tener el formato de una dirección de correo.
| +| `license_info` | `dict` | La información de la licencia para la API expuesta. Puede contener varios campos.
license_info fields
ParámetroTipoDescripción
namestrREQUERIDO (si se establece un license_info). El nombre de la licencia utilizada para la API.
identifierstrUna expresión de licencia SPDX para la API. El campo identifier es mutuamente excluyente del campo url. Disponible desde OpenAPI 3.1.0, FastAPI 0.99.0.
urlstrUna URL a la licencia utilizada para la API. DEBE tener el formato de una URL.
| + +Puedes configurarlos de la siguiente manera: + +{* ../../docs_src/metadata/tutorial001.py hl[3:16, 19:32] *} + +/// tip | Consejo + +Puedes escribir Markdown en el campo `description` y se mostrará en el resultado. + +/// + +Con esta configuración, la documentación automática de la API se vería así: + + + +## Identificador de licencia + +Desde OpenAPI 3.1.0 y FastAPI 0.99.0, también puedes establecer la `license_info` con un `identifier` en lugar de una `url`. + +Por ejemplo: + +{* ../../docs_src/metadata/tutorial001_1.py hl[31] *} + +## Metadata para etiquetas + +También puedes agregar metadata adicional para las diferentes etiquetas usadas para agrupar tus path operations con el parámetro `openapi_tags`. + +Este toma una list que contiene un diccionario para cada etiqueta. + +Cada diccionario puede contener: + +* `name` (**requerido**): un `str` con el mismo nombre de etiqueta que usas en el parámetro `tags` en tus *path operations* y `APIRouter`s. +* `description`: un `str` con una breve descripción de la etiqueta. Puede tener Markdown y se mostrará en la interfaz de documentación. +* `externalDocs`: un `dict` que describe documentación externa con: + * `description`: un `str` con una breve descripción para la documentación externa. + * `url` (**requerido**): un `str` con la URL para la documentación externa. + +### Crear metadata para etiquetas + +Probemos eso en un ejemplo con etiquetas para `users` y `items`. + +Crea metadata para tus etiquetas y pásala al parámetro `openapi_tags`: + +{* ../../docs_src/metadata/tutorial004.py hl[3:16,18] *} + +Nota que puedes utilizar Markdown dentro de las descripciones, por ejemplo "login" se mostrará en negrita (**login**) y "fancy" se mostrará en cursiva (_fancy_). + +/// tip | Consejo + +No tienes que agregar metadata para todas las etiquetas que uses. + +/// + +### Usar tus etiquetas + +Usa el parámetro `tags` con tus *path operations* (y `APIRouter`s) para asignarlas a diferentes etiquetas: + +{* ../../docs_src/metadata/tutorial004.py hl[21,26] *} + +/// info | Información + +Lee más sobre etiquetas en [Configuración de Path Operation](path-operation-configuration.md#tags){.internal-link target=_blank}. + +/// + +### Revisa la documentación + +Ahora, si revisas la documentación, mostrará toda la metadata adicional: + + + +### Orden de las etiquetas + +El orden de cada diccionario de metadata de etiqueta también define el orden mostrado en la interfaz de documentación. + +Por ejemplo, aunque `users` iría después de `items` en orden alfabético, se muestra antes porque agregamos su metadata como el primer diccionario en la list. + +## URL de OpenAPI + +Por defecto, el esquema OpenAPI se sirve en `/openapi.json`. + +Pero puedes configurarlo con el parámetro `openapi_url`. + +Por ejemplo, para configurarlo para que se sirva en `/api/v1/openapi.json`: + +{* ../../docs_src/metadata/tutorial002.py hl[3] *} + +Si quieres deshabilitar el esquema OpenAPI completamente, puedes establecer `openapi_url=None`, eso también deshabilitará las interfaces de usuario de documentación que lo usan. + +## URLs de Docs + +Puedes configurar las dos interfaces de usuario de documentación incluidas: + +* **Swagger UI**: servida en `/docs`. + * Puedes establecer su URL con el parámetro `docs_url`. + * Puedes deshabilitarla estableciendo `docs_url=None`. +* **ReDoc**: servida en `/redoc`. + * Puedes establecer su URL con el parámetro `redoc_url`. + * Puedes deshabilitarla estableciendo `redoc_url=None`. + +Por ejemplo, para configurar Swagger UI para que se sirva en `/documentation` y deshabilitar ReDoc: + +{* ../../docs_src/metadata/tutorial003.py hl[3] *} diff --git a/docs/es/docs/tutorial/middleware.md b/docs/es/docs/tutorial/middleware.md new file mode 100644 index 000000000..296374525 --- /dev/null +++ b/docs/es/docs/tutorial/middleware.md @@ -0,0 +1,72 @@ +# Middleware + +Puedes añadir middleware a las aplicaciones de **FastAPI**. + +Un "middleware" es una función que trabaja con cada **request** antes de que sea procesada por cualquier *path operation* específica. Y también con cada **response** antes de devolverla. + +* Toma cada **request** que llega a tu aplicación. +* Puede entonces hacer algo a esa **request** o ejecutar cualquier código necesario. +* Luego pasa la **request** para que sea procesada por el resto de la aplicación (por alguna *path operation*). +* Después toma la **response** generada por la aplicación (por alguna *path operation*). +* Puede hacer algo a esa **response** o ejecutar cualquier código necesario. +* Luego devuelve la **response**. + +/// note | Detalles Técnicos + +Si tienes dependencias con `yield`, el código de salida se ejecutará *después* del middleware. + +Si hubiera alguna tarea en segundo plano (documentada más adelante), se ejecutará *después* de todo el middleware. + +/// + +## Crear un middleware + +Para crear un middleware usas el decorador `@app.middleware("http")` encima de una función. + +La función middleware recibe: + +* La `request`. +* Una función `call_next` que recibirá la `request` como parámetro. + * Esta función pasará la `request` a la correspondiente *path operation*. + * Luego devuelve la `response` generada por la correspondiente *path operation*. +* Puedes entonces modificar aún más la `response` antes de devolverla. + +{* ../../docs_src/middleware/tutorial001.py hl[8:9,11,14] *} + +/// tip | Consejo + +Ten en cuenta que los custom proprietary headers se pueden añadir usando el prefijo 'X-'. + +Pero si tienes custom headers que deseas que un cliente en un navegador pueda ver, necesitas añadirlos a tus configuraciones de CORS ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) usando el parámetro `expose_headers` documentado en la documentación de CORS de Starlette. + +/// + +/// note | Detalles Técnicos + +También podrías usar `from starlette.requests import Request`. + +**FastAPI** lo proporciona como una conveniencia para ti, el desarrollador. Pero viene directamente de Starlette. + +/// + +### Antes y después de la `response` + +Puedes añadir código que se ejecute con la `request`, antes de que cualquier *path operation* la reciba. + +Y también después de que se genere la `response`, antes de devolverla. + +Por ejemplo, podrías añadir un custom header `X-Process-Time` que contenga el tiempo en segundos que tomó procesar la request y generar una response: + +{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *} + +/// tip | Consejo + +Aquí usamos `time.perf_counter()` en lugar de `time.time()` porque puede ser más preciso para estos casos de uso. 🤓 + +/// + +## Otros middlewares + +Más adelante puedes leer sobre otros middlewares en la [Guía del Usuario Avanzado: Middleware Avanzado](../advanced/middleware.md){.internal-link target=_blank}. + +Leerás sobre cómo manejar CORS con un middleware en la siguiente sección. diff --git a/docs/es/docs/tutorial/path-operation-configuration.md b/docs/es/docs/tutorial/path-operation-configuration.md new file mode 100644 index 000000000..909cd69b9 --- /dev/null +++ b/docs/es/docs/tutorial/path-operation-configuration.md @@ -0,0 +1,107 @@ +# Configuración de Path Operation + +Hay varios parámetros que puedes pasar a tu *path operation decorator* para configurarlo. + +/// warning | Advertencia + +Ten en cuenta que estos parámetros se pasan directamente al *path operation decorator*, no a tu *path operation function*. + +/// + +## Código de Estado del Response + +Puedes definir el `status_code` (HTTP) que se utilizará en el response de tu *path operation*. + +Puedes pasar directamente el código `int`, como `404`. + +Pero si no recuerdas para qué es cada código numérico, puedes usar las constantes atajo en `status`: + +{* ../../docs_src/path_operation_configuration/tutorial001_py310.py hl[1,15] *} + +Ese código de estado se usará en el response y se añadirá al esquema de OpenAPI. + +/// note | Detalles Técnicos + +También podrías usar `from starlette import status`. + +**FastAPI** ofrece el mismo `starlette.status` como `fastapi.status` solo por conveniencia para ti, el desarrollador. Pero viene directamente de Starlette. + +/// + +## Tags + +Puedes añadir tags a tu *path operation*, pasando el parámetro `tags` con un `list` de `str` (comúnmente solo una `str`): + +{* ../../docs_src/path_operation_configuration/tutorial002_py310.py hl[15,20,25] *} + +Serán añadidas al esquema de OpenAPI y usadas por las interfaces de documentación automática: + + + +### Tags con Enums + +Si tienes una gran aplicación, podrías terminar acumulando **varias tags**, y querrías asegurarte de que siempre uses la **misma tag** para *path operations* relacionadas. + +En estos casos, podría tener sentido almacenar las tags en un `Enum`. + +**FastAPI** soporta eso de la misma manera que con strings normales: + +{* ../../docs_src/path_operation_configuration/tutorial002b.py hl[1,8:10,13,18] *} + +## Resumen y Descripción + +Puedes añadir un `summary` y `description`: + +{* ../../docs_src/path_operation_configuration/tutorial003_py310.py hl[18:19] *} + +## Descripción desde docstring + +Como las descripciones tienden a ser largas y cubrir múltiples líneas, puedes declarar la descripción de la *path operation* en la docstring de la función y **FastAPI** la leerá desde allí. + +Puedes escribir Markdown en el docstring, se interpretará y mostrará correctamente (teniendo en cuenta la indentación del docstring). + +{* ../../docs_src/path_operation_configuration/tutorial004_py310.py hl[17:25] *} + +Será usado en la documentación interactiva: + + + +## Descripción del Response + +Puedes especificar la descripción del response con el parámetro `response_description`: + +{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[19] *} + +/// info | Información + +Ten en cuenta que `response_description` se refiere específicamente al response, mientras que `description` se refiere a la *path operation* en general. + +/// + +/// check | Revisa + +OpenAPI especifica que cada *path operation* requiere una descripción de response. + +Entonces, si no proporcionas una, **FastAPI** generará automáticamente una de "Response exitoso". + +/// + + + +## Deprecar una *path operation* + +Si necesitas marcar una *path operation* como deprecated, pero sin eliminarla, pasa el parámetro `deprecated`: + +{* ../../docs_src/path_operation_configuration/tutorial006.py hl[16] *} + +Se marcará claramente como deprecado en la documentación interactiva: + + + +Revisa cómo lucen las *path operations* deprecadas y no deprecadas: + + + +## Resumen + +Puedes configurar y añadir metadatos a tus *path operations* fácilmente pasando parámetros a los *path operation decorators*. diff --git a/docs/es/docs/tutorial/path-params-numeric-validations.md b/docs/es/docs/tutorial/path-params-numeric-validations.md new file mode 100644 index 000000000..44d73b5ed --- /dev/null +++ b/docs/es/docs/tutorial/path-params-numeric-validations.md @@ -0,0 +1,164 @@ +# Parámetros de Path y Validaciones Numéricas + +De la misma manera que puedes declarar más validaciones y metadatos para los parámetros de query con `Query`, puedes declarar el mismo tipo de validaciones y metadatos para los parámetros de path con `Path`. + +## Importar Path + +Primero, importa `Path` de `fastapi`, e importa `Annotated`: + +{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *} + +/// info | Información + +FastAPI agregó soporte para `Annotated` (y comenzó a recomendar su uso) en la versión 0.95.0. + +Si tienes una versión anterior, obtendrás errores al intentar usar `Annotated`. + +Asegúrate de [Actualizar la versión de FastAPI](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} a al menos la 0.95.1 antes de usar `Annotated`. + +/// + +## Declarar metadatos + +Puedes declarar todos los mismos parámetros que para `Query`. + +Por ejemplo, para declarar un valor de metadato `title` para el parámetro de path `item_id` puedes escribir: + +{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *} + +/// note | Nota + +Un parámetro de path siempre es requerido ya que tiene que formar parte del path. Incluso si lo declaras con `None` o le asignas un valor por defecto, no afectará en nada, siempre será requerido. + +/// + +## Ordena los parámetros como necesites + +/// tip | Consejo + +Esto probablemente no es tan importante o necesario si usas `Annotated`. + +/// + +Supongamos que quieres declarar el parámetro de query `q` como un `str` requerido. + +Y no necesitas declarar nada más para ese parámetro, así que realmente no necesitas usar `Query`. + +Pero aún necesitas usar `Path` para el parámetro de path `item_id`. Y no quieres usar `Annotated` por alguna razón. + +Python se quejará si pones un valor con un "default" antes de un valor que no tenga un "default". + +Pero puedes reordenarlos y poner el valor sin un default (el parámetro de query `q`) primero. + +No importa para **FastAPI**. Detectará los parámetros por sus nombres, tipos y declaraciones por defecto (`Query`, `Path`, etc.), no le importa el orden. + +Así que puedes declarar tu función como: + +//// tab | Python 3.8 non-Annotated + +/// tip | Consejo + +Prefiere usar la versión `Annotated` si es posible. + +/// + +{* ../../docs_src/path_params_numeric_validations/tutorial002.py hl[7] *} + +//// + +Pero ten en cuenta que si usas `Annotated`, no tendrás este problema, no importará ya que no estás usando los valores por defecto de los parámetros de la función para `Query()` o `Path()`. + +{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py *} + +## Ordena los parámetros como necesites, trucos + +/// tip | Consejo + +Esto probablemente no es tan importante o necesario si usas `Annotated`. + +/// + +Aquí hay un **pequeño truco** que puede ser útil, pero no lo necesitarás a menudo. + +Si quieres: + +* declarar el parámetro de query `q` sin un `Query` ni ningún valor por defecto +* declarar el parámetro de path `item_id` usando `Path` +* tenerlos en un orden diferente +* no usar `Annotated` + +...Python tiene una sintaxis especial para eso. + +Pasa `*`, como el primer parámetro de la función. + +Python no hará nada con ese `*`, pero sabrá que todos los parámetros siguientes deben ser llamados como argumentos de palabras clave (parejas key-value), también conocidos como kwargs. Incluso si no tienen un valor por defecto. + +{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *} + +### Mejor con `Annotated` + +Ten en cuenta que si usas `Annotated`, como no estás usando valores por defecto de los parámetros de la función, no tendrás este problema y probablemente no necesitarás usar `*`. + +{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *} + +## Validaciones numéricas: mayor o igual + +Con `Query` y `Path` (y otros que verás más adelante) puedes declarar restricciones numéricas. + +Aquí, con `ge=1`, `item_id` necesitará ser un número entero "`g`reater than or `e`qual" a `1`. + +{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *} + +## Validaciones numéricas: mayor que y menor o igual + +Lo mismo aplica para: + +* `gt`: `g`reater `t`han +* `le`: `l`ess than or `e`qual + +{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *} + +## Validaciones numéricas: flotantes, mayor y menor + +Las validaciones numéricas también funcionan para valores `float`. + +Aquí es donde se convierte en importante poder declarar gt y no solo ge. Ya que con esto puedes requerir, por ejemplo, que un valor sea mayor que `0`, incluso si es menor que `1`. + +Así, `0.5` sería un valor válido. Pero `0.0` o `0` no lo serían. + +Y lo mismo para lt. + +{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *} + +## Resumen + +Con `Query`, `Path` (y otros que aún no has visto) puedes declarar metadatos y validaciones de string de las mismas maneras que con [Parámetros de Query y Validaciones de String](query-params-str-validations.md){.internal-link target=_blank}. + +Y también puedes declarar validaciones numéricas: + +* `gt`: `g`reater `t`han +* `ge`: `g`reater than or `e`qual +* `lt`: `l`ess `t`han +* `le`: `l`ess than or `e`qual + +/// info | Información + +`Query`, `Path` y otras clases que verás más adelante son subclases de una clase común `Param`. + +Todas ellas comparten los mismos parámetros para validación adicional y metadatos que has visto. + +/// + +/// note | Nota técnica + +Cuando importas `Query`, `Path` y otros de `fastapi`, en realidad son funciones. + +Que cuando se llaman, retornan instances de clases con el mismo nombre. + +Así que importas `Query`, que es una función. Y cuando la llamas, retorna una instance de una clase también llamada `Query`. + +Estas funciones están allí (en lugar de usar simplemente las clases directamente) para que tu editor no marque errores sobre sus tipos. + +De esa forma puedes usar tu editor y herramientas de programación normales sin tener que agregar configuraciones personalizadas para omitir esos errores. + +/// diff --git a/docs/es/docs/tutorial/path-params.md b/docs/es/docs/tutorial/path-params.md index 765ae4140..12a1b647b 100644 --- a/docs/es/docs/tutorial/path-params.md +++ b/docs/es/docs/tutorial/path-params.md @@ -1,14 +1,12 @@ -# Parámetros de path +# Parámetros de Path -Puedes declarar los "parámetros" o "variables" con la misma sintaxis que usan los format strings de Python: +Puedes declarar "parámetros" o "variables" de path con la misma sintaxis que se usa en los format strings de Python: -```Python hl_lines="6-7" -{!../../../docs_src/path_params/tutorial001.py!} -``` +{* ../../docs_src/path_params/tutorial001.py hl[6:7] *} -El valor del parámetro de path `item_id` será pasado a tu función como el argumento `item_id`. +El valor del parámetro de path `item_id` se pasará a tu función como el argumento `item_id`. -Entonces, si corres este ejemplo y vas a http://127.0.0.1:8000/items/foo, verás una respuesta de: +Así que, si ejecutas este ejemplo y vas a http://127.0.0.1:8000/items/foo, verás un response de: ```JSON {"item_id":"foo"} @@ -16,175 +14,190 @@ Entonces, si corres este ejemplo y vas a Conversión de datos +## Conversión de datos -Si corres este ejemplo y abres tu navegador en http://127.0.0.1:8000/items/3 verás una respuesta de: +Si ejecutas este ejemplo y abres tu navegador en http://127.0.0.1:8000/items/3, verás un response de: ```JSON {"item_id":3} ``` -!!! check "Revisa" - Observa que el valor que recibió (y devolvió) tu función es `3`, como un Python `int`, y no un string `"3"`. +/// check | Revisa - Entonces, con esa declaración de tipos **FastAPI** te da "parsing" automático del request. +Nota que el valor que tu función recibió (y devolvió) es `3`, como un `int` de Python, no un string `"3"`. + +Entonces, con esa declaración de tipo, **FastAPI** te ofrece "parsing" automático de requests. + +/// ## Validación de datos -Pero si abres tu navegador en http://127.0.0.1:8000/items/foo verás este lindo error de HTTP: +Pero si vas al navegador en http://127.0.0.1:8000/items/foo, verás un bonito error HTTP de: ```JSON { - "detail": [ - { - "loc": [ - "path", - "item_id" - ], - "msg": "value is not a valid integer", - "type": "type_error.integer" - } - ] + "detail": [ + { + "type": "int_parsing", + "loc": [ + "path", + "item_id" + ], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "foo", + "url": "https://errors.pydantic.dev/2.1/v/int_parsing" + } + ] } ``` -debido a que el parámetro de path `item_id` tenía el valor `"foo"`, que no es un `int`. +porque el parámetro de path `item_id` tenía un valor de `"foo"`, que no es un `int`. + +El mismo error aparecería si proporcionaras un `float` en lugar de un `int`, como en: http://127.0.0.1:8000/items/4.2 -El mismo error aparecería si pasaras un `float` en vez de un `int` como en: http://127.0.0.1:8000/items/4.2 +/// check | Revisa -!!! check "Revisa" - Así, con la misma declaración de tipo de Python, **FastAPI** te da validación de datos. +Entonces, con la misma declaración de tipo de Python, **FastAPI** te ofrece validación de datos. - Observa que el error también muestra claramente el punto exacto en el que no pasó la validación. +Nota que el error también indica claramente el punto exacto donde la validación falló. - Esto es increíblemente útil cuando estás desarrollando y debugging código que interactúa con tu API. +Esto es increíblemente útil mientras desarrollas y depuras código que interactúa con tu API. + +/// ## Documentación -Cuando abras tu navegador en http://127.0.0.1:8000/docs verás la documentación automática e interactiva del API como: +Y cuando abras tu navegador en http://127.0.0.1:8000/docs, verás una documentación de API automática e interactiva como: -!!! check "Revisa" - Nuevamente, con la misma declaración de tipo de Python, **FastAPI** te da documentación automática e interactiva (integrándose con Swagger UI) +/// check | Revisa + +Nuevamente, solo con esa misma declaración de tipo de Python, **FastAPI** te ofrece documentación automática e interactiva (integrando Swagger UI). - Observa que el parámetro de path está declarado como un integer. +Nota que el parámetro de path está declarado como un entero. + +/// ## Beneficios basados en estándares, documentación alternativa -Debido a que el schema generado es del estándar OpenAPI hay muchas herramientas compatibles. +Y porque el esquema generado es del estándar OpenAPI, hay muchas herramientas compatibles. -Es por esto que **FastAPI** mismo provee una documentación alternativa de la API (usando ReDoc), a la que puedes acceder en http://127.0.0.1:8000/redoc: +Debido a esto, el propio **FastAPI** proporciona una documentación de API alternativa (usando ReDoc), a la cual puedes acceder en http://127.0.0.1:8000/redoc: -De la misma manera hay muchas herramientas compatibles. Incluyendo herramientas de generación de código para muchos lenguajes. +De la misma manera, hay muchas herramientas compatibles. Incluyendo herramientas de generación de código para muchos lenguajes. ## Pydantic -Toda la validación de datos es realizada tras bastidores por Pydantic, así que obtienes todos sus beneficios. Así sabes que estás en buenas manos. +Toda la validación de datos se realiza internamente con Pydantic, así que obtienes todos los beneficios de esta. Y sabes que estás en buenas manos. -Puedes usar las mismas declaraciones de tipos con `str`, `float`, `bool` y otros tipos de datos más complejos. +Puedes usar las mismas declaraciones de tipo con `str`, `float`, `bool` y muchos otros tipos de datos complejos. -Exploraremos varios de estos tipos en los próximos capítulos del tutorial. +Varios de estos se exploran en los siguientes capítulos del tutorial. ## El orden importa -Cuando creas *operaciones de path* puedes encontrarte con situaciones en las que tengas un path fijo. +Al crear *path operations*, puedes encontrarte en situaciones donde tienes un path fijo. -Digamos algo como `/users/me` que sea para obtener datos del usuario actual. +Como `/users/me`, imaginemos que es para obtener datos sobre el usuario actual. -... y luego puedes tener el path `/users/{user_id}` para obtener los datos sobre un usuario específico asociados a un ID de usuario. +Y luego también puedes tener un path `/users/{user_id}` para obtener datos sobre un usuario específico por algún ID de usuario. -Porque las *operaciones de path* son evaluadas en orden, tienes que asegurarte de que el path para `/users/me` sea declarado antes que el path para `/users/{user_id}`: +Debido a que las *path operations* se evalúan en orden, necesitas asegurarte de que el path para `/users/me` se declara antes que el de `/users/{user_id}`: -```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003.py!} -``` +{* ../../docs_src/path_params/tutorial003.py hl[6,11] *} + +De lo contrario, el path para `/users/{user_id}` también coincidiría para `/users/me`, "pensando" que está recibiendo un parámetro `user_id` con un valor de `"me"`. + +De manera similar, no puedes redefinir una path operation: + +{* ../../docs_src/path_params/tutorial003b.py hl[6,11] *} -De otra manera el path para `/users/{user_id}` coincidiría también con `/users/me` "pensando" que está recibiendo el parámetro `user_id` con el valor `"me"`. +La primera siempre será utilizada ya que el path coincide primero. ## Valores predefinidos -Si tienes una *operación de path* que recibe un *parámetro de path* pero quieres que los valores posibles del *parámetro de path* sean predefinidos puedes usar un `Enum` estándar de Python. +Si tienes una *path operation* que recibe un *path parameter*, pero quieres que los valores posibles válidos del *path parameter* estén predefinidos, puedes usar un `Enum` estándar de Python. -### Crea una clase `Enum` +### Crear una clase `Enum` -Importa `Enum` y crea una sub-clase que herede desde `str` y desde `Enum`. +Importa `Enum` y crea una subclase que herede de `str` y de `Enum`. -Al heredar desde `str` la documentación de la API podrá saber que los valores deben ser de tipo `string` y podrá mostrarlos correctamente. +Al heredar de `str`, la documentación de la API podrá saber que los valores deben ser de tipo `string` y podrá representarlos correctamente. -Luego crea atributos de clase con valores fijos, que serán los valores disponibles válidos: +Luego crea atributos de clase con valores fijos, que serán los valores válidos disponibles: -```Python hl_lines="1 6-9" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *} -!!! info "Información" - Las Enumerations (o enums) están disponibles en Python desde la versión 3.4. +/// info | Información -!!! tip "Consejo" - Si lo estás dudando, "AlexNet", "ResNet", y "LeNet" son solo nombres de modelos de Machine Learning. +Las enumeraciones (o enums) están disponibles en Python desde la versión 3.4. -### Declara un *parámetro de path* +/// -Luego, crea un *parámetro de path* con anotaciones de tipos usando la clase enum que creaste (`ModelName`): +/// tip | Consejo -```Python hl_lines="16" -{!../../../docs_src/path_params/tutorial005.py!} -``` +Si te estás preguntando, "AlexNet", "ResNet" y "LeNet" son solo nombres de modelos de Machine Learning. + +/// + +### Declarar un *path parameter* + +Luego crea un *path parameter* con una anotación de tipo usando la clase enum que creaste (`ModelName`): + +{* ../../docs_src/path_params/tutorial005.py hl[16] *} ### Revisa la documentación -Debido a que los valores disponibles para el *parámetro de path* están predefinidos, la documentación interactiva los puede mostrar bien: +Como los valores disponibles para el *path parameter* están predefinidos, la documentación interactiva puede mostrarlos de manera ordenada: -### Trabajando con los *enumerations* de Python +### Trabajando con *enumeraciones* de Python -El valor del *parámetro de path* será un *enumeration member*. +El valor del *path parameter* será un *miembro* de enumeración. -#### Compara *enumeration members* +#### Comparar *miembros* de enumeraciones -Puedes compararlo con el *enumeration member* en el enum (`ModelName`) que creaste: +Puedes compararlo con el *miembro* de enumeración en tu enum creada `ModelName`: -```Python hl_lines="17" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[17] *} -#### Obtén el *enumeration value* +#### Obtener el valor de *enumeración* -Puedes obtener el valor exacto (un `str` en este caso) usando `model_name.value`, o en general, `your_enum_member.value`: +Puedes obtener el valor actual (un `str` en este caso) usando `model_name.value`, o en general, `your_enum_member.value`: -```Python hl_lines="20" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[20] *} -!!! tip "Consejo" - También podrías obtener el valor `"lenet"` con `ModelName.lenet.value`. +/// tip | Consejo -#### Devuelve *enumeration members* +También podrías acceder al valor `"lenet"` con `ModelName.lenet.value`. -Puedes devolver *enum members* desde tu *operación de path* inclusive en un body de JSON anidado (por ejemplo, un `dict`). +/// -Ellos serán convertidos a sus valores correspondientes (strings en este caso) antes de devolverlos al cliente: +#### Devolver *miembros* de enumeración -```Python hl_lines="18 21 23" -{!../../../docs_src/path_params/tutorial005.py!} -``` +Puedes devolver *miembros de enum* desde tu *path operation*, incluso anidados en un cuerpo JSON (por ejemplo, un `dict`). + +Serán convertidos a sus valores correspondientes (cadenas en este caso) antes de devolverlos al cliente: + +{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *} -En tu cliente obtendrás una respuesta en JSON como: +En tu cliente recibirás un response JSON como: ```JSON { @@ -193,52 +206,53 @@ En tu cliente obtendrás una respuesta en JSON como: } ``` -## Parámetros de path parameters que contienen paths +## Parámetros de path conteniendo paths -Digamos que tienes una *operación de path* con un path `/files/{file_path}`. +Imaginemos que tienes una *path operation* con un path `/files/{file_path}`. -Pero necesitas que el mismo `file_path` contenga un path como `home/johndoe/myfile.txt`. +Pero necesitas que `file_path` en sí mismo contenga un *path*, como `home/johndoe/myfile.txt`. Entonces, la URL para ese archivo sería algo como: `/files/home/johndoe/myfile.txt`. ### Soporte de OpenAPI -OpenAPI no soporta una manera de declarar un *parámetro de path* que contenga un path, dado que esto podría llevar a escenarios que son difíciles de probar y definir. +OpenAPI no soporta una manera de declarar un *path parameter* para que contenga un *path* dentro, ya que eso podría llevar a escenarios que son difíciles de probar y definir. -Sin embargo, lo puedes hacer en **FastAPI** usando una de las herramientas internas de Starlette. +Sin embargo, todavía puedes hacerlo en **FastAPI**, usando una de las herramientas internas de Starlette. -La documentación seguirá funcionando, aunque no añadirá ninguna información diciendo que el parámetro debería contener un path. +Y la documentación seguiría funcionando, aunque no agregue ninguna documentación indicando que el parámetro debe contener un path. -### Convertidor de path +### Convertidor de Path -Usando una opción directamente desde Starlette puedes declarar un *parámetro de path* que contenga un path usando una URL como: +Usando una opción directamente de Starlette puedes declarar un *path parameter* conteniendo un *path* usando una URL como: ``` /files/{file_path:path} ``` -En este caso el nombre del parámetro es `file_path` y la última parte, `:path`, le dice que el parámetro debería coincidir con cualquier path. +En este caso, el nombre del parámetro es `file_path`, y la última parte, `:path`, indica que el parámetro debería coincidir con cualquier *path*. -Entonces lo puedes usar con: +Así que, puedes usarlo con: -```Python hl_lines="6" -{!../../../docs_src/path_params/tutorial004.py!} -``` +{* ../../docs_src/path_params/tutorial004.py hl[6] *} + +/// tip | Consejo + +Podrías necesitar que el parámetro contenga `/home/johndoe/myfile.txt`, con una barra inclinada (`/`) inicial. -!!! tip "Consejo" - Podrías necesitar que el parámetro contenga `/home/johndoe/myfile.txt` con un slash inicial (`/`). +En ese caso, la URL sería: `/files//home/johndoe/myfile.txt`, con una doble barra inclinada (`//`) entre `files` y `home`. - En este caso la URL sería `/files//home/johndoe/myfile.txt` con un slash doble (`//`) entre `files` y `home`. +/// -## Repaso +## Resumen -Con **FastAPI**, usando declaraciones de tipo de Python intuitivas y estándares, obtienes: +Con **FastAPI**, al usar declaraciones de tipo estándar de Python, cortas e intuitivas, obtienes: -* Soporte en el editor: chequeo de errores, auto-completado, etc. -* "Parsing" de datos +* Soporte del editor: chequeo de errores, autocompletado, etc. +* "parsing" de datos * Validación de datos -* Anotación de la API y documentación automática +* Anotación de API y documentación automática -Solo tienes que declararlos una vez. +Y solo tienes que declararlos una vez. -Esa es probablemente la principal ventaja visible de **FastAPI** sobre otros frameworks alternativos (aparte del rendimiento puro). +Probablemente esa sea la principal ventaja visible de **FastAPI** en comparación con otros frameworks alternativos (aparte del rendimiento bruto). diff --git a/docs/es/docs/tutorial/query-param-models.md b/docs/es/docs/tutorial/query-param-models.md new file mode 100644 index 000000000..8338fc358 --- /dev/null +++ b/docs/es/docs/tutorial/query-param-models.md @@ -0,0 +1,68 @@ +# Modelos de Parámetros Query + +Si tienes un grupo de **parámetros query** que están relacionados, puedes crear un **modelo de Pydantic** para declararlos. + +Esto te permitiría **reutilizar el modelo** en **múltiples lugares** y también declarar validaciones y metadatos para todos los parámetros de una vez. 😎 + +/// note | Nota + +Esto es compatible desde la versión `0.115.0` de FastAPI. 🤓 + +/// + +## Parámetros Query con un Modelo Pydantic + +Declara los **parámetros query** que necesitas en un **modelo de Pydantic**, y luego declara el parámetro como `Query`: + +{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *} + +**FastAPI** **extraerá** los datos para **cada campo** de los **parámetros query** en el request y te proporcionará el modelo de Pydantic que definiste. + +## Revisa la Documentación + +Puedes ver los parámetros query en la UI de documentación en `/docs`: + +
+ +
+ +## Prohibir Parámetros Query Extras + +En algunos casos de uso especiales (probablemente no muy comunes), podrías querer **restringir** los parámetros query que deseas recibir. + +Puedes usar la configuración del modelo de Pydantic para `forbid` cualquier campo `extra`: + +{* ../../docs_src/query_param_models/tutorial002_an_py310.py hl[10] *} + +Si un cliente intenta enviar algunos datos **extra** en los **parámetros query**, recibirán un response de **error**. + +Por ejemplo, si el cliente intenta enviar un parámetro query `tool` con un valor de `plumbus`, como: + +```http +https://example.com/items/?limit=10&tool=plumbus +``` + +Recibirán un response de **error** que les indica que el parámetro query `tool` no está permitido: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["query", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus" + } + ] +} +``` + +## Resumen + +Puedes usar **modelos de Pydantic** para declarar **parámetros query** en **FastAPI**. 😎 + +/// tip | Consejo + +Alerta de spoiler: también puedes usar modelos de Pydantic para declarar cookies y headers, pero leerás sobre eso más adelante en el tutorial. 🤫 + +/// diff --git a/docs/es/docs/tutorial/query-params-str-validations.md b/docs/es/docs/tutorial/query-params-str-validations.md new file mode 100644 index 000000000..9cb76156f --- /dev/null +++ b/docs/es/docs/tutorial/query-params-str-validations.md @@ -0,0 +1,499 @@ +# Parámetros de Query y Validaciones de String + +**FastAPI** te permite declarar información adicional y validación para tus parámetros. + +Tomemos esta aplicación como ejemplo: + +{* ../../docs_src/query_params_str_validations/tutorial001_py310.py hl[7] *} + +El parámetro de query `q` es del tipo `Union[str, None]` (o `str | None` en Python 3.10), lo que significa que es de tipo `str` pero también podría ser `None`, y de hecho, el valor por defecto es `None`, así que FastAPI sabrá que no es requerido. + +/// note | Nota + +FastAPI sabrá que el valor de `q` no es requerido por el valor por defecto `= None`. + +El `Union` en `Union[str, None]` permitirá a tu editor darte un mejor soporte y detectar errores. + +/// + +## Validaciones adicionales + +Vamos a hacer que, aunque `q` sea opcional, siempre que se proporcione, **su longitud no exceda los 50 caracteres**. + +### Importar `Query` y `Annotated` + +Para lograr eso, primero importa: + +* `Query` desde `fastapi` +* `Annotated` desde `typing` (o desde `typing_extensions` en Python por debajo de 3.9) + +//// tab | Python 3.10+ + +En Python 3.9 o superior, `Annotated` es parte de la biblioteca estándar, así que puedes importarlo desde `typing`. + +```Python hl_lines="1 3" +{!> ../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +En versiones de Python por debajo de 3.9 importas `Annotated` desde `typing_extensions`. + +Ya estará instalado con FastAPI. + +```Python hl_lines="3-4" +{!> ../../docs_src/query_params_str_validations/tutorial002_an.py!} +``` + +//// + +/// info | Información + +FastAPI añadió soporte para `Annotated` (y empezó a recomendarlo) en la versión 0.95.0. + +Si tienes una versión más antigua, obtendrás errores al intentar usar `Annotated`. + +Asegúrate de [Actualizar la versión de FastAPI](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} a al menos 0.95.1 antes de usar `Annotated`. + +/// + +## Usar `Annotated` en el tipo del parámetro `q` + +¿Recuerdas que te dije antes que `Annotated` puede ser usado para agregar metadatos a tus parámetros en la [Introducción a Tipos de Python](../python-types.md#type-hints-with-metadata-annotations){.internal-link target=_blank}? + +Ahora es el momento de usarlo con FastAPI. 🚀 + +Teníamos esta anotación de tipo: + +//// tab | Python 3.10+ + +```Python +q: str | None = None +``` + +//// + +//// tab | Python 3.8+ + +```Python +q: Union[str, None] = None +``` + +//// + +Lo que haremos es envolver eso con `Annotated`, para que se convierta en: + +//// tab | Python 3.10+ + +```Python +q: Annotated[str | None] = None +``` + +//// + +//// tab | Python 3.8+ + +```Python +q: Annotated[Union[str, None]] = None +``` + +//// + +Ambas versiones significan lo mismo, `q` es un parámetro que puede ser un `str` o `None`, y por defecto, es `None`. + +Ahora vamos a lo divertido. 🎉 + +## Agregar `Query` a `Annotated` en el parámetro `q` + +Ahora que tenemos este `Annotated` donde podemos poner más información (en este caso algunas validaciones adicionales), agrega `Query` dentro de `Annotated`, y establece el parámetro `max_length` a `50`: + +{* ../../docs_src/query_params_str_validations/tutorial002_an_py310.py hl[9] *} + +Nota que el valor por defecto sigue siendo `None`, por lo que el parámetro sigue siendo opcional. + +Pero ahora, al tener `Query(max_length=50)` dentro de `Annotated`, le estamos diciendo a FastAPI que queremos que tenga **validación adicional** para este valor, queremos que tenga un máximo de 50 caracteres. 😎 + +/// tip | Consejo + +Aquí estamos usando `Query()` porque este es un **parámetro de query**. Más adelante veremos otros como `Path()`, `Body()`, `Header()`, y `Cookie()`, que también aceptan los mismos argumentos que `Query()`. + +/// + +FastAPI ahora: + +* **Validará** los datos asegurándose de que la longitud máxima sea de 50 caracteres +* Mostrará un **error claro** para el cliente cuando los datos no sean válidos +* **Documentará** el parámetro en el OpenAPI esquema *path operation* (así aparecerá en la **UI de documentación automática**) + +## Alternativa (antigua): `Query` como valor por defecto + +Versiones anteriores de FastAPI (antes de 0.95.0) requerían que usaras `Query` como el valor por defecto de tu parámetro, en lugar de ponerlo en `Annotated`. Hay una alta probabilidad de que veas código usándolo alrededor, así que te lo explicaré. + +/// tip | Consejo + +Para nuevo código y siempre que sea posible, usa `Annotated` como se explicó arriba. Hay múltiples ventajas (explicadas a continuación) y no hay desventajas. 🍰 + +/// + +Así es como usarías `Query()` como el valor por defecto de tu parámetro de función, estableciendo el parámetro `max_length` a 50: + +{* ../../docs_src/query_params_str_validations/tutorial002_py310.py hl[7] *} + +Ya que en este caso (sin usar `Annotated`) debemos reemplazar el valor por defecto `None` en la función con `Query()`, ahora necesitamos establecer el valor por defecto con el parámetro `Query(default=None)`, esto sirve al mismo propósito de definir ese valor por defecto (al menos para FastAPI). + +Entonces: + +```Python +q: Union[str, None] = Query(default=None) +``` + +...hace que el parámetro sea opcional, con un valor por defecto de `None`, lo mismo que: + +```Python +q: Union[str, None] = None +``` + +Y en Python 3.10 y superior: + +```Python +q: str | None = Query(default=None) +``` + +...hace que el parámetro sea opcional, con un valor por defecto de `None`, lo mismo que: + +```Python +q: str | None = None +``` + +Pero las versiones de `Query` lo declaran explícitamente como un parámetro de query. + +/// info | Información + +Ten en cuenta que la parte más importante para hacer un parámetro opcional es la parte: + +```Python += None +``` + +o la parte: + +```Python += Query(default=None) +``` + +ya que usará ese `None` como el valor por defecto, y de esa manera hará el parámetro **no requerido**. + +La parte `Union[str, None]` permite que tu editor brinde un mejor soporte, pero no es lo que le dice a FastAPI que este parámetro no es requerido. + +/// + +Luego, podemos pasar más parámetros a `Query`. En este caso, el parámetro `max_length` que se aplica a los strings: + +```Python +q: Union[str, None] = Query(default=None, max_length=50) +``` + +Esto validará los datos, mostrará un error claro cuando los datos no sean válidos, y documentará el parámetro en el esquema del *path operation* de OpenaPI. + +### `Query` como valor por defecto o en `Annotated` + +Ten en cuenta que cuando uses `Query` dentro de `Annotated` no puedes usar el parámetro `default` para `Query`. + +En su lugar utiliza el valor por defecto real del parámetro de la función. De lo contrario, sería inconsistente. + +Por ejemplo, esto no está permitido: + +```Python +q: Annotated[str, Query(default="rick")] = "morty" +``` + +...porque no está claro si el valor por defecto debería ser `"rick"` o `"morty"`. + +Así que utilizarías (preferentemente): + +```Python +q: Annotated[str, Query()] = "rick" +``` + +...o en code bases más antiguos encontrarás: + +```Python +q: str = Query(default="rick") +``` + +### Ventajas de `Annotated` + +**Usar `Annotated` es recomendado** en lugar del valor por defecto en los parámetros de función, es **mejor** por múltiples razones. 🤓 + +El valor **por defecto** del **parámetro de función** es el valor **real por defecto**, eso es más intuitivo con Python en general. 😌 + +Podrías **llamar** a esa misma función en **otros lugares** sin FastAPI, y **funcionaría como se espera**. Si hay un parámetro **requerido** (sin un valor por defecto), tu **editor** te avisará con un error, **Python** también se quejará si lo ejecutas sin pasar el parámetro requerido. + +Cuando no usas `Annotated` y en su lugar usas el estilo de valor por defecto **(antiguo)**, si llamas a esa función sin FastAPI en **otros lugares**, tienes que **recordar** pasar los argumentos a la función para que funcione correctamente, de lo contrario, los valores serán diferentes de lo que esperas (por ejemplo, `QueryInfo` o algo similar en lugar de `str`). Y tu editor no se quejará, y Python no se quejará al ejecutar esa función, solo cuando los errores dentro de las operaciones hagan que funcione incorrectamente. + +Dado que `Annotated` puede tener más de una anotación de metadato, ahora podrías incluso usar la misma función con otras herramientas, como Typer. 🚀 + +## Agregar más validaciones + +También puedes agregar un parámetro `min_length`: + +{* ../../docs_src/query_params_str_validations/tutorial003_an_py310.py hl[10] *} + +## Agregar expresiones regulares + +Puedes definir una expresión regular `pattern` que el parámetro debe coincidir: + +{* ../../docs_src/query_params_str_validations/tutorial004_an_py310.py hl[11] *} + +Este patrón específico de expresión regular comprueba que el valor recibido del parámetro: + +* `^`: comience con los siguientes caracteres, no tiene caracteres antes. +* `fixedquery`: tiene el valor exacto `fixedquery`. +* `$`: termina allí, no tiene más caracteres después de `fixedquery`. + +Si te sientes perdido con todas estas ideas de **"expresión regular"**, no te preocupes. Son un tema difícil para muchas personas. Aún puedes hacer muchas cosas sin necesitar expresiones regulares todavía. + +Pero cuando las necesites y vayas a aprenderlas, ya sabes que puedes usarlas directamente en **FastAPI**. + +### Pydantic v1 `regex` en lugar de `pattern` + +Antes de la versión 2 de Pydantic y antes de FastAPI 0.100.0, el parámetro se llamaba `regex` en lugar de `pattern`, pero ahora está en desuso. + +Todavía podrías ver algo de código que lo usa: + +//// tab | Pydantic v1 + +{* ../../docs_src/query_params_str_validations/tutorial004_regex_an_py310.py hl[11] *} + +//// + +Pero que sepas que esto está deprecado y debería actualizarse para usar el nuevo parámetro `pattern`. 🤓 + +## Valores por defecto + +Puedes, por supuesto, usar valores por defecto diferentes de `None`. + +Digamos que quieres declarar el parámetro de query `q` para que tenga un `min_length` de `3`, y para que tenga un valor por defecto de `"fixedquery"`: + +{* ../../docs_src/query_params_str_validations/tutorial005_an_py39.py hl[9] *} + +/// note | Nota + +Tener un valor por defecto de cualquier tipo, incluyendo `None`, hace que el parámetro sea opcional (no requerido). + +/// + +## Parámetros requeridos + +Cuando no necesitamos declarar más validaciones o metadatos, podemos hacer que el parámetro de query `q` sea requerido simplemente no declarando un valor por defecto, como: + +```Python +q: str +``` + +en lugar de: + +```Python +q: Union[str, None] = None +``` + +Pero ahora lo estamos declarando con `Query`, por ejemplo, como: + +//// tab | Annotated + +```Python +q: Annotated[Union[str, None], Query(min_length=3)] = None +``` + +//// + +//// tab | non-Annotated + +```Python +q: Union[str, None] = Query(default=None, min_length=3) +``` + +//// + +Así que, cuando necesites declarar un valor como requerido mientras usas `Query`, simplemente puedes no declarar un valor por defecto: + +{* ../../docs_src/query_params_str_validations/tutorial006_an_py39.py hl[9] *} + +### Requerido, puede ser `None` + +Puedes declarar que un parámetro puede aceptar `None`, pero que aún así es requerido. Esto obligaría a los clientes a enviar un valor, incluso si el valor es `None`. + +Para hacer eso, puedes declarar que `None` es un tipo válido pero aún usar `...` como el valor por defecto: + +{* ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py hl[9] *} + +/// tip | Consejo + +Pydantic, que es lo que impulsa toda la validación y serialización de datos en FastAPI, tiene un comportamiento especial cuando usas `Optional` o `Union[Something, None]` sin un valor por defecto, puedes leer más al respecto en la documentación de Pydantic sobre Campos requeridos. + +/// + +/// tip | Consejo + +Recuerda que en la mayoría de los casos, cuando algo es requerido, puedes simplemente omitir el default, así que normalmente no tienes que usar `...`. + +/// + +## Lista de parámetros de Query / múltiples valores + +Cuando defines un parámetro de query explícitamente con `Query` también puedes declararlo para recibir una lista de valores, o dicho de otra manera, para recibir múltiples valores. + +Por ejemplo, para declarar un parámetro de query `q` que puede aparecer varias veces en la URL, puedes escribir: + +{* ../../docs_src/query_params_str_validations/tutorial011_an_py310.py hl[9] *} + +Entonces, con una URL como: + +``` +http://localhost:8000/items/?q=foo&q=bar +``` + +recibirías los múltiples valores del *query parameter* `q` (`foo` y `bar`) en una `list` de Python dentro de tu *path operation function*, en el *parámetro de función* `q`. + +Entonces, el response a esa URL sería: + +```JSON +{ + "q": [ + "foo", + "bar" + ] +} +``` + +/// tip | Consejo + +Para declarar un parámetro de query con un tipo de `list`, como en el ejemplo anterior, necesitas usar explícitamente `Query`, de lo contrario sería interpretado como un request body. + +/// + +La documentación interactiva de API se actualizará en consecuencia, para permitir múltiples valores: + + + +### Lista de parámetros de Query / múltiples valores con valores por defecto + +Y también puedes definir un valor por defecto `list` de valores si no se proporcionan ninguno: + +{* ../../docs_src/query_params_str_validations/tutorial012_an_py39.py hl[9] *} + +Si vas a: + +``` +http://localhost:8000/items/ +``` + +el valor por defecto de `q` será: `["foo", "bar"]` y tu response será: + +```JSON +{ + "q": [ + "foo", + "bar" + ] +} +``` + +#### Usando solo `list` + +También puedes usar `list` directamente en lugar de `List[str]` (o `list[str]` en Python 3.9+): + +{* ../../docs_src/query_params_str_validations/tutorial013_an_py39.py hl[9] *} + +/// note | Nota + +Ten en cuenta que en este caso, FastAPI no comprobará el contenido de la lista. + +Por ejemplo, `List[int]` comprobaría (y documentaría) que el contenido de la lista son enteros. Pero `list` sola no lo haría. + +/// + +## Declarar más metadatos + +Puedes agregar más información sobre el parámetro. + +Esa información se incluirá en el OpenAPI generado y será utilizada por las interfaces de usuario de documentación y herramientas externas. + +/// note | Nota + +Ten en cuenta que diferentes herramientas podrían tener diferentes niveles de soporte de OpenAPI. + +Algunas de ellas podrían no mostrar toda la información extra declarada todavía, aunque en la mayoría de los casos, la funcionalidad faltante ya está planificada para desarrollo. + +/// + +Puedes agregar un `title`: + +{* ../../docs_src/query_params_str_validations/tutorial007_an_py310.py hl[10] *} + +Y una `description`: + +{* ../../docs_src/query_params_str_validations/tutorial008_an_py310.py hl[14] *} + +## Alias para parámetros + +Imagina que quieres que el parámetro sea `item-query`. + +Como en: + +``` +http://127.0.0.1:8000/items/?item-query=foobaritems +``` + +Pero `item-query` no es un nombre de variable válido en Python. + +Lo más cercano sería `item_query`. + +Pero aún necesitas que sea exactamente `item-query`... + +Entonces puedes declarar un `alias`, y ese alias será usado para encontrar el valor del parámetro: + +{* ../../docs_src/query_params_str_validations/tutorial009_an_py310.py hl[9] *} + +## Declarar parámetros obsoletos + +Ahora digamos que ya no te gusta este parámetro. + +Tienes que dejarlo allí por un tiempo porque hay clientes usándolo, pero quieres que la documentación lo muestre claramente como deprecated. + +Luego pasa el parámetro `deprecated=True` a `Query`: + +{* ../../docs_src/query_params_str_validations/tutorial010_an_py310.py hl[19] *} + +La documentación lo mostrará así: + + + +## Excluir parámetros de OpenAPI + +Para excluir un parámetro de query del esquema de OpenAPI generado (y por lo tanto, de los sistemas de documentación automática), establece el parámetro `include_in_schema` de `Query` a `False`: + +{* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *} + +## Recapitulación + +Puedes declarar validaciones y metadatos adicionales para tus parámetros. + +Validaciones genéricas y metadatos: + +* `alias` +* `title` +* `description` +* `deprecated` + +Validaciones específicas para strings: + +* `min_length` +* `max_length` +* `pattern` + +En estos ejemplos viste cómo declarar validaciones para valores de tipo `str`. + +Mira los siguientes capítulos para aprender cómo declarar validaciones para otros tipos, como números. diff --git a/docs/es/docs/tutorial/query-params.md b/docs/es/docs/tutorial/query-params.md index 482af8dc0..09c66a545 100644 --- a/docs/es/docs/tutorial/query-params.md +++ b/docs/es/docs/tutorial/query-params.md @@ -1,12 +1,10 @@ -# Parámetros de query +# Parámetros de Query -Cuando declaras otros parámetros de la función que no hacen parte de los parámetros de path estos se interpretan automáticamente como parámetros de "query". +Cuando declaras otros parámetros de función que no son parte de los parámetros de path, son automáticamente interpretados como parámetros de "query". -```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial001.py!} -``` +{* ../../docs_src/query_params/tutorial001.py hl[9] *} -El query es el conjunto de pares de key-value que van después del `?` en la URL, separados por caracteres `&`. +La query es el conjunto de pares clave-valor que van después del `?` en una URL, separados por caracteres `&`. Por ejemplo, en la URL: @@ -19,36 +17,36 @@ http://127.0.0.1:8000/items/?skip=0&limit=10 * `skip`: con un valor de `0` * `limit`: con un valor de `10` -Dado que son parte de la URL son strings "naturalmente". +Como son parte de la URL, son "naturalmente" strings. -Pero cuando los declaras con tipos de Python (en el ejemplo arriba, como `int`) son convertidos a ese tipo y son validados con él. +Pero cuando los declaras con tipos de Python (en el ejemplo anterior, como `int`), son convertidos a ese tipo y validados respecto a él. -Todo el proceso que aplicaba a los parámetros de path también aplica a los parámetros de query: +Todo el mismo proceso que se aplica para los parámetros de path también se aplica para los parámetros de query: * Soporte del editor (obviamente) -* "Parsing" de datos +* "Parsing" de datos * Validación de datos * Documentación automática -## Configuraciones por defecto +## Valores por defecto -Como los parámetros de query no están fijos en una parte del path pueden ser opcionales y pueden tener valores por defecto. +Como los parámetros de query no son una parte fija de un path, pueden ser opcionales y pueden tener valores por defecto. -El ejemplo arriba tiene `skip=0` y `limit=10` como los valores por defecto. +En el ejemplo anterior, tienen valores por defecto de `skip=0` y `limit=10`. -Entonces, si vas a la URL: +Entonces, ir a la URL: ``` http://127.0.0.1:8000/items/ ``` -Sería lo mismo que ir a: +sería lo mismo que ir a: ``` http://127.0.0.1:8000/items/?skip=0&limit=10 ``` -Pero, si por ejemplo vas a: +Pero si vas a, por ejemplo: ``` http://127.0.0.1:8000/items/?skip=20 @@ -56,34 +54,26 @@ http://127.0.0.1:8000/items/?skip=20 Los valores de los parámetros en tu función serán: -* `skip=20`: porque lo definiste en la URL -* `limit=10`: porque era el valor por defecto +* `skip=20`: porque lo configuraste en la URL +* `limit=10`: porque ese era el valor por defecto ## Parámetros opcionales -Del mismo modo puedes declarar parámetros de query opcionales definiendo el valor por defecto como `None`: +De la misma manera, puedes declarar parámetros de query opcionales, estableciendo su valor por defecto en `None`: -```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial002.py!} -``` +{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *} -En este caso el parámetro de la función `q` será opcional y será `None` por defecto. +/// check | Revisa -!!! check "Revisa" - También puedes notar que **FastAPI** es lo suficientemente inteligente para darse cuenta de que el parámetro de path `item_id` es un parámetro de path y que `q` no lo es, y por lo tanto es un parámetro de query. +Además, nota que **FastAPI** es lo suficientemente inteligente para notar que el parámetro de path `item_id` es un parámetro de path y `q` no lo es, por lo tanto, es un parámetro de query. -!!! note "Nota" - FastAPI sabrá que `q` es opcional por el `= None`. +/// - El `Union` en `Union[str, None]` no es usado por FastAPI (FastAPI solo usará la parte `str`), pero el `Union[str, None]` le permitirá a tu editor ayudarte a encontrar errores en tu código. +## Conversión de tipos en parámetros de query -## Conversión de tipos de parámetros de query +También puedes declarar tipos `bool`, y serán convertidos: -También puedes declarar tipos `bool` y serán convertidos: - -```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial003.py!} -``` +{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *} En este caso, si vas a: @@ -115,58 +105,56 @@ o http://127.0.0.1:8000/items/foo?short=yes ``` -o cualquier otra variación (mayúsculas, primera letra en mayúscula, etc.) tu función verá el parámetro `short` con un valor `bool` de `True`. Si no, lo verá como `False`. +o cualquier otra variación (mayúsculas, primera letra en mayúscula, etc.), tu función verá el parámetro `short` con un valor `bool` de `True`. De lo contrario, será `False`. -## Múltiples parámetros de path y query +## Múltiples parámetros de path y de query -Puedes declarar múltiples parámetros de path y parámetros de query al mismo tiempo. **FastAPI** sabe cuál es cuál. +Puedes declarar múltiples parámetros de path y de query al mismo tiempo, **FastAPI** sabe cuál es cuál. -No los tienes que declarar en un orden específico. +Y no tienes que declararlos en un orden específico. Serán detectados por nombre: -```Python hl_lines="8 10" -{!../../../docs_src/query_params/tutorial004.py!} -``` +{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *} ## Parámetros de query requeridos -Cuando declaras un valor por defecto para los parámetros que no son de path (por ahora solo hemos visto parámetros de query), entonces no es requerido. +Cuando declaras un valor por defecto para parámetros que no son de path (por ahora, solo hemos visto parámetros de query), entonces no es requerido. -Si no quieres añadir un valor específico sino solo hacerlo opcional, pon el valor por defecto como `None`. +Si no quieres agregar un valor específico pero solo hacer que sea opcional, establece el valor por defecto como `None`. -Pero cuando quieres hacer que un parámetro de query sea requerido, puedes simplemente no declararle un valor por defecto: +Pero cuando quieres hacer un parámetro de query requerido, simplemente no declares ningún valor por defecto: -```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} -``` +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} -Aquí el parámetro de query `needy` es un parámetro de query requerido, del tipo `str`. +Aquí el parámetro de query `needy` es un parámetro de query requerido de tipo `str`. -Si abres tu navegador en una URL como: +Si abres en tu navegador una URL como: ``` http://127.0.0.1:8000/items/foo-item ``` -...sin añadir el parámetro `needy` requerido, verás un error como: +...sin agregar el parámetro requerido `needy`, verás un error como: ```JSON { - "detail": [ - { - "loc": [ - "query", - "needy" - ], - "msg": "field required", - "type": "value_error.missing" - } - ] + "detail": [ + { + "type": "missing", + "loc": [ + "query", + "needy" + ], + "msg": "Field required", + "input": null, + "url": "https://errors.pydantic.dev/2.1/v/missing" + } + ] } ``` -Dado que `needy` es un parámetro requerido necesitarías declararlo en la URL: +Como `needy` es un parámetro requerido, necesitarías establecerlo en la URL: ``` http://127.0.0.1:8000/items/foo-item?needy=sooooneedy @@ -181,17 +169,18 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy } ``` -Por supuesto que también puedes definir algunos parámetros como requeridos, con un valor por defecto y otros completamente opcionales: +Y por supuesto, puedes definir algunos parámetros como requeridos, algunos con un valor por defecto, y algunos enteramente opcionales: -```Python hl_lines="10" -{!../../../docs_src/query_params/tutorial006.py!} -``` +{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *} -En este caso hay 3 parámetros de query: +En este caso, hay 3 parámetros de query: * `needy`, un `str` requerido. * `skip`, un `int` con un valor por defecto de `0`. * `limit`, un `int` opcional. -!!! tip "Consejo" - También podrías usar los `Enum`s de la misma manera que con los [Parámetros de path](path-params.md#predefined-values){.internal-link target=_blank}. +/// tip | Consejo + +También podrías usar `Enum`s de la misma manera que con [Parámetros de Path](path-params.md#predefined-values){.internal-link target=_blank}. + +/// diff --git a/docs/es/docs/tutorial/request-files.md b/docs/es/docs/tutorial/request-files.md new file mode 100644 index 000000000..330523c7e --- /dev/null +++ b/docs/es/docs/tutorial/request-files.md @@ -0,0 +1,176 @@ +# Archivos de Request + +Puedes definir archivos que serán subidos por el cliente utilizando `File`. + +/// info | Información + +Para recibir archivos subidos, primero instala `python-multipart`. + +Asegúrate de crear un [entorno virtual](../virtual-environments.md){.internal-link target=_blank}, activarlo y luego instalarlo, por ejemplo: + +```console +$ pip install python-multipart +``` + +Esto es porque los archivos subidos se envían como "form data". + +/// + +## Importar `File` + +Importa `File` y `UploadFile` desde `fastapi`: + +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[3] *} + +## Definir Parámetros `File` + +Crea parámetros de archivo de la misma manera que lo harías para `Body` o `Form`: + +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[9] *} + +/// info | Información + +`File` es una clase que hereda directamente de `Form`. + +Pero recuerda que cuando importas `Query`, `Path`, `File` y otros desde `fastapi`, esos son en realidad funciones que devuelven clases especiales. + +/// + +/// tip | Consejo + +Para declarar cuerpos de File, necesitas usar `File`, porque de otra manera los parámetros serían interpretados como parámetros query o parámetros de cuerpo (JSON). + +/// + +Los archivos se subirán como "form data". + +Si declaras el tipo de tu parámetro de *path operation function* como `bytes`, **FastAPI** leerá el archivo por ti y recibirás el contenido como `bytes`. + +Ten en cuenta que esto significa que todo el contenido se almacenará en memoria. Esto funcionará bien para archivos pequeños. + +Pero hay varios casos en los que podrías beneficiarte de usar `UploadFile`. + +## Parámetros de Archivo con `UploadFile` + +Define un parámetro de archivo con un tipo de `UploadFile`: + +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[14] *} + +Usar `UploadFile` tiene varias ventajas sobre `bytes`: + +* No tienes que usar `File()` en el valor por defecto del parámetro. +* Usa un archivo "spooled": + * Un archivo almacenado en memoria hasta un límite de tamaño máximo, y después de superar este límite, se almacenará en el disco. +* Esto significa que funcionará bien para archivos grandes como imágenes, videos, binarios grandes, etc. sin consumir toda la memoria. +* Puedes obtener metadatos del archivo subido. +* Tiene una interfaz `async` parecida a un archivo. +* Expone un objeto Python real `SpooledTemporaryFile` que puedes pasar directamente a otros paquetes que esperan un objeto parecido a un archivo. + +### `UploadFile` + +`UploadFile` tiene los siguientes atributos: + +* `filename`: Un `str` con el nombre original del archivo que fue subido (por ejemplo, `myimage.jpg`). +* `content_type`: Un `str` con el tipo de contenido (MIME type / media type) (por ejemplo, `image/jpeg`). +* `file`: Un `SpooledTemporaryFile` (un objeto parecido a un archivo). Este es el objeto de archivo Python real que puedes pasar directamente a otras funciones o paquetes que esperan un objeto "parecido a un archivo". + +`UploadFile` tiene los siguientes métodos `async`. Todos ellos llaman a los métodos correspondientes del archivo por debajo (usando el `SpooledTemporaryFile` interno). + +* `write(data)`: Escribe `data` (`str` o `bytes`) en el archivo. +* `read(size)`: Lee `size` (`int`) bytes/caracteres del archivo. +* `seek(offset)`: Va a la posición de bytes `offset` (`int`) en el archivo. + * Por ejemplo, `await myfile.seek(0)` iría al inicio del archivo. + * Esto es especialmente útil si ejecutas `await myfile.read()` una vez y luego necesitas leer el contenido nuevamente. +* `close()`: Cierra el archivo. + +Como todos estos métodos son métodos `async`, necesitas "await" para ellos. + +Por ejemplo, dentro de una *path operation function* `async` puedes obtener los contenidos con: + +```Python +contents = await myfile.read() +``` + +Si estás dentro de una *path operation function* normal `def`, puedes acceder al `UploadFile.file` directamente, por ejemplo: + +```Python +contents = myfile.file.read() +``` + +/// note | Detalles Técnicos de `async` + +Cuando usas los métodos `async`, **FastAPI** ejecuta los métodos del archivo en un threadpool y los espera. + +/// + +/// note | Detalles Técnicos de Starlette + +El `UploadFile` de **FastAPI** hereda directamente del `UploadFile` de **Starlette**, pero añade algunas partes necesarias para hacerlo compatible con **Pydantic** y las otras partes de FastAPI. + +/// + +## Qué es "Form Data" + +La manera en que los forms de HTML (`
`) envían los datos al servidor normalmente utiliza una codificación "especial" para esos datos, es diferente de JSON. + +**FastAPI** se asegurará de leer esos datos del lugar correcto en lugar de JSON. + +/// note | Detalles Técnicos + +Los datos de los forms normalmente se codifican usando el "media type" `application/x-www-form-urlencoded` cuando no incluyen archivos. + +Pero cuando el formulario incluye archivos, se codifica como `multipart/form-data`. Si usas `File`, **FastAPI** sabrá que tiene que obtener los archivos de la parte correcta del cuerpo. + +Si deseas leer más sobre estas codificaciones y campos de formularios, dirígete a la MDN web docs para POST. + +/// + +/// warning | Advertencia + +Puedes declarar múltiples parámetros `File` y `Form` en una *path operation*, pero no puedes declarar campos `Body` que esperas recibir como JSON, ya que el request tendrá el cuerpo codificado usando `multipart/form-data` en lugar de `application/json`. + +Esto no es una limitación de **FastAPI**, es parte del protocolo HTTP. + +/// + +## Subida de Archivos Opcional + +Puedes hacer un archivo opcional utilizando anotaciones de tipos estándar y estableciendo un valor por defecto de `None`: + +{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *} + +## `UploadFile` con Metadatos Adicionales + +También puedes usar `File()` con `UploadFile`, por ejemplo, para establecer metadatos adicionales: + +{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *} + +## Subidas de Múltiples Archivos + +Es posible subir varios archivos al mismo tiempo. + +Estarían asociados al mismo "campo de formulario" enviado usando "form data". + +Para usar eso, declara una lista de `bytes` o `UploadFile`: + +{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *} + +Recibirás, como se declaró, una `list` de `bytes` o `UploadFile`s. + +/// note | Detalles Técnicos + +También podrías usar `from starlette.responses import HTMLResponse`. + +**FastAPI** proporciona las mismas `starlette.responses` como `fastapi.responses` solo como una conveniencia para ti, el desarrollador. Pero la mayoría de los responses disponibles vienen directamente de Starlette. + +/// + +### Subidas de Múltiples Archivos con Metadatos Adicionales + +Y de la misma manera que antes, puedes usar `File()` para establecer parámetros adicionales, incluso para `UploadFile`: + +{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *} + +## Recapitulación + +Usa `File`, `bytes` y `UploadFile` para declarar archivos que se subirán en el request, enviados como form data. diff --git a/docs/es/docs/tutorial/request-form-models.md b/docs/es/docs/tutorial/request-form-models.md new file mode 100644 index 000000000..9d5d7495a --- /dev/null +++ b/docs/es/docs/tutorial/request-form-models.md @@ -0,0 +1,78 @@ +# Modelos de Formulario + +Puedes usar **modelos de Pydantic** para declarar **campos de formulario** en FastAPI. + +/// info | Información + +Para usar formularios, primero instala `python-multipart`. + +Asegúrate de crear un [entorno virtual](../virtual-environments.md){.internal-link target=_blank}, activarlo, y luego instalarlo, por ejemplo: + +```console +$ pip install python-multipart +``` + +/// + +/// note | Nota + +Esto es compatible desde la versión `0.113.0` de FastAPI. 🤓 + +/// + +## Modelos de Pydantic para Formularios + +Solo necesitas declarar un **modelo de Pydantic** con los campos que quieres recibir como **campos de formulario**, y luego declarar el parámetro como `Form`: + +{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *} + +**FastAPI** **extraerá** los datos de **cada campo** de los **form data** en el request y te dará el modelo de Pydantic que definiste. + +## Revisa la Documentación + +Puedes verificarlo en la interfaz de documentación en `/docs`: + +
+ +
+ +## Prohibir Campos de Formulario Extra + +En algunos casos de uso especiales (probablemente no muy comunes), podrías querer **restringir** los campos de formulario a solo aquellos declarados en el modelo de Pydantic. Y **prohibir** cualquier campo **extra**. + +/// note | Nota + +Esto es compatible desde la versión `0.114.0` de FastAPI. 🤓 + +/// + +Puedes usar la configuración del modelo de Pydantic para `forbid` cualquier campo `extra`: + +{* ../../docs_src/request_form_models/tutorial002_an_py39.py hl[12] *} + +Si un cliente intenta enviar datos extra, recibirá un response de **error**. + +Por ejemplo, si el cliente intenta enviar los campos de formulario: + +* `username`: `Rick` +* `password`: `Portal Gun` +* `extra`: `Mr. Poopybutthole` + +Recibirá un response de error indicando que el campo `extra` no está permitido: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["body", "extra"], + "msg": "Extra inputs are not permitted", + "input": "Mr. Poopybutthole" + } + ] +} +``` + +## Resumen + +Puedes usar modelos de Pydantic para declarar campos de formulario en FastAPI. 😎 diff --git a/docs/es/docs/tutorial/request-forms-and-files.md b/docs/es/docs/tutorial/request-forms-and-files.md new file mode 100644 index 000000000..51dfbb357 --- /dev/null +++ b/docs/es/docs/tutorial/request-forms-and-files.md @@ -0,0 +1,41 @@ +# Request Forms and Files + +Puedes definir archivos y campos de formulario al mismo tiempo usando `File` y `Form`. + +/// info | Información + +Para recibir archivos subidos y/o form data, primero instala `python-multipart`. + +Asegúrate de crear un [entorno virtual](../virtual-environments.md){.internal-link target=_blank}, actívalo y luego instálalo, por ejemplo: + +```console +$ pip install python-multipart +``` + +/// + +## Importar `File` y `Form` + +{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[3] *} + +## Definir parámetros `File` y `Form` + +Crea parámetros de archivo y formulario de la misma manera que lo harías para `Body` o `Query`: + +{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[10:12] *} + +Los archivos y campos de formulario se subirán como form data y recibirás los archivos y campos de formulario. + +Y puedes declarar algunos de los archivos como `bytes` y algunos como `UploadFile`. + +/// warning | Advertencia + +Puedes declarar múltiples parámetros `File` y `Form` en una *path operation*, pero no puedes también declarar campos `Body` que esperas recibir como JSON, ya que el request tendrá el body codificado usando `multipart/form-data` en lugar de `application/json`. + +Esto no es una limitación de **FastAPI**, es parte del protocolo HTTP. + +/// + +## Resumen + +Usa `File` y `Form` juntos cuando necesites recibir datos y archivos en el mismo request. diff --git a/docs/es/docs/tutorial/request-forms.md b/docs/es/docs/tutorial/request-forms.md new file mode 100644 index 000000000..a9d62e660 --- /dev/null +++ b/docs/es/docs/tutorial/request-forms.md @@ -0,0 +1,73 @@ +# Form Data + +Cuando necesitas recibir campos de formulario en lugar de JSON, puedes usar `Form`. + +/// info | Información + +Para usar forms, primero instala `python-multipart`. + +Asegúrate de crear un [entorno virtual](../virtual-environments.md){.internal-link target=_blank}, activarlo, y luego instalarlo, por ejemplo: + +```console +$ pip install python-multipart +``` + +/// + +## Importar `Form` + +Importar `Form` desde `fastapi`: + +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[3] *} + +## Definir parámetros de `Form` + +Crea parámetros de formulario de la misma manera que lo harías para `Body` o `Query`: + +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[9] *} + +Por ejemplo, en una de las formas en las que se puede usar la especificación OAuth2 (llamada "password flow") se requiere enviar un `username` y `password` como campos de formulario. + +La especificación requiere que los campos se llamen exactamente `username` y `password`, y que se envíen como campos de formulario, no JSON. + +Con `Form` puedes declarar las mismas configuraciones que con `Body` (y `Query`, `Path`, `Cookie`), incluyendo validación, ejemplos, un alias (por ejemplo, `user-name` en lugar de `username`), etc. + +/// info | Información + +`Form` es una clase que hereda directamente de `Body`. + +/// + +/// tip | Consejo + +Para declarar bodies de forms, necesitas usar `Form` explícitamente, porque sin él, los parámetros se interpretarían como parámetros de query o como parámetros de body (JSON). + +/// + +## Sobre "Campos de Formulario" + +La manera en que los forms HTML (`
`) envían los datos al servidor normalmente usa una codificación "especial" para esos datos, es diferente de JSON. + +**FastAPI** se encargará de leer esos datos del lugar correcto en lugar de JSON. + +/// note | Detalles técnicos + +Los datos de forms normalmente se codifican usando el "media type" `application/x-www-form-urlencoded`. + +Pero cuando el formulario incluye archivos, se codifica como `multipart/form-data`. Leerás sobre la gestión de archivos en el próximo capítulo. + +Si quieres leer más sobre estas codificaciones y campos de formulario, dirígete a la MDN web docs para POST. + +/// + +/// warning | Advertencia + +Puedes declarar múltiples parámetros `Form` en una *path operation*, pero no puedes también declarar campos `Body` que esperas recibir como JSON, ya que el request tendrá el body codificado usando `application/x-www-form-urlencoded` en lugar de `application/json`. + +Esto no es una limitación de **FastAPI**, es parte del protocolo HTTP. + +/// + +## Recapitulación + +Usa `Form` para declarar parámetros de entrada de datos de formulario. diff --git a/docs/es/docs/tutorial/response-model.md b/docs/es/docs/tutorial/response-model.md new file mode 100644 index 000000000..09682f51b --- /dev/null +++ b/docs/es/docs/tutorial/response-model.md @@ -0,0 +1,357 @@ +# Modelo de Response - Tipo de Retorno + +Puedes declarar el tipo utilizado para el response anotando el **tipo de retorno** de la *path operation function*. + +Puedes utilizar **anotaciones de tipos** de la misma manera que lo harías para datos de entrada en **parámetros** de función, puedes utilizar modelos de Pydantic, listas, diccionarios, valores escalares como enteros, booleanos, etc. + +{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *} + +FastAPI usará este tipo de retorno para: + +* **Validar** los datos devueltos. + * Si los datos son inválidos (por ejemplo, falta un campo), significa que el código de *tu* aplicación está defectuoso, no devolviendo lo que debería, y retornará un error del servidor en lugar de devolver datos incorrectos. De esta manera, tú y tus clientes pueden estar seguros de que recibirán los datos y la forma de los datos esperada. +* Agregar un **JSON Schema** para el response, en la *path operation* de OpenAPI. + * Esto será utilizado por la **documentación automática**. + * También será utilizado por herramientas de generación automática de código de cliente. + +Pero lo más importante: + +* **Limitará y filtrará** los datos de salida a lo que se define en el tipo de retorno. + * Esto es particularmente importante para la **seguridad**, veremos más sobre eso a continuación. + +## Parámetro `response_model` + +Hay algunos casos en los que necesitas o quieres devolver algunos datos que no son exactamente lo que declara el tipo. + +Por ejemplo, podrías querer **devolver un diccionario** u objeto de base de datos, pero **declararlo como un modelo de Pydantic**. De esta manera el modelo de Pydantic haría toda la documentación de datos, validación, etc. para el objeto que devolviste (por ejemplo, un diccionario u objeto de base de datos). + +Si añadiste la anotación del tipo de retorno, las herramientas y editores se quejarían con un error (correcto) diciéndote que tu función está devolviendo un tipo (por ejemplo, un dict) que es diferente de lo que declaraste (por ejemplo, un modelo de Pydantic). + +En esos casos, puedes usar el parámetro del decorador de path operation `response_model` en lugar del tipo de retorno. + +Puedes usar el parámetro `response_model` en cualquiera de las *path operations*: + +* `@app.get()` +* `@app.post()` +* `@app.put()` +* `@app.delete()` +* etc. + +{* ../../docs_src/response_model/tutorial001_py310.py hl[17,22,24:27] *} + +/// note | Nota + +Observa que `response_model` es un parámetro del método "decorador" (`get`, `post`, etc). No de tu *path operation function*, como todos los parámetros y el cuerpo. + +/// + +`response_model` recibe el mismo tipo que declararías para un campo de modelo Pydantic, por lo que puede ser un modelo de Pydantic, pero también puede ser, por ejemplo, un `list` de modelos de Pydantic, como `List[Item]`. + +FastAPI usará este `response_model` para hacer toda la documentación de datos, validación, etc. y también para **convertir y filtrar los datos de salida** a su declaración de tipo. + +/// tip | Consejo + +Si tienes chequeos estrictos de tipos en tu editor, mypy, etc., puedes declarar el tipo de retorno de la función como `Any`. + +De esa manera le dices al editor que intencionalmente estás devolviendo cualquier cosa. Pero FastAPI todavía hará la documentación de datos, validación, filtrado, etc. con `response_model`. + +/// + +### Prioridad del `response_model` + +Si declaras tanto un tipo de retorno como un `response_model`, el `response_model` tomará prioridad y será utilizado por FastAPI. + +De esta manera puedes añadir anotaciones de tipos correctas a tus funciones incluso cuando estás devolviendo un tipo diferente al modelo de response, para ser utilizado por el editor y herramientas como mypy. Y aún así puedes hacer que FastAPI realice la validación de datos, documentación, etc. usando el `response_model`. + +También puedes usar `response_model=None` para desactivar la creación de un modelo de response para esa *path operation*, podrías necesitar hacerlo si estás añadiendo anotaciones de tipos para cosas que no son campos válidos de Pydantic, verás un ejemplo de eso en una de las secciones a continuación. + +## Devolver los mismos datos de entrada + +Aquí estamos declarando un modelo `UserIn`, contendrá una contraseña en texto plano: + +{* ../../docs_src/response_model/tutorial002_py310.py hl[7,9] *} + +/// info | Información + +Para usar `EmailStr`, primero instala `email-validator`. + +Asegúrate de crear un [entorno virtual](../virtual-environments.md){.internal-link target=_blank}, activarlo, y luego instalarlo, por ejemplo: + +```console +$ pip install email-validator +``` + +o con: + +```console +$ pip install "pydantic[email]" +``` + +/// + +Y estamos usando este modelo para declarar nuestra entrada y el mismo modelo para declarar nuestra salida: + +{* ../../docs_src/response_model/tutorial002_py310.py hl[16] *} + +Ahora, cada vez que un navegador esté creando un usuario con una contraseña, la API devolverá la misma contraseña en el response. + +En este caso, podría no ser un problema, porque es el mismo usuario que envía la contraseña. + +Pero si usamos el mismo modelo para otra *path operation*, podríamos estar enviando las contraseñas de nuestros usuarios a cada cliente. + +/// danger | Peligro + +Nunca almacenes la contraseña en texto plano de un usuario ni la envíes en un response como esta, a menos que conozcas todas las advertencias y sepas lo que estás haciendo. + +/// + +## Añadir un modelo de salida + +Podemos en cambio crear un modelo de entrada con la contraseña en texto plano y un modelo de salida sin ella: + +{* ../../docs_src/response_model/tutorial003_py310.py hl[9,11,16] *} + +Aquí, aunque nuestra *path operation function* está devolviendo el mismo usuario de entrada que contiene la contraseña: + +{* ../../docs_src/response_model/tutorial003_py310.py hl[24] *} + +...hemos declarado el `response_model` para ser nuestro modelo `UserOut`, que no incluye la contraseña: + +{* ../../docs_src/response_model/tutorial003_py310.py hl[22] *} + +Entonces, **FastAPI** se encargará de filtrar todos los datos que no estén declarados en el modelo de salida (usando Pydantic). + +### `response_model` o Tipo de Retorno + +En este caso, como los dos modelos son diferentes, si anotáramos el tipo de retorno de la función como `UserOut`, el editor y las herramientas se quejarían de que estamos devolviendo un tipo inválido, ya que son clases diferentes. + +Por eso en este ejemplo tenemos que declararlo en el parámetro `response_model`. + +...pero sigue leyendo abajo para ver cómo superar eso. + +## Tipo de Retorno y Filtrado de Datos + +Continuemos con el ejemplo anterior. Queríamos **anotar la función con un tipo**, pero queríamos poder devolver desde la función algo que en realidad incluya **más datos**. + +Queremos que FastAPI continúe **filtrando** los datos usando el modelo de response. Para que, incluso cuando la función devuelva más datos, el response solo incluya los campos declarados en el modelo de response. + +En el ejemplo anterior, debido a que las clases eran diferentes, tuvimos que usar el parámetro `response_model`. Pero eso también significa que no obtenemos el soporte del editor y las herramientas verificando el tipo de retorno de la función. + +Pero en la mayoría de los casos en los que necesitamos hacer algo como esto, queremos que el modelo solo **filtre/elimine** algunos de los datos como en este ejemplo. + +Y en esos casos, podemos usar clases y herencia para aprovechar las **anotaciones de tipos** de funciones para obtener mejor soporte en el editor y herramientas, y aún así obtener el **filtrado de datos** de FastAPI. + +{* ../../docs_src/response_model/tutorial003_01_py310.py hl[7:10,13:14,18] *} + +Con esto, obtenemos soporte de las herramientas, de los editores y mypy ya que este código es correcto en términos de tipos, pero también obtenemos el filtrado de datos de FastAPI. + +¿Cómo funciona esto? Vamos a echarle un vistazo. 🤓 + +### Anotaciones de Tipos y Herramientas + +Primero vamos a ver cómo los editores, mypy y otras herramientas verían esto. + +`BaseUser` tiene los campos base. Luego `UserIn` hereda de `BaseUser` y añade el campo `password`, por lo que incluirá todos los campos de ambos modelos. + +Anotamos el tipo de retorno de la función como `BaseUser`, pero en realidad estamos devolviendo una instancia de `UserIn`. + +El editor, mypy y otras herramientas no se quejarán de esto porque, en términos de tipificación, `UserIn` es una subclase de `BaseUser`, lo que significa que es un tipo *válido* cuando se espera algo que es un `BaseUser`. + +### Filtrado de Datos en FastAPI + +Ahora, para FastAPI, verá el tipo de retorno y se asegurará de que lo que devuelves incluya **solo** los campos que están declarados en el tipo. + +FastAPI realiza varias cosas internamente con Pydantic para asegurarse de que esas mismas reglas de herencia de clases no se utilicen para el filtrado de datos devueltos, de lo contrario, podrías terminar devolviendo muchos más datos de los que esperabas. + +De esta manera, puedes obtener lo mejor de ambos mundos: anotaciones de tipos con **soporte de herramientas** y **filtrado de datos**. + +## Verlo en la documentación + +Cuando veas la documentación automática, puedes verificar que el modelo de entrada y el modelo de salida tendrán cada uno su propio JSON Schema: + + + +Y ambos modelos se utilizarán para la documentación interactiva de la API: + + + +## Otras Anotaciones de Tipos de Retorno + +Podría haber casos en los que devuelvas algo que no es un campo válido de Pydantic y lo anotes en la función, solo para obtener el soporte proporcionado por las herramientas (el editor, mypy, etc). + +### Devolver un Response Directamente + +El caso más común sería [devolver un Response directamente como se explica más adelante en la documentación avanzada](../advanced/response-directly.md){.internal-link target=_blank}. + +{* ../../docs_src/response_model/tutorial003_02.py hl[8,10:11] *} + +Este caso simple es manejado automáticamente por FastAPI porque la anotación del tipo de retorno es la clase (o una subclase de) `Response`. + +Y las herramientas también estarán felices porque tanto `RedirectResponse` como `JSONResponse` son subclases de `Response`, por lo que la anotación del tipo es correcta. + +### Anotar una Subclase de Response + +También puedes usar una subclase de `Response` en la anotación del tipo: + +{* ../../docs_src/response_model/tutorial003_03.py hl[8:9] *} + +Esto también funcionará porque `RedirectResponse` es una subclase de `Response`, y FastAPI manejará automáticamente este caso simple. + +### Anotaciones de Tipos de Retorno Inválidas + +Pero cuando devuelves algún otro objeto arbitrario que no es un tipo válido de Pydantic (por ejemplo, un objeto de base de datos) y lo anotas así en la función, FastAPI intentará crear un modelo de response de Pydantic a partir de esa anotación de tipo, y fallará. + +Lo mismo sucedería si tuvieras algo como un union entre diferentes tipos donde uno o más de ellos no son tipos válidos de Pydantic, por ejemplo esto fallaría 💥: + +{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *} + +...esto falla porque la anotación de tipo no es un tipo de Pydantic y no es solo una sola clase `Response` o subclase, es una unión (cualquiera de los dos) entre una `Response` y un `dict`. + +### Desactivar el Modelo de Response + +Continuando con el ejemplo anterior, puede que no quieras tener la validación de datos por defecto, documentación, filtrado, etc. que realiza FastAPI. + +Pero puedes querer mantener la anotación del tipo de retorno en la función para obtener el soporte de herramientas como editores y verificadores de tipos (por ejemplo, mypy). + +En este caso, puedes desactivar la generación del modelo de response configurando `response_model=None`: + +{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *} + +Esto hará que FastAPI omita la generación del modelo de response y de esa manera puedes tener cualquier anotación de tipo de retorno que necesites sin que afecte a tu aplicación FastAPI. 🤓 + +## Parámetros de codificación del Modelo de Response + +Tu modelo de response podría tener valores por defecto, como: + +{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *} + +* `description: Union[str, None] = None` (o `str | None = None` en Python 3.10) tiene un valor por defecto de `None`. +* `tax: float = 10.5` tiene un valor por defecto de `10.5`. +* `tags: List[str] = []` tiene un valor por defecto de una lista vacía: `[]`. + +pero podrías querer omitirlos del resultado si no fueron en realidad almacenados. + +Por ejemplo, si tienes modelos con muchos atributos opcionales en una base de datos NoSQL, pero no quieres enviar responses JSON muy largos llenos de valores por defecto. + +### Usa el parámetro `response_model_exclude_unset` + +Puedes configurar el parámetro del decorador de path operation `response_model_exclude_unset=True`: + +{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *} + +y esos valores por defecto no serán incluidos en el response, solo los valores realmente establecidos. + +Entonces, si envías un request a esa *path operation* para el ítem con ID `foo`, el response (no incluyendo valores por defecto) será: + +```JSON +{ + "name": "Foo", + "price": 50.2 +} +``` + +/// info | Información + +En Pydantic v1 el método se llamaba `.dict()`, fue deprecado (pero aún soportado) en Pydantic v2, y renombrado a `.model_dump()`. + +Los ejemplos aquí usan `.dict()` para compatibilidad con Pydantic v1, pero deberías usar `.model_dump()` en su lugar si puedes usar Pydantic v2. + +/// + +/// info | Información + +FastAPI usa el método `.dict()` del modelo de Pydantic con su parámetro `exclude_unset` para lograr esto. + +/// + +/// info | Información + +También puedes usar: + +* `response_model_exclude_defaults=True` +* `response_model_exclude_none=True` + +como se describe en la documentación de Pydantic para `exclude_defaults` y `exclude_none`. + +/// + +#### Datos con valores para campos con valores por defecto + +Pero si tus datos tienen valores para los campos del modelo con valores por defecto, como el artículo con ID `bar`: + +```Python hl_lines="3 5" +{ + "name": "Bar", + "description": "The bartenders", + "price": 62, + "tax": 20.2 +} +``` + +serán incluidos en el response. + +#### Datos con los mismos valores que los valores por defecto + +Si los datos tienen los mismos valores que los valores por defecto, como el artículo con ID `baz`: + +```Python hl_lines="3 5-6" +{ + "name": "Baz", + "description": None, + "price": 50.2, + "tax": 10.5, + "tags": [] +} +``` + +FastAPI es lo suficientemente inteligente (de hecho, Pydantic es lo suficientemente inteligente) para darse cuenta de que, a pesar de que `description`, `tax` y `tags` tienen los mismos valores que los valores por defecto, fueron establecidos explícitamente (en lugar de tomados de los valores por defecto). + +Por lo tanto, se incluirán en el response JSON. + +/// tip | Consejo + +Ten en cuenta que los valores por defecto pueden ser cualquier cosa, no solo `None`. + +Pueden ser una lista (`[]`), un `float` de `10.5`, etc. + +/// + +### `response_model_include` y `response_model_exclude` + +También puedes usar los parámetros del decorador de path operation `response_model_include` y `response_model_exclude`. + +Aceptan un `set` de `str` con el nombre de los atributos a incluir (omitiendo el resto) o excluir (incluyendo el resto). + +Esto se puede usar como un atajo rápido si solo tienes un modelo de Pydantic y quieres eliminar algunos datos de la salida. + +/// tip | Consejo + +Pero todavía se recomienda usar las ideas anteriores, usando múltiples clases, en lugar de estos parámetros. + +Esto se debe a que el JSON Schema generado en el OpenAPI de tu aplicación (y la documentación) aún será el del modelo completo, incluso si usas `response_model_include` o `response_model_exclude` para omitir algunos atributos. + +Esto también se aplica a `response_model_by_alias` que funciona de manera similar. + +/// + +{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *} + +/// tip | Consejo + +La sintaxis `{"name", "description"}` crea un `set` con esos dos valores. + +Es equivalente a `set(["name", "description"])`. + +/// + +#### Usar `list`s en lugar de `set`s + +Si olvidas usar un `set` y usas un `list` o `tuple` en su lugar, FastAPI todavía lo convertirá a un `set` y funcionará correctamente: + +{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *} + +## Resumen + +Usa el parámetro `response_model` del *decorador de path operation* para definir modelos de response y especialmente para asegurarte de que los datos privados sean filtrados. + +Usa `response_model_exclude_unset` para devolver solo los valores establecidos explícitamente. diff --git a/docs/es/docs/tutorial/response-status-code.md b/docs/es/docs/tutorial/response-status-code.md new file mode 100644 index 000000000..92df1f4cc --- /dev/null +++ b/docs/es/docs/tutorial/response-status-code.md @@ -0,0 +1,101 @@ +# Código de Estado del Response + +De la misma manera que puedes especificar un modelo de response, también puedes declarar el código de estado HTTP usado para el response con el parámetro `status_code` en cualquiera de las *path operations*: + +* `@app.get()` +* `@app.post()` +* `@app.put()` +* `@app.delete()` +* etc. + +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} + +/// note | Nota + +Observa que `status_code` es un parámetro del método "decorador" (`get`, `post`, etc). No de tu *path operation function*, como todos los parámetros y body. + +/// + +El parámetro `status_code` recibe un número con el código de estado HTTP. + +/// info | Información + +`status_code` también puede recibir un `IntEnum`, como por ejemplo el `http.HTTPStatus` de Python. + +/// + +Esto hará: + +* Devolver ese código de estado en el response. +* Documentarlo como tal en el esquema de OpenAPI (y por lo tanto, en las interfaces de usuario): + + + +/// note | Nota + +Algunos códigos de response (ver la siguiente sección) indican que el response no tiene un body. + +FastAPI sabe esto, y producirá documentación OpenAPI que establece que no hay un response body. + +/// + +## Acerca de los códigos de estado HTTP + +/// note | Nota + +Si ya sabes qué son los códigos de estado HTTP, salta a la siguiente sección. + +/// + +En HTTP, envías un código de estado numérico de 3 dígitos como parte del response. + +Estos códigos de estado tienen un nombre asociado para reconocerlos, pero la parte importante es el número. + +En breve: + +* `100` y superiores son para "Información". Rara vez los usas directamente. Los responses con estos códigos de estado no pueden tener un body. +* **`200`** y superiores son para responses "Exitosos". Estos son los que usarías más. + * `200` es el código de estado por defecto, lo que significa que todo estaba "OK". + * Otro ejemplo sería `201`, "Created". Comúnmente se usa después de crear un nuevo registro en la base de datos. + * Un caso especial es `204`, "No Content". Este response se usa cuando no hay contenido para devolver al cliente, por lo tanto, el response no debe tener un body. +* **`300`** y superiores son para "Redirección". Los responses con estos códigos de estado pueden o no tener un body, excepto `304`, "Not Modified", que no debe tener uno. +* **`400`** y superiores son para responses de "Error del Cliente". Este es el segundo tipo que probablemente más usarías. + * Un ejemplo es `404`, para un response "Not Found". + * Para errores genéricos del cliente, puedes usar simplemente `400`. +* `500` y superiores son para errores del servidor. Casi nunca los usas directamente. Cuando algo sale mal en alguna parte de tu código de aplicación, o del servidor, automáticamente devolverá uno de estos códigos de estado. + +/// tip | Consejo + +Para saber más sobre cada código de estado y qué código es para qué, revisa la documentación de MDN sobre códigos de estado HTTP. + +/// + +## Atajo para recordar los nombres + +Veamos de nuevo el ejemplo anterior: + +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} + +`201` es el código de estado para "Created". + +Pero no tienes que memorizar lo que significa cada uno de estos códigos. + +Puedes usar las variables de conveniencia de `fastapi.status`. + +{* ../../docs_src/response_status_code/tutorial002.py hl[1,6] *} + +Son solo una conveniencia, mantienen el mismo número, pero de esa manera puedes usar el autocompletado del editor para encontrarlos: + + + +/// note | Nota Técnica + +También podrías usar `from starlette import status`. + +**FastAPI** proporciona el mismo `starlette.status` como `fastapi.status` solo como una conveniencia para ti, el desarrollador. Pero proviene directamente de Starlette. + +/// + +## Cambiando el valor por defecto + +Más adelante, en la [Guía de Usuario Avanzada](../advanced/response-change-status-code.md){.internal-link target=_blank}, verás cómo devolver un código de estado diferente al valor por defecto que estás declarando aquí. diff --git a/docs/es/docs/tutorial/schema-extra-example.md b/docs/es/docs/tutorial/schema-extra-example.md new file mode 100644 index 000000000..645060d71 --- /dev/null +++ b/docs/es/docs/tutorial/schema-extra-example.md @@ -0,0 +1,224 @@ +# Declarar Ejemplos de Request + +Puedes declarar ejemplos de los datos que tu aplicación puede recibir. + +Aquí tienes varias formas de hacerlo. + +## Datos extra de JSON Schema en modelos de Pydantic + +Puedes declarar `examples` para un modelo de Pydantic que se añadirá al JSON Schema generado. + +//// tab | Pydantic v2 + +{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:24] *} + +//// + +//// tab | Pydantic v1 + +{* ../../docs_src/schema_extra_example/tutorial001_pv1_py310.py hl[13:23] *} + +//// + +Esa información extra se añadirá tal cual al **JSON Schema** generado para ese modelo, y se usará en la documentación de la API. + +//// tab | Pydantic v2 + +En Pydantic versión 2, usarías el atributo `model_config`, que toma un `dict` como se describe en la documentación de Pydantic: Configuración. + +Puedes establecer `"json_schema_extra"` con un `dict` que contenga cualquier dato adicional que desees que aparezca en el JSON Schema generado, incluyendo `examples`. + +//// + +//// tab | Pydantic v1 + +En Pydantic versión 1, usarías una clase interna `Config` y `schema_extra`, como se describe en la documentación de Pydantic: Personalización de Esquema. + +Puedes establecer `schema_extra` con un `dict` que contenga cualquier dato adicional que desees que aparezca en el JSON Schema generado, incluyendo `examples`. + +//// + +/// tip | Consejo + +Podrías usar la misma técnica para extender el JSON Schema y añadir tu propia información extra personalizada. + +Por ejemplo, podrías usarlo para añadir metadatos para una interfaz de usuario frontend, etc. + +/// + +/// info | Información + +OpenAPI 3.1.0 (usado desde FastAPI 0.99.0) añadió soporte para `examples`, que es parte del estándar de **JSON Schema**. + +Antes de eso, solo soportaba la palabra clave `example` con un solo ejemplo. Eso aún es soportado por OpenAPI 3.1.0, pero está obsoleto y no es parte del estándar de JSON Schema. Así que se recomienda migrar de `example` a `examples`. 🤓 + +Puedes leer más al final de esta página. + +/// + +## Argumentos adicionales en `Field` + +Cuando usas `Field()` con modelos de Pydantic, también puedes declarar `examples` adicionales: + +{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *} + +## `examples` en JSON Schema - OpenAPI + +Cuando usas cualquiera de: + +* `Path()` +* `Query()` +* `Header()` +* `Cookie()` +* `Body()` +* `Form()` +* `File()` + +también puedes declarar un grupo de `examples` con información adicional que se añadirá a sus **JSON Schemas** dentro de **OpenAPI**. + +### `Body` con `examples` + +Aquí pasamos `examples` que contiene un ejemplo de los datos esperados en `Body()`: + +{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:29] *} + +### Ejemplo en la interfaz de documentación + +Con cualquiera de los métodos anteriores se vería así en los `/docs`: + + + +### `Body` con múltiples `examples` + +Por supuesto, también puedes pasar múltiples `examples`: + +{* ../../docs_src/schema_extra_example/tutorial004_an_py310.py hl[23:38] *} + +Cuando haces esto, los ejemplos serán parte del **JSON Schema** interno para esos datos de body. + +Sin embargo, al momento de escribir esto, Swagger UI, la herramienta encargada de mostrar la interfaz de documentación, no soporta mostrar múltiples ejemplos para los datos en **JSON Schema**. Pero lee más abajo para una solución alternativa. + +### `examples` específicos de OpenAPI + +Desde antes de que **JSON Schema** soportara `examples`, OpenAPI tenía soporte para un campo diferente también llamado `examples`. + +Estos `examples` específicos de **OpenAPI** van en otra sección en la especificación de OpenAPI. Van en los **detalles para cada *path operation***, no dentro de cada JSON Schema. + +Y Swagger UI ha soportado este campo particular de `examples` por un tiempo. Así que, puedes usarlo para **mostrar** diferentes **ejemplos en la interfaz de documentación**. + +La forma de este campo específico de OpenAPI `examples` es un `dict` con **múltiples ejemplos** (en lugar de una `list`), cada uno con información adicional que también se añadirá a **OpenAPI**. + +Esto no va dentro de cada JSON Schema contenido en OpenAPI, esto va afuera, directamente en la *path operation*. + +### Usando el Parámetro `openapi_examples` + +Puedes declarar los `examples` específicos de OpenAPI en FastAPI con el parámetro `openapi_examples` para: + +* `Path()` +* `Query()` +* `Header()` +* `Cookie()` +* `Body()` +* `Form()` +* `File()` + +Las claves del `dict` identifican cada ejemplo, y cada valor es otro `dict`. + +Cada `dict` específico del ejemplo en los `examples` puede contener: + +* `summary`: Descripción corta del ejemplo. +* `description`: Una descripción larga que puede contener texto Markdown. +* `value`: Este es el ejemplo real mostrado, e.g. un `dict`. +* `externalValue`: alternativa a `value`, una URL que apunta al ejemplo. Aunque esto puede no ser soportado por tantas herramientas como `value`. + +Puedes usarlo así: + +{* ../../docs_src/schema_extra_example/tutorial005_an_py310.py hl[23:49] *} + +### Ejemplos de OpenAPI en la Interfaz de Documentación + +Con `openapi_examples` añadido a `Body()`, los `/docs` se verían así: + + + +## Detalles Técnicos + +/// tip | Consejo + +Si ya estás usando la versión **0.99.0 o superior** de **FastAPI**, probablemente puedes **omitir** estos detalles. + +Son más relevantes para versiones más antiguas, antes de que OpenAPI 3.1.0 estuviera disponible. + +Puedes considerar esto una breve lección de **historia** de OpenAPI y JSON Schema. 🤓 + +/// + +/// warning | Advertencia + +Estos son detalles muy técnicos sobre los estándares **JSON Schema** y **OpenAPI**. + +Si las ideas anteriores ya funcionan para ti, eso podría ser suficiente, y probablemente no necesites estos detalles, siéntete libre de omitirlos. + +/// + +Antes de OpenAPI 3.1.0, OpenAPI usaba una versión más antigua y modificada de **JSON Schema**. + +JSON Schema no tenía `examples`, así que OpenAPI añadió su propio campo `example` a su versión modificada. + +OpenAPI también añadió los campos `example` y `examples` a otras partes de la especificación: + +* `Parameter Object` (en la especificación) que era usado por FastAPI: + * `Path()` + * `Query()` + * `Header()` + * `Cookie()` +* `Request Body Object`, en el campo `content`, sobre el `Media Type Object` (en la especificación) que era usado por FastAPI: + * `Body()` + * `File()` + * `Form()` + +/// info | Información + +Este viejo parámetro `examples` específico de OpenAPI ahora es `openapi_examples` desde FastAPI `0.103.0`. + +/// + +### Campo `examples` de JSON Schema + +Pero luego JSON Schema añadió un campo `examples` a una nueva versión de la especificación. + +Y entonces el nuevo OpenAPI 3.1.0 se basó en la última versión (JSON Schema 2020-12) que incluía este nuevo campo `examples`. + +Y ahora este nuevo campo `examples` tiene precedencia sobre el viejo campo único (y personalizado) `example`, que ahora está obsoleto. + +Este nuevo campo `examples` en JSON Schema es **solo una `list`** de ejemplos, no un dict con metadatos adicionales como en los otros lugares en OpenAPI (descritos arriba). + +/// info | Información + +Incluso después de que OpenAPI 3.1.0 fue lanzado con esta nueva integración más sencilla con JSON Schema, por un tiempo, Swagger UI, la herramienta que proporciona la documentación automática, no soportaba OpenAPI 3.1.0 (lo hace desde la versión 5.0.0 🎉). + +Debido a eso, las versiones de FastAPI anteriores a 0.99.0 todavía usaban versiones de OpenAPI menores a 3.1.0. + +/// + +### `examples` de Pydantic y FastAPI + +Cuando añades `examples` dentro de un modelo de Pydantic, usando `schema_extra` o `Field(examples=["algo"])`, ese ejemplo se añade al **JSON Schema** para ese modelo de Pydantic. + +Y ese **JSON Schema** del modelo de Pydantic se incluye en el **OpenAPI** de tu API, y luego se usa en la interfaz de documentación. + +En las versiones de FastAPI antes de 0.99.0 (0.99.0 y superior usan el nuevo OpenAPI 3.1.0) cuando usabas `example` o `examples` con cualquiera de las otras utilidades (`Query()`, `Body()`, etc.) esos ejemplos no se añadían al JSON Schema que describe esos datos (ni siquiera a la propia versión de JSON Schema de OpenAPI), se añadían directamente a la declaración de la *path operation* en OpenAPI (fuera de las partes de OpenAPI que usan JSON Schema). + +Pero ahora que FastAPI 0.99.0 y superiores usa OpenAPI 3.1.0, que usa JSON Schema 2020-12, y Swagger UI 5.0.0 y superiores, todo es más consistente y los ejemplos se incluyen en JSON Schema. + +### Swagger UI y `examples` específicos de OpenAPI + +Ahora, como Swagger UI no soportaba múltiples ejemplos de JSON Schema (a fecha de 2023-08-26), los usuarios no tenían una forma de mostrar múltiples ejemplos en los documentos. + +Para resolver eso, FastAPI `0.103.0` **añadió soporte** para declarar el mismo viejo campo **específico de OpenAPI** `examples` con el nuevo parámetro `openapi_examples`. 🤓 + +### Resumen + +Solía decir que no me gustaba mucho la historia... y mírame ahora dando lecciones de "historia tecnológica". 😅 + +En resumen, **actualiza a FastAPI 0.99.0 o superior**, y las cosas son mucho **más simples, consistentes e intuitivas**, y no necesitas conocer todos estos detalles históricos. 😎 diff --git a/docs/es/docs/tutorial/security/first-steps.md b/docs/es/docs/tutorial/security/first-steps.md new file mode 100644 index 000000000..5dbbab02a --- /dev/null +++ b/docs/es/docs/tutorial/security/first-steps.md @@ -0,0 +1,203 @@ +# Seguridad - Primeros pasos + +Imaginemos que tienes tu API de **backend** en algún dominio. + +Y tienes un **frontend** en otro dominio o en un path diferente del mismo dominio (o en una aplicación móvil). + +Y quieres tener una forma para que el frontend se autentique con el backend, usando un **username** y **password**. + +Podemos usar **OAuth2** para construir eso con **FastAPI**. + +Pero vamos a ahorrarte el tiempo de leer la larga especificación completa solo para encontrar esos pequeños fragmentos de información que necesitas. + +Usemos las herramientas proporcionadas por **FastAPI** para manejar la seguridad. + +## Cómo se ve + +Primero solo usemos el código y veamos cómo funciona, y luego volveremos para entender qué está sucediendo. + +## Crea `main.py` + +Copia el ejemplo en un archivo `main.py`: + +{* ../../docs_src/security/tutorial001_an_py39.py *} + +## Ejecútalo + +/// info | Información + +El paquete `python-multipart` se instala automáticamente con **FastAPI** cuando ejecutas el comando `pip install "fastapi[standard]"`. + +Sin embargo, si usas el comando `pip install fastapi`, el paquete `python-multipart` no se incluye por defecto. + +Para instalarlo manualmente, asegúrate de crear un [entorno virtual](../../virtual-environments.md){.internal-link target=_blank}, activarlo, y luego instalarlo con: + +```console +$ pip install python-multipart +``` + +Esto se debe a que **OAuth2** utiliza "form data" para enviar el `username` y `password`. + +/// + +Ejecuta el ejemplo con: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +## Revisa + +Ve a la documentación interactiva en: http://127.0.0.1:8000/docs. + +Verás algo así: + + + +/// check | ¡Botón de autorización! + +Ya tienes un nuevo y brillante botón de "Authorize". + +Y tu *path operation* tiene un pequeño candado en la esquina superior derecha que puedes pulsar. + +/// + +Y si lo haces, tendrás un pequeño formulario de autorización para escribir un `username` y `password` (y otros campos opcionales): + + + +/// note | Nota + +No importa lo que escribas en el formulario, aún no funcionará. Pero llegaremos allí. + +/// + +Esto por supuesto no es el frontend para los usuarios finales, pero es una gran herramienta automática para documentar interactivamente toda tu API. + +Puede ser utilizada por el equipo de frontend (que también puedes ser tú mismo). + +Puede ser utilizada por aplicaciones y sistemas de terceros. + +Y también puede ser utilizada por ti mismo, para depurar, revisar y probar la misma aplicación. + +## El flujo `password` + +Ahora retrocedamos un poco y entendamos qué es todo eso. + +El "flujo" `password` es una de las formas ("flujos") definidas en OAuth2, para manejar la seguridad y la autenticación. + +OAuth2 fue diseñado para que el backend o la API pudieran ser independientes del servidor que autentica al usuario. + +Pero en este caso, la misma aplicación de **FastAPI** manejará la API y la autenticación. + +Así que, revisémoslo desde ese punto de vista simplificado: + +* El usuario escribe el `username` y `password` en el frontend, y presiona `Enter`. +* El frontend (ejecutándose en el navegador del usuario) envía ese `username` y `password` a una URL específica en nuestra API (declarada con `tokenUrl="token"`). +* La API verifica ese `username` y `password`, y responde con un "token" (no hemos implementado nada de esto aún). + * Un "token" es solo un string con algún contenido que podemos usar luego para verificar a este usuario. + * Normalmente, un token se establece para que expire después de algún tiempo. + * Así que, el usuario tendrá que volver a iniciar sesión más adelante. + * Y si el token es robado, el riesgo es menor. No es como una llave permanente que funcionará para siempre (en la mayoría de los casos). +* El frontend almacena temporalmente ese token en algún lugar. +* El usuario hace clic en el frontend para ir a otra sección de la aplicación web frontend. +* El frontend necesita obtener más datos de la API. + * Pero necesita autenticación para ese endpoint específico. + * Así que, para autenticarse con nuestra API, envía un `header` `Authorization` con un valor de `Bearer ` más el token. + * Si el token contiene `foobar`, el contenido del `header` `Authorization` sería: `Bearer foobar`. + +## `OAuth2PasswordBearer` de **FastAPI** + +**FastAPI** proporciona varias herramientas, en diferentes niveles de abstracción, para implementar estas funcionalidades de seguridad. + +En este ejemplo vamos a usar **OAuth2**, con el flujo **Password**, usando un token **Bearer**. Hacemos eso utilizando la clase `OAuth2PasswordBearer`. + +/// info | Información + +Un token "bearer" no es la única opción. + +Pero es la mejor para nuestro caso de uso. + +Y podría ser la mejor para la mayoría de los casos de uso, a menos que seas un experto en OAuth2 y sepas exactamente por qué hay otra opción que se adapta mejor a tus necesidades. + +En ese caso, **FastAPI** también te proporciona las herramientas para construirlo. + +/// + +Cuando creamos una instance de la clase `OAuth2PasswordBearer` pasamos el parámetro `tokenUrl`. Este parámetro contiene la URL que el cliente (el frontend corriendo en el navegador del usuario) usará para enviar el `username` y `password` a fin de obtener un token. + +{* ../../docs_src/security/tutorial001_an_py39.py hl[8] *} + +/// tip | Consejo + +Aquí `tokenUrl="token"` se refiere a una URL relativa `token` que aún no hemos creado. Como es una URL relativa, es equivalente a `./token`. + +Porque estamos usando una URL relativa, si tu API estuviera ubicada en `https://example.com/`, entonces se referiría a `https://example.com/token`. Pero si tu API estuviera ubicada en `https://example.com/api/v1/`, entonces se referiría a `https://example.com/api/v1/token`. + +Usar una URL relativa es importante para asegurarse de que tu aplicación siga funcionando incluso en un caso de uso avanzado como [Detrás de un Proxy](../../advanced/behind-a-proxy.md){.internal-link target=_blank}. + +/// + +Este parámetro no crea ese endpoint / *path operation*, pero declara que la URL `/token` será la que el cliente deberá usar para obtener el token. Esa información se usa en OpenAPI, y luego en los sistemas de documentación interactiva del API. + +Pronto también crearemos la verdadera *path operation*. + +/// info | Información + +Si eres un "Pythonista" muy estricto, tal vez no te guste el estilo del nombre del parámetro `tokenUrl` en lugar de `token_url`. + +Eso es porque está usando el mismo nombre que en la especificación de OpenAPI. Para que si necesitas investigar más sobre cualquiera de estos esquemas de seguridad, puedas simplemente copiarlo y pegarlo para encontrar más información al respecto. + +/// + +La variable `oauth2_scheme` es una instance de `OAuth2PasswordBearer`, pero también es un "callable". + +Podría ser llamada como: + +```Python +oauth2_scheme(some, parameters) +``` + +Así que, puede usarse con `Depends`. + +### Úsalo + +Ahora puedes pasar ese `oauth2_scheme` en una dependencia con `Depends`. + +{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *} + +Esta dependencia proporcionará un `str` que se asigna al parámetro `token` de la *path operation function*. + +**FastAPI** sabrá que puede usar esta dependencia para definir un "security scheme" en el esquema OpenAPI (y en los docs automáticos del API). + +/// info | Detalles técnicos + +**FastAPI** sabrá que puede usar la clase `OAuth2PasswordBearer` (declarada en una dependencia) para definir el esquema de seguridad en OpenAPI porque hereda de `fastapi.security.oauth2.OAuth2`, que a su vez hereda de `fastapi.security.base.SecurityBase`. + +Todas las utilidades de seguridad que se integran con OpenAPI (y los docs automáticos del API) heredan de `SecurityBase`, así es como **FastAPI** puede saber cómo integrarlas en OpenAPI. + +/// + +## Lo que hace + +Irá y buscará en el request ese header `Authorization`, verificará si el valor es `Bearer ` más algún token, y devolverá el token como un `str`. + +Si no ve un header `Authorization`, o el valor no tiene un token `Bearer `, responderá directamente con un error de código de estado 401 (`UNAUTHORIZED`). + +Ni siquiera tienes que verificar si el token existe para devolver un error. Puedes estar seguro de que si tu función se ejecuta, tendrá un `str` en ese token. + +Puedes probarlo ya en los docs interactivos: + + + +Todavía no estamos verificando la validez del token, pero ya es un comienzo. + +## Resumen + +Así que, en solo 3 o 4 líneas adicionales, ya tienes alguna forma primitiva de seguridad. diff --git a/docs/es/docs/tutorial/security/get-current-user.md b/docs/es/docs/tutorial/security/get-current-user.md new file mode 100644 index 000000000..249a70c18 --- /dev/null +++ b/docs/es/docs/tutorial/security/get-current-user.md @@ -0,0 +1,103 @@ +# Obtener Usuario Actual + +En el capítulo anterior, el sistema de seguridad (que se basa en el sistema de inyección de dependencias) le estaba dando a la *path operation function* un `token` como un `str`: + +{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *} + +Pero eso aún no es tan útil. Vamos a hacer que nos dé el usuario actual. + +## Crear un modelo de usuario + +Primero, vamos a crear un modelo de usuario con Pydantic. + +De la misma manera que usamos Pydantic para declarar cuerpos, podemos usarlo en cualquier otra parte: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:6] *} + +## Crear una dependencia `get_current_user` + +Vamos a crear una dependencia `get_current_user`. + +¿Recuerdas que las dependencias pueden tener sub-dependencias? + +`get_current_user` tendrá una dependencia con el mismo `oauth2_scheme` que creamos antes. + +De la misma manera que estábamos haciendo antes en la *path operation* directamente, nuestra nueva dependencia `get_current_user` recibirá un `token` como un `str` de la sub-dependencia `oauth2_scheme`: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[25] *} + +## Obtener el usuario + +`get_current_user` usará una función de utilidad (falsa) que creamos, que toma un token como un `str` y devuelve nuestro modelo de Pydantic `User`: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[19:22,26:27] *} + +## Inyectar al usuario actual + +Entonces ahora podemos usar el mismo `Depends` con nuestro `get_current_user` en la *path operation*: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[31] *} + +Ten en cuenta que declaramos el tipo de `current_user` como el modelo de Pydantic `User`. + +Esto nos ayudará dentro de la función con todo el autocompletado y chequeo de tipos. + +/// tip | Consejo + +Tal vez recuerdes que los cuerpos de request también se declaran con modelos de Pydantic. + +Aquí **FastAPI** no se confundirá porque estás usando `Depends`. + +/// + +/// check | Revisa + +El modo en que este sistema de dependencias está diseñado nos permite tener diferentes dependencias (diferentes "dependables") que todas devuelven un modelo `User`. + +No estamos restringidos a tener solo una dependencia que pueda devolver ese tipo de datos. + +/// + +## Otros modelos + +Ahora puedes obtener el usuario actual directamente en las *path operation functions* y manejar los mecanismos de seguridad a nivel de **Dependency Injection**, usando `Depends`. + +Y puedes usar cualquier modelo o datos para los requisitos de seguridad (en este caso, un modelo de Pydantic `User`). + +Pero no estás limitado a usar algún modelo de datos, clase o tipo específico. + +¿Quieres tener un `id` y `email` y no tener un `username` en tu modelo? Claro. Puedes usar estas mismas herramientas. + +¿Quieres solo tener un `str`? ¿O solo un `dict`? ¿O un instance de clase modelo de base de datos directamente? Todo funciona de la misma manera. + +¿En realidad no tienes usuarios que inicien sesión en tu aplicación sino robots, bots u otros sistemas, que solo tienen un token de acceso? Una vez más, todo funciona igual. + +Usa cualquier tipo de modelo, cualquier tipo de clase, cualquier tipo de base de datos que necesites para tu aplicación. **FastAPI** te cubre con el sistema de inyección de dependencias. + +## Tamaño del código + +Este ejemplo podría parecer extenso. Ten en cuenta que estamos mezclando seguridad, modelos de datos, funciones de utilidad y *path operations* en el mismo archivo. + +Pero aquí está el punto clave. + +El tema de seguridad e inyección de dependencias se escribe una vez. + +Y puedes hacerlo tan complejo como desees. Y aún así, tenerlo escrito solo una vez, en un solo lugar. Con toda la flexibilidad. + +Pero puedes tener miles de endpoints (*path operations*) usando el mismo sistema de seguridad. + +Y todos ellos (o cualquier porción de ellos que quieras) pueden aprovechar la reutilización de estas dependencias o cualquier otra dependencia que crees. + +Y todas estas miles de *path operations* pueden ser tan pequeñas como 3 líneas: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[30:32] *} + +## Resumen + +Ahora puedes obtener el usuario actual directamente en tu *path operation function*. + +Ya estamos a mitad de camino. + +Solo necesitamos agregar una *path operation* para que el usuario/cliente envíe realmente el `username` y `password`. + +Eso es lo que viene a continuación. diff --git a/docs/es/docs/tutorial/security/index.md b/docs/es/docs/tutorial/security/index.md new file mode 100644 index 000000000..12e39fdaa --- /dev/null +++ b/docs/es/docs/tutorial/security/index.md @@ -0,0 +1,105 @@ +# Seguridad + +Hay muchas formas de manejar la seguridad, autenticación y autorización. + +Y normalmente es un tema complejo y "difícil". + +En muchos frameworks y sistemas, solo manejar la seguridad y autenticación requiere una gran cantidad de esfuerzo y código (en muchos casos puede ser el 50% o más de todo el código escrito). + +**FastAPI** proporciona varias herramientas para ayudarte a manejar la **Seguridad** de manera fácil, rápida y estándar, sin tener que estudiar y aprender todas las especificaciones de seguridad. + +Pero primero, vamos a revisar algunos pequeños conceptos. + +## ¿Con prisa? + +Si no te importan ninguno de estos términos y solo necesitas agregar seguridad con autenticación basada en nombre de usuario y contraseña *ahora mismo*, salta a los siguientes capítulos. + +## OAuth2 + +OAuth2 es una especificación que define varias maneras de manejar la autenticación y autorización. + +Es una especificación bastante extensa y cubre varios casos de uso complejos. + +Incluye formas de autenticarse usando un "tercero". + +Eso es lo que todos los sistemas con "iniciar sesión con Facebook, Google, Twitter, GitHub" utilizan internamente. + +### OAuth 1 + +Hubo un OAuth 1, que es muy diferente de OAuth2, y más complejo, ya que incluía especificaciones directas sobre cómo encriptar la comunicación. + +No es muy popular o usado hoy en día. + +OAuth2 no especifica cómo encriptar la comunicación, espera que tengas tu aplicación servida con HTTPS. + +/// tip | Consejo + +En la sección sobre **deployment** verás cómo configurar HTTPS de forma gratuita, usando Traefik y Let's Encrypt. + +/// + +## OpenID Connect + +OpenID Connect es otra especificación, basada en **OAuth2**. + +Solo extiende OAuth2 especificando algunas cosas que son relativamente ambiguas en OAuth2, para intentar hacerla más interoperable. + +Por ejemplo, el login de Google usa OpenID Connect (que internamente usa OAuth2). + +Pero el login de Facebook no soporta OpenID Connect. Tiene su propia versión de OAuth2. + +### OpenID (no "OpenID Connect") + +Hubo también una especificación "OpenID". Que intentaba resolver lo mismo que **OpenID Connect**, pero no estaba basada en OAuth2. + +Entonces, era un sistema completo adicional. + +No es muy popular o usado hoy en día. + +## OpenAPI + +OpenAPI (anteriormente conocido como Swagger) es la especificación abierta para construir APIs (ahora parte de la Linux Foundation). + +**FastAPI** se basa en **OpenAPI**. + +Eso es lo que hace posible tener múltiples interfaces de documentación interactiva automática, generación de código, etc. + +OpenAPI tiene una forma de definir múltiples "esquemas" de seguridad. + +Al usarlos, puedes aprovechar todas estas herramientas basadas en estándares, incluidos estos sistemas de documentación interactiva. + +OpenAPI define los siguientes esquemas de seguridad: + +* `apiKey`: una clave específica de la aplicación que puede provenir de: + * Un parámetro de query. + * Un header. + * Una cookie. +* `http`: sistemas de autenticación HTTP estándar, incluyendo: + * `bearer`: un header `Authorization` con un valor de `Bearer ` más un token. Esto se hereda de OAuth2. + * Autenticación básica HTTP. + * Digest HTTP, etc. +* `oauth2`: todas las formas de OAuth2 para manejar la seguridad (llamadas "flujos"). + * Varios de estos flujos son apropiados para construir un proveedor de autenticación OAuth 2.0 (como Google, Facebook, Twitter, GitHub, etc.): + * `implicit` + * `clientCredentials` + * `authorizationCode` + * Pero hay un "flujo" específico que puede usarse perfectamente para manejar la autenticación directamente en la misma aplicación: + * `password`: algunos de los próximos capítulos cubrirán ejemplos de esto. +* `openIdConnect`: tiene una forma de definir cómo descubrir automáticamente los datos de autenticación OAuth2. + * Este descubrimiento automático es lo que se define en la especificación de OpenID Connect. + +/// tip | Consejo + +Integrar otros proveedores de autenticación/autorización como Google, Facebook, Twitter, GitHub, etc. también es posible y relativamente fácil. + +El problema más complejo es construir un proveedor de autenticación/autorización como esos, pero **FastAPI** te da las herramientas para hacerlo fácilmente, mientras hace el trabajo pesado por ti. + +/// + +## Utilidades de **FastAPI** + +FastAPI proporciona varias herramientas para cada uno de estos esquemas de seguridad en el módulo `fastapi.security` que simplifican el uso de estos mecanismos de seguridad. + +En los siguientes capítulos verás cómo agregar seguridad a tu API usando esas herramientas proporcionadas por **FastAPI**. + +Y también verás cómo se integra automáticamente en el sistema de documentación interactiva. diff --git a/docs/es/docs/tutorial/security/oauth2-jwt.md b/docs/es/docs/tutorial/security/oauth2-jwt.md new file mode 100644 index 000000000..4ab9c8ca2 --- /dev/null +++ b/docs/es/docs/tutorial/security/oauth2-jwt.md @@ -0,0 +1,273 @@ +# OAuth2 con Password (y hashing), Bearer con tokens JWT + +Ahora que tenemos todo el flujo de seguridad, hagamos que la aplicación sea realmente segura, usando tokens JWT y hashing de contraseñas seguras. + +Este código es algo que puedes usar realmente en tu aplicación, guardar los hashes de las contraseñas en tu base de datos, etc. + +Vamos a empezar desde donde lo dejamos en el capítulo anterior e incrementarlo. + +## Acerca de JWT + +JWT significa "JSON Web Tokens". + +Es un estándar para codificar un objeto JSON en un string largo y denso sin espacios. Se ve así: + +``` +eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c +``` + +No está encriptado, por lo que cualquiera podría recuperar la información de los contenidos. + +Pero está firmado. Así que, cuando recibes un token que has emitido, puedes verificar que realmente lo emitiste. + +De esta manera, puedes crear un token con una expiración de, digamos, 1 semana. Y luego, cuando el usuario regresa al día siguiente con el token, sabes que el usuario todavía está registrado en tu sistema. + +Después de una semana, el token estará expirado y el usuario no estará autorizado y tendrá que iniciar sesión nuevamente para obtener un nuevo token. Y si el usuario (o un tercero) intenta modificar el token para cambiar la expiración, podrás descubrirlo, porque las firmas no coincidirían. + +Si quieres jugar con tokens JWT y ver cómo funcionan, revisa https://jwt.io. + +## Instalar `PyJWT` + +Necesitamos instalar `PyJWT` para generar y verificar los tokens JWT en Python. + +Asegúrate de crear un [entorno virtual](../../virtual-environments.md){.internal-link target=_blank}, activarlo y luego instalar `pyjwt`: + +
+ +```console +$ pip install pyjwt + +---> 100% +``` + +
+ +/// info | Información + +Si planeas usar algoritmos de firma digital como RSA o ECDSA, deberías instalar la dependencia del paquete de criptografía `pyjwt[crypto]`. + +Puedes leer más al respecto en la documentación de instalación de PyJWT. + +/// + +## Hashing de contraseñas + +"Hacer hashing" significa convertir algún contenido (una contraseña en este caso) en una secuencia de bytes (solo un string) que parece un galimatías. + +Siempre que pases exactamente el mismo contenido (exactamente la misma contraseña) obtienes exactamente el mismo galimatías. + +Pero no puedes convertir del galimatías de nuevo a la contraseña. + +### Por qué usar hashing de contraseñas + +Si tu base de datos es robada, el ladrón no tendrá las contraseñas en texto claro de tus usuarios, solo los hashes. + +Por lo tanto, el ladrón no podrá intentar usar esa contraseña en otro sistema (como muchos usuarios usan la misma contraseña en todas partes, esto sería peligroso). + +## Instalar `passlib` + +PassLib es un gran paquete de Python para manejar hashes de contraseñas. + +Soporta muchos algoritmos de hashing seguros y utilidades para trabajar con ellos. + +El algoritmo recomendado es "Bcrypt". + +Asegúrate de crear un [entorno virtual](../../virtual-environments.md){.internal-link target=_blank}, activarlo y luego instalar PassLib con Bcrypt: + +
+ +```console +$ pip install "passlib[bcrypt]" + +---> 100% +``` + +
+ +/// tip | Consejo + +Con `passlib`, incluso podrías configurarlo para poder leer contraseñas creadas por **Django**, un plug-in de seguridad de **Flask** u otros muchos. + +Así, podrías, por ejemplo, compartir los mismos datos de una aplicación de Django en una base de datos con una aplicación de FastAPI. O migrar gradualmente una aplicación de Django usando la misma base de datos. + +Y tus usuarios podrían iniciar sesión desde tu aplicación Django o desde tu aplicación **FastAPI**, al mismo tiempo. + +/// + +## Hash y verificación de contraseñas + +Importa las herramientas que necesitamos de `passlib`. + +Crea un "contexto" de PassLib. Este es el que se usará para hacer el hash y verificar las contraseñas. + +/// tip | Consejo + +El contexto de PassLib también tiene funcionalidad para usar diferentes algoritmos de hashing, incluidos los antiguos obsoletos solo para permitir verificarlos, etc. + +Por ejemplo, podrías usarlo para leer y verificar contraseñas generadas por otro sistema (como Django) pero hacer hash de cualquier contraseña nueva con un algoritmo diferente como Bcrypt. + +Y ser compatible con todos ellos al mismo tiempo. + +/// + +Crea una función de utilidad para hacer el hash de una contraseña que venga del usuario. + +Y otra utilidad para verificar si una contraseña recibida coincide con el hash almacenado. + +Y otra más para autenticar y devolver un usuario. + +{* ../../docs_src/security/tutorial004_an_py310.py hl[8,49,56:57,60:61,70:76] *} + +/// note | Nota + +Si revisas la nueva (falsa) base de datos `fake_users_db`, verás cómo se ve ahora la contraseña con hash: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`. + +/// + +## Manejo de tokens JWT + +Importa los módulos instalados. + +Crea una clave secreta aleatoria que se usará para firmar los tokens JWT. + +Para generar una clave secreta segura al azar usa el comando: + +
+ +```console +$ openssl rand -hex 32 + +09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7 +``` + +
+ +Y copia el resultado a la variable `SECRET_KEY` (no uses la del ejemplo). + +Crea una variable `ALGORITHM` con el algoritmo usado para firmar el token JWT y configúralo a `"HS256"`. + +Crea una variable para la expiración del token. + +Define un Modelo de Pydantic que se usará en el endpoint de token para el response. + +Crea una función de utilidad para generar un nuevo token de acceso. + +{* ../../docs_src/security/tutorial004_an_py310.py hl[4,7,13:15,29:31,79:87] *} + +## Actualizar las dependencias + +Actualiza `get_current_user` para recibir el mismo token que antes, pero esta vez, usando tokens JWT. + +Decodifica el token recibido, verifícalo y devuelve el usuario actual. + +Si el token es inválido, devuelve un error HTTP de inmediato. + +{* ../../docs_src/security/tutorial004_an_py310.py hl[90:107] *} + +## Actualizar la *path operation* `/token` + +Crea un `timedelta` con el tiempo de expiración del token. + +Crea un verdadero token de acceso JWT y devuélvelo. + +{* ../../docs_src/security/tutorial004_an_py310.py hl[118:133] *} + +### Detalles técnicos sobre el "sujeto" `sub` de JWT + +La especificación de JWT dice que hay una clave `sub`, con el sujeto del token. + +Es opcional usarlo, pero ahí es donde pondrías la identificación del usuario, por lo que lo estamos usando aquí. + +JWT podría ser usado para otras cosas aparte de identificar un usuario y permitirle realizar operaciones directamente en tu API. + +Por ejemplo, podrías identificar un "coche" o un "artículo de blog". + +Luego, podrías agregar permisos sobre esa entidad, como "conducir" (para el coche) o "editar" (para el blog). + +Y luego, podrías darle ese token JWT a un usuario (o bot), y ellos podrían usarlo para realizar esas acciones (conducir el coche, o editar el artículo del blog) sin siquiera necesitar tener una cuenta, solo con el token JWT que tu API generó para eso. + +Usando estas ideas, JWT puede ser utilizado para escenarios mucho más sofisticados. + +En esos casos, varias de esas entidades podrían tener el mismo ID, digamos `foo` (un usuario `foo`, un coche `foo`, y un artículo del blog `foo`). + +Entonces, para evitar colisiones de ID, cuando crees el token JWT para el usuario, podrías prefijar el valor de la clave `sub`, por ejemplo, con `username:`. Así, en este ejemplo, el valor de `sub` podría haber sido: `username:johndoe`. + +Lo importante a tener en cuenta es que la clave `sub` debería tener un identificador único a lo largo de toda la aplicación, y debería ser un string. + +## Revisa + +Ejecuta el servidor y ve a la documentación: http://127.0.0.1:8000/docs. + +Verás la interfaz de usuario como: + + + +Autoriza la aplicación de la misma manera que antes. + +Usando las credenciales: + +Usuario: `johndoe` +Contraseña: `secret` + +/// check | Revisa + +Observa que en ninguna parte del código está la contraseña en texto claro "`secret`", solo tenemos la versión con hash. + +/// + + + +Llama al endpoint `/users/me/`, obtendrás el response como: + +```JSON +{ + "username": "johndoe", + "email": "johndoe@example.com", + "full_name": "John Doe", + "disabled": false +} +``` + + + +Si abres las herramientas de desarrollador, podrías ver cómo los datos enviados solo incluyen el token, la contraseña solo se envía en la primera petición para autenticar al usuario y obtener ese token de acceso, pero no después: + + + +/// note | Nota + +Observa el header `Authorization`, con un valor que comienza con `Bearer `. + +/// + +## Uso avanzado con `scopes` + +OAuth2 tiene la noción de "scopes". + +Puedes usarlos para agregar un conjunto específico de permisos a un token JWT. + +Luego, puedes darle este token directamente a un usuario o a un tercero, para interactuar con tu API con un conjunto de restricciones. + +Puedes aprender cómo usarlos y cómo están integrados en **FastAPI** más adelante en la **Guía de Usuario Avanzada**. + +## Resumen + +Con lo que has visto hasta ahora, puedes configurar una aplicación **FastAPI** segura usando estándares como OAuth2 y JWT. + +En casi cualquier framework el manejo de la seguridad se convierte en un tema bastante complejo rápidamente. + +Muchos paquetes que lo simplifican tienen que hacer muchos compromisos con el modelo de datos, la base de datos y las funcionalidades disponibles. Y algunos de estos paquetes que simplifican las cosas demasiado en realidad tienen fallos de seguridad en el fondo. + +--- + +**FastAPI** no hace ningún compromiso con ninguna base de datos, modelo de datos o herramienta. + +Te da toda la flexibilidad para elegir aquellas que se ajusten mejor a tu proyecto. + +Y puedes usar directamente muchos paquetes bien mantenidos y ampliamente usados como `passlib` y `PyJWT`, porque **FastAPI** no requiere mecanismos complejos para integrar paquetes externos. + +Pero te proporciona las herramientas para simplificar el proceso tanto como sea posible sin comprometer la flexibilidad, la robustez o la seguridad. + +Y puedes usar e implementar protocolos seguros y estándar, como OAuth2 de una manera relativamente simple. + +Puedes aprender más en la **Guía de Usuario Avanzada** sobre cómo usar "scopes" de OAuth2, para un sistema de permisos más detallado, siguiendo estos mismos estándares. OAuth2 con scopes es el mecanismo utilizado por muchos grandes proveedores de autenticación, como Facebook, Google, GitHub, Microsoft, Twitter, etc. para autorizar aplicaciones de terceros para interactuar con sus APIs en nombre de sus usuarios. diff --git a/docs/es/docs/tutorial/security/simple-oauth2.md b/docs/es/docs/tutorial/security/simple-oauth2.md new file mode 100644 index 000000000..67449332f --- /dev/null +++ b/docs/es/docs/tutorial/security/simple-oauth2.md @@ -0,0 +1,289 @@ +# Simple OAuth2 con Password y Bearer + +Ahora vamos a construir a partir del capítulo anterior y agregar las partes faltantes para tener un flujo de seguridad completo. + +## Obtener el `username` y `password` + +Vamos a usar las utilidades de seguridad de **FastAPI** para obtener el `username` y `password`. + +OAuth2 especifica que cuando se utiliza el "password flow" (que estamos usando), el cliente/usuario debe enviar campos `username` y `password` como form data. + +Y la especificación dice que los campos deben llamarse así. Por lo que `user-name` o `email` no funcionarían. + +Pero no te preocupes, puedes mostrarlo como quieras a tus usuarios finales en el frontend. + +Y tus modelos de base de datos pueden usar cualquier otro nombre que desees. + +Pero para la *path operation* de inicio de sesión, necesitamos usar estos nombres para ser compatibles con la especificación (y poder, por ejemplo, utilizar el sistema de documentación integrada de la API). + +La especificación también establece que el `username` y `password` deben enviarse como form data (por lo que no hay JSON aquí). + +### `scope` + +La especificación también indica que el cliente puede enviar otro campo del formulario llamado "`scope`". + +El nombre del campo del formulario es `scope` (en singular), pero en realidad es un string largo con "scopes" separados por espacios. + +Cada "scope" es simplemente un string (sin espacios). + +Normalmente se utilizan para declarar permisos de seguridad específicos, por ejemplo: + +* `users:read` o `users:write` son ejemplos comunes. +* `instagram_basic` es usado por Facebook / Instagram. +* `https://www.googleapis.com/auth/drive` es usado por Google. + +/// info | Información + +En OAuth2 un "scope" es solo un string que declara un permiso específico requerido. + +No importa si tiene otros caracteres como `:` o si es una URL. + +Esos detalles son específicos de la implementación. + +Para OAuth2 son solo strings. + +/// + +## Código para obtener el `username` y `password` + +Ahora vamos a usar las utilidades proporcionadas por **FastAPI** para manejar esto. + +### `OAuth2PasswordRequestForm` + +Primero, importa `OAuth2PasswordRequestForm`, y úsalo como una dependencia con `Depends` en la *path operation* para `/token`: + +{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *} + +`OAuth2PasswordRequestForm` es una dependencia de clase que declara un body de formulario con: + +* El `username`. +* El `password`. +* Un campo opcional `scope` como un string grande, compuesto por strings separados por espacios. +* Un `grant_type` opcional. + +/// tip | Consejo + +La especificación de OAuth2 en realidad *requiere* un campo `grant_type` con un valor fijo de `password`, pero `OAuth2PasswordRequestForm` no lo obliga. + +Si necesitas imponerlo, utiliza `OAuth2PasswordRequestFormStrict` en lugar de `OAuth2PasswordRequestForm`. + +/// + +* Un `client_id` opcional (no lo necesitamos para nuestro ejemplo). +* Un `client_secret` opcional (no lo necesitamos para nuestro ejemplo). + +/// info | Información + +`OAuth2PasswordRequestForm` no es una clase especial para **FastAPI** como lo es `OAuth2PasswordBearer`. + +`OAuth2PasswordBearer` hace que **FastAPI** sepa que es un esquema de seguridad. Así que se añade de esa manera a OpenAPI. + +Pero `OAuth2PasswordRequestForm` es solo una dependencia de clase que podrías haber escrito tú mismo, o podrías haber declarado parámetros de `Form` directamente. + +Pero como es un caso de uso común, se proporciona directamente por **FastAPI**, solo para facilitarlo. + +/// + +### Usa el form data + +/// tip | Consejo + +La instance de la clase de dependencia `OAuth2PasswordRequestForm` no tendrá un atributo `scope` con el string largo separado por espacios, en su lugar, tendrá un atributo `scopes` con la lista real de strings para cada scope enviado. + +No estamos usando `scopes` en este ejemplo, pero la funcionalidad está ahí si la necesitas. + +/// + +Ahora, obtén los datos del usuario desde la base de datos (falsa), usando el `username` del campo del form. + +Si no existe tal usuario, devolvemos un error diciendo "Incorrect username or password". + +Para el error, usamos la excepción `HTTPException`: + +{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *} + +### Revisa el password + +En este punto tenemos los datos del usuario de nuestra base de datos, pero no hemos revisado el password. + +Primero pongamos esos datos en el modelo `UserInDB` de Pydantic. + +Nunca deberías guardar passwords en texto plano, así que, usaremos el sistema de hash de passwords (falso). + +Si los passwords no coinciden, devolvemos el mismo error. + +#### Hashing de passwords + +"Hacer hash" significa: convertir algún contenido (un password en este caso) en una secuencia de bytes (solo un string) que parece un galimatías. + +Siempre que pases exactamente el mismo contenido (exactamente el mismo password) obtienes exactamente el mismo galimatías. + +Pero no puedes convertir del galimatías al password. + +##### Por qué usar hashing de passwords + +Si tu base de datos es robada, el ladrón no tendrá los passwords en texto plano de tus usuarios, solo los hashes. + +Entonces, el ladrón no podrá intentar usar esos mismos passwords en otro sistema (como muchos usuarios usan el mismo password en todas partes, esto sería peligroso). + +{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *} + +#### Sobre `**user_dict` + +`UserInDB(**user_dict)` significa: + +*Pasa las claves y valores de `user_dict` directamente como argumentos clave-valor, equivalente a:* + +```Python +UserInDB( + username = user_dict["username"], + email = user_dict["email"], + full_name = user_dict["full_name"], + disabled = user_dict["disabled"], + hashed_password = user_dict["hashed_password"], +) +``` + +/// info | Información + +Para una explicación más completa de `**user_dict` revisa en [la documentación para **Extra Models**](../extra-models.md#about-user_indict){.internal-link target=_blank}. + +/// + +## Devolver el token + +El response del endpoint `token` debe ser un objeto JSON. + +Debe tener un `token_type`. En nuestro caso, como estamos usando tokens "Bearer", el tipo de token debe ser "`bearer`". + +Y debe tener un `access_token`, con un string que contenga nuestro token de acceso. + +Para este ejemplo simple, vamos a ser completamente inseguros y devolver el mismo `username` como el token. + +/// tip | Consejo + +En el próximo capítulo, verás una implementación segura real, con hashing de passwords y tokens JWT. + +Pero por ahora, enfoquémonos en los detalles específicos que necesitamos. + +/// + +{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *} + +/// tip | Consejo + +De acuerdo con la especificación, deberías devolver un JSON con un `access_token` y un `token_type`, igual que en este ejemplo. + +Esto es algo que tienes que hacer tú mismo en tu código, y asegurarte de usar esas claves JSON. + +Es casi lo único que tienes que recordar hacer correctamente tú mismo, para ser compatible con las especificaciones. + +Para el resto, **FastAPI** lo maneja por ti. + +/// + +## Actualizar las dependencias + +Ahora vamos a actualizar nuestras dependencias. + +Queremos obtener el `current_user` *solo* si este usuario está activo. + +Entonces, creamos una dependencia adicional `get_current_active_user` que a su vez utiliza `get_current_user` como dependencia. + +Ambas dependencias solo devolverán un error HTTP si el usuario no existe, o si está inactivo. + +Así que, en nuestro endpoint, solo obtendremos un usuario si el usuario existe, fue autenticado correctamente, y está activo: + +{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *} + +/// info | Información + +El header adicional `WWW-Authenticate` con el valor `Bearer` que estamos devolviendo aquí también es parte de la especificación. + +Cualquier código de estado HTTP (error) 401 "UNAUTHORIZED" se supone que también debe devolver un header `WWW-Authenticate`. + +En el caso de tokens bearer (nuestro caso), el valor de ese header debe ser `Bearer`. + +De hecho, puedes omitir ese header extra y aún funcionaría. + +Pero se proporciona aquí para cumplir con las especificaciones. + +Además, podría haber herramientas que lo esperen y lo usen (ahora o en el futuro) y eso podría ser útil para ti o tus usuarios, ahora o en el futuro. + +Ese es el beneficio de los estándares... + +/// + +## Verlo en acción + +Abre la documentación interactiva: http://127.0.0.1:8000/docs. + +### Autenticar + +Haz clic en el botón "Authorize". + +Usa las credenciales: + +Usuario: `johndoe` + +Contraseña: `secret` + + + +Después de autenticarte en el sistema, lo verás así: + + + +### Obtener tus propios datos de usuario + +Ahora usa la operación `GET` con la path `/users/me`. + +Obtendrás los datos de tu usuario, como: + +```JSON +{ + "username": "johndoe", + "email": "johndoe@example.com", + "full_name": "John Doe", + "disabled": false, + "hashed_password": "fakehashedsecret" +} +``` + + + +Si haces clic en el icono de candado y cierras sesión, y luego intentas la misma operación nuevamente, obtendrás un error HTTP 401 de: + +```JSON +{ + "detail": "Not authenticated" +} +``` + +### Usuario inactivo + +Ahora prueba con un usuario inactivo, autentícate con: + +Usuario: `alice` + +Contraseña: `secret2` + +Y trata de usar la operación `GET` con la path `/users/me`. + +Obtendrás un error de "Usuario inactivo", como: + +```JSON +{ + "detail": "Inactive user" +} +``` + +## Recapitulación + +Ahora tienes las herramientas para implementar un sistema de seguridad completo basado en `username` y `password` para tu API. + +Usando estas herramientas, puedes hacer que el sistema de seguridad sea compatible con cualquier base de datos y con cualquier modelo de usuario o de datos. + +El único detalle que falta es que en realidad no es "seguro" aún. + +En el próximo capítulo verás cómo usar un paquete de hashing de passwords seguro y tokens JWT. diff --git a/docs/es/docs/tutorial/sql-databases.md b/docs/es/docs/tutorial/sql-databases.md new file mode 100644 index 000000000..68cc78603 --- /dev/null +++ b/docs/es/docs/tutorial/sql-databases.md @@ -0,0 +1,360 @@ +# Bases de Datos SQL (Relacionales) + +**FastAPI** no requiere que uses una base de datos SQL (relacional). Pero puedes utilizar **cualquier base de datos** que desees. + +Aquí veremos un ejemplo usando SQLModel. + +**SQLModel** está construido sobre SQLAlchemy y Pydantic. Fue creado por el mismo autor de **FastAPI** para ser la combinación perfecta para aplicaciones de FastAPI que necesiten usar **bases de datos SQL**. + +/// tip | Consejo + +Puedes usar cualquier otro paquete de bases de datos SQL o NoSQL que quieras (en algunos casos llamadas "ORMs"), FastAPI no te obliga a usar nada. 😎 + +/// + +Como SQLModel se basa en SQLAlchemy, puedes usar fácilmente **cualquier base de datos soportada** por SQLAlchemy (lo que las hace también soportadas por SQLModel), como: + +* PostgreSQL +* MySQL +* SQLite +* Oracle +* Microsoft SQL Server, etc. + +En este ejemplo, usaremos **SQLite**, porque utiliza un solo archivo y Python tiene soporte integrado. Así que puedes copiar este ejemplo y ejecutarlo tal cual. + +Más adelante, para tu aplicación en producción, es posible que desees usar un servidor de base de datos como **PostgreSQL**. + +/// tip | Consejo + +Hay un generador de proyectos oficial con **FastAPI** y **PostgreSQL** que incluye un frontend y más herramientas: https://github.com/fastapi/full-stack-fastapi-template + +/// + +Este es un tutorial muy simple y corto, si deseas aprender sobre bases de datos en general, sobre SQL o más funcionalidades avanzadas, ve a la documentación de SQLModel. + +## Instalar `SQLModel` + +Primero, asegúrate de crear tu [entorno virtual](../virtual-environments.md){.internal-link target=_blank}, actívalo, y luego instala `sqlmodel`: + +
+ +```console +$ pip install sqlmodel +---> 100% +``` + +
+ +## Crear la App con un Solo Modelo + +Primero crearemos la versión más simple de la aplicación con un solo modelo de **SQLModel**. + +Más adelante la mejoraremos aumentando la seguridad y versatilidad con **múltiples modelos** a continuación. 🤓 + +### Crear Modelos + +Importa `SQLModel` y crea un modelo de base de datos: + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[1:11] hl[7:11] *} + +La clase `Hero` es muy similar a un modelo de Pydantic (de hecho, en el fondo, realmente *es un modelo de Pydantic*). + +Hay algunas diferencias: + +* `table=True` le dice a SQLModel que este es un *modelo de tabla*, que debe representar una **tabla** en la base de datos SQL, no es solo un *modelo de datos* (como lo sería cualquier otra clase regular de Pydantic). + +* `Field(primary_key=True)` le dice a SQLModel que `id` es la **clave primaria** en la base de datos SQL (puedes aprender más sobre claves primarias de SQL en la documentación de SQLModel). + + Al tener el tipo como `int | None`, SQLModel sabrá que esta columna debe ser un `INTEGER` en la base de datos SQL y que debe ser `NULLABLE`. + +* `Field(index=True)` le dice a SQLModel que debe crear un **índice SQL** para esta columna, lo que permitirá búsquedas más rápidas en la base de datos cuando se lean datos filtrados por esta columna. + + SQLModel sabrá que algo declarado como `str` será una columna SQL de tipo `TEXT` (o `VARCHAR`, dependiendo de la base de datos). + +### Crear un Engine + +Un `engine` de SQLModel (en el fondo, realmente es un `engine` de SQLAlchemy) es lo que **mantiene las conexiones** a la base de datos. + +Tendrías **un solo objeto `engine`** para todo tu código para conectar a la misma base de datos. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[14:18] hl[14:15,17:18] *} + +Usar `check_same_thread=False` permite a FastAPI usar la misma base de datos SQLite en diferentes hilos. Esto es necesario ya que **una sola request** podría usar **más de un hilo** (por ejemplo, en dependencias). + +No te preocupes, con la forma en que está estructurado el código, nos aseguraremos de usar **una sola *session* de SQLModel por request** más adelante, esto es realmente lo que intenta lograr el `check_same_thread`. + +### Crear las Tablas + +Luego añadimos una función que usa `SQLModel.metadata.create_all(engine)` para **crear las tablas** para todos los *modelos de tabla*. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[21:22] hl[21:22] *} + +### Crear una Dependencia de Session + +Una **`Session`** es lo que almacena los **objetos en memoria** y lleva un seguimiento de cualquier cambio necesario en los datos, luego **usa el `engine`** para comunicarse con la base de datos. + +Crearemos una **dependencia de FastAPI** con `yield` que proporcionará una nueva `Session` para cada request. Esto es lo que asegura que usemos una sola session por request. 🤓 + +Luego creamos una dependencia `Annotated` `SessionDep` para simplificar el resto del código que usará esta dependencia. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[25:30] hl[25:27,30] *} + +### Crear Tablas de Base de Datos al Arrancar + +Crearemos las tablas de la base de datos cuando arranque la aplicación. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[32:37] hl[35:37] *} + +Aquí creamos las tablas en un evento de inicio de la aplicación. + +Para producción probablemente usarías un script de migración que se ejecuta antes de iniciar tu aplicación. 🤓 + +/// tip | Consejo + +SQLModel tendrá utilidades de migración envolviendo Alembic, pero por ahora, puedes usar Alembic directamente. + +/// + +### Crear un Hero + +Debido a que cada modelo de SQLModel también es un modelo de Pydantic, puedes usarlo en las mismas **anotaciones de tipos** que podrías usar en modelos de Pydantic. + +Por ejemplo, si declaras un parámetro de tipo `Hero`, será leído desde el **JSON body**. + +De la misma manera, puedes declararlo como el **tipo de retorno** de la función, y luego la forma de los datos aparecerá en la interfaz automática de documentación de la API. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[40:45] hl[40:45] *} + + + +Aquí usamos la dependencia `SessionDep` (una `Session`) para añadir el nuevo `Hero` a la instance `Session`, comiteamos los cambios a la base de datos, refrescamos los datos en el `hero` y luego lo devolvemos. + +### Leer Heroes + +Podemos **leer** `Hero`s de la base de datos usando un `select()`. Podemos incluir un `limit` y `offset` para paginar los resultados. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[48:55] hl[51:52,54] *} + +### Leer Un Hero + +Podemos **leer** un único `Hero`. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[58:63] hl[60] *} + +### Eliminar un Hero + +También podemos **eliminar** un `Hero`. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[66:73] hl[71] *} + +### Ejecutar la App + +Puedes ejecutar la aplicación: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Luego dirígete a la interfaz de `/docs`, verás que **FastAPI** está usando estos **modelos** para **documentar** la API, y los usará para **serializar** y **validar** los datos también. + +
+ +
+ +## Actualizar la App con Múltiples Modelos + +Ahora vamos a **refactorizar** un poco esta aplicación para aumentar la **seguridad** y la **versatilidad**. + +Si revisas la aplicación anterior, en la interfaz verás que, hasta ahora, permite al cliente decidir el `id` del `Hero` a crear. 😱 + +No deberíamos permitir que eso suceda, podrían sobrescribir un `id` que ya tenemos asignado en la base de datos. Decidir el `id` debería ser tarea del **backend** o la **base de datos**, **no del cliente**. + +Además, creamos un `secret_name` para el héroe, pero hasta ahora, lo estamos devolviendo en todas partes, eso no es muy **secreto**... 😅 + +Arreglaremos estas cosas añadiendo unos **modelos extra**. Aquí es donde SQLModel brillará. ✨ + +### Crear Múltiples Modelos + +En **SQLModel**, cualquier clase de modelo que tenga `table=True` es un **modelo de tabla**. + +Y cualquier clase de modelo que no tenga `table=True` es un **modelo de datos**, estos son en realidad solo modelos de Pydantic (con un par de características extra pequeñas). 🤓 + +Con SQLModel, podemos usar **herencia** para **evitar duplicar** todos los campos en todos los casos. + +#### `HeroBase` - la clase base + +Comencemos con un modelo `HeroBase` que tiene todos los **campos que son compartidos** por todos los modelos: + +* `name` +* `age` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:9] hl[7:9] *} + +#### `Hero` - el *modelo de tabla* + +Luego, crearemos `Hero`, el *modelo de tabla* real, con los **campos extra** que no siempre están en los otros modelos: + +* `id` +* `secret_name` + +Debido a que `Hero` hereda de `HeroBase`, **también** tiene los **campos** declarados en `HeroBase`, por lo que todos los campos para `Hero` son: + +* `id` +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:14] hl[12:14] *} + +#### `HeroPublic` - el *modelo de datos* público + +A continuación, creamos un modelo `HeroPublic`, este es el que será **devuelto** a los clientes de la API. + +Tiene los mismos campos que `HeroBase`, por lo que no incluirá `secret_name`. + +Por fin, la identidad de nuestros héroes está protegida! 🥷 + +También vuelve a declarar `id: int`. Al hacer esto, estamos haciendo un **contrato** con los clientes de la API, para que siempre puedan esperar que el `id` esté allí y sea un `int` (nunca será `None`). + +/// tip | Consejo + +Tener el modelo de retorno asegurando que un valor siempre esté disponible y siempre sea `int` (no `None`) es muy útil para los clientes de la API, pueden escribir código mucho más simple teniendo esta certeza. + +Además, los **clientes generados automáticamente** tendrán interfaces más simples, para que los desarrolladores que se comuniquen con tu API puedan tener una experiencia mucho mejor trabajando con tu API. 😎 + +/// + +Todos los campos en `HeroPublic` son los mismos que en `HeroBase`, con `id` declarado como `int` (no `None`): + +* `id` +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:18] hl[17:18] *} + +#### `HeroCreate` - el *modelo de datos* para crear un héroe + +Ahora creamos un modelo `HeroCreate`, este es el que **validará** los datos de los clientes. + +Tiene los mismos campos que `HeroBase`, y también tiene `secret_name`. + +Ahora, cuando los clientes **crean un nuevo héroe**, enviarán el `secret_name`, se almacenará en la base de datos, pero esos nombres secretos no se devolverán en la API a los clientes. + +/// tip | Consejo + +Esta es la forma en la que manejarías **contraseñas**. Recíbelas, pero no las devuelvas en la API. + +También **hashea** los valores de las contraseñas antes de almacenarlos, **nunca los almacenes en texto plano**. + +/// + +Los campos de `HeroCreate` son: + +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:22] hl[21:22] *} + +#### `HeroUpdate` - el *modelo de datos* para actualizar un héroe + +No teníamos una forma de **actualizar un héroe** en la versión anterior de la aplicación, pero ahora con **múltiples modelos**, podemos hacerlo. 🎉 + +El *modelo de datos* `HeroUpdate` es algo especial, tiene **todos los mismos campos** que serían necesarios para crear un nuevo héroe, pero todos los campos son **opcionales** (todos tienen un valor por defecto). De esta forma, cuando actualices un héroe, puedes enviar solo los campos que deseas actualizar. + +Debido a que todos los **campos realmente cambian** (el tipo ahora incluye `None` y ahora tienen un valor por defecto de `None`), necesitamos **volver a declararlos**. + +Realmente no necesitamos heredar de `HeroBase` porque estamos volviendo a declarar todos los campos. Lo dejaré heredando solo por consistencia, pero esto no es necesario. Es más una cuestión de gusto personal. 🤷 + +Los campos de `HeroUpdate` son: + +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:28] hl[25:28] *} + +### Crear con `HeroCreate` y devolver un `HeroPublic` + +Ahora que tenemos **múltiples modelos**, podemos actualizar las partes de la aplicación que los usan. + +Recibimos en la request un *modelo de datos* `HeroCreate`, y a partir de él, creamos un *modelo de tabla* `Hero`. + +Este nuevo *modelo de tabla* `Hero` tendrá los campos enviados por el cliente, y también tendrá un `id` generado por la base de datos. + +Luego devolvemos el mismo *modelo de tabla* `Hero` tal cual desde la función. Pero como declaramos el `response_model` con el *modelo de datos* `HeroPublic`, **FastAPI** usará `HeroPublic` para validar y serializar los datos. + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[56:62] hl[56:58] *} + +/// tip | Consejo + +Ahora usamos `response_model=HeroPublic` en lugar de la **anotación de tipo de retorno** `-> HeroPublic` porque el valor que estamos devolviendo en realidad *no* es un `HeroPublic`. + +Si hubiéramos declarado `-> HeroPublic`, tu editor y linter se quejarían (con razón) de que estás devolviendo un `Hero` en lugar de un `HeroPublic`. + +Al declararlo en `response_model` le estamos diciendo a **FastAPI** que haga lo suyo, sin interferir con las anotaciones de tipo y la ayuda de tu editor y otras herramientas. + +/// + +### Leer Heroes con `HeroPublic` + +Podemos hacer lo mismo que antes para **leer** `Hero`s, nuevamente, usamos `response_model=list[HeroPublic]` para asegurar que los datos se validen y serialicen correctamente. + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[65:72] hl[65] *} + +### Leer Un Hero con `HeroPublic` + +Podemos **leer** un único héroe: + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[75:80] hl[77] *} + +### Actualizar un Hero con `HeroUpdate` + +Podemos **actualizar un héroe**. Para esto usamos una operación HTTP `PATCH`. + +Y en el código, obtenemos un `dict` con todos los datos enviados por el cliente, **solo los datos enviados por el cliente**, excluyendo cualquier valor que estaría allí solo por ser valores por defecto. Para hacerlo usamos `exclude_unset=True`. Este es el truco principal. 🪄 + +Luego usamos `hero_db.sqlmodel_update(hero_data)` para actualizar el `hero_db` con los datos de `hero_data`. + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[83:93] hl[83:84,88:89] *} + +### Eliminar un Hero de Nuevo + +**Eliminar** un héroe se mantiene prácticamente igual. + +No satisfaremos el deseo de refactorizar todo en este punto. 😅 + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[96:103] hl[101] *} + +### Ejecutar la App de Nuevo + +Puedes ejecutar la aplicación de nuevo: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Si vas a la interfaz de `/docs` de la API, verás que ahora está actualizada, y no esperará recibir el `id` del cliente al crear un héroe, etc. + +
+ +
+ +## Resumen + +Puedes usar **SQLModel** para interactuar con una base de datos SQL y simplificar el código con *modelos de datos* y *modelos de tablas*. + +Puedes aprender mucho más en la documentación de **SQLModel**, hay un mini tutorial sobre el uso de SQLModel con **FastAPI**. 🚀 diff --git a/docs/es/docs/tutorial/static-files.md b/docs/es/docs/tutorial/static-files.md new file mode 100644 index 000000000..6aefecc4b --- /dev/null +++ b/docs/es/docs/tutorial/static-files.md @@ -0,0 +1,40 @@ +# Archivos Estáticos + +Puedes servir archivos estáticos automáticamente desde un directorio utilizando `StaticFiles`. + +## Usa `StaticFiles` + +* Importa `StaticFiles`. +* "Monta" una instance de `StaticFiles()` en un path específico. + +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} + +/// note | Detalles Técnicos + +También podrías usar `from starlette.staticfiles import StaticFiles`. + +**FastAPI** proporciona el mismo `starlette.staticfiles` como `fastapi.staticfiles` solo como una conveniencia para ti, el desarrollador. Pero en realidad viene directamente de Starlette. + +/// + +### Qué es "Montar" + +"Montar" significa agregar una aplicación completa "independiente" en un path específico, que luego se encargará de manejar todos los sub-paths. + +Esto es diferente a usar un `APIRouter`, ya que una aplicación montada es completamente independiente. El OpenAPI y la documentación de tu aplicación principal no incluirán nada de la aplicación montada, etc. + +Puedes leer más sobre esto en la [Guía de Usuario Avanzada](../advanced/index.md){.internal-link target=_blank}. + +## Detalles + +El primer `"/static"` se refiere al sub-path en el que esta "sub-aplicación" será "montada". Por lo tanto, cualquier path que comience con `"/static"` será manejado por ella. + +El `directory="static"` se refiere al nombre del directorio que contiene tus archivos estáticos. + +El `name="static"` le da un nombre que puede ser utilizado internamente por **FastAPI**. + +Todos estos parámetros pueden ser diferentes a "`static`", ajústalos según las necesidades y detalles específicos de tu propia aplicación. + +## Más info + +Para más detalles y opciones revisa la documentación de Starlette sobre Archivos Estáticos. diff --git a/docs/es/docs/tutorial/testing.md b/docs/es/docs/tutorial/testing.md new file mode 100644 index 000000000..62ad89d58 --- /dev/null +++ b/docs/es/docs/tutorial/testing.md @@ -0,0 +1,240 @@ +# Testing + +Gracias a Starlette, escribir pruebas para aplicaciones de **FastAPI** es fácil y agradable. + +Está basado en HTTPX, que a su vez está diseñado basado en Requests, por lo que es muy familiar e intuitivo. + +Con él, puedes usar pytest directamente con **FastAPI**. + +## Usando `TestClient` + +/// info | Información + +Para usar `TestClient`, primero instala `httpx`. + +Asegúrate de crear un [entorno virtual](../virtual-environments.md){.internal-link target=_blank}, activarlo y luego instalarlo, por ejemplo: + +```console +$ pip install httpx +``` + +/// + +Importa `TestClient`. + +Crea un `TestClient` pasándole tu aplicación de **FastAPI**. + +Crea funciones con un nombre que comience con `test_` (esta es la convención estándar de `pytest`). + +Usa el objeto `TestClient` de la misma manera que con `httpx`. + +Escribe declaraciones `assert` simples con las expresiones estándar de Python que necesites revisar (otra vez, estándar de `pytest`). + +{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *} + +/// tip | Consejo + +Nota que las funciones de prueba son `def` normales, no `async def`. + +Y las llamadas al cliente también son llamadas normales, sin usar `await`. + +Esto te permite usar `pytest` directamente sin complicaciones. + +/// + +/// note | Nota Técnica + +También podrías usar `from starlette.testclient import TestClient`. + +**FastAPI** proporciona el mismo `starlette.testclient` como `fastapi.testclient` solo por conveniencia para ti, el desarrollador. Pero proviene directamente de Starlette. + +/// + +/// tip | Consejo + +Si quieres llamar a funciones `async` en tus pruebas además de enviar solicitudes a tu aplicación FastAPI (por ejemplo, funciones asincrónicas de bases de datos), echa un vistazo a las [Pruebas Asincrónicas](../advanced/async-tests.md){.internal-link target=_blank} en el tutorial avanzado. + +/// + +## Separando pruebas + +En una aplicación real, probablemente tendrías tus pruebas en un archivo diferente. + +Y tu aplicación de **FastAPI** también podría estar compuesta de varios archivos/módulos, etc. + +### Archivo de aplicación **FastAPI** + +Digamos que tienes una estructura de archivos como se describe en [Aplicaciones Más Grandes](bigger-applications.md){.internal-link target=_blank}: + +``` +. +├── app +│   ├── __init__.py +│   └── main.py +``` + +En el archivo `main.py` tienes tu aplicación de **FastAPI**: + +{* ../../docs_src/app_testing/main.py *} + +### Archivo de prueba + +Entonces podrías tener un archivo `test_main.py` con tus pruebas. Podría estar en el mismo paquete de Python (el mismo directorio con un archivo `__init__.py`): + +``` hl_lines="5" +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +Debido a que este archivo está en el mismo paquete, puedes usar importaciones relativas para importar el objeto `app` desde el módulo `main` (`main.py`): + +{* ../../docs_src/app_testing/test_main.py hl[3] *} + +...y tener el código para las pruebas tal como antes. + +## Pruebas: ejemplo extendido + +Ahora extiende este ejemplo y añade más detalles para ver cómo escribir pruebas para diferentes partes. + +### Archivo de aplicación **FastAPI** extendido + +Continuemos con la misma estructura de archivos que antes: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +Digamos que ahora el archivo `main.py` con tu aplicación de **FastAPI** tiene algunas otras **path operations**. + +Tiene una operación `GET` que podría devolver un error. + +Tiene una operación `POST` que podría devolver varios errores. + +Ambas *path operations* requieren un `X-Token` header. + +//// tab | Python 3.10+ + +```Python +{!> ../../docs_src/app_testing/app_b_an_py310/main.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python +{!> ../../docs_src/app_testing/app_b_an_py39/main.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python +{!> ../../docs_src/app_testing/app_b_an/main.py!} +``` + +//// + +//// tab | Python 3.10+ sin Anotar + +/// tip | Consejo + +Prefiere usar la versión `Annotated` si es posible. + +/// + +```Python +{!> ../../docs_src/app_testing/app_b_py310/main.py!} +``` + +//// + +//// tab | Python 3.8+ sin Anotar + +/// tip | Consejo + +Prefiere usar la versión `Annotated` si es posible. + +/// + +```Python +{!> ../../docs_src/app_testing/app_b/main.py!} +``` + +//// + +### Archivo de prueba extendido + +Podrías entonces actualizar `test_main.py` con las pruebas extendidas: + +{* ../../docs_src/app_testing/app_b/test_main.py *} + +Cada vez que necesites que el cliente pase información en el request y no sepas cómo, puedes buscar (Googlear) cómo hacerlo en `httpx`, o incluso cómo hacerlo con `requests`, dado que el diseño de HTTPX está basado en el diseño de Requests. + +Luego simplemente haces lo mismo en tus pruebas. + +Por ejemplo: + +* Para pasar un parámetro de *path* o *query*, añádelo a la URL misma. +* Para pasar un cuerpo JSON, pasa un objeto de Python (por ejemplo, un `dict`) al parámetro `json`. +* Si necesitas enviar *Form Data* en lugar de JSON, usa el parámetro `data` en su lugar. +* Para pasar *headers*, usa un `dict` en el parámetro `headers`. +* Para *cookies*, un `dict` en el parámetro `cookies`. + +Para más información sobre cómo pasar datos al backend (usando `httpx` o el `TestClient`) revisa la documentación de HTTPX. + +/// info | Información + +Ten en cuenta que el `TestClient` recibe datos que pueden ser convertidos a JSON, no modelos de Pydantic. + +Si tienes un modelo de Pydantic en tu prueba y quieres enviar sus datos a la aplicación durante las pruebas, puedes usar el `jsonable_encoder` descrito en [Codificador Compatible con JSON](encoder.md){.internal-link target=_blank}. + +/// + +## Ejecútalo + +Después de eso, solo necesitas instalar `pytest`. + +Asegúrate de crear un [entorno virtual](../virtual-environments.md){.internal-link target=_blank}, activarlo y luego instalarlo, por ejemplo: + +
+ +```console +$ pip install pytest + +---> 100% +``` + +
+ +Detectará los archivos y pruebas automáticamente, ejecutará las mismas y te reportará los resultados. + +Ejecuta las pruebas con: + +
+ +```console +$ pytest + +================ test session starts ================ +platform linux -- Python 3.6.9, pytest-5.3.5, py-1.8.1, pluggy-0.13.1 +rootdir: /home/user/code/superawesome-cli/app +plugins: forked-1.1.3, xdist-1.31.0, cov-2.8.1 +collected 6 items + +---> 100% + +test_main.py ...... [100%] + +================= 1 passed in 0.03s ================= +``` + +
diff --git a/docs/es/docs/virtual-environments.md b/docs/es/docs/virtual-environments.md new file mode 100644 index 000000000..71d450e09 --- /dev/null +++ b/docs/es/docs/virtual-environments.md @@ -0,0 +1,842 @@ +# Entornos Virtuales + +Cuando trabajas en proyectos de Python probablemente deberías usar un **entorno virtual** (o un mecanismo similar) para aislar los paquetes que instalas para cada proyecto. + +/// info | Información + +Si ya sabes sobre entornos virtuales, cómo crearlos y usarlos, podrías querer saltar esta sección. 🤓 + +/// + +/// tip | Consejo + +Un **entorno virtual** es diferente de una **variable de entorno**. + +Una **variable de entorno** es una variable en el sistema que puede ser usada por programas. + +Un **entorno virtual** es un directorio con algunos archivos en él. + +/// + +/// info | Información + +Esta página te enseñará cómo usar **entornos virtuales** y cómo funcionan. + +Si estás listo para adoptar una **herramienta que gestiona todo** por ti (incluyendo la instalación de Python), prueba uv. + +/// + +## Crea un Proyecto + +Primero, crea un directorio para tu proyecto. + +Lo que normalmente hago es crear un directorio llamado `code` dentro de mi directorio de usuario. + +Y dentro de eso creo un directorio por proyecto. + +
+ +```console +// Ve al directorio principal +$ cd +// Crea un directorio para todos tus proyectos de código +$ mkdir code +// Entra en ese directorio de código +$ cd code +// Crea un directorio para este proyecto +$ mkdir awesome-project +// Entra en ese directorio del proyecto +$ cd awesome-project +``` + +
+ +## Crea un Entorno Virtual + +Cuando empiezas a trabajar en un proyecto de Python **por primera vez**, crea un entorno virtual **dentro de tu proyecto**. + +/// tip | Consejo + +Solo necesitas hacer esto **una vez por proyecto**, no cada vez que trabajas. + +/// + +//// tab | `venv` + +Para crear un entorno virtual, puedes usar el módulo `venv` que viene con Python. + +
+ +```console +$ python -m venv .venv +``` + +
+ +/// details | Qué significa ese comando + +* `python`: usa el programa llamado `python` +* `-m`: llama a un módulo como un script, indicaremos cuál módulo a continuación +* `venv`: usa el módulo llamado `venv` que normalmente viene instalado con Python +* `.venv`: crea el entorno virtual en el nuevo directorio `.venv` + +/// + +//// + +//// tab | `uv` + +Si tienes instalado `uv`, puedes usarlo para crear un entorno virtual. + +
+ +```console +$ uv venv +``` + +
+ +/// tip | Consejo + +Por defecto, `uv` creará un entorno virtual en un directorio llamado `.venv`. + +Pero podrías personalizarlo pasando un argumento adicional con el nombre del directorio. + +/// + +//// + +Ese comando crea un nuevo entorno virtual en un directorio llamado `.venv`. + +/// details | `.venv` u otro nombre + +Podrías crear el entorno virtual en un directorio diferente, pero hay una convención de llamarlo `.venv`. + +/// + +## Activa el Entorno Virtual + +Activa el nuevo entorno virtual para que cualquier comando de Python que ejecutes o paquete que instales lo utilicen. + +/// tip | Consejo + +Haz esto **cada vez** que inicies una **nueva sesión de terminal** para trabajar en el proyecto. + +/// + +//// tab | Linux, macOS + +
+ +```console +$ source .venv/bin/activate +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ .venv\Scripts\Activate.ps1 +``` + +
+ +//// + +//// tab | Windows Bash + +O si usas Bash para Windows (por ejemplo, Git Bash): + +
+ +```console +$ source .venv/Scripts/activate +``` + +
+ +//// + +/// tip | Consejo + +Cada vez que instales un **nuevo paquete** en ese entorno, **activa** el entorno de nuevo. + +Esto asegura que si usas un programa de **terminal (CLI)** instalado por ese paquete, uses el de tu entorno virtual y no cualquier otro que podría estar instalado globalmente, probablemente con una versión diferente a la que necesitas. + +/// + +## Verifica que el Entorno Virtual esté Activo + +Verifica que el entorno virtual esté activo (el comando anterior funcionó). + +/// tip | Consejo + +Esto es **opcional**, pero es una buena forma de **revisar** que todo está funcionando como se esperaba y estás usando el entorno virtual que pretendes. + +/// + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
+ +Si muestra el binario de `python` en `.venv/bin/python`, dentro de tu proyecto (en este caso `awesome-project`), entonces funcionó. 🎉 + +//// + +//// tab | Windows PowerShell + +
+ +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
+ +Si muestra el binario de `python` en `.venv\Scripts\python`, dentro de tu proyecto (en este caso `awesome-project`), entonces funcionó. 🎉 + +//// + +## Actualiza `pip` + +/// tip | Consejo + +Si usas `uv` usarías eso para instalar cosas en lugar de `pip`, por lo que no necesitas actualizar `pip`. 😎 + +/// + +Si estás usando `pip` para instalar paquetes (viene por defecto con Python), deberías **actualizarlo** a la última versión. + +Muchos errores exóticos al instalar un paquete se resuelven simplemente actualizando `pip` primero. + +/// tip | Consejo + +Normalmente harías esto **una vez**, justo después de crear el entorno virtual. + +/// + +Asegúrate de que el entorno virtual esté activo (con el comando anterior) y luego ejecuta: + +
+ +```console +$ python -m pip install --upgrade pip + +---> 100% +``` + +
+ +## Añade `.gitignore` + +Si estás usando **Git** (deberías), añade un archivo `.gitignore` para excluir todo en tu `.venv` de Git. + +/// tip | Consejo + +Si usaste `uv` para crear el entorno virtual, ya lo hizo por ti, puedes saltarte este paso. 😎 + +/// + +/// tip | Consejo + +Haz esto **una vez**, justo después de crear el entorno virtual. + +/// + +
+ +```console +$ echo "*" > .venv/.gitignore +``` + +
+ +/// details | Qué significa ese comando + +* `echo "*"`: "imprimirá" el texto `*` en el terminal (la siguiente parte cambia eso un poco) +* `>`: cualquier cosa impresa en el terminal por el comando a la izquierda de `>` no debería imprimirse, sino escribirse en el archivo que va a la derecha de `>` +* `.gitignore`: el nombre del archivo donde debería escribirse el texto + +Y `*` para Git significa "todo". Así que, ignorará todo en el directorio `.venv`. + +Ese comando creará un archivo `.gitignore` con el contenido: + +```gitignore +* +``` + +/// + +## Instala Paquetes + +Después de activar el entorno, puedes instalar paquetes en él. + +/// tip | Consejo + +Haz esto **una vez** al instalar o actualizar los paquetes que necesita tu proyecto. + +Si necesitas actualizar una versión o agregar un nuevo paquete, **harías esto de nuevo**. + +/// + +### Instala Paquetes Directamente + +Si tienes prisa y no quieres usar un archivo para declarar los requisitos de paquetes de tu proyecto, puedes instalarlos directamente. + +/// tip | Consejo + +Es una (muy) buena idea poner los paquetes y las versiones que necesita tu programa en un archivo (por ejemplo, `requirements.txt` o `pyproject.toml`). + +/// + +//// tab | `pip` + +
+ +```console +$ pip install "fastapi[standard]" + +---> 100% +``` + +
+ +//// + +//// tab | `uv` + +Si tienes `uv`: + +
+ +```console +$ uv pip install "fastapi[standard]" +---> 100% +``` + +
+ +//// + +### Instala desde `requirements.txt` + +Si tienes un `requirements.txt`, ahora puedes usarlo para instalar sus paquetes. + +//// tab | `pip` + +
+ +```console +$ pip install -r requirements.txt +---> 100% +``` + +
+ +//// + +//// tab | `uv` + +Si tienes `uv`: + +
+ +```console +$ uv pip install -r requirements.txt +---> 100% +``` + +
+ +//// + +/// details | `requirements.txt` + +Un `requirements.txt` con algunos paquetes podría verse así: + +```requirements.txt +fastapi[standard]==0.113.0 +pydantic==2.8.0 +``` + +/// + +## Ejecuta Tu Programa + +Después de activar el entorno virtual, puedes ejecutar tu programa, y usará el Python dentro de tu entorno virtual con los paquetes que instalaste allí. + +
+ +```console +$ python main.py + +Hello World +``` + +
+ +## Configura Tu Editor + +Probablemente usarías un editor, asegúrate de configurarlo para que use el mismo entorno virtual que creaste (probablemente lo autodetectará) para que puedas obtener autocompletado y errores en línea. + +Por ejemplo: + +* VS Code +* PyCharm + +/// tip | Consejo + +Normalmente solo tendrías que hacer esto **una vez**, cuando crees el entorno virtual. + +/// + +## Desactiva el Entorno Virtual + +Una vez que hayas terminado de trabajar en tu proyecto, puedes **desactivar** el entorno virtual. + +
+ +```console +$ deactivate +``` + +
+ +De esta manera, cuando ejecutes `python` no intentará ejecutarse desde ese entorno virtual con los paquetes instalados allí. + +## Listo para Trabajar + +Ahora estás listo para empezar a trabajar en tu proyecto. + +/// tip | Consejo + +¿Quieres entender todo lo anterior? + +Continúa leyendo. 👇🤓 + +/// + +## Por qué Entornos Virtuales + +Para trabajar con FastAPI necesitas instalar Python. + +Después de eso, necesitarías **instalar** FastAPI y cualquier otro **paquete** que desees usar. + +Para instalar paquetes normalmente usarías el comando `pip` que viene con Python (o alternativas similares). + +Sin embargo, si solo usas `pip` directamente, los paquetes se instalarían en tu **entorno global de Python** (la instalación global de Python). + +### El Problema + +Entonces, ¿cuál es el problema de instalar paquetes en el entorno global de Python? + +En algún momento, probablemente terminarás escribiendo muchos programas diferentes que dependen de **diferentes paquetes**. Y algunos de estos proyectos en los que trabajas dependerán de **diferentes versiones** del mismo paquete. 😱 + +Por ejemplo, podrías crear un proyecto llamado `philosophers-stone`, este programa depende de otro paquete llamado **`harry`, usando la versión `1`**. Así que, necesitas instalar `harry`. + +```mermaid +flowchart LR + stone(philosophers-stone) -->|requires| harry-1[harry v1] +``` + +Luego, en algún momento después, creas otro proyecto llamado `prisoner-of-azkaban`, y este proyecto también depende de `harry`, pero este proyecto necesita **`harry` versión `3`**. + +```mermaid +flowchart LR + azkaban(prisoner-of-azkaban) --> |requires| harry-3[harry v3] +``` + +Pero ahora el problema es, si instalas los paquetes globalmente (en el entorno global) en lugar de en un **entorno virtual local**, tendrás que elegir qué versión de `harry` instalar. + +Si deseas ejecutar `philosophers-stone` necesitarás primero instalar `harry` versión `1`, por ejemplo con: + +
+ +```console +$ pip install "harry==1" +``` + +
+ +Y entonces terminarías con `harry` versión `1` instalada en tu entorno global de Python. + +```mermaid +flowchart LR + subgraph global[global env] + harry-1[harry v1] + end + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) -->|requires| harry-1 + end +``` + +Pero luego si deseas ejecutar `prisoner-of-azkaban`, necesitarás desinstalar `harry` versión `1` e instalar `harry` versión `3` (o simplemente instalar la versión `3` automáticamente desinstalaría la versión `1`). + +
+ +```console +$ pip install "harry==3" +``` + +
+ +Y entonces terminarías con `harry` versión `3` instalada en tu entorno global de Python. + +Y si intentas ejecutar `philosophers-stone` de nuevo, hay una posibilidad de que **no funcione** porque necesita `harry` versión `1`. + +```mermaid +flowchart LR + subgraph global[global env] + harry-1[harry v1] + style harry-1 fill:#ccc,stroke-dasharray: 5 5 + harry-3[harry v3] + end + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) -.-x|⛔️| harry-1 + end + subgraph azkaban-project[prisoner-of-azkaban project] + azkaban(prisoner-of-azkaban) --> |requires| harry-3 + end +``` + +/// tip | Consejo + +Es muy común en los paquetes de Python intentar lo mejor para **evitar romper cambios** en **nuevas versiones**, pero es mejor estar seguro e instalar nuevas versiones intencionalmente y cuando puedas ejecutar las pruebas para verificar que todo está funcionando correctamente. + +/// + +Ahora, imagina eso con **muchos** otros **paquetes** de los que dependen todos tus **proyectos**. Eso es muy difícil de manejar. Y probablemente terminarías ejecutando algunos proyectos con algunas **versiones incompatibles** de los paquetes, y sin saber por qué algo no está funcionando. + +Además, dependiendo de tu sistema operativo (por ejemplo, Linux, Windows, macOS), podría haber venido con Python ya instalado. Y en ese caso probablemente tenía algunos paquetes preinstalados con algunas versiones específicas **necesitadas por tu sistema**. Si instalas paquetes en el entorno global de Python, podrías terminar **rompiendo** algunos de los programas que vinieron con tu sistema operativo. + +## Dónde se Instalan los Paquetes + +Cuando instalas Python, crea algunos directorios con algunos archivos en tu computadora. + +Algunos de estos directorios son los encargados de tener todos los paquetes que instalas. + +Cuando ejecutas: + +
+ +```console +// No ejecutes esto ahora, solo es un ejemplo 🤓 +$ pip install "fastapi[standard]" +---> 100% +``` + +
+ +Eso descargará un archivo comprimido con el código de FastAPI, normalmente desde PyPI. + +También **descargará** archivos para otros paquetes de los que depende FastAPI. + +Luego, **extraerá** todos esos archivos y los pondrá en un directorio en tu computadora. + +Por defecto, pondrá esos archivos descargados y extraídos en el directorio que viene con tu instalación de Python, eso es el **entorno global**. + +## Qué son los Entornos Virtuales + +La solución a los problemas de tener todos los paquetes en el entorno global es usar un **entorno virtual para cada proyecto** en el que trabajas. + +Un entorno virtual es un **directorio**, muy similar al global, donde puedes instalar los paquetes para un proyecto. + +De esta manera, cada proyecto tendrá su propio entorno virtual (directorio `.venv`) con sus propios paquetes. + +```mermaid +flowchart TB + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) --->|requires| harry-1 + subgraph venv1[.venv] + harry-1[harry v1] + end + end + subgraph azkaban-project[prisoner-of-azkaban project] + azkaban(prisoner-of-azkaban) --->|requires| harry-3 + subgraph venv2[.venv] + harry-3[harry v3] + end + end + stone-project ~~~ azkaban-project +``` + +## Qué Significa Activar un Entorno Virtual + +Cuando activas un entorno virtual, por ejemplo con: + +//// tab | Linux, macOS + +
+ +```console +$ source .venv/bin/activate +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ .venv\Scripts\Activate.ps1 +``` + +
+ +//// + +//// tab | Windows Bash + +O si usas Bash para Windows (por ejemplo, Git Bash): + +
+ +```console +$ source .venv/Scripts/activate +``` + +
+ +//// + +Ese comando creará o modificará algunas [variables de entorno](environment-variables.md){.internal-link target=_blank} que estarán disponibles para los siguientes comandos. + +Una de esas variables es la variable `PATH`. + +/// tip | Consejo + +Puedes aprender más sobre la variable de entorno `PATH` en la sección [Variables de Entorno](environment-variables.md#path-environment-variable){.internal-link target=_blank}. + +/// + +Activar un entorno virtual agrega su path `.venv/bin` (en Linux y macOS) o `.venv\Scripts` (en Windows) a la variable de entorno `PATH`. + +Digamos que antes de activar el entorno, la variable `PATH` se veía así: + +//// tab | Linux, macOS + +```plaintext +/usr/bin:/bin:/usr/sbin:/sbin +``` + +Eso significa que el sistema buscaría programas en: + +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Windows\System32 +``` + +Eso significa que el sistema buscaría programas en: + +* `C:\Windows\System32` + +//// + +Después de activar el entorno virtual, la variable `PATH` se vería algo así: + +//// tab | Linux, macOS + +```plaintext +/home/user/code/awesome-project/.venv/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +Eso significa que el sistema ahora comenzará a buscar primero los programas en: + +```plaintext +/home/user/code/awesome-project/.venv/bin +``` + +antes de buscar en los otros directorios. + +Así que, cuando escribas `python` en el terminal, el sistema encontrará el programa Python en + +```plaintext +/home/user/code/awesome-project/.venv/bin/python +``` + +y utilizará ese. + +//// + +//// tab | Windows + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts;C:\Windows\System32 +``` + +Eso significa que el sistema ahora comenzará a buscar primero los programas en: + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts +``` + +antes de buscar en los otros directorios. + +Así que, cuando escribas `python` en el terminal, el sistema encontrará el programa Python en + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +y utilizará ese. + +//// + +Un detalle importante es que pondrá el path del entorno virtual al **comienzo** de la variable `PATH`. El sistema lo encontrará **antes** que cualquier otro Python disponible. De esta manera, cuando ejecutes `python`, utilizará el Python **del entorno virtual** en lugar de cualquier otro `python` (por ejemplo, un `python` de un entorno global). + +Activar un entorno virtual también cambia un par de otras cosas, pero esta es una de las cosas más importantes que hace. + +## Verificando un Entorno Virtual + +Cuando revisas si un entorno virtual está activo, por ejemplo con: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
+ +//// + +Eso significa que el programa `python` que se utilizará es el que está **en el entorno virtual**. + +Usas `which` en Linux y macOS y `Get-Command` en Windows PowerShell. + +La forma en que funciona ese comando es que irá y revisará la variable de entorno `PATH`, pasando por **cada path en orden**, buscando el programa llamado `python`. Una vez que lo encuentre, te **mostrará el path** a ese programa. + +La parte más importante es que cuando llamas a `python`, ese es el exacto "`python`" que será ejecutado. + +Así que, puedes confirmar si estás en el entorno virtual correcto. + +/// tip | Consejo + +Es fácil activar un entorno virtual, obtener un Python, y luego **ir a otro proyecto**. + +Y el segundo proyecto **no funcionaría** porque estás usando el **Python incorrecto**, de un entorno virtual para otro proyecto. + +Es útil poder revisar qué `python` se está usando. 🤓 + +/// + +## Por qué Desactivar un Entorno Virtual + +Por ejemplo, podrías estar trabajando en un proyecto `philosophers-stone`, **activar ese entorno virtual**, instalar paquetes y trabajar con ese entorno. + +Y luego quieres trabajar en **otro proyecto** `prisoner-of-azkaban`. + +Vas a ese proyecto: + +
+ +```console +$ cd ~/code/prisoner-of-azkaban +``` + +
+ +Si no desactivas el entorno virtual para `philosophers-stone`, cuando ejecutes `python` en el terminal, intentará usar el Python de `philosophers-stone`. + +
+ +```console +$ cd ~/code/prisoner-of-azkaban + +$ python main.py + +// Error importando sirius, no está instalado 😱 +Traceback (most recent call last): + File "main.py", line 1, in + import sirius +``` + +
+ +Pero si desactivas el entorno virtual y activas el nuevo para `prisoner-of-askaban` entonces cuando ejecutes `python` utilizará el Python del entorno virtual en `prisoner-of-azkaban`. + +
+ +```console +$ cd ~/code/prisoner-of-azkaban + +// No necesitas estar en el directorio antiguo para desactivar, puedes hacerlo donde sea que estés, incluso después de ir al otro proyecto 😎 +$ deactivate + +// Activa el entorno virtual en prisoner-of-azkaban/.venv 🚀 +$ source .venv/bin/activate + +// Ahora cuando ejecutes python, encontrará el paquete sirius instalado en este entorno virtual ✨ +$ python main.py + +I solemnly swear 🐺 +``` + +
+ +## Alternativas + +Esta es una guía simple para comenzar y enseñarte cómo funciona todo **por debajo**. + +Hay muchas **alternativas** para gestionar entornos virtuales, dependencias de paquetes (requisitos), proyectos. + +Una vez que estés listo y quieras usar una herramienta para **gestionar todo el proyecto**, dependencias de paquetes, entornos virtuales, etc. Te sugeriría probar uv. + +`uv` puede hacer muchas cosas, puede: + +* **Instalar Python** por ti, incluyendo diferentes versiones +* Gestionar el **entorno virtual** para tus proyectos +* Instalar **paquetes** +* Gestionar **dependencias y versiones** de paquetes para tu proyecto +* Asegurarse de que tengas un conjunto **exacto** de paquetes y versiones para instalar, incluidas sus dependencias, para que puedas estar seguro de que puedes ejecutar tu proyecto en producción exactamente igual que en tu computadora mientras desarrollas, esto se llama **locking** +* Y muchas otras cosas + +## Conclusión + +Si leíste y comprendiste todo esto, ahora **sabes mucho más** sobre entornos virtuales que muchos desarrolladores por ahí. 🤓 + +Conocer estos detalles probablemente te será útil en el futuro cuando estés depurando algo que parece complejo, pero sabrás **cómo funciona todo por debajo**. 😎 diff --git a/docs/es/llm-prompt.md b/docs/es/llm-prompt.md new file mode 100644 index 000000000..3340dbc99 --- /dev/null +++ b/docs/es/llm-prompt.md @@ -0,0 +1,148 @@ +Translate to Spanish (español). + +Use the informal grammar (use "tú" instead of "usted"). + +For instructions or titles in imperative, keep them in imperative, for example "Edit it" to "Edítalo". + +There are special blocks of notes, tips and others that look like: + +/// note + +To translate it, keep the same line and add the translation after a vertical bar: + +/// note | Nota + +Some examples: + +Source: + +/// tip + +Result: + +/// tip | Consejo + +Source: + +/// details | Preview + +Result: + +/// details | Vista previa + +Source: + +/// warning + +Result: + +/// warning | Advertencia + +Source: + +/// info + +Result: + +/// info | Información + +Source: + +/// note | Technical Details + +Result: + +/// note | Detalles Técnicos + +--- + +For the next terms, use the following translations: + +* framework: framework (do not translate to "marco") +* performance: rendimiento +* program (verb): programar +* code (verb): programar +* type hints: anotaciones de tipos +* type annotations: anotaciones de tipos +* autocomplete: autocompletado +* completion (in the context of autocompletion): autocompletado +* feature: funcionalidad +* sponsor: sponsor +* host (in a podcast): host +* request (as in HTTP request): request +* response (as in HTTP response): response +* path operation function: path operation function (do not translate to "función de operación de ruta") +* path operation: path operation (do not translate to "operación de ruta") +* path (as in URL path): path (do not translate to "ruta") +* query (as in URL query): query (do not translate to "consulta") +* cookie (as in HTTP cookie): cookie +* header (as in HTTP header): header +* form (as in HTML form): formulario +* type checks: chequeo de tipos +* parse: parse +* parsing: parsing +* marshall: marshall +* library: paquete (do not translate to "biblioteca" or "librería") +* instance: instance (do not translate to "instancia") +* scratch the surface: tocar los conceptos básicos +* string: string +* bug: bug +* docs: documentación (do not translate to "documentos") +* cheat sheet: cheat sheet (do not translate to "chuleta") +* key (as in key-value pair, dictionary key): clave +* array (as in JSON array): array +* API key: API key (do not translate to "clave API") +* 100% test coverage: cobertura de tests del 100% +* back and forth: de un lado a otro +* I/O (as in "input and output"): I/O (do not translate to "E/S") +* Machine Learning: Machine Learning (do not translate to "Aprendizaje Automático") +* Deep Learning: Deep Learning (do not translate to "Aprendizaje Profundo") +* callback hell: callback hell (do not translate to "infierno de callbacks") +* tip: Consejo (do not translate to "tip") +* check: Revisa (do not translate to "chequea" or "comprobación) +* Cross-Origin Resource Sharing: Cross-Origin Resource Sharing (do not translate to "Compartición de Recursos de Origen Cruzado") +* Release Notes: Release Notes (do not translate to "Notas de la Versión") +* Semantic Versioning: Semantic Versioning (do not translate to "Versionado Semántico") +* dependable: dependable (do not translate to "confiable" or "fiable") +* list (as in Python list): list +* context manager: context manager (do not translate to "gestor de contexto" or "administrador de contexto") +* a little bit: un poquito +* graph (data structure, as in "dependency graph"): grafo (do not translate to "gráfico") +* form data: form data (do not translate to "datos de formulario" or "datos de form") +* import (as in code import): import (do not translate to "importación") +* JSON Schema: JSON Schema (do not translate to "Esquema JSON") +* embed: embeber (do not translate to "incrustar") +* request body: request body (do not translate to "cuerpo de la petición") +* response body: response body (do not translate to "cuerpo de la respuesta") +* cross domain: cross domain (do not translate to "dominio cruzado") +* cross origin: cross origin (do not translate to "origen cruzado") +* plugin: plugin (do not translate to "complemento" or "extensión") +* plug-in: plug-in (do not translate to "complemento" or "extensión") +* plug-ins: plug-ins (do not translate to "complementos" or "extensiones") +* full stack: full stack (do not translate to "pila completa") +* full-stack: full-stack (do not translate to "de pila completa") +* stack: stack (do not translate to "pila") +* loop (as in async loop): loop (do not translate to "bucle" or "ciclo") +* hard dependencies: dependencias obligatorias (do not translate to "dependencias duras") +* locking: locking (do not translate to "bloqueo") +* testing (as in software testing): escribir pruebas (do not translate to "probar") +* code base: code base (do not translate to "base de código") +* default: por defecto (do not translate to "predeterminado") +* default values: valores por defecto (do not translate to "valores predeterminados") +* media type: media type (do not translate to "tipo de medio") +* instantiate: crear un instance (do not translate to "instanciar") +* OAuth2 Scopes: Scopes de OAuth2 (do not translate to "Alcances de OAuth2") +* on the fly: sobre la marcha (do not translate to "al vuelo") +* terminal: terminal (femenine, as in "la terminal") +* terminals: terminales (plural femenine, as in "las terminales") +* lifespan: lifespan (do not translate to "vida útil" or "tiempo de vida") +* unload: quitar de memoria (do not translate to "descargar") +* mount (noun): mount (do not translate to "montura") +* mount (verb): montar +* statement (as in code statement): statement (do not translate to "declaración" or "sentencia") +* worker process: worker process (do not translate to "proceso trabajador" or "proceso de trabajo") +* worker processes: worker processes (do not translate to "procesos trabajadores" or "procesos de trabajo") +* worker: worker (do not translate to "trabajador") +* load balancer: load balancer (do not translate to "balanceador de carga") +* load balance: load balance (do not translate to "balancear carga") +* self hosting: self hosting (do not translate to "auto alojamiento") diff --git a/docs/fa/docs/advanced/sub-applications.md b/docs/fa/docs/advanced/sub-applications.md index f3a948414..de813b6cf 100644 --- a/docs/fa/docs/advanced/sub-applications.md +++ b/docs/fa/docs/advanced/sub-applications.md @@ -12,9 +12,7 @@ ابتدا برنامه اصلی سطح بالا، **FastAPI** و path operations آن را ایجاد کنید: -```Python hl_lines="3 6-8" -{!../../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[3,6:8] *} ### زیر برنامه @@ -22,17 +20,13 @@ این زیر برنامه فقط یکی دیگر از برنامه های استاندارد FastAPI است، اما این برنامه ای است که متصل می شود: -```Python hl_lines="11 14-16" -{!../../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11,14:16] *} ### اتصال زیر برنامه در برنامه سطح بالا `app` اتصال زیر برنامه `subapi` در این نمونه `/subapi` در مسیر قرار میدهد و میشود: -```Python hl_lines="11 19" -{!../../../docs_src/sub_applications/tutorial001.py!} -``` +{* ../../docs_src/sub_applications/tutorial001.py hl[11,19] *} ### اسناد API خودکار را بررسی کنید @@ -69,4 +63,4 @@ $ uvicorn main:app --reload و زیر برنامه ها نیز می تواند زیر برنامه های متصل شده خود را داشته باشد و همه چیز به درستی کار کند، زیرا FastAPI تمام این مسیرهای `root_path` را به طور خودکار مدیریت می کند. -در بخش [پشت پراکسی](./behind-a-proxy.md){.internal-link target=_blank}. درباره `root_path` و نحوه استفاده درست از آن بیشتر خواهید آموخت. +در بخش [پشت پراکسی](behind-a-proxy.md){.internal-link target=_blank}. درباره `root_path` و نحوه استفاده درست از آن بیشتر خواهید آموخت. diff --git a/docs/fa/docs/features.md b/docs/fa/docs/features.md index 3040ce3dd..a5ab1597e 100644 --- a/docs/fa/docs/features.md +++ b/docs/fa/docs/features.md @@ -63,10 +63,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` یعنی: +/// info - کلید ها و مقادیر دیکشنری `second_user_data` را مستقیما به عنوان ارگومان های key-value بفرست، که معادل است با : `User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` یعنی: + +کلید ها و مقادیر دیکشنری `second_user_data` را مستقیما به عنوان ارگومان های key-value بفرست، که معادل است با : `User(id=4, name="Mary", joined="2018-11-30")` + +/// ### پشتیبانی ویرایشگر @@ -182,7 +185,7 @@ FastAPI شامل یک سیستم 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." -
Kabir Khan - Microsoft (ref)
+
Kabir Khan - Microsoft (ref)
--- @@ -84,7 +90,7 @@ FastAPI یک وب فریم‌ورک مدرن و سریع (با کارایی با
"Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted Hug to be - it's really inspiring to see someone build that."
-
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- @@ -111,7 +117,7 @@ FastAPI یک وب فریم‌ورک مدرن و سریع (با کارایی با FastAPI مبتنی بر ابزارهای قدرتمند زیر است: * فریم‌ورک Starlette برای بخش وب. -* کتابخانه Pydantic برای بخش داده‌. +* کتابخانه Pydantic برای بخش داده‌. ## نصب @@ -125,7 +131,7 @@ $ pip install fastapi -نصب یک سرور پروداکشن نظیر Uvicorn یا Hypercorn نیز جزء نیازمندی‌هاست. +نصب یک سرور پروداکشن نظیر Uvicorn یا Hypercorn نیز جزء نیازمندی‌هاست.
@@ -140,7 +146,7 @@ $ pip install "uvicorn[standard]" ## مثال ### ایجاد کنید -* فایلی به نام `main.py` با محتوای زیر ایجاد کنید : +* فایلی به نام `main.py` با محتوای زیر ایجاد کنید: ```Python from typing import Union @@ -163,7 +169,7 @@ def read_item(item_id: int, q: Union[str, None] = None):
همچنین می‌توانید از async def... نیز استفاده کنید -اگر در کدتان از `async` / `await` استفاده می‌کنید, از `async def` برای تعریف تابع خود استفاده کنید: +اگر در کدتان از `async` / `await` استفاده می‌کنید، از `async def` برای تعریف تابع خود استفاده کنید: ```Python hl_lines="9 14" from typing import Optional @@ -211,7 +217,7 @@ INFO: Application startup complete.
درباره دستور uvicorn main:app --reload... -دستور `uvicorn main:app` شامل موارد زیر است: +دستور `uvicorn main:app` شامل موارد زیر است: * `main`: فایل `main.py` (ماژول پایتون ایجاد شده). * `app`: شیء ایجاد شده در فایل `main.py` در خط `app = FastAPI()`. @@ -232,7 +238,7 @@ INFO: Application startup complete. تا اینجا شما APIای ساختید که: * درخواست‌های HTTP به _مسیرهای_ `/` و `/items/{item_id}` را دریافت می‌کند. -* هردو _مسیر_ عملیات (یا HTTP _متد_) `GET` را پشتیبانی می‌کنند. +* هردو _مسیر_ عملیات (یا HTTP _متد_) `GET` را پشتیبانی می‌کند. * _مسیر_ `/items/{item_id}` شامل _پارامتر مسیر_ `item_id` از نوع `int` است. * _مسیر_ `/items/{item_id}` شامل _پارامتر پرسمان_ اختیاری `q` از نوع `str` است. @@ -254,7 +260,7 @@ INFO: Application startup complete. ## تغییر مثال -حال فایل `main.py` را مطابق زیر ویرایش کنید تا بتوانید بدنه یک درخواست `PUT` را دریافت کنید. +حال فایل `main.py` را مطابق زیر ویرایش کنید تا بتوانید بدنه یک درخواست `PUT` را دریافت کنید. به کمک Pydantic بدنه درخواست را با انواع استاندارد پایتون تعریف کنید. @@ -298,11 +304,11 @@ def update_item(item_id: int, item: Item): ![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) -* روی دکمه "Try it out" کلیک کنید, اکنون می‌توانید پارامترهای مورد نیاز هر API را مشخص کرده و به صورت مستقیم با آنها تعامل کنید: +* روی دکمه "Try it out" کلیک کنید، اکنون می‌توانید پارامترهای مورد نیاز هر API را مشخص کرده و به صورت مستقیم با آنها تعامل کنید: ![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) -* سپس روی دکمه "Execute" کلیک کنید, خواهید دید که واسط کاریری با APIهای تعریف شده ارتباط برقرار کرده، پارامترهای مورد نیاز را به آن‌ها ارسال می‌کند، سپس نتایج را دریافت کرده و در صفحه نشان می‌دهد: +* سپس روی دکمه "Execute" کلیک کنید، خواهید دید که واسط کاربری با APIهای تعریف شده ارتباط برقرار کرده، پارامترهای مورد نیاز را به آن‌ها ارسال می‌کند، سپس نتایج را دریافت کرده و در صفحه نشان می‌دهد: ![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) @@ -342,7 +348,7 @@ item: Item * تکمیل کد. * بررسی انواع داده. * اعتبارسنجی داده: - * خطاهای خودکار و مشخص در هنگام نامعتبر بودن داده + * خطاهای خودکار و مشخص در هنگام نامعتبر بودن داده. * اعتبارسنجی، حتی برای اشیاء JSON تو در تو. * تبدیل داده ورودی: که از شبکه رسیده به انواع و داد‌ه‌ پایتونی. این داده‌ شامل: * JSON. @@ -366,22 +372,22 @@ item: Item به مثال قبلی باز می‌گردیم، در این مثال **FastAPI** موارد زیر را انجام می‌دهد: -* اعتبارسنجی اینکه پارامتر `item_id` در مسیر درخواست‌های `GET` و `PUT` موجود است . +* اعتبارسنجی اینکه پارامتر `item_id` در مسیر درخواست‌های `GET` و `PUT` موجود است. * اعتبارسنجی اینکه پارامتر `item_id` در درخواست‌های `GET` و `PUT` از نوع `int` است. * اگر غیر از این موارد باشد، سرویس‌گیرنده خطای مفید و مشخصی دریافت خواهد کرد. * بررسی وجود پارامتر پرسمان اختیاری `q` (مانند `http://127.0.0.1:8000/items/foo?q=somequery`) در درخواست‌های `GET`. - * از آنجا که پارامتر `q` با `= None` مقداردهی شده است, این پارامتر اختیاری است. + * از آنجا که پارامتر `q` با `= None` مقداردهی شده است، این پارامتر اختیاری است. * اگر از مقدار اولیه `None` استفاده نکنیم، این پارامتر الزامی خواهد بود (همانند بدنه درخواست در درخواست `PUT`). -* برای درخواست‌های `PUT` به آدرس `/items/{item_id}`, بدنه درخواست باید از نوع JSON تعریف شده باشد: +* برای درخواست‌های `PUT` به آدرس `/items/{item_id}`، بدنه درخواست باید از نوع JSON تعریف شده باشد: * بررسی اینکه بدنه شامل فیلدی با نام `name` و از نوع `str` است. * بررسی اینکه بدنه شامل فیلدی با نام `price` و از نوع `float` است. - * بررسی اینکه بدنه شامل فیلدی اختیاری با نام `is_offer` است, که در صورت وجود باید از نوع `bool` باشد. + * بررسی اینکه بدنه شامل فیلدی اختیاری با نام `is_offer` است، که در صورت وجود باید از نوع `bool` باشد. * تمامی این موارد برای اشیاء JSON در هر عمقی قابل بررسی می‌باشد. * تبدیل از/به JSON به صورت خودکار. -* مستندسازی همه چیز با استفاده از OpenAPI, که می‌توان از آن برای موارد زیر استفاده کرد: +* مستندسازی همه چیز با استفاده از OpenAPI، که می‌توان از آن برای موارد زیر استفاده کرد: * سیستم مستندات تعاملی. * تولید خودکار کد سرویس‌گیرنده‌ در زبان‌های برنامه‌نویسی بیشمار. -* فراهم سازی ۲ مستند تعاملی مبتنی بر وب به صورت پیش‌فرض . +* فراهم سازی ۲ مستند تعاملی مبتنی بر وب به صورت پیش‌فرض. --- @@ -413,7 +419,7 @@ item: Item **هشدار اسپویل**: بخش آموزش - راهنمای کاربر شامل موارد زیر است: -* اعلان **پارامترهای** موجود در بخش‌های دیگر درخواست، شامل: **سرآیند‌ (هدر)ها**, **کوکی‌ها**, **فیلد‌های فرم** و **فایل‌ها**. +* اعلان **پارامترهای** موجود در بخش‌های دیگر درخواست، شامل: **سرآیند‌ (هدر)ها**، **کوکی‌ها**، **فیلد‌های فرم** و **فایل‌ها**. * چگونگی تنظیم **محدودیت‌های اعتبارسنجی** به عنوان مثال `maximum_length` یا `regex`. * سیستم **Dependency Injection** قوی و کاربردی. * امنیت و تایید هویت, شامل پشتیبانی از **OAuth2** مبتنی بر **JWT tokens** و **HTTP Basic**. @@ -428,7 +434,7 @@ item: Item ## کارایی -معیار (بنچمارک‌)های مستقل TechEmpower حاکی از آن است که برنامه‌های **FastAPI** که تحت Uvicorn اجرا می‌شود، یکی از سریع‌ترین فریم‌ورک‌های مبتنی بر پایتون, است که کمی ضعیف‌تر از Starlette و Uvicorn عمل می‌کند (فریم‌ورک و سروری که FastAPI بر اساس آنها ایجاد شده است) (*) +معیار (بنچمارک‌)های مستقل TechEmpower حاکی از آن است که برنامه‌های **FastAPI** که تحت Uvicorn اجرا می‌شود، یکی از سریع‌ترین فریم‌ورک‌های مبتنی بر پایتون، است که کمی ضعیف‌تر از Starlette و Uvicorn عمل می‌کند (فریم‌ورک و سروری که FastAPI بر اساس آنها ایجاد شده است) (*) برای درک بهتری از این موضوع به بخش بنچ‌مارک‌ها مراجعه کنید. @@ -436,23 +442,23 @@ item: Item استفاده شده توسط Pydantic: -* email_validator - برای اعتبارسنجی آدرس‌های ایمیل. +* email-validator - برای اعتبارسنجی آدرس‌های ایمیل. استفاده شده توسط Starlette: * HTTPX - در صورتی که می‌خواهید از `TestClient` استفاده کنید. * aiofiles - در صورتی که می‌خواهید از `FileResponse` و `StaticFiles` استفاده کنید. * jinja2 - در صورتی که بخواهید از پیکربندی پیش‌فرض برای قالب‌ها استفاده کنید. -* python-multipart - در صورتی که بخواهید با استفاده از `request.form()` از قابلیت "تجزیه (parse)" فرم استفاده کنید. +* python-multipart - در صورتی که بخواهید با استفاده از `request.form()` از قابلیت "تجزیه (parse)" فرم استفاده کنید. * itsdangerous - در صورتی که بخواید از `SessionMiddleware` پشتیبانی کنید. -* pyyaml - برای پشتیبانی `SchemaGenerator` در Starlet (به احتمال زیاد برای کار کردن با FastAPI به آن نیازی پیدا نمی‌کنید.). +* pyyaml - برای پشتیبانی `SchemaGenerator` در Starlet (به احتمال زیاد برای کار کردن با FastAPI به آن نیازی پیدا نمی‌کنید). * graphene - در صورتی که از `GraphQLApp` پشتیبانی می‌کنید. -* ujson - در صورتی که بخواهید از `UJSONResponse` استفاده کنید. استفاده شده توسط FastAPI / Starlette: * uvicorn - برای سرور اجرا کننده برنامه وب. * orjson - در صورتی که بخواهید از `ORJSONResponse` استفاده کنید. +* ujson - در صورتی که بخواهید از `UJSONResponse` استفاده کنید. می‌توان همه این موارد را با استفاده از دستور `pip install fastapi[all]`. به صورت یکجا نصب کرد. diff --git a/docs/fa/docs/tutorial/middleware.md b/docs/fa/docs/tutorial/middleware.md new file mode 100644 index 000000000..75b1c4c5c --- /dev/null +++ b/docs/fa/docs/tutorial/middleware.md @@ -0,0 +1,63 @@ +# میان‌افزار - middleware + +شما میتوانید میان‌افزارها را در **FastAPI** اضافه کنید. + +"میان‌افزار" یک تابع است که با هر درخواست(request) قبل از پردازش توسط هر path operation (عملیات مسیر) خاص کار می‌کند. همچنین با هر پاسخ(response) قبل از بازگشت آن نیز کار می‌کند. + +* هر **درخواستی (request)** که به برنامه شما می آید را می گیرد. +* سپس می تواند کاری برای آن **درخواست** انجام دهید یا هر کد مورد نیازتان را اجرا کنید. +* سپس **درخواست** را به بخش دیگری از برنامه (توسط یک path operation مشخص) برای پردازش ارسال می کند. +* سپس **پاسخ** تولید شده توسط برنامه را (توسط یک path operation مشخص) دریافت می‌کند. +* می تواند کاری با **پاسخ** انجام دهید یا هر کد مورد نیازتان را اجرا کند. +* سپس **پاسخ** را برمی گرداند. + +/// توجه | جزئیات فنی + +در صورت وجود وابستگی هایی با `yield`، کد خروجی **پس از** اجرای میان‌‌افزار اجرا خواهد شد. + +در صورت وجود هر گونه وظایف پس زمینه (که در ادامه توضیح داده می‌شوند)، تمام میان‌افزارها *پس از آن* اجرا خواهند شد. + +/// + +## ساخت یک میان افزار + +برای ایجاد یک میان‌افزار، از دکوریتور `@app.middleware("http")` در بالای یک تابع استفاده می‌شود. + +تابع میان افزار دریافت می کند: +* `درخواست` +* تابع `call_next` که `درخواست` را به عنوان پارامتر دریافت می کند + * این تابع `درخواست` را به *path operation* مربوطه ارسال می کند. + * سپس `پاسخ` تولید شده توسط *path operation* مربوطه را برمی‌گرداند. +* شما می‌توانید سپس `پاسخ` را تغییر داده و پس از آن را برگردانید. + +{* ../../docs_src/middleware/tutorial001.py hl[8:9,11,14] *} + +/// نکته | به خاطر داشته باشید که هدرهای اختصاصی سفارشی را می توان با استفاده از پیشوند "X-" اضافه کرد. + +اما اگر هدرهای سفارشی دارید که می‌خواهید مرورگر کاربر بتواند آنها را ببیند، باید آنها را با استفاده از پارامتر `expose_headers` که در مستندات CORS از Starlette توضیح داده شده است، به پیکربندی CORS خود اضافه کنید. + +/// + +/// توجه | جزئیات فنی + +شما همچنین می‌توانید از `from starlette.requests import Request` استفاده کنید. + +**FastAPI** این را به عنوان یک سهولت برای شما به عنوان برنامه‌نویس فراهم می‌کند. اما این مستقیما از Starlette به دست می‌آید. + +/// + +### قبل و بعد از `پاسخ` + +شما می‌توانید کدی را برای اجرا با `درخواست`، قبل از اینکه هر *path operation* آن را دریافت کند، اضافه کنید. + +همچنین پس از تولید `پاسخ`، قبل از بازگشت آن، می‌توانید کدی را اضافه کنید. + +به عنوان مثال، می‌توانید یک هدر سفارشی به نام `X-Process-Time` که شامل زمان پردازش درخواست و تولید پاسخ به صورت ثانیه است، اضافه کنید. + +{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *} + + ## سایر میان افزار + +شما می‌توانید بعداً در مورد میان‌افزارهای دیگر در [راهنمای کاربر پیشرفته: میان‌افزار پیشرفته](../advanced/middleware.md){.internal-link target=_blank} بیشتر بخوانید. + +شما در بخش بعدی در مورد این که چگونه با استفاده از یک میان‌افزار، CORS را مدیریت کنید، خواهید خواند. diff --git a/docs/fa/docs/tutorial/security/index.md b/docs/fa/docs/tutorial/security/index.md new file mode 100644 index 000000000..c0827a8b3 --- /dev/null +++ b/docs/fa/docs/tutorial/security/index.md @@ -0,0 +1,106 @@ +# امنیت + +روش‌های مختلفی برای مدیریت امنیت، تأیید هویت و اعتبارسنجی وجود دارد. + +عموماً این یک موضوع پیچیده و "سخت" است. + +در بسیاری از فریم ورک ها و سیستم‌ها، فقط مدیریت امنیت و تأیید هویت نیاز به تلاش و کد نویسی زیادی دارد (در بسیاری از موارد می‌تواند 50% یا بیشتر کل کد نوشته شده باشد). + + +فریم ورک **FastAPI** ابزارهای متعددی را در اختیار شما قرار می دهد تا به راحتی، با سرعت، به صورت استاندارد و بدون نیاز به مطالعه و یادگیری همه جزئیات امنیت، در مدیریت **امنیت** به شما کمک کند. + +اما قبل از آن، بیایید برخی از مفاهیم کوچک را بررسی کنیم. + +## عجله دارید؟ + +اگر به هیچ یک از این اصطلاحات اهمیت نمی دهید و فقط نیاز به افزودن امنیت با تأیید هویت بر اساس نام کاربری و رمز عبور دارید، *همین الان* به فصل های بعدی بروید. + +## پروتکل استاندارد OAuth2 + +پروتکل استاندارد OAuth2 یک مشخصه است که چندین روش برای مدیریت تأیید هویت و اعتبار سنجی تعریف می کند. + +این مشخصه بسیار گسترده است و چندین حالت استفاده پیچیده را پوشش می دهد. + +در آن روش هایی برای تأیید هویت با استفاده از "برنامه های شخص ثالث" وجود دارد. + +این همان چیزی است که تمامی سیستم های با "ورود با فیسبوک، گوگل، توییتر، گیت هاب" در پایین آن را استفاده می کنند. + +### پروتکل استاندارد OAuth 1 + +پروتکل استاندارد OAuth1 نیز وجود داشت که با OAuth2 خیلی متفاوت است و پیچیدگی بیشتری داشت، زیرا شامل مشخصات مستقیم در مورد رمزگذاری ارتباط بود. + +در حال حاضر OAuth1 بسیار محبوب یا استفاده شده نیست. + +پروتکل استاندارد OAuth2 روش رمزگذاری ارتباط را مشخص نمی کند، بلکه انتظار دارد که برنامه شما با HTTPS سرویس دهی شود. + +/// نکته + +در بخش در مورد **استقرار** ، شما یاد خواهید گرفت که چگونه با استفاده از Traefik و Let's Encrypt رایگان HTTPS را راه اندازی کنید. + +/// + +## استاندارد OpenID Connect + +استاندارد OpenID Connect، مشخصه‌ای دیگر است که بر پایه **OAuth2** ساخته شده است. + +این مشخصه، به گسترش OAuth2 می‌پردازد و برخی مواردی که در OAuth2 نسبتاً تردید برانگیز هستند را مشخص می‌کند تا سعی شود آن را با سایر سیستم‌ها قابل ارتباط کند. + +به عنوان مثال، ورود به سیستم گوگل از OpenID Connect استفاده می‌کند (که در زیر از OAuth2 استفاده می‌کند). + +اما ورود به سیستم فیسبوک، از OpenID Connect پشتیبانی نمی‌کند. به جای آن، نسخه خودش از OAuth2 را دارد. + +### استاندارد OpenID (نه "OpenID Connect" ) + +همچنین مشخصه "OpenID" نیز وجود داشت که سعی در حل مسائل مشابه OpenID Connect داشت، اما بر پایه OAuth2 ساخته نشده بود. + +بنابراین، یک سیستم جداگانه بود. + +اکنون این مشخصه کمتر استفاده می‌شود و محبوبیت زیادی ندارد. + +## استاندارد OpenAPI + +استاندارد OpenAPI (قبلاً با نام Swagger شناخته می‌شد) یک open specification برای ساخت APIs (که در حال حاضر جزئی از بنیاد لینوکس میباشد) است. + +فریم ورک **FastAPI** بر اساس **OpenAPI** است. + +این خاصیت، امکان دارد تا چندین رابط مستندات تعاملی خودکار(automatic interactive documentation interfaces)، تولید کد و غیره وجود داشته باشد. + +مشخصه OpenAPI روشی برای تعریف چندین "schemes" دارد. + +با استفاده از آن‌ها، شما می‌توانید از همه این ابزارهای مبتنی بر استاندارد استفاده کنید، از جمله این سیستم‌های مستندات تعاملی(interactive documentation systems). + +استاندارد OpenAPI شیوه‌های امنیتی زیر را تعریف می‌کند: + +* شیوه `apiKey`: یک کلید اختصاصی برای برنامه که می‌تواند از موارد زیر استفاده شود: + * پارامتر جستجو. + * هدر. + * کوکی. +* شیوه `http`: سیستم‌های استاندارد احراز هویت HTTP، از جمله: + * مقدار `bearer`: یک هدر `Authorization` با مقدار `Bearer` به همراه یک توکن. این از OAuth2 به ارث برده شده است. + * احراز هویت پایه HTTP. + * ویژگی HTTP Digest و غیره. +* شیوه `oauth2`: تمام روش‌های OAuth2 برای مدیریت امنیت (به نام "flows"). + * چندین از این flows برای ساخت یک ارائه‌دهنده احراز هویت OAuth 2.0 مناسب هستند (مانند گوگل، فیسبوک، توییتر، گیت‌هاب و غیره): + * ویژگی `implicit` + * ویژگی `clientCredentials` + * ویژگی `authorizationCode` + * اما یک "flow" خاص وجود دارد که می‌تواند به طور کامل برای مدیریت احراز هویت در همان برنامه به کار رود: + * بررسی `password`: چند فصل بعدی به مثال‌های این مورد خواهیم پرداخت. +* شیوه `openIdConnect`: یک روش برای تعریف نحوه کشف داده‌های احراز هویت OAuth2 به صورت خودکار. + * کشف خودکار این موضوع را که در مشخصه OpenID Connect تعریف شده است، مشخص می‌کند. + +/// نکته + +ادغام سایر ارائه‌دهندگان احراز هویت/اجازه‌دهی مانند گوگل، فیسبوک، توییتر، گیت‌هاب و غیره نیز امکان‌پذیر و نسبتاً آسان است. + +مشکل پیچیده‌ترین مسئله، ساخت یک ارائه‌دهنده احراز هویت/اجازه‌دهی مانند آن‌ها است، اما **FastAPI** ابزارهای لازم برای انجام این کار را با سهولت به شما می‌دهد و همه کارهای سنگین را برای شما انجام می‌دهد. + +/// + +## ابزارهای **FastAPI** + +فریم ورک FastAPI ابزارهایی برای هر یک از این شیوه‌های امنیتی در ماژول`fastapi.security` فراهم می‌کند که استفاده از این مکانیزم‌های امنیتی را ساده‌تر می‌کند. + +در فصل‌های بعدی، شما یاد خواهید گرفت که چگونه با استفاده از این ابزارهای ارائه شده توسط **FastAPI**، امنیت را به API خود اضافه کنید. + +همچنین، خواهید دید که چگونه به صورت خودکار در سیستم مستندات تعاملی ادغام می‌شود. diff --git a/docs/fr/docs/advanced/additional-responses.md b/docs/fr/docs/advanced/additional-responses.md index 35b57594d..38527aad3 100644 --- a/docs/fr/docs/advanced/additional-responses.md +++ b/docs/fr/docs/advanced/additional-responses.md @@ -1,9 +1,12 @@ # Réponses supplémentaires dans OpenAPI -!!! Attention - Ceci concerne un sujet plutôt avancé. +/// warning | Attention - Si vous débutez avec **FastAPI**, vous n'en aurez peut-être pas besoin. +Ceci concerne un sujet plutôt avancé. + +Si vous débutez avec **FastAPI**, vous n'en aurez peut-être pas besoin. + +/// Vous pouvez déclarer des réponses supplémentaires, avec des codes HTTP, des types de médias, des descriptions, etc. @@ -23,24 +26,28 @@ Chacun de ces `dict` de réponse peut avoir une clé `model`, contenant un modè Par exemple, pour déclarer une autre réponse avec un code HTTP `404` et un modèle Pydantic `Message`, vous pouvez écrire : -```Python hl_lines="18 22" -{!../../../docs_src/additional_responses/tutorial001.py!} -``` +{* ../../docs_src/additional_responses/tutorial001.py hl[18,22] *} + +/// note | Remarque + +Gardez à l'esprit que vous devez renvoyer directement `JSONResponse`. + +/// + +/// info -!!! Remarque - Gardez à l'esprit que vous devez renvoyer directement `JSONResponse`. +La clé `model` ne fait pas partie d'OpenAPI. -!!! Info - La clé `model` ne fait pas partie d'OpenAPI. +**FastAPI** prendra le modèle Pydantic à partir de là, générera le `JSON Schema` et le placera au bon endroit. - **FastAPI** prendra le modèle Pydantic à partir de là, générera le `JSON Schema` et le placera au bon endroit. +Le bon endroit est : - Le bon endroit est : +* Dans la clé `content`, qui a pour valeur un autre objet JSON (`dict`) qui contient : + * Une clé avec le type de support, par ex. `application/json`, qui contient comme valeur un autre objet JSON, qui contient : + * Une clé `schema`, qui a pour valeur le schéma JSON du modèle, voici le bon endroit. + * **FastAPI** ajoute ici une référence aux schémas JSON globaux à un autre endroit de votre OpenAPI au lieu de l'inclure directement. De cette façon, d'autres applications et clients peuvent utiliser ces schémas JSON directement, fournir de meilleurs outils de génération de code, etc. - * Dans la clé `content`, qui a pour valeur un autre objet JSON (`dict`) qui contient : - * Une clé avec le type de support, par ex. `application/json`, qui contient comme valeur un autre objet JSON, qui contient : - * Une clé `schema`, qui a pour valeur le schéma JSON du modèle, voici le bon endroit. - * **FastAPI** ajoute ici une référence aux schémas JSON globaux à un autre endroit de votre OpenAPI au lieu de l'inclure directement. De cette façon, d'autres applications et clients peuvent utiliser ces schémas JSON directement, fournir de meilleurs outils de génération de code, etc. +/// Les réponses générées au format OpenAPI pour cette *opération de chemin* seront : @@ -168,17 +175,21 @@ Vous pouvez utiliser ce même paramètre `responses` pour ajouter différents ty Par exemple, vous pouvez ajouter un type de média supplémentaire `image/png`, en déclarant que votre *opération de chemin* peut renvoyer un objet JSON (avec le type de média `application/json`) ou une image PNG : -```Python hl_lines="19-24 28" -{!../../../docs_src/additional_responses/tutorial002.py!} -``` +{* ../../docs_src/additional_responses/tutorial002.py hl[19:24,28] *} + +/// note | Remarque + +Notez que vous devez retourner l'image en utilisant directement un `FileResponse`. + +/// -!!! Remarque - Notez que vous devez retourner l'image en utilisant directement un `FileResponse`. +/// info -!!! Info - À moins que vous ne spécifiiez explicitement un type de média différent dans votre paramètre `responses`, FastAPI supposera que la réponse a le même type de média que la classe de réponse principale (par défaut `application/json`). +À moins que vous ne spécifiiez explicitement un type de média différent dans votre paramètre `responses`, FastAPI supposera que la réponse a le même type de média que la classe de réponse principale (par défaut `application/json`). - Mais si vous avez spécifié une classe de réponse personnalisée avec `None` comme type de média, FastAPI utilisera `application/json` pour toute réponse supplémentaire associée à un modèle. +Mais si vous avez spécifié une classe de réponse personnalisée avec `None` comme type de média, FastAPI utilisera `application/json` pour toute réponse supplémentaire associée à un modèle. + +/// ## Combinaison d'informations @@ -192,9 +203,7 @@ Par exemple, vous pouvez déclarer une réponse avec un code HTTP `404` qui util Et une réponse avec un code HTTP `200` qui utilise votre `response_model`, mais inclut un `example` personnalisé : -```Python hl_lines="20-31" -{!../../../docs_src/additional_responses/tutorial003.py!} -``` +{* ../../docs_src/additional_responses/tutorial003.py hl[20:31] *} Tout sera combiné et inclus dans votre OpenAPI, et affiché dans la documentation de l'API : @@ -206,7 +215,7 @@ Vous voulez peut-être avoir des réponses prédéfinies qui s'appliquent à de Dans ces cas, vous pouvez utiliser la technique Python "d'affection par décomposition" (appelé _unpacking_ en anglais) d'un `dict` avec `**dict_to_unpack` : -``` Python +```Python old_dict = { "old key": "old value", "second old key": "second old value", @@ -216,7 +225,7 @@ new_dict = {**old_dict, "new key": "new value"} Ici, `new_dict` contiendra toutes les paires clé-valeur de `old_dict` plus la nouvelle paire clé-valeur : -``` Python +```Python { "old key": "old value", "second old key": "second old value", @@ -228,9 +237,7 @@ Vous pouvez utiliser cette technique pour réutiliser certaines réponses préd Par exemple: -```Python hl_lines="13-17 26" -{!../../../docs_src/additional_responses/tutorial004.py!} -``` +{* ../../docs_src/additional_responses/tutorial004.py hl[13:17,26] *} ## Plus d'informations sur les réponses OpenAPI diff --git a/docs/fr/docs/advanced/additional-status-codes.md b/docs/fr/docs/advanced/additional-status-codes.md index e7b003707..dde6b9a63 100644 --- a/docs/fr/docs/advanced/additional-status-codes.md +++ b/docs/fr/docs/advanced/additional-status-codes.md @@ -14,21 +14,25 @@ Mais vous voulez aussi qu'il accepte de nouveaux éléments. Et lorsque les él Pour y parvenir, importez `JSONResponse` et renvoyez-y directement votre contenu, en définissant le `status_code` que vous souhaitez : -```Python hl_lines="4 25" -{!../../../docs_src/additional_status_codes/tutorial001.py!} -``` +{* ../../docs_src/additional_status_codes/tutorial001.py hl[4,25] *} -!!! Attention - Lorsque vous renvoyez une `Response` directement, comme dans l'exemple ci-dessus, elle sera renvoyée directement. +/// warning | Attention - Elle ne sera pas sérialisée avec un modèle. +Lorsque vous renvoyez une `Response` directement, comme dans l'exemple ci-dessus, elle sera renvoyée directement. - Assurez-vous qu'il contient les données souhaitées et que les valeurs soient dans un format JSON valides (si vous utilisez une `JSONResponse`). +Elle ne sera pas sérialisée avec un modèle. -!!! note "Détails techniques" - Vous pouvez également utiliser `from starlette.responses import JSONResponse`. +Assurez-vous qu'il contient les données souhaitées et que les valeurs soient dans un format JSON valides (si vous utilisez une `JSONResponse`). - Pour plus de commodités, **FastAPI** fournit les objets `starlette.responses` sous forme d'un alias accessible par `fastapi.responses`. Mais la plupart des réponses disponibles proviennent directement de Starlette. Il en est de même avec l'objet `statut`. +/// + +/// note | Détails techniques + +Vous pouvez également utiliser `from starlette.responses import JSONResponse`. + +Pour plus de commodités, **FastAPI** fournit les objets `starlette.responses` sous forme d'un alias accessible par `fastapi.responses`. Mais la plupart des réponses disponibles proviennent directement de Starlette. Il en est de même avec l'objet `statut`. + +/// ## Documents OpenAPI et API diff --git a/docs/fr/docs/advanced/index.md b/docs/fr/docs/advanced/index.md index f4fa5ecf6..d9d8ad8e6 100644 --- a/docs/fr/docs/advanced/index.md +++ b/docs/fr/docs/advanced/index.md @@ -2,18 +2,21 @@ ## Caractéristiques supplémentaires -Le [Tutoriel - Guide de l'utilisateur](../tutorial/){.internal-link target=_blank} devrait suffire à vous faire découvrir toutes les fonctionnalités principales de **FastAPI**. +Le [Tutoriel - Guide de l'utilisateur](../tutorial/index.md){.internal-link target=_blank} devrait suffire à vous faire découvrir toutes les fonctionnalités principales de **FastAPI**. Dans les sections suivantes, vous verrez des options, configurations et fonctionnalités supplémentaires. -!!! Note - Les sections de ce chapitre ne sont **pas nécessairement "avancées"**. +/// note | Remarque - Et il est possible que pour votre cas d'utilisation, la solution se trouve dans l'un d'entre eux. +Les sections de ce chapitre ne sont **pas nécessairement "avancées"**. + +Et il est possible que pour votre cas d'utilisation, la solution se trouve dans l'un d'entre eux. + +/// ## Lisez d'abord le didacticiel -Vous pouvez utiliser la plupart des fonctionnalités de **FastAPI** grâce aux connaissances du [Tutoriel - Guide de l'utilisateur](../tutorial/){.internal-link target=_blank}. +Vous pouvez utiliser la plupart des fonctionnalités de **FastAPI** grâce aux connaissances du [Tutoriel - Guide de l'utilisateur](../tutorial/index.md){.internal-link target=_blank}. Et les sections suivantes supposent que vous l'avez lu et que vous en connaissez les idées principales. diff --git a/docs/fr/docs/advanced/path-operation-advanced-configuration.md b/docs/fr/docs/advanced/path-operation-advanced-configuration.md index 7ded97ce1..7daf0fc65 100644 --- a/docs/fr/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/fr/docs/advanced/path-operation-advanced-configuration.md @@ -2,16 +2,17 @@ ## ID d'opération OpenAPI -!!! Attention - Si vous n'êtes pas un "expert" en OpenAPI, vous n'en avez probablement pas besoin. +/// warning | Attention + +Si vous n'êtes pas un "expert" en OpenAPI, vous n'en avez probablement pas besoin. + +/// Dans OpenAPI, les chemins sont des ressources, tels que /users/ ou /items/, exposées par votre API, et les opérations sont les méthodes HTTP utilisées pour manipuler ces chemins, telles que GET, POST ou DELETE. Les operationId sont des chaînes uniques facultatives utilisées pour identifier une opération d'un chemin. Vous pouvez définir l'OpenAPI `operationId` à utiliser dans votre *opération de chemin* avec le paramètre `operation_id`. Vous devez vous assurer qu'il est unique pour chaque opération. -```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *} ### Utilisation du nom *path operation function* comme operationId @@ -19,25 +20,27 @@ Si vous souhaitez utiliser les noms de fonction de vos API comme `operationId`, Vous devriez le faire après avoir ajouté toutes vos *paramètres de chemin*. -```Python hl_lines="2 12-21 24" -{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2,12:21,24] *} + +/// tip | Astuce -!!! Astuce - Si vous appelez manuellement `app.openapi()`, vous devez mettre à jour les `operationId` avant. +Si vous appelez manuellement `app.openapi()`, vous devez mettre à jour les `operationId` avant. -!!! Attention - Pour faire cela, vous devez vous assurer que chacun de vos *chemin* ait un nom unique. +/// - Même s'ils se trouvent dans des modules différents (fichiers Python). +/// warning | Attention + +Pour faire cela, vous devez vous assurer que chacun de vos *chemin* ait un nom unique. + +Même s'ils se trouvent dans des modules différents (fichiers Python). + +/// ## Exclusion d'OpenAPI Pour exclure un *chemin* du schéma OpenAPI généré (et donc des systèmes de documentation automatiques), utilisez le paramètre `include_in_schema` et assignez-lui la valeur `False` : -```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *} ## Description avancée de docstring @@ -47,9 +50,7 @@ L'ajout d'un `\f` (un caractère d'échappement "form feed") va permettre à **F Il n'apparaîtra pas dans la documentation, mais d'autres outils (tel que Sphinx) pourront utiliser le reste. -```Python hl_lines="19-29" -{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19:29] *} ## Réponses supplémentaires @@ -59,14 +60,17 @@ Cela définit les métadonnées sur la réponse principale d'une *opération de Vous pouvez également déclarer des réponses supplémentaires avec leurs modèles, codes de statut, etc. -Il y a un chapitre entier ici dans la documentation à ce sujet, vous pouvez le lire sur [Réponses supplémentaires dans OpenAPI](./additional-responses.md){.internal-link target=_blank}. +Il y a un chapitre entier ici dans la documentation à ce sujet, vous pouvez le lire sur [Réponses supplémentaires dans OpenAPI](additional-responses.md){.internal-link target=_blank}. ## OpenAPI supplémentaire Lorsque vous déclarez un *chemin* dans votre application, **FastAPI** génère automatiquement les métadonnées concernant ce *chemin* à inclure dans le schéma OpenAPI. -!!! note "Détails techniques" - La spécification OpenAPI appelle ces métadonnées des Objets d'opération. +/// note | Détails techniques + +La spécification OpenAPI appelle ces métadonnées des Objets d'opération. + +/// Il contient toutes les informations sur le *chemin* et est utilisé pour générer automatiquement la documentation. @@ -74,8 +78,11 @@ Il inclut les `tags`, `parameters`, `requestBody`, `responses`, etc. Ce schéma OpenAPI spécifique aux *operations* est normalement généré automatiquement par **FastAPI**, mais vous pouvez également l'étendre. -!!! Astuce - Si vous avez seulement besoin de déclarer des réponses supplémentaires, un moyen plus pratique de le faire est d'utiliser les [réponses supplémentaires dans OpenAPI](./additional-responses.md){.internal-link target=_blank}. +/// tip | Astuce + +Si vous avez seulement besoin de déclarer des réponses supplémentaires, un moyen plus pratique de le faire est d'utiliser les [réponses supplémentaires dans OpenAPI](additional-responses.md){.internal-link target=_blank}. + +/// Vous pouvez étendre le schéma OpenAPI pour une *opération de chemin* en utilisant le paramètre `openapi_extra`. @@ -83,9 +90,7 @@ Vous pouvez étendre le schéma OpenAPI pour une *opération de chemin* en utili Cet `openapi_extra` peut être utile, par exemple, pour déclarer [OpenAPI Extensions](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions) : -```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial005.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial005.py hl[6] *} Si vous ouvrez la documentation automatique de l'API, votre extension apparaîtra au bas du *chemin* spécifique. @@ -132,9 +137,7 @@ Par exemple, vous pouvez décider de lire et de valider la requête avec votre p Vous pouvez le faire avec `openapi_extra` : -```Python hl_lines="20-37 39-40" -{!../../../docs_src/path_operation_advanced_configuration/tutorial006.py !} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial006.py hl[20:37,39:40] *} Dans cet exemple, nous n'avons déclaré aucun modèle Pydantic. En fait, le corps de la requête n'est même pas parsé en tant que JSON, il est lu directement en tant que `bytes`, et la fonction `magic_data_reader()` serait chargé de l'analyser d'une manière ou d'une autre. @@ -148,9 +151,7 @@ Et vous pouvez le faire même si le type de données dans la requête n'est pas Dans cet exemple, nous n'utilisons pas les fonctionnalités de FastAPI pour extraire le schéma JSON des modèles Pydantic ni la validation automatique pour JSON. En fait, nous déclarons le type de contenu de la requête en tant que YAML, et non JSON : -```Python hl_lines="17-22 24" -{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[17:22,24] *} Néanmoins, bien que nous n'utilisions pas la fonctionnalité par défaut, nous utilisons toujours un modèle Pydantic pour générer manuellement le schéma JSON pour les données que nous souhaitons recevoir en YAML. @@ -158,11 +159,12 @@ Ensuite, nous utilisons directement la requête et extrayons son contenu en tant Et nous analysons directement ce contenu YAML, puis nous utilisons à nouveau le même modèle Pydantic pour valider le contenu YAML : -```Python hl_lines="26-33" -{!../../../docs_src/path_operation_advanced_configuration/tutorial007.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[26:33] *} + +/// tip | Astuce + +Ici, nous réutilisons le même modèle Pydantic. -!!! Astuce - Ici, nous réutilisons le même modèle Pydantic. +Mais nous aurions pu tout aussi bien pu le valider d'une autre manière. - Mais nous aurions pu tout aussi bien pu le valider d'une autre manière. +/// diff --git a/docs/fr/docs/advanced/response-directly.md b/docs/fr/docs/advanced/response-directly.md index 1c923fb82..4ff883c77 100644 --- a/docs/fr/docs/advanced/response-directly.md +++ b/docs/fr/docs/advanced/response-directly.md @@ -14,8 +14,11 @@ Cela peut être utile, par exemple, pour retourner des en-têtes personnalisés En fait, vous pouvez retourner n'importe quelle `Response` ou n'importe quelle sous-classe de celle-ci. -!!! Note - `JSONResponse` est elle-même une sous-classe de `Response`. +/// note | Remarque + +`JSONResponse` est elle-même une sous-classe de `Response`. + +/// Et quand vous retournez une `Response`, **FastAPI** la transmet directement. @@ -31,14 +34,15 @@ Par exemple, vous ne pouvez pas mettre un modèle Pydantic dans une `JSONRespons Pour ces cas, vous pouvez spécifier un appel à `jsonable_encoder` pour convertir vos données avant de les passer à une réponse : -```Python hl_lines="6-7 21-22" -{!../../../docs_src/response_directly/tutorial001.py!} -``` +{* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *} + +/// note | Détails techniques + +Vous pouvez aussi utiliser `from starlette.responses import JSONResponse`. -!!! note "Détails techniques" - Vous pouvez aussi utiliser `from starlette.responses import JSONResponse`. +**FastAPI** fournit le même objet `starlette.responses` que `fastapi.responses` juste par commodité pour le développeur. Mais la plupart des réponses disponibles proviennent directement de Starlette. - **FastAPI** fournit le même objet `starlette.responses` que `fastapi.responses` juste par commodité pour le développeur. Mais la plupart des réponses disponibles proviennent directement de Starlette. +/// ## Renvoyer une `Response` personnalisée @@ -50,9 +54,7 @@ Disons que vous voulez retourner une réponse Flask Flask est un "micro-framework", il ne comprend pas d'intégrations de bases de données ni beaucoup de choses qui sont fournies par défaut dans Django. @@ -59,11 +65,14 @@ qui est nécessaire, était une caractéristique clé que je voulais conserver. Compte tenu de la simplicité de Flask, il semblait bien adapté à la création d'API. La prochaine chose à trouver était un "Django REST Framework" pour Flask. -!!! check "A inspiré **FastAPI** à" +/// check | A inspiré **FastAPI** à + Être un micro-framework. Il est donc facile de combiner les outils et les pièces nécessaires. Proposer un système de routage simple et facile à utiliser. +/// + ### Requests **FastAPI** n'est pas réellement une alternative à **Requests**. Leur cadre est très différent. @@ -98,9 +107,13 @@ def read_url(): Notez les similitudes entre `requests.get(...)` et `@app.get(...)`. -!!! check "A inspiré **FastAPI** à" -_ Avoir une API simple et intuitive. -_ Utiliser les noms de méthodes HTTP (opérations) directement, de manière simple et intuitive. \* Avoir des valeurs par défaut raisonnables, mais des personnalisations puissantes. +/// check | A inspiré **FastAPI** à + +Avoir une API simple et intuitive. + +Utiliser les noms de méthodes HTTP (opérations) directement, de manière simple et intuitive. \* Avoir des valeurs par défaut raisonnables, mais des personnalisations puissantes. + +/// ### Swagger / OpenAPI @@ -115,15 +128,18 @@ Swagger pour une API permettrait d'utiliser cette interface utilisateur web auto C'est pourquoi, lorsqu'on parle de la version 2.0, il est courant de dire "Swagger", et pour la version 3+ "OpenAPI". -!!! check "A inspiré **FastAPI** à" +/// check | A inspiré **FastAPI** à + Adopter et utiliser une norme ouverte pour les spécifications des API, au lieu d'un schéma personnalisé. - Intégrer des outils d'interface utilisateur basés sur des normes : +Intégrer des outils d'interface utilisateur basés sur des normes : - * Swagger UI - * ReDoc +* Swagger UI +* ReDoc - Ces deux-là ont été choisis parce qu'ils sont populaires et stables, mais en faisant une recherche rapide, vous pourriez trouver des dizaines d'alternatives supplémentaires pour OpenAPI (que vous pouvez utiliser avec **FastAPI**). +Ces deux-là ont été choisis parce qu'ils sont populaires et stables, mais en faisant une recherche rapide, vous pourriez trouver des dizaines d'alternatives supplémentaires pour OpenAPI (que vous pouvez utiliser avec **FastAPI**). + +/// ### Frameworks REST pour Flask @@ -150,9 +166,12 @@ Ces fonctionnalités sont ce pourquoi Marshmallow a été construit. C'est une e Mais elle a été créée avant que les type hints n'existent en Python. Ainsi, pour définir chaque schéma, vous devez utiliser des utilitaires et des classes spécifiques fournies par Marshmallow. -!!! check "A inspiré **FastAPI** à" +/// check | A inspiré **FastAPI** à + Utilisez du code pour définir des "schémas" qui fournissent automatiquement les types de données et la validation. +/// + ### Webargs Une autre grande fonctionnalité requise par les API est le APISpec Marshmallow et Webargs fournissent la validation, l'analyse et la sérialisation en tant que plug-ins. @@ -188,12 +213,18 @@ Mais alors, nous avons à nouveau le problème d'avoir une micro-syntaxe, dans u L'éditeur ne peut guère aider en la matière. Et si nous modifions les paramètres ou les schémas Marshmallow et que nous oublions de modifier également cette docstring YAML, le schéma généré deviendrait obsolète. -!!! info +/// info + APISpec a été créé par les développeurs de Marshmallow. -!!! check "A inspiré **FastAPI** à" +/// + +/// check | A inspiré **FastAPI** à + Supporter la norme ouverte pour les API, OpenAPI. +/// + ### Flask-apispec C'est un plug-in pour Flask, qui relie Webargs, Marshmallow et APISpec. @@ -215,12 +246,18 @@ j'ai (ainsi que plusieurs équipes externes) utilisées jusqu'à présent : Ces mêmes générateurs full-stack ont servi de base aux [Générateurs de projets pour **FastAPI**](project-generation.md){.internal-link target=\_blank}. -!!! info +/// info + Flask-apispec a été créé par les développeurs de Marshmallow. -!!! check "A inspiré **FastAPI** à" +/// + +/// check | A inspiré **FastAPI** à + Générer le schéma OpenAPI automatiquement, à partir du même code qui définit la sérialisation et la validation. +/// + ### NestJS (et Angular) Ce n'est même pas du Python, NestJS est un framework JavaScript (TypeScript) NodeJS inspiré d'Angular. @@ -236,24 +273,33 @@ Mais comme les données TypeScript ne sont pas préservées après la compilatio Il ne peut pas très bien gérer les modèles imbriqués. Ainsi, si le corps JSON de la requête est un objet JSON comportant des champs internes qui sont à leur tour des objets JSON imbriqués, il ne peut pas être correctement documenté et validé. -!!! check "A inspiré **FastAPI** à" +/// check | A inspiré **FastAPI** à + Utiliser les types Python pour bénéficier d'un excellent support de l'éditeur. - Disposer d'un puissant système d'injection de dépendances. Trouver un moyen de minimiser la répétition du code. +Disposer d'un puissant système d'injection de dépendances. Trouver un moyen de minimiser la répétition du code. + +/// ### Sanic C'était l'un des premiers frameworks Python extrêmement rapides basés sur `asyncio`. Il a été conçu pour être très similaire à Flask. -!!! note "Détails techniques" +/// note | Détails techniques + Il utilisait `uvloop` au lieu du système par défaut de Python `asyncio`. C'est ce qui l'a rendu si rapide. - Il a clairement inspiré Uvicorn et Starlette, qui sont actuellement plus rapides que Sanic dans les benchmarks. +Il a clairement inspiré Uvicorn et Starlette, qui sont actuellement plus rapides que Sanic dans les benchmarks. + +/// + +/// check | A inspiré **FastAPI** à -!!! check "A inspiré **FastAPI** à" Trouvez un moyen d'avoir une performance folle. - C'est pourquoi **FastAPI** est basé sur Starlette, car il s'agit du framework le plus rapide disponible (testé par des benchmarks tiers). +C'est pourquoi **FastAPI** est basé sur Starlette, car il s'agit du framework le plus rapide disponible (testé par des benchmarks tiers). + +/// ### Falcon @@ -267,12 +313,15 @@ pas possible de déclarer des paramètres de requête et des corps avec des indi Ainsi, la validation, la sérialisation et la documentation des données doivent être effectuées dans le code, et non pas automatiquement. Ou bien elles doivent être implémentées comme un framework au-dessus de Falcon, comme Hug. Cette même distinction se retrouve dans d'autres frameworks qui s'inspirent de la conception de Falcon, qui consiste à avoir un objet de requête et un objet de réponse comme paramètres. -!!! check "A inspiré **FastAPI** à" +/// check | A inspiré **FastAPI** à + Trouver des moyens d'obtenir de bonnes performances. - Avec Hug (puisque Hug est basé sur Falcon), **FastAPI** a inspiré la déclaration d'un paramètre `response` dans les fonctions. +Avec Hug (puisque Hug est basé sur Falcon), **FastAPI** a inspiré la déclaration d'un paramètre `response` dans les fonctions. + +Bien que dans FastAPI, il est facultatif, et est utilisé principalement pour définir les en-têtes, les cookies, et les codes de statut alternatifs. - Bien que dans FastAPI, il est facultatif, et est utilisé principalement pour définir les en-têtes, les cookies, et les codes de statut alternatifs. +/// ### Molten @@ -294,12 +343,15 @@ d'utiliser des décorateurs qui peuvent être placés juste au-dessus de la fonc méthode est plus proche de celle de Django que de celle de Flask (et Starlette). Il sépare dans le code des choses qui sont relativement fortement couplées. -!!! check "A inspiré **FastAPI** à" +/// check | A inspiré **FastAPI** à + Définir des validations supplémentaires pour les types de données utilisant la valeur "par défaut" des attributs du modèle. Ceci améliore le support de l'éditeur, et n'était pas disponible dans Pydantic auparavant. - Cela a en fait inspiré la mise à jour de certaines parties de Pydantic, afin de supporter le même style de déclaration de validation (toute cette fonctionnalité est maintenant déjà disponible dans Pydantic). +Cela a en fait inspiré la mise à jour de certaines parties de Pydantic, afin de supporter le même style de déclaration de validation (toute cette fonctionnalité est maintenant déjà disponible dans Pydantic). + +/// -### Hug +### Hug Hug a été l'un des premiers frameworks à implémenter la déclaration des types de paramètres d'API en utilisant les type hints Python. C'était une excellente idée qui a inspiré d'autres outils à faire de même. @@ -314,16 +366,22 @@ API et des CLI. Comme il est basé sur l'ancienne norme pour les frameworks web Python synchrones (WSGI), il ne peut pas gérer les Websockets et autres, bien qu'il soit également très performant. -!!! info +/// info + Hug a été créé par Timothy Crosley, le créateur de `isort`, un excellent outil pour trier automatiquement les imports dans les fichiers Python. -!!! check "A inspiré **FastAPI** à" +/// + +/// check | A inspiré **FastAPI** à + Hug a inspiré certaines parties d'APIStar, et était l'un des outils que je trouvais les plus prometteurs, à côté d'APIStar. - Hug a contribué à inspirer **FastAPI** pour utiliser les type hints Python - pour déclarer les paramètres, et pour générer automatiquement un schéma définissant l'API. +Hug a contribué à inspirer **FastAPI** pour utiliser les type hints Python +pour déclarer les paramètres, et pour générer automatiquement un schéma définissant l'API. + +Hug a inspiré **FastAPI** pour déclarer un paramètre `response` dans les fonctions pour définir les en-têtes et les cookies. - Hug a inspiré **FastAPI** pour déclarer un paramètre `response` dans les fonctions pour définir les en-têtes et les cookies. +/// ### APIStar (<= 0.5) @@ -351,27 +409,33 @@ Il ne s'agissait plus d'un framework web API, le créateur devant se concentrer Maintenant, APIStar est un ensemble d'outils pour valider les spécifications OpenAPI, et non un framework web. -!!! info +/// info + APIStar a été créé par Tom Christie. Le même gars qui a créé : - * Django REST Framework - * Starlette (sur lequel **FastAPI** est basé) - * Uvicorn (utilisé par Starlette et **FastAPI**) +* Django REST Framework +* Starlette (sur lequel **FastAPI** est basé) +* Uvicorn (utilisé par Starlette et **FastAPI**) + +/// + +/// check | A inspiré **FastAPI** à -!!! check "A inspiré **FastAPI** à" Exister. - L'idée de déclarer plusieurs choses (validation des données, sérialisation et documentation) avec les mêmes types Python, tout en offrant un excellent support pour les éditeurs, était pour moi une idée brillante. +L'idée de déclarer plusieurs choses (validation des données, sérialisation et documentation) avec les mêmes types Python, tout en offrant un excellent support pour les éditeurs, était pour moi une idée brillante. - Et après avoir longtemps cherché un framework similaire et testé de nombreuses alternatives, APIStar était la meilleure option disponible. +Et après avoir longtemps cherché un framework similaire et testé de nombreuses alternatives, APIStar était la meilleure option disponible. - Puis APIStar a cessé d'exister en tant que serveur et Starlette a été créé, et a constitué une meilleure base pour un tel système. Ce fut l'inspiration finale pour construire **FastAPI**. +Puis APIStar a cessé d'exister en tant que serveur et Starlette a été créé, et a constitué une meilleure base pour un tel système. Ce fut l'inspiration finale pour construire **FastAPI**. - Je considère **FastAPI** comme un "successeur spirituel" d'APIStar, tout en améliorant et en augmentant les fonctionnalités, le système de typage et d'autres parties, sur la base des enseignements tirés de tous ces outils précédents. +Je considère **FastAPI** comme un "successeur spirituel" d'APIStar, tout en améliorant et en augmentant les fonctionnalités, le système de typage et d'autres parties, sur la base des enseignements tirés de tous ces outils précédents. + +/// ## Utilisés par **FastAPI** -### Pydantic +### Pydantic Pydantic est une bibliothèque permettant de définir la validation, la sérialisation et la documentation des données (à l'aide de JSON Schema) en se basant sur les Python type hints. @@ -380,10 +444,13 @@ Cela le rend extrêmement intuitif. Il est comparable à Marshmallow. Bien qu'il soit plus rapide que Marshmallow dans les benchmarks. Et comme il est basé sur les mêmes type hints Python, le support de l'éditeur est grand. -!!! check "**FastAPI** l'utilise pour" +/// check | **FastAPI** l'utilise pour + Gérer toute la validation des données, leur sérialisation et la documentation automatique du modèle (basée sur le schéma JSON). - **FastAPI** prend ensuite ces données JSON Schema et les place dans OpenAPI, en plus de toutes les autres choses qu'il fait. +**FastAPI** prend ensuite ces données JSON Schema et les place dans OpenAPI, en plus de toutes les autres choses qu'il fait. + +/// ### Starlette @@ -413,17 +480,23 @@ Mais il ne fournit pas de validation automatique des données, de sérialisation C'est l'une des principales choses que **FastAPI** ajoute par-dessus, le tout basé sur les type hints Python (en utilisant Pydantic). Cela, plus le système d'injection de dépendances, les utilitaires de sécurité, la génération de schémas OpenAPI, etc. -!!! note "Détails techniques" +/// note | Détails techniques + ASGI est une nouvelle "norme" développée par les membres de l'équipe principale de Django. Il ne s'agit pas encore d'une "norme Python" (un PEP), bien qu'ils soient en train de le faire. - Néanmoins, il est déjà utilisé comme "standard" par plusieurs outils. Cela améliore grandement l'interopérabilité, puisque vous pouvez remplacer Uvicorn par n'importe quel autre serveur ASGI (comme Daphne ou Hypercorn), ou vous pouvez ajouter des outils compatibles ASGI, comme `python-socketio`. +Néanmoins, il est déjà utilisé comme "standard" par plusieurs outils. Cela améliore grandement l'interopérabilité, puisque vous pouvez remplacer Uvicorn par n'importe quel autre serveur ASGI (comme Daphne ou Hypercorn), ou vous pouvez ajouter des outils compatibles ASGI, comme `python-socketio`. + +/// + +/// check | **FastAPI** l'utilise pour -!!! check "**FastAPI** l'utilise pour" Gérer toutes les parties web de base. Ajouter des fonctionnalités par-dessus. - La classe `FastAPI` elle-même hérite directement de la classe `Starlette`. +La classe `FastAPI` elle-même hérite directement de la classe `Starlette`. - Ainsi, tout ce que vous pouvez faire avec Starlette, vous pouvez le faire directement avec **FastAPI**, car il s'agit en fait de Starlette sous stéroïdes. +Ainsi, tout ce que vous pouvez faire avec Starlette, vous pouvez le faire directement avec **FastAPI**, car il s'agit en fait de Starlette sous stéroïdes. + +/// ### Uvicorn @@ -434,12 +507,15 @@ quelque chose qu'un framework comme Starlette (ou **FastAPI**) fournirait par-de C'est le serveur recommandé pour Starlette et **FastAPI**. -!!! check "**FastAPI** le recommande comme" +/// check | **FastAPI** le recommande comme + Le serveur web principal pour exécuter les applications **FastAPI**. - Vous pouvez le combiner avec Gunicorn, pour avoir un serveur multi-processus asynchrone. +Vous pouvez le combiner avec Gunicorn, pour avoir un serveur multi-processus asynchrone. + +Pour plus de détails, consultez la section [Déploiement](deployment/index.md){.internal-link target=_blank}. - Pour plus de détails, consultez la section [Déploiement](deployment/index.md){.internal-link target=_blank}. +/// ## Benchmarks et vitesse diff --git a/docs/fr/docs/async.md b/docs/fr/docs/async.md index af4d6ca06..0ff5fa5d1 100644 --- a/docs/fr/docs/async.md +++ b/docs/fr/docs/async.md @@ -20,8 +20,11 @@ async def read_results(): return results ``` -!!! note - Vous pouvez uniquement utiliser `await` dans les fonctions créées avec `async def`. +/// note + +Vous pouvez uniquement utiliser `await` dans les fonctions créées avec `async def`. + +/// --- @@ -103,24 +106,44 @@ Pour expliquer la différence, voici une histoire de burgers : Vous amenez votre crush 😍 dans votre fast food 🍔 favori, et faites la queue pendant que le serveur 💁 prend les commandes des personnes devant vous. + + Puis vient votre tour, vous commandez alors 2 magnifiques burgers 🍔 pour votre crush 😍 et vous. -Vous payez 💸. + Le serveur 💁 dit quelque chose à son collègue dans la cuisine 👨‍🍳 pour qu'il sache qu'il doit préparer vos burgers 🍔 (bien qu'il soit déjà en train de préparer ceux des clients précédents). + + +Vous payez 💸. + Le serveur 💁 vous donne le numéro assigné à votre commande. + + Pendant que vous attendez, vous allez choisir une table avec votre crush 😍, vous discutez avec votre crush 😍 pendant un long moment (les burgers étant "magnifiques" ils sont très longs à préparer ✨🍔✨). Pendant que vous êtes assis à table, en attendant que les burgers 🍔 soient prêts, vous pouvez passer ce temps à admirer à quel point votre crush 😍 est géniale, mignonne et intelligente ✨😍✨. + + Pendant que vous discutez avec votre crush 😍, de temps en temps vous jetez un coup d'oeil au nombre affiché au-dessus du comptoir pour savoir si c'est à votre tour d'être servis. Jusqu'au moment où c'est (enfin) votre tour. Vous allez au comptoir, récupérez vos burgers 🍔 et revenez à votre table. + + Vous et votre crush 😍 mangez les burgers 🍔 et passez un bon moment ✨. + + +/// info + +Illustrations proposées par Ketrina Thompson. 🎨 + +/// + --- Imaginez que vous êtes l'ordinateur / le programme 🤖 dans cette histoire. @@ -149,26 +172,44 @@ Vous attendez pendant que plusieurs (disons 8) serveurs qui sont aussi des cuisi Chaque personne devant vous attend 🕙 que son burger 🍔 soit prêt avant de quitter le comptoir car chacun des 8 serveurs va lui-même préparer le burger directement avant de prendre la commande suivante. + + Puis c'est enfin votre tour, vous commandez 2 magnifiques burgers 🍔 pour vous et votre crush 😍. Vous payez 💸. + + Le serveur va dans la cuisine 👨‍🍳. Vous attendez devant le comptoir afin que personne ne prenne vos burgers 🍔 avant vous, vu qu'il n'y a pas de numéro de commande. + + Vous et votre crush 😍 étant occupés à vérifier que personne ne passe devant vous prendre vos burgers au moment où ils arriveront 🕙, vous ne pouvez pas vous préoccuper de votre crush 😞. C'est du travail "synchrone", vous être "synchronisés" avec le serveur/cuisinier 👨‍🍳. Vous devez attendre 🕙 et être présent au moment exact où le serveur/cuisinier 👨‍🍳 finira les burgers 🍔 et vous les donnera, sinon quelqu'un risque de vous les prendre. + + Puis le serveur/cuisinier 👨‍🍳 revient enfin avec vos burgers 🍔, après un long moment d'attente 🕙 devant le comptoir. + + Vous prenez vos burgers 🍔 et allez à une table avec votre crush 😍 Vous les mangez, et vous avez terminé 🍔 ⏹. + + Durant tout ce processus, il n'y a presque pas eu de discussions ou de flirts car la plupart de votre temps à été passé à attendre 🕙 devant le comptoir 😞. +/// info + +Illustrations proposées par Ketrina Thompson. 🎨 + +/// + --- Dans ce scénario de burgers parallèles, vous êtes un ordinateur / programme 🤖 avec deux processeurs (vous et votre crush 😍) attendant 🕙 à deux et dédiant votre attention 🕙 à "attendre devant le comptoir" pour une longue durée. @@ -352,12 +393,15 @@ Tout ceci est donc ce qui donne sa force à **FastAPI** (à travers Starlette) e ## Détails très techniques -!!! warning "Attention !" - Vous pouvez probablement ignorer cela. +/// warning | Attention ! + +Vous pouvez probablement ignorer cela. + +Ce sont des détails très poussés sur comment **FastAPI** fonctionne en arrière-plan. - Ce sont des détails très poussés sur comment **FastAPI** fonctionne en arrière-plan. +Si vous avez de bonnes connaissances techniques (coroutines, threads, code bloquant, etc.) et êtes curieux de comment **FastAPI** gère `async def` versus le `def` classique, cette partie est faite pour vous. - Si vous avez de bonnes connaissances techniques (coroutines, threads, code bloquant, etc.) et êtes curieux de comment **FastAPI** gère `async def` versus le `def` classique, cette partie est faite pour vous. +/// ### Fonctions de chemin @@ -365,7 +409,7 @@ Quand vous déclarez une *fonction de chemin* avec un `def` normal et non `async Si vous venez d'un autre framework asynchrone qui ne fonctionne pas comme de la façon décrite ci-dessus et que vous êtes habitués à définir des *fonctions de chemin* basiques avec un simple `def` pour un faible gain de performance (environ 100 nanosecondes), veuillez noter que dans **FastAPI**, l'effet serait plutôt contraire. Dans ces cas-là, il vaut mieux utiliser `async def` à moins que votre *fonction de chemin* utilise du code qui effectue des opérations I/O bloquantes. -Au final, dans les deux situations, il est fort probable que **FastAPI** soit tout de même [plus rapide](/#performance){.internal-link target=_blank} que (ou au moins de vitesse égale à) votre framework précédent. +Au final, dans les deux situations, il est fort probable que **FastAPI** soit tout de même [plus rapide](index.md#performance){.internal-link target=_blank} que (ou au moins de vitesse égale à) votre framework précédent. ### Dépendances diff --git a/docs/fr/docs/contributing.md b/docs/fr/docs/contributing.md deleted file mode 100644 index 8292f14bb..000000000 --- a/docs/fr/docs/contributing.md +++ /dev/null @@ -1,501 +0,0 @@ -# Développement - Contribuer - -Tout d'abord, vous voudrez peut-être voir les moyens de base pour [aider FastAPI et obtenir de l'aide](help-fastapi.md){.internal-link target=_blank}. - -## Développement - -Si vous avez déjà cloné le dépôt et que vous savez que vous devez vous plonger dans le code, voici quelques directives pour mettre en place votre environnement. - -### Environnement virtuel avec `venv` - -Vous pouvez créer un environnement virtuel dans un répertoire en utilisant le module `venv` de Python : - -
- -```console -$ python -m venv env -``` - -
- -Cela va créer un répertoire `./env/` avec les binaires Python et vous pourrez alors installer des paquets pour cet environnement isolé. - -### Activer l'environnement - -Activez le nouvel environnement avec : - -=== "Linux, macOS" - -
- - ```console - $ source ./env/bin/activate - ``` - -
- -=== "Windows PowerShell" - -
- - ```console - $ .\env\Scripts\Activate.ps1 - ``` - -
- -=== "Windows Bash" - - Ou si vous utilisez Bash pour Windows (par exemple Git Bash): - -
- - ```console - $ source ./env/Scripts/activate - ``` - -
- -Pour vérifier que cela a fonctionné, utilisez : - -=== "Linux, macOS, Windows Bash" - -
- - ```console - $ which pip - - some/directory/fastapi/env/bin/pip - ``` - -
- -=== "Windows PowerShell" - -
- - ```console - $ Get-Command pip - - some/directory/fastapi/env/bin/pip - ``` - -
- -Si celui-ci montre le binaire `pip` à `env/bin/pip`, alors ça a fonctionné. 🎉 - - - -!!! tip - Chaque fois que vous installez un nouveau paquet avec `pip` sous cet environnement, activez à nouveau l'environnement. - - Cela permet de s'assurer que si vous utilisez un programme terminal installé par ce paquet (comme `flit`), vous utilisez celui de votre environnement local et pas un autre qui pourrait être installé globalement. - -### Flit - -**FastAPI** utilise Flit pour build, packager et publier le projet. - -Après avoir activé l'environnement comme décrit ci-dessus, installez `flit` : - -
- -```console -$ pip install flit - ----> 100% -``` - -
- -Réactivez maintenant l'environnement pour vous assurer que vous utilisez le "flit" que vous venez d'installer (et non un environnement global). - -Et maintenant, utilisez `flit` pour installer les dépendances de développement : - -=== "Linux, macOS" - -
- - ```console - $ flit install --deps develop --symlink - - ---> 100% - ``` - -
- -=== "Windows" - - Si vous êtes sous Windows, utilisez `--pth-file` au lieu de `--symlink` : - -
- - ```console - $ flit install --deps develop --pth-file - - ---> 100% - ``` - -
- -Il installera toutes les dépendances et votre FastAPI local dans votre environnement local. - -#### Utiliser votre FastAPI local - -Si vous créez un fichier Python qui importe et utilise FastAPI, et que vous l'exécutez avec le Python de votre environnement local, il utilisera votre code source FastAPI local. - -Et si vous mettez à jour le code source local de FastAPI, tel qu'il est installé avec `--symlink` (ou `--pth-file` sous Windows), lorsque vous exécutez à nouveau ce fichier Python, il utilisera la nouvelle version de FastAPI que vous venez d'éditer. - -De cette façon, vous n'avez pas à "installer" votre version locale pour pouvoir tester chaque changement. - -### Formatage - -Il existe un script que vous pouvez exécuter qui formatera et nettoiera tout votre code : - -
- -```console -$ bash scripts/format.sh -``` - -
- -Il effectuera également un tri automatique de touts vos imports. - -Pour qu'il puisse les trier correctement, vous devez avoir FastAPI installé localement dans votre environnement, avec la commande dans la section ci-dessus en utilisant `--symlink` (ou `--pth-file` sous Windows). - -### Formatage des imports - -Il existe un autre script qui permet de formater touts les imports et de s'assurer que vous n'avez pas d'imports inutilisés : - -
- -```console -$ bash scripts/format-imports.sh -``` - -
- -Comme il exécute une commande après l'autre et modifie et inverse de nombreux fichiers, il prend un peu plus de temps à s'exécuter, il pourrait donc être plus facile d'utiliser fréquemment `scripts/format.sh` et `scripts/format-imports.sh` seulement avant de commit. - -## Documentation - -Tout d'abord, assurez-vous que vous configurez votre environnement comme décrit ci-dessus, qui installera toutes les exigences. - -La documentation utilise MkDocs. - -Et il y a des outils/scripts supplémentaires en place pour gérer les traductions dans `./scripts/docs.py`. - -!!! tip - Vous n'avez pas besoin de voir le code dans `./scripts/docs.py`, vous l'utilisez simplement dans la ligne de commande. - -Toute la documentation est au format Markdown dans le répertoire `./docs/fr/`. - -De nombreux tutoriels comportent des blocs de code. - -Dans la plupart des cas, ces blocs de code sont de véritables applications complètes qui peuvent être exécutées telles quelles. - -En fait, ces blocs de code ne sont pas écrits à l'intérieur du Markdown, ce sont des fichiers Python dans le répertoire `./docs_src/`. - -Et ces fichiers Python sont inclus/injectés dans la documentation lors de la génération du site. - -### Documentation pour les tests - -La plupart des tests sont en fait effectués par rapport aux exemples de fichiers sources dans la documentation. - -Cela permet de s'assurer que : - -* La documentation est à jour. -* Les exemples de documentation peuvent être exécutés tels quels. -* La plupart des fonctionnalités sont couvertes par la documentation, assurées par la couverture des tests. - -Au cours du développement local, un script build le site et vérifie les changements éventuels, puis il est rechargé en direct : - -
- -```console -$ python ./scripts/docs.py live - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -Il servira la documentation sur `http://127.0.0.1:8008`. - -De cette façon, vous pouvez modifier la documentation/les fichiers sources et voir les changements en direct. - -#### Typer CLI (facultatif) - -Les instructions ici vous montrent comment utiliser le script à `./scripts/docs.py` avec le programme `python` directement. - -Mais vous pouvez également utiliser Typer CLI, et vous obtiendrez l'auto-complétion dans votre terminal pour les commandes après l'achèvement de l'installation. - -Si vous installez Typer CLI, vous pouvez installer la complétion avec : - -
- -```console -$ typer --install-completion - -zsh completion installed in /home/user/.bashrc. -Completion will take effect once you restart the terminal. -``` - -
- -### Apps et documentation en même temps - -Si vous exécutez les exemples avec, par exemple : - -
- -```console -$ uvicorn tutorial001:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -Comme Uvicorn utilisera par défaut le port `8000`, la documentation sur le port `8008` n'entrera pas en conflit. - -### Traductions - -L'aide aux traductions est TRÈS appréciée ! Et cela ne peut se faire sans l'aide de la communauté. 🌎 🚀 - -Voici les étapes à suivre pour aider à la traduction. - -#### Conseils et lignes directrices - -* Vérifiez les pull requests existantes pour votre langue et ajouter des reviews demandant des changements ou les approuvant. - -!!! tip - Vous pouvez ajouter des commentaires avec des suggestions de changement aux pull requests existantes. - - Consultez les documents concernant l'ajout d'un review de pull request pour l'approuver ou demander des modifications. - -* Vérifiez dans issues pour voir s'il y a une personne qui coordonne les traductions pour votre langue. - -* Ajoutez une seule pull request par page traduite. Il sera ainsi beaucoup plus facile pour les autres de l'examiner. - -Pour les langues que je ne parle pas, je vais attendre plusieurs autres reviews de la traduction avant de merge. - -* Vous pouvez également vérifier s'il existe des traductions pour votre langue et y ajouter une review, ce qui m'aidera à savoir si la traduction est correcte et je pourrai la fusionner. - -* Utilisez les mêmes exemples en Python et ne traduisez que le texte des documents. Vous n'avez pas besoin de changer quoi que ce soit pour que cela fonctionne. - -* Utilisez les mêmes images, noms de fichiers et liens. Vous n'avez pas besoin de changer quoi que ce soit pour que cela fonctionne. - -* Pour vérifier le code à 2 lettres de la langue que vous souhaitez traduire, vous pouvez utiliser le tableau Liste des codes ISO 639-1. - -#### Langue existante - -Disons que vous voulez traduire une page pour une langue qui a déjà des traductions pour certaines pages, comme l'espagnol. - -Dans le cas de l'espagnol, le code à deux lettres est `es`. Ainsi, le répertoire des traductions espagnoles se trouve à l'adresse `docs/es/`. - -!!! tip - La langue principale ("officielle") est l'anglais, qui se trouve à l'adresse "docs/en/". - -Maintenant, lancez le serveur en live pour les documents en espagnol : - -
- -```console -// Use the command "live" and pass the language code as a CLI argument -$ python ./scripts/docs.py live es - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -Vous pouvez maintenant aller sur http://127.0.0.1:8008 et voir vos changements en direct. - -Si vous regardez le site web FastAPI docs, vous verrez que chaque langue a toutes les pages. Mais certaines pages ne sont pas traduites et sont accompagnées d'une notification concernant la traduction manquante. - -Mais si vous le gérez localement de cette manière, vous ne verrez que les pages déjà traduites. - -Disons maintenant que vous voulez ajouter une traduction pour la section [Features](features.md){.internal-link target=_blank}. - -* Copiez le fichier à : - -``` -docs/en/docs/features.md -``` - -* Collez-le exactement au même endroit mais pour la langue que vous voulez traduire, par exemple : - -``` -docs/es/docs/features.md -``` - -!!! tip - Notez que le seul changement dans le chemin et le nom du fichier est le code de langue, qui passe de `en` à `es`. - -* Ouvrez maintenant le fichier de configuration de MkDocs pour l'anglais à - -``` -docs/en/docs/mkdocs.yml -``` - -* Trouvez l'endroit où cette `docs/features.md` se trouve dans le fichier de configuration. Quelque part comme : - -```YAML hl_lines="8" -site_name: FastAPI -# More stuff -nav: -- FastAPI: index.md -- Languages: - - en: / - - es: /es/ -- features.md -``` - -* Ouvrez le fichier de configuration MkDocs pour la langue que vous éditez, par exemple : - -``` -docs/es/docs/mkdocs.yml -``` - -* Ajoutez-le à l'endroit exact où il se trouvait pour l'anglais, par exemple : - -```YAML hl_lines="8" -site_name: FastAPI -# More stuff -nav: -- FastAPI: index.md -- Languages: - - en: / - - es: /es/ -- features.md -``` - -Assurez-vous que s'il y a d'autres entrées, la nouvelle entrée avec votre traduction est exactement dans le même ordre que dans la version anglaise. - -Si vous allez sur votre navigateur, vous verrez que maintenant les documents montrent votre nouvelle section. 🎉 - -Vous pouvez maintenant tout traduire et voir à quoi cela ressemble au fur et à mesure que vous enregistrez le fichier. - -#### Nouvelle langue - -Disons que vous voulez ajouter des traductions pour une langue qui n'est pas encore traduite, pas même quelques pages. - -Disons que vous voulez ajouter des traductions pour le Créole, et que ce n'est pas encore dans les documents. - -En vérifiant le lien ci-dessus, le code pour "Créole" est `ht`. - -L'étape suivante consiste à exécuter le script pour générer un nouveau répertoire de traduction : - -
- -```console -// Use the command new-lang, pass the language code as a CLI argument -$ python ./scripts/docs.py new-lang ht - -Successfully initialized: docs/ht -Updating ht -Updating en -``` - -
- -Vous pouvez maintenant vérifier dans votre éditeur de code le répertoire nouvellement créé `docs/ht/`. - -!!! tip - Créez une première demande d'extraction à l'aide de cette fonction, afin de configurer la nouvelle langue avant d'ajouter des traductions. - - Ainsi, d'autres personnes peuvent vous aider à rédiger d'autres pages pendant que vous travaillez sur la première. 🚀 - -Commencez par traduire la page principale, `docs/ht/index.md`. - -Vous pouvez ensuite continuer avec les instructions précédentes, pour une "langue existante". - -##### Nouvelle langue non prise en charge - -Si, lors de l'exécution du script du serveur en direct, vous obtenez une erreur indiquant que la langue n'est pas prise en charge, quelque chose comme : - -``` - raise TemplateNotFound(template) -jinja2.exceptions.TemplateNotFound: partials/language/xx.html -``` - -Cela signifie que le thème ne supporte pas cette langue (dans ce cas, avec un faux code de 2 lettres de `xx`). - -Mais ne vous inquiétez pas, vous pouvez définir la langue du thème en anglais et ensuite traduire le contenu des documents. - -Si vous avez besoin de faire cela, modifiez le fichier `mkdocs.yml` pour votre nouvelle langue, il aura quelque chose comme : - -```YAML hl_lines="5" -site_name: FastAPI -# More stuff -theme: - # More stuff - language: xx -``` - -Changez cette langue de `xx` (de votre code de langue) à `fr`. - -Vous pouvez ensuite relancer le serveur live. - -#### Prévisualisez le résultat - -Lorsque vous utilisez le script à `./scripts/docs.py` avec la commande `live`, il n'affiche que les fichiers et les traductions disponibles pour la langue courante. - -Mais une fois que vous avez terminé, vous pouvez tester le tout comme il le ferait en ligne. - -Pour ce faire, il faut d'abord construire tous les documents : - -
- -```console -// Use the command "build-all", this will take a bit -$ python ./scripts/docs.py build-all - -Updating es -Updating en -Building docs for: en -Building docs for: es -Successfully built docs for: es -Copying en index.md to README.md -``` - -
- -Cela génère tous les documents à `./docs_build/` pour chaque langue. Cela inclut l'ajout de tout fichier dont la traduction est manquante, avec une note disant que "ce fichier n'a pas encore de traduction". Mais vous n'avez rien à faire avec ce répertoire. - -Ensuite, il construit tous ces sites MkDocs indépendants pour chaque langue, les combine, et génère le résultat final à `./site/`. - -Ensuite, vous pouvez servir cela avec le commandement `serve`: - -
- -```console -// Use the command "serve" after running "build-all" -$ python ./scripts/docs.py serve - -Warning: this is a very simple server. For development, use mkdocs serve instead. -This is here only to preview a site with translations already built. -Make sure you run the build-all command first. -Serving at: http://127.0.0.1:8008 -``` - -
- -## Tests - -Il existe un script que vous pouvez exécuter localement pour tester tout le code et générer des rapports de couverture en HTML : - -
- -```console -$ bash scripts/test-cov-html.sh -``` - -
- -Cette commande génère un répertoire `./htmlcov/`, si vous ouvrez le fichier `./htmlcov/index.html` dans votre navigateur, vous pouvez explorer interactivement les régions de code qui sont couvertes par les tests, et remarquer s'il y a une région manquante. diff --git a/docs/fr/docs/deployment/docker.md b/docs/fr/docs/deployment/docker.md index d2dcae722..05b597a2d 100644 --- a/docs/fr/docs/deployment/docker.md +++ b/docs/fr/docs/deployment/docker.md @@ -17,8 +17,11 @@ Cette image est dotée d'un mécanisme d'"auto-tuning", de sorte qu'il vous suff Mais vous pouvez toujours changer et mettre à jour toutes les configurations avec des variables d'environnement ou des fichiers de configuration. -!!! tip "Astuce" - Pour voir toutes les configurations et options, rendez-vous sur la page de l'image Docker : tiangolo/uvicorn-gunicorn-fastapi. +/// tip | Astuce + +Pour voir toutes les configurations et options, rendez-vous sur la page de l'image Docker : tiangolo/uvicorn-gunicorn-fastapi. + +/// ## Créer un `Dockerfile` diff --git a/docs/fr/docs/deployment/https.md b/docs/fr/docs/deployment/https.md index ccf1f847a..3f7068ff0 100644 --- a/docs/fr/docs/deployment/https.md +++ b/docs/fr/docs/deployment/https.md @@ -4,8 +4,11 @@ Il est facile de penser que HTTPS peut simplement être "activé" ou non. Mais c'est beaucoup plus complexe que cela. -!!! tip - Si vous êtes pressé ou si cela ne vous intéresse pas, passez aux sections suivantes pour obtenir des instructions étape par étape afin de tout configurer avec différentes techniques. +/// tip + +Si vous êtes pressé ou si cela ne vous intéresse pas, passez aux sections suivantes pour obtenir des instructions étape par étape afin de tout configurer avec différentes techniques. + +/// Pour apprendre les bases du HTTPS, du point de vue d'un utilisateur, consultez https://howhttps.works/. diff --git a/docs/fr/docs/deployment/manually.md b/docs/fr/docs/deployment/manually.md index c53e2db67..7c29242a9 100644 --- a/docs/fr/docs/deployment/manually.md +++ b/docs/fr/docs/deployment/manually.md @@ -5,7 +5,7 @@ La principale chose dont vous avez besoin pour exécuter une application **FastA Il existe 3 principales alternatives : * Uvicorn : un serveur ASGI haute performance. -* Hypercorn : un serveur +* Hypercorn : un serveur ASGI compatible avec HTTP/2 et Trio entre autres fonctionnalités. * Daphne : le serveur ASGI conçu pour Django Channels. @@ -25,75 +25,89 @@ Lorsqu'on se réfère à la machine distante, il est courant de l'appeler **serv Vous pouvez installer un serveur compatible ASGI avec : -=== "Uvicorn" +//// tab | Uvicorn - * Uvicorn, un serveur ASGI rapide comme l'éclair, basé sur uvloop et httptools. +* Uvicorn, un serveur ASGI rapide comme l'éclair, basé sur uvloop et httptools. -
+
+ +```console +$ pip install "uvicorn[standard]" - ```console - $ pip install "uvicorn[standard]" +---> 100% +``` + +
- ---> 100% - ``` +/// tip | Astuce -
+En ajoutant `standard`, Uvicorn va installer et utiliser quelques dépendances supplémentaires recommandées. - !!! tip "Astuce" - En ajoutant `standard`, Uvicorn va installer et utiliser quelques dépendances supplémentaires recommandées. +Cela inclut `uvloop`, le remplaçant performant de `asyncio`, qui fournit le gros gain de performance en matière de concurrence. - Cela inclut `uvloop`, le remplaçant performant de `asyncio`, qui fournit le gros gain de performance en matière de concurrence. +/// -=== "Hypercorn" +//// - * Hypercorn, un serveur ASGI également compatible avec HTTP/2. +//// tab | Hypercorn -
+* Hypercorn, un serveur ASGI également compatible avec HTTP/2. - ```console - $ pip install hypercorn +
+ +```console +$ pip install hypercorn + +---> 100% +``` - ---> 100% - ``` +
-
+...ou tout autre serveur ASGI. - ...ou tout autre serveur ASGI. +//// ## Exécutez le programme serveur Vous pouvez ensuite exécuter votre application de la même manière que vous l'avez fait dans les tutoriels, mais sans l'option `--reload`, par exemple : -=== "Uvicorn" +//// tab | Uvicorn -
+
- ```console - $ uvicorn main:app --host 0.0.0.0 --port 80 +```console +$ uvicorn main:app --host 0.0.0.0 --port 80 - INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) - ``` +INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) +``` -
+
+ +//// -=== "Hypercorn" +//// tab | Hypercorn -
+
+ +```console +$ hypercorn main:app --bind 0.0.0.0:80 + +Running on 0.0.0.0:8080 over http (CTRL + C to quit) +``` + +
- ```console - $ hypercorn main:app --bind 0.0.0.0:80 +//// - Running on 0.0.0.0:8080 over http (CTRL + C to quit) - ``` +/// warning -
+N'oubliez pas de supprimer l'option `--reload` si vous l'utilisiez. -!!! warning - N'oubliez pas de supprimer l'option `--reload` si vous l'utilisiez. + L'option `--reload` consomme beaucoup plus de ressources, est plus instable, etc. - L'option `--reload` consomme beaucoup plus de ressources, est plus instable, etc. + Cela aide beaucoup pendant le **développement**, mais vous **ne devriez pas** l'utiliser en **production**. - Cela aide beaucoup pendant le **développement**, mais vous **ne devriez pas** l'utiliser en **production**. +/// ## Hypercorn avec Trio diff --git a/docs/fr/docs/deployment/versions.md b/docs/fr/docs/deployment/versions.md index 136165e9d..9d84274e2 100644 --- a/docs/fr/docs/deployment/versions.md +++ b/docs/fr/docs/deployment/versions.md @@ -48,8 +48,11 @@ des changements non rétrocompatibles. FastAPI suit également la convention que tout changement de version "PATCH" est pour des corrections de bogues et des changements rétrocompatibles. -!!! tip "Astuce" - Le "PATCH" est le dernier chiffre, par exemple, dans `0.2.3`, la version PATCH est `3`. +/// tip | Astuce + +Le "PATCH" est le dernier chiffre, par exemple, dans `0.2.3`, la version PATCH est `3`. + +/// Donc, vous devriez être capable d'épingler une version comme suit : @@ -59,8 +62,11 @@ fastapi>=0.45.0,<0.46.0 Les changements non rétrocompatibles et les nouvelles fonctionnalités sont ajoutés dans les versions "MINOR". -!!! tip "Astuce" - Le "MINOR" est le numéro au milieu, par exemple, dans `0.2.3`, la version MINOR est `2`. +/// tip | Astuce + +Le "MINOR" est le numéro au milieu, par exemple, dans `0.2.3`, la version MINOR est `2`. + +/// ## Mise à jour des versions FastAPI diff --git a/docs/fr/docs/external-links.md b/docs/fr/docs/external-links.md deleted file mode 100644 index 37b8c5b13..000000000 --- a/docs/fr/docs/external-links.md +++ /dev/null @@ -1,33 +0,0 @@ -# Articles et liens externes - -**FastAPI** possède une grande communauté en constante extension. - -Il existe de nombreux articles, outils et projets liés à **FastAPI**. - -Voici une liste incomplète de certains d'entre eux. - -!!! tip "Astuce" - Si vous avez un article, projet, outil, ou quoi que ce soit lié à **FastAPI** qui n'est actuellement pas listé ici, créez une Pull Request l'ajoutant. - -{% for section_name, section_content in external_links.items() %} - -## {{ section_name }} - -{% for lang_name, lang_content in section_content.items() %} - -### {{ lang_name }} - -{% for item in lang_content %} - -* {{ item.title }} by {{ item.author }}. - -{% endfor %} -{% endfor %} -{% endfor %} - -## Projets - -Les projets Github avec le topic `fastapi` les plus récents : - -
-
diff --git a/docs/fr/docs/fastapi-people.md b/docs/fr/docs/fastapi-people.md deleted file mode 100644 index 945f0794e..000000000 --- a/docs/fr/docs/fastapi-people.md +++ /dev/null @@ -1,175 +0,0 @@ -# La communauté FastAPI - -FastAPI a une communauté extraordinaire qui accueille des personnes de tous horizons. - -## Créateur - Mainteneur - -Salut! 👋 - -C'est moi : - -{% if people %} -
-{% for user in people.maintainers %} - -
@{{ user.login }}
Réponses: {{ user.answers }}
Pull Requests: {{ user.prs }}
-{% endfor %} - -
-{% endif %} - -Je suis le créateur et le responsable de **FastAPI**. Vous pouvez en lire plus à ce sujet dans [Aide FastAPI - Obtenir de l'aide - Se rapprocher de l'auteur](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. - -...Mais ici, je veux vous montrer la communauté. - ---- - -**FastAPI** reçoit beaucoup de soutien de la part de la communauté. Et je tiens à souligner leurs contributions. - -Ce sont ces personnes qui : - -* [Aident les autres à résoudre des problèmes (questions) dans GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}. -* [Créent des Pull Requests](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. -* Review les Pull Requests, [particulièrement important pour les traductions](contributing.md#translations){.internal-link target=_blank}. - -Une salve d'applaudissements pour eux. 👏 🙇 - -## Utilisateurs les plus actifs le mois dernier - -Ce sont les utilisateurs qui ont [aidé le plus les autres avec des problèmes (questions) dans GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank} au cours du dernier mois. ☕ - -{% if people %} -
-{% for user in people.last_month_active %} - -
@{{ user.login }}
Questions répondues: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Experts - -Voici les **Experts FastAPI**. 🤓 - -Ce sont les utilisateurs qui ont [aidé le plus les autres avec des problèmes (questions) dans GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank} depuis *toujours*. - -Ils ont prouvé qu'ils étaient des experts en aidant beaucoup d'autres personnes. ✨ - -{% if people %} -
-{% for user in people.experts %} - -
@{{ user.login }}
Questions répondues: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Principaux contributeurs - -Ces utilisateurs sont les **Principaux contributeurs**. 👷 - -Ces utilisateurs ont [créé le plus grand nombre de demandes Pull Request](help-fastapi.md#create-a-pull-request){.internal-link target=_blank} qui ont été *merged*. - -Ils ont contribué au code source, à la documentation, aux traductions, etc. 📦 - -{% if people %} -
-{% for user in people.top_contributors %} - -
@{{ user.login }}
Pull Requests: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -Il existe de nombreux autres contributeurs (plus d'une centaine), vous pouvez les voir tous dans la Page des contributeurs de FastAPI GitHub. 👷 - -## Principaux Reviewers - -Ces utilisateurs sont les **Principaux Reviewers**. 🕵️ - -### Reviewers des traductions - -Je ne parle que quelques langues (et pas très bien 😅). Ainsi, les reviewers sont ceux qui ont le [**pouvoir d'approuver les traductions**](contributing.md#translations){.internal-link target=_blank} de la documentation. Sans eux, il n'y aurait pas de documentation dans plusieurs autres langues. - ---- - -Les **Principaux Reviewers** 🕵️ ont examiné le plus grand nombre de demandes Pull Request des autres, assurant la qualité du code, de la documentation, et surtout, des **traductions**. - -{% if people %} -
-{% for user in people.top_reviewers %} - -
@{{ user.login }}
Reviews: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Sponsors - -Ce sont les **Sponsors**. 😎 - -Ils soutiennent mon travail avec **FastAPI** (et d'autres) avec GitHub Sponsors. - -{% if sponsors %} - -{% if sponsors.gold %} - -### Gold Sponsors - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Silver Sponsors - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Bronze Sponsors - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -{% endif %} -### Individual Sponsors - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
- -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
- -{% endfor %} -{% endif %} - -## À propos des données - détails techniques - -L'intention de cette page est de souligner l'effort de la communauté pour aider les autres. - -Notamment en incluant des efforts qui sont normalement moins visibles, et, dans de nombreux cas, plus difficile, comme aider d'autres personnes à résoudre des problèmes et examiner les Pull Requests de traduction. - -Les données sont calculées chaque mois, vous pouvez lire le code source ici. - -Je me réserve également le droit de mettre à jour l'algorithme, les sections, les seuils, etc. (juste au cas où 🤷). diff --git a/docs/fr/docs/features.md b/docs/fr/docs/features.md index 0c1f6269a..afb1de243 100644 --- a/docs/fr/docs/features.md +++ b/docs/fr/docs/features.md @@ -62,10 +62,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` signifie: +/// info - Utilise les clés et valeurs du dictionnaire `second_user_data` directement comme des arguments clé-valeur. C'est équivalent à: `User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` signifie: + +Utilise les clés et valeurs du dictionnaire `second_user_data` directement comme des arguments clé-valeur. C'est équivalent à: `User(id=4, name="Mary", joined="2018-11-30")` + +/// ### Support d'éditeurs @@ -174,7 +177,7 @@ Avec **FastAPI** vous aurez toutes les fonctionnalités de **Starlette** (FastAP ## Fonctionnalités de Pydantic -**FastAPI** est totalement compatible avec (et basé sur) Pydantic. Le code utilisant Pydantic que vous ajouterez fonctionnera donc aussi. +**FastAPI** est totalement compatible avec (et basé sur) Pydantic. Le code utilisant Pydantic que vous ajouterez fonctionnera donc aussi. Inclus des librairies externes basées, aussi, sur Pydantic, servent d'ORMs, ODMs pour les bases de données. @@ -189,8 +192,6 @@ Avec **FastAPI** vous aurez toutes les fonctionnalités de **Pydantic** (comme * Si vous connaissez le typage en python vous savez comment utiliser Pydantic. * Aide votre **IDE/linter/cerveau**: * Parce que les structures de données de pydantic consistent seulement en une instance de classe que vous définissez; l'auto-complétion, le linting, mypy et votre intuition devrait être largement suffisante pour valider vos données. -* **Rapide**: - * Dans les benchmarks Pydantic est plus rapide que toutes les autres librairies testées. * Valide les **structures complexes**: * Utilise les modèles hiérarchique de Pydantic, le `typage` Python pour les `Lists`, `Dict`, etc. * Et les validateurs permettent aux schémas de données complexes d'être clairement et facilement définis, validés et documentés sous forme d'un schéma JSON. diff --git a/docs/fr/docs/help-fastapi.md b/docs/fr/docs/help-fastapi.md index 525c699f5..a365a8d3a 100644 --- a/docs/fr/docs/help-fastapi.md +++ b/docs/fr/docs/help-fastapi.md @@ -12,13 +12,13 @@ Il existe également plusieurs façons d'obtenir de l'aide. ## Star **FastAPI** sur GitHub -Vous pouvez "star" FastAPI dans GitHub (en cliquant sur le bouton étoile en haut à droite) : https://github.com/tiangolo/fastapi. ⭐️ +Vous pouvez "star" FastAPI dans GitHub (en cliquant sur le bouton étoile en haut à droite) : https://github.com/fastapi/fastapi. ⭐️ En ajoutant une étoile, les autres utilisateurs pourront la trouver plus facilement et constater qu'elle a déjà été utile à d'autres. ## Watch le dépôt GitHub pour les releases -Vous pouvez "watch" FastAPI dans GitHub (en cliquant sur le bouton "watch" en haut à droite) : https://github.com/tiangolo/fastapi. 👀 +Vous pouvez "watch" FastAPI dans GitHub (en cliquant sur le bouton "watch" en haut à droite) : https://github.com/fastapi/fastapi. 👀 Vous pouvez y sélectionner "Releases only". @@ -44,7 +44,7 @@ Vous pouvez : ## Tweeter sur **FastAPI** -Tweetez à propos de **FastAPI** et faites-moi savoir, ainsi qu'aux autres, pourquoi vous aimez ça. 🎉 +Tweetez à propos de **FastAPI** et faites-moi savoir, ainsi qu'aux autres, pourquoi vous aimez ça. 🎉 J'aime entendre parler de l'utilisation du **FastAPI**, de ce que vous avez aimé dedans, dans quel projet/entreprise l'utilisez-vous, etc. @@ -56,11 +56,11 @@ J'aime entendre parler de l'utilisation du **FastAPI**, de ce que vous avez aim ## Aider les autres à résoudre les problèmes dans GitHub -Vous pouvez voir les problèmes existants et essayer d'aider les autres, la plupart du temps il s'agit de questions dont vous connaissez peut-être déjà la réponse. 🤓 +Vous pouvez voir les problèmes existants et essayer d'aider les autres, la plupart du temps il s'agit de questions dont vous connaissez peut-être déjà la réponse. 🤓 ## Watch le dépôt GitHub -Vous pouvez "watch" FastAPI dans GitHub (en cliquant sur le bouton "watch" en haut à droite) : https://github.com/tiangolo/fastapi. 👀 +Vous pouvez "watch" FastAPI dans GitHub (en cliquant sur le bouton "watch" en haut à droite) : https://github.com/fastapi/fastapi. 👀 Si vous sélectionnez "Watching" au lieu de "Releases only", vous recevrez des notifications lorsque quelqu'un crée une nouvelle Issue. @@ -68,7 +68,7 @@ Vous pouvez alors essayer de les aider à résoudre ces problèmes. ## Créer une Issue -Vous pouvez créer une Issue dans le dépôt GitHub, par exemple pour : +Vous pouvez créer une Issue dans le dépôt GitHub, par exemple pour : * Poser une question ou s'informer sur un problème. * Suggérer une nouvelle fonctionnalité. @@ -77,7 +77,7 @@ Vous pouvez créer une Pull Request, par exemple : +Vous pouvez créer une Pull Request, par exemple : * Pour corriger une faute de frappe que vous avez trouvée sur la documentation. * Proposer de nouvelles sections de documentation. diff --git a/docs/fr/docs/history-design-future.md b/docs/fr/docs/history-design-future.md index b77664be6..6b26dd079 100644 --- a/docs/fr/docs/history-design-future.md +++ b/docs/fr/docs/history-design-future.md @@ -1,6 +1,6 @@ # Histoire, conception et avenir -Il y a quelque temps, un utilisateur de **FastAPI** a demandé : +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 [...]. @@ -54,7 +54,7 @@ Le tout de manière à offrir la meilleure expérience de développement à tous ## Exigences -Après avoir testé plusieurs alternatives, j'ai décidé que j'allais utiliser **Pydantic** pour ses avantages. +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. diff --git a/docs/fr/docs/index.md b/docs/fr/docs/index.md index f732fc74c..d25f7a939 100644 --- a/docs/fr/docs/index.md +++ b/docs/fr/docs/index.md @@ -1,3 +1,9 @@ +# FastAPI + + +

FastAPI

@@ -5,11 +11,11 @@ Framework FastAPI, haute performance, facile à apprendre, rapide à coder, prêt pour la production

- - Test + + Test - - Coverage + + Coverage Package version @@ -23,11 +29,11 @@ **Documentation** : https://fastapi.tiangolo.com -**Code Source** : https://github.com/tiangolo/fastapi +**Code Source** : https://github.com/fastapi/fastapi --- -FastAPI est un framework web moderne et rapide (haute performance) pour la création d'API avec Python 3.8+, basé sur les annotations de type standard de Python. +FastAPI est un framework web moderne et rapide (haute performance) pour la création d'API avec Python, basé sur les annotations de type standard de Python. Les principales fonctionnalités sont : @@ -63,7 +69,7 @@ Les principales fonctionnalités sont : "_[...] J'utilise beaucoup **FastAPI** ces derniers temps. [...] Je prévois de l'utiliser dans mon équipe pour tous les **services de ML chez Microsoft**. Certains d'entre eux seront intégrés dans le coeur de **Windows** et dans certains produits **Office**._" -

Kabir Khan - Microsoft (ref)
+
Kabir Khan - Microsoft (ref)
--- @@ -87,7 +93,7 @@ Les principales fonctionnalités sont : "_Honnêtement, ce que vous avez construit a l'air super solide et élégant. A bien des égards, c'est comme ça que je voulais que **Hug** soit - c'est vraiment inspirant de voir quelqu'un construire ça._" -
Timothy Crosley - Créateur de Hug (ref)
+
Timothy Crosley - Créateur de Hug (ref)
--- @@ -115,12 +121,10 @@ Si vous souhaitez construire une application Starlette pour les parties web. -* Pydantic pour les parties données. +* Pydantic pour les parties données. ## Installation @@ -331,7 +335,7 @@ Vous faites cela avec les types Python standard modernes. Vous n'avez pas à apprendre une nouvelle syntaxe, les méthodes ou les classes d'une bibliothèque spécifique, etc. -Juste du **Python 3.8+** standard. +Juste du **Python** standard. Par exemple, pour un `int`: @@ -445,21 +449,21 @@ Pour en savoir plus, consultez la section email_validator - pour la validation des adresses email. +* email-validator - pour la validation des adresses email. Utilisées par Starlette : * requests - Obligatoire si vous souhaitez utiliser `TestClient`. * jinja2 - Obligatoire si vous souhaitez utiliser la configuration de template par défaut. -* python-multipart - Obligatoire si vous souhaitez supporter le "décodage" de formulaire avec `request.form()`. +* python-multipart - Obligatoire si vous souhaitez supporter le "décodage" de formulaire avec `request.form()`. * itsdangerous - Obligatoire pour la prise en charge de `SessionMiddleware`. * pyyaml - Obligatoire pour le support `SchemaGenerator` de Starlette (vous n'en avez probablement pas besoin avec FastAPI). -* ujson - Obligatoire si vous souhaitez utiliser `UJSONResponse`. Utilisées par FastAPI / Starlette : * uvicorn - Pour le serveur qui charge et sert votre application. * orjson - Obligatoire si vous voulez utiliser `ORJSONResponse`. +* ujson - Obligatoire si vous souhaitez utiliser `UJSONResponse`. Vous pouvez tout installer avec `pip install fastapi[all]`. diff --git a/docs/fr/docs/learn/index.md b/docs/fr/docs/learn/index.md new file mode 100644 index 000000000..46fc095dc --- /dev/null +++ b/docs/fr/docs/learn/index.md @@ -0,0 +1,5 @@ +# Apprendre + +Voici les sections introductives et les tutoriels pour apprendre **FastAPI**. + +Vous pouvez considérer ceci comme un **manuel**, un **cours**, la **méthode officielle** et recommandée pour appréhender FastAPI. 😎 diff --git a/docs/fr/docs/project-generation.md b/docs/fr/docs/project-generation.md index c58d2cd2b..4c04dc167 100644 --- a/docs/fr/docs/project-generation.md +++ b/docs/fr/docs/project-generation.md @@ -14,7 +14,7 @@ GitHub : Swarm * Intégration **Docker Compose** et optimisation pour développement local. * Serveur web Python **prêt au déploiement** utilisant Uvicorn et Gunicorn. -* Backend Python **FastAPI** : +* Backend Python **FastAPI** : * **Rapide** : Très hautes performances, comparables à **NodeJS** ou **Go** (grâce à Starlette et Pydantic). * **Intuitif** : Excellent support des éditeurs. Complétion partout. Moins de temps passé à déboguer. * **Facile** : Fait pour être facile à utiliser et apprendre. Moins de temps passé à lire de la documentation. diff --git a/docs/fr/docs/python-types.md b/docs/fr/docs/python-types.md index f49fbafd3..99ca90827 100644 --- a/docs/fr/docs/python-types.md +++ b/docs/fr/docs/python-types.md @@ -13,16 +13,17 @@ Seulement le minimum nécessaire pour les utiliser avec **FastAPI** sera couvert Mais même si vous n'utilisez pas ou n'utiliserez jamais **FastAPI**, vous pourriez bénéficier d'apprendre quelques choses sur ces dernières. -!!! note - Si vous êtes un expert Python, et que vous savez déjà **tout** sur les annotations de type, passez au chapitre suivant. +/// note + +Si vous êtes un expert Python, et que vous savez déjà **tout** sur les annotations de type, passez au chapitre suivant. + +/// ## Motivations Prenons un exemple simple : -```Python -{!../../../docs_src/python_types/tutorial001.py!} -``` +{*../../docs_src/python_types/tutorial001.py*} Exécuter ce programe affiche : @@ -36,9 +37,7 @@ La fonction : * Convertit la première lettre de chaque paramètre en majuscules grâce à `title()`. * Concatène les résultats avec un espace entre les deux. -```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} -``` +{*../../docs_src/python_types/tutorial001.py hl[2] *} ### Limitations @@ -81,9 +80,7 @@ C'est tout. Ce sont des annotations de types : -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} -``` +{*../../docs_src/python_types/tutorial002.py hl[1] *} À ne pas confondre avec la déclaration de valeurs par défaut comme ici : @@ -111,9 +108,7 @@ Vous pouvez donc dérouler les options jusqu'à trouver la méthode à laquelle Cette fonction possède déjà des annotations de type : -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} -``` +{*../../docs_src/python_types/tutorial003.py hl[1] *} Comme l'éditeur connaît le type des variables, vous n'avez pas seulement l'auto-complétion, mais aussi de la détection d'erreurs : @@ -121,9 +116,7 @@ Comme l'éditeur connaît le type des variables, vous n'avez pas seulement l'aut Maintenant que vous avez connaissance du problème, convertissez `age` en chaîne de caractères grâce à `str(age)` : -```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} -``` +{*../../docs_src/python_types/tutorial004.py hl[2] *} ## Déclarer des types @@ -142,9 +135,7 @@ Comme par exemple : * `bool` * `bytes` -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} -``` +{*../../docs_src/python_types/tutorial005.py hl[1] *} ### Types génériques avec des paramètres de types @@ -160,9 +151,7 @@ Par exemple, définissons une variable comme `list` de `str`. Importez `List` (avec un `L` majuscule) depuis `typing`. -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial006.py!} -``` +{*../../docs_src/python_types/tutorial006.py hl[1] *} Déclarez la variable, en utilisant la syntaxe des deux-points (`:`). @@ -170,14 +159,15 @@ Et comme type, mettez `List`. Les listes étant un type contenant des types internes, mettez ces derniers entre crochets (`[`, `]`) : -```Python hl_lines="4" -{!../../../docs_src/python_types/tutorial006.py!} -``` +{*../../docs_src/python_types/tutorial006.py hl[4] *} + +/// tip | Astuce + +Ces types internes entre crochets sont appelés des "paramètres de type". -!!! tip "Astuce" - Ces types internes entre crochets sont appelés des "paramètres de type". +Ici, `str` est un paramètre de type passé à `List`. - Ici, `str` est un paramètre de type passé à `List`. +/// Ce qui signifie : "la variable `items` est une `list`, et chacun de ses éléments a pour type `str`. @@ -195,9 +185,7 @@ Et pourtant, l'éditeur sait qu'elle est de type `str` et pourra donc vous aider C'est le même fonctionnement pour déclarer un `tuple` ou un `set` : -```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial007.py!} -``` +{*../../docs_src/python_types/tutorial007.py hl[1,4] *} Dans cet exemple : @@ -210,9 +198,7 @@ Pour définir un `dict`, il faut lui passer 2 paramètres, séparés par une vir Le premier paramètre de type est pour les clés et le second pour les valeurs du dictionnaire (`dict`). -```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial008.py!} -``` +{*../../docs_src/python_types/tutorial008.py hl[1,4] *} Dans cet exemple : @@ -224,9 +210,7 @@ Dans cet exemple : Vous pouvez aussi utiliser `Optional` pour déclarer qu'une variable a un type, comme `str` mais qu'il est "optionnel" signifiant qu'il pourrait aussi être `None`. -```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} -``` +{*../../docs_src/python_types/tutorial009.py hl[1,4] *} Utiliser `Optional[str]` plutôt que `str` permettra à l'éditeur de vous aider à détecter les erreurs où vous supposeriez qu'une valeur est toujours de type `str`, alors qu'elle pourrait aussi être `None`. @@ -249,15 +233,12 @@ Vous pouvez aussi déclarer une classe comme type d'une variable. Disons que vous avez une classe `Person`, avec une variable `name` : -```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} -``` +{*../../docs_src/python_types/tutorial010.py hl[1:3] *} + Vous pouvez ensuite déclarer une variable de type `Person` : -```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} -``` +{*../../docs_src/python_types/tutorial010.py hl[6] *} Et vous aurez accès, encore une fois, au support complet offert par l'éditeur : @@ -265,7 +246,7 @@ Et vous aurez accès, encore une fois, au support complet offert par l'éditeur ## Les modèles Pydantic -Pydantic est une bibliothèque Python pour effectuer de la validation de données. +Pydantic est une bibliothèque Python pour effectuer de la validation de données. Vous déclarez la forme de la donnée avec des classes et des attributs. @@ -277,12 +258,13 @@ Ainsi, votre éditeur vous offrira un support adapté pour l'objet résultant. Extrait de la documentation officielle de **Pydantic** : -```Python -{!../../../docs_src/python_types/tutorial011.py!} -``` +{*../../docs_src/python_types/tutorial011.py*} + +/// info -!!! info - Pour en savoir plus à propos de Pydantic, allez jeter un coup d'oeil à sa documentation. +Pour en savoir plus à propos de Pydantic, allez jeter un coup d'oeil à sa documentation. + +/// **FastAPI** est basé entièrement sur **Pydantic**. @@ -310,5 +292,8 @@ Tout cela peut paraître bien abstrait, mais ne vous inquiétez pas, vous verrez Ce qu'il faut retenir c'est qu'en utilisant les types standard de Python, à un seul endroit (plutôt que d'ajouter plus de classes, de décorateurs, etc.), **FastAPI** fera une grande partie du travail pour vous. -!!! info - Si vous avez déjà lu le tutoriel et êtes revenus ici pour voir plus sur les types, une bonne ressource est la "cheat sheet" de `mypy`. +/// info + +Si vous avez déjà lu le tutoriel et êtes revenus ici pour voir plus sur les types, une bonne ressource est la "cheat sheet" de `mypy`. + +/// diff --git a/docs/fr/docs/tutorial/background-tasks.md b/docs/fr/docs/tutorial/background-tasks.md index f7cf1a6cc..2065ca58e 100644 --- a/docs/fr/docs/tutorial/background-tasks.md +++ b/docs/fr/docs/tutorial/background-tasks.md @@ -16,9 +16,7 @@ Cela comprend, par exemple : Pour commencer, importez `BackgroundTasks` et définissez un paramètre dans votre *fonction de chemin* avec `BackgroundTasks` comme type déclaré. -```Python hl_lines="1 13" -{!../../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *} **FastAPI** créera l'objet de type `BackgroundTasks` pour vous et le passera comme paramètre. @@ -32,18 +30,14 @@ Dans cet exemple, la fonction de tâche écrira dans un fichier (afin de simuler L'opération d'écriture n'utilisant ni `async` ni `await`, on définit la fonction avec un `def` normal. -```Python hl_lines="6-9" -{!../../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *} ## Ajouter une tâche d'arrière-plan Dans votre *fonction de chemin*, passez votre fonction de tâche à l'objet de type `BackgroundTasks` (`background_tasks` ici) grâce à la méthode `.add_task()` : -```Python hl_lines="14" -{!../../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[14] *} `.add_task()` reçoit comme arguments : @@ -57,9 +51,7 @@ Utiliser `BackgroundTasks` fonctionne aussi avec le système d'injection de dép **FastAPI** sait quoi faire dans chaque cas et comment réutiliser le même objet, afin que tous les paramètres de type `BackgroundTasks` soient fusionnés et que les tâches soient exécutées en arrière-plan : -```Python hl_lines="13 15 22 25" -{!../../../docs_src/background_tasks/tutorial002.py!} -``` +{* ../../docs_src/background_tasks/tutorial002.py hl[13,15,22,25] *} Dans cet exemple, les messages seront écrits dans le fichier `log.txt` après que la réponse soit envoyée. @@ -85,8 +77,6 @@ Si vous avez besoin de réaliser des traitements lourds en tâche d'arrière-pla Ces outils nécessitent généralement des configurations plus complexes ainsi qu'un gestionnaire de queue de message, comme RabbitMQ ou Redis, mais ils permettent d'exécuter des tâches d'arrière-plan dans différents process, et potentiellement, sur plusieurs serveurs. -Pour voir un exemple, allez voir les [Générateurs de projets](../project-generation.md){.internal-link target=_blank}, ils incluent tous Celery déjà configuré. - Mais si vous avez besoin d'accéder aux variables et objets de la même application **FastAPI**, ou si vous avez besoin d'effectuer de petites tâches d'arrière-plan (comme envoyer des notifications par email), vous pouvez simplement vous contenter d'utiliser `BackgroundTasks`. ## Résumé diff --git a/docs/fr/docs/tutorial/body-multiple-params.md b/docs/fr/docs/tutorial/body-multiple-params.md new file mode 100644 index 000000000..0541acc74 --- /dev/null +++ b/docs/fr/docs/tutorial/body-multiple-params.md @@ -0,0 +1,171 @@ +# Body - Paramètres multiples + +Maintenant que nous avons vu comment manipuler `Path` et `Query`, voyons comment faire pour le corps d'une requête, communément désigné par le terme anglais "body". + +## Mélanger les paramètres `Path`, `Query` et body + +Tout d'abord, sachez que vous pouvez mélanger les déclarations des paramètres `Path`, `Query` et body, **FastAPI** saura quoi faire. + +Vous pouvez également déclarer des paramètres body comme étant optionnels, en leur assignant une valeur par défaut à `None` : + +{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *} + +/// note + +Notez que, dans ce cas, le paramètre `item` provenant du `Body` est optionnel (sa valeur par défaut est `None`). + +/// + +## Paramètres multiples du body + +Dans l'exemple précédent, les opérations de routage attendaient un body JSON avec les attributs d'un `Item`, par exemple : + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +Mais vous pouvez également déclarer plusieurs paramètres provenant de body, par exemple `item` et `user` simultanément : + +{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *} + +Dans ce cas, **FastAPI** détectera qu'il y a plus d'un paramètre dans le body (chacun correspondant à un modèle Pydantic). + +Il utilisera alors les noms des paramètres comme clés, et s'attendra à recevoir quelque chose de semblable à : + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + } +} +``` + +/// note + +"Notez que, bien que nous ayons déclaré le paramètre `item` de la même manière que précédemment, il est maintenant associé à la clé `item` dans le corps de la requête."`. + +/// + +**FastAPI** effectue la conversion de la requête de façon transparente, de sorte que les objets `item` et `user` se trouvent correctement définis. + +Il effectue également la validation des données (même imbriquées les unes dans les autres), et permet de les documenter correctement (schéma OpenAPI et documentation auto-générée). + +## Valeurs scalaires dans le body + +De la même façon qu'il existe `Query` et `Path` pour définir des données supplémentaires pour les paramètres query et path, **FastAPI** fournit un équivalent `Body`. + +Par exemple, en étendant le modèle précédent, vous pouvez vouloir ajouter un paramètre `importance` dans le même body, en plus des paramètres `item` et `user`. + +Si vous le déclarez tel quel, comme c'est une valeur [scalaire](https://docs.github.com/fr/graphql/reference/scalars), **FastAPI** supposera qu'il s'agit d'un paramètre de requête (`Query`). + +Mais vous pouvez indiquer à **FastAPI** de la traiter comme une variable de body en utilisant `Body` : + +{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *} + +Dans ce cas, **FastAPI** s'attendra à un body semblable à : + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + }, + "importance": 5 +} +``` + +Encore une fois, cela convertira les types de données, les validera, permettra de générer la documentation, etc... + +## Paramètres multiples body et query + +Bien entendu, vous pouvez déclarer autant de paramètres que vous le souhaitez, en plus des paramètres body déjà déclarés. + +Par défaut, les valeurs [scalaires](https://docs.github.com/fr/graphql/reference/scalars) sont interprétées comme des paramètres query, donc inutile d'ajouter explicitement `Query`. Vous pouvez juste écrire : + +```Python +q: Union[str, None] = None +``` + +Ou bien, en Python 3.10 et supérieur : + +```Python +q: str | None = None +``` + +Par exemple : + +{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[27] *} + +/// info + +`Body` possède les mêmes paramètres de validation additionnels et de gestion des métadonnées que `Query` et `Path`, ainsi que d'autres que nous verrons plus tard. + +/// + +## Inclure un paramètre imbriqué dans le body + +Disons que vous avez seulement un paramètre `item` dans le body, correspondant à un modèle Pydantic `Item`. + +Par défaut, **FastAPI** attendra sa déclaration directement dans le body. + +Cependant, si vous souhaitez qu'il interprête correctement un JSON avec une clé `item` associée au contenu du modèle, comme cela serait le cas si vous déclariez des paramètres body additionnels, vous pouvez utiliser le paramètre spécial `embed` de `Body` : + +```Python +item: Item = Body(embed=True) +``` + +Voici un exemple complet : + +{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *} + +Dans ce cas **FastAPI** attendra un body semblable à : + +```JSON hl_lines="2" +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + } +} +``` + +au lieu de : + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +## Pour résumer + +Vous pouvez ajouter plusieurs paramètres body dans votre fonction de routage, même si une requête ne peut avoir qu'un seul body. + +Cependant, **FastAPI** se chargera de faire opérer sa magie, afin de toujours fournir à votre fonction des données correctes, les validera et documentera le schéma associé. + +Vous pouvez également déclarer des valeurs [scalaires](https://docs.github.com/fr/graphql/reference/scalars) à recevoir dans le body. + +Et vous pouvez indiquer à **FastAPI** d'inclure le body dans une autre variable, même lorsqu'un seul paramètre est déclaré. diff --git a/docs/fr/docs/tutorial/body.md b/docs/fr/docs/tutorial/body.md index 89720c973..760b6d80a 100644 --- a/docs/fr/docs/tutorial/body.md +++ b/docs/fr/docs/tutorial/body.md @@ -6,22 +6,23 @@ Le corps d'une **requête** est de la donnée envoyée par le client à votre AP Votre API aura presque toujours à envoyer un corps de **réponse**. Mais un client n'a pas toujours à envoyer un corps de **requête**. -Pour déclarer un corps de **requête**, on utilise les modèles de Pydantic en profitant de tous leurs avantages et fonctionnalités. +Pour déclarer un corps de **requête**, on utilise les modèles de Pydantic en profitant de tous leurs avantages et fonctionnalités. -!!! info - Pour envoyer de la donnée, vous devriez utiliser : `POST` (le plus populaire), `PUT`, `DELETE` ou `PATCH`. +/// info - Envoyer un corps dans une requête `GET` a un comportement non défini dans les spécifications, cela est néanmoins supporté par **FastAPI**, seulement pour des cas d'utilisation très complexes/extrêmes. +Pour envoyer de la donnée, vous devriez utiliser : `POST` (le plus populaire), `PUT`, `DELETE` ou `PATCH`. - Ceci étant découragé, la documentation interactive générée par Swagger UI ne montrera pas de documentation pour le corps d'une requête `GET`, et les proxys intermédiaires risquent de ne pas le supporter. +Envoyer un corps dans une requête `GET` a un comportement non défini dans les spécifications, cela est néanmoins supporté par **FastAPI**, seulement pour des cas d'utilisation très complexes/extrêmes. + +Ceci étant découragé, la documentation interactive générée par Swagger UI ne montrera pas de documentation pour le corps d'une requête `GET`, et les proxys intermédiaires risquent de ne pas le supporter. + +/// ## Importez le `BaseModel` de Pydantic Commencez par importer la classe `BaseModel` du module `pydantic` : -```Python hl_lines="4" -{!../../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[4] *} ## Créez votre modèle de données @@ -29,9 +30,7 @@ Déclarez ensuite votre modèle de données en tant que classe qui hérite de `B Utilisez les types Python standard pour tous les attributs : -```Python hl_lines="7-11" -{!../../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[7:11] *} Tout comme pour la déclaration de paramètres de requête, quand un attribut de modèle a une valeur par défaut, il n'est pas nécessaire. Sinon, cet attribut doit être renseigné dans le corps de la requête. Pour rendre ce champ optionnel simplement, utilisez `None` comme valeur par défaut. @@ -59,9 +58,7 @@ Par exemple, le modèle ci-dessus déclare un "objet" JSON (ou `dict` Python) te Pour l'ajouter à votre *opération de chemin*, déclarez-le comme vous déclareriez des paramètres de chemin ou de requête : -```Python hl_lines="18" -{!../../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[18] *} ...et déclarez que son type est le modèle que vous avez créé : `Item`. @@ -110,24 +107,25 @@ Mais vous auriez le même support de l'éditeur avec -!!! tip "Astuce" - Si vous utilisez PyCharm comme éditeur, vous pouvez utiliser le Plugin Pydantic PyCharm Plugin. +/// tip | Astuce + +Si vous utilisez PyCharm comme éditeur, vous pouvez utiliser le Plugin Pydantic PyCharm Plugin. - Ce qui améliore le support pour les modèles Pydantic avec : +Ce qui améliore le support pour les modèles Pydantic avec : - * de l'auto-complétion - * des vérifications de type - * du "refactoring" (ou remaniement de code) - * de la recherche - * de l'inspection +* de l'auto-complétion +* des vérifications de type +* du "refactoring" (ou remaniement de code) +* de la recherche +* de l'inspection + +/// ## Utilisez le modèle Dans la fonction, vous pouvez accéder à tous les attributs de l'objet du modèle directement : -```Python hl_lines="21" -{!../../../docs_src/body/tutorial002.py!} -``` +{* ../../docs_src/body/tutorial002.py hl[21] *} ## Corps de la requête + paramètres de chemin @@ -135,9 +133,7 @@ Vous pouvez déclarer des paramètres de chemin et un corps de requête pour la **FastAPI** est capable de reconnaître que les paramètres de la fonction qui correspondent aux paramètres de chemin doivent être **récupérés depuis le chemin**, et que les paramètres de fonctions déclarés comme modèles Pydantic devraient être **récupérés depuis le corps de la requête**. -```Python hl_lines="17-18" -{!../../../docs_src/body/tutorial003.py!} -``` +{* ../../docs_src/body/tutorial003.py hl[17:18] *} ## Corps de la requête + paramètres de chemin et de requête @@ -145,9 +141,7 @@ Vous pouvez aussi déclarer un **corps**, et des paramètres de **chemin** et de **FastAPI** saura reconnaître chacun d'entre eux et récupérer la bonne donnée au bon endroit. -```Python hl_lines="18" -{!../../../docs_src/body/tutorial004.py!} -``` +{* ../../docs_src/body/tutorial004.py hl[18] *} Les paramètres de la fonction seront reconnus comme tel : @@ -155,10 +149,13 @@ Les paramètres de la fonction seront reconnus comme tel : * Si le paramètre est d'un **type singulier** (comme `int`, `float`, `str`, `bool`, etc.), il sera interprété comme un paramètre de **requête**. * Si le paramètre est déclaré comme ayant pour type un **modèle Pydantic**, il sera interprété comme faisant partie du **corps** de la requête. -!!! note - **FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `=None`. +/// note + +**FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `=None`. + +Le type `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI**, mais sera utile à votre éditeur pour améliorer le support offert par ce dernier et détecter plus facilement des erreurs de type. - Le type `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI**, mais sera utile à votre éditeur pour améliorer le support offert par ce dernier et détecter plus facilement des erreurs de type. +/// ## Sans Pydantic diff --git a/docs/fr/docs/tutorial/debugging.md b/docs/fr/docs/tutorial/debugging.md index e58872d30..ab00fbdeb 100644 --- a/docs/fr/docs/tutorial/debugging.md +++ b/docs/fr/docs/tutorial/debugging.md @@ -6,9 +6,7 @@ Vous pouvez connecter le débogueur da Dans votre application FastAPI, importez et exécutez directement `uvicorn` : -```Python hl_lines="1 15" -{!../../../docs_src/debugging/tutorial001.py!} -``` +{* ../../docs_src/debugging/tutorial001.py hl[1,15] *} ### À propos de `__name__ == "__main__"` @@ -74,9 +72,12 @@ Ainsi, la ligne : ne sera pas exécutée. -!!! info +/// info + Pour plus d'informations, consultez la documentation officielle de Python. +/// + ## Exécutez votre code avec votre débogueur Parce que vous exécutez le serveur Uvicorn directement depuis votre code, vous pouvez appeler votre programme Python (votre application FastAPI) directement depuis le débogueur. diff --git a/docs/fr/docs/tutorial/first-steps.md b/docs/fr/docs/tutorial/first-steps.md index e98283f1e..758145362 100644 --- a/docs/fr/docs/tutorial/first-steps.md +++ b/docs/fr/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ Le fichier **FastAPI** le plus simple possible pourrait ressembler à cela : -```Python -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} Copiez ce code dans un fichier nommé `main.py`. @@ -24,12 +22,15 @@ $ uvicorn main:app --reload
-!!! note - La commande `uvicorn main:app` fait référence à : +/// note + +La commande `uvicorn main:app` fait référence à : + +* `main` : le fichier `main.py` (le module Python). +* `app` : l'objet créé dans `main.py` via la ligne `app = FastAPI()`. +* `--reload` : l'option disant à uvicorn de redémarrer le serveur à chaque changement du code. À ne pas utiliser en production ! - * `main` : le fichier `main.py` (le module Python). - * `app` : l'objet créé dans `main.py` via la ligne `app = FastAPI()`. - * `--reload` : l'option disant à uvicorn de redémarrer le serveur à chaque changement du code. À ne pas utiliser en production ! +/// Vous devriez voir dans la console, une ligne semblable à la suivante : @@ -131,22 +132,21 @@ Vous pourriez aussi l'utiliser pour générer du code automatiquement, pour les ### Étape 1 : import `FastAPI` -```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI` est une classe Python qui fournit toutes les fonctionnalités nécessaires au lancement de votre API. -!!! note "Détails techniques" - `FastAPI` est une classe héritant directement de `Starlette`. +/// note | Détails techniques + +`FastAPI` est une classe héritant directement de `Starlette`. - Vous pouvez donc aussi utiliser toutes les fonctionnalités de Starlette depuis `FastAPI`. +Vous pouvez donc aussi utiliser toutes les fonctionnalités de Starlette depuis `FastAPI`. + +/// ### Étape 2 : créer une "instance" `FastAPI` -```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[3] *} Ici la variable `app` sera une "instance" de la classe `FastAPI`. @@ -166,9 +166,7 @@ $ uvicorn main:app --reload Si vous créez votre app avec : -```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} -``` +{* ../../docs_src/first_steps/tutorial002.py hl[3] *} Et la mettez dans un fichier `main.py`, alors vous appelleriez `uvicorn` avec : @@ -200,9 +198,11 @@ https://example.com/items/foo /items/foo ``` -!!! info - Un chemin, ou "path" est aussi souvent appelé route ou "endpoint". +/// info +Un chemin, ou "path" est aussi souvent appelé route ou "endpoint". + +/// #### Opération @@ -242,25 +242,26 @@ Nous allons donc aussi appeler ces dernières des "**opérations**". #### Définir un *décorateur d'opération de chemin* -```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[6] *} Le `@app.get("/")` dit à **FastAPI** que la fonction en dessous est chargée de gérer les requêtes qui vont sur : * le chemin `/` * en utilisant une opération get -!!! info "`@décorateur` Info" - Cette syntaxe `@something` en Python est appelée un "décorateur". +/// info | `@décorateur` Info - Vous la mettez au dessus d'une fonction. Comme un joli chapeau décoratif (j'imagine que ce terme vient de là 🤷🏻‍♂). +Cette syntaxe `@something` en Python est appelée un "décorateur". - Un "décorateur" prend la fonction en dessous et en fait quelque chose. +Vous la mettez au dessus d'une fonction. Comme un joli chapeau décoratif (j'imagine que ce terme vient de là 🤷🏻‍♂). - Dans notre cas, ce décorateur dit à **FastAPI** que la fonction en dessous correspond au **chemin** `/` avec l'**opération** `get`. +Un "décorateur" prend la fonction en dessous et en fait quelque chose. - C'est le "**décorateur d'opération de chemin**". +Dans notre cas, ce décorateur dit à **FastAPI** que la fonction en dessous correspond au **chemin** `/` avec l'**opération** `get`. + +C'est le "**décorateur d'opération de chemin**". + +/// Vous pouvez aussi utiliser les autres opérations : @@ -275,14 +276,17 @@ Tout comme celles les plus exotiques : * `@app.patch()` * `@app.trace()` -!!! tip "Astuce" - Vous êtes libres d'utiliser chaque opération (méthode HTTP) comme vous le désirez. +/// tip | Astuce + +Vous êtes libres d'utiliser chaque opération (méthode HTTP) comme vous le désirez. - **FastAPI** n'impose pas de sens spécifique à chacune d'elle. +**FastAPI** n'impose pas de sens spécifique à chacune d'elle. - Les informations qui sont présentées ici forment une directive générale, pas des obligations. +Les informations qui sont présentées ici forment une directive générale, pas des obligations. - Par exemple, quand l'on utilise **GraphQL**, toutes les actions sont effectuées en utilisant uniquement des opérations `POST`. +Par exemple, quand l'on utilise **GraphQL**, toutes les actions sont effectuées en utilisant uniquement des opérations `POST`. + +/// ### Étape 4 : définir la **fonction de chemin**. @@ -292,9 +296,7 @@ Voici notre "**fonction de chemin**" (ou fonction d'opération de chemin) : * **opération** : `get`. * **fonction** : la fonction sous le "décorateur" (sous `@app.get("/")`). -```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[7] *} C'est une fonction Python. @@ -306,18 +308,17 @@ Ici, c'est une fonction asynchrone (définie avec `async def`). Vous pourriez aussi la définir comme une fonction classique plutôt qu'avec `async def` : -```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} -``` +{* ../../docs_src/first_steps/tutorial003.py hl[7] *} + +/// note -!!! note - Si vous ne connaissez pas la différence, allez voir la section [Concurrence : *"Vous êtes pressés ?"*](../async.md#vous-etes-presses){.internal-link target=_blank}. +Si vous ne connaissez pas la différence, allez voir la section [Concurrence : *"Vous êtes pressés ?"*](../async.md#vous-etes-presses){.internal-link target=_blank}. + +/// ### Étape 5 : retourner le contenu -```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[8] *} Vous pouvez retourner un dictionnaire (`dict`), une liste (`list`), des valeurs seules comme des chaines de caractères (`str`) et des entiers (`int`), etc. diff --git a/docs/fr/docs/tutorial/index.md b/docs/fr/docs/tutorial/index.md index 4dc202b33..83cc5f9e8 100644 --- a/docs/fr/docs/tutorial/index.md +++ b/docs/fr/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install fastapi[all] ... qui comprend également `uvicorn`, que vous pouvez utiliser comme serveur pour exécuter votre code. -!!! note - Vous pouvez également l'installer pièce par pièce. +/// note - C'est ce que vous feriez probablement une fois que vous voudrez déployer votre application en production : +Vous pouvez également l'installer pièce par pièce. - ``` - pip install fastapi - ``` +C'est ce que vous feriez probablement une fois que vous voudrez déployer votre application en production : - Installez également `uvicorn` pour qu'il fonctionne comme serveur : +``` +pip install fastapi +``` + +Installez également `uvicorn` pour qu'il fonctionne comme serveur : + +``` +pip install uvicorn +``` - ``` - pip install uvicorn - ``` +Et la même chose pour chacune des dépendances facultatives que vous voulez utiliser. - Et la même chose pour chacune des dépendances facultatives que vous voulez utiliser. +/// ## Guide utilisateur avancé diff --git a/docs/fr/docs/tutorial/path-params-numeric-validations.md b/docs/fr/docs/tutorial/path-params-numeric-validations.md new file mode 100644 index 000000000..3f3280e64 --- /dev/null +++ b/docs/fr/docs/tutorial/path-params-numeric-validations.md @@ -0,0 +1,163 @@ +# Paramètres de chemin et validations numériques + +De la même façon que vous pouvez déclarer plus de validations et de métadonnées pour les paramètres de requête avec `Query`, vous pouvez déclarer le même type de validations et de métadonnées pour les paramètres de chemin avec `Path`. + +## Importer Path + +Tout d'abord, importez `Path` de `fastapi`, et importez `Annotated` : + +{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *} + +/// info + +FastAPI a ajouté le support pour `Annotated` (et a commencé à le recommander) dans la version 0.95.0. + +Si vous avez une version plus ancienne, vous obtiendrez des erreurs en essayant d'utiliser `Annotated`. + +Assurez-vous de [Mettre à jour la version de FastAPI](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} à la version 0.95.1 à minima avant d'utiliser `Annotated`. + +/// + +## Déclarer des métadonnées + +Vous pouvez déclarer les mêmes paramètres que pour `Query`. + +Par exemple, pour déclarer une valeur de métadonnée `title` pour le paramètre de chemin `item_id`, vous pouvez écrire : + +{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *} + +/// note + +Un paramètre de chemin est toujours requis car il doit faire partie du chemin. Même si vous l'avez déclaré avec `None` ou défini une valeur par défaut, cela ne changerait rien, il serait toujours requis. + +/// + +## Ordonnez les paramètres comme vous le souhaitez + +/// tip + +Ce n'est probablement pas aussi important ou nécessaire si vous utilisez `Annotated`. + +/// + +Disons que vous voulez déclarer le paramètre de requête `q` comme un `str` requis. + +Et vous n'avez pas besoin de déclarer autre chose pour ce paramètre, donc vous n'avez pas vraiment besoin d'utiliser `Query`. + +Mais vous avez toujours besoin d'utiliser `Path` pour le paramètre de chemin `item_id`. Et vous ne voulez pas utiliser `Annotated` pour une raison quelconque. + +Python se plaindra si vous mettez une valeur avec une "défaut" avant une valeur qui n'a pas de "défaut". + +Mais vous pouvez les réorganiser, et avoir la valeur sans défaut (le paramètre de requête `q`) en premier. + +Cela n'a pas d'importance pour **FastAPI**. Il détectera les paramètres par leurs noms, types et déclarations par défaut (`Query`, `Path`, etc), il ne se soucie pas de l'ordre. + +Ainsi, vous pouvez déclarer votre fonction comme suit : + +{* ../../docs_src/path_params_numeric_validations/tutorial002.py hl[7] *} + +Mais gardez à l'esprit que si vous utilisez `Annotated`, vous n'aurez pas ce problème, cela n'aura pas d'importance car vous n'utilisez pas les valeurs par défaut des paramètres de fonction pour `Query()` ou `Path()`. + +{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py hl[10] *} + +## Ordonnez les paramètres comme vous le souhaitez (astuces) + +/// tip + +Ce n'est probablement pas aussi important ou nécessaire si vous utilisez `Annotated`. + +/// + +Voici une **petite astuce** qui peut être pratique, mais vous n'en aurez pas souvent besoin. + +Si vous voulez : + +* déclarer le paramètre de requête `q` sans `Query` ni valeur par défaut +* déclarer le paramètre de chemin `item_id` en utilisant `Path` +* les avoir dans un ordre différent +* ne pas utiliser `Annotated` + +...Python a une petite syntaxe spéciale pour cela. + +Passez `*`, comme premier paramètre de la fonction. + +Python ne fera rien avec ce `*`, mais il saura que tous les paramètres suivants doivent être appelés comme arguments "mots-clés" (paires clé-valeur), également connus sous le nom de kwargs. Même s'ils n'ont pas de valeur par défaut. + +{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *} + +# Avec `Annotated` + +Gardez à l'esprit que si vous utilisez `Annotated`, comme vous n'utilisez pas les valeurs par défaut des paramètres de fonction, vous n'aurez pas ce problème, et vous n'aurez probablement pas besoin d'utiliser `*`. + +{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *} + +## Validations numériques : supérieur ou égal + +Avec `Query` et `Path` (et d'autres que vous verrez plus tard) vous pouvez déclarer des contraintes numériques. + +Ici, avec `ge=1`, `item_id` devra être un nombre entier "`g`reater than or `e`qual" à `1`. + +{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *} + +## Validations numériques : supérieur ou égal et inférieur ou égal + +La même chose s'applique pour : + +* `gt` : `g`reater `t`han +* `le` : `l`ess than or `e`qual + +{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *} + +## Validations numériques : supérieur et inférieur ou égal + +La même chose s'applique pour : + +* `gt` : `g`reater `t`han +* `le` : `l`ess than or `e`qual + +{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *} + +## Validations numériques : flottants, supérieur et inférieur + +Les validations numériques fonctionnent également pour les valeurs `float`. + +C'est ici qu'il devient important de pouvoir déclarer gt et pas seulement ge. Avec cela, vous pouvez exiger, par exemple, qu'une valeur doit être supérieure à `0`, même si elle est inférieure à `1`. + +Ainsi, `0.5` serait une valeur valide. Mais `0.0` ou `0` ne le serait pas. + +Et la même chose pour lt. + +{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *} + +## Pour résumer + +Avec `Query`, `Path` (et d'autres que vous verrez plus tard) vous pouvez déclarer des métadonnées et des validations de chaînes de la même manière qu'avec les [Paramètres de requête et validations de chaînes](query-params-str-validations.md){.internal-link target=_blank}. + +Et vous pouvez également déclarer des validations numériques : + +* `gt` : `g`reater `t`han +* `ge` : `g`reater than or `e`qual +* `lt` : `l`ess `t`han +* `le` : `l`ess than or `e`qual + +/// info + +`Query`, `Path`, et d'autres classes que vous verrez plus tard sont des sous-classes d'une classe commune `Param`. + +Tous partagent les mêmes paramètres pour des validations supplémentaires et des métadonnées que vous avez vu précédemment. + +/// + +/// note | Détails techniques + +Lorsque vous importez `Query`, `Path` et d'autres de `fastapi`, ce sont en fait des fonctions. + +Ces dernières, lorsqu'elles sont appelées, renvoient des instances de classes du même nom. + +Ainsi, vous importez `Query`, qui est une fonction. Et lorsque vous l'appelez, elle renvoie une instance d'une classe également nommée `Query`. + +Ces fonctions sont là (au lieu d'utiliser simplement les classes directement) pour que votre éditeur ne marque pas d'erreurs sur leurs types. + +De cette façon, vous pouvez utiliser votre éditeur et vos outils de codage habituels sans avoir à ajouter des configurations personnalisées pour ignorer ces erreurs. + +/// diff --git a/docs/fr/docs/tutorial/path-params.md b/docs/fr/docs/tutorial/path-params.md index 894d62dd4..71c96b18e 100644 --- a/docs/fr/docs/tutorial/path-params.md +++ b/docs/fr/docs/tutorial/path-params.md @@ -4,9 +4,7 @@ Vous pouvez déclarer des "paramètres" ou "variables" de chemin avec la même s formatage de chaîne Python : -```Python hl_lines="6-7" -{!../../../docs_src/path_params/tutorial001.py!} -``` +{* ../../docs_src/path_params/tutorial001.py hl[6:7] *} La valeur du paramètre `item_id` sera transmise à la fonction dans l'argument `item_id`. @@ -22,15 +20,16 @@ vous verrez comme réponse : Vous pouvez déclarer le type d'un paramètre de chemin dans la fonction, en utilisant les annotations de type Python : -```Python hl_lines="7" -{!../../../docs_src/path_params/tutorial002.py!} -``` +{* ../../docs_src/path_params/tutorial002.py hl[7] *} Ici, `item_id` est déclaré comme `int`. -!!! hint "Astuce" - Ceci vous permettra d'obtenir des fonctionnalités de l'éditeur dans votre fonction, telles - que des vérifications d'erreur, de l'auto-complétion, etc. +/// check | vérifier + +Ceci vous permettra d'obtenir des fonctionnalités de l'éditeur dans votre fonction, telles +que des vérifications d'erreur, de l'auto-complétion, etc. + +/// ## Conversion de données @@ -40,12 +39,15 @@ Si vous exécutez cet exemple et allez sur "parsing"
automatique. +Comme vous l'avez remarqué, la valeur reçue par la fonction (et renvoyée ensuite) est `3`, +en tant qu'entier (`int`) Python, pas la chaîne de caractères (`string`) `"3"`. + +Grâce aux déclarations de types, **FastAPI** fournit du +"parsing" automatique. + +/// ## Validation de données @@ -72,12 +74,15 @@ La même erreur se produira si vous passez un nombre flottant (`float`) et non u http://127.0.0.1:8000/items/4.2. -!!! hint "Astuce" - Donc, avec ces mêmes déclarations de type Python, **FastAPI** vous fournit de la validation de données. +/// check | vérifier + +Donc, avec ces mêmes déclarations de type Python, **FastAPI** vous fournit de la validation de données. - Notez que l'erreur mentionne le point exact où la validation n'a pas réussi. +Notez que l'erreur mentionne le point exact où la validation n'a pas réussi. - Ce qui est incroyablement utile au moment de développer et débugger du code qui interagit avec votre API. +Ce qui est incroyablement utile au moment de développer et débugger du code qui interagit avec votre API. + +/// ## Documentation @@ -86,10 +91,13 @@ documentation générée automatiquement et interactive : -!!! info - À nouveau, en utilisant uniquement les déclarations de type Python, **FastAPI** vous fournit automatiquement une documentation interactive (via Swagger UI). +/// info + +À nouveau, en utilisant uniquement les déclarations de type Python, **FastAPI** vous fournit automatiquement une documentation interactive (via Swagger UI). + +On voit bien dans la documentation que `item_id` est déclaré comme entier. - On voit bien dans la documentation que `item_id` est déclaré comme entier. +/// ## Les avantages d'avoir une documentation basée sur une norme, et la documentation alternative. @@ -106,7 +114,7 @@ pour de nombreux langages. ## Pydantic -Toute la validation de données est effectué en arrière-plan avec Pydantic, +Toute la validation de données est effectué en arrière-plan avec Pydantic, dont vous bénéficierez de tous les avantages. Vous savez donc que vous êtes entre de bonnes mains. ## L'ordre importe @@ -119,9 +127,7 @@ Et vous avez un second chemin : `/users/{user_id}` pour récupérer de la donné Les *fonctions de chemin* étant évaluées dans l'ordre, il faut s'assurer que la fonction correspondant à `/users/me` est déclarée avant celle de `/users/{user_id}` : -```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003.py!} -``` +{* ../../docs_src/path_params/tutorial003.py hl[6,11] *} Sinon, le chemin `/users/{user_id}` correspondrait aussi à `/users/me`, la fonction "croyant" qu'elle a reçu un paramètre `user_id` avec pour valeur `"me"`. @@ -137,23 +143,25 @@ En héritant de `str` la documentation sera capable de savoir que les valeurs do Créez ensuite des attributs de classe avec des valeurs fixes, qui seront les valeurs autorisées pour cette énumération. -```Python hl_lines="1 6-9" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *} + +/// info -!!! info - Les énumérations (ou enums) sont disponibles en Python depuis la version 3.4. +Les énumérations (ou enums) sont disponibles en Python depuis la version 3.4. -!!! tip "Astuce" - Pour ceux qui se demandent, "AlexNet", "ResNet", et "LeNet" sont juste des noms de modèles de Machine Learning. +/// + +/// tip | Astuce + +Pour ceux qui se demandent, "AlexNet", "ResNet", et "LeNet" sont juste des noms de modèles de Machine Learning. + +/// ### Déclarer un paramètre de chemin Créez ensuite un *paramètre de chemin* avec une annotation de type désignant l'énumération créée précédemment (`ModelName`) : -```Python hl_lines="16" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[16] *} ### Documentation @@ -169,20 +177,19 @@ La valeur du *paramètre de chemin* sera un des "membres" de l'énumération. Vous pouvez comparer ce paramètre avec les membres de votre énumération `ModelName` : -```Python hl_lines="17" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[17] *} #### Récupérer la *valeur de l'énumération* Vous pouvez obtenir la valeur réel d'un membre (une chaîne de caractères ici), avec `model_name.value`, ou en général, `votre_membre_d'enum.value` : -```Python hl_lines="20" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[20] *} -!!! tip "Astuce" - Vous pouvez aussi accéder la valeur `"lenet"` avec `ModelName.lenet.value`. +/// tip | Astuce + +Vous pouvez aussi accéder la valeur `"lenet"` avec `ModelName.lenet.value`. + +/// #### Retourner des *membres d'énumération* @@ -190,9 +197,7 @@ Vous pouvez retourner des *membres d'énumération* dans vos *fonctions de chemi Ils seront convertis vers leurs valeurs correspondantes (chaînes de caractères ici) avant d'être transmis au client : -```Python hl_lines="18 21 23" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *} Le client recevra une réponse JSON comme celle-ci : @@ -231,14 +236,15 @@ Dans ce cas, le nom du paramètre est `file_path`, et la dernière partie, `:pat Vous pouvez donc l'utilisez comme tel : -```Python hl_lines="6" -{!../../../docs_src/path_params/tutorial004.py!} -``` +{* ../../docs_src/path_params/tutorial004.py hl[6] *} + +/// tip | Astuce + +Vous pourriez avoir besoin que le paramètre contienne `/home/johndoe/myfile.txt`, avec un slash au début (`/`). -!!! tip "Astuce" - Vous pourriez avoir besoin que le paramètre contienne `/home/johndoe/myfile.txt`, avec un slash au début (`/`). +Dans ce cas, l'URL serait : `/files//home/johndoe/myfile.txt`, avec un double slash (`//`) entre `files` et `home`. - Dans ce cas, l'URL serait : `/files//home/johndoe/myfile.txt`, avec un double slash (`//`) entre `files` et `home`. +/// ## Récapitulatif diff --git a/docs/fr/docs/tutorial/query-params-str-validations.md b/docs/fr/docs/tutorial/query-params-str-validations.md index f5248fe8b..c54c0c717 100644 --- a/docs/fr/docs/tutorial/query-params-str-validations.md +++ b/docs/fr/docs/tutorial/query-params-str-validations.md @@ -4,16 +4,17 @@ Commençons avec cette application pour exemple : -```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial001.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial001.py hl[9] *} Le paramètre de requête `q` a pour type `Union[str, None]` (ou `str | None` en Python 3.10), signifiant qu'il est de type `str` mais pourrait aussi être égal à `None`, et bien sûr, la valeur par défaut est `None`, donc **FastAPI** saura qu'il n'est pas requis. -!!! note - **FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `= None`. +/// note + +**FastAPI** saura que la valeur de `q` n'est pas requise grâce à la valeur par défaut `= None`. - Le `Union` dans `Union[str, None]` permettra à votre éditeur de vous offrir un meilleur support et de détecter les erreurs. +Le `Union` dans `Union[str, None]` permettra à votre éditeur de vous offrir un meilleur support et de détecter les erreurs. + +/// ## Validation additionnelle @@ -23,17 +24,13 @@ Nous allons imposer que bien que `q` soit un paramètre optionnel, dès qu'il es Pour cela, importez d'abord `Query` depuis `fastapi` : -```Python hl_lines="3" -{!../../../docs_src/query_params_str_validations/tutorial002.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[3] *} ## Utiliser `Query` comme valeur par défaut Construisez ensuite la valeur par défaut de votre paramètre avec `Query`, en choisissant 50 comme `max_length` : -```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial002.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[9] *} Comme nous devons remplacer la valeur par défaut `None` dans la fonction par `Query()`, nous pouvons maintenant définir la valeur par défaut avec le paramètre `Query(default=None)`, il sert le même objectif qui est de définir cette valeur par défaut. @@ -51,22 +48,25 @@ q: Union[str, None] = None Mais déclare explicitement `q` comme étant un paramètre de requête. -!!! info - Gardez à l'esprit que la partie la plus importante pour rendre un paramètre optionnel est : +/// info + +Gardez à l'esprit que la partie la plus importante pour rendre un paramètre optionnel est : + +```Python += None +``` - ```Python - = None - ``` +ou : - ou : +```Python += Query(None) +``` - ```Python - = Query(None) - ``` +et utilisera ce `None` pour détecter que ce paramètre de requête **n'est pas requis**. - et utilisera ce `None` pour détecter que ce paramètre de requête **n'est pas requis**. +Le `Union[str, None]` est uniquement là pour permettre à votre éditeur un meilleur support. - Le `Union[str, None]` est uniquement là pour permettre à votre éditeur un meilleur support. +/// Ensuite, nous pouvons passer d'autres paramètres à `Query`. Dans cet exemple, le paramètre `max_length` qui s'applique aux chaînes de caractères : @@ -80,17 +80,13 @@ Cela va valider les données, montrer une erreur claire si ces dernières ne son Vous pouvez aussi rajouter un second paramètre `min_length` : -```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial003.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial003.py hl[9] *} ## Ajouter des validations par expressions régulières On peut définir une expression régulière à laquelle le paramètre doit correspondre : -```Python hl_lines="10" -{!../../../docs_src/query_params_str_validations/tutorial004.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial004.py hl[10] *} Cette expression régulière vérifie que la valeur passée comme paramètre : @@ -108,12 +104,13 @@ De la même façon que vous pouvez passer `None` comme premier argument pour l'u Disons que vous déclarez le paramètre `q` comme ayant une longueur minimale de `3`, et une valeur par défaut étant `"fixedquery"` : -```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial005.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial005.py hl[7] *} + +/// note | Rappel + +Avoir une valeur par défaut rend le paramètre optionnel. -!!! note "Rappel" - Avoir une valeur par défaut rend le paramètre optionnel. +/// ## Rendre ce paramètre requis @@ -137,12 +134,13 @@ q: Union[str, None] = Query(default=None, min_length=3) Donc pour déclarer une valeur comme requise tout en utilisant `Query`, il faut utiliser `...` comme premier argument : -```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial006.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial006.py hl[7] *} + +/// info -!!! info - Si vous n'avez jamais vu ce `...` auparavant : c'est une des constantes natives de Python appelée "Ellipsis". +Si vous n'avez jamais vu ce `...` auparavant : c'est une des constantes natives de Python appelée "Ellipsis". + +/// Cela indiquera à **FastAPI** que la présence de ce paramètre est obligatoire. @@ -152,9 +150,7 @@ Quand on définit un paramètre de requête explicitement avec `Query` on peut a Par exemple, pour déclarer un paramètre de requête `q` qui peut apparaître plusieurs fois dans une URL, on écrit : -```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial011.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial011.py hl[9] *} Ce qui fait qu'avec une URL comme : @@ -175,8 +171,11 @@ Donc la réponse de cette URL serait : } ``` -!!! tip "Astuce" - Pour déclarer un paramètre de requête de type `list`, comme dans l'exemple ci-dessus, il faut explicitement utiliser `Query`, sinon cela sera interprété comme faisant partie du corps de la requête. +/// tip | Astuce + +Pour déclarer un paramètre de requête de type `list`, comme dans l'exemple ci-dessus, il faut explicitement utiliser `Query`, sinon cela sera interprété comme faisant partie du corps de la requête. + +/// La documentation sera donc mise à jour automatiquement pour autoriser plusieurs valeurs : @@ -186,9 +185,7 @@ La documentation sera donc mise à jour automatiquement pour autoriser plusieurs Et l'on peut aussi définir une liste de valeurs par défaut si aucune n'est fournie : -```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial012.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial012.py hl[9] *} Si vous allez à : @@ -213,14 +210,15 @@ et la réponse sera : Il est aussi possible d'utiliser directement `list` plutôt que `List[str]` : -```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial013.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial013.py hl[7] *} -!!! note - Dans ce cas-là, **FastAPI** ne vérifiera pas le contenu de la liste. +/// note - Par exemple, `List[int]` vérifiera (et documentera) que la liste est bien entièrement composée d'entiers. Alors qu'un simple `list` ne ferait pas cette vérification. +Dans ce cas-là, **FastAPI** ne vérifiera pas le contenu de la liste. + +Par exemple, `List[int]` vérifiera (et documentera) que la liste est bien entièrement composée d'entiers. Alors qu'un simple `list` ne ferait pas cette vérification. + +/// ## Déclarer des métadonnées supplémentaires @@ -228,22 +226,21 @@ On peut aussi ajouter plus d'informations sur le paramètre. Ces informations seront incluses dans le schéma `OpenAPI` généré et utilisées par la documentation interactive ou les outils externes utilisés. -!!! note - Gardez en tête que les outils externes utilisés ne supportent pas forcément tous parfaitement OpenAPI. +/// note + +Gardez en tête que les outils externes utilisés ne supportent pas forcément tous parfaitement OpenAPI. + +Il se peut donc que certains d'entre eux n'utilisent pas toutes les métadonnées que vous avez déclarées pour le moment, bien que dans la plupart des cas, les fonctionnalités manquantes ont prévu d'être implémentées. - Il se peut donc que certains d'entre eux n'utilisent pas toutes les métadonnées que vous avez déclarées pour le moment, bien que dans la plupart des cas, les fonctionnalités manquantes ont prévu d'être implémentées. +/// Vous pouvez ajouter un `title` : -```Python hl_lines="10" -{!../../../docs_src/query_params_str_validations/tutorial007.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial007.py hl[10] *} Et une `description` : -```Python hl_lines="13" -{!../../../docs_src/query_params_str_validations/tutorial008.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial008.py hl[13] *} ## Alias de paramètres @@ -263,9 +260,7 @@ Mais vous avez vraiment envie que ce soit exactement `item-query`... Pour cela vous pouvez déclarer un `alias`, et cet alias est ce qui sera utilisé pour trouver la valeur du paramètre : -```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial009.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial009.py hl[9] *} ## Déprécier des paramètres @@ -275,9 +270,7 @@ Il faut qu'il continue à exister pendant un certain temps car vos clients l'uti On utilise alors l'argument `deprecated=True` de `Query` : -```Python hl_lines="18" -{!../../../docs_src/query_params_str_validations/tutorial010.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial010.py hl[18] *} La documentation le présentera comme il suit : diff --git a/docs/fr/docs/tutorial/query-params.md b/docs/fr/docs/tutorial/query-params.md index 962135f63..b87c26c78 100644 --- a/docs/fr/docs/tutorial/query-params.md +++ b/docs/fr/docs/tutorial/query-params.md @@ -2,9 +2,7 @@ Quand vous déclarez des paramètres dans votre fonction de chemin qui ne font pas partie des paramètres indiqués dans le chemin associé, ces paramètres sont automatiquement considérés comme des paramètres de "requête". -```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial001.py!} -``` +{* ../../docs_src/query_params/tutorial001.py hl[9] *} La partie appelée requête (ou **query**) dans une URL est l'ensemble des paires clés-valeurs placées après le `?` , séparées par des `&`. @@ -63,28 +61,29 @@ Les valeurs des paramètres de votre fonction seront : De la même façon, vous pouvez définir des paramètres de requête comme optionnels, en leur donnant comme valeur par défaut `None` : -```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial002.py!} -``` +{* ../../docs_src/query_params/tutorial002.py hl[9] *} Ici, le paramètre `q` sera optionnel, et aura `None` comme valeur par défaut. -!!! check "Remarque" - On peut voir que **FastAPI** est capable de détecter que le paramètre de chemin `item_id` est un paramètre de chemin et que `q` n'en est pas un, c'est donc un paramètre de requête. +/// check | Remarque + +On peut voir que **FastAPI** est capable de détecter que le paramètre de chemin `item_id` est un paramètre de chemin et que `q` n'en est pas un, c'est donc un paramètre de requête. -!!! note - **FastAPI** saura que `q` est optionnel grâce au `=None`. +/// - Le `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI** (**FastAPI** n'en utilisera que la partie `str`), mais il servira tout de même à votre éditeur de texte pour détecter des erreurs dans votre code. +/// note +**FastAPI** saura que `q` est optionnel grâce au `=None`. + +Le `Optional` dans `Optional[str]` n'est pas utilisé par **FastAPI** (**FastAPI** n'en utilisera que la partie `str`), mais il servira tout de même à votre éditeur de texte pour détecter des erreurs dans votre code. + +/// ## Conversion des types des paramètres de requête Vous pouvez aussi déclarer des paramètres de requête comme booléens (`bool`), **FastAPI** les convertira : -```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial003.py!} -``` +{* ../../docs_src/query_params/tutorial003.py hl[9] *} Avec ce code, en allant sur : @@ -126,9 +125,7 @@ Et vous n'avez pas besoin de les déclarer dans un ordre spécifique. Ils seront détectés par leurs noms : -```Python hl_lines="8 10" -{!../../../docs_src/query_params/tutorial004.py!} -``` +{* ../../docs_src/query_params/tutorial004.py hl[8,10] *} ## Paramètres de requête requis @@ -138,9 +135,7 @@ Si vous ne voulez pas leur donner de valeur par défaut mais juste les rendre op Mais si vous voulez rendre un paramètre de requête obligatoire, vous pouvez juste ne pas y affecter de valeur par défaut : -```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} -``` +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} Ici le paramètre `needy` est un paramètre requis (ou obligatoire) de type `str`. @@ -184,9 +179,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy Et bien sur, vous pouvez définir certains paramètres comme requis, certains avec des valeurs par défaut et certains entièrement optionnels : -```Python hl_lines="10" -{!../../../docs_src/query_params/tutorial006.py!} -``` +{* ../../docs_src/query_params/tutorial006.py hl[10] *} Ici, on a donc 3 paramètres de requête : @@ -194,5 +187,8 @@ Ici, on a donc 3 paramètres de requête : * `skip`, un `int` avec comme valeur par défaut `0`. * `limit`, un `int` optionnel. -!!! tip "Astuce" - Vous pouvez utiliser les `Enum`s de la même façon qu'avec les [Paramètres de chemin](path-params.md#valeurs-predefinies){.internal-link target=_blank}. +/// tip | Astuce + +Vous pouvez utiliser les `Enum`s de la même façon qu'avec les [Paramètres de chemin](path-params.md#valeurs-predefinies){.internal-link target=_blank}. + +/// diff --git a/docs/he/docs/index.md b/docs/he/docs/index.md index 802dbe8b5..bd166f205 100644 --- a/docs/he/docs/index.md +++ b/docs/he/docs/index.md @@ -1,3 +1,9 @@ +# FastAPI + + +

FastAPI

@@ -5,11 +11,11 @@ תשתית FastAPI, ביצועים גבוהים, קלה ללמידה, מהירה לתכנות, מוכנה לסביבת ייצור

- - Test + + Test - - Coverage + + Coverage Package version @@ -23,7 +29,7 @@ **תיעוד**: https://fastapi.tiangolo.com -**קוד**: https://github.com/tiangolo/fastapi +**קוד**: https://github.com/fastapi/fastapi --- @@ -31,7 +37,7 @@ FastAPI היא תשתית רשת מודרנית ומהירה (ביצועים ג תכונות המפתח הן: -- **מהירה**: ביצועים גבוהים מאוד, בקנה אחד עם NodeJS ו - Go (תודות ל - Starlette ו - Pydantic). [אחת מתשתיות הפייתון המהירות ביותר](#performance). +- **מהירה**: ביצועים גבוהים מאוד, בקנה אחד עם NodeJS ו - Go (תודות ל - Starlette ו - Pydantic). [אחת מתשתיות הפייתון המהירות ביותר](#_14). - **מהירה לתכנות**: הגבירו את מהירות פיתוח התכונות החדשות בכ - %200 עד %300. \* - **פחות שגיאות**: מנעו כ - %40 משגיאות אנוש (מפתחים). \* @@ -64,7 +70,7 @@ 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._" -

Kabir Khan - Microsoft (ref)
+
Kabir Khan - Microsoft (ref)
--- @@ -88,7 +94,7 @@ FastAPI היא תשתית רשת מודרנית ומהירה (ביצועים ג "_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- @@ -115,7 +121,7 @@ FastAPI היא תשתית רשת מודרנית ומהירה (ביצועים ג FastAPI עומדת על כתפי ענקיות: - Starlette לחלקי הרשת. -- Pydantic לחלקי המידע. +- Pydantic לחלקי המידע. ## התקנה @@ -129,7 +135,7 @@ $ pip install fastapi -תצטרכו גם שרת ASGI כגון Uvicorn או Hypercorn. +תצטרכו גם שרת ASGI כגון Uvicorn או Hypercorn.
@@ -440,21 +446,21 @@ item: Item בשימוש Pydantic: -- email_validator - לאימות כתובות אימייל. +- email-validator - לאימות כתובות אימייל. בשימוש Starlette: - httpx - דרוש אם ברצונכם להשתמש ב - `TestClient`. - jinja2 - דרוש אם ברצונכם להשתמש בברירת המחדל של תצורת הטמפלייטים. -- python-multipart - דרוש אם ברצונכם לתמוך ב "פרסור" טפסים, באצמעות request.form(). +- python-multipart - דרוש אם ברצונכם לתמוך ב "פרסור" טפסים, באצמעות request.form(). - itsdangerous - דרוש אם ברצונכם להשתמש ב - `SessionMiddleware`. - pyyaml - דרוש אם ברצונכם להשתמש ב - `SchemaGenerator` של Starlette (כנראה שאתם לא צריכים את זה עם FastAPI). -- ujson - דרוש אם ברצונכם להשתמש ב - `UJSONResponse`. בשימוש FastAPI / Starlette: - uvicorn - לשרת שטוען ומגיש את האפליקציה שלכם. - orjson - דרוש אם ברצונכם להשתמש ב - `ORJSONResponse`. +- ujson - דרוש אם ברצונכם להשתמש ב - `UJSONResponse`. תוכלו להתקין את כל אלו באמצעות pip install "fastapi[all]". diff --git a/docs/hu/docs/index.md b/docs/hu/docs/index.md index 29c3c05ac..45ff49c3b 100644 --- a/docs/hu/docs/index.md +++ b/docs/hu/docs/index.md @@ -5,11 +5,11 @@ FastAPI keretrendszer, nagy teljesítmény, könnyen tanulható, gyorsan kódolható, productionre kész

- - Test + + Test - - Coverage + + Coverage Package version @@ -23,10 +23,10 @@ **Dokumentáció**: https://fastapi.tiangolo.com -**Forrás kód**: https://github.com/tiangolo/fastapi +**Forrás kód**: https://github.com/fastapi/fastapi --- -A FastAPI egy modern, gyors (nagy teljesítményű), webes keretrendszer API-ok építéséhez Python 3.8+-al, a Python szabványos típusjelöléseire építve. +A FastAPI egy modern, gyors (nagy teljesítményű), webes keretrendszer API-ok építéséhez Python -al, a Python szabványos típusjelöléseire építve. Kulcs funkciók: @@ -63,7 +63,7 @@ Kulcs funkciók: "_[...] 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._" -

Kabir Khan - Microsoft (ref)
+
Kabir Khan - Microsoft (ref)
--- @@ -87,7 +87,7 @@ Kulcs funkciók: "_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- @@ -115,12 +115,10 @@ Ha egy olyan CLI alkalmazást fejlesztesz amit a parancssorban kell használni w ## Követelmények -Python 3.8+ - A FastAPI óriások vállán áll: * Starlette a webes részekhez. -* Pydantic az adat részekhez. +* Pydantic az adat részekhez. ## Telepítés @@ -331,7 +329,7 @@ Ezt standard modern Python típusokkal csinálod. Nem kell új szintaxist, vagy specifikus könyvtár mert metódósait, stb. megtanulnod. -Csak standard **Python 3.8+**. +Csak standard **Python**. Például egy `int`-nek: @@ -378,7 +376,7 @@ Visszatérve az előző kód példához. A **FastAPI**: * Validálja hogy van egy `item_id` mező a `GET` és `PUT` kérésekben. * Validálja hogy az `item_id` `int` típusú a `GET` és `PUT` kérésekben. * Ha nem akkor látni fogunk egy tiszta hibát ezzel kapcsolatban. -* ellenőrzi hogyha van egy opcionális query paraméter `q` névvel (azaz `http://127.0.0.1:8000/items/foo?q=somequery`) `GET` kérések esetén. +* ellenőrzi hogyha van egy opcionális query paraméter `q` névvel (azaz `http://127.0.0.1:8000/items/foo?q=somequery`) `GET` kérések esetén. * Mivel a `q` paraméter `= None`-al van deklarálva, ezért opcionális. * `None` nélkül ez a mező kötelező lenne (mint például a body `PUT` kérések esetén). * a `/items/{item_id}` címre érkező `PUT` kérések esetén, a JSON-t a következőképpen olvassa be: @@ -445,7 +443,7 @@ Ezeknek a további megértéséhez: email_validator - e-mail validációkra. +* email-validator - e-mail validációkra. * pydantic-settings - Beállítások követésére. * pydantic-extra-types - Extra típusok Pydantic-hoz. @@ -453,15 +451,15 @@ Starlette által használt: * httpx - Követelmény ha a `TestClient`-et akarod használni. * jinja2 - Követelmény ha az alap template konfigurációt akarod használni. -* python-multipart - Követelmény ha "parsing"-ot akarsz támogatni, `request.form()`-al. +* python-multipart - Követelmény ha "parsing"-ot akarsz támogatni, `request.form()`-al. * itsdangerous - Követelmény `SessionMiddleware` támogatáshoz. * pyyaml - Követelmény a Starlette `SchemaGenerator`-ának támogatásához (valószínűleg erre nincs szükség FastAPI használása esetén). -* ujson - Követelmény ha `UJSONResponse`-t akarsz használni. FastAPI / Starlette által használt * uvicorn - Szerverekhez amíg betöltik és szolgáltatják az applikációdat. * orjson - Követelmény ha `ORJSONResponse`-t akarsz használni. +* ujson - Követelmény ha `UJSONResponse`-t akarsz használni. Ezeket mind telepítheted a `pip install "fastapi[all]"` paranccsal. diff --git a/docs/id/docs/index.md b/docs/id/docs/index.md new file mode 100644 index 000000000..5fb0c4c9c --- /dev/null +++ b/docs/id/docs/index.md @@ -0,0 +1,495 @@ +# FastAPI + + + +

+ FastAPI +

+

+ FastAPI, framework performa tinggi, mudah dipelajari, cepat untuk coding, siap untuk pengembangan +

+

+ + Test + + + Coverage + + + Package version + + + Supported Python versions + +

+ +--- + +**Dokumentasi**: https://fastapi.tiangolo.com + +**Kode Sumber**: https://github.com/fastapi/fastapi + +--- + +FastAPI adalah *framework* *web* moderen, cepat (performa-tinggi) untuk membangun API dengan Python berdasarkan tipe petunjuk Python. + +Fitur utama FastAPI: + +* **Cepat**: Performa sangat tinggi, setara **NodeJS** dan **Go** (berkat Starlette dan Pydantic). [Salah satu *framework* Python tercepat yang ada](#performa). +* **Cepat untuk coding**: Meningkatkan kecepatan pengembangan fitur dari 200% sampai 300%. * +* **Sedikit bug**: Mengurangi hingga 40% kesalahan dari manusia (pemrogram). * +* **Intuitif**: Dukungan editor hebat. Penyelesaian di mana pun. Lebih sedikit *debugging*. +* **Mudah**: Dibuat mudah digunakan dan dipelajari. Sedikit waktu membaca dokumentasi. +* **Ringkas**: Mengurasi duplikasi kode. Beragam fitur dari setiap deklarasi parameter. Lebih sedikit *bug*. +* **Handal**: Dapatkan kode siap-digunakan. Dengan dokumentasi otomatis interaktif. +* **Standar-resmi**: Berdasarkan (kompatibel dengan ) standar umum untuk API: OpenAPI (sebelumnya disebut Swagger) dan JSON Schema. + +* estimasi berdasarkan pengujian tim internal pengembangan applikasi siap pakai. + +## Sponsor + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} + +{% endfor -%} +{%- for sponsor in sponsors.silver -%} + +{% endfor %} +{% endif %} + + + +Sponsor lainnya + +## Opini + +"_[...] Saya banyak menggunakan **FastAPI** sekarang ini. [...] Saya berencana menggunakannya di semua tim servis ML Microsoft. Beberapa dari mereka sudah mengintegrasikan dengan produk inti *Windows** dan sebagian produk **Office**._" + +
Kabir Khan - Microsoft (ref)
+ +--- + +"_Kami adopsi library **FastAPI** untuk membuat server **REST** yang melakukan kueri untuk menghasilkan **prediksi**. [untuk Ludwig]_" + +
Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber (ref)
+ +--- + +"_**Netflix** dengan bangga mengumumkan rilis open-source orkestrasi framework **manajemen krisis** : **Dispatch**! [dibuat dengan **FastAPI**]_" + +
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (ref)
+ +--- + +"_Saya sangat senang dengan **FastAPI**. Sangat menyenangkan!_" + +
Brian Okken - Python Bytes podcast host (ref)
+ +--- + +"_Jujur, apa yang anda buat sangat solid dan berkualitas. Ini adalah yang saya inginkan di **Hug** - sangat menginspirasi melihat seseorang membuat ini._" + +
Timothy Crosley - Hug creator (ref)
+ +--- + +"_Jika anda ingin mempelajari **framework moderen** untuk membangun REST API, coba **FastAPI** [...] cepat, mudah digunakan dan dipelajari [...]_" + +"_Kami sudah pindah ke **FastAPI** untuk **API** kami [...] Saya pikir kamu juga akan suka [...]_" + +
Ines Montani - Matthew Honnibal - Explosion AI founders - spaCy creators (ref) - (ref)
+ +--- +"_Jika anda ingin membuat API Python siap pakai, saya merekomendasikan **FastAPI**. FastAPI **didesain indah**, **mudah digunakan** dan **sangat scalable**, FastAPI adalah **komponen kunci** di strategi pengembangan API pertama kami dan mengatur banyak otomatisasi dan service seperti TAC Engineer kami._" + +
Deon Pillsbury - Cisco (ref)
+ +--- + +## **Typer**, CLI FastAPI + + + +Jika anda mengembangkan app CLI yang digunakan di terminal bukan sebagai API web, kunjungi **Typer**. + +**Typer** adalah saudara kecil FastAPI. Dan ditujukan sebagai **CLI FastAPI**. ⌨️ 🚀 + +## Prayarat + +FastAPI berdiri di pundak raksasa: + +* Starlette untuk bagian web. +* Pydantic untuk bagian data. + +## Instalasi + +Buat dan aktifkan virtual environment kemudian *install* FastAPI: + +
+ +```console +$ pip install "fastapi[standard]" + +---> 100% +``` + +
+ +**Catatan**: Pastikan anda menulis `"fastapi[standard]"` dengan tanda petik untuk memastikan bisa digunakan di semua *terminal*. + +## Contoh + +### Buat app + +* Buat file `main.py` dengan: + +```Python +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@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} +``` + +
+Atau gunakan async def... + +Jika kode anda menggunakan `async` / `await`, gunakan `async def`: + +```Python hl_lines="9 14" +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +async def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +async def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +**Catatan**: + +Jika anda tidak paham, kunjungi _"Panduan cepat"_ bagian `async` dan `await` di dokumentasi. + +
+ +### Jalankan + +Jalankan *server* dengan: + +
+ +```console +$ fastapi dev main.py + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + │ fastapi run │ + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [2248755] using WatchFiles +INFO: Started server process [2248757] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +
+Mengenai perintah fastapi dev main.py... + +Perintah `fastapi dev` membaca file `main.py`, memeriksa app **FastAPI** di dalamnya, dan menjalan server dengan Uvicorn. + +Secara otomatis, `fastapi dev` akan mengaktifkan *auto-reload* untuk pengembangan lokal. + +Informasi lebih lanjut kunjungi Dokumen FastAPI CLI. + +
+ +### Periksa + +Buka *browser* di http://127.0.0.1:8000/items/5?q=somequery. + +Anda akan melihat respon JSON berikut: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +Anda telah membuat API: + +* Menerima permintaan HTTP di _path_ `/` dan `/items/{item_id}`. +* Kedua _paths_ menerima operasi `GET` (juga disebut _metode_ HTTP). +* _path_ `/items/{item_id}` memiliki _parameter path_ `item_id` yang harus berjenis `int`. +* _path_ `/items/{item_id}` memiliki _query parameter_ `q` berjenis `str`. + +### Dokumentasi API interaktif + +Sekarang kunjungi http://127.0.0.1:8000/docs. + +Anda akan melihat dokumentasi API interaktif otomatis (dibuat oleh Swagger UI): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### Dokumentasi API alternatif + +Kemudian kunjungi http://127.0.0.1:8000/redoc. + +Anda akan melihat dokumentasi alternatif otomatis (dibuat oleh ReDoc): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## Contoh upgrade + +Sekarang ubah `main.py` untuk menerima struktur permintaan `PUT`. + +Deklarasikan struktur menggunakan tipe standar Python, berkat 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} +``` + +Server `fastapi dev` akan otomatis memuat kembali. + +### Upgrade dokumentasi API interaktif + +Kunjungi http://127.0.0.1:8000/docs. + +* Dokumentasi API interaktif akan otomatis diperbarui, termasuk kode yang baru: + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* Klik tombol "Try it out", anda dapat mengisi parameter dan langsung berinteraksi dengan API: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) + +* Kemudian klik tombol "Execute", tampilan pengguna akan berkomunikasi dengan API, mengirim parameter, mendapatkan dan menampilkan hasil ke layar: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) + +### Upgrade dokumentasi API alternatif + +Kunjungi http://127.0.0.1:8000/redoc. + +* Dokumentasi alternatif akan menampilkan parameter *query* dan struktur *request*: + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### Ringkasan + +Singkatnya, anda mendeklarasikan **sekali** jenis parameter, struktur, dll. sebagai parameter fungsi. + +Anda melakukannya dengan tipe standar moderen Python. + +Anda tidak perlu belajar sintaksis, metode, *classs* baru dari *library* tertentu, dll. + +Cukup **Python** standar. + +Sebagai contoh untuk `int`: + +```Python +item_id: int +``` + +atau untuk model lebih rumit `Item`: + +```Python +item: Item +``` + +...dengan sekali deklarasi anda mendapatkan: + +* Dukungan editor, termasuk: + * Pelengkapan kode. + * Pengecekan tipe. +* Validasi data: + * Kesalahan otomatis dan jelas ketika data tidak sesuai. + * Validasi hingga untuk object JSON bercabang mendalam. +* Konversi input data: berasal dari jaringan ke data dan tipe Python. Membaca dari: + * JSON. + * Parameter path. + * Parameter query. + * Cookie. + * Header. + * Form. + * File. +* Konversi output data: konversi data Python ke tipe jaringan data (seperti JSON): + * Konversi tipe Python (`str`, `int`, `float`, `bool`, `list`, dll). + * Objek `datetime`. + * Objek `UUID`. + * Model database. + * ...dan banyak lagi. +* Dokumentasi interaktif otomatis, termasuk 2 alternatif tampilan pengguna: + * Swagger UI. + * ReDoc. + +--- + +Kembali ke kode contoh sebelumnya, **FastAPI** akan: + +* Validasi apakah terdapat `item_id` di *path* untuk permintaan `GET` dan `PUT` requests. +* Validasi apakah `item_id` berjenit `int` untuk permintaan `GET` dan `PUT`. + * Jika tidak, klien akan melihat pesan kesalahan jelas. +* Periksa jika ada parameter *query* opsional bernama `q` (seperti `http://127.0.0.1:8000/items/foo?q=somequery`) untuk permintaan `GET`. + * Karena parameter `q` dideklarasikan dengan `= None`, maka bersifat opsional. + * Tanpa `None` maka akan menjadi wajib ada (seperti struktur di kondisi dengan `PUT`). +* Untuk permintaan `PUT` `/items/{item_id}`, membaca struktur sebagai JSON: + * Memeriksa terdapat atribut wajib `name` harus berjenis `str`. + * Memeriksa terdapat atribut wajib`price` harus berjenis `float`. + * Memeriksa atribut opsional `is_offer`, harus berjenis `bool`, jika ada. + * Semua ini juga sama untuk objek json yang bersarang mendalam. +* Konversi dari dan ke JSON secara otomatis. +* Dokumentasi segalanya dengan OpenAPI, dengan menggunakan: + * Sistem dokumentasi interaktif. + * Sistem otomatis penghasil kode, untuk banyak bahasa. +* Menyediakan 2 tampilan dokumentasi web interaktif dengan langsung. + +--- + +Kita baru menyentuh permukaannya saja, tetapi anda sudah mulai paham gambaran besar cara kerjanya. + +Coba ubah baris: + +```Python + return {"item_name": item.name, "item_id": item_id} +``` + +...dari: + +```Python + ... "item_name": item.name ... +``` + +...menjadi: + +```Python + ... "item_price": item.price ... +``` + +...anda akan melihat kode editor secara otomatis melengkapi atributnya dan tahu tipe nya: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +Untuk contoh lengkap termasuk fitur lainnya, kunjungi Tutorial - Panduan Pengguna. + +**Peringatan spoiler**: tutorial - panduan pengguna termasuk: + +* Deklarasi **parameter** dari tempat berbeda seperti: **header**, **cookie**, **form field** and **file**. +* Bagaimana mengatur **batasan validasi** seperti `maximum_length`atau `regex`. +* Sistem **Dependency Injection** yang hebat dan mudah digunakan. +* Keamanan dan autentikasi, termasuk dukungan ke **OAuth2** dengan **JWT token** dan autentikasi **HTTP Basic**. +* Teknik lebih aju (tetapi mudah dipakai untuk deklarasi **model JSON bersarang ke dalam** (berkat Pydantic). +* Integrasi **GraphQL** dengan Strawberry dan library lainnya. +* Fitur lainnya (berkat Starlette) seperti: + * **WebSocket** + * Test yang sangat mudah berdasarkan HTTPX dan `pytest` + * **CORS** + * **Cookie Session** + * ...dan lainnya. + +## Performa + +Tolok ukur Independent TechEmpower mendapati aplikasi **FastAPI** berjalan menggunakan Uvicorn sebagai salah satu framework Python tercepat yang ada, hanya di bawah Starlette dan Uvicorn itu sendiri (digunakan di internal FastAPI). (*) + +Penjelasan lebih lanjut, lihat bagian Tolok ukur. + +## Dependensi + +FastAPI bergantung pada Pydantic dan Starlette. + +### Dependensi `standar` + +Ketika anda meng-*install* FastAPI dengan `pip install "fastapi[standard]"`, maka FastAPI akan menggunakan sekumpulan dependensi opsional `standar`: + +Digunakan oleh Pydantic: + +* email-validator - untuk validasi email. + +Digunakan oleh Starlette: + +* httpx - Dibutuhkan jika anda menggunakan `TestClient`. +* jinja2 - Dibutuhkan jika anda menggunakan konfigurasi template bawaan. +* python-multipart - Dibutuhkan jika anda menggunakan form dukungan "parsing", dengan `request.form()`. + +Digunakan oleh FastAPI / Starlette: + +* uvicorn - untuk server yang memuat dan melayani aplikasi anda. Termasuk `uvicorn[standard]`, yang memasukan sejumlah dependensi (misal `uvloop`) untuk needed melayani dengan performa tinggi. +* `fastapi-cli` - untuk menyediakan perintah `fastapi`. + +### Tanpda dependensi `standard` + +Jika anda tidak ingin menambahkan dependensi opsional `standard`, anda dapat menggunakan `pip install fastapi` daripada `pip install "fastapi[standard]"`. + +### Dependensi Opsional Tambahan + +Ada beberapa dependensi opsional yang bisa anda install. + +Dependensi opsional tambahan Pydantic: + +* pydantic-settings - untuk manajemen setting. +* pydantic-extra-types - untuk tipe tambahan yang digunakan dengan Pydantic. + +Dependensi tambahan opsional FastAPI: + +* orjson - Diperlukan jika anda akan menggunakan`ORJSONResponse`. +* ujson - Diperlukan jika anda akan menggunakan `UJSONResponse`. + +## Lisensi + +Project terlisensi dengan lisensi MIT. diff --git a/docs/id/docs/tutorial/first-steps.md b/docs/id/docs/tutorial/first-steps.md new file mode 100644 index 000000000..9b461507d --- /dev/null +++ b/docs/id/docs/tutorial/first-steps.md @@ -0,0 +1,332 @@ +# Langkah Pertama + +File FastAPI yang paling sederhana bisa seperti berikut: + +{* ../../docs_src/first_steps/tutorial001.py *} + +Salin file tersebut ke `main.py`. + +Jalankan di server: + +
+ +```console +$ fastapi dev main.py +INFO Using path main.py +INFO Resolved absolute path /home/user/code/awesomeapp/main.py +INFO Searching for package file structure from directories with __init__.py files +INFO Importing from /home/user/code/awesomeapp + + ╭─ Python module file ─╮ + │ │ + │ 🐍 main.py │ + │ │ + ╰──────────────────────╯ + +INFO Importing module main +INFO Found importable FastAPI app + + ╭─ Importable FastAPI app ─╮ + │ │ + │ from main import app │ + │ │ + ╰──────────────────────────╯ + +INFO Using import string main:app + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + fastapi run + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [2265862] using WatchFiles +INFO: Started server process [2265873] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +Di output, terdapat sebaris pesan: + +```hl_lines="4" +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +Baris tersebut menunjukan URL dimana app aktif di komputer anda. + + +### Mencoba aplikasi + +Buka browser di http://127.0.0.1:8000. + +Anda akan melihat response JSON sebagai berikut: + +```JSON +{"message": "Hello World"} +``` + +### Dokumen API interaktif + +Sekarang kunjungi http://127.0.0.1:8000/docs. + +Anda akan melihat dokumentasi API interaktif otomatis (dibuat oleh Swagger UI): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### Dokumen API alternatif + +Dan sekarang, kunjungi http://127.0.0.1:8000/redoc. + +Anda akan melihat dokumentasi alternatif otomatis (dibuat oleh ReDoc): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +### OpenAPI + +**FastAPI** membuat sebuah "schema" dimana semua API anda menggunakan standar **OpenAPI** untuk mendefinisikan API. + +#### "Schema" + +"schema" adalah suatu definisi atau deskripsi dari sesuatu. Bukan kode yang mengimplementasi definisi tersebut. Ini hanyalah sebuah deskripsi abstrak. + +#### "schema" API + +Dalam hal ini, OpenAPI adalah spesifikasi yang menunjukan bagaimana untuk mendefinisikan sebuah skema di API anda. + +Definisi skema ini termasuk jalur API anda, parameter yang bisa diterima, dll. + +#### "schema" Data + +Istilah "schema" bisa juga merujuk ke struktur data, seperti konten JSON. + +Dalam kondisi ini, ini berarti attribut JSON dan tipe data yang dimiliki, dll. + +#### Schema OpenAPI and JSON + +"schema" OpenAPI mendefinisikan skema API dari API yang anda buat. Skema tersebut termasuk definisi (atau "schema") dari data yang dikirim atau diterima oleh API dari **JSON Schema**, skema data standar JSON. + +#### Lihat `openapi.json` + +Jika anda penasaran bagaimana skema OpenAPI polos seperti apa, FastAPI secara otomatis membuat JSON (schema) dengan deksripsi API anda. + +anda bisa melihatnya di: http://127.0.0.1:8000/openapi.json. + +Anda akan melihat JSON yang dimulai seperti: + +```JSON +{ + "openapi": "3.1.0", + "info": { + "title": "FastAPI", + "version": "0.1.0" + }, + "paths": { + "/items/": { + "get": { + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + + + +... +``` + +#### Kegunaan OpenAPI + +Skema OpenAPI adalah tulang punggung dua sistem dokumentasi API interaktif yang ada di FastAPI. + +Ada banyak alternatif sistem dokumentasi lainnya yang semuanya berdasarkan OpenAPI. Anda bisa menambahkannya ke aplikasi **FastAPI** anda. + +Anda juga bisa menggunakan OpenAPI untuk membuat kode secara otomatis, untuk klien yang menggunakan API anda. Sebagai contoh, frontend, aplikasi mobile atau IoT. + +## Ringkasan, secara bertahap + +### Langkah 1: impor `FastAPI` + +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} + +`FastAPI` adalah class Python yang menyediakan semua fungsionalitas API anda. + +/// note | Detail Teknis + +`FastAPI` adalah class turunan langsung dari `Starlette`. + +Anda bisa menggunakan semua fungsionalitas Starlette dengan `FastAPI` juga. + +/// + +### Langkah 2: buat "instance" dari `FastAPI` + +{* ../../docs_src/first_steps/tutorial001.py hl[3] *} + +Di sini variabel `app` akan menjadi sebuah "instance" dari class `FastAPI`. + +Ini akan menjadi gerbang utama untuk membuat semua API anda. + +### Langkah 3: Buat *operasi path* + +#### Path + +"Path" atau jalur di sini merujuk ke bagian URL terakhir dimulai dari `/` pertama. + +Sehingga, URL seperti: + +``` +https://example.com/items/foo +``` + +...path-nya adalah: + +``` +/items/foo +``` + +/// info + +"path" juga biasa disebut "endpoint" atau "route". + +/// + +ketika membuat API, "path" adalah jalan utama untuk memisahkan "concern" dan "resources". + +#### Operasi + +"Operasi" di sini merujuk ke salah satu dari metode HTTP berikut. + +Salah satu dari: + +* `POST` +* `GET` +* `PUT` +* `DELETE` + +...dan operasi lainnya yang unik: + +* `OPTIONS` +* `HEAD` +* `PATCH` +* `TRACE` + +Dalam protokol HTTP, anda bisa berkomunikasi ke setiap path menggunakan satu (atau lebih) metode di atas. + +--- + +Ketika membuat API, anda umumnya menggunakan metode HTTP tertentu untuk proses tertentu. + +Umumnya menggunakan: + +* `POST`: untuk membuat data. +* `GET`: untuk membaca data. +* `PUT`: untuk memperbarui data. +* `DELETE`: untuk menghapus data. + +Sehingga, di OpanAPI, setiap metode HTTP ini disebut sebuah "operasi". + +Kita akan menyebut mereka juga "**operasi**". + +#### Mendefinisikan *dekorator operasi path* + +{* ../../docs_src/first_steps/tutorial001.py hl[6] *} + +`@app.get("/")` memberitahu **FastAPI** bahwa fungsi di bawahnya mengurusi request yang menuju ke: + +* path `/` +* menggunakan operasi get + +/// info | `@decorator` Info + +Sintaksis `@sesuatu` di Python disebut "dekorator". + +Dekorator ditempatkan di atas fungsi. Seperti sebuah topi cantik (Saya pikir istilah ini berasal dari situ). + +"dekorator" memanggil dan bekerja dengan fungsi yang ada di bawahnya + +Pada kondisi ini, dekorator ini memberi tahu **FastAPI** bahwa fungsi di bawah nya berhubungan dengan **path** `/` dengan **operasi** `get`. + +Sehingga disebut **dekorator operasi path**. + +/// + +Operasi lainnya yang bisa digunakan: + +* `@app.post()` +* `@app.put()` +* `@app.delete()` + +Dan operasi unik lainnya: + +* `@app.options()` +* `@app.head()` +* `@app.patch()` +* `@app.trace()` + +/// tip | Tips + +Jika anda bisa menggunakan operasi apa saja (metode HTTP). + +**FastAPI** tidak mengharuskan anda menggunakan operasi tertentu. + +Informasi di sini hanyalah sebagai panduan, bukan keharusan. + +Sebagai contoh, ketika menggunakan GraphQL, semua operasi umumnya hanya menggunakan `POST`. + +/// + +### Langkah 4: mendefinisikan **fungsi operasi path** + +Ini "**fungsi operasi path**" kita: + +* **path**: adalah `/`. +* **operasi**: adalah `get`. +* **fungsi**: adalah fungsi yang ada di bawah dekorator (di bawah `@app.get("/")`). + +{* ../../docs_src/first_steps/tutorial001.py hl[7] *} + +Ini adalah fungsi Python. + +Fungsi ini dipanggil **FastAPI** setiap kali menerima request ke URL "`/`" dengan operasi `GET`. + +Di kondisi ini, ini adalah sebuah fungsi `async`. + +--- + +Anda bisa mendefinisikan fungsi ini sebagai fungsi normal daripada `async def`: + +{* ../../docs_src/first_steps/tutorial003.py hl[7] *} + +/// note | Catatan + +Jika anda tidak tahu perbedaannya, kunjungi [Async: *"Panduan cepat"*](../async.md#in-a-hurry){.internal-link target=_blank}. + +/// + +### Langkah 5: hasilkan konten + +{* ../../docs_src/first_steps/tutorial001.py hl[8] *} + +Anda bisa menghasilkan `dict`, `list`, nilai singular seperti `str`, `int`, dll. + +Anda juga bisa menghasilkan model Pydantic (anda akan belajar mengenai ini nanti). + +Ada banyak objek dan model yang secara otomatis dikonversi ke JSON (termasuk ORM, dll). Anda bisa menggunakan yang anda suka, kemungkinan sudah didukung. + +## Ringkasan + +* Impor `FastAPI`. +* Buat sebuah instance `app`. +* Tulis **dekorator operasi path** menggunakan dekorator seperti `@app.get("/")`. +* Definisikan **fungsi operasi path**; sebagai contoh, `def root(): ...`. +* Jalankan server development dengan perintah `fastapi dev`. diff --git a/docs/id/docs/tutorial/index.md b/docs/id/docs/tutorial/index.md index b8ed96ae1..c01ec9a89 100644 --- a/docs/id/docs/tutorial/index.md +++ b/docs/id/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ...yang juga termasuk `uvicorn`, yang dapat kamu gunakan sebagai server yang menjalankan kodemu. -!!! catatan - Kamu juga dapat meng-installnya bagian demi bagian. +/// note | Catatan - Hal ini mungkin yang akan kamu lakukan ketika kamu hendak menyebarkan (men-deploy) aplikasimu ke tahap produksi: +Kamu juga dapat meng-installnya bagian demi bagian. - ``` - pip install fastapi - ``` +Hal ini mungkin yang akan kamu lakukan ketika kamu hendak menyebarkan (men-deploy) aplikasimu ke tahap produksi: - Juga install `uvicorn` untuk menjalankan server" +``` +pip install fastapi +``` + +Juga install `uvicorn` untuk menjalankan server" + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +Dan demikian juga untuk pilihan dependensi yang hendak kamu gunakan. - Dan demikian juga untuk pilihan dependensi yang hendak kamu gunakan. +/// ## Pedoman Pengguna Lanjutan diff --git a/docs/id/docs/tutorial/path-params.md b/docs/id/docs/tutorial/path-params.md new file mode 100644 index 000000000..7c24de4d3 --- /dev/null +++ b/docs/id/docs/tutorial/path-params.md @@ -0,0 +1,258 @@ +# Parameter Path + +"parameter" atau "variabel" path didefinisikan dengan sintaksis Python format string: + +{* ../../docs_src/path_params/tutorial001.py hl[6:7] *} + +Nilai parameter path `item_id` akan dikirim ke fungsi sebagai argument `item_id`: + +Jika anda menjalankan contoh berikut dan kunjungi http://127.0.0.1:8000/items/foo, anda akan melihat respon: + +```JSON +{"item_id":"foo"} +``` + +## Parameter path dengan tipe data + +Tipe data parameter path bisa didefinisikan di dalam fungsi, menggunakan anotasi tipe data standar Python: + +{* ../../docs_src/path_params/tutorial002.py hl[7] *} + +Dalam hal ini `item_id` didefinisikan sebagai `int`. + +/// check | Periksa + +Penyunting kode anda bisa membantu periksa di dalam fungsi seperti pemeriksaan kesalahan, kelengkapan kode, dll. + +/// + +## Konversi data + +Jika contoh berikut dijalankan dan diakses browser melalui http://127.0.0.1:8000/items/3, anda akan melihat respon: + +```JSON +{"item_id":3} +``` + +/// check | Periksa + +Perhatikan nilai fungsi yang diterima (dan dihasilkan) adalah `3`, sebagai `int` di Python, dan bukan string `"3"`. + +Sehingga dengan deklarasi tipe data **FastAPI** memberikan request otomatis "parsing". + +/// + +## Validasi Data + +Tetapi jika di browser anda akses http://127.0.0.1:8000/items/foo, anda akan melihat pesan kesalahan HTTP: + +```JSON +{ + "detail": [ + { + "type": "int_parsing", + "loc": [ + "path", + "item_id" + ], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "foo", + "url": "https://errors.pydantic.dev/2.1/v/int_parsing" + } + ] +} +``` + +Karena parameter path `item_id` bernilai `"foo"` yang bukan tipe data `int`. + +Kesalahan yang sama akan muncul jika menggunakan `float` daripada `int`, seperti di: http://127.0.0.1:8000/items/4.2 + +/// check | Periksa + +Dengan deklarasi tipe data Python, **FastAPI** melakukan validasi data. + +Perhatikan kesalahan tersebut juga menjelaskan validasi apa yang tidak sesuai. + +Validasi ini sangat membantu ketika mengembangkan dan men-*debug* kode yang berhubungan dengan API anda. + +/// + +## Dokumentasi + +Ketika anda membuka browser di http://127.0.0.1:8000/docs, anda melihat dokumentasi API interaktif otomatis berikut: + + + +/// check | Periksa + +Dengan deklarasi tipe data Python yang sama, **FastAPI** membuat dokumentasi interaktif otomatis (terintegrasi Swagger UI). + +Perhatikan parameter path dideklarasikan sebagai integer. + +/// + +## Keuntungan basis-standar, dokumentasi alternatif + +Karena skema yang dibuat berasal dari standar OpenAPI, maka banyak alat lain yang kompatibel. + +Sehingga **FastAPI** menyediakan dokumentasi alternatif (menggunakan ReDoc), yang bisa diakses di http://127.0.0.1:8000/redoc: + + + +Cara yang sama untuk menggunakan tools kompatibel lainnya. Termasuk alat membuat kode otomatis untuk banyak bahasa. + +## Pydantic + +Semua validasi data dikerjakan di belakang layar oleh Pydantic, sehingga anda mendapatkan banyak kemudahan. Anda juga tahu proses ini akan ditangani dengan baik. + +Anda bisa mendeklarasikan tipe data dengan `str`, `float`, `bool` dan banyak tipe data kompleks lainnya. + +Beberapa tipe di atas akan dibahas pada bab berikutnya tutorial ini. + +## Urutan berpengaruh + +Ketika membuat *operasi path*, anda bisa menghadapi kondisi dimana *path* nya sudah tetap. + +Seperti `/users/me`, untuk mendapatkan data user yang sedang aktif. + +Kemudian anda bisa memiliki path `/users/{user_id}` untuk mendapatkan data user tertentu melalui user ID. + +karena *operasi path* dievaluasi melalui urutan, anda harus memastikan path untuk `/users/me` dideklarasikan sebelum `/user/{user_id}`: + +{* ../../docs_src/path_params/tutorial003.py hl[6,11] *} + +Sebaliknya, path `/users/{user_id}` juga akan sesuai dengan `/users/me`, "menganggap" menerima parameter `user_id` dengan nilai `"me"`. + +Serupa, anda juga tidak bisa mendefinisikan operasi path: + +{* ../../docs_src/path_params/tutorial003b.py hl[6,11] *} + +Path pertama akan selalu digunakan karena path sesuai dengan yang pertama. + +## Nilai terdefinisi + +Jika ada *operasi path* yang menerima *parameter path*, tetapi anda ingin nilai valid *parameter path* sudah terdefinisi, anda bisa menggunakan standar Python `Enum`. + +### Membuat class `Enum` + +Import `Enum` dan buat *sub-class* warisan dari `str` dan `Enum`. + +Dengan warisan dari `str` dokumen API mengetahui nilai nya harus berjenis `string` supaya bisa digunakan dengan benar. + +Kemudian buat atribut *class* dengan nilai tetap *string* yang benar: + +{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *} + +/// info + +Enumerasi (atau enum) tersedia di Python sejak versi 3.4. + +/// + +/// tip | Tips + +"AlxexNet", "ResNet", dan "LeNet" adalah nama model *Machine Learning*. + +/// + +### Mendeklarasikan *parameter path* + +Kemudian buat *parameter path* dengan tipe anotasi menggunakan *class* enum dari (`ModelName`) + +{* ../../docs_src/path_params/tutorial005.py hl[16] *} + +### Periksa dokumentasi + +Karena nilai yang tersedia untuk *parameter path* telah terdefinisi, dokumen interatik bisa memunculkan: + + + +### Bekerja dengan *enumarasi* Python + +Nilai *parameter path* akan menjadi *anggota enumerasi*. + +#### Membandingkan *anggota enumerasi* + +Anda bisa membandingkan parameter *path* dengan *anggota enumerasi* di enum `ModelName` yang anda buat: + +{* ../../docs_src/path_params/tutorial005.py hl[17] *} + +#### Mendapatkan *nilai enumerasi* + +Anda bisa mendapatkan nilai (`str` dalam kasus ini) menggunakan `model_name.value`, atau secara umum `anggota_enum_anda.value`: + +{* ../../docs_src/path_params/tutorial005.py hl[20] *} + +/// tip | Tips + +Anda bisa mengakses nilai `"lenet"` dnegan `ModelName.lenet.value`. + +/// + +#### Menghasilkan *anggota enumerasi* + +Anda bisa menghasilkan *anggota enumerasi* dari *operasi path* bahkan di body JSON bersarang (contoh `dict`). + +They will be converted to their corresponding values (strings in this case) before returning them to the client: + +{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *} + +Klien akan mendapatkan respon JSON seperti berikut: + +```JSON +{ + "model_name": "alexnet", + "message": "Deep Learning FTW!" +} +``` + +## Parameter path berisi path + +Misalkan terdapat *operasi path* dengan path `/files/{file_path}`. + +Tetapi anda memerlukan `file_path` itu berisi *path*, seperti like `home/johndoe/myfile.txt`. + +Sehingga URL untuk file tersebut akan seperti: `/files/home/johndoe/myfile.txt`. + +### Dukungan OpenAPI + +OpenAPI tidak bisa mendeklarasikan *parameter path* berisi *path* di dalamnya, karena menyebabkan kondisi yang sulit di*test* dan didefinisikan. + +Tetapi, di **FastAPI** anda tetap bisa melakukannya dengan menggunakan *tools* internal dari Starlette. + +Dan dokumentasi tetap berfungsi walaupun tidak menambahkan keterangan bahwa parameter harus berisi *path*. + +### Konverter path + +Melalui Starlette anda bisa mendeklarasikan *parameter path* berisi *path* dengan URL seperti: + +``` +/files/{file_path:path} +``` + +Dikondisi ini nama parameter adalah `file_path` dan bagian terakhir `:path` menginformasikan parameter harus sesuai dengan setiap *path*. + +Sehingga anda bisa menggunakan: + +{* ../../docs_src/path_params/tutorial004.py hl[6] *} + +/// tip | Tips + +Anda mungkin perlu parameter berisi `/home/johndoe/myfile.txt` di awali garis belakang (`/`). + +Di kondisi ini, URL nya menjadi: `/files//home/johndoe/myfile.txt`, dengan dua garis belakang (`//`) di antara `files` dan `home`. + +/// + +## Ringkasan + +Di **FastAPI** dengan menggunakan deklarasi tipe Python standar, pendek, intuitif, anda mendapatkan: + +* Dukungan editor: pemeriksaan kesalahan, autocompletion, dll. +* "Parsing" data. +* Validasi data. +* Annotasi API dan dokumentasi otomatis. + +Semua itu anda hanya perlu mendeklarasikan sekali saja. + +Ini adalah salah satu keunggulan **FastAPI** dibandingkan dengan *framework* lainnya (selain dari performa Python *native*c) diff --git a/docs/id/docs/tutorial/static-files.md b/docs/id/docs/tutorial/static-files.md new file mode 100644 index 000000000..b55f31394 --- /dev/null +++ b/docs/id/docs/tutorial/static-files.md @@ -0,0 +1,40 @@ +# Berkas Statis + +Anda dapat menyajikan berkas statis secara otomatis dari sebuah direktori menggunakan `StaticFiles`. + +## Penggunaan `StaticFiles` + +* Mengimpor `StaticFiles`. +* "Mount" representatif `StaticFiles()` di jalur spesifik. + +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} + +/// note | Detail Teknis + +Anda dapat pula menggunakan `from starlette.staticfiles import StaticFiles`. + +**FastAPI** menyediakan `starlette.staticfiles` sama seperti `fastapi.staticfiles` sebagai kemudahan pada Anda, yaitu para pengembang. Tetapi ini asli berasal langsung dari Starlette. + +/// + +### Apa itu "Mounting" + +"Mounting" dimaksud menambah aplikasi "independen" secara lengkap di jalur spesifik, kemudian menangani seluruh sub-jalur. + +Hal ini berbeda dari menggunakan `APIRouter` karena aplikasi yang dimount benar-benar independen. OpenAPI dan dokumentasi dari aplikasi utama Anda tak akan menyertakan apa pun dari aplikasi yang dimount, dst. + +Anda dapat mempelajari mengenai ini dalam [Panduan Pengguna Lanjutan](../advanced/index.md){.internal-link target=_blank}. + +## Detail + +Terhadap `"/static"` pertama mengacu pada sub-jalur yang akan menjadi tempat "sub-aplikasi" ini akan "dimount". Maka, jalur apa pun yang dimulai dengan `"/static"` akan ditangani oleh sub-jalur tersebut. + +Terhadap `directory="static"` mengacu pada nama direktori yang berisi berkas statis Anda. + +Terhadap `name="static"` ialah nama yang dapat digunakan secara internal oleh **FastAPI**. + +Seluruh parameter ini dapat berbeda dari sekadar "`static`", sesuaikan parameter dengan keperluan dan detail spesifik akan aplikasi Anda. + +## Info lanjutan + +Sebagai detail dan opsi tambahan lihat dokumentasi Starlette perihal Berkas Statis. diff --git a/docs/it/docs/index.md b/docs/it/docs/index.md new file mode 100644 index 000000000..dc8f5b846 --- /dev/null +++ b/docs/it/docs/index.md @@ -0,0 +1,463 @@ +

+ FastAPI +

+

+ FastAPI framework, alte prestazioni, facile da imparare, rapido da implementare, pronto per il rilascio in produzione +

+ +

+ + Test + + + Coverage + + + Package version + + + Supported Python versions + +

+ +--- + +**Documentazione**: https://fastapi.tiangolo.com + +**Codice Sorgente**: https://github.com/fastapi/fastapi + +--- + +FastAPI è un web framework moderno e veloce (a prestazioni elevate) che serve a creare API con Python 3.6+ basato sulle annotazioni di tipo di Python. + +Le sue caratteristiche principali sono: + +* **Velocità**: Prestazioni molto elevate, alla pari di **NodeJS** e **Go** (grazie a Starlette e Pydantic). [Uno dei framework Python più veloci in circolazione](#performance). +* **Veloce da programmare**: Velocizza il lavoro consentendo il rilascio di nuove funzionalità tra il 200% e il 300% più rapidamente. * +* **Meno bug**: Riduce di circa il 40% gli errori che commettono gli sviluppatori durante la scrittura del codice. * +* **Intuitivo**: Grande supporto per gli editor di testo con autocompletamento in ogni dove. In questo modo si può dedicare meno tempo al debugging. +* **Facile**: Progettato per essere facile da usare e imparare. Si riduce il tempo da dedicare alla lettura della documentazione. +* **Sintentico**: Minimizza la duplicazione di codice. Molteplici funzionalità, ognuna con la propria dichiarazione dei parametri. Meno errori. +* **Robusto**: Crea codice pronto per la produzione con documentazione automatica interattiva. +* **Basato sugli standard**: Basato su (e completamente compatibile con) gli open standard per le API: OpenAPI (precedentemente Swagger) e JSON Schema. + +* Stima basata sull'esito di test eseguiti su codice sorgente di applicazioni rilasciate in produzione da un team interno di sviluppatori. + +## Sponsor + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} + +{% endfor -%} +{%- for sponsor in sponsors.silver -%} + +{% endfor %} +{% endif %} + + + +Altri sponsor + +## Recensioni + +"_[...] 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._" + +
Kabir Khan - Microsoft (ref)
+ +--- + +"_We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]_" + +
Piero Molino, Yaroslav Dudin, e Sai Sumanth Miryala - Uber (ref)
+ +--- + +"_**Netflix** is pleased to announce the open-source release of our **crisis management** orchestration framework: **Dispatch**! [built with **FastAPI**]_" + +
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (ref)
+ +--- + +"_I’m over the moon excited about **FastAPI**. It’s so fun!_" + +
Brian Okken - Python Bytes podcast host (ref)
+ +--- + +"_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._" + +
Timothy Crosley - Hug creator (ref)
+ +--- + +"_If you're looking to learn one **modern framework** for building REST APIs, check out **FastAPI** [...] It's fast, easy to use and easy to learn [...]_" + +"_We've switched over to **FastAPI** for our **APIs** [...] I think you'll like it [...]_" + +
Ines Montani - Matthew Honnibal - Explosion AI founders - spaCy creators (ref) - (ref)
+ +--- + +## **Typer**, la FastAPI delle CLI + + + +Se stai sviluppando un'app CLI da usare nel terminale invece che una web API, ti consigliamo **Typer**. + +**Typer** è il fratello minore di FastAPI. Ed è stato ideato per essere la **FastAPI delle CLI**. ⌨️ 🚀 + +## Requisiti + +Python 3.6+ + +FastAPI è basata su importanti librerie: + +* Starlette per le parti web. +* Pydantic per le parti dei dati. + +## Installazione + +
+ +```console +$ pip install fastapi + +---> 100% +``` + +
+ +Per il rilascio in produzione, sarà necessario un server ASGI come Uvicorn oppure Hypercorn. + +
+ +```console +$ pip install uvicorn[standard] + +---> 100% +``` + +
+ +## Esempio + +### Crea un file + +* Crea un file `main.py` con: + +```Python +from fastapi import FastAPI +from typing import Optional + +app = FastAPI() + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: str = Optional[None]): + return {"item_id": item_id, "q": q} +``` + +
+Oppure usa async def... + +Se il tuo codice usa `async` / `await`, allora usa `async def`: + +```Python hl_lines="7 12" +from fastapi import FastAPI +from typing import Optional + +app = FastAPI() + + +@app.get("/") +async def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +async def read_item(item_id: int, q: Optional[str] = None): + return {"item_id": item_id, "q": q} +``` + +**Nota**: + +e vuoi approfondire, consulta la sezione _"In a hurry?"_ su `async` e `await` nella documentazione. + +
+ +### Esegui il server + +Puoi far partire il server così: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [28720] +INFO: Started server process [28722] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +
+Informazioni sul comando uvicorn main:app --reload... + +Vediamo il comando `uvicorn main:app` in dettaglio: + +* `main`: il file `main.py` (il "modulo" Python). +* `app`: l'oggetto creato dentro `main.py` con la riga di codice `app = FastAPI()`. +* `--reload`: ricarica il server se vengono rilevati cambiamenti del codice. Usalo solo durante la fase di sviluppo. + +
+ +### Testa l'API + +Apri il browser all'indirizzo http://127.0.0.1:8000/items/5?q=somequery. + +Vedrai la seguente risposta JSON: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +Hai appena creato un'API che: + +* Riceve richieste HTTP sui _paths_ `/` and `/items/{item_id}`. +* Entrambi i _paths_ accettano`GET` operations (conosciuti anche come HTTP _methods_). +* Il _path_ `/items/{item_id}` ha un _path parameter_ `item_id` che deve essere un `int`. +* Il _path_ `/items/{item_id}` ha una `str` _query parameter_ `q`. + +### Documentazione interattiva dell'API + +Adesso vai all'indirizzo http://127.0.0.1:8000/docs. + +Vedrai la documentazione interattiva dell'API (offerta da Swagger UI): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### Documentazione interattiva alternativa + +Adesso accedi all'url http://127.0.0.1:8000/redoc. + +Vedrai la documentazione interattiva dell'API (offerta da ReDoc): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## Esempio più avanzato + +Adesso modifica il file `main.py` per ricevere un _body_ da una richiesta `PUT`. + +Dichiara il _body_ usando le annotazioni di tipo standard di Python, grazie a Pydantic. + +```Python hl_lines="2 7-10 23-25" +from fastapi import FastAPI +from pydantic import BaseModel +from typing import Optional + +app = FastAPI() + + +class Item(BaseModel): + name: str + price: float + is_offer: bool = Optional[None] + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Optional[str] = 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} +``` + +Il server dovrebbe ricaricarsi in automatico (perché hai specificato `--reload` al comando `uvicorn` lanciato precedentemente). + +### Aggiornamento della documentazione interattiva + +Adesso vai su http://127.0.0.1:8000/docs. + +* La documentazione interattiva dell'API verrà automaticamente aggiornata, includendo il nuovo _body_: + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* Fai click sul pulsante "Try it out", che ti permette di inserire i parametri per interagire direttamente con l'API: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) + +* Successivamente, premi sul pulsante "Execute". L'interfaccia utente comunicherà con la tua API, invierà i parametri, riceverà i risultati della richiesta, e li mostrerà sullo schermo: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) + +### Aggiornamento della documentazione alternativa + +Ora vai su http://127.0.0.1:8000/redoc. + +* Anche la documentazione alternativa dell'API mostrerà il nuovo parametro della query e il _body_: + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### Riepilogo + +Ricapitolando, è sufficiente dichiarare **una sola volta** i tipi dei parametri, del body, ecc. come parametri di funzioni. + +Questo con le annotazioni per i tipi standard di Python. + +Non c'è bisogno di imparare una nuova sintassi, metodi o classi specifici a una libreria, ecc. + +È normalissimo **Python 3.6+**. + +Per esempio, per un `int`: + +```Python +item_id: int +``` + +o per un modello `Item` più complesso: + +```Python +item: Item +``` + +...e con quella singola dichiarazione hai in cambio: + +* Supporto per gli editor di testo, incluso: + * Autocompletamento. + * Controllo sulle annotazioni di tipo. +* Validazione dei dati: + * Errori chiari e automatici quando i dati sono invalidi. + * Validazione anche per gli oggetti JSON più complessi. +* Conversione dei dati di input: da risorse esterne a dati e tipi di Python. È possibile leggere da: + * JSON. + * Path parameters. + * Query parameters. + * Cookies. + * Headers. + * Form. + * File. +* Conversione dei dati di output: converte dati e tipi di Python a dati per la rete (come JSON): + * Converte i tipi di Python (`str`, `int`, `float`, `bool`, `list`, ecc). + * Oggetti `datetime`. + * Oggetti `UUID`. + * Modelli del database. + * ...e molto di più. +* Generazione di una documentazione dell'API interattiva, con scelta dell'interfaccia grafica: + * Swagger UI. + * ReDoc. + +--- + +Tornando al precedente esempio, **FastAPI**: + +* Validerà che esiste un `item_id` nel percorso delle richieste `GET` e `PUT`. +* Validerà che `item_id` sia di tipo `int` per le richieste `GET` e `PUT`. + * Se non lo è, il client vedrà un errore chiaro e utile. +* Controllerà se ci sia un parametro opzionale chiamato `q` (per esempio `http://127.0.0.1:8000/items/foo?q=somequery`) per le richieste `GET`. + * Siccome il parametro `q` è dichiarato con `= None`, è opzionale. + * Senza il `None` sarebbe stato obbligatorio (come per il body della richiesta `PUT`). +* Per le richieste `PUT` su `/items/{item_id}`, leggerà il body come JSON, questo comprende: + * verifica che la richiesta abbia un attributo obbligatorio `name` e che sia di tipo `str`. + * verifica che la richiesta abbia un attributo obbligatorio `price` e che sia di tipo `float`. + * verifica che la richiesta abbia un attributo opzionale `is_offer` e che sia di tipo `bool`, se presente. + * Tutto questo funzionerebbe anche con oggetti JSON più complessi. +* Convertirà *da* e *a* JSON automaticamente. +* Documenterà tutto con OpenAPI, che può essere usato per: + * Sistemi di documentazione interattivi. + * Sistemi di generazione di codice dal lato client, per molti linguaggi. +* Fornirà 2 interfacce di documentazione dell'API interattive. + +--- + +Questa è solo la punta dell'iceberg, ma dovresti avere già un'idea di come il tutto funzioni. + +Prova a cambiare questa riga di codice: + +```Python + return {"item_name": item.name, "item_id": item_id} +``` + +...da: + +```Python + ... "item_name": item.name ... +``` + +...a: + +```Python + ... "item_price": item.price ... +``` + +...e osserva come il tuo editor di testo autocompleterà gli attributi e sarà in grado di riconoscere i loro tipi: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +Per un esempio più completo che mostra più funzionalità del framework, consulta Tutorial - Guida Utente. + +**Spoiler alert**: il tutorial - Guida Utente include: + +* Dichiarazione di **parameters** da altri posti diversi come: **headers**, **cookies**, **form fields** e **files**. +* Come stabilire **vincoli di validazione** come `maximum_length` o `regex`. +* Un sistema di **Dependency Injection** facile da usare e molto potente. +e potente. +* Sicurezza e autenticazione, incluso il supporto per **OAuth2** con **token JWT** e autenticazione **HTTP Basic**. +* Tecniche più avanzate (ma ugualmente semplici) per dichiarare **modelli JSON altamente nidificati** (grazie a Pydantic). +* E altre funzionalità (grazie a Starlette) come: + * **WebSockets** + * **GraphQL** + * test molto facili basati su `requests` e `pytest` + * **CORS** + * **Cookie Sessions** + * ...e altro ancora. + +## Prestazioni + +Benchmark indipendenti di TechEmpower mostrano che **FastAPI** basato su Uvicorn è uno dei framework Python più veloci in circolazione, solamente dietro a Starlette e Uvicorn (usate internamente da FastAPI). (*) + +Per approfondire, consulta la sezione Benchmarks. + +## Dipendenze opzionali + +Usate da Pydantic: + +* email-validator - per la validazione di email. + +Usate da Starlette: + +* requests - Richiesto se vuoi usare il `TestClient`. +* aiofiles - Richiesto se vuoi usare `FileResponse` o `StaticFiles`. +* jinja2 - Richiesto se vuoi usare la configurazione template di default. +* python-multipart - Richiesto se vuoi supportare il "parsing" con `request.form()`. +* itsdangerous - Richiesto per usare `SessionMiddleware`. +* pyyaml - Richiesto per il supporto dello `SchemaGenerator` di Starlette (probabilmente non ti serve con FastAPI). +* graphene - Richiesto per il supporto di `GraphQLApp`. + +Usate da FastAPI / Starlette: + +* uvicorn - per il server che carica e serve la tua applicazione. +* orjson - ichiesto se vuoi usare `ORJSONResponse`. +* ujson - Richiesto se vuoi usare `UJSONResponse`. + +Puoi installarle tutte con `pip install fastapi[all]`. + +## Licenza + +Questo progetto è concesso in licenza in base ai termini della licenza MIT. diff --git a/docs/it/mkdocs.yml b/docs/it/mkdocs.yml new file mode 100644 index 000000000..de18856f4 --- /dev/null +++ b/docs/it/mkdocs.yml @@ -0,0 +1 @@ +INHERIT: ../en/mkdocs.yml diff --git a/docs/ja/docs/advanced/additional-status-codes.md b/docs/ja/docs/advanced/additional-status-codes.md index d1f8e6451..33457f591 100644 --- a/docs/ja/docs/advanced/additional-status-codes.md +++ b/docs/ja/docs/advanced/additional-status-codes.md @@ -14,21 +14,25 @@ これを達成するには、 `JSONResponse` をインポートし、 `status_code` を設定して直接内容を返します。 -```Python hl_lines="4 25" -{!../../../docs_src/additional_status_codes/tutorial001.py!} -``` +{* ../../docs_src/additional_status_codes/tutorial001.py hl[4,25] *} -!!! warning "注意" - 上記の例のように `Response` を明示的に返す場合、それは直接返されます。 +/// warning | 注意 - モデルなどはシリアライズされません。 +上記の例のように `Response` を明示的に返す場合、それは直接返されます。 - 必要なデータが含まれていることや、値が有効なJSONであること (`JSONResponse` を使う場合) を確認してください。 +モデルなどはシリアライズされません。 -!!! note "技術詳細" - `from starlette.responses import JSONResponse` を利用することもできます。 +必要なデータが含まれていることや、値が有効なJSONであること (`JSONResponse` を使う場合) を確認してください。 - **FastAPI** は `fastapi.responses` と同じ `starlette.responses` を、開発者の利便性のために提供しています。しかし有効なレスポンスはほとんどStarletteから来ています。 `status` についても同じです。 +/// + +/// note | 技術詳細 + +`from starlette.responses import JSONResponse` を利用することもできます。 + +**FastAPI** は `fastapi.responses` と同じ `starlette.responses` を、開発者の利便性のために提供しています。しかし有効なレスポンスはほとんどStarletteから来ています。 `status` についても同じです。 + +/// ## OpenAPIとAPIドキュメント diff --git a/docs/ja/docs/advanced/custom-response.md b/docs/ja/docs/advanced/custom-response.md index d8b47629a..1b2cd914d 100644 --- a/docs/ja/docs/advanced/custom-response.md +++ b/docs/ja/docs/advanced/custom-response.md @@ -12,8 +12,11 @@ そしてもし、`Response` が、`JSONResponse` や `UJSONResponse` の場合のようにJSONメディアタイプ (`application/json`) ならば、データは *path operationデコレータ* に宣言したPydantic `response_model` により自動的に変換 (もしくはフィルタ) されます。 -!!! note "備考" - メディアタイプを指定せずにレスポンスクラスを利用すると、FastAPIは何もコンテンツがないことを期待します。そのため、生成されるOpenAPIドキュメントにレスポンスフォーマットが記載されません。 +/// note | 備考 + +メディアタイプを指定せずにレスポンスクラスを利用すると、FastAPIは何もコンテンツがないことを期待します。そのため、生成されるOpenAPIドキュメントにレスポンスフォーマットが記載されません。 + +/// ## `ORJSONResponse` を使う @@ -21,19 +24,23 @@ 使いたい `Response` クラス (サブクラス) をインポートし、 *path operationデコレータ* に宣言します。 -```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial001b.py!} -``` +{* ../../docs_src/custom_response/tutorial001b.py hl[2,7] *} + +/// info | 情報 + +パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用することもできます。 + +この場合、HTTPヘッダー `Content-Type` には `application/json` がセットされます。 + +そして、OpenAPIにはそのようにドキュメントされます。 -!!! info "情報" - パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用することもできます。 +/// - この場合、HTTPヘッダー `Content-Type` には `application/json` がセットされます。 +/// tip | 豆知識 - そして、OpenAPIにはそのようにドキュメントされます。 +`ORJSONResponse` は、現在はFastAPIのみで利用可能で、Starletteでは利用できません。 -!!! tip "豆知識" - `ORJSONResponse` は、現在はFastAPIのみで利用可能で、Starletteでは利用できません。 +/// ## HTMLレスポンス @@ -42,16 +49,17 @@ * `HTMLResponse` をインポートする。 * *path operation* のパラメータ `content_type` に `HTMLResponse` を渡す。 -```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial002.py!} -``` +{* ../../docs_src/custom_response/tutorial002.py hl[2,7] *} -!!! info "情報" - パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用されます。 +/// info | 情報 - この場合、HTTPヘッダー `Content-Type` には `text/html` がセットされます。 +パラメータ `response_class` は、レスポンスの「メディアタイプ」を定義するために利用されます。 - そして、OpenAPIにはそのようにドキュメント化されます。 +この場合、HTTPヘッダー `Content-Type` には `text/html` がセットされます。 + +そして、OpenAPIにはそのようにドキュメント化されます。 + +/// ### `Response` を返す @@ -59,15 +67,19 @@ 上記と同じ例において、 `HTMLResponse` を返すと、このようになります: -```Python hl_lines="2 7 19" -{!../../../docs_src/custom_response/tutorial003.py!} -``` +{* ../../docs_src/custom_response/tutorial003.py hl[2,7,19] *} + +/// warning | 注意 + +*path operation関数* から直接返される `Response` は、OpenAPIにドキュメントされず (例えば、 `Content-Type` がドキュメントされない) 、自動的な対話的ドキュメントからも閲覧できません。 + +/// -!!! warning "注意" - *path operation関数* から直接返される `Response` は、OpenAPIにドキュメントされず (例えば、 `Content-Type` がドキュメントされない) 、自動的な対話的ドキュメントからも閲覧できません。 +/// info | 情報 -!!! info "情報" - もちろん、実際の `Content-Type` ヘッダーやステータスコードなどは、返された `Response` オブジェクトに由来しています。 +もちろん、実際の `Content-Type` ヘッダーやステータスコードなどは、返された `Response` オブジェクトに由来しています。 + +/// ### OpenAPIドキュメントと `Response` のオーバーライド @@ -79,9 +91,7 @@ 例えば、このようになります: -```Python hl_lines="7 21 23" -{!../../../docs_src/custom_response/tutorial004.py!} -``` +{* ../../docs_src/custom_response/tutorial004.py hl[7,21,23] *} この例では、関数 `generate_html_response()` は、`str` のHTMLを返すのではなく `Response` を生成して返しています。 @@ -97,10 +107,13 @@ `Response` を使って他の何かを返せますし、カスタムのサブクラスも作れることを覚えておいてください。 -!!! note "技術詳細" - `from starlette.responses import HTMLResponse` も利用できます。 +/// note | 技術詳細 + +`from starlette.responses import HTMLResponse` も利用できます。 + +**FastAPI** は開発者の利便性のために `fastapi.responses` として `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。 - **FastAPI** は開発者の利便性のために `fastapi.responses` として `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。 +/// ### `Response` @@ -117,9 +130,7 @@ FastAPI (実際にはStarlette) は自動的にContent-Lengthヘッダーを含みます。また、media_typeに基づいたContent-Typeヘッダーを含み、テキストタイプのためにcharsetを追加します。 -```Python hl_lines="1 18" -{!../../../docs_src/response_directly/tutorial002.py!} -``` +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} ### `HTMLResponse` @@ -129,9 +140,7 @@ FastAPI (実際にはStarlette) は自動的にContent-Lengthヘッダーを含 テキストやバイトを受け取り、プレーンテキストのレスポンスを返します。 -```Python hl_lines="2 7 9" -{!../../../docs_src/custom_response/tutorial005.py!} -``` +{* ../../docs_src/custom_response/tutorial005.py hl[2,7,9] *} ### `JSONResponse` @@ -147,31 +156,31 @@ FastAPI (実際にはStarlette) は自動的にContent-Lengthヘッダーを含 `ujson`を使った、代替のJSONレスポンスです。 -!!! warning "注意" - `ujson` は、いくつかのエッジケースの取り扱いについて、Pythonにビルトインされた実装よりも作りこまれていません。 +/// warning | 注意 + +`ujson` は、いくつかのエッジケースの取り扱いについて、Pythonにビルトインされた実装よりも作りこまれていません。 + +/// + +{* ../../docs_src/custom_response/tutorial001.py hl[2,7] *} -```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial001.py!} -``` +/// tip | 豆知識 -!!! tip "豆知識" - `ORJSONResponse` のほうが高速な代替かもしれません。 +`ORJSONResponse` のほうが高速な代替かもしれません。 + +/// ### `RedirectResponse` HTTPリダイレクトを返します。デフォルトでは307ステータスコード (Temporary Redirect) となります。 -```Python hl_lines="2 9" -{!../../../docs_src/custom_response/tutorial006.py!} -``` +{* ../../docs_src/custom_response/tutorial006.py hl[2,9] *} ### `StreamingResponse` 非同期なジェネレータか通常のジェネレータ・イテレータを受け取り、レスポンスボディをストリームします。 -```Python hl_lines="2 14" -{!../../../docs_src/custom_response/tutorial007.py!} -``` +{* ../../docs_src/custom_response/tutorial007.py hl[2,14] *} #### `StreamingResponse` をファイルライクなオブジェクトとともに使う @@ -179,12 +188,13 @@ HTTPリダイレクトを返します。デフォルトでは307ステータス これにはクラウドストレージとの連携や映像処理など、多くのライブラリが含まれています。 -```Python hl_lines="2 10-12 14" -{!../../../docs_src/custom_response/tutorial008.py!} -``` +{* ../../docs_src/custom_response/tutorial008.py hl[2,10:12,14] *} + +/// tip | 豆知識 + +ここでは `async` や `await` をサポートしていない標準の `open()` を使っているので、通常の `def` でpath operationを宣言していることに注意してください。 -!!! tip "豆知識" - ここでは `async` や `await` をサポートしていない標準の `open()` を使っているので、通常の `def` でpath operationを宣言していることに注意してください。 +/// ### `FileResponse` @@ -199,9 +209,7 @@ HTTPリダイレクトを返します。デフォルトでは307ステータス ファイルレスポンスには、適切な `Content-Length` 、 `Last-Modified` 、 `ETag` ヘッダーが含まれます。 -```Python hl_lines="2 10" -{!../../../docs_src/custom_response/tutorial009.py!} -``` +{* ../../docs_src/custom_response/tutorial009.py hl[2,10] *} ## デフォルトレスポンスクラス @@ -211,12 +219,13 @@ HTTPリダイレクトを返します。デフォルトでは307ステータス 以下の例では、 **FastAPI** は、全ての *path operation* で `JSONResponse` の代わりに `ORJSONResponse` をデフォルトとして利用します。 -```Python hl_lines="2 4" -{!../../../docs_src/custom_response/tutorial010.py!} -``` +{* ../../docs_src/custom_response/tutorial010.py hl[2,4] *} + +/// tip | 豆知識 + +前に見たように、 *path operation* の中で `response_class` をオーバーライドできます。 -!!! tip "豆知識" - 前に見たように、 *path operation* の中で `response_class` をオーバーライドできます。 +/// ## その他のドキュメント diff --git a/docs/ja/docs/advanced/index.md b/docs/ja/docs/advanced/index.md index 0732fc405..22eaf6eb8 100644 --- a/docs/ja/docs/advanced/index.md +++ b/docs/ja/docs/advanced/index.md @@ -2,18 +2,21 @@ ## さらなる機能 -[チュートリアル - ユーザーガイド](../tutorial/){.internal-link target=_blank}により、**FastAPI**の主要な機能は十分に理解できたことでしょう。 +[チュートリアル - ユーザーガイド](../tutorial/index.md){.internal-link target=_blank}により、**FastAPI**の主要な機能は十分に理解できたことでしょう。 以降のセクションでは、チュートリアルでは説明しきれなかったオプションや設定、および機能について説明します。 -!!! tip "豆知識" - 以降のセクションは、 **必ずしも"応用編"ではありません**。 +/// tip | 豆知識 - ユースケースによっては、その中から解決策を見つけられるかもしれません。 +以降のセクションは、 **必ずしも"応用編"ではありません**。 + +ユースケースによっては、その中から解決策を見つけられるかもしれません。 + +/// ## 先にチュートリアルを読む -[チュートリアル - ユーザーガイド](../tutorial/){.internal-link target=_blank}の知識があれば、**FastAPI**の主要な機能を利用することができます。 +[チュートリアル - ユーザーガイド](../tutorial/index.md){.internal-link target=_blank}の知識があれば、**FastAPI**の主要な機能を利用することができます。 以降のセクションは、すでにチュートリアルを読んで、その主要なアイデアを理解できていることを前提としています。 diff --git a/docs/ja/docs/advanced/nosql-databases.md b/docs/ja/docs/advanced/nosql-databases.md deleted file mode 100644 index fbd76e96b..000000000 --- a/docs/ja/docs/advanced/nosql-databases.md +++ /dev/null @@ -1,156 +0,0 @@ -# NoSQL (分散 / ビッグデータ) Databases - -**FastAPI** はあらゆる NoSQLと統合することもできます。 - -ここではドキュメントベースのNoSQLデータベースである**Couchbase**を使用した例を見てみましょう。 - -他にもこれらのNoSQLデータベースを利用することが出来ます: - -* **MongoDB** -* **Cassandra** -* **CouchDB** -* **ArangoDB** -* **ElasticSearch** など。 - -!!! tip "豆知識" - **FastAPI**と**Couchbase**を使った公式プロジェクト・ジェネレータがあります。すべて**Docker**ベースで、フロントエンドやその他のツールも含まれています: https://github.com/tiangolo/full-stack-fastapi-couchbase - -## Couchbase コンポーネントの Import - -まずはImportしましょう。今はその他のソースコードに注意を払う必要はありません。 - -```Python hl_lines="3-5" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -## "document type" として利用する定数の定義 - -documentで利用する固定の`type`フィールドを用意しておきます。 - -これはCouchbaseで必須ではありませんが、後々の助けになるベストプラクティスです。 - -```Python hl_lines="9" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -## `Bucket` を取得する関数の追加 - -**Couchbase**では、bucketはdocumentのセットで、様々な種類のものがあります。 - -Bucketは通常、同一のアプリケーション内で互いに関係を持っています。 - -リレーショナルデータベースの世界でいう"database"(データベースサーバではなく特定のdatabase)と類似しています。 - -**MongoDB** で例えると"collection"と似た概念です。 - -次のコードでは主に `Bucket` を利用してCouchbaseを操作します。 - -この関数では以下の処理を行います: - -* **Couchbase** クラスタ(1台の場合もあるでしょう)に接続 - * タイムアウトのデフォルト値を設定 -* クラスタで認証を取得 -* `Bucket` インスタンスを取得 - * タイムアウトのデフォルト値を設定 -* 作成した`Bucket`インスタンスを返却 - -```Python hl_lines="12-21" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -## Pydantic モデルの作成 - -**Couchbase**のdocumentは実際には単にJSONオブジェクトなのでPydanticを利用してモデルに出来ます。 - -### `User` モデル - -まずは`User`モデルを作成してみましょう: - -```Python hl_lines="24-28" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -このモデルは*path operation*に使用するので`hashed_password`は含めません。 - -### `UserInDB` モデル - -それでは`UserInDB`モデルを作成しましょう。 - -こちらは実際にデータベースに保存されるデータを保持します。 - -`User`モデルの持つ全ての属性に加えていくつかの属性を追加するのでPydanticの`BaseModel`を継承せずに`User`のサブクラスとして定義します: - -```Python hl_lines="31-33" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -!!! note "備考" - データベースに保存される`hashed_password`と`type`フィールドを`UserInDB`モデルに保持させていることに注意してください。 - - しかしこれらは(*path operation*で返却する)一般的な`User`モデルには含まれません - -## user の取得 - -それでは次の関数を作成しましょう: - -* username を取得する -* username を利用してdocumentのIDを生成する -* 作成したIDでdocumentを取得する -* documentの内容を`UserInDB`モデルに設定する - -*path operation関数*とは別に、`username`(またはその他のパラメータ)からuserを取得することだけに特化した関数を作成することで、より簡単に複数の部分で再利用したりユニットテストを追加することができます。 - -```Python hl_lines="36-42" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -### f-strings - -`f"userprofile::{username}"` という記載に馴染みがありませんか?これは Python の"f-string"と呼ばれるものです。 - -f-stringの`{}`の中に入れられた変数は、文字列の中に展開/注入されます。 - -### `dict` アンパック - -`UserInDB(**result.value)`という記載に馴染みがありませんか?これは`dict`の"アンパック"と呼ばれるものです。 - -これは`result.value`の`dict`からそのキーと値をそれぞれ取りキーワード引数として`UserInDB`に渡します。 - -例えば`dict`が下記のようになっていた場合: - -```Python -{ - "username": "johndoe", - "hashed_password": "some_hash", -} -``` - -`UserInDB`には次のように渡されます: - -```Python -UserInDB(username="johndoe", hashed_password="some_hash") -``` - -## **FastAPI** コードの実装 - -### `FastAPI` app の作成 - -```Python hl_lines="46" -{!../../../docs_src/nosql_databases/tutorial001.py!} -``` - -### *path operation関数*の作成 - -私たちのコードはCouchbaseを呼び出しており、実験的なPython 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/advanced/path-operation-advanced-configuration.md b/docs/ja/docs/advanced/path-operation-advanced-configuration.md index 35b381cae..05188d5b2 100644 --- a/docs/ja/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/ja/docs/advanced/path-operation-advanced-configuration.md @@ -2,16 +2,17 @@ ## OpenAPI operationId -!!! warning "注意" - あなたがOpenAPIの「エキスパート」でなければ、これは必要ないかもしれません。 +/// warning | 注意 + +あなたがOpenAPIの「エキスパート」でなければ、これは必要ないかもしれません。 + +/// *path operation* で `operation_id` パラメータを利用することで、OpenAPIの `operationId` を設定できます。 `operation_id` は各オペレーションで一意にする必要があります。 -```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *} ### *path operation関数* の名前をoperationIdとして使用する @@ -19,25 +20,27 @@ APIの関数名を `operationId` として利用したい場合、すべてのAP そうする場合は、すべての *path operation* を追加した後に行う必要があります。 -```Python hl_lines="2 12-21 24" -{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2,12:21,24] *} + +/// tip | 豆知識 + +`app.openapi()` を手動でコールする場合、その前に`operationId`を更新する必要があります。 + +/// + +/// warning | 注意 -!!! tip "豆知識" - `app.openapi()` を手動でコールする場合、その前に`operationId`を更新する必要があります。 +この方法をとる場合、各 *path operation関数* が一意な名前である必要があります。 -!!! warning "注意" - この方法をとる場合、各 *path operation関数* が一意な名前である必要があります。 +それらが異なるモジュール (Pythonファイル) にあるとしてもです。 - それらが異なるモジュール (Pythonファイル) にあるとしてもです。 +/// ## OpenAPIから除外する 生成されるOpenAPIスキーマ (つまり、自動ドキュメント生成の仕組み) から *path operation* を除外するには、 `include_in_schema` パラメータを `False` にします。 -```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *} ## docstringによる説明の高度な設定 @@ -47,6 +50,4 @@ APIの関数名を `operationId` として利用したい場合、すべてのAP ドキュメントには表示されませんが、他のツール (例えばSphinx) では残りの部分を利用できるでしょう。 -```Python hl_lines="19-29" -{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19:29] *} diff --git a/docs/ja/docs/advanced/response-directly.md b/docs/ja/docs/advanced/response-directly.md index 10ec88548..42412d507 100644 --- a/docs/ja/docs/advanced/response-directly.md +++ b/docs/ja/docs/advanced/response-directly.md @@ -14,8 +14,11 @@ 実際は、`Response` やそのサブクラスを返すことができます。 -!!! tip "豆知識" - `JSONResponse` それ自体は、 `Response` のサブクラスです。 +/// tip | 豆知識 + +`JSONResponse` それ自体は、 `Response` のサブクラスです。 + +/// `Response` を返した場合は、**FastAPI** は直接それを返します。 @@ -31,14 +34,15 @@ このようなケースでは、レスポンスにデータを含める前に `jsonable_encoder` を使ってデータを変換できます。 -```Python hl_lines="6-7 21-22" -{!../../../docs_src/response_directly/tutorial001.py!} -``` +{* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *} + +/// note | 技術詳細 + +また、`from starlette.responses import JSONResponse` も利用できます。 -!!! note "技術詳細" - また、`from starlette.responses import JSONResponse` も利用できます。 +**FastAPI** は開発者の利便性のために `fastapi.responses` という `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。 - **FastAPI** は開発者の利便性のために `fastapi.responses` という `starlette.responses` と同じものを提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。 +/// ## カスタム `Response` を返す @@ -50,9 +54,7 @@ XMLを文字列にし、`Response` に含め、それを返します。 -```Python hl_lines="1 18" -{!../../../docs_src/response_directly/tutorial002.py!} -``` +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} ## 備考 diff --git a/docs/ja/docs/advanced/websockets.md b/docs/ja/docs/advanced/websockets.md index 65e4112a6..43009eba8 100644 --- a/docs/ja/docs/advanced/websockets.md +++ b/docs/ja/docs/advanced/websockets.md @@ -38,30 +38,27 @@ $ pip install websockets しかし、これはWebSocketのサーバーサイドに焦点を当て、実用的な例を示す最も簡単な方法です。 -```Python hl_lines="2 6-38 41-43" -{!../../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[2,6:38,41:43] *} ## `websocket` を作成する **FastAPI** アプリケーションで、`websocket` を作成します。 -```Python hl_lines="1 46-47" -{!../../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[1,46:47] *} + +/// note | 技術詳細 + +`from starlette.websockets import WebSocket` を使用しても構いません. -!!! note "技術詳細" - `from starlette.websockets import WebSocket` を使用しても構いません. +**FastAPI** は開発者の利便性のために、同じ `WebSocket` を提供します。しかし、こちらはStarletteから直接提供されるものです。 - **FastAPI** は開発者の利便性のために、同じ `WebSocket` を提供します。しかし、こちらはStarletteから直接提供されるものです。 +/// ## メッセージの送受信 WebSocketルートでは、 `await` を使ってメッセージの送受信ができます。 -```Python hl_lines="48-52" -{!../../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[48:52] *} バイナリやテキストデータ、JSONデータを送受信できます。 @@ -112,16 +109,17 @@ WebSocketエンドポイントでは、`fastapi` から以下をインポート これらは、他のFastAPI エンドポイント/*path operation* の場合と同じように機能します。 -```Python hl_lines="58-65 68-83" -{!../../../docs_src/websockets/tutorial002.py!} -``` +{* ../../docs_src/websockets/tutorial002.py hl[58:65,68:83] *} + +/// info | 情報 -!!! info "情報" - WebSocket で `HTTPException` を発生させることはあまり意味がありません。したがって、WebSocketの接続を直接閉じる方がよいでしょう。 +WebSocket で `HTTPException` を発生させることはあまり意味がありません。したがって、WebSocketの接続を直接閉じる方がよいでしょう。 - クロージングコードは、仕様で定義された有効なコードの中から使用することができます。 +クロージングコードは、仕様で定義された有効なコードの中から使用することができます。 - 将来的には、どこからでも `raise` できる `WebSocketException` が用意され、専用の例外ハンドラを追加できるようになる予定です。これは、Starlette の PR #527 に依存するものです。 +将来的には、どこからでも `raise` できる `WebSocketException` が用意され、専用の例外ハンドラを追加できるようになる予定です。これは、Starlette の PR #527 に依存するものです。 + +/// ### 依存関係を用いてWebSocketsを試してみる @@ -144,8 +142,11 @@ $ uvicorn main:app --reload * パスで使用される「Item ID」 * クエリパラメータとして使用される「Token」 -!!! tip "豆知識" - クエリ `token` は依存パッケージによって処理されることに注意してください。 +/// tip | 豆知識 + +クエリ `token` は依存パッケージによって処理されることに注意してください。 + +/// これにより、WebSocketに接続してメッセージを送受信できます。 @@ -155,9 +156,7 @@ $ uvicorn main:app --reload WebSocket接続が閉じられると、 `await websocket.receive_text()` は例外 `WebSocketDisconnect` を発生させ、この例のようにキャッチして処理することができます。 -```Python hl_lines="81-83" -{!../../../docs_src/websockets/tutorial003.py!} -``` +{* ../../docs_src/websockets/tutorial003.py hl[81:83] *} 試してみるには、 @@ -171,12 +170,15 @@ WebSocket接続が閉じられると、 `await websocket.receive_text()` は例 Client #1596980209979 left the chat ``` -!!! tip "豆知識" - 上記のアプリは、複数の WebSocket 接続に対してメッセージを処理し、ブロードキャストする方法を示すための最小限のシンプルな例です。 +/// tip | 豆知識 + +上記のアプリは、複数の WebSocket 接続に対してメッセージを処理し、ブロードキャストする方法を示すための最小限のシンプルな例です。 + +しかし、すべての接続がメモリ内の単一のリストで処理されるため、プロセスの実行中にのみ機能し、単一のプロセスでのみ機能することに注意してください。 - しかし、すべての接続がメモリ内の単一のリストで処理されるため、プロセスの実行中にのみ機能し、単一のプロセスでのみ機能することに注意してください。 +もしFastAPIと簡単に統合できて、RedisやPostgreSQLなどでサポートされている、より堅牢なものが必要なら、encode/broadcaster を確認してください。 - もしFastAPIと簡単に統合できて、RedisやPostgreSQLなどでサポートされている、より堅牢なものが必要なら、encode/broadcaster を確認してください。 +/// ## その他のドキュメント diff --git a/docs/ja/docs/alternatives.md b/docs/ja/docs/alternatives.md index ca6b29a07..8129a7002 100644 --- a/docs/ja/docs/alternatives.md +++ b/docs/ja/docs/alternatives.md @@ -30,11 +30,17 @@ Mozilla、Red Hat、Eventbrite など多くの企業で利用されています これは**自動的なAPIドキュメント生成**の最初の例であり、これは**FastAPI**に向けた「調査」を触発した最初のアイデアの一つでした。 -!!! note "備考" - Django REST Framework は Tom Christie によって作成されました。StarletteとUvicornの生みの親であり、**FastAPI**のベースとなっています。 +/// note | 備考 -!!! check "**FastAPI**へ与えたインスピレーション" - 自動でAPIドキュメントを生成するWebユーザーインターフェースを持っている点。 +Django REST Framework は Tom Christie によって作成されました。StarletteとUvicornの生みの親であり、**FastAPI**のベースとなっています。 + +/// + +/// check | **FastAPI**へ与えたインスピレーション + +自動でAPIドキュメントを生成するWebユーザーインターフェースを持っている点。 + +/// ### Flask @@ -50,11 +56,13 @@ Flask は「マイクロフレームワーク」であり、データベース Flaskのシンプルさを考えると、APIを構築するのに適しているように思えました。次に見つけるべきは、Flask 用の「Django REST Framework」でした。 -!!! check "**FastAPI**へ与えたインスピレーション" - マイクロフレームワークであること。ツールやパーツを目的に合うように簡単に組み合わせられる点。 +/// check | **FastAPI**へ与えたインスピレーション + +マイクロフレームワークであること。ツールやパーツを目的に合うように簡単に組み合わせられる点。 - シンプルで簡単なルーティングの仕組みを持っている点。 +シンプルで簡単なルーティングの仕組みを持っている点。 +/// ### Requests @@ -90,11 +98,13 @@ def read_url(): `requests.get(...)` と`@app.get(...)` には類似点が見受けられます。 -!!! check "**FastAPI**へ与えたインスピレーション" - * シンプルで直感的なAPIを持っている点。 - * HTTPメソッド名を直接利用し、単純で直感的である。 - * 適切なデフォルト値を持ちつつ、強力なカスタマイズ性を持っている。 +/// check | **FastAPI**へ与えたインスピレーション + +* シンプルで直感的なAPIを持っている点。 +* HTTPメソッド名を直接利用し、単純で直感的である。 +* 適切なデフォルト値を持ちつつ、強力なカスタマイズ性を持っている。 +/// ### Swagger / OpenAPI @@ -108,15 +118,18 @@ def read_url(): そのため、バージョン2.0では「Swagger」、バージョン3以上では「OpenAPI」と表記するのが一般的です。 -!!! check "**FastAPI**へ与えたインスピレーション" - 独自のスキーマの代わりに、API仕様のオープンな標準を採用しました。 +/// check | **FastAPI**へ与えたインスピレーション - そして、標準に基づくユーザーインターフェースツールを統合しています。 +独自のスキーマの代わりに、API仕様のオープンな標準を採用しました。 - * Swagger UI - * ReDoc +そして、標準に基づくユーザーインターフェースツールを統合しています。 - この二つは人気で安定したものとして選択されましたが、少し検索してみると、 (**FastAPI**と同時に使用できる) OpenAPIのための多くの代替となるツールを見つけることができます。 +* Swagger UI +* ReDoc + +この二つは人気で安定したものとして選択されましたが、少し検索してみると、 (**FastAPI**と同時に使用できる) OpenAPIのための多くの代替となるツールを見つけることができます。 + +/// ### Flask REST フレームワーク @@ -134,8 +147,11 @@ APIが必要とするもう一つの大きな機能はデータのバリデー しかし、それはPythonの型ヒントが存在する前に作られたものです。そのため、すべてのスキーマを定義するためには、Marshmallowが提供する特定のユーティリティやクラスを使用する必要があります。 -!!! check "**FastAPI**へ与えたインスピレーション" - コードで「スキーマ」を定義し、データの型やバリデーションを自動で提供する点。 +/// check | **FastAPI**へ与えたインスピレーション + +コードで「スキーマ」を定義し、データの型やバリデーションを自動で提供する点。 + +/// ### Webargs @@ -147,11 +163,17 @@ WebargsはFlaskをはじめとするいくつかのフレームワークの上 素晴らしいツールで、私も**FastAPI**を持つ前はよく使っていました。 -!!! info "情報" - Webargsは、Marshmallowと同じ開発者により作られました。 +/// info | 情報 + +Webargsは、Marshmallowと同じ開発者により作られました。 + +/// -!!! check "**FastAPI**へ与えたインスピレーション" - 受信したデータに対する自動的なバリデーションを持っている点。 +/// check | **FastAPI**へ与えたインスピレーション + +受信したデータに対する自動的なバリデーションを持っている点。 + +/// ### APISpec @@ -171,11 +193,17 @@ Flask, Starlette, Responderなどにおいてはそのように動作します エディタでは、この問題を解決することはできません。また、パラメータやMarshmallowスキーマを変更したときに、YAMLのdocstringを変更するのを忘れてしまうと、生成されたスキーマが古くなってしまいます。 -!!! info "情報" - APISpecは、Marshmallowと同じ開発者により作成されました。 +/// info | 情報 + +APISpecは、Marshmallowと同じ開発者により作成されました。 + +/// + +/// check | **FastAPI**へ与えたインスピレーション + +OpenAPIという、APIについてのオープンな標準をサポートしている点。 -!!! check "**FastAPI**へ与えたインスピレーション" - OpenAPIという、APIについてのオープンな標準をサポートしている点。 +/// ### Flask-apispec @@ -197,11 +225,17 @@ Flask、Flask-apispec、Marshmallow、Webargsの組み合わせは、**FastAPI** そして、これらのフルスタックジェネレーターは、[**FastAPI** Project Generators](project-generation.md){.internal-link target=_blank}の元となっていました。 -!!! info "情報" - Flask-apispecはMarshmallowと同じ開発者により作成されました。 +/// info | 情報 -!!! check "**FastAPI**へ与えたインスピレーション" - シリアライゼーションとバリデーションを定義したコードから、OpenAPIスキーマを自動的に生成する点。 +Flask-apispecはMarshmallowと同じ開発者により作成されました。 + +/// + +/// check | **FastAPI**へ与えたインスピレーション + +シリアライゼーションとバリデーションを定義したコードから、OpenAPIスキーマを自動的に生成する点。 + +/// ### NestJS (とAngular) @@ -217,24 +251,33 @@ Angular 2にインスピレーションを受けた、統合された依存性 入れ子になったモデルをうまく扱えません。そのため、リクエストのJSONボディが内部フィールドを持つJSONオブジェクトで、それが順番にネストされたJSONオブジェクトになっている場合、適切にドキュメント化やバリデーションをすることができません。 -!!! check "**FastAPI**へ与えたインスピレーション" - 素晴らしいエディターの補助を得るために、Pythonの型ヒントを利用している点。 +/// check | **FastAPI**へ与えたインスピレーション + +素晴らしいエディターの補助を得るために、Pythonの型ヒントを利用している点。 + +強力な依存性注入の仕組みを持ち、コードの繰り返しを最小化する方法を見つけた点。 - 強力な依存性注入の仕組みを持ち、コードの繰り返しを最小化する方法を見つけた点。 +/// ### Sanic `asyncio`に基づいた、Pythonのフレームワークの中でも非常に高速なものの一つです。Flaskと非常に似た作りになっています。 -!!! note "技術詳細" - Pythonの`asyncio`ループの代わりに、`uvloop`が利用されています。それにより、非常に高速です。 +/// note | 技術詳細 - `Uvicorn`と`Starlette`に明らかなインスピレーションを与えており、それらは現在オープンなベンチマークにおいてSanicより高速です。 +Pythonの`asyncio`ループの代わりに、`uvloop`が利用されています。それにより、非常に高速です。 -!!! check "**FastAPI**へ与えたインスピレーション" - 物凄い性能を出す方法を見つけた点。 +`Uvicorn`と`Starlette`に明らかなインスピレーションを与えており、それらは現在オープンなベンチマークにおいてSanicより高速です。 - **FastAPI**が、(サードパーティのベンチマークによりテストされた) 最も高速なフレームワークであるStarletteに基づいている理由です。 +/// + +/// check | **FastAPI**へ与えたインスピレーション + +物凄い性能を出す方法を見つけた点。 + +**FastAPI**が、(サードパーティのベンチマークによりテストされた) 最も高速なフレームワークであるStarletteに基づいている理由です。 + +/// ### Falcon @@ -246,12 +289,15 @@ Pythonのウェブフレームワーク標準規格 (WSGI) を使用していま そのため、データのバリデーション、シリアライゼーション、ドキュメント化は、自動的にできずコードの中で行わなければなりません。あるいは、HugのようにFalconの上にフレームワークとして実装されなければなりません。このような分断は、パラメータとして1つのリクエストオブジェクトと1つのレスポンスオブジェクトを持つというFalconのデザインにインスピレーションを受けた他のフレームワークでも起こります。 -!!! check "**FastAPI**へ与えたインスピレーション" - 素晴らしい性能を得るための方法を見つけた点。 +/// check | **FastAPI**へ与えたインスピレーション + +素晴らしい性能を得るための方法を見つけた点。 + +Hug (HugはFalconをベースにしています) と一緒に、**FastAPI**が`response`引数を関数に持つことにインスピレーションを与えました。 - Hug (HugはFalconをベースにしています) と一緒に、**FastAPI**が`response`引数を関数に持つことにインスピレーションを与えました。 +**FastAPI**では任意ですが、ヘッダーやCookieやステータスコードを設定するために利用されています。 - **FastAPI**では任意ですが、ヘッダーやCookieやステータスコードを設定するために利用されています。 +/// ### Molten @@ -269,10 +315,13 @@ Pydanticのようなデータのバリデーション、シリアライゼーシ ルーティングは一つの場所で宣言され、他の場所で宣言された関数を使用します (エンドポイントを扱う関数のすぐ上に配置できるデコレータを使用するのではなく) 。これはFlask (やStarlette) よりも、Djangoに近いです。これは、比較的緊密に結合されているものをコードの中で分離しています。 -!!! check "**FastAPI**へ与えたインスピレーション" - モデルの属性の「デフォルト」値を使用したデータ型の追加バリデーションを定義します。これはエディタの補助を改善するもので、以前はPydanticでは利用できませんでした。 +/// check | **FastAPI**へ与えたインスピレーション - 同様の方法でのバリデーションの宣言をサポートするよう、Pydanticを部分的にアップデートするインスピーレションを与えました。(現在はこれらの機能は全てPydanticで可能となっています。) +モデルの属性の「デフォルト」値を使用したデータ型の追加バリデーションを定義します。これはエディタの補助を改善するもので、以前はPydanticでは利用できませんでした。 + +同様の方法でのバリデーションの宣言をサポートするよう、Pydanticを部分的にアップデートするインスピーレションを与えました。(現在はこれらの機能は全てPydanticで可能となっています。) + +/// ### Hug @@ -288,15 +337,21 @@ OpenAPIやJSON Schemaのような標準に基づいたものではありませ 以前のPythonの同期型Webフレームワーク標準 (WSGI) をベースにしているため、Websocketなどは扱えませんが、それでも高性能です。 -!!! info "情報" - HugはTimothy Crosleyにより作成されました。彼は`isort`など、Pythonのファイル内のインポートの並び替えを自動的におこうなう素晴らしいツールの開発者です。 +/// info | 情報 + +HugはTimothy Crosleyにより作成されました。彼は`isort`など、Pythonのファイル内のインポートの並び替えを自動的におこうなう素晴らしいツールの開発者です。 + +/// + +/// check | **FastAPI**へ与えたインスピレーション + +HugはAPIStarに部分的なインスピレーションを与えており、私が発見した中ではAPIStarと同様に最も期待の持てるツールの一つでした。 -!!! check "**FastAPI**へ与えたインスピレーション" - HugはAPIStarに部分的なインスピレーションを与えており、私が発見した中ではAPIStarと同様に最も期待の持てるツールの一つでした。 +Hugは、**FastAPI**がPythonの型ヒントを用いてパラメータを宣言し自動的にAPIを定義するスキーマを生成することを触発しました。 - Hugは、**FastAPI**がPythonの型ヒントを用いてパラメータを宣言し自動的にAPIを定義するスキーマを生成することを触発しました。 +Hugは、**FastAPI**がヘッダーやクッキーを設定するために関数に `response`引数を宣言することにインスピレーションを与えました。 - Hugは、**FastAPI**がヘッダーやクッキーを設定するために関数に `response`引数を宣言することにインスピレーションを与えました。 +/// ### APIStar (<= 0.5) @@ -322,27 +377,33 @@ OpenAPIやJSON Schemaのような標準に基づいたものではありませ 今ではAPIStarはOpenAPI仕様を検証するためのツールセットであり、ウェブフレームワークではありません。 -!!! info "情報" - APIStarはTom Christieにより開発されました。以下の開発者でもあります: +/// info | 情報 - * Django REST Framework - * Starlette (**FastAPI**のベースになっています) - * Uvicorn (Starletteや**FastAPI**で利用されています) +APIStarはTom Christieにより開発されました。以下の開発者でもあります: -!!! check "**FastAPI**へ与えたインスピレーション" - 存在そのもの。 +* Django REST Framework +* Starlette (**FastAPI**のベースになっています) +* Uvicorn (Starletteや**FastAPI**で利用されています) - 複数の機能 (データのバリデーション、シリアライゼーション、ドキュメント化) を同じPython型で宣言し、同時に優れたエディタの補助を提供するというアイデアは、私にとって素晴らしいアイデアでした。 +/// - そして、長い間同じようなフレームワークを探し、多くの異なる代替ツールをテストした結果、APIStarが最良の選択肢となりました。 +/// check | **FastAPI**へ与えたインスピレーション - その後、APIStarはサーバーとして存在しなくなり、Starletteが作られ、そのようなシステムのための新しくより良い基盤となりました。これが**FastAPI**を構築するための最終的なインスピレーションでした。 +存在そのもの。 - 私は、これまでのツールから学んだことをもとに、機能や型システムなどの部分を改善・拡充しながら、**FastAPI**をAPIStarの「精神的な後継者」と考えています。 +複数の機能 (データのバリデーション、シリアライゼーション、ドキュメント化) を同じPython型で宣言し、同時に優れたエディタの補助を提供するというアイデアは、私にとって素晴らしいアイデアでした。 + +そして、長い間同じようなフレームワークを探し、多くの異なる代替ツールをテストした結果、APIStarが最良の選択肢となりました。 + +その後、APIStarはサーバーとして存在しなくなり、Starletteが作られ、そのようなシステムのための新しくより良い基盤となりました。これが**FastAPI**を構築するための最終的なインスピレーションでした。 + +私は、これまでのツールから学んだことをもとに、機能や型システムなどの部分を改善・拡充しながら、**FastAPI**をAPIStarの「精神的な後継者」と考えています。 + +/// ## **FastAPI**が利用しているもの -### Pydantic +### Pydantic Pydanticは、Pythonの型ヒントを元にデータのバリデーション、シリアライゼーション、 (JSON Schemaを使用した) ドキュメントを定義するライブラリです。 @@ -350,10 +411,13 @@ Pydanticは、Pythonの型ヒントを元にデータのバリデーション、 Marshmallowに匹敵しますが、ベンチマークではMarshmallowよりも高速です。また、Pythonの型ヒントを元にしているので、エディタの補助が素晴らしいです。 -!!! check "**FastAPI**での使用用途" - データのバリデーション、データのシリアライゼーション、自動的なモデルの (JSON Schemaに基づいた) ドキュメント化の全てを扱えます。 +/// check | **FastAPI**での使用用途 + +データのバリデーション、データのシリアライゼーション、自動的なモデルの (JSON Schemaに基づいた) ドキュメント化の全てを扱えます。 + +**FastAPI**はJSON SchemaのデータをOpenAPIに利用します。 - **FastAPI**はJSON SchemaのデータをOpenAPIに利用します。 +/// ### Starlette @@ -383,17 +447,23 @@ Starletteは基本的なWebマイクロフレームワークの機能をすべ これは **FastAPI** が追加する主な機能の一つで、すべての機能は Pythonの型ヒントに基づいています (Pydanticを使用しています) 。これに加えて、依存性注入の仕組み、セキュリティユーティリティ、OpenAPIスキーマ生成などがあります。 -!!! note "技術詳細" - ASGIはDjangoのコアチームメンバーにより開発された新しい「標準」です。まだ「Pythonの標準 (PEP) 」ではありませんが、現在そうなるように進めています。 +/// note | 技術詳細 - しかしながら、いくつかのツールにおいてすでに「標準」として利用されています。このことは互換性を大きく改善するもので、Uvicornから他のASGIサーバー (DaphneやHypercorn) に乗り換えることができたり、あなたが`python-socketio`のようなASGI互換のツールを追加することもできます。 +ASGIはDjangoのコアチームメンバーにより開発された新しい「標準」です。まだ「Pythonの標準 (PEP) 」ではありませんが、現在そうなるように進めています。 -!!! check "**FastAPI**での使用用途" - webに関するコアな部分を全て扱います。その上に機能を追加します。 +しかしながら、いくつかのツールにおいてすでに「標準」として利用されています。このことは互換性を大きく改善するもので、Uvicornから他のASGIサーバー (DaphneやHypercorn) に乗り換えることができたり、あなたが`python-socketio`のようなASGI互換のツールを追加することもできます。 - `FastAPI`クラスそのものは、`Starlette`クラスを直接継承しています。 +/// - 基本的にはStarletteの強化版であるため、Starletteで可能なことは**FastAPI**で直接可能です。 +/// check | **FastAPI**での使用用途 + +webに関するコアな部分を全て扱います。その上に機能を追加します。 + +`FastAPI`クラスそのものは、`Starlette`クラスを直接継承しています。 + +基本的にはStarletteの強化版であるため、Starletteで可能なことは**FastAPI**で直接可能です。 + +/// ### Uvicorn @@ -403,12 +473,15 @@ Uvicornは非常に高速なASGIサーバーで、uvloopとhttptoolsにより構 Starletteや**FastAPI**のサーバーとして推奨されています。 -!!! check "**FastAPI**が推奨する理由" - **FastAPI**アプリケーションを実行するメインのウェブサーバーである点。 +/// check | **FastAPI**が推奨する理由 + +**FastAPI**アプリケーションを実行するメインのウェブサーバーである点。 + +Gunicornと組み合わせることで、非同期でマルチプロセスなサーバーを持つことがきます。 - Gunicornと組み合わせることで、非同期でマルチプロセスなサーバーを持つことがきます。 +詳細は[デプロイ](deployment/index.md){.internal-link target=_blank}の項目で確認してください。 - 詳細は[デプロイ](deployment/index.md){.internal-link target=_blank}の項目で確認してください。 +/// ## ベンチマーク と スピード diff --git a/docs/ja/docs/async.md b/docs/ja/docs/async.md index 8fac2cb38..d1da1f82d 100644 --- a/docs/ja/docs/async.md +++ b/docs/ja/docs/async.md @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! note "備考" - `async def` を使用して作成された関数の内部でしか `await` は使用できません。 +/// note | 備考 + +`async def` を使用して作成された関数の内部でしか `await` は使用できません。 + +/// --- @@ -355,12 +358,15 @@ async def read_burgers(): ## 非常に発展的な技術的詳細 -!!! warning "注意" - 恐らくスキップしても良いでしょう。 +/// warning | 注意 + +恐らくスキップしても良いでしょう。 + +この部分は**FastAPI**の仕組みに関する非常に技術的な詳細です。 - この部分は**FastAPI**の仕組みに関する非常に技術的な詳細です。 +かなりの技術知識 (コルーチン、スレッド、ブロッキングなど) があり、FastAPIが `async def` と通常の `def` をどのように処理するか知りたい場合は、先に進んでください。 - かなりの技術知識 (コルーチン、スレッド、ブロッキングなど) があり、FastAPIが `async def` と通常の `def` をどのように処理するか知りたい場合は、先に進んでください。 +/// ### Path operation 関数 @@ -368,7 +374,7 @@ async def read_burgers(): 上記の方法と違った方法の別の非同期フレームワークから来ており、小さなパフォーマンス向上 (約100ナノ秒) のために通常の `def` を使用して些細な演算のみ行う *path operation 関数* を定義するのに慣れている場合は、**FastAPI**ではまったく逆の効果になることに注意してください。このような場合、*path operation 関数* がブロッキングI/Oを実行しないのであれば、`async def` の使用をお勧めします。 -それでも、どちらの状況でも、**FastAPI**が過去のフレームワークよりも (またはそれに匹敵するほど) [高速になる](/#performance){.internal-link target=_blank}可能性があります。 +それでも、どちらの状況でも、**FastAPI**が過去のフレームワークよりも (またはそれに匹敵するほど) [高速になる](index.md#_10){.internal-link target=_blank}可能性があります。 ### 依存関係 @@ -390,4 +396,4 @@ async def read_burgers(): 繰り返しになりますが、これらは非常に技術的な詳細であり、検索して辿り着いた場合は役立つでしょう。 -それ以外の場合は、上記のセクションのガイドラインで問題ないはずです: 急いでいますか?。 +それ以外の場合は、上記のセクションのガイドラインで問題ないはずです: 急いでいますか?。 diff --git a/docs/ja/docs/contributing.md b/docs/ja/docs/contributing.md deleted file mode 100644 index 31db51c52..000000000 --- a/docs/ja/docs/contributing.md +++ /dev/null @@ -1,470 +0,0 @@ -# 開発 - 貢献 - -まず、[FastAPIを応援 - ヘルプの入手](help-fastapi.md){.internal-link target=_blank}の基本的な方法を見て、ヘルプを得た方がいいかもしれません。 - -## 開発 - -すでにリポジトリをクローンし、コードを詳しく調べる必要があるとわかっている場合に、環境構築のためのガイドラインをいくつか紹介します。 - -### `venv`を使用した仮想環境 - -Pythonの`venv`モジュールを使用して、ディレクトリに仮想環境を作成します: - -
- -```console -$ python -m venv env -``` - -
- -これにより、Pythonバイナリを含む`./env/`ディレクトリが作成され、その隔離された環境にパッケージのインストールが可能になります。 - -### 仮想環境の有効化 - -新しい環境を有効化するには: - -=== "Linux, macOS" - -
- - ```console - $ source ./env/bin/activate - ``` - -
- -=== "Windows PowerShell" - -
- - ```console - $ .\env\Scripts\Activate.ps1 - ``` - -
- -=== "Windows Bash" - - もしwindows用のBash (例えば、Git Bash)を使っているなら: - -
- - ```console - $ source ./env/Scripts/activate - ``` - -
- -動作の確認には、下記を実行します: - -=== "Linux, macOS, Windows Bash" - -
- - ```console - $ which pip - - some/directory/fastapi/env/bin/pip - ``` - -
- -=== "Windows PowerShell" - -
- - ```console - $ Get-Command pip - - some/directory/fastapi/env/bin/pip - ``` - -
- -`env/bin/pip`に`pip`バイナリが表示される場合は、正常に機能しています。🎉 - - -!!! tip "豆知識" - この環境で`pip`を使って新しいパッケージをインストールするたびに、仮想環境を再度有効化します。 - - これにより、そのパッケージによってインストールされたターミナルのプログラム を使用する場合、ローカル環境のものを使用し、グローバルにインストールされたものは使用されなくなります。 - -### pip - -上記のように環境を有効化した後: - -
- -```console -$ pip install -r requirements.txt - ----> 100% -``` - -
- -これで、すべての依存関係とFastAPIを、ローカル環境にインストールします。 - -#### ローカル環境でFastAPIを使う - -FastAPIをインポートして使用するPythonファイルを作成し、ローカル環境で実行すると、ローカルのFastAPIソースコードが使用されます。 - -そして、`-e` でインストールされているローカルのFastAPIソースコードを更新した場合、そのPythonファイルを再度実行すると、更新したばかりの新しいバージョンのFastAPIが使用されます。 - -これにより、ローカルバージョンを「インストール」しなくても、すべての変更をテストできます。 - -### コードの整形 - -すべてのコードを整形してクリーンにするスクリプトがあります: - -
- -```console -$ bash scripts/format.sh -``` - -
- -また、すべてのインポートを自動でソートします。 - -正しく並べ替えるには、上記セクションのコマンドで `-e` を使い、FastAPIをローカル環境にインストールしている必要があります。 - -### インポートの整形 - -他にも、すべてのインポートを整形し、未使用のインポートがないことを確認するスクリプトがあります: - -
- -```console -$ bash scripts/format-imports.sh -``` - -
- -多くのファイルを編集したり、リバートした後、これらのコマンドを実行すると、少し時間がかかります。なので`scripts/format.sh`を頻繁に使用し、`scripts/format-imports.sh`をコミット前に実行する方が楽でしょう。 - -## ドキュメント - -まず、上記のように環境をセットアップしてください。すべての必要なパッケージがインストールされます。 - -ドキュメントは、MkDocsを使っています。 - -そして、翻訳を処理するためのツール/スクリプトが、`./scripts/docs.py`に用意されています。 - -!!! tip "豆知識" - `./scripts/docs.py`のコードを見る必要はなく、コマンドラインからただ使うだけです。 - -すべてのドキュメントが、Markdown形式で`./docs/en/`ディレクトリにあります。 - -多くのチュートリアルには、コードブロックがあります。 - -ほとんどの場合、これらのコードブロックは、実際にそのまま実行できる完全なアプリケーションです。 - -実際、これらのコードブロックはMarkdown内には記述されておらず、`./docs_src/`ディレクトリのPythonファイルです。 - -そして、これらのPythonファイルは、サイトの生成時にドキュメントに含まれるか/挿入されます。 - -### ドキュメントのテスト - -ほとんどのテストは、実際にドキュメント内のサンプルソースファイルに対して実行されます。 - -これにより、次のことが確認できます: - -* ドキュメントが最新であること。 -* ドキュメントの例が、そのまま実行できること。 -* ほとんどの機能がドキュメントでカバーされており、テスト範囲で保証されていること。 - -ローカル開発中に、サイトを構築して変更がないかチェックするスクリプトがあり、ライブリロードされます: - -
- -```console -$ python ./scripts/docs.py live - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -ドキュメントは、`http://127.0.0.1:8008`で提供します。 - -そうすることで、ドキュメント/ソースファイルを編集し、変更をライブで見ることができます。 - -#### Typer CLI (任意) - -ここでは、`./scripts/docs.py`のスクリプトを`python`プログラムで直接使う方法を説明します。 - -ですがTyper CLIを使用して、インストール完了後にターミナルでの自動補完もできます。 - -Typer CLIをインストールする場合、次のコマンドで補完をインストールできます: - -
- -```console -$ typer --install-completion - -zsh completion installed in /home/user/.bashrc. -Completion will take effect once you restart the terminal. -``` - -
- -### アプリとドキュメントを同時に - -以下の様にサンプルを実行すると: - -
- -```console -$ uvicorn tutorial001:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -Uvicornはデフォルトでポート`8000`を使用するため、ポート`8008`のドキュメントは衝突しません。 - -### 翻訳 - -翻訳のヘルプをとても歓迎しています!これはコミュニティの助けなしでは成し遂げられません。 🌎🚀 - -翻訳を支援するための手順は次のとおりです。 - -#### 豆知識とガイドライン - -* あなたの言語の今あるプルリクエストを確認し、変更や承認をするレビューを追加します。 - -!!! tip "豆知識" - すでにあるプルリクエストに修正提案つきのコメントを追加できます。 - - 修正提案の承認のためにプルリクエストのレビューの追加のドキュメントを確認してください。 - -* issuesをチェックして、あなたの言語に対応する翻訳があるかどうかを確認してください。 - -* 翻訳したページごとに1つのプルリクエストを追加します。これにより、他のユーザーがレビューしやすくなります。 - -私が話さない言語については、他の何人かが翻訳をレビューするのを待って、マージします。 - -* 自分の言語の翻訳があるかどうか確認し、レビューを追加できます。これにより、翻訳が正しく、マージできることがわかります。 - -* 同じPythonの例を使用し、ドキュメント内のテキストのみを翻訳してください。何も変更する必要はありません。 - -* 同じ画像、ファイル名、リンクを使用します。何も変更する必要はありません。 - -* 翻訳する言語の2文字のコードを確認するには、表 ISO 639-1コードのリストが使用できます。 - -#### すでにある言語 - -スペイン語の様に、既に一部のページが翻訳されている言語の翻訳を追加したいとしましょう。 - -スペイン語の場合、2文字のコードは`es`です。したがって、スペイン語のディレクトリは`docs/es/`です。 - -!!! tip "豆知識" - メイン (「公式」) 言語は英語で、`docs/en/`にあります。 - -次に、ドキュメントのライブサーバーをスペイン語で実行します: - -
- -```console -// コマンド"live"を使用し、言語コードをCLIに引数で渡します。 -$ python ./scripts/docs.py live es - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -これでhttp://127.0.0.1:8008 を開いて、変更を確認できます。 - -FastAPI docs Webサイトを見ると、すべての言語にすべてのページがあります。しかし、一部のページは翻訳されておらず、翻訳の欠落ページについて通知があります。 - -しかし、このようにローカルで実行すると、翻訳済みのページのみが表示されます。 - -ここで、セクション[Features](features.md){.internal-link target=_blank}の翻訳を追加するとします。 - -* 下記のファイルをコピーします: - -``` -docs/en/docs/features.md -``` - -* 翻訳したい言語のまったく同じところに貼り付けます。例えば: - -``` -docs/es/docs/features.md -``` - -!!! tip "豆知識" - パスとファイル名の変更は、`en`から`es`への言語コードだけであることに注意してください。 - -* ここで、英語のMkDocs構成ファイルを開きます: - -``` -docs/en/docs/mkdocs.yml -``` - -* 設定ファイルの中で、`docs/features.md`が記述されている箇所を見つけます: - -```YAML hl_lines="8" -site_name: FastAPI -# More stuff -nav: -- FastAPI: index.md -- Languages: - - en: / - - es: /es/ -- features.md -``` - -* 編集している言語のMkDocs構成ファイルを開きます。例えば: - -``` -docs/es/docs/mkdocs.yml -``` - -* 英語とまったく同じ場所に追加します。例えば: - -```YAML hl_lines="8" -site_name: FastAPI -# More stuff -nav: -- FastAPI: index.md -- Languages: - - en: / - - es: /es/ -- features.md -``` - -他のエントリがある場合は、翻訳を含む新しいエントリが英語版とまったく同じ順序になっていることを確認してください。 - -ブラウザにアクセスすれば、ドキュメントに新しいセクションが表示されています。 🎉 - -これですべて翻訳して、ファイルを保存した状態を確認できます。 - -#### 新しい言語 - -まだ翻訳されていない言語の翻訳を追加したいとしましょう。 - -クレオール語の翻訳を追加したいのですが、それはまだドキュメントにありません。 - -上記のリンクを確認すると、「クレオール語」のコードは`ht`です。 - -次のステップは、スクリプトを実行して新しい翻訳ディレクトリを生成することです: - -
- -```console -// コマンド「new-lang」を使用して、言語コードをCLIに引数で渡します -$ python ./scripts/docs.py new-lang ht - -Successfully initialized: docs/ht -Updating ht -Updating en -``` - -
- -これで、新しく作成された`docs/ht/`ディレクトリをコードエディターから確認できます。 - -!!! tip "豆知識" - 翻訳を追加する前に、これだけで最初のプルリクエストを作成し、新しい言語の設定をセットアップします。 - - そうすることで、最初のページで作業している間、誰かの他のページの作業を助けることができます。 🚀 - -まず、メインページの`docs/ht/index.md`を翻訳します。 - -その後、「既存の言語」で、さきほどの手順を続行してください。 - -##### まだサポートされていない新しい言語 - -ライブサーバースクリプトを実行するときに、サポートされていない言語に関するエラーが発生した場合は、次のように表示されます: - -``` - raise TemplateNotFound(template) -jinja2.exceptions.TemplateNotFound: partials/language/xx.html -``` - -これは、テーマがその言語をサポートしていないことを意味します (この場合は、`xx`の2文字の偽のコード) 。 - -ただし、心配しないでください。テーマ言語を英語に設定して、ドキュメントの内容を翻訳できます。 - -その必要がある場合は、新しい言語の`mkdocs.yml`を次のように編集してください: - -```YAML hl_lines="5" -site_name: FastAPI -# More stuff -theme: - # More stuff - language: xx -``` - -その言語を`xx` (あなたの言語コード) から`en`に変更します。 - -その後、ライブサーバーを再起動します。 - -#### 結果のプレビュー - -`./scripts/docs.py`のスクリプトを`live`コマンドで使用すると、現在の言語で利用可能なファイルと翻訳のみが表示されます。 - -しかし一度実行したら、オンラインで表示されるのと同じように、すべてをテストできます。 - -このために、まずすべてのドキュメントをビルドします: - -
- -```console -// 「build-all」コマンドは少し時間がかかります。 -$ python ./scripts/docs.py build-all - -Updating es -Updating en -Building docs for: en -Building docs for: es -Successfully built docs for: es -Copying en index.md to README.md -``` - -
- -これで、言語ごとにすべてのドキュメントが`./docs_build/`に作成されます。 - -これには、翻訳が欠落しているファイルを追加することと、「このファイルにはまだ翻訳がない」というメモが含まれます。ただし、そのディレクトリで何もする必要はありません。 - -次に、言語ごとにこれらすべての個別のMkDocsサイトを構築し、それらを組み合わせて、`./site/`に最終結果を出力します。 - -これは、コマンド`serve`で提供できます: - -
- -```console -// 「build-all」コマンドの実行の後に、「serve」コマンドを使います -$ python ./scripts/docs.py serve - -Warning: this is a very simple server. For development, use mkdocs serve instead. -This is here only to preview a site with translations already built. -Make sure you run the build-all command first. -Serving at: http://127.0.0.1:8008 -``` - -
- -## テスト - -すべてのコードをテストし、HTMLでカバレッジレポートを生成するためにローカルで実行できるスクリプトがあります: - -
- -```console -$ bash scripts/test-cov-html.sh -``` - -
- -このコマンドは`./htmlcov/`ディレクトリを生成します。ブラウザでファイル`./htmlcov/index.html`を開くと、テストでカバーされているコードの領域をインタラクティブに探索できます。それによりテストが不足しているかどうか気付くことができます。 diff --git a/docs/ja/docs/deployment/concepts.md b/docs/ja/docs/deployment/concepts.md index 38cbca219..c6b21fd1b 100644 --- a/docs/ja/docs/deployment/concepts.md +++ b/docs/ja/docs/deployment/concepts.md @@ -30,7 +30,7 @@ ## セキュリティ - HTTPS -[前チャプターのHTTPSについて](./https.md){.internal-link target=_blank}では、HTTPSがどのようにAPIを暗号化するのかについて学びました。 +[前チャプターのHTTPSについて](https.md){.internal-link target=_blank}では、HTTPSがどのようにAPIを暗号化するのかについて学びました。 通常、アプリケーションサーバにとって**外部の**コンポーネントである**TLS Termination Proxy**によって提供されることが一般的です。このプロキシは通信の暗号化を担当します。 @@ -151,10 +151,13 @@ FastAPIでWeb APIを構築する際に、コードにエラーがある場合、 しかし、実行中の**プロセス**をクラッシュさせるような本当にひどいエラーの場合、少なくとも2〜3回ほどプロセスを**再起動**させる外部コンポーネントが必要でしょう。 -!!! tip - ...とはいえ、アプリケーション全体が**すぐにクラッシュする**のであれば、いつまでも再起動し続けるのは意味がないでしょう。しかし、その場合はおそらく開発中か少なくともデプロイ直後に気づくと思われます。 +/// tip - そこで、**将来**クラッシュする可能性があり、それでも再スタートさせることに意味があるような、主なケースに焦点を当ててみます。 +...とはいえ、アプリケーション全体が**すぐにクラッシュする**のであれば、いつまでも再起動し続けるのは意味がないでしょう。しかし、その場合はおそらく開発中か少なくともデプロイ直後に気づくと思われます。 + +そこで、**将来**クラッシュする可能性があり、それでも再スタートさせることに意味があるような、主なケースに焦点を当ててみます。 + +/// あなたはおそらく**外部コンポーネント**がアプリケーションの再起動を担当することを望むと考えます。 なぜなら、その時点でUvicornとPythonを使った同じアプリケーションはすでにクラッシュしており、同じアプリケーションの同じコードに対して何もできないためです。 @@ -188,7 +191,7 @@ FastAPI アプリケーションでは、Uvicorn のようなサーバープロ ### ワーカー・プロセス と ポート -[HTTPSについて](./https.md){.internal-link target=_blank}のドキュメントで、1つのサーバーで1つのポートとIPアドレスの組み合わせでリッスンできるのは1つのプロセスだけであることを覚えていますでしょうか? +[HTTPSについて](https.md){.internal-link target=_blank}のドキュメントで、1つのサーバーで1つのポートとIPアドレスの組み合わせでリッスンできるのは1つのプロセスだけであることを覚えていますでしょうか? これはいまだに同じです。 @@ -243,11 +246,14 @@ FastAPI アプリケーションでは、Uvicorn のようなサーバープロ * **クラウド・サービス**によるレプリケーション * クラウド・サービスはおそらく**あなたのためにレプリケーションを処理**します。**実行するプロセス**や使用する**コンテナイメージ**を定義できるかもしれませんが、いずれにせよ、それはおそらく**単一のUvicornプロセス**であり、クラウドサービスはそのレプリケーションを担当するでしょう。 -!!! tip - これらの**コンテナ**やDockerそしてKubernetesに関する項目が、まだあまり意味をなしていなくても心配しないでください。 - +/// tip + +これらの**コンテナ**やDockerそしてKubernetesに関する項目が、まだあまり意味をなしていなくても心配しないでください。 + + +コンテナ・イメージ、Docker、Kubernetesなどについては、次の章で詳しく説明します: [コンテナ内のFastAPI - Docker](docker.md){.internal-link target=_blank}. - コンテナ・イメージ、Docker、Kubernetesなどについては、次の章で詳しく説明します: [コンテナ内のFastAPI - Docker](./docker.md){.internal-link target=_blank}. +/// ## 開始前の事前のステップ @@ -265,10 +271,13 @@ FastAPI アプリケーションでは、Uvicorn のようなサーバープロ もちろん、事前のステップを何度も実行しても問題がない場合もあり、その際は対処がかなり楽になります。 -!!! tip - また、セットアップによっては、アプリケーションを開始する前の**事前のステップ**が必要ない場合もあることを覚えておいてください。 +/// tip - その場合は、このようなことを心配する必要はないです。🤷 +また、セットアップによっては、アプリケーションを開始する前の**事前のステップ**が必要ない場合もあることを覚えておいてください。 + +その場合は、このようなことを心配する必要はないです。🤷 + +/// ### 事前ステップの戦略例 @@ -280,9 +289,12 @@ FastAPI アプリケーションでは、Uvicorn のようなサーバープロ * 事前のステップを実行し、アプリケーションを起動するbashスクリプト * 利用するbashスクリプトを起動/再起動したり、エラーを検出したりする方法は以前として必要になるでしょう。 -!!! tip - - コンテナを使った具体的な例については、次の章で紹介します: [コンテナ内のFastAPI - Docker](./docker.md){.internal-link target=_blank}. +/// tip + + +コンテナを使った具体的な例については、次の章で紹介します: [コンテナ内のFastAPI - Docker](docker.md){.internal-link target=_blank}. + +/// ## リソースの利用 diff --git a/docs/ja/docs/deployment/docker.md b/docs/ja/docs/deployment/docker.md index ca9dedc3c..53fc851f1 100644 --- a/docs/ja/docs/deployment/docker.md +++ b/docs/ja/docs/deployment/docker.md @@ -6,9 +6,12 @@ FastAPIアプリケーションをデプロイする場合、一般的なアプ Linuxコンテナの使用には、**セキュリティ**、**反復可能性(レプリカビリティ)**、**シンプリシティ**など、いくつかの利点があります。 -!!! tip - TODO: なぜか遷移できない - お急ぎで、すでにこれらの情報をご存じですか? [以下の`Dockerfile`の箇所👇](#build-a-docker-image-for-fastapi)へジャンプしてください。 +/// tip + +TODO: なぜか遷移できない +お急ぎで、すでにこれらの情報をご存じですか? [以下の`Dockerfile`の箇所👇](#build-a-docker-image-for-fastapi)へジャンプしてください。 + +///
Dockerfile プレビュー 👀 @@ -117,7 +120,7 @@ FastAPI用の**Dockerイメージ**を、**公式Python**イメージに基づ 最も一般的な方法は、`requirements.txt` ファイルにパッケージ名とそのバージョンを 1 行ずつ書くことです。 -もちろん、[FastAPI バージョンについて](./versions.md){.internal-link target=_blank}で読んだのと同じアイデアを使用して、バージョンの範囲を設定します。 +もちろん、[FastAPI バージョンについて](versions.md){.internal-link target=_blank}で読んだのと同じアイデアを使用して、バージョンの範囲を設定します。 例えば、`requirements.txt` は次のようになります: @@ -139,10 +142,13 @@ Successfully installed fastapi pydantic uvicorn
-!!! info - パッケージの依存関係を定義しインストールするためのフォーマットやツールは他にもあります。 +/// info + +パッケージの依存関係を定義しインストールするためのフォーマットやツールは他にもあります。 - Poetryを使った例は、後述するセクションでご紹介します。👇 +Poetryを使った例は、後述するセクションでご紹介します。👇 + +/// ### **FastAPI**コードを作成する @@ -207,8 +213,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 4. 要件ファイルにあるパッケージの依存関係をインストールします `--no-cache-dir` オプションはダウンロードしたパッケージをローカルに保存しないように `pip` に指示します。これは、同じパッケージをインストールするために `pip` を再度実行する場合にのみ有効ですが、コンテナで作業する場合はそうではないです。 - !!! note - `--no-cache-dir`は`pip`に関連しているだけで、Dockerやコンテナとは何の関係もないです。 + /// note + + `--no-cache-dir`は`pip`に関連しているだけで、Dockerやコンテナとは何の関係もないです。 + + /// `--upgrade` オプションは、パッケージが既にインストールされている場合、`pip` にアップグレードするように指示します。 @@ -230,8 +239,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] そのためプログラムは `/code` で開始しその中にあなたのコードがある `./app` ディレクトリがあるので、**Uvicorn** は `app.main` から `app` を参照し、**インポート** することができます。 -!!! tip - コード内の"+"の吹き出しをクリックして、各行が何をするのかをレビューしてください。👆 +/// tip + +コード内の"+"の吹き出しをクリックして、各行が何をするのかをレビューしてください。👆 + +/// これで、次のようなディレクトリ構造になるはずです: @@ -305,10 +317,13 @@ $ docker build -t myimage . -!!! tip - 末尾の `.` に注目してほしいです。これは `./` と同じ意味です。 これはDockerにコンテナイメージのビルドに使用するディレクトリを指示します。 +/// tip + +末尾の `.` に注目してほしいです。これは `./` と同じ意味です。 これはDockerにコンテナイメージのビルドに使用するディレクトリを指示します。 - この場合、同じカレント・ディレクトリ(`.`)です。 +この場合、同じカレント・ディレクトリ(`.`)です。 + +/// ### Dockerコンテナの起動する @@ -384,7 +399,7 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ## デプロイメントのコンセプト -コンテナという観点から、[デプロイのコンセプト](./concepts.md){.internal-link target=_blank}に共通するいくつかについて、もう一度説明しましょう。 +コンテナという観点から、[デプロイのコンセプト](concepts.md){.internal-link target=_blank}に共通するいくつかについて、もう一度説明しましょう。 コンテナは主に、アプリケーションの**ビルドとデプロイ**のプロセスを簡素化するためのツールですが、これらの**デプロイのコンセプト**を扱うための特定のアプローチを強制するものではないです。 @@ -405,8 +420,11 @@ FastAPI アプリケーションの **コンテナ・イメージ**(および 例えばTraefikのように、**HTTPS**と**証明書**の**自動**取得を扱う別のコンテナである可能性もあります。 -!!! tip - TraefikはDockerやKubernetesなどと統合されているので、コンテナ用のHTTPSの設定や構成はとても簡単です。 +/// tip + +TraefikはDockerやKubernetesなどと統合されているので、コンテナ用のHTTPSの設定や構成はとても簡単です。 + +/// あるいは、(コンテナ内でアプリケーションを実行しながら)クラウド・プロバイダーがサービスの1つとしてHTTPSを処理することもできます。 @@ -434,8 +452,11 @@ Kubernetesのような分散コンテナ管理システムの1つは通常、入 このコンポーネントはリクエストの **負荷** を受け、 (うまくいけば) その負荷を**バランスよく** ワーカーに分配するので、一般に **ロードバランサ** とも呼ばれます。 -!!! tip -  HTTPSに使われるものと同じ**TLS Termination Proxy**コンポーネントは、おそらく**ロードバランサー**にもなるでしょう。 +/// tip + +HTTPSに使われるものと同じ**TLS Termination Proxy**コンポーネントは、おそらく**ロードバランサー**にもなるでしょう。 + +/// そしてコンテナで作業する場合、コンテナの起動と管理に使用する同じシステムには、**ロードバランサー**(**TLS Termination Proxy**の可能性もある)から**ネットワーク通信**(HTTPリクエストなど)をアプリのあるコンテナ(複数可)に送信するための内部ツールが既にあるはずです。 @@ -461,7 +482,7 @@ Kubernetesのような分散コンテナ管理システムの1つは通常、入 もちろん、**特殊なケース**として、**Gunicornプロセスマネージャ**を持つ**コンテナ**内で複数の**Uvicornワーカープロセス**を起動させたい場合があります。 -このような場合、**公式のDockerイメージ**を使用することができます。このイメージには、複数の**Uvicornワーカープロセス**を実行するプロセスマネージャとして**Gunicorn**が含まれており、現在のCPUコアに基づいてワーカーの数を自動的に調整するためのデフォルト設定がいくつか含まれています。詳しくは後述の[Gunicornによる公式Dockerイメージ - Uvicorn](#gunicornによる公式dockerイメージ---Uvicorn)で説明します。 +このような場合、**公式のDockerイメージ**を使用することができます。このイメージには、複数の**Uvicornワーカープロセス**を実行するプロセスマネージャとして**Gunicorn**が含まれており、現在のCPUコアに基づいてワーカーの数を自動的に調整するためのデフォルト設定がいくつか含まれています。詳しくは後述の[Gunicornによる公式Dockerイメージ - Uvicorn](#gunicorndocker-uvicorn)で説明します。 以下は、それが理にかなっている場合の例です: @@ -520,8 +541,11 @@ Docker Composeで**シングルサーバ**(クラスタではない)にデ 複数の**コンテナ**があり、おそらくそれぞれが**単一のプロセス**を実行している場合(**Kubernetes**クラスタなど)、レプリケートされたワーカーコンテナを実行する**前に**、単一のコンテナで**事前のステップ**の作業を行う**別のコンテナ**を持ちたいと思うでしょう。 -!!! info - もしKubernetesを使用している場合, これはおそらくInit コンテナでしょう。 +/// info + +もしKubernetesを使用している場合, これはおそらくInit コンテナでしょう。 + +/// ユースケースが事前のステップを**並列で複数回**実行するのに問題がない場合(例:データベースの準備チェック)、メインプロセスを開始する前に、それらのステップを各コンテナに入れることが可能です。 @@ -531,14 +555,17 @@ Docker Composeで**シングルサーバ**(クラスタではない)にデ ## Gunicornによる公式Dockerイメージ - Uvicorn -前の章で詳しく説明したように、Uvicornワーカーで動作するGunicornを含む公式のDockerイメージがあります: [Server Workers - Gunicorn と Uvicorn](./server-workers.md){.internal-link target=_blank}で詳しく説明しています。 +前の章で詳しく説明したように、Uvicornワーカーで動作するGunicornを含む公式のDockerイメージがあります: [Server Workers - Gunicorn と Uvicorn](server-workers.md){.internal-link target=_blank}で詳しく説明しています。 このイメージは、主に上記で説明した状況で役に立つでしょう: [複数のプロセスと特殊なケースを持つコンテナ(Containers with Multiple Processes and Special Cases)](#containers-with-multiple-processes-and-special-cases) * tiangolo/uvicorn-gunicorn-fastapi. -!!! warning - このベースイメージや類似のイメージは**必要ない**可能性が高いので、[上記の: FastAPI用のDockerイメージをビルドする(Build a Docker Image for FastAPI)](#build-a-docker-image-for-fastapi)のようにゼロからイメージをビルドする方が良いでしょう。 +/// warning + +このベースイメージや類似のイメージは**必要ない**可能性が高いので、[上記の: FastAPI用のDockerイメージをビルドする(Build a Docker Image for FastAPI)](#build-a-docker-image-for-fastapi)のようにゼロからイメージをビルドする方が良いでしょう。 + +/// このイメージには、利用可能なCPUコアに基づいて**ワーカー・プロセスの数**を設定する**オートチューニング**メカニズムが含まれています。 @@ -546,8 +573,11 @@ Docker Composeで**シングルサーバ**(クラスタではない)にデ また、スクリプトで**開始前の事前ステップ**を実行することもサポートしている。 -!!! tip - すべての設定とオプションを見るには、Dockerイメージのページをご覧ください: tiangolo/uvicorn-gunicorn-fastapi +/// tip + +すべての設定とオプションを見るには、Dockerイメージのページをご覧ください: tiangolo/uvicorn-gunicorn-fastapi + +/// ### 公式Dockerイメージのプロセス数 @@ -672,8 +702,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 9. 生成された `requirements.txt` ファイルにあるパッケージの依存関係をインストールします 10. app` ディレクトリを `/code` ディレクトリにコピーします 11. uvicorn` コマンドを実行して、`app.main` からインポートした `app` オブジェクトを使用するように指示します -!!! tip - "+"の吹き出しをクリックすると、それぞれの行が何をするのかを見ることができます +/// tip + +"+"の吹き出しをクリックすると、それぞれの行が何をするのかを見ることができます + +/// **Dockerステージ**は`Dockerfile`の一部で、**一時的なコンテナイメージ**として動作します。 diff --git a/docs/ja/docs/deployment/https.md b/docs/ja/docs/deployment/https.md index a291f870f..ac40b0982 100644 --- a/docs/ja/docs/deployment/https.md +++ b/docs/ja/docs/deployment/https.md @@ -4,8 +4,11 @@ HTTPSは単に「有効」か「無効」かで決まるものだと思いがち しかし、それよりもはるかに複雑です。 -!!! tip - もし急いでいたり、HTTPSの仕組みについて気にしないのであれば、次のセクションに進み、さまざまなテクニックを使ってすべてをセットアップするステップ・バイ・ステップの手順をご覧ください。 +/// tip + +もし急いでいたり、HTTPSの仕組みについて気にしないのであれば、次のセクションに進み、さまざまなテクニックを使ってすべてをセットアップするステップ・バイ・ステップの手順をご覧ください。 + +/// 利用者の視点から **HTTPS の基本を学ぶ**に当たっては、次のリソースをオススメします: https://howhttps.works/. @@ -75,8 +78,11 @@ DNSサーバーでは、**取得したドメイン**をあなたのサーバー これはおそらく、最初の1回だけあり、すべてをセットアップするときに行うでしょう。 -!!! tip - ドメイン名の話はHTTPSに関する話のはるか前にありますが、すべてがドメインとIPアドレスに依存するため、ここで言及する価値があります。 +/// tip + +ドメイン名の話はHTTPSに関する話のはるか前にありますが、すべてがドメインとIPアドレスに依存するため、ここで言及する価値があります。 + +/// ### DNS @@ -124,8 +130,11 @@ TLS Termination Proxyは、1つ以上の**TLS証明書**(HTTPS証明書)に これが**HTTPS**であり、純粋な(暗号化されていない)TCP接続ではなく、**セキュアなTLS接続**の中に**HTTP**があるだけです。 -!!! tip - 通信の暗号化は、HTTPレベルではなく、**TCPレベル**で行われることに注意してください。 +/// tip + +通信の暗号化は、HTTPレベルではなく、**TCPレベル**で行われることに注意してください。 + +/// ### HTTPS リクエスト diff --git a/docs/ja/docs/deployment/manually.md b/docs/ja/docs/deployment/manually.md index 67010a66f..4ea6bd8ff 100644 --- a/docs/ja/docs/deployment/manually.md +++ b/docs/ja/docs/deployment/manually.md @@ -4,66 +4,77 @@ 以下の様なASGI対応のサーバをインストールする必要があります: -=== "Uvicorn" +//// tab | Uvicorn - * Uvicorn, uvloopとhttptoolsを基にした高速なASGIサーバ。 +* Uvicorn, uvloopとhttptoolsを基にした高速なASGIサーバ。 -
+
- ```console - $ pip install "uvicorn[standard]" +```console +$ pip install "uvicorn[standard]" - ---> 100% - ``` +---> 100% +``` -
+
-!!! tip "豆知識" - `standard` を加えることで、Uvicornがインストールされ、いくつかの推奨される依存関係を利用するようになります。 +//// - これには、`asyncio` の高性能な完全互換品である `uvloop` が含まれ、並行処理のパフォーマンスが大幅に向上します。 +/// tip | 豆知識 -=== "Hypercorn" +`standard` を加えることで、Uvicornがインストールされ、いくつかの推奨される依存関係を利用するようになります。 - * Hypercorn, HTTP/2にも対応しているASGIサーバ。 +これには、`asyncio` の高性能な完全互換品である `uvloop` が含まれ、並行処理のパフォーマンスが大幅に向上します。 -
+/// - ```console - $ pip install hypercorn +//// tab | Hypercorn - ---> 100% - ``` +* Hypercorn, HTTP/2にも対応しているASGIサーバ。 -
+
- ...または、これら以外のASGIサーバ。 +```console +$ pip install hypercorn + +---> 100% +``` + +
+ +...または、これら以外のASGIサーバ。 + +//// そして、チュートリアルと同様な方法でアプリケーションを起動して下さい。ただし、以下の様に`--reload` オプションは使用しないで下さい: -=== "Uvicorn" +//// tab | Uvicorn + +
+ +```console +$ uvicorn main:app --host 0.0.0.0 --port 80 -
+INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) +``` - ```console - $ uvicorn main:app --host 0.0.0.0 --port 80 +
- INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) - ``` +//// -
+//// tab | Hypercorn -=== "Hypercorn" +
-
+```console +$ hypercorn main:app --bind 0.0.0.0:80 - ```console - $ hypercorn main:app --bind 0.0.0.0:80 +Running on 0.0.0.0:8080 over http (CTRL + C to quit) +``` - Running on 0.0.0.0:8080 over http (CTRL + C to quit) - ``` +
-
+//// 停止した場合に自動的に再起動させるツールを設定したいかもしれません。 diff --git a/docs/ja/docs/deployment/server-workers.md b/docs/ja/docs/deployment/server-workers.md index e1ea165a2..38ceab017 100644 --- a/docs/ja/docs/deployment/server-workers.md +++ b/docs/ja/docs/deployment/server-workers.md @@ -13,15 +13,18 @@ アプリケーションをデプロイする際には、**複数のコア**を利用し、そしてより多くのリクエストを処理できるようにするために、プロセスの**レプリケーション**を持つことを望むでしょう。 -前のチャプターである[デプロイメントのコンセプト](./concepts.md){.internal-link target=_blank}にて見てきたように、有効な戦略がいくつかあります。 +前のチャプターである[デプロイメントのコンセプト](concepts.md){.internal-link target=_blank}にて見てきたように、有効な戦略がいくつかあります。 ここでは**Gunicorn**が**Uvicornのワーカー・プロセス**を管理する場合の使い方について紹介していきます。 -!!! info - - DockerやKubernetesなどのコンテナを使用している場合は、次の章で詳しく説明します: [コンテナ内のFastAPI - Docker](./docker.md){.internal-link target=_blank} +/// info - 特に**Kubernetes**上で実行する場合は、おそらく**Gunicornを使用せず**、**コンテナごとに単一のUvicornプロセス**を実行することになりますが、それについてはこの章の後半で説明します。 + +DockerやKubernetesなどのコンテナを使用している場合は、次の章で詳しく説明します: [コンテナ内のFastAPI - Docker](docker.md){.internal-link target=_blank} + +特に**Kubernetes**上で実行する場合は、おそらく**Gunicornを使用せず**、**コンテナごとに単一のUvicornプロセス**を実行することになりますが、それについてはこの章の後半で説明します。 + +/// ## GunicornによるUvicornのワーカー・プロセスの管理 @@ -167,7 +170,7 @@ $ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4 ## コンテナとDocker -次章の[コンテナ内のFastAPI - Docker](./docker.md){.internal-link target=_blank}では、その他の**デプロイのコンセプト**を扱うために実施するであろう戦略をいくつか紹介します。 +次章の[コンテナ内のFastAPI - Docker](docker.md){.internal-link target=_blank}では、その他の**デプロイのコンセプト**を扱うために実施するであろう戦略をいくつか紹介します。 また、**GunicornとUvicornワーカー**を含む**公式Dockerイメージ**と、簡単なケースに役立ついくつかのデフォルト設定も紹介します。 diff --git a/docs/ja/docs/deployment/versions.md b/docs/ja/docs/deployment/versions.md index 03cccb3f3..7575fc4f7 100644 --- a/docs/ja/docs/deployment/versions.md +++ b/docs/ja/docs/deployment/versions.md @@ -42,8 +42,11 @@ PoetryやPipenvなど、他のインストール管理ツールを使用して FastAPIでは「パッチ」バージョンはバグ修正と非破壊的な変更に留めるという規約に従っています。 -!!! tip "豆知識" - 「パッチ」は最後の数字を指します。例えば、`0.2.3` ではパッチバージョンは `3` です。 +/// tip | 豆知識 + +「パッチ」は最後の数字を指します。例えば、`0.2.3` ではパッチバージョンは `3` です。 + +/// 従って、以下の様なバージョンの固定が望ましいです: @@ -53,8 +56,11 @@ fastapi>=0.45.0,<0.46.0 破壊的な変更と新機能実装は「マイナー」バージョンで加えられます。 -!!! tip "豆知識" - 「マイナー」は真ん中の数字です。例えば、`0.2.3` ではマイナーバージョンは `2` です。 +/// tip | 豆知識 + +「マイナー」は真ん中の数字です。例えば、`0.2.3` ではマイナーバージョンは `2` です。 + +/// ## FastAPIのバージョンのアップグレード diff --git a/docs/ja/docs/environment-variables.md b/docs/ja/docs/environment-variables.md new file mode 100644 index 000000000..507af3a0c --- /dev/null +++ b/docs/ja/docs/environment-variables.md @@ -0,0 +1,301 @@ +# 環境変数 + +/// tip + +もし、「環境変数」とは何か、それをどう使うかを既に知っている場合は、このセクションをスキップして構いません。 + +/// + +環境変数(**env var**とも呼ばれる)はPythonコードの**外側**、つまり**OS**に存在する変数で、Pythonから読み取ることができます。(他のプログラムでも同様に読み取れます。) + +環境変数は、アプリケーションの**設定**の管理や、Pythonの**インストール**などに役立ちます。 + +## 環境変数の作成と使用 + +環境変数は**シェル(ターミナル)**内で**作成**して使用でき、それらにPythonは不要です。 + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// You could create an env var MY_NAME with +$ export MY_NAME="Wade Wilson" + +// Then you could use it with other programs, like +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ + +```console +// Create an env var MY_NAME +$ $Env:MY_NAME = "Wade Wilson" + +// Use it with other programs, like +$ echo "Hello $Env:MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +## Pythonで環境変数を読み取る + +環境変数をPythonの**外側**、ターミナル(や他の方法)で作成し、**Python内で読み取る**こともできます。 + +例えば、以下のような`main.py`ファイルを用意します: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// tip + +`os.getenv()` の第2引数は、デフォルトで返される値を指定します。 + +この引数を省略するとデフォルト値として`None`が返されますが、ここではデフォルト値として`"World"`を指定しています。 + +/// + +次に、このPythonプログラムを呼び出します。 + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// Here we don't set the env var yet +$ python main.py + +// As we didn't set the env var, we get the default value + +Hello World from Python + +// But if we create an environment variable first +$ export MY_NAME="Wade Wilson" + +// And then call the program again +$ python main.py + +// Now it can read the environment variable + +Hello Wade Wilson from Python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// Here we don't set the env var yet +$ python main.py + +// As we didn't set the env var, we get the default value + +Hello World from Python + +// But if we create an environment variable first +$ $Env:MY_NAME = "Wade Wilson" + +// And then call the program again +$ python main.py + +// Now it can read the environment variable + +Hello Wade Wilson from Python +``` + +
+ +//// + +環境変数はコードの外側で設定し、内側から読み取ることができるので、他のファイルと一緒に(`git`に)保存する必要がありません。そのため、環境変数をコンフィグレーションや**設定**に使用することが一般的です。 + +また、**特定のプログラムの呼び出し**のための環境変数を、そのプログラムのみ、その実行中に限定して利用できるよう作成できます。 + +そのためには、プログラム起動コマンドと同じコマンドライン上の、起動コマンド直前で環境変数を作成してください。 + +
+ +```console +// Create an env var MY_NAME in line for this program call +$ MY_NAME="Wade Wilson" python main.py + +// Now it can read the environment variable + +Hello Wade Wilson from Python + +// The env var no longer exists afterwards +$ python main.py + +Hello World from Python +``` + +
+ +/// tip + +詳しくは The Twelve-Factor App: Config を参照してください。 + +/// + +## 型とバリデーション + +環境変数は**テキスト文字列**のみを扱うことができます。これは、環境変数がPython外部に存在し、他のプログラムやシステム全体(Linux、Windows、macOS間の互換性を含む)と連携する必要があるためです。 + +つまり、Pythonが環境変数から読み取る**あらゆる値**は **`str`型となり**、他の型への変換やバリデーションはコード内で行う必要があります。 + +環境変数を使用して**アプリケーション設定**を管理する方法については、[高度なユーザーガイド - Settings and Environment Variables](./advanced/settings.md){.internal-link target=_blank}で詳しく学べます。 + +## `PATH`環境変数 + +**`PATH`**という**特別な**環境変数があります。この環境変数は、OS(Linux、macOS、Windows)が実行するプログラムを発見するために使用されます。 + +`PATH`変数は、複数のディレクトリのパスから成る長い文字列です。このパスはLinuxやMacOSの場合は`:`で、Windowsの場合は`;`で区切られています。 + +例えば、`PATH`環境変数は次のような文字列かもしれません: + +//// tab | Linux, macOS + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +これは、OSはプログラムを見つけるために以下のディレクトリを探す、ということを意味します: + +* `/usr/local/bin` +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32 +``` + +これは、OSはプログラムを見つけるために以下のディレクトリを探す、ということを意味します: + +* `C:\Program Files\Python312\Scripts` +* `C:\Program Files\Python312` +* `C:\Windows\System32` + +//// + +ターミナル上で**コマンド**を入力すると、 OSはそのプログラムを見つけるために、`PATH`環境変数のリストに記載された**それぞれのディレクトリを探し**ます。 + +例えば、ターミナル上で`python`を入力すると、OSは`python`によって呼ばれるプログラムを見つけるために、そのリストの**先頭のディレクトリ**を最初に探します。 + +OSは、もしそのプログラムをそこで発見すれば**実行し**ますが、そうでなければリストの**他のディレクトリ**を探していきます。 + +### PythonのインストールとPATH環境変数の更新 + +Pythonのインストール時に`PATH`環境変数を更新したいか聞かれるかもしれません。 + +/// tab | Linux, macOS + +Pythonをインストールして、そのプログラムが`/opt/custompython/bin`というディレクトリに配置されたとします。 + +もし、`PATH`環境変数を更新するように答えると、`PATH`環境変数に`/opt/custompython/bin`が追加されます。 + +`PATH`環境変数は以下のように更新されるでしょう: + +``` plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin +``` + +このようにして、ターミナルで`python`と入力したときに、OSは`/opt/custompython/bin`(リストの末尾のディレクトリ)にあるPythonプログラムを見つけ、使用します。 + +/// + +/// tab | Windows + +Pythonをインストールして、そのプログラムが`C:\opt\custompython\bin`というディレクトリに配置されたとします。 + +もし、`PATH`環境変数を更新するように答えると、`PATH`環境変数に`C:\opt\custompython\bin`が追加されます。 + +`PATH`環境変数は以下のように更新されるでしょう: + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin +``` + +このようにして、ターミナルで`python`と入力したときに、OSは`C:\opt\custompython\bin\python`(リストの末尾のディレクトリ)にあるPythonプログラムを見つけ、使用します。 + +/// + +つまり、ターミナルで以下のコマンドを入力すると: + +
+ +``` console +$ python +``` + +
+ +/// tab | Linux, macOS + +OSは`/opt/custompython/bin`にある`python`プログラムを**見つけ**て実行します。 + +これは、次のコマンドを入力した場合とほとんど同等です: + +
+ +```console +$ /opt/custompython/bin/python +``` + +
+ +/// + +/// tab | Windows + +OSは`C:\opt\custompython\bin\python`にある`python`プログラムを**見つけ**て実行します。 + +これは、次のコマンドを入力した場合とほとんど同等です: + +
+ +```console +$ C:\opt\custompython\bin\python +``` + +
+ +/// + +この情報は、[Virtual Environments](virtual-environments.md) について学ぶ際にも役立ちます。 + +## まとめ + +これで、**環境変数**とは何か、Pythonでどのように使用するかについて、基本的な理解が得られたはずです。 + +環境変数についての詳細は、Wikipedia: Environment Variable を参照してください。 + +環境変数の用途や適用方法が最初は直感的ではないかもしれませんが、開発中のさまざまなシナリオで繰り返し登場します。そのため、基本を知っておくことが重要です。 + +たとえば、この情報は次のセクションで扱う[Virtual Environments](virtual-environments.md)にも関連します。 diff --git a/docs/ja/docs/external-links.md b/docs/ja/docs/external-links.md deleted file mode 100644 index aca5d5b34..000000000 --- a/docs/ja/docs/external-links.md +++ /dev/null @@ -1,33 +0,0 @@ -# 外部リンク・記事 - -**FastAPI**には、絶えず成長している素晴らしいコミュニティがあります。 - -**FastAPI**に関連する投稿、記事、ツール、およびプロジェクトは多数あります。 - -それらの不完全なリストを以下に示します。 - -!!! tip "豆知識" - ここにまだ載っていない**FastAPI**に関連する記事、プロジェクト、ツールなどがある場合は、 プルリクエストして下さい。 - -{% for section_name, section_content in external_links.items() %} - -## {{ section_name }} - -{% for lang_name, lang_content in section_content.items() %} - -### {{ lang_name }} - -{% for item in lang_content %} - -* {{ item.title }} by {{ item.author }}. - -{% endfor %} -{% endfor %} -{% endfor %} - -## プロジェクト - -`fastapi`トピックの最新のGitHubプロジェクト: - -
-
diff --git a/docs/ja/docs/fastapi-people.md b/docs/ja/docs/fastapi-people.md deleted file mode 100644 index 11dd656ea..000000000 --- a/docs/ja/docs/fastapi-people.md +++ /dev/null @@ -1,179 +0,0 @@ -# FastAPI People - -FastAPIには、様々なバックグラウンドの人々を歓迎する素晴らしいコミュニティがあります。 - -## Creator - Maintainer - -こんにちは! 👋 - -これが私です: - -{% if people %} -
-{% for user in people.maintainers %} - -
@{{ user.login }}
Answers: {{ user.answers }}
Pull Requests: {{ user.prs }}
-{% endfor %} - -
- -{% endif %} - -私は **FastAPI** の作成者および Maintainer です。詳しくは [FastAPIを応援 - ヘルプの入手 - 開発者とつながる](help-fastapi.md#開発者とつながる){.internal-link target=_blank} に記載しています。 - -...ところで、ここではコミュニティを紹介したいと思います。 - ---- - -**FastAPI** は、コミュニティから多くのサポートを受けています。そこで、彼らの貢献にスポットライトを当てたいと思います。 - -紹介するのは次のような人々です: - -* [GitHub issuesで他の人を助ける](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}。 -* [プルリクエストをする](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}。 -* プルリクエストのレビューをする ([特に翻訳に重要](contributing.md#translations){.internal-link target=_blank})。 - -彼らに大きな拍手を。👏 🙇 - -## 先月最もアクティブだったユーザー - -彼らは、先月の[GitHub issuesで最も多くの人を助けた](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}ユーザーです。☕ - -{% if people %} -
-{% for user in people.last_month_active %} - -
@{{ user.login }}
Issues replied: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Experts - -**FastAPI experts** を紹介します。🤓 - -彼らは、*これまでに* [GitHub issuesで最も多くの人を助けた](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}ユーザーです。 - -多くの人を助けることでexpertsであると示されています。✨ - -{% if people %} -
-{% for user in people.experts %} - -
@{{ user.login }}
Issues replied: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Top Contributors - -**Top Contributors** を紹介します。👷 - -彼らは、*マージされた* [最も多くのプルリクエストを作成した](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}ユーザーです。 - -ソースコード、ドキュメント、翻訳などに貢献してくれました。📦 - -{% if people %} -
-{% for user in people.top_contributors %} - -
@{{ user.login }}
Pull Requests: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -他にもたくさん (100人以上) の contributors がいます。FastAPI GitHub Contributors ページですべての contributors を確認できます。👷 - -## Top Reviewers - -以下のユーザーは **Top Reviewers** です。🕵️ - -### 翻訳のレビュー - -私は少しの言語しか話せません (もしくはあまり上手ではありません😅)。したがって、reviewers は、ドキュメントの[**翻訳を承認する権限**](contributing.md#translations){.internal-link target=_blank}を持っています。それらがなければ、いくつかの言語のドキュメントはなかったでしょう。 - ---- - -**Top Reviewers** 🕵️は、他の人からのプルリクエストのほとんどをレビューし、コード、ドキュメント、特に**翻訳**の品質を保証しています。 - -{% if people %} -
-{% for user in people.top_reviewers %} - -
@{{ user.login }}
Reviews: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Sponsors - -**Sponsors** を紹介します。😎 - -彼らは、GitHub Sponsors を介して私の **FastAPI** などに関する活動を支援してくれています。 - -{% if sponsors %} - -{% if sponsors.gold %} - -### Gold Sponsors - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Silver Sponsors - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Bronze Sponsors - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -{% endif %} - -### Individual Sponsors - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
- -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
- -{% endfor %} -{% endif %} - -## データについて - 技術詳細 - -このページの目的は、他の人を助けるためのコミュニティの努力にスポットライトを当てるためです。 - -特に、他の人の issues を支援したり、翻訳のプルリクエストを確認したりするなど、通常は目立たず、多くの場合、より困難な作業を含みます。 - -データは毎月集計されます。ソースコードはこちらで確認できます。 - -ここでは、スポンサーの貢献も強調しています。 - -アルゴリズム、セクション、閾値などは更新されるかもしれません (念のために 🤷)。 diff --git a/docs/ja/docs/features.md b/docs/ja/docs/features.md index 853364f11..4024590cf 100644 --- a/docs/ja/docs/features.md +++ b/docs/ja/docs/features.md @@ -62,10 +62,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info "情報" - `**second_user_data` は以下を意味します: +/// info | 情報 - `second_user_data`辞書のキーと値を直接、キーと値の引数として渡します。これは、`User(id=4, name="Mary", joined="2018-11-30")`と同等です。 +`**second_user_data` は以下を意味します: + +`second_user_data`辞書のキーと値を直接、キーと値の引数として渡します。これは、`User(id=4, name="Mary", joined="2018-11-30")`と同等です。 + +/// ### エディタのサポート @@ -177,7 +180,7 @@ FastAPIには非常に使いやすく、非常に強力なIDE/リンター/思考 とうまく連携します**: * Pydanticのデータ構造は、ユーザーが定義するクラスの単なるインスタンスであるため、オートコンプリート、リンティング、mypy、およびユーザーの直感はすべて、検証済みのデータで適切に機能するはずです。 -* **高速**: - * ベンチマークでは、Pydanticは他のすべてのテスト済みライブラリよりも高速です。 * **複雑な構造**を検証: * 階層的なPydanticモデルや、Pythonの「`typing`」の「`list`」と「`dict`」などの利用。 * バリデーターにより、複雑なデータスキーマを明確かつ簡単に定義、チェックし、JSONスキーマとして文書化できます。 diff --git a/docs/ja/docs/help-fastapi.md b/docs/ja/docs/help-fastapi.md index e753b7ce3..d999fa127 100644 --- a/docs/ja/docs/help-fastapi.md +++ b/docs/ja/docs/help-fastapi.md @@ -12,13 +12,13 @@ FastAPIやユーザーや開発者を応援したいですか? ## GitHubで **FastAPI** にStar -GitHubでFastAPIに「Star」をつけることができます (右上部のStarボタンをクリック): https://github.com/tiangolo/fastapi. ⭐️ +GitHubでFastAPIに「Star」をつけることができます (右上部のStarボタンをクリック): https://github.com/fastapi/fastapi. ⭐️ スターを増やすことで、他のユーザーの目につきやすくなり、多くの人にとって便利なものであることを示せます。 ## GitHubレポジトリのリリースをWatch -GitHubでFastAPIを「Watch」できます (右上部のWatchボタンをクリック): https://github.com/tiangolo/fastapi. 👀 +GitHubでFastAPIを「Watch」できます (右上部のWatchボタンをクリック): https://github.com/fastapi/fastapi. 👀 そこで「Releases only」を選択できます。 @@ -42,7 +42,7 @@ GitHubでFastAPIを「Watch」できます (右上部のWatchボタンをクリ ## **FastAPI** に関するツイート -**FastAPI** についてツイートし、開発者や他の人にどこが気に入ったのか教えてください。🎉 +**FastAPI** についてツイートし、開発者や他の人にどこが気に入ったのか教えてください。🎉 **FastAPI** がどのように使われ、どこが気に入られ、どんなプロジェクト/会社で使われているかなどについて知りたいです。 @@ -54,11 +54,11 @@ GitHubでFastAPIを「Watch」できます (右上部のWatchボタンをクリ ## GitHub issuesで他の人を助ける -既存のissuesを確認して、他の人を助けてみてください。皆さんが回答を知っているかもしれない質問がほとんどです。🤓 +既存のissuesを確認して、他の人を助けてみてください。皆さんが回答を知っているかもしれない質問がほとんどです。🤓 ## GitHubレポジトリをWatch -GitHubでFastAPIを「watch」できます (右上部の「watch」ボタンをクリック): https://github.com/tiangolo/fastapi. 👀 +GitHubでFastAPIを「watch」できます (右上部の「watch」ボタンをクリック): https://github.com/fastapi/fastapi. 👀 「Releases only」ではなく「Watching」を選択すると、新たなissueが立てられた際に通知されます。 @@ -66,7 +66,7 @@ GitHubでFastAPIを「watch」できます (右上部の「watch」ボタンを ## issuesを立てる -GitHubレポジトリで新たなissueを立てられます。例えば: +GitHubレポジトリで新たなissueを立てられます。例えば: * 質問、または、問題の報告 * 新機能の提案 @@ -75,7 +75,7 @@ GitHubレポジトリでプルリクエストを作成できます: +以下の様なプルリクエストを作成できます: * ドキュメントのタイプミスを修正。 * 新たなドキュメントセクションを提案。 diff --git a/docs/ja/docs/history-design-future.md b/docs/ja/docs/history-design-future.md index d0d1230c4..bc4a160ea 100644 --- a/docs/ja/docs/history-design-future.md +++ b/docs/ja/docs/history-design-future.md @@ -1,6 +1,6 @@ # 歴史、設計、そしてこれから -少し前に、**FastAPI** +少し前に、**FastAPI** のユーザーに以下の様に尋ねられました: > このプロジェクトの歴史は?何もないところから、数週間ですごいものができているようです。 [...] @@ -55,7 +55,7 @@ ## 要件 -いくつかの代替手法を試したあと、私は**Pydantic**の強みを利用することを決めました。 +いくつかの代替手法を試したあと、私は**Pydantic**の強みを利用することを決めました。 そして、JSON Schemaに完全に準拠するようにしたり、制約宣言を定義するさまざまな方法をサポートしたり、いくつかのエディターでのテストに基づいてエディターのサポート (型チェック、自動補完) を改善するために貢献しました。 diff --git a/docs/ja/docs/how-to/conditional-openapi.md b/docs/ja/docs/how-to/conditional-openapi.md index b892ed6c6..bfaa9e6d7 100644 --- a/docs/ja/docs/how-to/conditional-openapi.md +++ b/docs/ja/docs/how-to/conditional-openapi.md @@ -29,9 +29,7 @@ 例えば、 -```Python hl_lines="6 11" -{!../../../docs_src/conditional_openapi/tutorial001.py!} -``` +{* ../../docs_src/conditional_openapi/tutorial001.py hl[6,11] *} ここでは `openapi_url` の設定を、デフォルトの `"/openapi.json"` のまま宣言しています。 diff --git a/docs/ja/docs/index.md b/docs/ja/docs/index.md index 22c31e7ca..1ba85f8e0 100644 --- a/docs/ja/docs/index.md +++ b/docs/ja/docs/index.md @@ -1,3 +1,9 @@ +# FastAPI + + +

FastAPI

@@ -5,14 +11,17 @@ FastAPI framework, high performance, easy to learn, fast to code, ready for production

- - Build Status + + Test - - Coverage + + Coverage + + + Package version - Package version + Supported Python versions

@@ -20,15 +29,15 @@ **ドキュメント**: https://fastapi.tiangolo.com -**ソースコード**: https://github.com/tiangolo/fastapi +**ソースコード**: https://github.com/fastapi/fastapi --- -FastAPI は、Pythonの標準である型ヒントに基づいてPython 3.8 以降でAPI を構築するための、モダンで、高速(高パフォーマンス)な、Web フレームワークです。 +FastAPI は、Pythonの標準である型ヒントに基づいてPython 以降でAPI を構築するための、モダンで、高速(高パフォーマンス)な、Web フレームワークです。 主な特徴: -- **高速**: **NodeJS** や **Go** 並みのとても高いパフォーマンス (Starlette と Pydantic のおかげです)。 [最も高速な Python フレームワークの一つです](#performance). +- **高速**: **NodeJS** や **Go** 並みのとても高いパフォーマンス (Starlette と Pydantic のおかげです)。 [最も高速な Python フレームワークの一つです](#_10). - **高速なコーディング**: 開発速度を約 200%~300%向上させます。 \* - **少ないバグ**: 開発者起因のヒューマンエラーを約 40%削減します。 \* @@ -61,7 +70,7 @@ FastAPI は、Pythonの標準である型ヒントに基づいてPython 3.8 以 "_[...] 最近 **FastAPI** を使っています。 [...] 実際に私のチームの全ての **Microsoft の機械学習サービス** で使用する予定です。 そのうちのいくつかのコアな**Windows**製品と**Office**製品に統合されつつあります。_" -
Kabir Khan - Microsoft (ref)
+
Kabir Khan - Microsoft (ref)
--- @@ -85,7 +94,7 @@ FastAPI は、Pythonの標準である型ヒントに基づいてPython 3.8 以 "_正直、超堅実で洗練されているように見えます。いろんな意味で、それは私がハグしたかったものです。_" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- @@ -107,12 +116,10 @@ FastAPI は、Pythonの標準である型ヒントに基づいてPython 3.8 以 ## 必要条件 -Python 3.8+ - FastAPI は巨人の肩の上に立っています。 - Web の部分はStarlette -- データの部分はPydantic +- データの部分はPydantic ## インストール @@ -126,7 +133,7 @@ $ pip install fastapi -本番環境では、Uvicorn または、 Hypercornのような、 ASGI サーバーが必要になります。 +本番環境では、Uvicorn または、 Hypercornのような、 ASGI サーバーが必要になります。
@@ -431,22 +438,22 @@ item: Item Pydantic によって使用されるもの: -- email_validator - E メールの検証 +- email-validator - E メールの検証 Starlette によって使用されるもの: - httpx - `TestClient`を使用するために必要です。 - jinja2 - デフォルトのテンプレート設定を使用する場合は必要です。 -- python-multipart - "parsing"`request.form()`からの変換をサポートしたい場合は必要です。 +- python-multipart - "parsing"`request.form()`からの変換をサポートしたい場合は必要です。 - itsdangerous - `SessionMiddleware` サポートのためには必要です。 - pyyaml - Starlette の `SchemaGenerator` サポートのために必要です。 (FastAPI では必要ないでしょう。) - graphene - `GraphQLApp` サポートのためには必要です。 -- ujson - `UJSONResponse`を使用する場合は必須です。 FastAPI / Starlette に使用されるもの: - uvicorn - アプリケーションをロードしてサーブするサーバーのため。 - orjson - `ORJSONResponse`を使用したい場合は必要です。 +- ujson - `UJSONResponse`を使用する場合は必須です。 これらは全て `pip install fastapi[all]`でインストールできます。 diff --git a/docs/ja/docs/learn/index.md b/docs/ja/docs/learn/index.md new file mode 100644 index 000000000..2f24c670a --- /dev/null +++ b/docs/ja/docs/learn/index.md @@ -0,0 +1,5 @@ +# 学習 + +ここでは、**FastAPI** を学習するための入門セクションとチュートリアルを紹介します。 + +これは、FastAPIを学習するにあたっての**書籍**や**コース**であり、**公式**かつ推奨される方法とみなすことができます 😎 diff --git a/docs/ja/docs/project-generation.md b/docs/ja/docs/project-generation.md index 4b6f0f9fd..daef52efa 100644 --- a/docs/ja/docs/project-generation.md +++ b/docs/ja/docs/project-generation.md @@ -14,7 +14,7 @@ GitHub: **FastAPI** バックエンド: +* Python **FastAPI** バックエンド: * **高速**: **NodeJS** や **Go** 並みのとても高いパフォーマンス (Starlette と Pydantic のおかげ)。 * **直感的**: 素晴らしいエディタのサポートや 補完。 デバッグ時間の短縮。 * **簡単**: 簡単に利用、習得できるようなデザイン。ドキュメントを読む時間を削減。 diff --git a/docs/ja/docs/python-types.md b/docs/ja/docs/python-types.md new file mode 100644 index 000000000..a847ce5d5 --- /dev/null +++ b/docs/ja/docs/python-types.md @@ -0,0 +1,314 @@ +# Pythonの型の紹介 + +**Python 3.6以降** では「型ヒント」オプションがサポートされています。 + +これらの **"型ヒント"** は変数のを宣言することができる新しい構文です。(Python 3.6以降) + +変数に型を宣言することでエディターやツールがより良いサポートを提供することができます。 + +ここではPythonの型ヒントについての **クイックチュートリアル/リフレッシュ** で、**FastAPI**でそれらを使用するために必要な最低限のことだけをカバーしています。...実際には本当に少ないです。 + +**FastAPI** はすべてこれらの型ヒントに基づいており、多くの強みと利点を与えてくれます。 + +しかしたとえまったく **FastAPI** を使用しない場合でも、それらについて少し学ぶことで利点を得ることができるでしょう。 + +/// note | 備考 + +もしあなたがPythonの専門家で、すでに型ヒントについてすべて知っているのであれば、次の章まで読み飛ばしてください。 + +/// + +## 動機 + +簡単な例から始めてみましょう: + +{* ../../docs_src/python_types/tutorial001.py *} + + +このプログラムを実行すると以下が出力されます: + +``` +John Doe +``` + +この関数は以下のようなことを行います: + +* `first_name`と`last_name`を取得します。 +* `title()`を用いて、それぞれの最初の文字を大文字に変換します。 +* 真ん中にスペースを入れて連結します。 + +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + + +### 編集 + +これはとても簡単なプログラムです。 + +しかし、今、あなたがそれを一から書いていたと想像してみてください。 + +パラメータの準備ができていたら、そのとき、関数の定義を始めていたことでしょう... + +しかし、そうすると「最初の文字を大文字に変換するあのメソッド」を呼び出す必要があります。 + +それは`upper`でしたか?`uppercase`でしたか?それとも`first_uppercase`?または`capitalize`? + +そして、古くからプログラマーの友人であるエディタで自動補完を試してみます。 + +関数の最初のパラメータ`first_name`を入力し、ドット(`.`)を入力してから、`Ctrl+Space`を押すと補完が実行されます。 + +しかし、悲しいことに、これはなんの役にも立ちません: + + + +### 型の追加 + +先ほどのコードから一行変更してみましょう。 + +以下の関数のパラメータ部分を: + +```Python + first_name, last_name +``` + +以下へ変更します: + +```Python + first_name: str, last_name: str +``` + +これだけです。 + +それが「型ヒント」です: + +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + + +これは、以下のようにデフォルト値を宣言するのと同じではありません: + +```Python + first_name="john", last_name="doe" +``` + +それとは別物です。 + +イコール(`=`)ではなく、コロン(`:`)を使用します。 + +そして、通常、型ヒントを追加しても、それらがない状態と起こることは何も変わりません。 + +しかし今、あなたが再びその関数を作成している最中に、型ヒントを使っていると想像してみて下さい。 + +同じタイミングで`Ctrl+Space`で自動補完を実行すると、以下のようになります: + + + +これであれば、あなたは「ベルを鳴らす」一つを見つけるまで、オプションを見て、スクロールすることができます: + + + +## より強い動機 + +この関数を見てください。すでに型ヒントを持っています: + +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + + +エディタは変数の型を知っているので、補完だけでなく、エラーチェックをすることもできます。 + + + +これで`age`を`str(age)`で文字列に変換して修正する必要があることがわかります: + +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + + +## 型の宣言 + +関数のパラメータとして、型ヒントを宣言している主な場所を確認しました。 + +これは **FastAPI** で使用する主な場所でもあります。 + +### 単純な型 + +`str`だけでなく、Pythonの標準的な型すべてを宣言することができます。 + +例えば、以下を使用可能です: + +* `int` +* `float` +* `bool` +* `bytes` + +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + + +### 型パラメータを持つジェネリック型 + +データ構造の中には、`dict`、`list`、`set`、そして`tuple`のように他の値を含むことができるものがあります。また内部の値も独自の型を持つことができます。 + +これらの型や内部の型を宣言するには、Pythonの標準モジュール`typing`を使用します。 + +これらの型ヒントをサポートするために特別に存在しています。 + +#### `List` + +例えば、`str`の`list`の変数を定義してみましょう。 + +`typing`から`List`をインポートします(大文字の`L`を含む): + +{* ../../docs_src/python_types/tutorial006.py hl[1] *} + + +同じようにコロン(`:`)の構文で変数を宣言します。 + +型として、`List`を入力します。 + +リストはいくつかの内部の型を含む型なので、それらを角括弧で囲んでいます。 + +{* ../../docs_src/python_types/tutorial006.py hl[4] *} + + +/// tip | 豆知識 + +角括弧内の内部の型は「型パラメータ」と呼ばれています。 + +この場合、`str`は`List`に渡される型パラメータです。 + +/// + +つまり: 変数`items`は`list`であり、このリストの各項目は`str`です。 + +そうすることで、エディタはリストの項目を処理している間にもサポートを提供できます。 + + + +タイプがなければ、それはほぼ不可能です。 + +変数`item`はリスト`items`の要素の一つであることに注意してください。 + +それでも、エディタはそれが`str`であることを知っていて、そのためのサポートを提供しています。 + +#### `Tuple` と `Set` + +`tuple`と`set`の宣言も同様です: + +{* ../../docs_src/python_types/tutorial007.py hl[1,4] *} + + +つまり: + +* 変数`items_t`は`int`、`int`、`str`の3つの項目を持つ`tuple`です + +* 変数`items_s`はそれぞれの項目が`bytes`型である`set`です。 + +#### `Dict` + +`dict`を宣言するためには、カンマ区切りで2つの型パラメータを渡します。 + +最初の型パラメータは`dict`のキーです。 + +2番目の型パラメータは`dict`の値です。 + +{* ../../docs_src/python_types/tutorial008.py hl[1,4] *} + + +つまり: + +* 変数`prices`は`dict`であり: + * この`dict`のキーは`str`型です。(つまり、各項目の名前) + * この`dict`の値は`float`型です。(つまり、各項目の価格) + +#### `Optional` + +また、`Optional`を使用して、変数が`str`のような型を持つことを宣言することもできますが、それは「オプション」であり、`None`にすることもできます。 + +```Python hl_lines="1 4" +{!../../docs_src/python_types/tutorial009.py!} +``` + +ただの`str`の代わりに`Optional[str]`を使用することで、エディタは値が常に`str`であると仮定している場合に実際には`None`である可能性があるエラーを検出するのに役立ちます。 + +#### ジェネリック型 + +以下のように角括弧で型パラメータを取る型を: + +* `List` +* `Tuple` +* `Set` +* `Dict` +* `Optional` +* ...など + +**ジェネリック型** または **ジェネリクス** と呼びます。 + +### 型としてのクラス + +変数の型としてクラスを宣言することもできます。 + +例えば、`Person`クラスという名前のクラスがあるとしましょう: + +{* ../../docs_src/python_types/tutorial010.py hl[1,2,3] *} + + +変数の型を`Person`として宣言することができます: + +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + + +そして、再び、すべてのエディタのサポートを得ることができます: + + + +## Pydanticのモデル + +Pydantic はデータ検証を行うためのPythonライブラリです。 + +データの「形」を属性付きのクラスとして宣言します。 + +そして、それぞれの属性は型を持ちます。 + +さらに、いくつかの値を持つクラスのインスタンスを作成すると、その値を検証し、適切な型に変換して(もしそうであれば)全てのデータを持つオブジェクトを提供してくれます。 + +また、その結果のオブジェクトですべてのエディタのサポートを受けることができます。 + +Pydanticの公式ドキュメントから引用: + +{* ../../docs_src/python_types/tutorial011.py *} + + +/// info | 情報 + +Pydanticについてより学びたい方はドキュメントを参照してください. + +/// + +**FastAPI** はすべてPydanticをベースにしています。 + +すべてのことは[チュートリアル - ユーザーガイド](tutorial/index.md){.internal-link target=_blank}で実際に見ることができます。 + +## **FastAPI**での型ヒント + +**FastAPI** はこれらの型ヒントを利用していくつかのことを行います。 + +**FastAPI** では型ヒントを使って型パラメータを宣言すると以下のものが得られます: + +* **エディタサポート**. +* **型チェック**. + +...そして **FastAPI** は同じように宣言をすると、以下のことを行います: + +* **要件の定義**: リクエストパスパラメータ、クエリパラメータ、ヘッダー、ボディ、依存関係などから要件を定義します。 +* **データの変換**: リクエストのデータを必要な型に変換します。 +* **データの検証**: リクエストごとに: + * データが無効な場合にクライアントに返される **自動エラー** を生成します。 +* **ドキュメント** OpenAPIを使用したAPI: + * 自動的に対話型ドキュメントのユーザーインターフェイスで使用されます。 + +すべてが抽象的に聞こえるかもしれません。心配しないでください。 この全ての動作は [チュートリアル - ユーザーガイド](tutorial/index.md){.internal-link target=_blank}で見ることができます。 + +重要なのは、Pythonの標準的な型を使うことで、(クラスやデコレータなどを追加するのではなく)1つの場所で **FastAPI** が多くの作業を代わりにやってくれているということです。 + +/// info | 情報 + +すでにすべてのチュートリアルを終えて、型についての詳細を見るためにこのページに戻ってきた場合は、`mypy`のチートシートを参照してください + +/// diff --git a/docs/ja/docs/tutorial/background-tasks.md b/docs/ja/docs/tutorial/background-tasks.md new file mode 100644 index 000000000..650a079fb --- /dev/null +++ b/docs/ja/docs/tutorial/background-tasks.md @@ -0,0 +1,84 @@ +# バックグラウンドタスク + +レスポンスを返した *後に* 実行されるバックグラウンドタスクを定義できます。 + +これは、リクエスト後に処理を開始する必要があるが、クライアントがレスポンスを受け取る前に処理を終える必要のない操作に役立ちます。 + +これには、たとえば次のものが含まれます。 + +* 作業実行後のメール通知: + * メールサーバーへの接続とメールの送信は「遅い」(数秒) 傾向があるため、すぐにレスポンスを返し、バックグラウンドでメール通知ができます。 +* データ処理: + * たとえば、時間のかかる処理を必要とするファイル受信時には、「受信済み」(HTTP 202) のレスポンスを返し、バックグラウンドで処理できます。 + +## `BackgroundTasks` の使用 + +まず初めに、`BackgroundTasks` をインポートし、` BackgroundTasks` の型宣言と共に、*path operation 関数* のパラメーターを定義します: + +{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *} + +**FastAPI** は、`BackgroundTasks` 型のオブジェクトを作成し、そのパラメーターに渡します。 + +## タスク関数の作成 + +バックグラウンドタスクとして実行される関数を作成します。 + +これは、パラメーターを受け取ることができる単なる標準的な関数です。 + +これは `async def` または通常の `def` 関数であり、**FastAPI** はこれを正しく処理します。 + +ここで、タスク関数はファイル書き込みを実行します (メール送信のシミュレーション)。 + +また、書き込み操作では `async` と `await` を使用しないため、通常の `def` で関数を定義します。 + +{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *} + +## バックグラウンドタスクの追加 + +*path operations 関数* 内で、`.add_task()` メソッドを使用してタスク関数を *background tasks* オブジェクトに渡します。 + +{* ../../docs_src/background_tasks/tutorial001.py hl[14] *} + +`.add_task()` は以下の引数を受け取ります: + +* バックグラウンドで実行されるタスク関数 (`write_notification`)。 +* タスク関数に順番に渡す必要のある引数の列 (`email`)。 +* タスク関数に渡す必要のあるキーワード引数 (`message="some notification"`)。 + +## 依存性注入 + +`BackgroundTasks` の使用は依存性注入システムでも機能し、様々な階層 (*path operations 関数*、依存性 (依存可能性)、サブ依存性など) で `BackgroundTasks` 型のパラメーターを宣言できます。 + +**FastAPI** は、それぞれの場合の処理​​方法と同じオブジェクトの再利用方法を知っているため、すべてのバックグラウンドタスクがマージされ、バックグラウンドで後で実行されます。 + +{* ../../docs_src/background_tasks/tutorial002.py hl[13,15,22,25] *} + +この例では、レスポンスが送信された *後* にメッセージが `log.txt` ファイルに書き込まれます。 + +リクエストにクエリがあった場合、バックグラウンドタスクでログに書き込まれます。 + +そして、*path operations 関数* で生成された別のバックグラウンドタスクは、`email` パスパラメータを使用してメッセージを書き込みます。 + +## 技術的な詳細 + +`BackgroundTasks` クラスは、`starlette.background`から直接取得されます。 + +これは、FastAPI に直接インポート/インクルードされるため、`fastapi` からインポートできる上に、`starlette.background`から別の `BackgroundTask` (末尾に `s` がない) を誤ってインポートすることを回避できます。 + +`BackgroundTasks`のみを使用することで (`BackgroundTask` ではなく)、`Request` オブジェクトを直接使用する場合と同様に、それを *path operations 関数* パラメーターとして使用し、**FastAPI** に残りの処理を任せることができます。 + +それでも、FastAPI で `BackgroundTask` を単独で使用することは可能ですが、コード内でオブジェクトを作成し、それを含むStarlette `Response` を返す必要があります。 + +詳細については、バックグラウンドタスクに関する Starlette の公式ドキュメントを参照して下さい。 + +## 警告 + +大量のバックグラウンド計算が必要であり、必ずしも同じプロセスで実行する必要がない場合 (たとえば、メモリや変数などを共有する必要がない場合)、Celery のようなより大きな他のツールを使用するとメリットがあるかもしれません。 + +これらは、より複雑な構成、RabbitMQ や Redis などのメッセージ/ジョブキューマネージャーを必要とする傾向がありますが、複数のプロセス、特に複数のサーバーでバックグラウンドタスクを実行できます。 + +ただし、同じ **FastAPI** アプリから変数とオブジェクトにアクセスする必要がある場合、または小さなバックグラウンドタスク (電子メール通知の送信など) を実行する必要がある場合は、単に `BackgroundTasks` を使用できます。 + +## まとめ + +`BackgroundTasks` をインポートして、*path operations 関数* や依存関係のパラメータに `BackgroundTasks`を使用し、バックグラウンドタスクを追加して下さい。 diff --git a/docs/ja/docs/tutorial/body-fields.md b/docs/ja/docs/tutorial/body-fields.md new file mode 100644 index 000000000..0466320f1 --- /dev/null +++ b/docs/ja/docs/tutorial/body-fields.md @@ -0,0 +1,53 @@ +# ボディ - フィールド + +`Query`や`Path`、`Body`を使って *path operation関数* のパラメータに追加のバリデーションやメタデータを宣言するのと同じように、Pydanticの`Field`を使ってPydanticモデルの内部でバリデーションやメタデータを宣言することができます。 + +## `Field`のインポート + +まず、以下のようにインポートします: + +{* ../../docs_src/body_fields/tutorial001.py hl[4] *} + +/// warning | 注意 + +`Field`は他の全てのもの(`Query`、`Path`、`Body`など)とは違い、`fastapi`からではなく、`pydantic`から直接インポートされていることに注意してください。 + +/// + +## モデルの属性の宣言 + +以下のように`Field`をモデルの属性として使用することができます: + +{* ../../docs_src/body_fields/tutorial001.py hl[11,12,13,14] *} + +`Field`は`Query`や`Path`、`Body`と同じように動作し、全く同様のパラメータなどを持ちます。 + +/// note | 技術詳細 + +実際には次に見る`Query`や`Path`などは、共通の`Param`クラスのサブクラスのオブジェクトを作成しますが、それ自体はPydanticの`FieldInfo`クラスのサブクラスです。 + +また、Pydanticの`Field`は`FieldInfo`のインスタンスも返します。 + +`Body`は`FieldInfo`のサブクラスのオブジェクトを直接返すこともできます。そして、他にも`Body`クラスのサブクラスであるものがあります。 + +`fastapi`から`Query`や`Path`などをインポートする場合、これらは実際には特殊なクラスを返す関数であることに注意してください。 + +/// + +/// tip | 豆知識 + +型、デフォルト値、`Field`を持つ各モデルの属性が、`Path`や`Query`、`Body`の代わりに`Field`を持つ、*path operation 関数の*パラメータと同じ構造になっていることに注目してください。 + +/// + +## 追加情報の追加 + +追加情報は`Field`や`Query`、`Body`などで宣言することができます。そしてそれは生成されたJSONスキーマに含まれます。 + +後に例を用いて宣言を学ぶ際に、追加情報を句悪方法を学べます。 + +## まとめ + +Pydanticの`Field`を使用して、モデルの属性に追加のバリデーションやメタデータを宣言することができます。 + +追加のキーワード引数を使用して、追加のJSONスキーマのメタデータを渡すこともできます。 diff --git a/docs/ja/docs/tutorial/body-multiple-params.md b/docs/ja/docs/tutorial/body-multiple-params.md new file mode 100644 index 000000000..cbfdda4b2 --- /dev/null +++ b/docs/ja/docs/tutorial/body-multiple-params.md @@ -0,0 +1,167 @@ +# ボディ - 複数のパラメータ + +これまで`Path`と`Query`をどう使うかを見てきましたが、リクエストボディの宣言のより高度な使い方を見てみましょう。 + +## `Path`、`Query`とボディパラメータを混ぜる + +まず、もちろん、`Path`と`Query`とリクエストボディのパラメータの宣言は自由に混ぜることができ、 **FastAPI** は何をするべきかを知っています。 + +また、デフォルトの`None`を設定することで、ボディパラメータをオプションとして宣言することもできます: + +{* ../../docs_src/body_multiple_params/tutorial001.py hl[19,20,21] *} + +/// note | 備考 + +この場合、ボディから取得する`item`はオプションであることに注意してください。デフォルト値は`None`です。 + +/// + +## 複数のボディパラメータ + +上述の例では、*path operations*は`item`の属性を持つ以下のようなJSONボディを期待していました: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +しかし、`item`と`user`のように複数のボディパラメータを宣言することもできます: + +{* ../../docs_src/body_multiple_params/tutorial002.py hl[22] *} + +この場合、**FastAPI**は関数内に複数のボディパラメータ(Pydanticモデルである2つのパラメータ)があることに気付きます。 + +そのため、パラメータ名をボディのキー(フィールド名)として使用し、以下のようなボディを期待しています: + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + } +} +``` + +/// note | 備考 + +以前と同じように`item`が宣言されていたにもかかわらず、`item`はキー`item`を持つボディの内部にあることが期待されていることに注意してください。 + +/// + +**FastAPI** はリクエストから自動で変換を行い、パラメータ`item`が特定の内容を受け取り、`user`も同じように特定の内容を受け取ります。 + +複合データの検証を行い、OpenAPIスキーマや自動ドキュメントのように文書化してくれます。 + +## ボディ内の単数値 + +クエリとパスパラメータの追加データを定義するための `Query` と `Path` があるのと同じように、 **FastAPI** は同等の `Body` を提供します。 + +例えば、前のモデルを拡張して、同じボディに `item` と `user` の他にもう一つのキー `importance` を入れたいと決めることができます。 + +単数値なのでそのまま宣言すると、**FastAPI** はそれがクエリパラメータであるとみなします。 + +しかし、`Body`を使用して、**FastAPI** に別のボディキーとして扱うように指示することができます: + + +{* ../../docs_src/body_multiple_params/tutorial003.py hl[23] *} + +この場合、**FastAPI** は以下のようなボディを期待します: + + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + }, + "importance": 5 +} +``` + +繰り返しになりますが、データ型の変換、検証、文書化などを行います。 + +## 複数のボディパラメータとクエリ + +もちろん、ボディパラメータに加えて、必要に応じて追加のクエリパラメータを宣言することもできます。 + +デフォルトでは、単数値はクエリパラメータとして解釈されるので、明示的に `Query` を追加する必要はありません。 + +```Python +q: str = None +``` + +以下において: + +{* ../../docs_src/body_multiple_params/tutorial004.py hl[27] *} + +/// info | 情報 + +`Body`もまた、後述する `Query` や `Path` などと同様に、すべての検証パラメータとメタデータパラメータを持っています。 + +/// + +## 単一のボディパラメータの埋め込み + +Pydanticモデル`Item`のボディパラメータ`item`を1つだけ持っているとしましょう。 + +デフォルトでは、**FastAPI**はそのボディを直接期待します。 + +しかし、追加のボディパラメータを宣言したときのように、キー `item` を持つ JSON とその中のモデルの内容を期待したい場合は、特別な `Body` パラメータ `embed` を使うことができます: + +```Python +item: Item = Body(..., embed=True) +``` + +以下において: + +{* ../../docs_src/body_multiple_params/tutorial005.py hl[17] *} + +この場合、**FastAPI** は以下のようなボディを期待します: + +```JSON hl_lines="2" +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + } +} +``` + +以下の代わりに: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +## まとめ + +リクエストが単一のボディしか持てない場合でも、*path operation関数*に複数のボディパラメータを追加することができます。 + +しかし、**FastAPI** はそれを処理し、関数内の正しいデータを与え、*path operation*内の正しいスキーマを検証し、文書化します。 + +また、ボディの一部として受け取る単数値を宣言することもできます。 + +また、単一のパラメータしか宣言されていない場合でも、ボディをキーに埋め込むように **FastAPI** に指示することができます。 diff --git a/docs/ja/docs/tutorial/body-nested-models.md b/docs/ja/docs/tutorial/body-nested-models.md new file mode 100644 index 000000000..a1680d10f --- /dev/null +++ b/docs/ja/docs/tutorial/body-nested-models.md @@ -0,0 +1,231 @@ +# ボディ - ネストされたモデル + +**FastAPI** を使用すると、深くネストされた任意のモデルを定義、検証、文書化、使用することができます(Pydanticのおかげです)。 + +## リストのフィールド + +属性をサブタイプとして定義することができます。例えば、Pythonの`list`は以下のように定義できます: + +{* ../../docs_src/body_nested_models/tutorial001.py hl[12] *} + +これにより、各項目の型は宣言されていませんが、`tags`はある項目のリストになります。 + +## タイプパラメータを持つリストのフィールド + +しかし、Pythonには型や「タイプパラメータ」を使ってリストを宣言する方法があります: + +### typingの`List`をインポート + +まず、Pythonの標準の`typing`モジュールから`List`をインポートします: + +{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *} + +### タイプパラメータを持つ`List`の宣言 + +`list`や`dict`、`tuple`のようなタイプパラメータ(内部の型)を持つ型を宣言するには: + +* `typing`モジュールからそれらをインストールします。 +* 角括弧(`[`と`]`)を使って「タイプパラメータ」として内部の型を渡します: + +```Python +from typing import List + +my_list: List[str] +``` + +型宣言の標準的なPythonの構文はこれだけです。 + +内部の型を持つモデルの属性にも同じ標準の構文を使用してください。 + +そのため、以下の例では`tags`を具体的な「文字列のリスト」にすることができます: + +{* ../../docs_src/body_nested_models/tutorial002.py hl[14] *} + +## セット型 + +しかし、よく考えてみると、タグは繰り返すべきではなく、おそらくユニークな文字列になるのではないかと気付いたとします。 + +そして、Pythonにはユニークな項目のセットのための特別なデータ型`set`があります。 + +そのため、以下のように、`Set`をインポートして`str`の`set`として`tags`を宣言することができます: + +{* ../../docs_src/body_nested_models/tutorial003.py hl[1,14] *} + +これを使えば、データが重複しているリクエストを受けた場合でも、ユニークな項目のセットに変換されます。 + +そして、そのデータを出力すると、たとえソースに重複があったとしても、固有の項目のセットとして出力されます。 + +また、それに応じて注釈をつけたり、文書化したりします。 + +## ネストされたモデル + +Pydanticモデルの各属性には型があります。 + +しかし、その型はそれ自体が別のPydanticモデルである可能性があります。 + +そのため、特定の属性名、型、バリデーションを指定して、深くネストしたJSON`object`を宣言することができます。 + +すべては、任意のネストにされています。 + +### サブモデルの定義 + +例えば、`Image`モデルを定義することができます: + +{* ../../docs_src/body_nested_models/tutorial004.py hl[9,10,11] *} + +### サブモデルを型として使用 + +そして、それを属性の型として使用することができます: + +{* ../../docs_src/body_nested_models/tutorial004.py hl[20] *} + +これは **FastAPI** が以下のようなボディを期待することを意味します: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2, + "tags": ["rock", "metal", "bar"], + "image": { + "url": "http://example.com/baz.jpg", + "name": "The Foo live" + } +} +``` + +繰り返しになりますが、**FastAPI** を使用して、その宣言を行うだけで以下のような恩恵を受けられます: + +* ネストされたモデルでも対応可能なエディタのサポート(補完など) +* データ変換 +* データの検証 +* 自動文書化 + +## 特殊な型とバリデーション + +`str`や`int`、`float`のような通常の単数型の他にも、`str`を継承したより複雑な単数型を使うこともできます。 + +すべてのオプションをみるには、Pydanticのエキゾチック な型のドキュメントを確認してください。次の章でいくつかの例をみることができます。 + +例えば、`Image`モデルのように`url`フィールドがある場合、`str`の代わりにPydanticの`HttpUrl`を指定することができます: + +{* ../../docs_src/body_nested_models/tutorial005.py hl[4,10] *} + +文字列は有効なURLであることが確認され、そのようにJSONスキーマ・OpenAPIで文書化されます。 + +## サブモデルのリストを持つ属性 + +Pydanticモデルを`list`や`set`などのサブタイプとして使用することもできます: + +{* ../../docs_src/body_nested_models/tutorial006.py hl[20] *} + +これは、次のようなJSONボディを期待します(変換、検証、ドキュメントなど): + +```JSON hl_lines="11" +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2, + "tags": [ + "rock", + "metal", + "bar" + ], + "images": [ + { + "url": "http://example.com/baz.jpg", + "name": "The Foo live" + }, + { + "url": "http://example.com/dave.jpg", + "name": "The Baz" + } + ] +} +``` + +/// info | 情報 + +`images`キーが画像オブジェクトのリストを持つようになったことに注目してください。 + +/// + +## 深くネストされたモデル + +深くネストされた任意のモデルを定義することができます: + +{* ../../docs_src/body_nested_models/tutorial007.py hl[9,14,20,23,27] *} + +/// info | 情報 + +`Offer`は`Item`のリストであり、オプションの`Image`のリストを持っていることに注目してください。 + +/// + +## 純粋なリストのボディ + +期待するJSONボディのトップレベルの値がJSON`array`(Pythonの`list`)であれば、Pydanticモデルと同じように、関数のパラメータで型を宣言することができます: + +```Python +images: List[Image] +``` + +以下のように: + +{* ../../docs_src/body_nested_models/tutorial008.py hl[15] *} + +## あらゆる場所でのエディタサポート + +エディタのサポートもどこでも受けることができます。 + +以下のようにリストの中の項目でも: + + + +Pydanticモデルではなく、`dict`を直接使用している場合はこのようなエディタのサポートは得られません。 + +しかし、それらについて心配する必要はありません。入力された辞書は自動的に変換され、出力も自動的にJSONに変換されます。 + +## 任意の`dict`のボディ + +また、ある型のキーと別の型の値を持つ`dict`としてボディを宣言することもできます。 + +有効なフィールド・属性名を事前に知る必要がありません(Pydanticモデルの場合のように)。 + +これは、まだ知らないキーを受け取りたいときに便利だと思います。 + +--- + +他にも、`int`のように他の型のキーを持ちたい場合などに便利です。 + +それをここで見ていきましょう。 + +この場合、`int`のキーと`float`の値を持つものであれば、どんな`dict`でも受け入れることができます: + +{* ../../docs_src/body_nested_models/tutorial009.py hl[15] *} + +/// tip | 豆知識 + +JSONはキーとして`str`しかサポートしていないことに注意してください。 + +しかしPydanticには自動データ変換機能があります。 + +これは、APIクライアントがキーとして文字列しか送信できなくても、それらの文字列に純粋な整数が含まれている限り、Pydanticが変換して検証することを意味します。 + +そして、`weights`として受け取る`dict`は、実際には`int`のキーと`float`の値を持つことになります。 + +/// + +## まとめ + +**FastAPI** を使用すると、Pydanticモデルが提供する最大限の柔軟性を持ちながら、コードをシンプルに短く、エレガントに保つことができます。 + +以下のような利点があります: + +* エディタのサポート(どこでも補完!) +* データ変換(別名:構文解析・シリアライズ) +* データの検証 +* スキーマ文書 +* 自動文書化 diff --git a/docs/ja/docs/tutorial/body-updates.md b/docs/ja/docs/tutorial/body-updates.md index 7a56ef2b9..ffbe52e1d 100644 --- a/docs/ja/docs/tutorial/body-updates.md +++ b/docs/ja/docs/tutorial/body-updates.md @@ -6,9 +6,7 @@ `jsonable_encoder`を用いて、入力データをJSON形式で保存できるデータに変換することができます(例:NoSQLデータベース)。例えば、`datetime`を`str`に変換します。 -```Python hl_lines="30 31 32 33 34 35" -{!../../../docs_src/body_updates/tutorial001.py!} -``` +{* ../../docs_src/body_updates/tutorial001.py hl[30,31,32,33,34,35] *} 既存のデータを置き換えるべきデータを受け取るために`PUT`は使用されます。 @@ -34,14 +32,17 @@ つまり、更新したいデータだけを送信して、残りはそのままにしておくことができます。 -!!! Note "備考" - `PATCH`は`PUT`よりもあまり使われておらず、知られていません。 +/// note | 備考 + +`PATCH`は`PUT`よりもあまり使われておらず、知られていません。 + +また、多くのチームは部分的な更新であっても`PUT`だけを使用しています。 - また、多くのチームは部分的な更新であっても`PUT`だけを使用しています。 +**FastAPI** はどんな制限も課けていないので、それらを使うのは **自由** です。 - **FastAPI** はどんな制限も課けていないので、それらを使うのは **自由** です。 +しかし、このガイドでは、それらがどのように使用されることを意図しているかを多かれ少なかれ、示しています。 - しかし、このガイドでは、それらがどのように使用されることを意図しているかを多かれ少なかれ、示しています。 +/// ### Pydanticの`exclude_unset`パラメータの使用 @@ -53,9 +54,7 @@ これを使うことで、デフォルト値を省略して、設定された(リクエストで送られた)データのみを含む`dict`を生成することができます: -```Python hl_lines="34" -{!../../../docs_src/body_updates/tutorial002.py!} -``` +{* ../../docs_src/body_updates/tutorial002.py hl[34] *} ### Pydanticの`update`パラメータ @@ -63,9 +62,7 @@ `stored_item_model.copy(update=update_data)`のように: -```Python hl_lines="35" -{!../../../docs_src/body_updates/tutorial002.py!} -``` +{* ../../docs_src/body_updates/tutorial002.py hl[35] *} ### 部分的更新のまとめ @@ -82,18 +79,22 @@ * データをDBに保存します。 * 更新されたモデルを返します。 -```Python hl_lines="30 31 32 33 34 35 36 37" -{!../../../docs_src/body_updates/tutorial002.py!} -``` +{* ../../docs_src/body_updates/tutorial002.py hl[30,31,32,33,34,35,36,37] *} + +/// tip | 豆知識 + +実際には、HTTPの`PUT`操作でも同じテクニックを使用することができます。 + +しかし、これらのユースケースのために作成されたので、ここでの例では`PATCH`を使用しています。 + +/// -!!! tip "豆知識" - 実際には、HTTPの`PUT`操作でも同じテクニックを使用することができます。 +/// note | 備考 - しかし、これらのユースケースのために作成されたので、ここでの例では`PATCH`を使用しています。 +入力モデルがまだ検証されていることに注目してください。 -!!! note "備考" - 入力モデルがまだ検証されていることに注目してください。 +そのため、すべての属性を省略できる部分的な変更を受け取りたい場合は、すべての属性をオプションとしてマークしたモデルを用意する必要があります(デフォルト値または`None`を使用して)。 - そのため、すべての属性を省略できる部分的な変更を受け取りたい場合は、すべての属性をオプションとしてマークしたモデルを用意する必要があります(デフォルト値または`None`を使用して)。 +**更新** のためのオプション値がすべて設定されているモデルと、**作成** のための必須値が設定されているモデルを区別するには、[追加モデル](extra-models.md){.internal-link target=_blank}で説明されている考え方を利用することができます。 - **更新** のためのオプション値がすべて設定されているモデルと、**作成** のための必須値が設定されているモデルを区別するには、[追加モデル](extra-models.md){.internal-link target=_blank}で説明されている考え方を利用することができます。 +/// diff --git a/docs/ja/docs/tutorial/body.md b/docs/ja/docs/tutorial/body.md index d2559205b..8376959d5 100644 --- a/docs/ja/docs/tutorial/body.md +++ b/docs/ja/docs/tutorial/body.md @@ -6,22 +6,23 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければなりません。しかし、クライアントは必ずしも **リクエスト** ボディを送らなければいけないわけではありません。 -**リクエスト** ボディを宣言するために Pydantic モデルを使用します。そして、その全てのパワーとメリットを利用します。 +**リクエスト** ボディを宣言するために Pydantic モデルを使用します。そして、その全てのパワーとメリットを利用します。 -!!! info "情報" - データを送るには、`POST` (もっともよく使われる)、`PUT`、`DELETE` または `PATCH` を使うべきです。 +/// info | 情報 - GET リクエストでボディを送信することは、仕様では未定義の動作ですが、FastAPI でサポートされており、非常に複雑な(極端な)ユースケースにのみ対応しています。 +データを送るには、`POST` (もっともよく使われる)、`PUT`、`DELETE` または `PATCH` を使うべきです。 - 非推奨なので、Swagger UIを使った対話型のドキュメントにはGETのボディ情報は表示されません。さらに、中継するプロキシが対応していない可能性があります。 +GET リクエストでボディを送信することは、仕様では未定義の動作ですが、FastAPI でサポートされており、非常に複雑な(極端な)ユースケースにのみ対応しています。 + +非推奨なので、Swagger UIを使った対話型のドキュメントにはGETのボディ情報は表示されません。さらに、中継するプロキシが対応していない可能性があります。 + +/// ## Pydanticの `BaseModel` をインポート ます初めに、 `pydantic` から `BaseModel` をインポートする必要があります: -```Python hl_lines="2" -{!../../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[2] *} ## データモデルの作成 @@ -29,9 +30,7 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ すべての属性にpython標準の型を使用します: -```Python hl_lines="5-9" -{!../../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[5:9] *} クエリパラメータの宣言と同様に、モデル属性がデフォルト値をもつとき、必須な属性ではなくなります。それ以外は必須になります。オプショナルな属性にしたい場合は `None` を使用してください。 @@ -59,9 +58,7 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ *パスオペレーション* に加えるために、パスパラメータやクエリパラメータと同じ様に宣言します: -```Python hl_lines="16" -{!../../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[16] *} ...そして、作成したモデル `Item` で型を宣言します。 @@ -110,24 +107,25 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ -!!! tip "豆知識" - PyCharmエディタを使用している場合は、Pydantic PyCharm Pluginが使用可能です。 +/// tip | 豆知識 + +PyCharmエディタを使用している場合は、Pydantic PyCharm Pluginが使用可能です。 - 以下のエディターサポートが強化されます: +以下のエディターサポートが強化されます: - * 自動補完 - * 型チェック - * リファクタリング - * 検索 - * インスペクション +* 自動補完 +* 型チェック +* リファクタリング +* 検索 +* インスペクション + +/// ## モデルの使用 関数内部で、モデルの全ての属性に直接アクセスできます: -```Python hl_lines="19" -{!../../../docs_src/body/tutorial002.py!} -``` +{* ../../docs_src/body/tutorial002.py hl[19] *} ## リクエストボディ + パスパラメータ @@ -135,9 +133,7 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ **FastAPI** はパスパラメータである関数パラメータは**パスから受け取り**、Pydanticモデルによって宣言された関数パラメータは**リクエストボディから受け取る**ということを認識します。 -```Python hl_lines="15-16" -{!../../../docs_src/body/tutorial003.py!} -``` +{* ../../docs_src/body/tutorial003.py hl[15:16] *} ## リクエストボディ + パスパラメータ + クエリパラメータ @@ -145,9 +141,7 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ **FastAPI** はそれぞれを認識し、適切な場所からデータを取得します。 -```Python hl_lines="16" -{!../../../docs_src/body/tutorial004.py!} -``` +{* ../../docs_src/body/tutorial004.py hl[16] *} 関数パラメータは以下の様に認識されます: @@ -155,11 +149,14 @@ APIはほとんどの場合 **レスポンス** ボディを送らなければ * パラメータが**単数型** (`int`、`float`、`str`、`bool` など)の場合は**クエリ**パラメータとして解釈されます。 * パラメータが **Pydantic モデル**型で宣言された場合、リクエスト**ボディ**として解釈されます。 -!!! note "備考" - FastAPIは、`= None`があるおかげで、`q`がオプショナルだとわかります。 +/// note | 備考 + +FastAPIは、`= None`があるおかげで、`q`がオプショナルだとわかります。 + +`Optional[str]` の`Optional` はFastAPIでは使用されていません(FastAPIは`str`の部分のみ使用します)。しかし、`Optional[str]` はエディタがコードのエラーを見つけるのを助けてくれます。 - `Optional[str]` の`Optional` はFastAPIでは使用されていません(FastAPIは`str`の部分のみ使用します)。しかし、`Optional[str]` はエディタがコードのエラーを見つけるのを助けてくれます。 +/// ## Pydanticを使わない方法 -もしPydanticモデルを使用したくない場合は、**Body**パラメータが利用できます。[Body - Multiple Parameters: Singular values in body](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}を確認してください。 +もしPydanticモデルを使用したくない場合は、**Body**パラメータが利用できます。[Body - Multiple Parameters: Singular values in body](body-multiple-params.md#_2){.internal-link target=_blank}を確認してください。 diff --git a/docs/ja/docs/tutorial/cookie-param-models.md b/docs/ja/docs/tutorial/cookie-param-models.md new file mode 100644 index 000000000..8285f44ef --- /dev/null +++ b/docs/ja/docs/tutorial/cookie-param-models.md @@ -0,0 +1,77 @@ +# クッキーパラメータモデル + +もし関連する**複数のクッキー**から成るグループがあるなら、それらを宣言するために、**Pydanticモデル**を作成できます。🍪 + +こうすることで、**複数の場所**で**そのPydanticモデルを再利用**でき、バリデーションやメタデータを、すべてのクッキーパラメータに対して一度に宣言できます。😎 + +/// note | 備考 + +この機能は、FastAPIのバージョン `0.115.0` からサポートされています。🤓 + +/// + +/// tip | 豆知識 + +これと同じテクニックは `Query` 、 `Cookie` 、 `Header` にも適用できます。 😎 + +/// + +## クッキーにPydanticモデルを使用する + +必要な複数の**クッキー**パラメータを**Pydanticモデル**で宣言し、さらに、それを `Cookie` として宣言しましょう: + +{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *} + +**FastAPI**は、リクエストの**クッキー**から**それぞれのフィールド**のデータを**抽出**し、定義された**Pydanticモデル**を提供します。 + +## ドキュメントの確認 + +対話的APIドキュメントUI `/docs` で、定義されているクッキーを確認できます: + +
+ +
+ +/// info | 備考 + + +**ブラウザがクッキーを処理し**ていますが、特別な方法で内部的に処理を行っているために、**JavaScript**からは簡単に操作**できない**ことに留意してください。 + +**対話的APIドキュメントUI** `/docs` にアクセスすれば、*パスオペレーション*に関するクッキーの**ドキュメンテーション**を確認できます。 + +しかし、たとえ**クッキーデータを入力して**「Execute」をクリックしても、対話的APIドキュメントUIは**JavaScript**で動作しているためクッキーは送信されず、まるで値を入力しなかったかのような**エラー**メッセージが表示されます。 + +/// + +## 余分なクッキーを禁止する + +特定の(あまり一般的ではないかもしれない)ケースで、受け付けるクッキーを**制限**する必要があるかもしれません。 + +あなたのAPIは独自の クッキー同意 を管理する能力を持っています。 🤪🍪 + +Pydanticのモデルの Configuration を利用して、 `extra` フィールドを `forbid` とすることができます。 + +{* ../../docs_src/cookie_param_models/tutorial002_an_py39.py hl[10] *} + +もしクライアントが**余分なクッキー**を送ろうとすると、**エラー**レスポンスが返されます。 + +どうせAPIに拒否されるのにあなたの同意を得ようと精一杯努力する可哀想なクッキーバナーたち... 🍪 + +例えば、クライアントがクッキー `santa_tracker` を `good-list-please` という値で送ろうとすると、`santa_tracker` という クッキーが許可されていない ことを通知する**エラー**レスポンスが返されます: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["cookie", "santa_tracker"], + "msg": "Extra inputs are not permitted", + "input": "good-list-please", + } + ] +} +``` + +## まとめ + +**FastAPI**では、**クッキー**を宣言するために、**Pydanticモデル**を使用できます。😎 diff --git a/docs/ja/docs/tutorial/cookie-params.md b/docs/ja/docs/tutorial/cookie-params.md index 193be305f..13af6d3c7 100644 --- a/docs/ja/docs/tutorial/cookie-params.md +++ b/docs/ja/docs/tutorial/cookie-params.md @@ -6,9 +6,7 @@ まず、`Cookie`をインポートします: -```Python hl_lines="3" -{!../../../docs_src/cookie_params/tutorial001.py!} -``` +{* ../../docs_src/cookie_params/tutorial001.py hl[3] *} ## `Cookie`のパラメータを宣言 @@ -16,17 +14,21 @@ 最初の値がデフォルト値で、追加の検証パラメータや注釈パラメータをすべて渡すことができます: -```Python hl_lines="9" -{!../../../docs_src/cookie_params/tutorial001.py!} -``` +{* ../../docs_src/cookie_params/tutorial001.py hl[9] *} -!!! note "技術詳細" - `Cookie`は`Path`と`Query`の「姉妹」クラスです。また、同じ共通の`Param`クラスを継承しています。 +/// note | 技術詳細 - しかし、`fastapi`から`Query`や`Path`、`Cookie`などをインポートする場合、それらは実際には特殊なクラスを返す関数であることを覚えておいてください。 +`Cookie`は`Path`と`Query`の「姉妹」クラスです。また、同じ共通の`Param`クラスを継承しています。 -!!! info "情報" - クッキーを宣言するには、`Cookie`を使う必要があります。なぜなら、そうしないとパラメータがクエリのパラメータとして解釈されてしまうからです。 +しかし、`fastapi`から`Query`や`Path`、`Cookie`などをインポートする場合、それらは実際には特殊なクラスを返す関数であることを覚えておいてください。 + +/// + +/// info | 情報 + +クッキーを宣言するには、`Cookie`を使う必要があります。なぜなら、そうしないとパラメータがクエリのパラメータとして解釈されてしまうからです。 + +/// ## まとめ diff --git a/docs/ja/docs/tutorial/cors.md b/docs/ja/docs/tutorial/cors.md index 9d6ce8cdc..f7bd59b70 100644 --- a/docs/ja/docs/tutorial/cors.md +++ b/docs/ja/docs/tutorial/cors.md @@ -46,9 +46,7 @@ * 特定のHTTPメソッド (`POST`、`PUT`) またはワイルドカード `"*"` を使用してすべて許可。 * 特定のHTTPヘッダー、またはワイルドカード `"*"`を使用してすべて許可。 -```Python hl_lines="2 6-11 13-19" -{!../../../docs_src/cors/tutorial001.py!} -``` +{* ../../docs_src/cors/tutorial001.py hl[2,6:11,13:19] *} `CORSMiddleware` 実装のデフォルトのパラメータはCORSに関して制限を与えるものになっているので、ブラウザにドメインを跨いで特定のオリジン、メソッド、またはヘッダーを使用可能にするためには、それらを明示的に有効にする必要があります @@ -78,7 +76,10 @@ CORSについてより詳しい情報は、Mozilla CORS documentation を参照して下さい。 -!!! note "技術詳細" - `from starlette.middleware.cors import CORSMiddleware` も使用できます。 +/// note | 技術詳細 - **FastAPI** は、開発者の利便性を高めるために、`fastapi.middleware` でいくつかのミドルウェアを提供します。利用可能なミドルウェアのほとんどは、Starletteから直接提供されています。 +`from starlette.middleware.cors import CORSMiddleware` も使用できます。 + +**FastAPI** は、開発者の利便性を高めるために、`fastapi.middleware` でいくつかのミドルウェアを提供します。利用可能なミドルウェアのほとんどは、Starletteから直接提供されています。 + +/// diff --git a/docs/ja/docs/tutorial/debugging.md b/docs/ja/docs/tutorial/debugging.md index 35e1ca7ad..6c29679ef 100644 --- a/docs/ja/docs/tutorial/debugging.md +++ b/docs/ja/docs/tutorial/debugging.md @@ -6,9 +6,7 @@ Visual Studio CodeやPyCharmなどを使用して、エディター上でデバ FastAPIアプリケーション上で、`uvicorn` を直接インポートして実行します: -```Python hl_lines="1 15" -{!../../../docs_src/debugging/tutorial001.py!} -``` +{* ../../docs_src/debugging/tutorial001.py hl[1,15] *} ### `__name__ == "__main__"` について @@ -74,8 +72,11 @@ from myapp import app は実行されません。 -!!! info "情報" - より詳しい情報は、公式Pythonドキュメントを参照してください。 +/// info | 情報 + +より詳しい情報は、公式Pythonドキュメントを参照してください。 + +/// ## デバッガーでコードを実行 diff --git a/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md new file mode 100644 index 000000000..80153529e --- /dev/null +++ b/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md @@ -0,0 +1,180 @@ +# 依存関係としてのクラス + +**依存性注入** システムを深く掘り下げる前に、先ほどの例をアップグレードしてみましょう。 + +## 前の例の`dict` + +前の例では、依存関係("dependable")から`dict`を返していました: + +{* ../../docs_src/dependencies/tutorial001.py hl[9] *} + +しかし、*path operation関数*のパラメータ`commons`に`dict`が含まれています。 + +また、エディタは`dict`のキーと値の型を知ることができないため、多くのサポート(補完のような)を提供することができません。 + +もっとうまくやれるはずです...。 + +## 依存関係を作るもの + +これまでは、依存関係が関数として宣言されているのを見てきました。 + +しかし、依存関係を定義する方法はそれだけではありません(その方が一般的かもしれませんが)。 + +重要なのは、依存関係が「呼び出し可能」なものであることです。 + +Pythonにおける「**呼び出し可能**」とは、Pythonが関数のように「呼び出す」ことができるものを指します。 + +そのため、`something`オブジェクト(関数ではないかもしれませんが)を持っていて、それを次のように「呼び出す」(実行する)ことができるとします: + +```Python +something() +``` + +または + +```Python +something(some_argument, some_keyword_argument="foo") +``` + +これを「呼び出し可能」なものと呼びます。 + +## 依存関係としてのクラス + +Pythonのクラスのインスタンスを作成する際に、同じ構文を使用していることに気づくかもしれません。 + +例えば: + +```Python +class Cat: + def __init__(self, name: str): + self.name = name + + +fluffy = Cat(name="Mr Fluffy") +``` + +この場合、`fluffy`は`Cat`クラスのインスタンスです。 + +そして`fluffy`を作成するために、`Cat`を「呼び出している」ことになります。 + +そのため、Pythonのクラスもまた「呼び出し可能」です。 + +そして、**FastAPI** では、Pythonのクラスを依存関係として使用することができます。 + +FastAPIが実際にチェックしているのは、それが「呼び出し可能」(関数、クラス、その他なんでも)であり、パラメータが定義されているかどうかということです。 + +**FastAPI** の依存関係として「呼び出し可能なもの」を渡すと、その「呼び出し可能なもの」のパラメータを解析し、サブ依存関係も含めて、*path operation関数*のパラメータと同じように処理します。 + +それは、パラメータが全くない呼び出し可能なものにも適用されます。パラメータのない*path operation関数*と同じように。 + +そこで、上で紹介した依存関係の`common_parameters`を`CommonQueryParams`クラスに変更します: + +{* ../../docs_src/dependencies/tutorial002.py hl[11,12,13,14,15] *} + +クラスのインスタンスを作成するために使用される`__init__`メソッドに注目してください: + +{* ../../docs_src/dependencies/tutorial002.py hl[12] *} + +...以前の`common_parameters`と同じパラメータを持っています: + +{* ../../docs_src/dependencies/tutorial001.py hl[8] *} + +これらのパラメータは **FastAPI** が依存関係を「解決」するために使用するものです。 + +どちらの場合も以下を持っています: + +* オプショナルの`q`クエリパラメータ。 +* `skip`クエリパラメータ、デフォルトは`0`。 +* `limit`クエリパラメータ、デフォルトは`100`。 + +どちらの場合も、データは変換され、検証され、OpenAPIスキーマなどで文書化されます。 + +## 使用 + +これで、このクラスを使用して依存関係を宣言することができます。 + +{* ../../docs_src/dependencies/tutorial002.py hl[19] *} + +**FastAPI** は`CommonQueryParams`クラスを呼び出します。これにより、そのクラスの「インスタンス」が作成され、インスタンスはパラメータ`commons`として関数に渡されます。 + +## 型注釈と`Depends` + +上のコードでは`CommonQueryParams`を2回書いていることに注目してください: + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +以下にある最後の`CommonQueryParams`: + +```Python +... = Depends(CommonQueryParams) +``` + +...は、**FastAPI** が依存関係を知るために実際に使用するものです。 + +そこからFastAPIが宣言されたパラメータを抽出し、それが実際にFastAPIが呼び出すものです。 + +--- + +この場合、以下にある最初の`CommonQueryParams`: + +```Python +commons: CommonQueryParams ... +``` + +...は **FastAPI** に対して特別な意味をもちません。FastAPIはデータ変換や検証などには使用しません(それらのためには`= Depends(CommonQueryParams)`を使用しています)。 + +実際には以下のように書けばいいだけです: + +```Python +commons = Depends(CommonQueryParams) +``` + +以下にあるように: + +{* ../../docs_src/dependencies/tutorial003.py hl[19] *} + +しかし、型を宣言することは推奨されています。そうすれば、エディタは`commons`のパラメータとして何が渡されるかを知ることができ、コードの補完や型チェックなどを行うのに役立ちます: + + + +## ショートカット + +しかし、ここでは`CommonQueryParams`を2回書くというコードの繰り返しが発生していることがわかります: + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +依存関係が、クラス自体のインスタンスを作成するために**FastAPI**が「呼び出す」*特定の*クラスである場合、**FastAPI** はこれらのケースのショートカットを提供しています。 + +それらの具体的なケースについては以下のようにします: + +以下のように書く代わりに: + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +...以下のように書きます: + +```Python +commons: CommonQueryParams = Depends() +``` + +パラメータの型として依存関係を宣言し、`Depends()`の中でパラメータを指定せず、`Depends()`をその関数のパラメータの「デフォルト」値(`=`のあとの値)として使用することで、`Depends(CommonQueryParams)`の中でクラス全体を*もう一度*書かなくてもよくなります。 + +同じ例では以下のようになります: + +{* ../../docs_src/dependencies/tutorial004.py hl[19] *} + +...そして **FastAPI** は何をすべきか知っています。 + +/// tip | 豆知識 + +役に立つというよりも、混乱するようであれば無視してください。それをする*必要*はありません。 + +それは単なるショートカットです。なぜなら **FastAPI** はコードの繰り返しを最小限に抑えることに気を使っているからです。 + +/// diff --git a/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md new file mode 100644 index 000000000..0fb15ae02 --- /dev/null +++ b/docs/ja/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -0,0 +1,57 @@ +# path operationデコレータの依存関係 + +場合によっては*path operation関数*の中で依存関係の戻り値を本当に必要としないこともあります。 + +もしくは、依存関係が値を返さない場合もあります。 + +しかし、それでも実行・解決する必要があります。 + +このような場合、*path operation関数*のパラメータを`Depends`で宣言する代わりに、*path operation decorator*に`dependencies`の`list`を追加することができます。 + +## *path operationデコレータ*への`dependencies`の追加 + +*path operationデコレータ*はオプショナルの引数`dependencies`を受け取ります。 + +それは`Depends()`の`list`であるべきです: + +{* ../../docs_src/dependencies/tutorial006.py hl[17] *} + +これらの依存関係は、通常の依存関係と同様に実行・解決されます。しかし、それらの値(何かを返す場合)は*path operation関数*には渡されません。 + +/// tip | 豆知識 + +エディタによっては、未使用の関数パラメータをチェックしてエラーとして表示するものもあります。 + +`dependencies`を`path operationデコレータ`で使用することで、エディタやツールのエラーを回避しながら確実に実行することができます。 + +また、コードの未使用のパラメータがあるのを見て、それが不要だと思ってしまうような新しい開発者の混乱を避けるのにも役立つかもしれません。 + +/// + +## 依存関係のエラーと戻り値 + +通常使用している依存関係の*関数*と同じものを使用することができます。 + +### 依存関係の要件 + +これらはリクエストの要件(ヘッダのようなもの)やその他のサブ依存関係を宣言することができます: + +{* ../../docs_src/dependencies/tutorial006.py hl[6,11] *} + +### 例外の発生 + +これらの依存関係は通常の依存関係と同じように、例外を`raise`発生させることができます: + +{* ../../docs_src/dependencies/tutorial006.py hl[8,13] *} + +### 戻り値 + +そして、値を返すことも返さないこともできますが、値は使われません。 + +つまり、すでにどこかで使っている通常の依存関係(値を返すもの)を再利用することができ、値は使われなくても依存関係は実行されます: + +{* ../../docs_src/dependencies/tutorial006.py hl[9,14] *} + +## *path operations*のグループに対する依存関係 + +後で、より大きなアプリケーションの構造([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md){.internal-link target=_blank})について読む時に、おそらく複数のファイルを使用して、*path operations*のグループに対して単一の`dependencies`パラメータを宣言する方法を学ぶでしょう。 diff --git a/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md new file mode 100644 index 000000000..35a69de0d --- /dev/null +++ b/docs/ja/docs/tutorial/dependencies/dependencies-with-yield.md @@ -0,0 +1,241 @@ +# yieldを持つ依存関係 + +FastAPIは、いくつかの終了後の追加のステップを行う依存関係をサポートしています。 + +これを行うには、`return`の代わりに`yield`を使い、その後に追加のステップを書きます。 + +/// tip | 豆知識 + +`yield`は必ず一度だけ使用するようにしてください。 + +/// + +/// info | 情報 + +これを動作させるには、**Python 3.7** 以上を使用するか、**Python 3.6** では"backports"をインストールする必要があります: + +``` +pip install async-exit-stack async-generator +``` + +これによりasync-exit-stackasync-generatorがインストールされます。 + +/// + +/// note | 技術詳細 + +以下と一緒に使用できる関数なら何でも有効です: + +* `@contextlib.contextmanager`または +* `@contextlib.asynccontextmanager` + +これらは **FastAPI** の依存関係として使用するのに有効です。 + +実際、FastAPIは内部的にこれら2つのデコレータを使用しています。 + +/// + +## `yield`を持つデータベースの依存関係 + +例えば、これを使ってデータベースセッションを作成し、終了後にそれを閉じることができます。 + +レスポンスを送信する前に`yield`文を含む前のコードのみが実行されます。 + +{* ../../docs_src/dependencies/tutorial007.py hl[2,3,4] *} + +生成された値は、*path operations*や他の依存関係に注入されるものです: + +{* ../../docs_src/dependencies/tutorial007.py hl[4] *} + +`yield`文に続くコードは、レスポンスが送信された後に実行されます: + +{* ../../docs_src/dependencies/tutorial007.py hl[5,6] *} + +/// tip | 豆知識 + +`async`や通常の関数を使用することができます。 + +**FastAPI** は、通常の依存関係と同じように、それぞれで正しいことを行います。 + +/// + +## `yield`と`try`を持つ依存関係 + +`yield`を持つ依存関係で`try`ブロックを使用した場合、その依存関係を使用した際に発生した例外を受け取ることになります。 + +例えば、途中のどこかの時点で、別の依存関係や*path operation*の中で、データベーストランザクションを「ロールバック」したり、その他のエラーを作成したりするコードがあった場合、依存関係の中で例外を受け取ることになります。 + +そのため、依存関係の中にある特定の例外を`except SomeException`で探すことができます。 + +同様に、`finally`を用いて例外があったかどうかにかかわらず、終了ステップを確実に実行することができます。 + +{* ../../docs_src/dependencies/tutorial007.py hl[3,5] *} + +## `yield`を持つサブ依存関係 + +任意の大きさや形のサブ依存関係やサブ依存関係の「ツリー」を持つことができ、その中で`yield`を使用することができます。 + +**FastAPI** は、`yield`を持つ各依存関係の「終了コード」が正しい順番で実行されていることを確認します。 + +例えば、`dependency_c`は`dependency_b`と`dependency_b`に依存する`dependency_a`に、依存することができます: + +{* ../../docs_src/dependencies/tutorial008.py hl[4,12,20] *} + +そして、それらはすべて`yield`を使用することができます。 + +この場合、`dependency_c`は終了コードを実行するために、`dependency_b`(ここでは`dep_b`という名前)の値がまだ利用可能である必要があります。 + +そして、`dependency_b`は`dependency_a`(ここでは`dep_a`という名前)の値を終了コードで利用できるようにする必要があります。 + +{* ../../docs_src/dependencies/tutorial008.py hl[16,17,24,25] *} + +同様に、`yield`と`return`が混在した依存関係を持つこともできます。 + +また、単一の依存関係を持っていて、`yield`などの他の依存関係をいくつか必要とすることもできます。 + +依存関係の組み合わせは自由です。 + +**FastAPI** は、全てが正しい順序で実行されていることを確認します。 + +/// note | 技術詳細 + +これはPythonのContext Managersのおかげで動作します。 + +**FastAPI** はこれを実現するために内部的に使用しています。 + +/// + +## `yield`と`HTTPException`を持つ依存関係 + +`yield`と例外をキャッチする`try`ブロックを持つことができる依存関係を使用することができることがわかりました。 + +`yield`の後の終了コードで`HTTPException`などを発生させたくなるかもしれません。しかし**それはうまくいきません** + +`yield`を持つ依存関係の終了コードは[例外ハンドラ](../handling-errors.md#_4){.internal-link target=_blank}の*後に*実行されます。依存関係によって投げられた例外を終了コード(`yield`の後)でキャッチするものはなにもありません。 + +つまり、`yield`の後に`HTTPException`を発生させた場合、`HTTTPException`をキャッチしてHTTP 400のレスポンスを返すデフォルトの(あるいは任意のカスタムの)例外ハンドラは、その例外をキャッチすることができなくなります。 + +これは、依存関係に設定されているもの(例えば、DBセッション)を、例えば、バックグラウンドタスクで使用できるようにするものです。 + +バックグラウンドタスクはレスポンスが送信された*後*に実行されます。そのため、*すでに送信されている*レスポンスを変更する方法すらないので、`HTTPException`を発生させる方法はありません。 + +しかし、バックグラウンドタスクがDBエラーを発生させた場合、少なくとも`yield`で依存関係のセッションをロールバックしたり、きれいに閉じたりすることができ、エラーをログに記録したり、リモートのトラッキングシステムに報告したりすることができます。 + +例外が発生する可能性があるコードがある場合は、最も普通の「Python流」なことをして、コードのその部分に`try`ブロックを追加してください。 + +レスポンスを返したり、レスポンスを変更したり、`HTTPException`を発生させたりする*前に*処理したいカスタム例外がある場合は、[カスタム例外ハンドラ](../handling-errors.md#_4){.internal-link target=_blank}を作成してください。 + +/// tip | 豆知識 + +`HTTPException`を含む例外は、`yield`の*前*でも発生させることができます。ただし、後ではできません。 + +/// + +実行の順序は多かれ少なかれ以下の図のようになります。時間は上から下へと流れていきます。そして、各列はコードを相互作用させたり、実行したりしている部分の一つです。 + +```mermaid +sequenceDiagram + +participant client as Client +participant handler as Exception handler +participant dep as Dep with yield +participant operation as Path Operation +participant tasks as Background tasks + + Note over client,tasks: Can raise exception for dependency, handled after response is sent + Note over client,operation: Can raise HTTPException and can change the response + client ->> dep: Start request + Note over dep: Run code up to yield + opt raise + dep -->> handler: Raise HTTPException + handler -->> client: HTTP error response + dep -->> dep: Raise other exception + end + dep ->> operation: Run dependency, e.g. DB session + opt raise + operation -->> handler: Raise HTTPException + handler -->> client: HTTP error response + operation -->> dep: Raise other exception + end + operation ->> client: Return response to client + Note over client,operation: Response is already sent, can't change it anymore + opt Tasks + operation -->> tasks: Send background tasks + end + opt Raise other exception + tasks -->> dep: Raise other exception + end + Note over dep: After yield + opt Handle other exception + dep -->> dep: Handle exception, can't change response. E.g. close DB session. + end +``` + +/// info | 情報 + +**1つのレスポンス** だけがクライアントに送信されます。それはエラーレスポンスの一つかもしれませんし、*path operation*からのレスポンスかもしれません。 + +いずれかのレスポンスが送信された後、他のレスポンスを送信することはできません。 + +/// + +/// tip | 豆知識 + +この図は`HTTPException`を示していますが、[カスタム例外ハンドラ](../handling-errors.md#_4){.internal-link target=_blank}を作成することで、他の例外を発生させることもできます。そして、その例外は依存関係の終了コードではなく、そのカスタム例外ハンドラによって処理されます。 + +しかし例外ハンドラで処理されない例外を発生させた場合は、依存関係の終了コードで処理されます。 + +/// + +## コンテキストマネージャ + +### 「コンテキストマネージャ」とは + +「コンテキストマネージャ」とは、`with`文の中で使用できるPythonオブジェクトのことです。 + +例えば、ファイルを読み込むには`with`を使用することができます: + +```Python +with open("./somefile.txt") as f: + contents = f.read() + print(contents) +``` + +その後の`open("./somefile.txt")`は「コンテキストマネージャ」と呼ばれるオブジェクトを作成します。 + +`with`ブロックが終了すると、例外があったとしてもファイルを確かに閉じます。 + +`yield`を依存関係を作成すると、**FastAPI** は内部的にそれをコンテキストマネージャに変換し、他の関連ツールと組み合わせます。 + +### `yield`を持つ依存関係でのコンテキストマネージャの使用 + +/// warning | 注意 + +これは多かれ少なかれ、「高度な」発想です。 + +**FastAPI** を使い始めたばかりの方は、とりあえずスキップした方がよいかもしれません。 + +/// + +Pythonでは、以下の2つのメソッドを持つクラスを作成する: `__enter__()`と`__exit__()`ことでコンテキストマネージャを作成することができます。 + +また、依存関数の中で`with`や`async with`文を使用することによって`yield`を持つ **FastAPI** の依存関係の中でそれらを使用することができます: + +{* ../../docs_src/dependencies/tutorial010.py hl[1,2,3,4,5,6,7,8,9,13] *} + +/// tip | 豆知識 + +コンテキストマネージャを作成するもう一つの方法はwithです: + +* `@contextlib.contextmanager` または +* `@contextlib.asynccontextmanager` + +これらを使って、関数を単一の`yield`でデコレートすることができます。 + +これは **FastAPI** が内部的に`yield`を持つ依存関係のために使用しているものです。 + +しかし、FastAPIの依存関係にデコレータを使う必要はありません(そして使うべきではありません)。 + +FastAPIが内部的にやってくれます。 + +/// diff --git a/docs/ja/docs/tutorial/dependencies/index.md b/docs/ja/docs/tutorial/dependencies/index.md new file mode 100644 index 000000000..c2b5e7bba --- /dev/null +++ b/docs/ja/docs/tutorial/dependencies/index.md @@ -0,0 +1,212 @@ +# 依存関係 - 最初のステップ + +** FastAPI** は非常に強力でありながら直感的な **依存性注入** システムを持っています。 + +それは非常にシンプルに使用できるように設計されており、開発者が他のコンポーネント **FastAPI** と統合するのが非常に簡単になるように設計されています。 + +## 「依存性注入」とは + +**「依存性注入」** とは、プログラミングにおいて、コード(この場合は、*path operation関数*)が動作したり使用したりするために必要なもの(「依存関係」)を宣言する方法があることを意味します: + +そして、そのシステム(この場合は、**FastAPI**)は、必要な依存関係をコードに提供するために必要なことは何でも行います(依存関係を「注入」します)。 + +これは以下のようなことが必要な時にとても便利です: + +* ロジックを共有している。(同じコードロジックを何度も繰り返している)。 +* データベース接続を共有する。 +* セキュリティ、認証、ロール要件などを強制する。 +* そのほかにも多くのこと... + +これらすべてを、コードの繰り返しを最小限に抑えながら行います。 + +## 最初のステップ + +非常にシンプルな例を見てみましょう。あまりにもシンプルなので、今のところはあまり参考にならないでしょう。 + +しかし、この方法では **依存性注入** システムがどのように機能するかに焦点を当てることができます。 + +### 依存関係の作成 + +まずは依存関係に注目してみましょう。 + +以下のように、*path operation関数*と同じパラメータを全て取ることができる関数にすぎません: + +{* ../../docs_src/dependencies/tutorial001.py hl[8,9] *} + +これだけです。 + +**2行**。 + +そして、それはすべての*path operation関数*が持っているのと同じ形と構造を持っています。 + +「デコレータ」を含まない(`@app.get("/some-path")`を含まない)*path operation関数*と考えることもできます。 + +そして何でも返すことができます。 + +この場合、この依存関係は以下を期待しています: + +* オプショナルのクエリパラメータ`q`は`str`です。 +* オプショナルのクエリパラメータ`skip`は`int`で、デフォルトは`0`です。 +* オプショナルのクエリパラメータ`limit`は`int`で、デフォルトは`100`です。 + +そして、これらの値を含む`dict`を返します。 + +### `Depends`のインポート + +{* ../../docs_src/dependencies/tutorial001.py hl[3] *} + +### "dependant"での依存関係の宣言 + +*path operation関数*のパラメータに`Body`や`Query`などを使用するのと同じように、新しいパラメータに`Depends`を使用することができます: + +{* ../../docs_src/dependencies/tutorial001.py hl[13,18] *} + +関数のパラメータに`Depends`を使用するのは`Body`や`Query`などと同じですが、`Depends`の動作は少し異なります。 + +`Depends`は1つのパラメータしか与えられません。 + +このパラメータは関数のようなものである必要があります。 + +そして、その関数は、*path operation関数*が行うのと同じ方法でパラメータを取ります。 + +/// tip | 豆知識 + +次の章では、関数以外の「もの」が依存関係として使用できるものを見ていきます。 + +/// + +新しいリクエストが到着するたびに、**FastAPI** が以下のような処理を行います: + +* 依存関係("dependable")関数を正しいパラメータで呼び出します。 +* 関数の結果を取得します。 +* *path operation関数*のパラメータにその結果を代入してください。 + +```mermaid +graph TB + +common_parameters(["common_parameters"]) +read_items["/items/"] +read_users["/users/"] + +common_parameters --> read_items +common_parameters --> read_users +``` + +この方法では、共有されるコードを一度書き、**FastAPI** が*path operations*のための呼び出しを行います。 + +/// check | 確認 + +特別なクラスを作成してどこかで **FastAPI** に渡して「登録」する必要はないことに注意してください。 + +`Depends`を渡すだけで、**FastAPI** が残りの処理をしてくれます。 + +/// + +## `async`にするかどうか + +依存関係は **FastAPI**(*path operation関数*と同じ)からも呼び出されるため、関数を定義する際にも同じルールが適用されます。 + +`async def`や通常の`def`を使用することができます。 + +また、通常の`def`*path operation関数*の中に`async def`を入れて依存関係を宣言したり、`async def`*path operation関数*の中に`def`を入れて依存関係を宣言したりすることなどができます。 + +それは重要ではありません。**FastAPI** は何をすべきかを知っています。 + +/// note | 備考 + +わからない場合は、ドキュメントの[Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank}の中の`async`と`await`についてのセクションを確認してください。 + +/// + +## OpenAPIとの統合 + +依存関係(およびサブ依存関係)のすべてのリクエスト宣言、検証、および要件は、同じOpenAPIスキーマに統合されます。 + +つまり、対話型ドキュメントにはこれらの依存関係から得られる全ての情報も含まれているということです: + + + +## 簡単な使い方 + +見てみると、*path*と*operation*が一致した時に*path operation関数*が宣言されていて、**FastAPI** が正しいパラメータで関数を呼び出してリクエストからデータを抽出する処理をしています。 + +実は、すべての(あるいはほとんどの)Webフレームワークは、このように動作します。 + +これらの関数を直接呼び出すことはありません。これらの関数はフレームワーク(この場合は、**FastAPI**)によって呼び出されます。 + +依存性注入システムでは、**FastAPI** に*path operation*もまた、*path operation関数*の前に実行されるべき他の何かに「依存」していることを伝えることができ、**FastAPI** がそれを実行し、結果を「注入」することを引き受けます。 + +他にも、「依存性注入」と同じような考えの一般的な用語があります: + +* リソース +* プロバイダ +* サービス +* インジェクタブル +* コンポーネント + +## **FastAPI** プラグイン + +統合や「プラグイン」は **依存性注入** システムを使って構築することができます。しかし、実際には、**「プラグイン」を作成する必要はありません**。依存関係を使用することで、無限の数の統合やインタラクションを宣言することができ、それが**path operation関数*で利用可能になるからです。 + +依存関係は非常にシンプルで直感的な方法で作成することができ、必要なPythonパッケージをインポートするだけで、*文字通り*数行のコードでAPI関数と統合することができます。 + +次の章では、リレーショナルデータベースやNoSQLデータベース、セキュリティなどについて、その例を見ていきます。 + +## **FastAPI** 互換性 + +依存性注入システムがシンプルなので、**FastAPI** は以下のようなものと互換性があります: + +* すべてのリレーショナルデータベース +* NoSQLデータベース +* 外部パッケージ +* 外部API +* 認証・認可システム +* API利用状況監視システム +* レスポンスデータ注入システム +* など。 + +## シンプルでパワフル + +階層依存性注入システムは、定義や使用方法が非常にシンプルであるにもかかわらず、非常に強力なものとなっています。 + +依存関係事態を定義する依存関係を定義することができます。 + +最終的には、依存関係の階層ツリーが構築され、**依存性注入**システムが、これらの依存関係(およびそのサブ依存関係)をすべて解決し、各ステップで結果を提供(注入)します。 + +例えば、4つのAPIエンドポイント(*path operations*)があるとします: + +* `/items/public/` +* `/items/private/` +* `/users/{user_id}/activate` +* `/items/pro/` + +そして、依存関係とサブ依存関係だけで、それぞれに異なるパーミッション要件を追加することができます: + +```mermaid +graph TB + +current_user(["current_user"]) +active_user(["active_user"]) +admin_user(["admin_user"]) +paying_user(["paying_user"]) + +public["/items/public/"] +private["/items/private/"] +activate_user["/users/{user_id}/activate"] +pro_items["/items/pro/"] + +current_user --> active_user +active_user --> admin_user +active_user --> paying_user + +current_user --> public +active_user --> private +admin_user --> activate_user +paying_user --> pro_items +``` + +## **OpenAPI** との統合 + +これら全ての依存関係は、要件を宣言すると同時に、*path operations*にパラメータやバリデーションを追加します。 + +**FastAPI** はそれをすべてOpenAPIスキーマに追加して、対話型のドキュメントシステムに表示されるようにします。 diff --git a/docs/ja/docs/tutorial/dependencies/sub-dependencies.md b/docs/ja/docs/tutorial/dependencies/sub-dependencies.md new file mode 100644 index 000000000..211a86a0a --- /dev/null +++ b/docs/ja/docs/tutorial/dependencies/sub-dependencies.md @@ -0,0 +1,86 @@ +# サブ依存関係 + +**サブ依存関係** を持つ依存関係を作成することができます。 + +それらは必要なだけ **深く** することができます。 + +**FastAPI** はそれらを解決してくれます。 + +### 最初の依存関係「依存可能なもの」 + +以下のような最初の依存関係(「依存可能なもの」)を作成することができます: + +{* ../../docs_src/dependencies/tutorial005.py hl[8,9] *} + +これはオプショナルのクエリパラメータ`q`を`str`として宣言し、それを返すだけです。 + +これは非常にシンプルです(あまり便利ではありません)が、サブ依存関係がどのように機能するかに焦点を当てるのに役立ちます。 + +### 第二の依存関係 「依存可能なもの」と「依存」 + +そして、別の依存関数(「依存可能なもの」)を作成して、同時にそれ自身の依存関係を宣言することができます(つまりそれ自身も「依存」です): + +{* ../../docs_src/dependencies/tutorial005.py hl[13] *} + +宣言されたパラメータに注目してみましょう: + +* この関数は依存関係(「依存可能なもの」)そのものであるにもかかわらず、別の依存関係を宣言しています(何か他のものに「依存」しています)。 + * これは`query_extractor`に依存しており、それが返す値をパラメータ`q`に代入します。 +* また、オプショナルの`last_query`クッキーを`str`として宣言します。 + * ユーザーがクエリ`q`を提供しなかった場合、クッキーに保存していた最後に使用したクエリを使用します。 + +### 依存関係の使用 + +以下のように依存関係を使用することができます: + +{* ../../docs_src/dependencies/tutorial005.py hl[21] *} + +/// info | 情報 + +*path operation関数*の中で宣言している依存関係は`query_or_cookie_extractor`の1つだけであることに注意してください。 + +しかし、**FastAPI** は`query_extractor`を最初に解決し、その結果を`query_or_cookie_extractor`を呼び出す時に渡す必要があることを知っています。 + +/// + +```mermaid +graph TB + +query_extractor(["query_extractor"]) +query_or_cookie_extractor(["query_or_cookie_extractor"]) + +read_query["/items/"] + +query_extractor --> query_or_cookie_extractor --> read_query +``` + +## 同じ依存関係の複数回の使用 + +依存関係の1つが同じ*path operation*に対して複数回宣言されている場合、例えば、複数の依存関係が共通のサブ依存関係を持っている場合、**FastAPI** はリクエストごとに1回だけそのサブ依存関係を呼び出します。 + +そして、返された値を「キャッシュ」に保存し、同じリクエストに対して依存関係を何度も呼び出す代わりに、特定のリクエストでそれを必要とする全ての「依存関係」に渡すことになります。 + +高度なシナリオでは、「キャッシュされた」値を使うのではなく、同じリクエストの各ステップ(おそらく複数回)で依存関係を呼び出す必要があることがわかっている場合、`Depens`を使用する際に、`use_cache=False`というパラメータを設定することができます。 + +```Python hl_lines="1" +async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)): + return {"fresh_value": fresh_value} +``` + +## まとめ + +ここで使われている派手な言葉は別にして、**依存性注入** システムは非常にシンプルです。 + +*path operation関数*と同じように見えるただの関数です。 + +しかし、それでも非常に強力で、任意の深くネストされた依存関係「グラフ」(ツリー)を宣言することができます。 + +/// tip | 豆知識 + +これらの単純な例では、全てが役に立つとは言えないかもしれません。 + +しかし、**security** についての章で、それがどれほど有用であるかがわかるでしょう。 + +そして、あなたを救うコードの量もみることになるでしょう。 + +/// diff --git a/docs/ja/docs/tutorial/encoder.md b/docs/ja/docs/tutorial/encoder.md new file mode 100644 index 000000000..409ebeec6 --- /dev/null +++ b/docs/ja/docs/tutorial/encoder.md @@ -0,0 +1,35 @@ +# JSON互換エンコーダ + +データ型(Pydanticモデルのような)をJSONと互換性のあるもの(`dict`や`list`など)に変更する必要がある場合があります。 + +例えば、データベースに保存する必要がある場合です。 + +そのために、**FastAPI** は`jsonable_encoder()`関数を提供しています。 + +## `jsonable_encoder`の使用 + +JSON互換のデータのみを受信するデータベース`fase_db`があるとしましょう。 + +例えば、`datetime`オブジェクトはJSONと互換性がないので、このデーターベースには受け取られません。 + +そのため、`datetime`オブジェクトはISO形式のデータを含む`str`に変換されなければなりません。 + +同様に、このデータベースはPydanticモデル(属性を持つオブジェクト)を受け取らず、`dict`だけを受け取ります。 + +そのために`jsonable_encoder`を使用することができます。 + +Pydanticモデルのようなオブジェクトを受け取り、JSON互換版を返します: + +{* ../../docs_src/encoder/tutorial001.py hl[5,22] *} + +この例では、Pydanticモデルを`dict`に、`datetime`を`str`に変換します。 + +呼び出した結果は、Pythonの標準の`json.dumps()`でエンコードできるものです。 + +これはJSON形式のデータを含む大きな`str`を(文字列として)返しません。JSONと互換性のある値とサブの値を持つPython標準のデータ構造(例:`dict`)を返します。 + +/// note | 備考 + +`jsonable_encoder`は実際には **FastAPI** が内部的にデータを変換するために使用します。しかしこれは他の多くのシナリオで有用です。 + +/// diff --git a/docs/ja/docs/tutorial/extra-data-types.md b/docs/ja/docs/tutorial/extra-data-types.md new file mode 100644 index 000000000..1be1c3f92 --- /dev/null +++ b/docs/ja/docs/tutorial/extra-data-types.md @@ -0,0 +1,62 @@ +# 追加データ型 + +今までは、以下のような一般的なデータ型を使用してきました: + +* `int` +* `float` +* `str` +* `bool` + +しかし、より複雑なデータ型を使用することもできます。 + +そして、今まで見てきたのと同じ機能を持つことになります: + +* 素晴らしいエディタのサポート +* 受信したリクエストからのデータ変換 +* レスポンスデータのデータ変換 +* データの検証 +* 自動注釈と文書化 + +## 他のデータ型 + +ここでは、使用できる追加のデータ型のいくつかを紹介します: + +* `UUID`: + * 多くのデータベースやシステムで共通のIDとして使用される、標準的な「ユニバーサルにユニークな識別子」です。 + * リクエストとレスポンスでは`str`として表現されます。 +* `datetime.datetime`: + * Pythonの`datetime.datetime`です。 + * リクエストとレスポンスはISO 8601形式の`str`で表現されます: `2008-09-15T15:53:00+05:00` +* `datetime.date`: + * Pythonの`datetime.date`です。 + * リクエストとレスポンスはISO 8601形式の`str`で表現されます: `2008-09-15` +* `datetime.time`: + * Pythonの`datetime.time`. + * リクエストとレスポンスはISO 8601形式の`str`で表現されます: `14:23:55.003` +* `datetime.timedelta`: + * Pythonの`datetime.timedelta`です。 + * リクエストとレスポンスでは合計秒数の`float`で表現されます。 + * Pydanticでは「ISO 8601 time diff encoding」として表現することも可能です。詳細はドキュメントを参照してください。 +* `frozenset`: + * リクエストとレスポンスでは`set`と同じように扱われます: + * リクエストでは、リストが読み込まれ、重複を排除して`set`に変換されます。 + * レスポンスでは`set`が`list`に変換されます。 + * 生成されたスキーマは`set`の値が一意であることを指定します(JSON Schemaの`uniqueItems`を使用します)。 +* `bytes`: + * Pythonの標準的な`bytes`です。 + * リクエストとレスポンスでは`str`として扱われます。 + * 生成されたスキーマは`str`で`binary`の「フォーマット」持つことを指定します。 +* `Decimal`: + * Pythonの標準的な`Decimal`です。 + * リクエストやレスポンスでは`float`と同じように扱います。 + +* Pydanticの全ての有効な型はこちらで確認できます: Pydantic data types。 +## 例 + +ここでは、上記の型のいくつかを使用したパラメータを持つ*path operation*の例を示します。 + +{* ../../docs_src/extra_data_types/tutorial001.py hl[1,2,12:16] *} + +関数内のパラメータは自然なデータ型を持っていることに注意してください。そして、以下のように通常の日付操作を行うことができます: + +{* ../../docs_src/extra_data_types/tutorial001.py hl[18,19] *} diff --git a/docs/ja/docs/tutorial/extra-models.md b/docs/ja/docs/tutorial/extra-models.md new file mode 100644 index 000000000..b7e215409 --- /dev/null +++ b/docs/ja/docs/tutorial/extra-models.md @@ -0,0 +1,191 @@ +# モデル - より詳しく + +先ほどの例に続き、複数の関連モデルを持つことが一般的です。 + +これはユーザーモデルの場合は特にそうです。なぜなら: + +* **入力モデル** にはパスワードが必要です。 +* **出力モデル**はパスワードをもつべきではありません。 +* **データベースモデル**はおそらくハッシュ化されたパスワードが必要になるでしょう。 + +/// danger | 危険 + +ユーザーの平文のパスワードは絶対に保存しないでください。常に認証に利用可能な「安全なハッシュ」を保存してください。 + +知らない方は、[セキュリティの章](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}で「パスワードハッシュ」とは何かを学ぶことができます。 + +/// + +## 複数のモデル + +ここでは、パスワードフィールドをもつモデルがどのように見えるのか、また、どこで使われるのか、大まかなイメージを紹介します: + +{* ../../docs_src/extra_models/tutorial001.py hl[9,11,16,22,24,29:30,33:35,40:41] *} + +### `**user_in.dict()`について + +#### Pydanticの`.dict()` + +`user_in`は`UserIn`クラスのPydanticモデルです。 + +Pydanticモデルには、モデルのデータを含む`dict`を返す`.dict()`メソッドがあります。 + +そこで、以下のようなPydanticオブジェクト`user_in`を作成すると: + +```Python +user_in = UserIn(username="john", password="secret", email="john.doe@example.com") +``` + +そして呼び出すと: + +```Python +user_dict = user_in.dict() +``` + +これで変数`user_dict`のデータを持つ`dict`ができました。(これはPydanticモデルのオブジェクトの代わりに`dict`です)。 + +そして呼び出すと: + +```Python +print(user_dict) +``` + +以下のようなPythonの`dict`を得ることができます: + +```Python +{ + 'username': 'john', + 'password': 'secret', + 'email': 'john.doe@example.com', + 'full_name': None, +} +``` + +#### `dict`の展開 + +`user_dict`のような`dict`を受け取り、それを`**user_dict`を持つ関数(またはクラス)に渡すと、Pythonはそれを「展開」します。これは`user_dict`のキーと値を直接キー・バリューの引数として渡します。 + +そこで上述の`user_dict`の続きを以下のように書くと: + +```Python +UserInDB(**user_dict) +``` + +以下と同等の結果になります: + +```Python +UserInDB( + username="john", + password="secret", + email="john.doe@example.com", + full_name=None, +) +``` + +もっと正確に言えば、`user_dict`を将来的にどんな内容であっても直接使用することになります: + +```Python +UserInDB( + username = user_dict["username"], + password = user_dict["password"], + email = user_dict["email"], + full_name = user_dict["full_name"], +) +``` + +#### 別のモデルからつくるPydanticモデル + +上述の例では`user_in.dict()`から`user_dict`をこのコードのように取得していますが: + +```Python +user_dict = user_in.dict() +UserInDB(**user_dict) +``` + +これは以下と同等です: + +```Python +UserInDB(**user_in.dict()) +``` + +...なぜなら`user_in.dict()`は`dict`であり、`**`を付与して`UserInDB`を渡してPythonに「展開」させているからです。 + +そこで、別のPydanticモデルのデータからPydanticモデルを取得します。 + +#### `dict`の展開と追加引数 + +そして、追加のキーワード引数`hashed_password=hashed_password`を以下のように追加すると: + +```Python +UserInDB(**user_in.dict(), hashed_password=hashed_password) +``` + +...以下のようになります: + +```Python +UserInDB( + username = user_dict["username"], + password = user_dict["password"], + email = user_dict["email"], + full_name = user_dict["full_name"], + hashed_password = hashed_password, +) +``` + +/// warning | 注意 + +サポートしている追加機能は、データの可能な流れをデモするだけであり、もちろん本当のセキュリティを提供しているわけではありません。 + +/// + +## 重複の削減 + +コードの重複を減らすことは、**FastAPI**の中核的なアイデアの1つです。 + +コードの重複が増えると、バグやセキュリティの問題、コードの非同期化問題(ある場所では更新しても他の場所では更新されない場合)などが発生する可能性が高くなります。 + +そして、これらのモデルは全てのデータを共有し、属性名や型を重複させています。 + +もっと良い方法があります。 + +他のモデルのベースとなる`UserBase`モデルを宣言することができます。そして、そのモデルの属性(型宣言、検証など)を継承するサブクラスを作ることができます。 + +データの変換、検証、文書化などはすべて通常通りに動作します。 + +このようにして、モデル間の違いだけを宣言することができます: + +{* ../../docs_src/extra_models/tutorial002.py hl[9,15,16,19,20,23,24] *} + +## `Union`または`anyOf` + +レスポンスを2つの型の`Union`として宣言することができます。 + +OpenAPIでは`anyOf`で定義されます。 + +そのためには、標準的なPythonの型ヒント`typing.Union`を使用します: + +{* ../../docs_src/extra_models/tutorial003.py hl[1,14,15,18,19,20,33] *} + +## モデルのリスト + +同じように、オブジェクトのリストのレスポンスを宣言することができます。 + +そのためには、標準のPythonの`typing.List`を使用する: + +{* ../../docs_src/extra_models/tutorial004.py hl[1,20] *} + +## 任意の`dict`を持つレスポンス + +また、Pydanticモデルを使用せずに、キーと値の型だけを定義した任意の`dict`を使ってレスポンスを宣言することもできます。 + +これは、有効なフィールド・属性名(Pydanticモデルに必要なもの)を事前に知らない場合に便利です。 + +この場合、`typing.Dict`を使用することができます: + +{* ../../docs_src/extra_models/tutorial005.py hl[1,8] *} + +## まとめ + +複数のPydanticモデルを使用し、ケースごとに自由に継承します。 + +エンティティが異なる「状態」を持たなければならない場合は、エンティティごとに単一のデータモデルを持つ必要はありません。`password` や `password_hash` やパスワードなしなどのいくつかの「状態」をもつユーザー「エンティティ」の場合の様にすれば良いです。 diff --git a/docs/ja/docs/tutorial/first-steps.md b/docs/ja/docs/tutorial/first-steps.md index c696f7d48..d14f0cbec 100644 --- a/docs/ja/docs/tutorial/first-steps.md +++ b/docs/ja/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ 最もシンプルなFastAPIファイルは以下のようになります: -```Python -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} これを`main.py`にコピーします。 @@ -24,12 +22,15 @@ $ uvicorn main:app --reload
-!!! note "備考" - `uvicorn main:app`は以下を示します: +/// note | 備考 + +`uvicorn main:app`は以下を示します: + +* `main`: `main.py`ファイル (Python "module")。 +* `app`: `main.py`内部で作られるobject(`app = FastAPI()`のように記述される)。 +* `--reload`: コードの変更時にサーバーを再起動させる。開発用。 - * `main`: `main.py`ファイル (Python "module")。 - * `app`: `main.py`内部で作られるobject(`app = FastAPI()`のように記述される)。 - * `--reload`: コードの変更時にサーバーを再起動させる。開発用。 +/// 出力には次のような行があります: @@ -130,22 +131,21 @@ OpenAPIスキーマは、FastAPIに含まれている2つのインタラクテ ### Step 1: `FastAPI`をインポート -```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI`は、APIのすべての機能を提供するPythonクラスです。 -!!! note "技術詳細" - `FastAPI`は`Starlette`を直接継承するクラスです。 +/// note | 技術詳細 + +`FastAPI`は`Starlette`を直接継承するクラスです。 - `FastAPI`でもStarletteのすべての機能を利用可能です。 +`FastAPI`でもStarletteのすべての機能を利用可能です。 + +/// ### Step 2: `FastAPI`の「インスタンス」を生成 -```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[3] *} ここで、`app`変数が`FastAPI`クラスの「インスタンス」になります。 これが、すべてのAPIを作成するための主要なポイントになります。 @@ -164,9 +164,7 @@ $ uvicorn main:app --reload 以下のようなアプリを作成したとき: -```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} -``` +{* ../../docs_src/first_steps/tutorial002.py hl[3] *} そして、それを`main.py`ファイルに置き、次のように`uvicorn`を呼び出します: @@ -198,8 +196,11 @@ https://example.com/items/foo /items/foo ``` -!!! info "情報" - 「パス」は一般に「エンドポイント」または「ルート」とも呼ばれます。 +/// info | 情報 + +「パス」は一般に「エンドポイント」または「ルート」とも呼ばれます。 + +/// APIを構築する際、「パス」は「関心事」と「リソース」を分離するための主要な方法です。 @@ -240,24 +241,25 @@ APIを構築するときは、通常、これらの特定のHTTPメソッドを #### *パスオペレーションデコレータ*を定義 -```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[6] *} `@app.get("/")`は直下の関数が下記のリクエストの処理を担当することを**FastAPI**に伝えます: * パス `/` * get オペレーション -!!! info "`@decorator` について" - Pythonにおける`@something`シンタックスはデコレータと呼ばれます。 +/// info | `@decorator` について + +Pythonにおける`@something`シンタックスはデコレータと呼ばれます。 + +「デコレータ」は関数の上に置きます。かわいらしい装飾的な帽子のようです(この用語の由来はそこにあると思います)。 - 「デコレータ」は関数の上に置きます。かわいらしい装飾的な帽子のようです(この用語の由来はそこにあると思います)。 +「デコレータ」は直下の関数を受け取り、それを使って何かを行います。 - 「デコレータ」は直下の関数を受け取り、それを使って何かを行います。 +私たちの場合、このデコレーターは直下の関数が**オペレーション** `get`を使用した**パス**` / `に対応することを**FastAPI** に通知します。 - 私たちの場合、このデコレーターは直下の関数が**オペレーション** `get`を使用した**パス**` / `に対応することを**FastAPI** に通知します。 +これが「*パスオペレーションデコレータ*」です。 - これが「*パスオペレーションデコレータ*」です。 +/// 他のオペレーションも使用できます: @@ -272,14 +274,17 @@ APIを構築するときは、通常、これらの特定のHTTPメソッドを * `@app.patch()` * `@app.trace()` -!!! tip "豆知識" - 各オペレーション (HTTPメソッド)は自由に使用できます。 +/// tip | 豆知識 + +各オペレーション (HTTPメソッド)は自由に使用できます。 + +**FastAPI**は特定の意味づけを強制しません。 - **FastAPI**は特定の意味づけを強制しません。 +ここでの情報は、要件ではなくガイドラインとして提示されます。 - ここでの情報は、要件ではなくガイドラインとして提示されます。 +例えば、GraphQLを使用する場合、通常は`POST`オペレーションのみを使用してすべてのアクションを実行します。 - 例えば、GraphQLを使用する場合、通常は`POST`オペレーションのみを使用してすべてのアクションを実行します。 +/// ### Step 4: **パスオペレーション**を定義 @@ -289,9 +294,7 @@ APIを構築するときは、通常、これらの特定のHTTPメソッドを * **オペレーション**: は`get`です。 * **関数**: 「デコレータ」の直下にある関数 (`@app.get("/")`の直下) です。 -```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[7] *} これは、Pythonの関数です。 @@ -303,18 +306,17 @@ APIを構築するときは、通常、これらの特定のHTTPメソッドを `async def`の代わりに通常の関数として定義することもできます: -```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} -``` +{* ../../docs_src/first_steps/tutorial003.py hl[7] *} + +/// note | 備考 -!!! note "備考" - 違いが分からない場合は、[Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}を確認してください。 +違いが分からない場合は、[Async: *"急いでいますか?"*](../async.md#_1){.internal-link target=_blank}を確認してください。 + +/// ### Step 5: コンテンツの返信 -```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[8] *} `dict`、`list`、`str`、`int`などを返すことができます。 diff --git a/docs/ja/docs/tutorial/handling-errors.md b/docs/ja/docs/tutorial/handling-errors.md new file mode 100644 index 000000000..9a46cc738 --- /dev/null +++ b/docs/ja/docs/tutorial/handling-errors.md @@ -0,0 +1,261 @@ +# エラーハンドリング + +APIを使用しているクライアントにエラーを通知する必要がある状況はたくさんあります。 + +このクライアントは、フロントエンドを持つブラウザ、誰かのコード、IoTデバイスなどが考えられます。 + +クライアントに以下のようなことを伝える必要があるかもしれません: + +* クライアントにはその操作のための十分な権限がありません。 +* クライアントはそのリソースにアクセスできません。 +* クライアントがアクセスしようとしていた項目が存在しません。 +* など + +これらの場合、通常は **400**(400から499)の範囲内の **HTTPステータスコード** を返すことになります。 + +これは200のHTTPステータスコード(200から299)に似ています。これらの「200」ステータスコードは、何らかの形でリクエスト「成功」であったことを意味します。 + +400の範囲にあるステータスコードは、クライアントからのエラーがあったことを意味します。 + +**"404 Not Found"** のエラー(およびジョーク)を覚えていますか? + +## `HTTPException`の使用 + +HTTPレスポンスをエラーでクライアントに返すには、`HTTPException`を使用します。 + +### `HTTPException`のインポート + +{* ../../docs_src/handling_errors/tutorial001.py hl[1] *} + +### コード内での`HTTPException`の発生 + +`HTTPException`は通常のPythonの例外であり、APIに関連するデータを追加したものです。 + +Pythonの例外なので、`return`ではなく、`raise`です。 + +これはまた、*path operation関数*の内部で呼び出しているユーティリティ関数の内部から`HTTPException`を発生させた場合、*path operation関数*の残りのコードは実行されず、そのリクエストを直ちに終了させ、`HTTPException`からのHTTPエラーをクライアントに送信することを意味します。 + +値を返す`return`よりも例外を発生させることの利点は、「依存関係とセキュリティ」のセクションでより明確になります。 + +この例では、クライアントが存在しないIDでアイテムを要求した場合、`404`のステータスコードを持つ例外を発生させます: + +{* ../../docs_src/handling_errors/tutorial001.py hl[11] *} + +### レスポンス結果 + +クライアントが`http://example.com/items/foo`(`item_id` `"foo"`)をリクエストすると、HTTPステータスコードが200で、以下のJSONレスポンスが返されます: + +```JSON +{ + "item": "The Foo Wrestlers" +} +``` + +しかし、クライアントが`http://example.com/items/bar`(存在しない`item_id` `"bar"`)をリクエストした場合、HTTPステータスコード404("not found"エラー)と以下のJSONレスポンスが返されます: + +```JSON +{ + "detail": "Item not found" +} +``` + +/// tip | 豆知識 + +`HTTPException`を発生させる際には、`str`だけでなく、JSONに変換できる任意の値を`detail`パラメータとして渡すことができます。 + +`dist`や`list`などを渡すことができます。 + +これらは **FastAPI** によって自動的に処理され、JSONに変換されます。 + +/// + +## カスタムヘッダーの追加 + +例えば、いくつかのタイプのセキュリティのために、HTTPエラーにカスタムヘッダを追加できると便利な状況がいくつかあります。 + +おそらくコードの中で直接使用する必要はないでしょう。 + +しかし、高度なシナリオのために必要な場合には、カスタムヘッダーを追加することができます: + +{* ../../docs_src/handling_errors/tutorial002.py hl[14] *} + +## カスタム例外ハンドラのインストール + +カスタム例外ハンドラはStarletteと同じ例外ユーティリティを使用して追加することができます。 + +あなた(または使用しているライブラリ)が`raise`するかもしれないカスタム例外`UnicornException`があるとしましょう。 + +そして、この例外をFastAPIでグローバルに処理したいと思います。 + +カスタム例外ハンドラを`@app.exception_handler()`で追加することができます: + +{* ../../docs_src/handling_errors/tutorial003.py hl[5,6,7,13,14,15,16,17,18,24] *} + +ここで、`/unicorns/yolo`をリクエストすると、*path operation*は`UnicornException`を`raise`します。 + +しかし、これは`unicorn_exception_handler`で処理されます。 + +そのため、HTTPステータスコードが`418`で、JSONの内容が以下のような明確なエラーを受け取ることになります: + +```JSON +{"message": "Oops! yolo did something. There goes a rainbow..."} +``` + +/// note | 技術詳細 + +また、`from starlette.requests import Request`と`from starlette.responses import JSONResponse`を使用することもできます。 + +**FastAPI** は開発者の利便性を考慮して、`fastapi.responses`と同じ`starlette.responses`を提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。これは`Request`と同じです。 + +/// + +## デフォルトの例外ハンドラのオーバーライド + +**FastAPI** にはいくつかのデフォルトの例外ハンドラがあります。 + +これらのハンドラは、`HTTPException`を`raise`させた場合や、リクエストに無効なデータが含まれている場合にデフォルトのJSONレスポンスを返す役割を担っています。 + +これらの例外ハンドラを独自のものでオーバーライドすることができます。 + +### リクエスト検証の例外のオーバーライド + +リクエストに無効なデータが含まれている場合、**FastAPI** は内部的に`RequestValidationError`を発生させます。 + +また、そのためのデフォルトの例外ハンドラも含まれています。 + +これをオーバーライドするには`RequestValidationError`をインポートして`@app.exception_handler(RequestValidationError)`と一緒に使用して例外ハンドラをデコレートします。 + +この例外ハンドラは`Requset`と例外を受け取ります。 + +{* ../../docs_src/handling_errors/tutorial004.py hl[2,14,15,16] *} + +これで、`/items/foo`にアクセスすると、デフォルトのJSONエラーの代わりに以下が返されます: + +```JSON +{ + "detail": [ + { + "loc": [ + "path", + "item_id" + ], + "msg": "value is not a valid integer", + "type": "type_error.integer" + } + ] +} +``` + +以下のようなテキスト版を取得します: + +``` +1 validation error +path -> item_id + value is not a valid integer (type=type_error.integer) +``` + +#### `RequestValidationError`と`ValidationError` + +/// warning | 注意 + +これらは今のあなたにとって重要でない場合は省略しても良い技術的な詳細です。 + +/// + +`RequestValidationError`はPydanticの`ValidationError`のサブクラスです。 + +**FastAPI** は`response_model`でPydanticモデルを使用していて、データにエラーがあった場合、ログにエラーが表示されるようにこれを使用しています。 + +しかし、クライアントやユーザーはそれを見ることはありません。その代わりに、クライアントはHTTPステータスコード`500`の「Internal Server Error」を受け取ります。 + +*レスポンス*やコードのどこか(クライアントの*リクエスト*ではなく)にPydanticの`ValidationError`がある場合、それは実際にはコードのバグなのでこのようにすべきです。 + +また、あなたがそれを修正している間は、セキュリティの脆弱性が露呈する場合があるため、クライアントやユーザーがエラーに関する内部情報にアクセスできないようにしてください。 + +### エラーハンドラ`HTTPException`のオーバーライド + +同様に、`HTTPException`ハンドラをオーバーライドすることもできます。 + +例えば、これらのエラーに対しては、JSONではなくプレーンテキストを返すようにすることができます: + +{* ../../docs_src/handling_errors/tutorial004.py hl[3,4,9,10,11,22] *} + +/// note | 技術詳細 + +また、`from starlette.responses import PlainTextResponse`を使用することもできます。 + +**FastAPI** は開発者の利便性を考慮して、`fastapi.responses`と同じ`starlette.responses`を提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。 + +/// + +### `RequestValidationError`のボディの使用 + +`RequestValidationError`には無効なデータを含む`body`が含まれています。 + +アプリ開発中に本体のログを取ってデバッグしたり、ユーザーに返したりなどに使用することができます。 + +{* ../../docs_src/handling_errors/tutorial005.py hl[14] *} + +ここで、以下のような無効な項目を送信してみてください: + +```JSON +{ + "title": "towel", + "size": "XL" +} +``` + +受信したボディを含むデータが無効であることを示すレスポンスが表示されます: + +```JSON hl_lines="12 13 14 15" +{ + "detail": [ + { + "loc": [ + "body", + "size" + ], + "msg": "value is not a valid integer", + "type": "type_error.integer" + } + ], + "body": { + "title": "towel", + "size": "XL" + } +} +``` + +#### FastAPIの`HTTPException`とStarletteの`HTTPException` + +**FastAPI**は独自の`HTTPException`を持っています。 + +また、 **FastAPI**のエラークラス`HTTPException`はStarletteのエラークラス`HTTPException`を継承しています。 + +唯一の違いは、**FastAPI** の`HTTPException`はレスポンスに含まれるヘッダを追加できることです。 + +これはOAuth 2.0といくつかのセキュリティユーティリティのために内部的に必要とされ、使用されています。 + +そのため、コード内では通常通り **FastAPI** の`HTTPException`を発生させ続けることができます。 + +しかし、例外ハンドラを登録する際には、Starletteの`HTTPException`を登録しておく必要があります。 + +これにより、Starletteの内部コードやStarletteの拡張機能やプラグインの一部が`HTTPException`を発生させた場合、ハンドラがそれをキャッチして処理することができるようになります。 + +以下の例では、同じコード内で両方の`HTTPException`を使用できるようにするために、Starletteの例外の名前を`StarletteHTTPException`に変更しています: + +```Python +from starlette.exceptions import HTTPException as StarletteHTTPException +``` + +### **FastAPI** の例外ハンドラの再利用 + +また、何らかの方法で例外を使用することもできますが、**FastAPI** から同じデフォルトの例外ハンドラを使用することもできます。 + +デフォルトの例外ハンドラを`fastapi.exception_handlers`からインポートして再利用することができます: + +{* ../../docs_src/handling_errors/tutorial006.py hl[2,3,4,5,15,21] *} + +この例では、非常に表現力のあるメッセージでエラーを`print`しています。 + +しかし、例外を使用して、デフォルトの例外ハンドラを再利用することができるということが理解できます。 diff --git a/docs/ja/docs/tutorial/header-params.md b/docs/ja/docs/tutorial/header-params.md index 1bf8440bb..ac89afbdb 100644 --- a/docs/ja/docs/tutorial/header-params.md +++ b/docs/ja/docs/tutorial/header-params.md @@ -6,9 +6,7 @@ まず、`Header`をインポートします: -```Python hl_lines="3" -{!../../../docs_src/header_params/tutorial001.py!} -``` +{* ../../docs_src/header_params/tutorial001.py hl[3] *} ## `Header`のパラメータの宣言 @@ -16,17 +14,21 @@ 最初の値がデフォルト値で、追加の検証パラメータや注釈パラメータをすべて渡すことができます。 -```Python hl_lines="9" -{!../../../docs_src/header_params/tutorial001.py!} -``` +{* ../../docs_src/header_params/tutorial001.py hl[9] *} + +/// note | 技術詳細 + +`Header`は`Path`や`Query`、`Cookie`の「姉妹」クラスです。また、同じ共通の`Param`クラスを継承しています。 + +しかし、`fastapi`から`Query`や`Path`、`Header`などをインポートする場合、それらは実際には特殊なクラスを返す関数であることを覚えておいてください。 -!!! note "技術詳細" - `Header`は`Path`や`Query`、`Cookie`の「姉妹」クラスです。また、同じ共通の`Param`クラスを継承しています。 +/// - しかし、`fastapi`から`Query`や`Path`、`Header`などをインポートする場合、それらは実際には特殊なクラスを返す関数であることを覚えておいてください。 +/// info | 情報 -!!! info "情報" - ヘッダーを宣言するには、`Header`を使う必要があります。なぜなら、そうしないと、パラメータがクエリのパラメータとして解釈されてしまうからです。 +ヘッダーを宣言するには、`Header`を使う必要があります。なぜなら、そうしないと、パラメータがクエリのパラメータとして解釈されてしまうからです。 + +/// ## 自動変換 @@ -44,13 +46,13 @@ もしなんらかの理由でアンダースコアからハイフンへの自動変換を無効にする必要がある場合は、`Header`の`convert_underscores`に`False`を設定してください: -```Python hl_lines="9" -{!../../../docs_src/header_params/tutorial002.py!} -``` +{* ../../docs_src/header_params/tutorial002.py hl[9] *} -!!! warning "注意" - `convert_underscores`を`False`に設定する前に、HTTPプロキシやサーバの中にはアンダースコアを含むヘッダーの使用を許可していないものがあることに注意してください。 +/// warning | 注意 +`convert_underscores`を`False`に設定する前に、HTTPプロキシやサーバの中にはアンダースコアを含むヘッダーの使用を許可していないものがあることに注意してください。 + +/// ## ヘッダーの重複 @@ -62,9 +64,7 @@ 例えば、複数回出現する可能性のある`X-Token`のヘッダを定義するには、以下のように書くことができます: -```Python hl_lines="9" -{!../../../docs_src/header_params/tutorial003.py!} -``` +{* ../../docs_src/header_params/tutorial003.py hl[9] *} もし、その*path operation*で通信する場合は、次のように2つのHTTPヘッダーを送信します: diff --git a/docs/ja/docs/tutorial/index.md b/docs/ja/docs/tutorial/index.md index 856cde44b..87d3751fd 100644 --- a/docs/ja/docs/tutorial/index.md +++ b/docs/ja/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ...これには、コードを実行するサーバーとして使用できる `uvicorn`も含まれます。 -!!! note "備考" - パーツ毎にインストールすることも可能です。 +/// note | 備考 - 以下は、アプリケーションを本番環境にデプロイする際に行うであろうものです: +パーツ毎にインストールすることも可能です。 - ``` - pip install fastapi - ``` +以下は、アプリケーションを本番環境にデプロイする際に行うであろうものです: - また、サーバーとして動作するように`uvicorn` をインストールします: +``` +pip install fastapi +``` + +また、サーバーとして動作するように`uvicorn` をインストールします: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +そして、使用したい依存関係をそれぞれ同様にインストールします。 - そして、使用したい依存関係をそれぞれ同様にインストールします。 +/// ## 高度なユーザーガイド diff --git a/docs/ja/docs/tutorial/metadata.md b/docs/ja/docs/tutorial/metadata.md new file mode 100644 index 000000000..b93dedcb9 --- /dev/null +++ b/docs/ja/docs/tutorial/metadata.md @@ -0,0 +1,101 @@ +# メタデータとドキュメントのURL + +**FastAPI** アプリケーションのいくつかのメタデータの設定をカスタマイズできます。 + +## タイトル、説明文、バージョン + +以下を設定できます: + +* **タイトル**: OpenAPIおよび自動APIドキュメントUIでAPIのタイトル/名前として使用される。 +* **説明文**: OpenAPIおよび自動APIドキュメントUIでのAPIの説明文。 +* **バージョン**: APIのバージョン。例: `v2` または `2.5.0`。 + *たとえば、以前のバージョンのアプリケーションがあり、OpenAPIも使用している場合に便利です。 + +これらを設定するには、パラメータ `title`、`description`、`version` を使用します: + +{* ../../docs_src/metadata/tutorial001.py hl[4:6] *} + +この設定では、自動APIドキュメントは以下の様になります: + + + +## タグのためのメタデータ + +さらに、パラメータ `openapi_tags` を使うと、path operations をグループ分けするための複数のタグに関するメタデータを追加できます。 + +それぞれのタグ毎にひとつの辞書を含むリストをとります。 + +それぞれの辞書は以下をもつことができます: + +* `name` (**必須**): *path operations* および `APIRouter` の `tags` パラメーターで使用するのと同じタグ名である `str`。 +* `description`: タグの簡単な説明文である `str`。 Markdownで記述でき、ドキュメントUIに表示されます。 +* `externalDocs`: 外部ドキュメントを説明するための `dict`: + * `description`: 外部ドキュメントの簡単な説明文である `str`。 + * `url` (**必須**): 外部ドキュメントのURLである `str`。 + +### タグのためのメタデータの作成 + +`users` と `items` のタグを使った例でメタデータの追加を試してみましょう。 + +タグのためのメタデータを作成し、それを `openapi_tags` パラメータに渡します。 + +{* ../../docs_src/metadata/tutorial004.py hl[3:16,18] *} + +説明文 (description) の中で Markdown を使用できることに注意してください。たとえば、「login」は太字 (**login**) で表示され、「fancy」は斜体 (_fancy_) で表示されます。 + +/// tip | 豆知識 + +使用するすべてのタグにメタデータを追加する必要はありません。 + +/// + +### 自作タグの使用 + +`tags` パラメーターを使用して、それぞれの *path operations* (および `APIRouter`) を異なるタグに割り当てます: + +{* ../../docs_src/metadata/tutorial004.py hl[21,26] *} + +/// info | 情報 + +タグのより詳しい説明を知りたい場合は [Path Operation Configuration](path-operation-configuration.md#tags){.internal-link target=_blank} を参照して下さい。 + +/// + +### ドキュメントの確認 + +ここで、ドキュメントを確認すると、追加したメタデータがすべて表示されます: + + + +### タグの順番 + +タグのメタデータ辞書の順序は、ドキュメントUIに表示される順序の定義にもなります。 + +たとえば、`users` はアルファベット順では `items` の後に続きます。しかし、リストの最初に `users` のメタデータ辞書を追加したため、ドキュメントUIでは `users` が先に表示されます。 + +## OpenAPI URL + +デフォルトでは、OpenAPIスキーマは `/openapi.json` で提供されます。 + +ただし、パラメータ `openapi_url` を使用して設定を変更できます。 + +たとえば、`/api/v1/openapi.json` で提供されるように設定するには: + +{* ../../docs_src/metadata/tutorial002.py hl[3] *} + +OpenAPIスキーマを完全に無効にする場合は、`openapi_url=None` を設定できます。これにより、それを使用するドキュメントUIも無効になります。 + +## ドキュメントのURL + +以下の2つのドキュメントUIを構築できます: + +* **Swagger UI**: `/docs` で提供されます。 + * URL はパラメータ `docs_url` で設定できます。 + * `docs_url=None` を設定することで無効にできます。 +* ReDoc: `/redoc` で提供されます。 + * URL はパラメータ `redoc_url` で設定できます。 + * `redoc_url=None` を設定することで無効にできます。 + +たとえば、`/documentation` でSwagger UIが提供されるように設定し、ReDocを無効にするには: + +{* ../../docs_src/metadata/tutorial003.py hl[3] *} diff --git a/docs/ja/docs/tutorial/middleware.md b/docs/ja/docs/tutorial/middleware.md index 973eb2b1a..326e9145c 100644 --- a/docs/ja/docs/tutorial/middleware.md +++ b/docs/ja/docs/tutorial/middleware.md @@ -11,10 +11,13 @@ * その**レスポンス**に対して何かを実行したり、必要なコードを実行したりできます。 * そして、**レスポンス**を返します。 -!!! note "技術詳細" - `yield` を使った依存関係をもつ場合は、終了コードはミドルウェアの *後に* 実行されます。 +/// note | 技術詳細 - バックグラウンドタスク (後述) がある場合は、それらは全てのミドルウェアの *後に* 実行されます。 +`yield` を使った依存関係をもつ場合は、終了コードはミドルウェアの *後に* 実行されます。 + +バックグラウンドタスク (後述) がある場合は、それらは全てのミドルウェアの *後に* 実行されます。 + +/// ## ミドルウェアの作成 @@ -28,19 +31,23 @@ * 次に、対応する*path operation*によって生成された `response` を返します。 * その後、`response` を返す前にさらに `response` を変更することもできます。 -```Python hl_lines="8-9 11 14" -{!../../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[8:9,11,14] *} + +/// tip | 豆知識 + +'X-'プレフィックスを使用してカスタムの独自ヘッダーを追加できます。 + +ただし、ブラウザのクライアントに表示させたいカスタムヘッダーがある場合は、StarletteのCORSドキュメントに記載されているパラメータ `expose_headers` を使用して、それらをCORS設定に追加する必要があります ([CORS (オリジン間リソース共有)](cors.md){.internal-link target=_blank}) + +/// -!!! tip "豆知識" - 'X-'プレフィックスを使用してカスタムの独自ヘッダーを追加できます。 +/// note | 技術詳細 - ただし、ブラウザのクライアントに表示させたいカスタムヘッダーがある場合は、StarletteのCORSドキュメントに記載されているパラメータ `expose_headers` を使用して、それらをCORS設定に追加する必要があります ([CORS (オリジン間リソース共有)](cors.md){.internal-link target=_blank}) +`from starlette.requests import Request` を使用することもできます。 -!!! note "技術詳細" - `from starlette.requests import Request` を使用することもできます。 +**FastAPI**は、開発者の便利のためにこれを提供していますが、Starletteから直接きています。 - **FastAPI**は、開発者の便利のためにこれを提供していますが、Starletteから直接きています。 +/// ### `response` の前後 @@ -50,9 +57,7 @@ 例えば、リクエストの処理とレスポンスの生成にかかった秒数を含むカスタムヘッダー `X-Process-Time` を追加できます: -```Python hl_lines="10 12-13" -{!../../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *} ## その他のミドルウェア diff --git a/docs/ja/docs/tutorial/path-operation-configuration.md b/docs/ja/docs/tutorial/path-operation-configuration.md new file mode 100644 index 000000000..0cc38cb25 --- /dev/null +++ b/docs/ja/docs/tutorial/path-operation-configuration.md @@ -0,0 +1,97 @@ +# Path Operationの設定 + +*path operationデコレータ*を設定するためのパラメータがいくつかあります。 + +/// warning | 注意 + +これらのパラメータは*path operation関数*ではなく、*path operationデコレータ*に直接渡されることに注意してください。 + +/// + +## レスポンスステータスコード + +*path operation*のレスポンスで使用する(HTTP)`status_code`を定義することができます。 + +`404`のように`int`のコードを直接渡すことができます。 + +しかし、それぞれの番号コードが何のためのものか覚えていない場合は、`status`のショートカット定数を使用することができます: + +{* ../../docs_src/path_operation_configuration/tutorial001.py hl[3,17] *} + +そのステータスコードはレスポンスで使用され、OpenAPIスキーマに追加されます。 + +/// note | 技術詳細 + +また、`from starlette import status`を使用することもできます。 + +**FastAPI** は開発者の利便性を考慮して、`fastapi.status`と同じ`starlette.status`を提供しています。しかし、これはStarletteから直接提供されています。 + +/// + +## タグ + +`tags`パラメータを`str`の`list`(通常は1つの`str`)と一緒に渡すと、*path operation*にタグを追加できます: + +{* ../../docs_src/path_operation_configuration/tutorial002.py hl[17,22,27] *} + +これらはOpenAPIスキーマに追加され、自動ドキュメントのインターフェースで使用されます: + + + +## 概要と説明 + +`summary`と`description`を追加できます: + +{* ../../docs_src/path_operation_configuration/tutorial003.py hl[20:21] *} + +## docstringを用いた説明 + +説明文は長くて複数行におよぶ傾向があるので、関数docstring内に*path operation*の説明文を宣言できます。すると、**FastAPI** は説明文を読み込んでくれます。 + +docstringにMarkdownを記述すれば、正しく解釈されて表示されます。(docstringのインデントを考慮して) + +{* ../../docs_src/path_operation_configuration/tutorial004.py hl[19:27] *} + +これは対話的ドキュメントで使用されます: + + + +## レスポンスの説明 + +`response_description`パラメータでレスポンスの説明をすることができます。 + +{* ../../docs_src/path_operation_configuration/tutorial005.py hl[21] *} + +/// info | 情報 + +`respnse_description`は具体的にレスポンスを参照し、`description`は*path operation*全般を参照していることに注意してください。 + +/// + +/// check | 確認 + +OpenAPIは*path operation*ごとにレスポンスの説明を必要としています。 + +そのため、それを提供しない場合は、**FastAPI** が自動的に「成功のレスポンス」を生成します。 + +/// + + + +## 非推奨の*path operation* + +*path operation*をdeprecatedとしてマークする必要があるが、それを削除しない場合は、`deprecated`パラメータを渡します: + +{* ../../docs_src/path_operation_configuration/tutorial006.py hl[16] *} + +対話的ドキュメントでは非推奨と明記されます: + + + +*path operations*が非推奨である場合とそうでない場合でどのように見えるかを確認してください: + + + +## まとめ + +*path operationデコレータ*にパラメータを渡すことで、*path operations*のメタデータを簡単に設定・追加することができます。 diff --git a/docs/ja/docs/tutorial/path-params-numeric-validations.md b/docs/ja/docs/tutorial/path-params-numeric-validations.md new file mode 100644 index 000000000..a1810ae37 --- /dev/null +++ b/docs/ja/docs/tutorial/path-params-numeric-validations.md @@ -0,0 +1,117 @@ +# パスパラメータと数値の検証 + +クエリパラメータに対して`Query`でより多くのバリデーションとメタデータを宣言できるのと同じように、パスパラメータに対しても`Path`で同じ種類のバリデーションとメタデータを宣言することができます。 + +## Pathのインポート + +まず初めに、`fastapi`から`Path`をインポートします: + +{* ../../docs_src/path_params_numeric_validations/tutorial001.py hl[1] *} + +## メタデータの宣言 + +パラメータは`Query`と同じものを宣言することができます。 + +例えば、パスパラメータ`item_id`に対して`title`のメタデータを宣言するには以下のようにします: + +{* ../../docs_src/path_params_numeric_validations/tutorial001.py hl[8] *} + +/// note | 備考 + +パスの一部でなければならないので、パスパラメータは常に必須です。 + +そのため、`...`を使用して必須と示す必要があります。 + +それでも、`None`で宣言しても、デフォルト値を設定しても、何の影響もなく、常に必要とされていることに変わりはありません。 + +/// + +## 必要に応じてパラメータを並び替える + +クエリパラメータ`q`を必須の`str`として宣言したいとしましょう。 + +また、このパラメータには何も宣言する必要がないので、`Query`を使う必要はありません。 + +しかし、パスパラメータ`item_id`のために`Path`を使用する必要があります。 + +Pythonは「デフォルト」を持たない値の前に「デフォルト」を持つ値を置くことができません。 + +しかし、それらを並び替えることができ、デフォルト値を持たない値(クエリパラメータ`q`)を最初に持つことができます。 + +**FastAPI**では関係ありません。パラメータは名前、型、デフォルトの宣言(`Query`、`Path`など)で検出され、順番は気にしません。 + +そのため、以下のように関数を宣言することができます: + +{* ../../docs_src/path_params_numeric_validations/tutorial002.py hl[8] *} + +## 必要に応じてパラメータを並び替えるトリック + +クエリパラメータ`q`を`Query`やデフォルト値なしで宣言し、パスパラメータ`item_id`を`Path`を用いて宣言し、それらを別の順番に並びたい場合、Pythonには少し特殊な構文が用意されています。 + +関数の最初のパラメータとして`*`を渡します。 + +Pythonはその`*`で何かをすることはありませんが、それ以降のすべてのパラメータがキーワード引数(キーと値のペア)として呼ばれるべきものであると知っているでしょう。それはkwargsとしても知られています。たとえデフォルト値がなくても。 + +{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[8] *} + +## 数値の検証: 以上 + +`Query`と`Path`(、そして後述する他のもの)を用いて、文字列の制約を宣言することができますが、数値の制約も同様に宣言できます。 + +ここで、`ge=1`の場合、`item_id`は`1`「より大きい`g`か、同じ`e`」整数でなれけばなりません。 + +{* ../../docs_src/path_params_numeric_validations/tutorial004.py hl[8] *} + +## 数値の検証: より大きいと小なりイコール + +以下も同様です: + +* `gt`: より大きい(`g`reater `t`han) +* `le`: 小なりイコール(`l`ess than or `e`qual) + +{* ../../docs_src/path_params_numeric_validations/tutorial005.py hl[9] *} + +## 数値の検証: 浮動小数点、 大なり小なり + +数値のバリデーションは`float`の値に対しても有効です。 + +ここで重要になってくるのはgtだけでなくgeも宣言できることです。これと同様に、例えば、値が`1`より小さくても`0`より大きくなければならないことを要求することができます。 + +したがって、`0.5`は有効な値ですが、`0.0`や`0`はそうではありません。 + +これはltも同じです。 + +{* ../../docs_src/path_params_numeric_validations/tutorial006.py hl[11] *} + +## まとめ + +`Query`と`Path`(そしてまだ見たことない他のもの)では、[クエリパラメータと文字列の検証](query-params-str-validations.md){.internal-link target=_blank}と同じようにメタデータと文字列の検証を宣言することができます。 + +また、数値のバリデーションを宣言することもできます: + +* `gt`: より大きい(`g`reater `t`han) +* `ge`: 以上(`g`reater than or `e`qual) +* `lt`: より小さい(`l`ess `t`han) +* `le`: 以下(`l`ess than or `e`qual) + +/// info | 情報 + +`Query`、`Path`などは後に共通の`Param`クラスのサブクラスを見ることになります。(使う必要はありません) + +そして、それらすべては、これまで見てきた追加のバリデーションとメタデータと同じパラメータを共有しています。 + +/// + +/// note | 技術詳細 + +`fastapi`から`Query`、`Path`などをインポートすると、これらは実際には関数です。 + +呼び出されると、同じ名前のクラスのインスタンスを返します。 + +そのため、関数である`Query`をインポートし、それを呼び出すと、`Query`という名前のクラスのインスタンスが返されます。 + +これらの関数は(クラスを直接使うのではなく)エディタが型についてエラーとしないようにするために存在します。 + +この方法によって、これらのエラーを無視するための設定を追加することなく、通常のエディタやコーディングツールを使用することができます。 + +/// diff --git a/docs/ja/docs/tutorial/path-params.md b/docs/ja/docs/tutorial/path-params.md index 66de05afb..1893ec12f 100644 --- a/docs/ja/docs/tutorial/path-params.md +++ b/docs/ja/docs/tutorial/path-params.md @@ -2,9 +2,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメータ」や「パス変数」を宣言できます: -```Python hl_lines="6 7" -{!../../../docs_src/path_params/tutorial001.py!} -``` +{* ../../docs_src/path_params/tutorial001.py hl[6,7] *} パスパラメータ `item_id` の値は、引数 `item_id` として関数に渡されます。 @@ -18,14 +16,15 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー 標準のPythonの型アノテーションを使用して、関数内のパスパラメータの型を宣言できます: -```Python hl_lines="7" -{!../../../docs_src/path_params/tutorial002.py!} -``` +{* ../../docs_src/path_params/tutorial002.py hl[7] *} ここでは、 `item_id` は `int` として宣言されています。 -!!! check "確認" - これにより、関数内でのエディターサポート (エラーチェックや補完など) が提供されます。 +/// check | 確認 + +これにより、関数内でのエディターサポート (エラーチェックや補完など) が提供されます。 + +/// ## データ変換 @@ -35,10 +34,13 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー {"item_id":3} ``` -!!! check "確認" - 関数が受け取った(および返した)値は、文字列の `"3"` ではなく、Pythonの `int` としての `3` であることに注意してください。 +/// check | 確認 - したがって、型宣言を使用すると、**FastAPI**は自動リクエスト "解析" を行います。 +関数が受け取った(および返した)値は、文字列の `"3"` ではなく、Pythonの `int` としての `3` であることに注意してください。 + +したがって、型宣言を使用すると、**FastAPI**は自動リクエスト "解析" を行います。 + +/// ## データバリデーション @@ -63,12 +65,15 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー http://127.0.0.1:8000/items/4.2 で見られるように、intのかわりに `float` が与えられた場合にも同様なエラーが表示されます。 -!!! check "確認" - したがって、Pythonの型宣言を使用することで、**FastAPI**はデータのバリデーションを行います。 +/// check | 確認 + +したがって、Pythonの型宣言を使用することで、**FastAPI**はデータのバリデーションを行います。 - 表示されたエラーには問題のある箇所が明確に指摘されていることに注意してください。 +表示されたエラーには問題のある箇所が明確に指摘されていることに注意してください。 - これは、APIに関連するコードの開発およびデバッグに非常に役立ちます。 +これは、APIに関連するコードの開発およびデバッグに非常に役立ちます。 + +/// ## ドキュメント @@ -76,10 +81,13 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー -!!! check "確認" - 繰り返しになりますが、Python型宣言を使用するだけで、**FastAPI**は対話的なAPIドキュメントを自動的に生成します(Swagger UIを統合)。 +/// check | 確認 + +繰り返しになりますが、Python型宣言を使用するだけで、**FastAPI**は対話的なAPIドキュメントを自動的に生成します(Swagger UIを統合)。 + +パスパラメータが整数として宣言されていることに注意してください。 - パスパラメータが整数として宣言されていることに注意してください。 +/// ## 標準であることのメリット、ドキュメンテーションの代替物 @@ -93,7 +101,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー ## Pydantic -すべてのデータバリデーションは Pydantic によって内部で実行されるため、Pydanticの全てのメリットが得られます。そして、安心して利用することができます。 +すべてのデータバリデーションは Pydantic によって内部で実行されるため、Pydanticの全てのメリットが得られます。そして、安心して利用することができます。 `str`、 `float` 、 `bool` および他の多くの複雑なデータ型を型宣言に使用できます。 @@ -109,9 +117,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー *path operations* は順に評価されるので、 `/users/me` が `/users/{user_id}` よりも先に宣言されているか確認する必要があります: -```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003.py!} -``` +{* ../../docs_src/path_params/tutorial003.py hl[6,11] *} それ以外の場合、 `/users/{users_id}` は `/users/me` としてもマッチします。値が「"me"」であるパラメータ `user_id` を受け取ると「考え」ます。 @@ -127,23 +133,25 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー そして、固定値のクラス属性を作ります。すると、その値が使用可能な値となります: -```Python hl_lines="1 6 7 8 9" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[1,6,7,8,9] *} + +/// info | 情報 -!!! info "情報" - Enumerations (もしくは、enums)はPython 3.4以降で利用できます。 +Enumerations (もしくは、enums)はPython 3.4以降で利用できます。 -!!! tip "豆知識" - "AlexNet"、"ResNet"そして"LeNet"は機械学習モデルの名前です。 +/// + +/// tip | 豆知識 + +"AlexNet"、"ResNet"そして"LeNet"は機械学習モデルの名前です。 + +/// ### *パスパラメータ*の宣言 次に、作成したenumクラスである`ModelName`を使用した型アノテーションをもつ*パスパラメータ*を作成します: -```Python hl_lines="16" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[16] *} ### ドキュメントの確認 @@ -159,20 +167,19 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー これは、作成した列挙型 `ModelName` の*列挙型メンバ*と比較できます: -```Python hl_lines="17" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[17] *} #### *列挙値*の取得 `model_name.value` 、もしくは一般に、 `your_enum_member.value` を使用して実際の値 (この場合は `str`) を取得できます。 -```Python hl_lines="20" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[20] *} -!!! tip "豆知識" - `ModelName.lenet.value` でも `"lenet"` 値にアクセスできます。 +/// tip | 豆知識 + +`ModelName.lenet.value` でも `"lenet"` 値にアクセスできます。 + +/// #### *列挙型メンバ*の返却 @@ -180,9 +187,7 @@ Pythonのformat文字列と同様のシンタックスで「パスパラメー それらはクライアントに返される前に適切な値 (この場合は文字列) に変換されます。 -```Python hl_lines="18 21 23" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *} クライアントは以下の様なJSONレスポンスを得ます: @@ -221,14 +226,15 @@ Starletteのオプションを直接使用することで、以下のURLの様 したがって、以下の様に使用できます: -```Python hl_lines="6" -{!../../../docs_src/path_params/tutorial004.py!} -``` +{* ../../docs_src/path_params/tutorial004.py hl[6] *} + +/// tip | 豆知識 + +最初のスラッシュ (`/`)が付いている `/home/johndoe/myfile.txt` をパラメータが含んでいる必要があります。 -!!! tip "豆知識" - 最初のスラッシュ (`/`)が付いている `/home/johndoe/myfile.txt` をパラメータが含んでいる必要があります。 +この場合、URLは `files` と `home` の間にダブルスラッシュ (`//`) のある、 `/files//home/johndoe/myfile.txt` になります。 - この場合、URLは `files` と `home` の間にダブルスラッシュ (`//`) のある、 `/files//home/johndoe/myfile.txt` になります。 +/// ## まとめ diff --git a/docs/ja/docs/tutorial/query-param-models.md b/docs/ja/docs/tutorial/query-param-models.md new file mode 100644 index 000000000..053d0740b --- /dev/null +++ b/docs/ja/docs/tutorial/query-param-models.md @@ -0,0 +1,68 @@ +# クエリパラメータモデル + +もし関連する**複数のクエリパラメータ**から成るグループがあるなら、それらを宣言するために、**Pydanticモデル**を作成できます。 + +こうすることで、**複数の場所**で**そのPydanticモデルを再利用**でき、バリデーションやメタデータを、すべてのクエリパラメータに対して一度に宣言できます。😎 + +/// note | 備考 + +この機能は、FastAPIのバージョン `0.115.0` からサポートされています。🤓 + +/// + +## クエリパラメータにPydanticモデルを使用する + +必要な**複数のクエリパラメータ**を**Pydanticモデル**で宣言し、さらに、それを `Query` として宣言しましょう: + +{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *} + +**FastAPI**は、リクエストの**クエリパラメータ**からそれぞれの**フィールド**のデータを**抽出**し、定義された**Pydanticモデル**を提供します。 + +## ドキュメントの確認 + +対話的APIドキュメント `/docs` でクエリパラメータを確認できます: + +
+ +
+ +## 余分なクエリパラメータを禁止する + +特定の(あまり一般的ではないかもしれない)ケースで、受け付けるクエリパラメータを**制限**する必要があるかもしれません。 + +Pydanticのモデルの Configuration を利用して、 `extra` フィールドを `forbid` とすることができます。 + +{* ../../docs_src/query_param_models/tutorial002_an_py310.py hl[10] *} + +もしクライアントが**クエリパラメータ**として**余分な**データを送ろうとすると、**エラー**レスポンスが返されます。 + +例えば、クライアントがクエリパラメータ `tool` に、値 `plumbus` を設定して送ろうとすると: + +```http +https://example.com/items/?limit=10&tool=plumbus +``` + +クエリパラメータ `tool` が許可されていないことを通知する**エラー**レスポンスが返されます。 + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["query", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus" + } + ] +} +``` + +## まとめ + +**FastAPI**では、**クエリパラメータ**を宣言するために、**Pydanticモデル**を使用できます。😎 + +/// tip | 豆知識 + +ネタバレ注意: Pydanticモデルはクッキーやヘッダーの宣言にも使用できますが、その内容については後のチュートリアルで学びます。🤫 + +/// diff --git a/docs/ja/docs/tutorial/query-params-str-validations.md b/docs/ja/docs/tutorial/query-params-str-validations.md index 8d375d7ce..22b89e452 100644 --- a/docs/ja/docs/tutorial/query-params-str-validations.md +++ b/docs/ja/docs/tutorial/query-params-str-validations.md @@ -4,16 +4,18 @@ 以下のアプリケーションを例にしてみましょう: -```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial001.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial001.py hl[9] *} クエリパラメータ `q` は `Optional[str]` 型で、`None` を許容する `str` 型を意味しており、デフォルトは `None` です。そのため、FastAPIはそれが必須ではないと理解します。 -!!! note "備考" - FastAPIは、 `q` はデフォルト値が `=None` であるため、必須ではないと理解します。 +/// note | 備考 + +FastAPIは、 `q` はデフォルト値が `=None` であるため、必須ではないと理解します。 + +`Optional[str]` における `Optional` はFastAPIには利用されませんが、エディターによるより良いサポートとエラー検出を可能にします。 + +/// - `Optional[str]` における `Optional` はFastAPIには利用されませんが、エディターによるより良いサポートとエラー検出を可能にします。 ## バリデーションの追加 `q`はオプショナルですが、もし値が渡されてきた場合には、**50文字を超えないこと**を強制してみましょう。 @@ -22,17 +24,13 @@ そのために、まずは`fastapi`から`Query`をインポートします: -```Python hl_lines="3" -{!../../../docs_src/query_params_str_validations/tutorial002.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[3] *} ## デフォルト値として`Query`を使用 パラメータのデフォルト値として使用し、パラメータ`max_length`を50に設定します: -```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial002.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[9] *} デフォルト値`None`を`Query(default=None)`に置き換える必要があるので、`Query`の最初の引数はデフォルト値を定義するのと同じです。 @@ -50,22 +48,25 @@ q: Optional[str] = None しかし、これはクエリパラメータとして明示的に宣言しています。 -!!! info "情報" - FastAPIは以下の部分を気にすることを覚えておいてください: +/// info | 情報 - ```Python - = None - ``` +FastAPIは以下の部分を気にすることを覚えておいてください: - もしくは: +```Python += None +``` - ```Python - = Query(default=None) - ``` +もしくは: - そして、 `None` を利用することでクエリパラメータが必須ではないと検知します。 +```Python += Query(default=None) +``` + +そして、 `None` を利用することでクエリパラメータが必須ではないと検知します。 - `Optional` の部分は、エディターによるより良いサポートを可能にします。 +`Optional` の部分は、エディターによるより良いサポートを可能にします。 + +/// そして、さらに多くのパラメータを`Query`に渡すことができます。この場合、文字列に適用される、`max_length`パラメータを指定します。 @@ -79,17 +80,13 @@ q: Union[str, None] = Query(default=None, max_length=50) パラメータ`min_length`も追加することができます: -```Python hl_lines="10" -{!../../../docs_src/query_params_str_validations/tutorial003.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial003.py hl[10] *} ## 正規表現の追加 パラメータが一致するべき正規表現を定義することができます: -```Python hl_lines="11" -{!../../../docs_src/query_params_str_validations/tutorial004.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial004.py hl[11] *} この特定の正規表現は受け取ったパラメータの値をチェックします: @@ -107,12 +104,13 @@ q: Union[str, None] = Query(default=None, max_length=50) クエリパラメータ`q`の`min_length`を`3`とし、デフォルト値を`fixedquery`としてみましょう: -```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial005.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial005.py hl[7] *} + +/// note | 備考 + +デフォルト値を指定すると、パラメータは任意になります。 -!!! note "備考" - デフォルト値を指定すると、パラメータは任意になります。 +/// ## 必須にする @@ -136,12 +134,13 @@ q: Union[str, None] = Query(default=None, min_length=3) そのため、`Query`を使用して必須の値を宣言する必要がある場合は、第一引数に`...`を使用することができます: -```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial006.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial006.py hl[7] *} + +/// info | 情報 -!!! info "情報" - これまで`...`を見たことがない方へ: これは特殊な単一値です。Pythonの一部であり、"Ellipsis"と呼ばれています。 +これまで`...`を見たことがない方へ: これは特殊な単一値です。Pythonの一部であり、"Ellipsis"と呼ばれています。 + +/// これは **FastAPI** にこのパラメータが必須であることを知らせます。 @@ -151,9 +150,7 @@ q: Union[str, None] = Query(default=None, min_length=3) 例えば、URL内に複数回出現するクエリパラメータ`q`を宣言するには以下のように書きます: -```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial011.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial011.py hl[9] *} そしてURLは以下です: @@ -174,8 +171,11 @@ http://localhost:8000/items/?q=foo&q=bar } ``` -!!! tip "豆知識" - 上述の例のように、`list`型のクエリパラメータを宣言するには明示的に`Query`を使用する必要があります。そうしない場合、リクエストボディと解釈されます。 +/// tip | 豆知識 + +上述の例のように、`list`型のクエリパラメータを宣言するには明示的に`Query`を使用する必要があります。そうしない場合、リクエストボディと解釈されます。 + +/// 対話的APIドキュメントは複数の値を許可するために自動的に更新されます。 @@ -185,9 +185,7 @@ http://localhost:8000/items/?q=foo&q=bar また、値が指定されていない場合はデフォルトの`list`を定義することもできます。 -```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial012.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial012.py hl[9] *} 以下のURLを開くと: @@ -210,14 +208,15 @@ http://localhost:8000/items/ `List[str]`の代わりに直接`list`を使うこともできます: -```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial013.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial013.py hl[7] *} -!!! note "備考" - この場合、FastAPIはリストの内容をチェックしないことを覚えておいてください。 +/// note | 備考 - 例えば`List[int]`はリストの内容が整数であるかどうかをチェックします(そして、文書化します)。しかし`list`だけではそうしません。 +この場合、FastAPIはリストの内容をチェックしないことを覚えておいてください。 + +例えば`List[int]`はリストの内容が整数であるかどうかをチェックします(そして、文書化します)。しかし`list`だけではそうしません。 + +/// ## より多くのメタデータを宣言する @@ -225,22 +224,21 @@ http://localhost:8000/items/ その情報は、生成されたOpenAPIに含まれ、ドキュメントのユーザーインターフェースや外部のツールで使用されます。 -!!! note "備考" - ツールによってOpenAPIのサポートのレベルが異なる可能性があることを覚えておいてください。 +/// note | 備考 + +ツールによってOpenAPIのサポートのレベルが異なる可能性があることを覚えておいてください。 + +その中には、宣言されたすべての追加情報が表示されていないものもあるかもしれませんが、ほとんどの場合、不足している機能はすでに開発の計画がされています。 - その中には、宣言されたすべての追加情報が表示されていないものもあるかもしれませんが、ほとんどの場合、不足している機能はすでに開発の計画がされています。 +/// `title`を追加できます: -```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial007.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial007.py hl[9] *} `description`を追加できます: -```Python hl_lines="13" -{!../../../docs_src/query_params_str_validations/tutorial008.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial008.py hl[13] *} ## エイリアスパラメータ @@ -260,9 +258,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems それならば、`alias`を宣言することができます。エイリアスはパラメータの値を見つけるのに使用されます: -```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial009.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial009.py hl[9] *} ## 非推奨パラメータ @@ -272,9 +268,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems その場合、`Query`にパラメータ`deprecated=True`を渡します: -```Python hl_lines="18" -{!../../../docs_src/query_params_str_validations/tutorial010.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial010.py hl[18] *} ドキュメントは以下のようになります: diff --git a/docs/ja/docs/tutorial/query-params.md b/docs/ja/docs/tutorial/query-params.md index 5202009ef..74e455579 100644 --- a/docs/ja/docs/tutorial/query-params.md +++ b/docs/ja/docs/tutorial/query-params.md @@ -1,11 +1,8 @@ - # クエリパラメータ パスパラメータではない関数パラメータを宣言すると、それらは自動的に "クエリ" パラメータとして解釈されます。 -```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial001.py!} -``` +{* ../../docs_src/query_params/tutorial001.py hl[9] *} クエリはURL内で `?` の後に続くキーとバリューの組で、 `&` で区切られています。 @@ -64,27 +61,21 @@ http://127.0.0.1:8000/items/?skip=20 同様に、デフォルト値を `None` とすることで、オプショナルなクエリパラメータを宣言できます: -```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial002.py!} -``` +{* ../../docs_src/query_params/tutorial002.py hl[9] *} この場合、関数パラメータ `q` はオプショナルとなり、デフォルトでは `None` になります。 -!!! check "確認" - パスパラメータ `item_id` はパスパラメータであり、`q` はそれとは違ってクエリパラメータであると判別できるほど**FastAPI** が賢いということにも注意してください。 +/// check | 確認 -!!! note "備考" - FastAPIは、`= None`があるおかげで、`q`がオプショナルだとわかります。 +パスパラメータ `item_id` はパスパラメータであり、`q` はそれとは違ってクエリパラメータであると判別できるほど**FastAPI** が賢いということにも注意してください。 - `Optional[str]` の`Optional` はFastAPIでは使用されていません(FastAPIは`str`の部分のみ使用します)。しかし、`Optional[str]` はエディタがコードのエラーを見つけるのを助けてくれます。 +/// ## クエリパラメータの型変換 `bool` 型も宣言できます。これは以下の様に変換されます: -```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial003.py!} -``` +{* ../../docs_src/query_params/tutorial003.py hl[9] *} この場合、以下にアクセスすると: @@ -126,9 +117,7 @@ http://127.0.0.1:8000/items/foo?short=yes 名前で判別されます: -```Python hl_lines="8 10" -{!../../../docs_src/query_params/tutorial004.py!} -``` +{* ../../docs_src/query_params/tutorial004.py hl[8,10] *} ## 必須のクエリパラメータ @@ -138,9 +127,7 @@ http://127.0.0.1:8000/items/foo?short=yes しかしクエリパラメータを必須にしたい場合は、ただデフォルト値を宣言しなければよいです: -```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} -``` +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} ここで、クエリパラメータ `needy` は `str` 型の必須のクエリパラメータです @@ -184,9 +171,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy そして当然、あるパラメータを必須に、別のパラメータにデフォルト値を設定し、また別のパラメータをオプショナルにできます: -```Python hl_lines="10" -{!../../../docs_src/query_params/tutorial006.py!} -``` +{* ../../docs_src/query_params/tutorial006.py hl[10] *} この場合、3つのクエリパラメータがあります。: @@ -194,6 +179,8 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy * `skip`、デフォルト値を `0` とする `int` 。 * `limit`、オプショナルな `int` 。 -!!! tip "豆知識" +/// tip | 豆知識 + +[パスパラメータ](path-params.md#_8){.internal-link target=_blank}と同様に `Enum` を使用できます。 - [パスパラメータ](path-params.md#predefined-values){.internal-link target=_blank}と同様に `Enum` を使用できます。 +/// diff --git a/docs/ja/docs/tutorial/request-forms-and-files.md b/docs/ja/docs/tutorial/request-forms-and-files.md new file mode 100644 index 000000000..110e3106a --- /dev/null +++ b/docs/ja/docs/tutorial/request-forms-and-files.md @@ -0,0 +1,37 @@ +# リクエストフォームとファイル + +`File`と`Form`を同時に使うことでファイルとフォームフィールドを定義することができます。 + +/// info | 情報 + +アップロードされたファイルやフォームデータを受信するには、まず`python-multipart`をインストールします。 + +例えば、`pip install python-multipart`のように。 + +/// + +## `File`と`Form`のインポート + +{* ../../docs_src/request_forms_and_files/tutorial001.py hl[1] *} + +## `File`と`Form`のパラメータの定義 + +ファイルやフォームのパラメータは`Body`や`Query`の場合と同じように作成します: + +{* ../../docs_src/request_forms_and_files/tutorial001.py hl[8] *} + +ファイルとフォームフィールドがフォームデータとしてアップロードされ、ファイルとフォームフィールドを受け取ります。 + +また、いくつかのファイルを`bytes`として、いくつかのファイルを`UploadFile`として宣言することができます。 + +/// warning | 注意 + +*path operation*で複数の`File`と`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストのボディは`application/json`の代わりに`multipart/form-data`を使ってエンコードされているからです。 + +これは **FastAPI** の制限ではなく、HTTPプロトコルの一部です。 + +/// + +## まとめ + +同じリクエストでデータやファイルを受け取る必要がある場合は、`File` と`Form`を一緒に使用します。 diff --git a/docs/ja/docs/tutorial/request-forms.md b/docs/ja/docs/tutorial/request-forms.md index bce6e8d9a..eca2cd6dc 100644 --- a/docs/ja/docs/tutorial/request-forms.md +++ b/docs/ja/docs/tutorial/request-forms.md @@ -2,26 +2,25 @@ JSONの代わりにフィールドを受け取る場合は、`Form`を使用します。 -!!! info "情報" - フォームを使うためには、まず`python-multipart`をインストールします。 +/// info | 情報 - たとえば、`pip install python-multipart`のように。 +フォームを使うためには、まず`python-multipart`をインストールします。 + +たとえば、`pip install python-multipart`のように。 + +/// ## `Form`のインポート `fastapi`から`Form`をインポートします: -```Python hl_lines="1" -{!../../../docs_src/request_forms/tutorial001.py!} -``` +{* ../../docs_src/request_forms/tutorial001.py hl[1] *} ## `Form`のパラメータの定義 `Body`や`Query`の場合と同じようにフォームパラメータを作成します: -```Python hl_lines="7" -{!../../../docs_src/request_forms/tutorial001.py!} -``` +{* ../../docs_src/request_forms/tutorial001.py hl[7] *} 例えば、OAuth2仕様が使用できる方法の1つ(「パスワードフロー」と呼ばれる)では、フォームフィールドとして`username`と`password`を送信する必要があります。 @@ -29,11 +28,17 @@ JSONの代わりにフィールドを受け取る場合は、`Form`を使用し `Form`では`Body`(および`Query`や`Path`、`Cookie`)と同じメタデータとバリデーションを宣言することができます。 -!!! info "情報" - `Form`は`Body`を直接継承するクラスです。 +/// info | 情報 + +`Form`は`Body`を直接継承するクラスです。 + +/// + +/// tip | 豆知識 -!!! tip "豆知識" - フォームのボディを宣言するには、明示的に`Form`を使用する必要があります。なぜなら、これを使わないと、パラメータはクエリパラメータやボディ(JSON)パラメータとして解釈されるからです。 +フォームのボディを宣言するには、明示的に`Form`を使用する必要があります。なぜなら、これを使わないと、パラメータはクエリパラメータやボディ(JSON)パラメータとして解釈されるからです。 + +/// ## 「フォームフィールド」について @@ -41,17 +46,23 @@ HTMLフォーム(`
`)がサーバにデータを送信する方 **FastAPI** は、JSONの代わりにそのデータを適切な場所から読み込むようにします。 -!!! note "技術詳細" - フォームからのデータは通常、`application/x-www-form-urlencoded`の「media type」を使用してエンコードされます。 +/// note | 技術詳細 + +フォームからのデータは通常、`application/x-www-form-urlencoded`の「media type」を使用してエンコードされます。 + +しかし、フォームがファイルを含む場合は、`multipart/form-data`としてエンコードされます。ファイルの扱いについては次の章で説明します。 + +これらのエンコーディングやフォームフィールドの詳細については、MDNPOSTのウェブドキュメントを参照してください。 + +/// - しかし、フォームがファイルを含む場合は、`multipart/form-data`としてエンコードされます。ファイルの扱いについては次の章で説明します。 +/// warning | 注意 - これらのエンコーディングやフォームフィールドの詳細については、MDNPOSTのウェブドキュメントを参照してください。 +*path operation*で複数の`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストは`application/json`の代わりに`application/x-www-form-urlencoded`を使ってボディをエンコードするからです。 -!!! warning "注意" - *path operation*で複数の`Form`パラメータを宣言することができますが、JSONとして受け取ることを期待している`Body`フィールドを宣言することはできません。なぜなら、リクエストは`application/json`の代わりに`application/x-www-form-urlencoded`を使ってボディをエンコードするからです。 +これは **FastAPI**の制限ではなく、HTTPプロトコルの一部です。 - これは **FastAPI**の制限ではなく、HTTPプロトコルの一部です。 +/// ## まとめ diff --git a/docs/ja/docs/tutorial/response-model.md b/docs/ja/docs/tutorial/response-model.md new file mode 100644 index 000000000..b8464a4c7 --- /dev/null +++ b/docs/ja/docs/tutorial/response-model.md @@ -0,0 +1,212 @@ +# レスポンスモデル + +*path operations* のいずれにおいても、`response_model`パラメータを使用して、レスポンスのモデルを宣言することができます: + +* `@app.get()` +* `@app.post()` +* `@app.put()` +* `@app.delete()` +* など。 + +{* ../../docs_src/response_model/tutorial001.py hl[17] *} + +/// note | 備考 + +`response_model`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数* のパラメータではありません。 + +/// + +Pydanticモデルの属性に対して宣言するのと同じ型を受け取るので、Pydanticモデルになることもできますが、例えば、`List[Item]`のようなPydanticモデルの`list`になることもできます。 + +FastAPIは`response_model`を使って以下のことをします: + +* 出力データを型宣言に変換します。 +* データを検証します。 +* OpenAPIの *path operation* で、レスポンス用のJSON Schemaを追加します。 +* 自動ドキュメントシステムで使用されます。 + +しかし、最も重要なのは: + +* 出力データをモデルのデータに限定します。これがどのように重要なのか以下で見ていきましょう。 + +/// note | 技術詳細 + +レスポンスモデルは、関数の戻り値のアノテーションではなく、このパラメータで宣言されています。なぜなら、パス関数は実際にはそのレスポンスモデルを返すのではなく、`dict`やデータベースオブジェクト、あるいは他のモデルを返し、`response_model`を使用してフィールドの制限やシリアライズを行うからです。 + +/// + +## 同じ入力データの返却 + +ここでは`UserIn`モデルを宣言しています。それには平文のパスワードが含まれています: + +{* ../../docs_src/response_model/tutorial002.py hl[9,11] *} + +そして、このモデルを使用して入力を宣言し、同じモデルを使って出力を宣言しています: + +{* ../../docs_src/response_model/tutorial002.py hl[17,18] *} + +これで、ブラウザがパスワードを使ってユーザーを作成する際に、APIがレスポンスで同じパスワードを返すようになりました。 + +この場合、ユーザー自身がパスワードを送信しているので問題ないかもしれません。 + +しかし、同じモデルを別の*path operation*に使用すると、すべてのクライアントにユーザーのパスワードを送信してしまうことになります。 + +/// danger | 危険 + +ユーザーの平文のパスワードを保存したり、レスポンスで送信したりすることは絶対にしないでください。 + +/// + +## 出力モデルの追加 + +代わりに、平文のパスワードを持つ入力モデルと、パスワードを持たない出力モデルを作成することができます: + +{* ../../docs_src/response_model/tutorial003.py hl[9,11,16] *} + +ここでは、*path operation関数*がパスワードを含む同じ入力ユーザーを返しているにもかかわらず: + +{* ../../docs_src/response_model/tutorial003.py hl[24] *} + +...`response_model`を`UserOut`と宣言したことで、パスワードが含まれていません: + +{* ../../docs_src/response_model/tutorial003.py hl[22] *} + +そのため、**FastAPI** は出力モデルで宣言されていない全てのデータをフィルタリングしてくれます(Pydanticを使用)。 + +## ドキュメントを見る + +自動ドキュメントを見ると、入力モデルと出力モデルがそれぞれ独自のJSON Schemaを持っていることが確認できます。 + + + +そして、両方のモデルは、対話型のAPIドキュメントに使用されます: + + + +## レスポンスモデルのエンコーディングパラメータ + +レスポンスモデルにはデフォルト値を設定することができます: + +{* ../../docs_src/response_model/tutorial004.py hl[11,13,14] *} + +* `description: str = None`は`None`がデフォルト値です。 +* `tax: float = 10.5`は`10.5`がデフォルト値です。 +* `tags: List[str] = []` は空のリスト(`[]`)がデフォルト値です。 + +しかし、実際に保存されていない場合には結果からそれらを省略した方が良いかもしれません。 + +例えば、NoSQLデータベースに多くのオプション属性を持つモデルがあるが、デフォルト値でいっぱいの非常に長いJSONレスポンスを送信したくない場合です。 + +### `response_model_exclude_unset`パラメータの使用 + +*path operation デコレータ*に`response_model_exclude_unset=True`パラメータを設定することができます: + +{* ../../docs_src/response_model/tutorial004.py hl[24] *} + +そして、これらのデフォルト値はレスポンスに含まれず、実際に設定された値のみが含まれます。 + +そのため、*path operation*にID`foo`が設定されたitemのリクエストを送ると、レスポンスは以下のようになります(デフォルト値を含まない): + +```JSON +{ + "name": "Foo", + "price": 50.2 +} +``` + +/// info | 情報 + +FastAPIはこれをするために、Pydanticモデルの`.dict()`をその`exclude_unset`パラメータで使用しています。 + +/// + +/// info | 情報 + +以下も使用することができます: + +* `response_model_exclude_defaults=True` +* `response_model_exclude_none=True` + +`exclude_defaults`と`exclude_none`については、Pydanticのドキュメントで説明されている通りです。 + +/// + +#### デフォルト値を持つフィールドの値を持つデータ + +しかし、ID`bar`のitemのように、デフォルト値が設定されているモデルのフィールドに値が設定されている場合: + +```Python hl_lines="3 5" +{ + "name": "Bar", + "description": "The bartenders", + "price": 62, + "tax": 20.2 +} +``` + +それらはレスポンスに含まれます。 + +#### デフォルト値と同じ値を持つデータ + +ID`baz`のitemのようにデフォルト値と同じ値を持つデータの場合: + +```Python hl_lines="3 5 6" +{ + "name": "Baz", + "description": None, + "price": 50.2, + "tax": 10.5, + "tags": [] +} +``` + +FastAPIは十分に賢いので(実際には、Pydanticが十分に賢い)`description`や`tax`、`tags`はデフォルト値と同じ値を持っているにもかかわらず、明示的に設定されていることを理解しています。(デフォルトから取得するのではなく) + +そのため、それらはJSONレスポンスに含まれることになります。 + +/// tip | 豆知識 + +デフォルト値は`None`だけでなく、なんでも良いことに注意してください。 +例えば、リスト(`[]`)や`10.5`の`float`などです。 + +/// + +### `response_model_include`と`response_model_exclude` + +*path operationデコレータ*として`response_model_include`と`response_model_exclude`も使用することができます。 + +属性名を持つ`str`の`set`を受け取り、含める(残りを省略する)か、除外(残りを含む)します。 + +これは、Pydanticモデルが1つしかなく、出力からいくつかのデータを削除したい場合のクイックショートカットとして使用することができます。 + +/// tip | 豆知識 + +それでも、これらのパラメータではなく、複数のクラスを使用して、上記のようなアイデアを使うことをおすすめします。 + +これは`response_model_include`や`response_mode_exclude`を使用していくつかの属性を省略しても、アプリケーションのOpenAPI(とドキュメント)で生成されたJSON Schemaが完全なモデルになるからです。 + +同様に動作する`response_model_by_alias`にも当てはまります。 + +/// + +{* ../../docs_src/response_model/tutorial005.py hl[31,37] *} + +/// tip | 豆知識 + +`{"name", "description"}`の構文はこれら2つの値をもつ`set`を作成します。 + +これは`set(["name", "description"])`と同等です。 + +/// + +#### `set`の代わりに`list`を使用する + +もし`set`を使用することを忘れて、代わりに`list`や`tuple`を使用しても、FastAPIはそれを`set`に変換して正しく動作します: + +{* ../../docs_src/response_model/tutorial006.py hl[31,37] *} + +## まとめ + +*path operationデコレータの*`response_model`パラメータを使用して、レスポンスモデルを定義し、特にプライベートデータがフィルタリングされていることを保証します。 + +明示的に設定された値のみを返すには、`response_model_exclude_unset`を使用します。 diff --git a/docs/ja/docs/tutorial/response-status-code.md b/docs/ja/docs/tutorial/response-status-code.md new file mode 100644 index 000000000..6d197d543 --- /dev/null +++ b/docs/ja/docs/tutorial/response-status-code.md @@ -0,0 +1,101 @@ +# レスポンスステータスコード + +レスポンスモデルを指定するのと同じ方法で、レスポンスに使用されるHTTPステータスコードを以下の*path operations*のいずれかの`status_code`パラメータで宣言することもできます。 + +* `@app.get()` +* `@app.post()` +* `@app.put()` +* `@app.delete()` +* など。 + +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} + +/// note | 備考 + +`status_code`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数*のものではありません。 + +/// + +`status_code`パラメータはHTTPステータスコードを含む数値を受け取ります。 + +/// info | 情報 + +`status_code`は代わりに、Pythonの`http.HTTPStatus`のように、`IntEnum`を受け取ることもできます。 + +/// + +これは: + +* レスポンスでステータスコードを返します。 +* OpenAPIスキーマ(およびユーザーインターフェース)に以下のように文書化します: + + + +/// note | 備考 + +いくつかのレスポンスコード(次のセクションを参照)は、レスポンスにボディがないことを示しています。 + +FastAPIはこれを知っていて、レスポンスボディがないというOpenAPIドキュメントを生成します。 + +/// + +## HTTPステータスコードについて + +/// note | 備考 + +すでにHTTPステータスコードが何であるかを知っている場合は、次のセクションにスキップしてください。 + +/// + +HTTPでは、レスポンスの一部として3桁の数字のステータスコードを送信します。 + +これらのステータスコードは、それらを認識するために関連付けられた名前を持っていますが、重要な部分は番号です。 + +つまり: + +* `100`以上は「情報」のためのものです。。直接使うことはほとんどありません。これらのステータスコードを持つレスポンスはボディを持つことができません。 +* **`200`** 以上は「成功」のレスポンスのためのものです。これらは最も利用するであろうものです。 + * `200`はデフォルトのステータスコードで、すべてが「OK」であったことを意味します。 + * 別の例としては、`201`(Created)があります。これはデータベースに新しいレコードを作成した後によく使用されます。 + * 特殊なケースとして、`204`(No Content)があります。このレスポンスはクライアントに返すコンテンツがない場合に使用されます。そしてこのレスポンスはボディを持つことはできません。 +* **`300`** 以上は「リダイレクト」のためのものです。これらのステータスコードを持つレスポンスは`304`(Not Modified)を除き、ボディを持つことも持たないこともできます。 +* **`400`** 以上は「クライアントエラー」のレスポンスのためのものです。これらは、おそらく最も多用するであろう2番目のタイプです。 + * 例えば、`404`は「Not Found」レスポンスです。 + * クライアントからの一般的なエラーについては、`400`を使用することができます。 +* `500`以上はサーバーエラーのためのものです。これらを直接使うことはほとんどありません。アプリケーションコードやサーバーのどこかで何か問題が発生した場合、これらのステータスコードのいずれかが自動的に返されます。 + +/// tip | 豆知識 + +それぞれのステータスコードとどのコードが何のためのコードなのかについて詳細はMDN HTTP レスポンスステータスコードについてのドキュメントを参照してください。 + +/// + +## 名前を覚えるための近道 + +先ほどの例をもう一度見てみましょう: + +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} + +`201`は「作成完了」のためのステータスコードです。 + +しかし、それぞれのコードの意味を暗記する必要はありません。 + +`fastapi.status`の便利な変数を利用することができます。 + +{* ../../docs_src/response_status_code/tutorial002.py hl[1,6] *} + +それらは便利です。それらは同じ番号を保持しており、その方法ではエディタの自動補完を使用してそれらを見つけることができます。 + + + +/// note | 技術詳細 + +また、`from starlette import status`を使うこともできます。 + +**FastAPI** は、`開発者の利便性を考慮して、fastapi.status`と同じ`starlette.status`を提供しています。しかし、これはStarletteから直接提供されています。 + +/// + +## デフォルトの変更 + +後に、[高度なユーザーガイド](../advanced/response-change-status-code.md){.internal-link target=_blank}で、ここで宣言しているデフォルトとは異なるステータスコードを返す方法を見ていきます。 diff --git a/docs/ja/docs/tutorial/schema-extra-example.md b/docs/ja/docs/tutorial/schema-extra-example.md new file mode 100644 index 000000000..1834e67b2 --- /dev/null +++ b/docs/ja/docs/tutorial/schema-extra-example.md @@ -0,0 +1,55 @@ +# スキーマの追加 - 例 + +JSON Schemaに追加する情報を定義することができます。 + +一般的なユースケースはこのドキュメントで示されているように`example`を追加することです。 + +JSON Schemaの追加情報を宣言する方法はいくつかあります。 + +## Pydanticの`schema_extra` + +Pydanticのドキュメント: スキーマのカスタマイズで説明されているように、`Config`と`schema_extra`を使ってPydanticモデルの例を宣言することができます: + +{* ../../docs_src/schema_extra_example/tutorial001.py hl[15,16,17,18,19,20,21,22,23] *} + +その追加情報はそのまま出力され、JSON Schemaに追加されます。 + +## `Field`の追加引数 + +後述する`Field`、`Path`、`Query`、`Body`などでは、任意の引数を関数に渡すことでJSON Schemaの追加情報を宣言することもできます: + +{* ../../docs_src/schema_extra_example/tutorial002.py hl[4,10,11,12,13] *} + +/// warning | 注意 + +これらの追加引数が渡されても、文書化のためのバリデーションは追加されず、注釈だけが追加されることを覚えておいてください。 + +/// + +## `Body`の追加引数 + +追加情報を`Field`に渡すのと同じように、`Path`、`Query`、`Body`などでも同じことができます。 + +例えば、`Body`にボディリクエストの`example`を渡すことができます: + +{* ../../docs_src/schema_extra_example/tutorial003.py hl[21,22,23,24,25,26] *} + +## ドキュメントのUIの例 + +上記のいずれの方法でも、`/docs`の中では以下のようになります: + + + +## 技術詳細 + +`example` と `examples`について... + +JSON Schemaの最新バージョンでは`examples`というフィールドを定義していますが、OpenAPIは`examples`を持たない古いバージョンのJSON Schemaをベースにしています。 + +そのため、OpenAPIでは同じ目的のために`example`を独自に定義しており(`examples`ではなく`example`として)、それがdocs UI(Swagger UIを使用)で使用されています。 + +つまり、`example`はJSON Schemaの一部ではありませんが、OpenAPIの一部であり、それがdocs UIで使用されることになります。 + +## その他の情報 + +同じように、フロントエンドのユーザーインターフェースなどをカスタマイズするために、各モデルのJSON Schemaに追加される独自の追加情報を追加することができます。 diff --git a/docs/ja/docs/tutorial/security/first-steps.md b/docs/ja/docs/tutorial/security/first-steps.md index f83b59cfd..0ce0f929b 100644 --- a/docs/ja/docs/tutorial/security/first-steps.md +++ b/docs/ja/docs/tutorial/security/first-steps.md @@ -20,18 +20,19 @@ `main.py`に、下記の例をコピーします: -```Python -{!../../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py *} ## 実行 -!!! info "情報" - まず`python-multipart`をインストールします。 +/// info | 情報 + +まず`python-multipart`をインストールします。 - 例えば、`pip install python-multipart`。 +例えば、`pip install python-multipart`。 - これは、**OAuth2**が `ユーザー名` や `パスワード` を送信するために、「フォームデータ」を使うからです。 +これは、**OAuth2**が `ユーザー名` や `パスワード` を送信するために、「フォームデータ」を使うからです。 + +/// 例を実行します: @@ -53,17 +54,23 @@ $ uvicorn main:app --reload -!!! check "Authorizeボタン!" - すでにピカピカの新しい「Authorize」ボタンがあります。 +/// check | Authorizeボタン! + +すでにピカピカの新しい「Authorize」ボタンがあります。 - そして、あなたの*path operation*には、右上にクリックできる小さな鍵アイコンがあります。 +そして、あなたの*path operation*には、右上にクリックできる小さな鍵アイコンがあります。 + +/// それをクリックすると、`ユーザー名`と`パスワード` (およびその他のオプションフィールド) を入力する小さな認証フォームが表示されます: -!!! note "備考" - フォームに何を入力しても、まだうまくいきません。ですが、これから動くようになります。 +/// note | 備考 + +フォームに何を入力しても、まだうまくいきません。ですが、これから動くようになります。 + +/// もちろんエンドユーザーのためのフロントエンドではありません。しかし、すべてのAPIをインタラクティブにドキュメント化するための素晴らしい自動ツールです。 @@ -105,36 +112,43 @@ OAuth2は、バックエンドやAPIがユーザーを認証するサーバー この例では、**Bearer**トークンを使用して**OAuth2**を**パスワード**フローで使用します。これには`OAuth2PasswordBearer`クラスを使用します。 -!!! info "情報" - 「bearer」トークンが、唯一の選択肢ではありません。 +/// info | 情報 + +「bearer」トークンが、唯一の選択肢ではありません。 - しかし、私たちのユースケースには最適です。 +しかし、私たちのユースケースには最適です。 - あなたがOAuth2の専門家で、あなたのニーズに適した別のオプションがある理由を正確に知っている場合を除き、ほとんどのユースケースに最適かもしれません。 +あなたがOAuth2の専門家で、あなたのニーズに適した別のオプションがある理由を正確に知っている場合を除き、ほとんどのユースケースに最適かもしれません。 - その場合、**FastAPI**はそれを構築するためのツールも提供します。 +その場合、**FastAPI**はそれを構築するためのツールも提供します。 + +/// `OAuth2PasswordBearer` クラスのインスタンスを作成する時に、パラメーター`tokenUrl`を渡します。このパラメーターには、クライアント (ユーザーのブラウザで動作するフロントエンド) がトークンを取得するために`ユーザー名`と`パスワード`を送信するURLを指定します。 -```Python hl_lines="6" -{!../../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[6] *} + +/// tip | 豆知識 -!!! tip "豆知識" - ここで、`tokenUrl="token"`は、まだ作成していない相対URL`token`を指します。相対URLなので、`./token`と同じです。 +ここで、`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を使っているので、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 を使うことは、[プロキシと接続](../../advanced/behind-a-proxy.md){.internal-link target=_blank}のような高度なユースケースでもアプリケーションを動作させ続けるために重要です。 + +/// このパラメーターはエンドポイント/ *path operation*を作成しません。しかし、URL`/token`はクライアントがトークンを取得するために使用するものであると宣言します。この情報は OpenAPI やインタラクティブな API ドキュメントシステムで使われます。 実際のpath operationもすぐに作ります。 -!!! info "情報" - 非常に厳格な「Pythonista」であれば、パラメーター名のスタイルが`token_url`ではなく`tokenUrl`であることを気に入らないかもしれません。 +/// info | 情報 + +非常に厳格な「Pythonista」であれば、パラメーター名のスタイルが`token_url`ではなく`tokenUrl`であることを気に入らないかもしれません。 - それはOpenAPI仕様と同じ名前を使用しているからです。そのため、これらのセキュリティスキームについてもっと調べる必要がある場合は、それをコピーして貼り付ければ、それについての詳細な情報を見つけることができます。 +それはOpenAPI仕様と同じ名前を使用しているからです。そのため、これらのセキュリティスキームについてもっと調べる必要がある場合は、それをコピーして貼り付ければ、それについての詳細な情報を見つけることができます。 + +/// 変数`oauth2_scheme`は`OAuth2PasswordBearer`のインスタンスですが、「呼び出し可能」です。 @@ -150,18 +164,19 @@ oauth2_scheme(some, parameters) これで`oauth2_scheme`を`Depends`で依存関係に渡すことができます。 -```Python hl_lines="10" -{!../../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[10] *} この依存関係は、*path operation function*のパラメーター`token`に代入される`str`を提供します。 **FastAPI**は、この依存関係を使用してOpenAPIスキーマ (および自動APIドキュメント) で「セキュリティスキーム」を定義できることを知っています。 -!!! info "技術詳細" - **FastAPI**は、`OAuth2PasswordBearer` クラス (依存関係で宣言されている) を使用してOpenAPIのセキュリティスキームを定義できることを知っています。これは`fastapi.security.oauth2.OAuth2`、`fastapi.security.base.SecurityBase`を継承しているからです。 +/// info | 技術詳細 + +**FastAPI**は、`OAuth2PasswordBearer` クラス (依存関係で宣言されている) を使用してOpenAPIのセキュリティスキームを定義できることを知っています。これは`fastapi.security.oauth2.OAuth2`、`fastapi.security.base.SecurityBase`を継承しているからです。 + +OpenAPIと統合するセキュリティユーティリティ (および自動APIドキュメント) はすべて`SecurityBase`を継承しています。それにより、**FastAPI**はそれらをOpenAPIに統合する方法を知ることができます。 - OpenAPIと統合するセキュリティユーティリティ (および自動APIドキュメント) はすべて`SecurityBase`を継承しています。それにより、**FastAPI**はそれらをOpenAPIに統合する方法を知ることができます。 +/// ## どのように動作するか diff --git a/docs/ja/docs/tutorial/security/get-current-user.md b/docs/ja/docs/tutorial/security/get-current-user.md new file mode 100644 index 000000000..9fc46c07c --- /dev/null +++ b/docs/ja/docs/tutorial/security/get-current-user.md @@ -0,0 +1,106 @@ +# 現在のユーザーの取得 + +一つ前の章では、(依存性注入システムに基づいた)セキュリティシステムは、 *path operation関数* に `str` として `token` を与えていました: + +{* ../../docs_src/security/tutorial001.py hl[10] *} + +しかし、それはまだそんなに有用ではありません。 + +現在のユーザーを取得するようにしてみましょう。 + +## ユーザーモデルの作成 + +まずは、Pydanticのユーザーモデルを作成しましょう。 + +ボディを宣言するのにPydanticを使用するのと同じやり方で、Pydanticを別のどんなところでも使うことができます: + +{* ../../docs_src/security/tutorial002.py hl[5,12:16] *} + +## 依存関係 `get_current_user` を作成 + +依存関係 `get_current_user` を作ってみましょう。 + +依存関係はサブ依存関係を持つことができるのを覚えていますか? + +`get_current_user` は前に作成した `oauth2_scheme` と同じ依存関係を持ちます。 + +以前直接 *path operation* の中でしていたのと同じように、新しい依存関係である `get_current_user` は `str` として `token` を受け取るようになります: + +{* ../../docs_src/security/tutorial002.py hl[25] *} + +## ユーザーの取得 + +`get_current_user` は作成した(偽物の)ユーティリティ関数を使って、 `str` としてトークンを受け取り、先ほどのPydanticの `User` モデルを返却します: + +{* ../../docs_src/security/tutorial002.py hl[19:22,26:27] *} + +## 現在のユーザーの注入 + +ですので、 `get_current_user` に対して同様に *path operation* の中で `Depends` を利用できます。 + +{* ../../docs_src/security/tutorial002.py hl[31] *} + +Pydanticモデルの `User` として、 `current_user` の型を宣言することに注意してください。 + +その関数の中ですべての入力補完や型チェックを行う際に役に立ちます。 + +/// tip | 豆知識 + +リクエストボディはPydanticモデルでも宣言できることを覚えているかもしれません。 + +ここでは `Depends` を使っているおかげで、 **FastAPI** が混乱することはありません。 + +/// + +/// check | 確認 + +依存関係システムがこのように設計されているおかげで、 `User` モデルを返却する別の依存関係(別の"dependables")を持つことができます。 + +同じデータ型を返却する依存関係は一つだけしか持てない、という制約が入ることはないのです。 + +/// + +## 別のモデル + +これで、*path operation関数* の中で現在のユーザーを直接取得し、`Depends` を使って、 **依存性注入** レベルでセキュリティメカニズムを処理できるようになりました。 + +そして、セキュリティ要件のためにどんなモデルやデータでも利用することができます。(この場合は、 Pydanticモデルの `User`) + +しかし、特定のデータモデルやクラス、型に制限されることはありません。 + +モデルを、 `id` と `email` は持つが、 `username` は全く持たないようにしたいですか? わかりました。同じ手段でこうしたこともできます。 + +ある `str` だけを持ちたい? あるいはある `dict` だけですか? それとも、データベースクラスのモデルインスタンスを直接持ちたいですか? すべて同じやり方で機能します。 + +実際には、あなたのアプリケーションにはログインするようなユーザーはおらず、単にアクセストークンを持つロボットやボット、別のシステムがありますか?ここでも、全く同じようにすべて機能します。 + +あなたのアプリケーションに必要なのがどんな種類のモデル、どんな種類のクラス、どんな種類のデータベースであったとしても、 **FastAPI** は依存性注入システムでカバーしてくれます。 + + +## コードサイズ + +この例は冗長に見えるかもしれません。セキュリティとデータモデルユーティリティ関数および *path operations* が同じファイルに混在しているということを覚えておいてください。 + +しかし、ここに重要なポイントがあります。 + +セキュリティと依存性注入に関するものは、一度だけ書きます。 + +そして、それは好きなだけ複雑にすることができます。それでも、一箇所に、一度だけ書くのです。すべての柔軟性を備えます。 + +しかし、同じセキュリティシステムを使って何千ものエンドポイント(*path operations*)を持つことができます。 + +そして、それらエンドポイントのすべて(必要な、どの部分でも)がこうした依存関係や、あなたが作成する別の依存関係を再利用する利点を享受できるのです。 + +さらに、こうした何千もの *path operations* は、たった3行で表現できるのです: + +{* ../../docs_src/security/tutorial002.py hl[30:32] *} + +## まとめ + +これで、 *path operation関数* の中で直接現在のユーザーを取得できるようになりました。 + +既に半分のところまで来ています。 + +あとは、 `username` と `password` を実際にそのユーザーやクライアントに送る、 *path operation* を追加する必要があるだけです。 + +次はそれを説明します。 diff --git a/docs/ja/docs/tutorial/security/index.md b/docs/ja/docs/tutorial/security/index.md new file mode 100644 index 000000000..37b8bb958 --- /dev/null +++ b/docs/ja/docs/tutorial/security/index.md @@ -0,0 +1,106 @@ +# セキュリティ入門 + +セキュリティ、認証、認可を扱うには多くの方法があります。 + +そして、通常、それは複雑で「難しい」トピックです。 + +多くのフレームワークやシステムでは、セキュリティと認証を処理するだけで、膨大な労力とコードが必要になります(多くの場合、書かれた全コードの50%以上を占めることがあります)。 + +**FastAPI** は、セキュリティの仕様をすべて勉強して学ぶことなく、標準的な方法で簡単に、迅速に**セキュリティ**を扱うためのツールをいくつか提供します。 + +しかし、その前に、いくつかの小さな概念を確認しましょう。 + +## お急ぎですか? + +もし、これらの用語に興味がなく、ユーザー名とパスワードに基づく認証でセキュリティを**今すぐ**確保する必要がある場合は、次の章に進んでください。 + +## OAuth2 + +OAuth2は、認証と認可を処理するためのいくつかの方法を定義した仕様です。 + +かなり広範囲な仕様で、いくつかの複雑なユースケースをカバーしています。 + +これには「サードパーティ」を使用して認証する方法が含まれています。 + +これが、「Facebook、Google、Twitter、GitHubを使ってログイン」を使用したすべてのシステムの背後で使われている仕組みです。 + +### OAuth 1 + +OAuth 1というものもありましたが、これはOAuth2とは全く異なり、通信をどのように暗号化するかという仕様が直接的に含まれており、より複雑なものとなっています。 + +現在ではあまり普及していませんし、使われてもいません。 + +OAuth2は、通信を暗号化する方法を指定せず、アプリケーションがHTTPSで提供されることを想定しています。 + +/// tip | 豆知識 + +**デプロイ**のセクションでは、TraefikとLet's Encryptを使用して、無料でHTTPSを設定する方法が紹介されています。 + +/// + +## OpenID Connect + +OpenID Connectは、**OAuth2**をベースにした別の仕様です。 + +これはOAuth2を拡張したもので、OAuth2ではやや曖昧だった部分を明確にし、より相互運用性を高めようとしたものです。 + +例として、GoogleのログインはOpenID Connectを使用しています(これはOAuth2がベースになっています)。 + +しかし、FacebookのログインはOpenID Connectをサポートしていません。OAuth2を独自にアレンジしています。 + +### OpenID (「OpenID Connect」ではない) + +また、「OpenID」という仕様もありました。それは、**OpenID Connect**と同じことを解決しようとしたものですが、OAuth2に基づいているわけではありませんでした。 + +つまり、完全な追加システムだったのです。 + +現在ではあまり普及していませんし、使われてもいません。 + +## OpenAPI + +OpenAPI(以前はSwaggerとして知られていました)は、APIを構築するためのオープンな仕様です(現在はLinux Foundationの一部になっています)。 + +**FastAPI**は、**OpenAPI**をベースにしています。 + +それが、複数の自動対話型ドキュメント・インターフェースやコード生成などを可能にしているのです。 + +OpenAPIには、複数のセキュリティ「スキーム」を定義する方法があります。 + +それらを使用することで、これらの対話型ドキュメントシステムを含む、標準ベースのツールをすべて活用できます。 + +OpenAPIでは、以下のセキュリティスキームを定義しています: + +* `apiKey`: アプリケーション固有のキーで、これらのものから取得できます。 + * クエリパラメータ + * ヘッダー + * クッキー +* `http`: 標準的なHTTP認証システムで、これらのものを含みます。 + * `bearer`: ヘッダ `Authorization` の値が `Bearer ` で、トークンが含まれます。これはOAuth2から継承しています。 + * HTTP Basic認証 + * HTTP ダイジェスト認証など +* `oauth2`: OAuth2のセキュリティ処理方法(「フロー」と呼ばれます)のすべて。 + * これらのフローのいくつかは、OAuth 2.0認証プロバイダ(Google、Facebook、Twitter、GitHubなど)を構築するのに適しています。 + * `implicit` + * `clientCredentials` + * `authorizationCode` + * しかし、同じアプリケーション内で認証を直接処理するために完全に機能する特定の「フロー」があります。 + * `password`: 次のいくつかの章では、その例を紹介します。 +* `openIdConnect`: OAuth2認証データを自動的に発見する方法を定義できます。 + * この自動検出メカニズムは、OpenID Connectの仕様で定義されているものです。 + + +/// tip | 豆知識 + +Google、Facebook、Twitter、GitHubなど、他の認証/認可プロバイダを統合することも可能で、比較的簡単です。 + +最も複雑な問題は、それらのような認証/認可プロバイダを構築することですが、**FastAPI**は、あなたのために重い仕事をこなしながら、それを簡単に行うためのツールを提供します。 + +/// + +## **FastAPI** ユーティリティ + +FastAPIは `fastapi.security` モジュールの中で、これらのセキュリティスキームごとにいくつかのツールを提供し、これらのセキュリティメカニズムを簡単に使用できるようにします。 + +次の章では、**FastAPI** が提供するこれらのツールを使って、あなたのAPIにセキュリティを追加する方法について見ていきます。 + +また、それがどのようにインタラクティブなドキュメントシステムに自動的に統合されるかも見ていきます。 diff --git a/docs/ja/docs/tutorial/security/oauth2-jwt.md b/docs/ja/docs/tutorial/security/oauth2-jwt.md index d5b179aa0..4859819cc 100644 --- a/docs/ja/docs/tutorial/security/oauth2-jwt.md +++ b/docs/ja/docs/tutorial/security/oauth2-jwt.md @@ -44,10 +44,13 @@ $ pip install python-jose[cryptography] ここでは、推奨されているものを使用します:pyca/cryptography。 -!!! tip "豆知識" - このチュートリアルでは以前、PyJWTを使用していました。 +/// tip | 豆知識 - しかし、Python-joseは、PyJWTのすべての機能に加えて、後に他のツールと統合して構築する際におそらく必要となる可能性のあるいくつかの追加機能を提供しています。そのため、代わりにPython-joseを使用するように更新されました。 +このチュートリアルでは以前、PyJWTを使用していました。 + +しかし、Python-joseは、PyJWTのすべての機能に加えて、後に他のツールと統合して構築する際におそらく必要となる可能性のあるいくつかの追加機能を提供しています。そのため、代わりにPython-joseを使用するように更新されました。 + +/// ## パスワードのハッシュ化 @@ -83,13 +86,15 @@ $ pip install passlib[bcrypt] -!!! tip "豆知識" - `passlib`を使用すると、**Django**や**Flask**のセキュリティプラグインなどで作成されたパスワードを読み取れるように設定できます。 +/// tip | 豆知識 - 例えば、Djangoアプリケーションからデータベース内の同じデータをFastAPIアプリケーションと共有できるだけではなく、同じデータベースを使用してDjangoアプリケーションを徐々に移行することもできます。 +`passlib`を使用すると、**Django**や**Flask**のセキュリティプラグインなどで作成されたパスワードを読み取れるように設定できます。 - また、ユーザーはDjangoアプリまたは**FastAPI**アプリからも、同時にログインできるようになります。 +例えば、Djangoアプリケーションからデータベース内の同じデータをFastAPIアプリケーションと共有できるだけではなく、同じデータベースを使用してDjangoアプリケーションを徐々に移行することもできます。 +また、ユーザーはDjangoアプリまたは**FastAPI**アプリからも、同時にログインできるようになります。 + +/// ## パスワードのハッシュ化と検証 @@ -97,12 +102,15 @@ $ pip install passlib[bcrypt] PassLib の「context」を作成します。これは、パスワードのハッシュ化と検証に使用されるものです。 -!!! tip "豆知識" - PassLibのcontextには、検証だけが許された非推奨の古いハッシュアルゴリズムを含む、様々なハッシュアルゴリズムを使用した検証機能もあります。 +/// tip | 豆知識 + +PassLibのcontextには、検証だけが許された非推奨の古いハッシュアルゴリズムを含む、様々なハッシュアルゴリズムを使用した検証機能もあります。 - 例えば、この機能を使用して、別のシステム(Djangoなど)によって生成されたパスワードを読み取って検証し、Bcryptなどの別のアルゴリズムを使用して新しいパスワードをハッシュするといったことができます。 +例えば、この機能を使用して、別のシステム(Djangoなど)によって生成されたパスワードを読み取って検証し、Bcryptなどの別のアルゴリズムを使用して新しいパスワードをハッシュするといったことができます。 - そして、同時にそれらはすべてに互換性があります。 +そして、同時にそれらはすべてに互換性があります。 + +/// ユーザーから送られてきたパスワードをハッシュ化するユーティリティー関数を作成します。 @@ -110,12 +118,13 @@ PassLib の「context」を作成します。これは、パスワードのハ さらに、ユーザーを認証して返す関数も作成します。 -```Python hl_lines="7 48 55-56 59-60 69-75" -{!../../../docs_src/security/tutorial004.py!} -``` +{* ../../docs_src/security/tutorial004.py hl[7,48,55:56,59:60,69:75] *} + +/// note | 備考 + +新しい(偽の)データベース`fake_users_db`を確認すると、ハッシュ化されたパスワードが次のようになっていることがわかります:`"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"` -!!! note "備考" - 新しい(偽の)データベース`fake_users_db`を確認すると、ハッシュ化されたパスワードが次のようになっていることがわかります:`"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"` +/// ## JWTトークンの取り扱い @@ -145,9 +154,7 @@ JWTトークンの署名に使用するアルゴリズム`"HS256"`を指定し 新しいアクセストークンを生成するユーティリティ関数を作成します。 -```Python hl_lines="6 12-14 28-30 78-86" -{!../../../docs_src/security/tutorial004.py!} -``` +{* ../../docs_src/security/tutorial004.py hl[6,12:14,28:30,78:86] *} ## 依存関係の更新 @@ -157,9 +164,7 @@ JWTトークンの署名に使用するアルゴリズム`"HS256"`を指定し トークンが無効な場合は、すぐにHTTPエラーを返します。 -```Python hl_lines="89-106" -{!../../../docs_src/security/tutorial004.py!} -``` +{* ../../docs_src/security/tutorial004.py hl[89:106] *} ## `/token` パスオペレーションの更新 @@ -167,9 +172,7 @@ JWTトークンの署名に使用するアルゴリズム`"HS256"`を指定し JWTアクセストークンを作成し、それを返します。 -```Python hl_lines="115-130" -{!../../../docs_src/security/tutorial004.py!} -``` +{* ../../docs_src/security/tutorial004.py hl[115:130] *} ### JWTの"subject" `sub` についての技術的な詳細 @@ -208,8 +211,11 @@ IDの衝突を回避するために、ユーザーのJWTトークンを作成す Username: `johndoe` Password: `secret` -!!! check "確認" - コードのどこにも平文のパスワード"`secret`"はなく、ハッシュ化されたものしかないことを確認してください。 +/// check | 確認 + +コードのどこにも平文のパスワード"`secret`"はなく、ハッシュ化されたものしかないことを確認してください。 + +/// @@ -230,8 +236,11 @@ Password: `secret` -!!! note "備考" - ヘッダーの`Authorization`には、`Bearer`で始まる値があります。 +/// note | 備考 + +ヘッダーの`Authorization`には、`Bearer`で始まる値があります。 + +/// ## `scopes` を使った高度なユースケース diff --git a/docs/ja/docs/tutorial/static-files.md b/docs/ja/docs/tutorial/static-files.md index 1d9c434c3..f63f3f3b1 100644 --- a/docs/ja/docs/tutorial/static-files.md +++ b/docs/ja/docs/tutorial/static-files.md @@ -7,14 +7,15 @@ * `StaticFiles` をインポート。 * `StaticFiles()` インスタンスを生成し、特定のパスに「マウント」。 -```Python hl_lines="2 6" -{!../../../docs_src/static_files/tutorial001.py!} -``` +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} -!!! note "技術詳細" - `from starlette.staticfiles import StaticFiles` も使用できます。 +/// note | 技術詳細 - **FastAPI**は、開発者の利便性のために、`starlette.staticfiles` と同じ `fastapi.staticfiles` を提供します。しかし、実際にはStarletteから直接渡されています。 +`from starlette.staticfiles import StaticFiles` も使用できます。 + +**FastAPI**は、開発者の利便性のために、`starlette.staticfiles` と同じ `fastapi.staticfiles` を提供します。しかし、実際にはStarletteから直接渡されています。 + +/// ### 「マウント」とは diff --git a/docs/ja/docs/tutorial/testing.md b/docs/ja/docs/tutorial/testing.md index 037e9628f..fe6c8c6b4 100644 --- a/docs/ja/docs/tutorial/testing.md +++ b/docs/ja/docs/tutorial/testing.md @@ -18,24 +18,31 @@ チェックしたい Python の標準的な式と共に、シンプルに `assert` 文を記述します。 -```Python hl_lines="2 12 15-18" -{!../../../docs_src/app_testing/tutorial001.py!} -``` +{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *} + +/// tip | 豆知識 + +テスト関数は `async def` ではなく、通常の `def` であることに注意してください。 + +また、クライアントへの呼び出しも通常の呼び出しであり、`await` を使用しません。 -!!! tip "豆知識" - テスト関数は `async def` ではなく、通常の `def` であることに注意してください。 +これにより、煩雑にならずに、`pytest` を直接使用できます。 - また、クライアントへの呼び出しも通常の呼び出しであり、`await` を使用しません。 +/// - これにより、煩雑にならずに、`pytest` を直接使用できます。 +/// note | 技術詳細 -!!! note "技術詳細" - `from starlette.testclient import TestClient` も使用できます。 +`from starlette.testclient import TestClient` も使用できます。 - **FastAPI** は開発者の利便性のために `fastapi.testclient` と同じ `starlette.testclient` を提供します。しかし、実際にはStarletteから直接渡されています。 +**FastAPI** は開発者の利便性のために `fastapi.testclient` と同じ `starlette.testclient` を提供します。しかし、実際にはStarletteから直接渡されています。 -!!! tip "豆知識" - FastAPIアプリケーションへのリクエストの送信とは別に、テストで `async` 関数 (非同期データベース関数など) を呼び出したい場合は、高度なチュートリアルの[Async Tests](../advanced/async-tests.md){.internal-link target=_blank} を参照してください。 +/// + +/// tip | 豆知識 + +FastAPIアプリケーションへのリクエストの送信とは別に、テストで `async` 関数 (非同期データベース関数など) を呼び出したい場合は、高度なチュートリアルの[Async Tests](../advanced/async-tests.md){.internal-link target=_blank} を参照してください。 + +/// ## テストの分離 @@ -47,17 +54,13 @@ **FastAPI** アプリに `main.py` ファイルがあるとします: -```Python -{!../../../docs_src/app_testing/main.py!} -``` +{* ../../docs_src/app_testing/main.py *} ### テストファイル 次に、テストを含む `test_main.py` ファイルを作成し、`main` モジュール (`main.py`) から `app` をインポートします: -```Python -{!../../../docs_src/app_testing/test_main.py!} -``` +{* ../../docs_src/app_testing/test_main.py *} ## テスト: 例の拡張 @@ -74,25 +77,13 @@ これらの *path operation* には `X-Token` ヘッダーが必要です。 -=== "Python 3.10+" - - ```Python - {!> ../../../docs_src/app_testing/app_b_py310/main.py!} - ``` - -=== "Python 3.6+" - - ```Python - {!> ../../../docs_src/app_testing/app_b/main.py!} - ``` +{* ../../docs_src/app_testing/app_b_py310/main.py *} ### 拡張版テストファイル 次に、先程のものに拡張版のテストを加えた、`test_main_b.py` を作成します。 -```Python -{!> ../../../docs_src/app_testing/app_b/test_main.py!} -``` +{* ../../docs_src/app_testing/app_b/test_main.py *} リクエストに情報を渡せるクライアントが必要で、その方法がわからない場合はいつでも、`httpx` での実現方法を検索 (Google) できます。 @@ -108,10 +99,13 @@ (`httpx` または `TestClient` を使用して) バックエンドにデータを渡す方法の詳細は、HTTPXのドキュメントを確認してください。 -!!! info "情報" - `TestClient` は、Pydanticモデルではなく、JSONに変換できるデータを受け取ることに注意してください。 +/// info | 情報 + +`TestClient` は、Pydanticモデルではなく、JSONに変換できるデータを受け取ることに注意してください。 + +テストにPydanticモデルがあり、テスト中にそのデータをアプリケーションに送信したい場合は、[JSON互換エンコーダ](encoder.md){.internal-link target=_blank} で説明されている `jsonable_encoder` が利用できます。 - テストにPydanticモデルがあり、テスト中にそのデータをアプリケーションに送信したい場合は、[JSON互換エンコーダ](encoder.md){.internal-link target=_blank} で説明されている `jsonable_encoder` が利用できます。 +/// ## 実行 diff --git a/docs/ko/docs/about/index.md b/docs/ko/docs/about/index.md new file mode 100644 index 000000000..ee7804d32 --- /dev/null +++ b/docs/ko/docs/about/index.md @@ -0,0 +1,3 @@ +# 소개 + +FastAPI에 대한 디자인, 영감 등에 대해 🤓 diff --git a/docs/ko/docs/advanced/additional-status-codes.md b/docs/ko/docs/advanced/additional-status-codes.md new file mode 100644 index 000000000..da06cb778 --- /dev/null +++ b/docs/ko/docs/advanced/additional-status-codes.md @@ -0,0 +1,41 @@ +# 추가 상태 코드 + +기본적으로 **FastAPI**는 응답을 `JSONResponse`를 사용하여 반환하며, *경로 작업(path operation)*에서 반환한 내용을 해당 `JSONResponse` 안에 넣어 반환합니다. + +기본 상태 코드 또는 *경로 작업*에서 설정한 상태 코드를 사용합니다. + +## 추가 상태 코드 + +기본 상태 코드와 별도로 추가 상태 코드를 반환하려면 `JSONResponse`와 같이 `Response`를 직접 반환하고 추가 상태 코드를 직접 설정할 수 있습니다. + +예를 들어 항목을 업데이트할 수 있는 *경로 작업*이 있고 성공 시 200 “OK”의 HTTP 상태 코드를 반환한다고 가정해 보겠습니다. + +하지만 새로운 항목을 허용하기를 원할 것입니다. 항목이 이전에 존재하지 않았다면 이를 생성하고 HTTP 상태 코드 201 "Created"를 반환합니다. + +이를 위해서는 `JSONResponse`를 가져와서 원하는 `status_code`를 설정하여 콘텐츠를 직접 반환합니다: + +{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *} + +/// warning | 경고 + +위의 예제처럼 `Response`를 직접 반환하면 바로 반환됩니다. + +모델 등과 함께 직렬화되지 않습니다. + +원하는 데이터가 있는지, 값이 유효한 JSON인지 확인합니다(`JSONResponse`를 사용하는 경우). + +/// + +/// note | 기술적 세부 정보 + +`from starlette.responses import JSONResponse`를 사용할 수도 있습니다. + +**FastAPI**는 개발자 여러분을 위한 편의성으로 `fastapi.responses`와 동일한 `starlette.responses`를 제공합니다. 그러나 사용 가능한 응답의 대부분은 Starlette에서 직접 제공됩니다. `status` 또한 마찬가지입니다. + +/// + +## OpenAPI 및 API 문서 + +추가 상태 코드와 응답을 직접 반환하는 경우, FastAPI는 반환할 내용을 미리 알 수 있는 방법이 없기 때문에 OpenAPI 스키마(API 문서)에 포함되지 않습니다. + +하지만 다음을 사용하여 코드에 이를 문서화할 수 있습니다: [추가 응답](additional-responses.md){.internal-link target=_blank}. diff --git a/docs/ko/docs/advanced/advanced-dependencies.md b/docs/ko/docs/advanced/advanced-dependencies.md new file mode 100644 index 000000000..7fa043fa3 --- /dev/null +++ b/docs/ko/docs/advanced/advanced-dependencies.md @@ -0,0 +1,67 @@ +# 고급 의존성 + +## 매개변수화된 의존성 + +지금까지 본 모든 의존성은 고정된 함수 또는 클래스입니다. + +하지만 여러 개의 함수나 클래스를 선언하지 않고도 의존성에 매개변수를 설정해야 하는 경우가 있을 수 있습니다. + +예를 들어, `q` 쿼리 매개변수가 특정 고정된 내용을 포함하고 있는지 확인하는 의존성을 원한다고 가정해 봅시다. + +이때 해당 고정된 내용을 매개변수화할 수 있길 바랍니다. + +## "호출 가능한" 인스턴스 + +Python에는 클래스의 인스턴스를 "호출 가능"하게 만드는 방법이 있습니다. + +클래스 자체(이미 호출 가능함)가 아니라 해당 클래스의 인스턴스에 대해 호출 가능하게 하는 것입니다. + +이를 위해 `__call__` 메서드를 선언합니다: + +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[12] *} + +이 경우, **FastAPI**는 추가 매개변수와 하위 의존성을 확인하기 위해 `__call__`을 사용하게 되며, +나중에 *경로 연산 함수*에서 매개변수에 값을 전달할 때 이를 호출하게 됩니다. + +## 인스턴스 매개변수화하기 + +이제 `__init__`을 사용하여 의존성을 "매개변수화"할 수 있는 인스턴스의 매개변수를 선언할 수 있습니다: + +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[9] *} + +이 경우, **FastAPI**는 `__init__`에 전혀 관여하지 않으며, 우리는 이 메서드를 코드에서 직접 사용하게 됩니다. + +## 인스턴스 생성하기 + +다음과 같이 이 클래스의 인스턴스를 생성할 수 있습니다: + +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[18] *} + +이렇게 하면 `checker.fixed_content` 속성에 `"bar"`라는 값을 담아 의존성을 "매개변수화"할 수 있습니다. + +## 인스턴스를 의존성으로 사용하기 + +그런 다음, `Depends(FixedContentQueryChecker)` 대신 `Depends(checker)`에서 이 `checker` 인스턴스를 사용할 수 있으며, +클래스 자체가 아닌 인스턴스 `checker`가 의존성이 됩니다. + +의존성을 해결할 때 **FastAPI**는 이 `checker`를 다음과 같이 호출합니다: + +```Python +checker(q="somequery") +``` + +...그리고 이때 반환되는 값을 *경로 연산 함수*의 `fixed_content_included` 매개변수로 전달합니다: + +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[22] *} + +/// tip | 참고 + +이 모든 과정이 복잡하게 느껴질 수 있습니다. 그리고 지금은 이 방법이 얼마나 유용한지 명확하지 않을 수도 있습니다. + +이 예시는 의도적으로 간단하게 만들었지만, 전체 구조가 어떻게 작동하는지 보여줍니다. + +보안 관련 장에서는 이와 같은 방식으로 구현된 편의 함수들이 있습니다. + +이 모든 과정을 이해했다면, 이러한 보안 도구들이 내부적으로 어떻게 작동하는지 이미 파악한 것입니다. + +/// diff --git a/docs/ko/docs/advanced/async-tests.md b/docs/ko/docs/advanced/async-tests.md new file mode 100644 index 000000000..37dfe2979 --- /dev/null +++ b/docs/ko/docs/advanced/async-tests.md @@ -0,0 +1,108 @@ +# 비동기 테스트 코드 작성 + +이전 장에서 `TestClient` 를 이용해 **FastAPI** 어플리케이션 테스트를 작성하는 법을 배우셨을텐데요. +지금까지는 `async` 키워드 사용없이 동기 함수의 테스트 코드를 작성하는 법만 익혔습니다. + +하지만 비동기 함수를 사용하여 테스트 코드를 작성하는 것은 매우 유용할 수 있습니다. +예를 들면 데이터베이스에 비동기로 쿼리하는 경우를 생각해봅시다. +FastAPI 애플리케이션에 요청을 보내고, 비동기 데이터베이스 라이브러리를 사용하여 백엔드가 데이터베이스에 올바르게 데이터를 기록했는지 확인하고 싶을 때가 있을 겁니다. + +이런 경우의 테스트 코드를 어떻게 비동기로 작성하는지 알아봅시다. + +## pytest.mark.anyio + +앞에서 작성한 테스트 함수에서 비동기 함수를 호출하고 싶다면, 테스트 코드도 비동기 함수여야합니다. +AnyIO는 특정 테스트 함수를 비동기 함수로 호출 할 수 있는 깔끔한 플러그인을 제공합니다. + + +## HTTPX + +**FastAPI** 애플리케이션이 `async def` 대신 `def` 키워드로 선언된 함수를 사용하더라도, 내부적으로는 여전히 `비동기` 애플리케이션입니다. + +`TestClient`는 pytest 표준을 사용하여 비동기 FastAPI 애플리케이션을 일반적인 `def` 테스트 함수 내에서 호출할 수 있도록 내부에서 마술을 부립니다. 하지만 이 마술은 비동기 함수 내부에서 사용할 때는 더 이상 작동하지 않습니다. 테스트를 비동기로 실행하면, 더 이상 테스트 함수 내부에서 `TestClient`를 사용할 수 없습니다. + +`TestClient`는 HTTPX를 기반으로 하고 있으며, 다행히 이를 직접 사용하여 API를 테스트할 수 있습니다. + +## 예시 + +간단한 예시를 위해 [더 큰 어플리케이션 만들기](../ko/tutorial/bigger-applications.md){.internal-link target=_blank} 와 [테스트](../ko/tutorial/testing.md){.internal-link target=_blank}:에서 다룬 파일 구조와 비슷한 형태를 확인해봅시다: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + + `main.py`는 아래와 같아야 합니다: + +{* ../../docs_src/async_tests/main.py *} + +`test_main.py` 파일은 `main.py`에 대한 테스트가 있을 텐데, 다음과 같을 수 있습니다: + +{* ../../docs_src/async_tests/test_main.py *} + +## 실행하기 + +아래의 명령어로 테스트 코드를 실행합니다: + +
+ +```console +$ pytest + +---> 100% +``` + +
+ +## 자세히 보기 + +`@pytest.mark.anyio` 마커는 pytest에게 이 테스트 함수가 비동기로 호출되어야 함을 알려줍니다: + +{* ../../docs_src/async_tests/test_main.py hl[7] *} + +/// tip | 팁 + +테스트 함수가 이제 `TestClient`를 사용할 때처럼 단순히 `def`가 아니라 `async def`로 작성된 점에 주목해주세요. + +/// + +그 다음에 `AsyncClient` 로 앱을 만들고 비동기 요청을 `await` 키워드로 보낼 수 있습니다: + +{* ../../docs_src/async_tests/test_main.py hl[9:12] *} + +위의 코드는: + +```Python +response = client.get('/') +``` + +`TestClient` 에 요청을 보내던 것과 동일합니다. + +/// tip | 팁 + +새로운 `AsyncClient`를 사용할 때 async/await를 사용하고 있다는 점에 주목하세요. 이 요청은 비동기적으로 처리됩니다. + +/// + +/// warning | 경고 + +만약의 어플리케이션이 Lifespan 이벤트에 의존성을 갖고 있다면 `AsyncClient` 가 이러한 이벤트를 실행시키지 않습니다. +`AsyncClient` 가 테스트를 실행시켰다는 것을 확인하기 위해 +`LifespanManager` from florimondmanca/asgi-lifespan.확인해주세요. + + +/// + +## 그 외의 비동기 함수 호출 + +테스트 함수가 이제 비동기 함수이므로, FastAPI 애플리케이션에 요청을 보내는 것 외에도 다른 `async` 함수를 호출하고 `await` 키워드를 사용 할 수 있습니다. + +/// tip | 팁 + +테스트에 비동기 함수 호출을 통합할 때 (예: MongoDB의 MotorClient를 사용할 때) `RuntimeError: Task attached to a different loop` 오류가 발생한다면, 이벤트 루프가 필요한 객체는 반드시 비동기 함수 내에서만 인스턴스화해야 한다는 점을 주의하세요! +예를 들어 `@app.on_event("startup")` 콜백 내에서 인스턴스화하는 것이 좋습니다. + +/// diff --git a/docs/ko/docs/advanced/custom-response.md b/docs/ko/docs/advanced/custom-response.md new file mode 100644 index 000000000..2001956fa --- /dev/null +++ b/docs/ko/docs/advanced/custom-response.md @@ -0,0 +1,313 @@ +# 사용자 정의 응답 - HTML, Stream, 파일, 기타 + +기본적으로, **FastAPI** 응답을 `JSONResponse`를 사용하여 반환합니다. + +이를 재정의 하려면 [응답을 직접 반환하기](response-directly.md){.internal-link target=_blank}에서 본 것처럼 `Response`를 직접 반환하면 됩니다. + +그러나 `Response` (또는 `JSONResponse`와 같은 하위 클래스)를 직접 반환하면, 데이터가 자동으로 변환되지 않으며 (심지어 `response_model`을 선언했더라도), 문서화가 자동으로 생성되지 않습니다(예를 들어, 생성된 OpenAPI의 일부로 HTTP 헤더 `Content-Type`에 특정 "미디어 타입"을 포함하는 경우). + +하지만 *경로 작업 데코레이터*에서 `response_class` 매개변수를 사용하여 원하는 `Response`(예: 모든 `Response` 하위 클래스)를 선언할 수도 있습니다. + +*경로 작업 함수*에서 반환하는 내용은 해당 `Response`안에 포함됩니다. + +그리고 만약 그 `Response`가 `JSONResponse`와 `UJSONResponse`의 경우 처럼 JSON 미디어 타입(`application/json`)을 가지고 있다면, *경로 작업 데코레이터*에서 선언한 Pydantic의 `response_model`을 사용해 자동으로 변환(및 필터링) 됩니다. + +/// note | 참고 + +미디어 타입이 없는 응답 클래스를 사용하는 경우, FastAPI는 응답에 내용이 없을 것으로 예상하므로 생성된 OpenAPI 문서에서 응답 형식을 문서화하지 않습니다. + +/// + +## `ORJSONResponse` 사용하기 + +예를 들어, 성능을 극대화하려는 경우, orjson을 설치하여 사용하고 응답을 `ORJSONResponse`로 설정할 수 있습니다. + +사용하고자 하는 `Response` 클래스(하위 클래스)를 임포트한 후, **경로 작업 데코레이터*에서 선언하세요. + +대규모 응답의 경우, 딕셔너리를 반환하는 것보다 `Response`를 반환하는 것이 훨씬 빠릅니다. + +이유는 기본적으로, FastAPI가 내부의 모든 항목을 검사하고 JSON으로 직렬화할 수 있는지 확인하기 때문입니다. 이는 사용자 안내서에서 설명된 [JSON 호환 가능 인코더](../tutorial/encoder.md){.internal-link target=_blank}를 사용하는 방식과 동일합니다. 이를 통해 데이터베이스 모델과 같은 **임의의 객체**를 반환할 수 있습니다. + +하지만 반환하는 내용이 **JSON으로 직렬화 가능**하다고 확신하는 경우, 해당 내용을 응답 클래스에 직접 전달할 수 있으며, FastAPI가 반환 내용을 `jsonable_encoder`를 통해 처리한 뒤 응답 클래스에 전달하는 오버헤드를 피할 수 있습니다. + +{* ../../docs_src/custom_response/tutorial001b.py hl[2,7] *} + +/// info | 정보 + +`response_class` 매개변수는 응답의 "미디어 타입"을 정의하는 데에도 사용됩니다. + +이 경우, HTTP 헤더 `Content-Type`은 `application/json`으로 설정됩니다. + +그리고 이는 OpenAPI에 그대로 문서화됩니다. + +/// + +/// tip | 팁 + +`ORJSONResponse`는 FastAPI에서만 사용할 수 있고 Starlette에서는 사용할 수 없습니다. + +/// + +## HTML 응답 + +**FastAPI**에서 HTML 응답을 직접 반환하려면 `HTMLResponse`를 사용하세요. + +* `HTMLResponse`를 임포트 합니다. +* *경로 작업 데코레이터*의 `response_class` 매개변수로 `HTMLResponse`를 전달합니다. + +{* ../../docs_src/custom_response/tutorial002.py hl[2,7] *} + +/// info | 정보 + +`response_class` 매개변수는 응답의 "미디어 타입"을 정의하는 데에도 사용됩니다. + +이 경우, HTTP 헤더 `Content-Type`은 `text/html`로 설정됩니다. + +그리고 이는 OpenAPI에 그대로 문서화 됩니다. + +/// + +### `Response` 반환하기 + +[응답을 직접 반환하기](response-directly.md){.internal-link target=_blank}에서 본 것 처럼, *경로 작업*에서 응답을 직접 반환하여 재정의할 수도 있습니다. + +위의 예제와 동일하게 `HTMLResponse`를 반환하는 코드는 다음과 같을 수 있습니다: + +{* ../../docs_src/custom_response/tutorial003.py hl[2,7,19] *} + +/// warning | 경고 + +*경로 작업 함수*에서 직접 반환된 `Response`는 OpenAPI에 문서화되지 않습니다(예를들어, `Content-Type`이 문서화되지 않음) 자동 대화형 문서에서도 표시되지 않습니다. + +/// + +/// info | 정보 + +물론 실제 `Content-Type` 헤더, 상태 코드 등은 반환된 `Response` 객체에서 가져옵니다. + +/// + +### OpenAPI에 문서화하고 `Response` 재정의 하기 + +함수 내부에서 응답을 재정의하면서 동시에 OpenAPI에서 "미디어 타입"을 문서화하고 싶다면, `response_class` 매게변수를 사용하면서 `Response` 객체를 반환할 수 있습니다. + +이 경우 `response_class`는 OpenAPI *경로 작업*을 문서화하는 데만 사용되고, 실제로는 여러분이 반환한 `Response`가 그대로 사용됩니다. + +### `HTMLResponse`직접 반환하기 + +예를 들어, 다음과 같이 작성할 수 있습니다: + +{* ../../docs_src/custom_response/tutorial004.py hl[7,21,23] *} + +이 예제에서, `generate_html_response()` 함수는 HTML을 `str`로 반환하는 대신 이미 `Response`를 생성하고 반환합니다. + +`generate_html_response()`를 호출한 결과를 반환함으로써, 기본적인 **FastAPI** 기본 동작을 재정의 하는 `Response`를 이미 반환하고 있습니다. + +하지만 `response_class`에 `HTMLResponse`를 함께 전달했기 때문에, FastAPI는 이를 OpenAPI 및 대화형 문서에서 `text/html`로 HTML을 문서화 하는 방법을 알 수 있습니다. + + + +## 사용 가능한 응답들 + +다음은 사용할 수 있는 몇가지 응답들 입니다. + +`Response`를 사용하여 다른 어떤 것도 반환 할수 있으며, 직접 하위 클래스를 만들 수도 있습니다. + +/// note | 기술 세부사항 + +`from starlette.responses import HTMLResponse`를 사용할 수도 있습니다. + +**FastAPI**는 개발자인 여러분의 편의를 위해 `starlette.responses`를 `fastapi.responses`로 제공 하지만, 대부분의 사용 가능한 응답은 Starlette에서 직접 가져옵니다. + +/// + +### `Response` + +기본 `Response` 클래스는 다른 모든 응답 클래스의 부모 클래스 입니다. + +이 클래스를 직접 반환할 수 있습니다. + +다음 매개변수를 받을 수 있습니다: + +* `content` - `str` 또는 `bytes`. +* `status_code` - HTTP 상태코드를 나타내는 `int`. +* `headers` - 문자열로 이루어진 `dict`. +* `media_type` - 미디어 타입을 나타내는 `str` 예: `"text/html"`. + +FastAPI (실제로는 Starlette)가 자동으로 `Content-Length` 헤더를 포함시킵니다. 또한 `media_type`에 기반하여 `Content-Type` 헤더를 포함하며, 텍스트 타입의 경우 문자 집합을 추가 합니다. + +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} + +### `HTMLResponse` + +텍스트 또는 바이트를 받아 HTML 응답을 반환합니다. 위에서 설명한 내용과 같습니다. + +### `PlainTextResponse` + +텍스트 또는 바이트를 받아 일반 텍스트 응답을 반환합니다. + +{* ../../docs_src/custom_response/tutorial005.py hl[2,7,9] *} + +### `JSONResponse` + +데이터를 받아 `application/json`으로 인코딩된 응답을 반환합니다. + +이는 위에서 설명했듯이 **FastAPI**에서 기본적으로 사용되는 응답 형식입니다. + +### `ORJSONResponse` + + `orjson`을 사용하여 빠른 JSON 응답을 제공하는 대안입니다. 위에서 설명한 내용과 같습니다. + +/// info | 정보 + +이를 사용하려면 `orjson`을 설치해야합니다. 예: `pip install orjson`. + +/// + +### `UJSONResponse` + +`ujson`을 사용한 또 다른 JSON 응답 형식입니다. + +/// info | 정보 + +이 응답을 사용하려면 `ujson`을 설치해야합니다. 예: 'pip install ujson`. + +/// + +/// warning | 경고 + +`ujson` 은 일부 예외 경우를 처리하는 데 있어 Python 내장 구현보다 덜 엄격합니다. + +/// + +{* ../../docs_src/custom_response/tutorial001.py hl[2,7] *} + +/// tip | 팁 + +`ORJSONResponse`가 더 빠른 대안일 가능성이 있습니다. + +/// + +### `RedirectResponse` + +HTTP 리디렉션 응답을 반환합니다. 기본적으로 상태 코드는 307(임시 리디렉션)으로 설정됩니다. + +`RedirectResponse`를 직접 반환할 수 있습니다. + +{* ../../docs_src/custom_response/tutorial006.py hl[2,9] *} + +--- + +또는 `response_class` 매개변수에서 사용할 수도 있습니다: + + +{* ../../docs_src/custom_response/tutorial006b.py hl[2,7,9] *} + +이 경우, *경로 작업* 함수에서 URL을 직접 반환할 수 있습니다. + +이 경우, 사용되는 `status_code`는 `RedirectResponse`의 기본값인 `307` 입니다. + +--- + +`status_code` 매개변수를 `response_class` 매개변수와 함께 사용할 수도 있습니다: + +{* ../../docs_src/custom_response/tutorial006c.py hl[2,7,9] *} + +### `StreamingResponse` + +비동기 제너레이터 또는 일반 제너레이터/이터레이터를 받아 응답 본문을 스트리밍 합니다. + +{* ../../docs_src/custom_response/tutorial007.py hl[2,14] *} + +#### 파일과 같은 객체를 사용한 `StreamingResponse` + +파일과 같은 객체(예: `open()`으로 반환된 객체)가 있는 경우, 해당 파일과 같은 객체를 반복(iterate)하는 제너레이터 함수를 만들 수 있습니다. + +이 방식으로, 파일 전체를 메모리에 먼저 읽어들일 필요 없이, 제너레이터 함수를 `StreamingResponse`에 전달하여 반환할 수 있습니다. + +이 방식은 클라우드 스토리지, 비디오 처리 등의 다양한 라이브러리와 함께 사용할 수 있습니다. + +{* ../../docs_src/custom_response/tutorial008.py hl[2,10:12,14] *} + +1. 이것이 제너레이터 함수입니다. `yield` 문을 포함하고 있으므로 "제너레이터 함수"입니다. +2. `with` 블록을 사용함으로써, 제너레이터 함수가 완료된 후 파일과 같은 객체가 닫히도록 합니다. 즉, 응답 전송이 끝난 후 닫힙니다. +3. 이 `yield from`은 함수가 `file_like`라는 객체를 반복(iterate)하도록 합니다. 반복된 각 부분은 이 제너레이터 함수(`iterfile`)에서 생성된 것처럼 `yield` 됩니다. + + 이렇게 하면 "생성(generating)" 작업을 내부적으로 다른 무언가에 위임하는 제너레이터 함수가 됩니다. + + 이 방식을 사용하면 `with` 블록 안에서 파일을 열 수 있어, 작업이 완료된 후 파일과 같은 객체가 닫히는 것을 보장할 수 있습니다. + +/// tip | 팁 + +여기서 표준 `open()`을 사용하고 있기 때문에 `async`와 `await`를 지원하지 않습니다. 따라서 경로 작업은 일반 `def`로 선언합니다. + +/// + +### `FileResponse` + +파일을 비동기로 스트리밍하여 응답합니다. + +다른 응답 유형과는 다른 인수를 사용하여 객체를 생성합니다: + +* `path` - 스트리밍할 파일의 경로. +* `headers` - 딕셔너리 형식의 사용자 정의 헤더. +* `media_type` - 미디어 타입을 나타내는 문자열. 설정되지 않은 경우 파일 이름이나 경로를 사용하여 추론합니다. +* `filename` - 설정된 경우 응답의 `Content-Disposition`에 포함됩니다. + +파일 응답에는 적절한 `Content-Length`, `Last-Modified`, 및 `ETag` 헤더가 포함됩니다. + +{* ../../docs_src/custom_response/tutorial009.py hl[2,10] *} + +또한 `response_class` 매개변수를 사용할 수도 있습니다: + +{* ../../docs_src/custom_response/tutorial009b.py hl[2,8,10] *} + +이 경우, 경로 작업 함수에서 파일 경로를 직접 반환할 수 있습니다. + +## 사용자 정의 응답 클래스 + +`Response`를 상속받아 사용자 정의 응답 클래스를 생성하고 사용할 수 있습니다. + +예를 들어, 포함된 `ORJSONResponse` 클래스에서 사용되지 않는 설정으로 orjson을 사용하고 싶다고 가정해봅시다. + +만약 들여쓰기 및 포맷된 JSON을 반환하고 싶다면, `orjson.OPT_INDENT_2` 옵션을 사용할 수 있습니다. + +`CustomORJSONResponse`를 생성할 수 있습니다. 여기서 핵심은 `Response.render(content)` 메서드를 생성하여 내용을 `bytes`로 반환하는 것입니다: + +{* ../../docs_src/custom_response/tutorial009c.py hl[9:14,17] *} + +이제 다음 대신: + +```json +{"message": "Hello World"} +``` + +이 응답은 이렇게 반환됩니다: + +```json +{ + "message": "Hello World" +} +``` + +물론 JSON 포맷팅보다 더 유용하게 활용할 방법을 찾을 수 있을 것입니다. 😉 + +## 기본 응답 클래스 + +**FastAPI** 클래스 객체 또는 `APIRouter`를 생성할 때 기본적으로 사용할 응답 클래스를 지정할 수 있습니다. + +이를 정의하는 매개변수는 `default_response_class`입니다. + +아래 예제에서 **FastAPI**는 모든 경로 작업에서 기본적으로 `JSONResponse` 대신 `ORJSONResponse`를 사용합니다. + +{* ../../docs_src/custom_response/tutorial010.py hl[2,4] *} + +/// tip | 팁 + +여전히 이전처럼 *경로 작업*에서 `response_class`를 재정의할 수 있습니다. + +/// + +## 추가 문서화 + +OpenAPI에서 `responses`를 사용하여 미디어 타입 및 기타 세부 정보를 선언할 수도 있습니다: [OpenAPI에서 추가 응답](additional-responses.md){.internal-link target=_blank}. diff --git a/docs/ko/docs/advanced/events.md b/docs/ko/docs/advanced/events.md new file mode 100644 index 000000000..ae349e7be --- /dev/null +++ b/docs/ko/docs/advanced/events.md @@ -0,0 +1,53 @@ +# 이벤트: startup과 shutdown + +필요에 따라 응용 프로그램이 시작되기 전이나 종료될 때 실행되는 이벤트 핸들러(함수)를 정의할 수 있습니다. + +이 함수들은 `async def` 또는 평범하게 `def`으로 선언할 수 있습니다. + +/// warning | 경고 + +이벤트 핸들러는 주 응용 프로그램에서만 작동합니다. [하위 응용 프로그램 - 마운트](./sub-applications.md){.internal-link target=_blank}에서는 작동하지 않습니다. + +/// + +## `startup` 이벤트 + +응용 프로그램을 시작하기 전에 실행하려는 함수를 "startup" 이벤트로 선언합니다: + +{* ../../docs_src/events/tutorial001.py hl[8] *} + +이 경우 `startup` 이벤트 핸들러 함수는 단순히 몇 가지 값으로 구성된 `dict` 형식의 "데이터베이스"를 초기화합니다. + +하나 이상의 이벤트 핸들러 함수를 추가할 수도 있습니다. + +그리고 응용 프로그램은 모든 `startup` 이벤트 핸들러가 완료될 때까지 요청을 받지 않습니다. + +## `shutdown` 이벤트 + +응용 프로그램이 종료될 때 실행하려는 함수를 추가하려면 `"shutdown"` 이벤트로 선언합니다: + +{* ../../docs_src/events/tutorial002.py hl[6] *} + +이 예제에서 `shutdown` 이벤트 핸들러 함수는 `"Application shutdown"`이라는 텍스트가 적힌 `log.txt` 파일을 추가할 것입니다. + +/// info | 정보 + +`open()` 함수에서 `mode="a"`는 "추가"를 의미합니다. 따라서 이미 존재하는 파일의 내용을 덮어쓰지 않고 새로운 줄을 추가합니다. + +/// + +/// tip | 팁 + +이 예제에서는 파일과 상호작용 하기 위해 파이썬 표준 함수인 `open()`을 사용하고 있습니다. + +따라서 디스크에 데이터를 쓰기 위해 "대기"가 필요한 I/O (입력/출력) 작업을 수행합니다. + +그러나 `open()`은 `async`와 `await`을 사용하지 않기 때문에 이벤트 핸들러 함수는 `async def`가 아닌 표준 `def`로 선언하고 있습니다. + +/// + +/// info | 정보 + +이벤트 핸들러에 관한 내용은 Starlette 이벤트 문서에서 추가로 확인할 수 있습니다. + +/// diff --git a/docs/ko/docs/advanced/index.md b/docs/ko/docs/advanced/index.md new file mode 100644 index 000000000..31704727c --- /dev/null +++ b/docs/ko/docs/advanced/index.md @@ -0,0 +1,27 @@ +# 심화 사용자 안내서 - 도입부 + +## 추가 기능 + +메인 [자습서 - 사용자 안내서](../tutorial/index.md){.internal-link target=_blank}는 여러분이 **FastAPI**의 모든 주요 기능을 둘러보시기에 충분할 것입니다. + +이어지는 장에서는 여러분이 다른 옵션, 구성 및 추가 기능을 보실 수 있습니다. + +/// tip | 팁 + +다음 장들이 **반드시 "심화"**인 것은 아닙니다. + +그리고 여러분의 사용 사례에 대한 해결책이 그중 하나에 있을 수 있습니다. + +/// + +## 자습서를 먼저 읽으십시오 + +여러분은 메인 [자습서 - 사용자 안내서](../tutorial/index.md){.internal-link target=_blank}의 지식으로 **FastAPI**의 대부분의 기능을 사용하실 수 있습니다. + +이어지는 장들은 여러분이 메인 자습서 - 사용자 안내서를 이미 읽으셨으며 주요 아이디어를 알고 계신다고 가정합니다. + +## TestDriven.io 강좌 + +여러분이 문서의 이 부분을 보완하시기 위해 심화-기초 강좌 수강을 희망하신다면 다음을 참고 하시기를 바랍니다: **TestDriven.io**의 FastAPI와 Docker를 사용한 테스트 주도 개발. + +그들은 현재 전체 수익의 10퍼센트를 **FastAPI** 개발에 기부하고 있습니다. 🎉 😄 diff --git a/docs/ko/docs/advanced/middlewares.md b/docs/ko/docs/advanced/middlewares.md new file mode 100644 index 000000000..c00aedeaf --- /dev/null +++ b/docs/ko/docs/advanced/middlewares.md @@ -0,0 +1,96 @@ +# 고급 미들웨어 + +메인 튜토리얼에서 [Custom Middleware](../tutorial/middleware.md){.internal-link target=_blank}를 응용프로그램에 추가하는 방법을 읽으셨습니다. + +그리고 [CORS with the `CORSMiddleware`](){.internal-link target=_blank}하는 방법도 보셨습니다. + +이 섹션에서는 다른 미들웨어들을 사용하는 방법을 알아보겠습니다. + +## ASGI 미들웨어 추가하기 + +**FastAPI**는 Starlette을 기반으로 하고 있으며, ASGI 사양을 구현하므로 ASGI 미들웨어를 사용할 수 있습니다. + +미들웨어가 FastAPI나 Starlette용으로 만들어지지 않아도 ASGI 사양을 준수하는 한 동작할 수 있습니다. + +일반적으로 ASGI 미들웨어는 첫 번째 인수로 ASGI 앱을 받는 클래스들입니다. + +따라서 타사 ASGI 미들웨어 문서에서 일반적으로 다음과 같이 사용하도록 안내할 것입니다. + +```Python +from unicorn import UnicornMiddleware + +app = SomeASGIApp() + +new_app = UnicornMiddleware(app, some_config="rainbow") +``` + +하지만 내부 미들웨어가 서버 오류를 처리하고 사용자 정의 예외 처리기가 제대로 작동하도록 하는 더 간단한 방법을 제공하는 FastAPI(실제로는 Starlette)가 있습니다. + +이를 위해 `app.add_middleware()`를 사용합니다(CORS의 예에서와 같이). + +```Python +from fastapi import FastAPI +from unicorn import UnicornMiddleware + +app = FastAPI() + +app.add_middleware(UnicornMiddleware, some_config="rainbow") +``` + +`app.add_middleware()`는 첫 번째 인수로 미들웨어 클래스와 미들웨어에 전달할 추가 인수를 받습니다. + +## 통합 미들웨어 + +**FastAPI**에는 일반적인 사용 사례를 위한 여러 미들웨어가 포함되어 있으며, 사용 방법은 다음에서 살펴보겠습니다. + +/// note | 기술 세부 사항 + +다음 예제에서는 `from starlette.middleware.something import SomethingMiddleware`를 사용할 수도 있습니다. + +**FastAPI**는 개발자의 편의를 위해 `fastapi.middleware`에 여러 미들웨어를 제공합니다. 그러나 사용 가능한 대부분의 미들웨어는 Starlette에서 직접 제공합니다. + +/// + +## `HTTPSRedirectMiddleware` + +들어오는 모든 요청이 `https` 또는 `wss`여야 합니다. + +`http` 또는 `ws`로 들어오는 모든 요청은 대신 보안 체계로 리디렉션됩니다. + +{* ../../docs_src/advanced_middleware/tutorial001.py hl[2,6] *} + +## `TrustedHostMiddleware` + +HTTP 호스트 헤더 공격을 방지하기 위해 모든 수신 요청에 올바르게 설정된 `Host` 헤더를 갖도록 강제합니다. + +{* ../../docs_src/advanced_middleware/tutorial002.py hl[2,6:8] *} + +다음 인수가 지원됩니다: + +* `allowed_hosts` - 호스트 이름으로 허용해야 하는 도메인 이름 목록입니다. 일치하는 하위 도메인에 대해 `*.example.com`과 같은 와일드카드 도메인이 지원됩니다. 모든 호스트 이름을 허용하려면 `allowed_hosts=[“*”]`를 사용하거나 미들웨어를 생략하세요. + +수신 요청의 유효성이 올바르게 확인되지 않으면 `400`이라는 응답이 전송됩니다. + +## `GZipMiddleware` + +`Accept-Encoding` 헤더에 `“gzip”`이 포함된 모든 요청에 대해 GZip 응답을 처리합니다. + +미들웨어는 표준 응답과 스트리밍 응답을 모두 처리합니다. + +{* ../../docs_src/advanced_middleware/tutorial003.py hl[2,6] *} + +지원되는 인수는 다음과 같습니다: + +* `minimum_size` - 이 최소 크기(바이트)보다 작은 응답은 GZip하지 않습니다. 기본값은 `500`입니다. +* `compresslevel` - GZip 압축 중에 사용됩니다. 1에서 9 사이의 정수입니다. 기본값은 `9`입니다. 값이 낮을수록 압축 속도는 빨라지지만 파일 크기는 커지고, 값이 높을수록 압축 속도는 느려지지만 파일 크기는 작아집니다. + +## 기타 미들웨어 + +다른 많은 ASGI 미들웨어가 있습니다. + +예를 들어: + +유비콘의 `ProxyHeadersMiddleware`> +MessagePack + +사용 가능한 다른 미들웨어를 확인하려면 스타렛의 미들웨어 문서ASGI Awesome List를 참조하세요. diff --git a/docs/ko/docs/advanced/response-change-status-code.md b/docs/ko/docs/advanced/response-change-status-code.md new file mode 100644 index 000000000..1ba9aa3cc --- /dev/null +++ b/docs/ko/docs/advanced/response-change-status-code.md @@ -0,0 +1,31 @@ +# 응답 - 상태 코드 변경 + +기본 [응답 상태 코드 설정](../tutorial/response-status-code.md){.internal-link target=_blank}이 가능하다는 걸 이미 알고 계실 겁니다. + +하지만 경우에 따라 기본 설정과 다른 상태 코드를 반환해야 할 때가 있습니다. + +## 사용 예 + +예를 들어 기본적으로 HTTP 상태 코드 "OK" `200`을 반환하고 싶다고 가정해 봅시다. + +하지만 데이터가 존재하지 않으면 이를 새로 생성하고, HTTP 상태 코드 "CREATED" `201`을 반환하고자 할 때가 있을 수 있습니다. + +이때도 여전히 `response_model`을 사용하여 반환하는 데이터를 필터링하고 변환하고 싶을 수 있습니다. + +이런 경우에는 `Response` 파라미터를 사용할 수 있습니다. + +## `Response` 파라미터 사용하기 + +*경로 작동 함수*에 `Response` 타입의 파라미터를 선언할 수 있습니다. (쿠키와 헤더에 대해 선언하는 것과 유사하게) + +그리고 이 *임시* 응답 객체에서 `status_code`를 설정할 수 있습니다. + +{* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *} + +그리고 평소처럼 원하는 객체(`dict`, 데이터베이스 모델 등)를 반환할 수 있습니다. + +`response_model`을 선언했다면 반환된 객체는 여전히 필터링되고 변환됩니다. + +**FastAPI**는 이 *임시* 응답 객체에서 상태 코드(쿠키와 헤더 포함)를 추출하여, `response_model`로 필터링된 반환 값을 최종 응답에 넣습니다. + +또한, 의존성에서도 `Response` 파라미터를 선언하고 그 안에서 상태 코드를 설정할 수 있습니다. 단, 마지막으로 설정된 상태 코드가 우선 적용된다는 점을 유의하세요. diff --git a/docs/ko/docs/advanced/response-cookies.md b/docs/ko/docs/advanced/response-cookies.md new file mode 100644 index 000000000..327f20afe --- /dev/null +++ b/docs/ko/docs/advanced/response-cookies.md @@ -0,0 +1,49 @@ +# 응답 쿠키 + +## `Response` 매개변수 사용하기 + +*경로 작동 함수*에서 `Response` 타입의 매개변수를 선언할 수 있습니다. + +그런 다음 해당 *임시* 응답 객체에서 쿠키를 설정할 수 있습니다. + +{* ../../docs_src/response_cookies/tutorial002.py hl[1,8:9] *} + +그런 다음 필요한 객체(`dict`, 데이터베이스 모델 등)를 반환할 수 있습니다. + +그리고 `response_model`을 선언했다면 반환한 객체를 거르고 변환하는 데 여전히 사용됩니다. + +**FastAPI**는 그 *임시* 응답에서 쿠키(또한 헤더 및 상태 코드)를 추출하고, 반환된 값이 포함된 최종 응답에 이를 넣습니다. 이 값은 `response_model`로 걸러지게 됩니다. + +또한 의존관계에서 `Response` 매개변수를 선언하고, 해당 의존성에서 쿠키(및 헤더)를 설정할 수도 있습니다. + +## `Response`를 직접 반환하기 + +코드에서 `Response`를 직접 반환할 때도 쿠키를 생성할 수 있습니다. + +이를 위해 [Response를 직접 반환하기](response-directly.md){.internal-link target=_blank}에서 설명한 대로 응답을 생성할 수 있습니다. + +그런 다음 쿠키를 설정하고 반환하면 됩니다: +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} +/// tip + +`Response` 매개변수를 사용하지 않고 응답을 직접 반환하는 경우, FastAPI는 이를 직접 반환한다는 점에 유의하세요. + +따라서 데이터가 올바른 유형인지 확인해야 합니다. 예: `JSONResponse`를 반환하는 경우, JSON과 호환되는지 확인하세요. + +또한 `response_model`로 걸러져야 할 데이터가 전달되지 않도록 확인하세요. + +/// + +### 추가 정보 + +/// note | 기술적 세부사항 + +`from starlette.responses import Response` 또는 `from starlette.responses import JSONResponse`를 사용할 수도 있습니다. + +**FastAPI**는 개발자의 편의를 위해 `fastapi.responses`로 동일한 `starlette.responses`를 제공합니다. 그러나 대부분의 응답은 Starlette에서 직접 제공됩니다. + +또한 `Response`는 헤더와 쿠키를 설정하는 데 자주 사용되므로, **FastAPI**는 이를 `fastapi.Response`로도 제공합니다. + +/// + +사용 가능한 모든 매개변수와 옵션은 Starlette 문서에서 확인할 수 있습니다. diff --git a/docs/ko/docs/advanced/response-directly.md b/docs/ko/docs/advanced/response-directly.md new file mode 100644 index 000000000..08d63c43c --- /dev/null +++ b/docs/ko/docs/advanced/response-directly.md @@ -0,0 +1,63 @@ +# 응답을 직접 반환하기 + +**FastAPI**에서 *경로 작업(path operation)*을 생성할 때, 일반적으로 `dict`, `list`, Pydantic 모델, 데이터베이스 모델 등의 데이터를 반환할 수 있습니다. + +기본적으로 **FastAPI**는 [JSON 호환 가능 인코더](../tutorial/encoder.md){.internal-link target=_blank}에 설명된 `jsonable_encoder`를 사용해 해당 반환 값을 자동으로 `JSON`으로 변환합니다. + +그런 다음, JSON 호환 데이터(예: `dict`)를 `JSONResponse`에 넣어 사용자의 응답을 전송하는 방식으로 처리됩니다. + +그러나 *경로 작업*에서 `JSONResponse`를 직접 반환할 수도 있습니다. + +예를 들어, 사용자 정의 헤더나 쿠키를 반환해야 하는 경우에 유용할 수 있습니다. + +## `Response` 반환하기 + +사실, `Response` 또는 그 하위 클래스를 반환할 수 있습니다. + +/// tip + +`JSONResponse` 자체도 `Response`의 하위 클래스입니다. + +/// + +그리고 `Response`를 반환하면 **FastAPI**가 이를 그대로 전달합니다. + +Pydantic 모델로 데이터 변환을 수행하지 않으며, 내용을 다른 형식으로 변환하지 않습니다. + +이로 인해 많은 유연성을 얻을 수 있습니다. 어떤 데이터 유형이든 반환할 수 있고, 데이터 선언이나 유효성 검사를 재정의할 수 있습니다. + +## `Response`에서 `jsonable_encoder` 사용하기 + +**FastAPI**는 반환하는 `Response`에 아무런 변환을 하지 않으므로, 그 내용이 준비되어 있어야 합니다. + +예를 들어, Pydantic 모델을 `dict`로 변환해 `JSONResponse`에 넣지 않으면 JSON 호환 유형으로 변환된 데이터 유형(예: `datetime`, `UUID` 등)이 사용되지 않습니다. + +이러한 경우, 데이터를 응답에 전달하기 전에 `jsonable_encoder`를 사용하여 변환할 수 있습니다: + +{* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *} + +/// note | 기술적 세부 사항 + +`from starlette.responses import JSONResponse`를 사용할 수도 있습니다. + +**FastAPI**는 개발자의 편의를 위해 `starlette.responses`를 `fastapi.responses`로 제공합니다. 그러나 대부분의 가능한 응답은 Starlette에서 직접 제공합니다. + +/// + +## 사용자 정의 `Response` 반환하기 +위 예제는 필요한 모든 부분을 보여주지만, 아직 유용하지는 않습니다. 사실 데이터를 직접 반환하면 **FastAPI**가 이를 `JSONResponse`에 넣고 `dict`로 변환하는 등 모든 작업을 자동으로 처리합니다. + +이제, 사용자 정의 응답을 반환하는 방법을 알아보겠습니다. + +예를 들어 XML 응답을 반환하고 싶다고 가정해보겠습니다. + +XML 내용을 문자열에 넣고, 이를 `Response`에 넣어 반환할 수 있습니다: + +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} + +## 참고 사항 +`Response`를 직접 반환할 때, 그 데이터는 자동으로 유효성 검사되거나, 변환(직렬화)되거나, 문서화되지 않습니다. + +그러나 [OpenAPI에서 추가 응답](additional-responses.md){.internal-link target=_blank}에서 설명된 대로 문서화할 수 있습니다. + +이후 단락에서 자동 데이터 변환, 문서화 등을 사용하면서 사용자 정의 `Response`를 선언하는 방법을 확인할 수 있습니다. diff --git a/docs/ko/docs/advanced/response-headers.md b/docs/ko/docs/advanced/response-headers.md new file mode 100644 index 000000000..e8abe0be2 --- /dev/null +++ b/docs/ko/docs/advanced/response-headers.md @@ -0,0 +1,41 @@ +# 응답 헤더 + +## `Response` 매개변수 사용하기 + +여러분은 *경로 작동 함수*에서 `Response` 타입의 매개변수를 선언할 수 있습니다 (쿠키와 같이 사용할 수 있습니다). + +그런 다음, 여러분은 해당 *임시* 응답 객체에서 헤더를 설정할 수 있습니다. + +{* ../../docs_src/response_headers/tutorial002.py hl[1,7:8] *} + +그 후, 일반적으로 사용하듯이 필요한 객체(`dict`, 데이터베이스 모델 등)를 반환할 수 있습니다. + +`response_model`을 선언한 경우, 반환한 객체를 필터링하고 변환하는 데 여전히 사용됩니다. + +**FastAPI**는 해당 *임시* 응답에서 헤더(쿠키와 상태 코드도 포함)를 추출하여, 여러분이 반환한 값을 포함하는 최종 응답에 `response_model`로 필터링된 값을 넣습니다. + +또한, 종속성에서 `Response` 매개변수를 선언하고 그 안에서 헤더(및 쿠키)를 설정할 수 있습니다. + +## `Response` 직접 반환하기 + +`Response`를 직접 반환할 때에도 헤더를 추가할 수 있습니다. + +[응답을 직접 반환하기](response-directly.md){.internal-link target=_blank}에서 설명한 대로 응답을 생성하고, 헤더를 추가 매개변수로 전달하세요. + +{* ../../docs_src/response_headers/tutorial001.py hl[10:12] *} + +/// note | 기술적 세부사항 + +`from starlette.responses import Response`나 `from starlette.responses import JSONResponse`를 사용할 수도 있습니다. + +**FastAPI**는 `starlette.responses`를 `fastapi.responses`로 개발자의 편의를 위해 직접 제공하지만, 대부분의 응답은 Starlette에서 직접 제공됩니다. + +그리고 `Response`는 헤더와 쿠키를 설정하는 데 자주 사용될 수 있으므로, **FastAPI**는 `fastapi.Response`로도 이를 제공합니다. + +/// + +## 커스텀 헤더 + +‘X-’ 접두어를 사용하여 커스텀 사설 헤더를 추가할 수 있습니다. + +하지만, 여러분이 브라우저에서 클라이언트가 볼 수 있기를 원하는 커스텀 헤더가 있는 경우, CORS 설정에 이를 추가해야 합니다([CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md){.internal-link target=_blank}에서 자세히 알아보세요). `expose_headers` 매개변수를 사용하여 Starlette의 CORS 설명서에 문서화된 대로 설정할 수 있습니다. diff --git a/docs/ko/docs/advanced/templates.md b/docs/ko/docs/advanced/templates.md new file mode 100644 index 000000000..4cb4cbe0d --- /dev/null +++ b/docs/ko/docs/advanced/templates.md @@ -0,0 +1,127 @@ +# 템플릿 + +**FastAPI**와 함께 원하는 어떤 템플릿 엔진도 사용할 수 있습니다. + +일반적인 선택은 Jinja2로, Flask와 다른 도구에서도 사용됩니다. + +설정을 쉽게 할 수 있는 유틸리티가 있으며, 이를 **FastAPI** 애플리케이션에서 직접 사용할 수 있습니다(Starlette 제공). + +## 의존성 설치 + +가상 환경을 생성하고(virtual environment{.internal-link target=_blank}), 활성화한 후 jinja2를 설치해야 합니다: + + +
+ +```console +$ pip install jinja2 + +---> 100% +``` + +
+ +## 사용하기 `Jinja2Templates` + +* `Jinja2Templates`를 가져옵니다. +* 나중에 재사용할 수 있는 `templates` 객체를 생성합니다. +* 템플릿을 반환할 경로 작업에 `Request` 매개변수를 선언합니다. +* 생성한 `templates`를 사용하여 `TemplateResponse`를 렌더링하고 반환합니다. 템플릿의 이름, 요청 객체 및 Jinja2 템플릿 내에서 사용될 키-값 쌍이 포함된 "컨텍스트" 딕셔너리도 전달합니다. + + +```Python hl_lines="4 11 15-18" +{!../../docs_src/templates/tutorial001.py!} +``` + +/// note | 참고 + +FastAPI 0.108.0 이전과 Starlette 0.29.0에서는 `name`이 첫 번째 매개변수였습니다. + +또한 이전 버전에서는 `request` 객체가 Jinja2의 컨텍스트에서 키-값 쌍의 일부로 전달되었습니다. + +/// + +/// tip | 팁 + +`response_class=HTMLResponse`를 선언하면 문서 UI 응답이 HTML임을 알 수 있습니다. + +/// + +/// note | 기술 세부 사항 +`from starlette.templating import Jinja2Templates`를 사용할 수도 있습니다. + +**FastAPI**는 개발자를 위한 편리함으로 `fastapi.templating` 대신 `starlette.templating`을 제공합니다. 하지만 대부분의 사용 가능한 응답은 Starlette에서 직접 옵니다. `Request` 및 `StaticFiles`도 마찬가지입니다. +/// + +## 템플릿 작성하기 + +그런 다음 `templates/item.html`에 템플릿을 작성할 수 있습니다. 예를 들면: + +```jinja hl_lines="7" +{!../../docs_src/templates/templates/item.html!} +``` + +### 템플릿 컨텍스트 값 + +다음과 같은 HTML에서: + +{% raw %} + +```jinja +Item ID: {{ id }} +``` + +{% endraw %} + +...이는 전달한 "컨텍스트" `dict`에서 가져온 `id`를 표시합니다: + +```Python +{"id": id} +``` + +예를 들어, ID가 `42`일 경우, 이는 다음과 같이 렌더링됩니다: + +```html +Item ID: 42 +``` + +### 템플릿 `url_for` 인수 + +템플릿 내에서 `url_for()`를 사용할 수도 있으며, 이는 *경로 작업 함수*에서 사용될 인수와 동일한 인수를 받습니다. + +따라서 다음과 같은 부분에서: + +{% raw %} + +```jinja + +``` + +{% endraw %} + +...이는 *경로 작업 함수* `read_item(id=id)`가 처리할 동일한 URL로 링크를 생성합니다. + +예를 들어, ID가 `42`일 경우, 이는 다음과 같이 렌더링됩니다: +```html + +``` + +## 템플릿과 정적 파일 + +템플릿 내에서 `url_for()`를 사용할 수 있으며, 예를 들어 `name="static"`으로 마운트한 `StaticFiles`와 함께 사용할 수 있습니다. + +```jinja hl_lines="4" +{!../../docs_src/templates/templates/item.html!} +``` + +이 예제에서는 `static/styles.css`에 있는 CSS 파일에 연결될 것입니다: + +```CSS hl_lines="4" +{!../../docs_src/templates/static/styles.css!} +``` + +그리고 `StaticFiles`를 사용하고 있으므로, 해당 CSS 파일은 **FastAPI** 애플리케이션에서 `/static/styles.css` URL로 자동 제공됩니다. + +## 더 많은 세부 사항 + +템플릿 테스트를 포함한 더 많은 세부 사항은 Starlette의 템플릿 문서를 확인하세요. diff --git a/docs/ko/docs/advanced/testing-dependencies.md b/docs/ko/docs/advanced/testing-dependencies.md new file mode 100644 index 000000000..780e19431 --- /dev/null +++ b/docs/ko/docs/advanced/testing-dependencies.md @@ -0,0 +1,53 @@ +# 테스트 의존성 오버라이드 + +## 테스트 중 의존성 오버라이드하기 + +테스트를 진행하다 보면 의존성을 오버라이드해야 하는 경우가 있습니다. + +원래 의존성을 실행하고 싶지 않을 수도 있습니다(또는 그 의존성이 가지고 있는 하위 의존성까지도 실행되지 않길 원할 수 있습니다). + +대신, 테스트 동안(특정 테스트에서만) 사용될 다른 의존성을 제공하고, 원래 의존성이 사용되던 곳에서 사용할 수 있는 값을 제공하기를 원할 수 있습니다. + +### 사용 사례: 외부 서비스 + +예를 들어, 외부 인증 제공자를 호출해야 하는 경우를 생각해봅시다. + +토큰을 보내면 인증된 사용자를 반환합니다. + +제공자는 요청당 요금을 부과할 수 있으며, 테스트를 위해 고정된 모의 사용자가 있는 경우보다 호출하는 데 시간이 더 걸릴 수 있습니다. + +외부 제공자를 한 번만 테스트하고 싶을 수도 있지만 테스트를 실행할 때마다 반드시 호출할 필요는 없습니다. + +이 경우 해당 공급자를 호출하는 종속성을 오버라이드하고 테스트에 대해서만 모의 사용자를 반환하는 사용자 지정 종속성을 사용할 수 있습니다. + +### `app.dependency_overrides` 속성 사용하기 + +이런 경우를 위해 **FastAPI** 응용 프로그램에는 `app.dependency_overrides`라는 속성이 있습니다. 이는 간단한 `dict`입니다. + +테스트를 위해 의존성을 오버라이드하려면, 원래 의존성(함수)을 키로 설정하고 오버라이드할 의존성(다른 함수)을 값으로 설정합니다. + +그럼 **FastAPI**는 원래 의존성 대신 오버라이드된 의존성을 호출합니다. + +{* ../../docs_src/dependency_testing/tutorial001_an_py310.py hl[26:27,30] *} + +/// tip | 팁 + +**FastAPI** 애플리케이션 어디에서든 사용된 의존성에 대해 오버라이드를 설정할 수 있습니다. + +원래 의존성은 *경로 동작 함수*, *경로 동작 데코레이터*(반환값을 사용하지 않는 경우), `.include_router()` 호출 등에서 사용될 수 있습니다. + +FastAPI는 여전히 이를 오버라이드할 수 있습니다. + +/// + +그런 다음, `app.dependency_overrides`를 빈 `dict`로 설정하여 오버라이드를 재설정(제거)할 수 있습니다: + +```python +app.dependency_overrides = {} +``` + +/// tip | 팁 + +특정 테스트에서만 의존성을 오버라이드하고 싶다면, 테스트 시작 시(테스트 함수 내부) 오버라이드를 설정하고 테스트 종료 시(테스트 함수 끝부분) 재설정하면 됩니다. + +/// diff --git a/docs/ko/docs/advanced/testing-events.md b/docs/ko/docs/advanced/testing-events.md new file mode 100644 index 000000000..502762f23 --- /dev/null +++ b/docs/ko/docs/advanced/testing-events.md @@ -0,0 +1,5 @@ +# 이벤트 테스트: 시작 - 종료 + +테스트에서 이벤트 핸들러(`startup` 및 `shutdown`)를 실행해야 하는 경우, `with` 문과 함께 `TestClient`를 사용할 수 있습니다. + +{* ../../docs_src/app_testing/tutorial003.py hl[9:12,20:24] *} diff --git a/docs/ko/docs/advanced/testing-websockets.md b/docs/ko/docs/advanced/testing-websockets.md new file mode 100644 index 000000000..9f3b4a451 --- /dev/null +++ b/docs/ko/docs/advanced/testing-websockets.md @@ -0,0 +1,13 @@ +# WebSocket 테스트하기 + +`TestClient`를 사용하여 WebSocket을 테스트할 수 있습니다. + +이를 위해 `with` 문에서 `TestClient`를 사용하여 WebSocket에 연결합니다: + +{* ../../docs_src/app_testing/tutorial002.py hl[27:31] *} + +/// note | 참고 + +자세한 내용은 Starlette의 WebSocket 테스트에 관한 설명서를 참고하시길 바랍니다. + +/// diff --git a/docs/ko/docs/advanced/using-request-directly.md b/docs/ko/docs/advanced/using-request-directly.md new file mode 100644 index 000000000..bfa4fa4db --- /dev/null +++ b/docs/ko/docs/advanced/using-request-directly.md @@ -0,0 +1,56 @@ +# `Request` 직접 사용하기 + +지금까지 요청에서 필요한 부분을 각 타입으로 선언하여 사용해 왔습니다. + +다음과 같은 곳에서 데이터를 가져왔습니다: + +* 경로의 파라미터로부터. +* 헤더. +* 쿠키. +* 기타 등등. + +이렇게 함으로써, **FastAPI**는 데이터를 검증하고 변환하며, API에 대한 문서를 자동화로 생성합니다. + +하지만 `Request` 객체에 직접 접근해야 하는 상황이 있을 수 있습니다. + +## `Request` 객체에 대한 세부 사항 + +**FastAPI**는 실제로 내부에 **Starlette**을 사용하며, 그 위에 여러 도구를 덧붙인 구조입니다. 따라서 여러분이 필요할 때 Starlette의 `Request` 객체를 직접 사용할 수 있습니다. + +`Request` 객체에서 데이터를 직접 가져오는 경우(예: 본문을 읽기)에는 FastAPI가 해당 데이터를 검증하거나 변환하지 않으며, 문서화(OpenAPI를 통한 문서 자동화(로 생성된) API 사용자 인터페이스)도 되지 않습니다. + +그러나 다른 매개변수(예: Pydantic 모델을 사용한 본문)는 여전히 검증, 변환, 주석 추가 등이 이루어집니다. + +하지만 특정한 경우에는 `Request` 객체에 직접 접근하는 것이 유용할 수 있습니다. + +## `Request` 객체를 직접 사용하기 + +여러분이 클라이언트의 IP 주소/호스트 정보를 *경로 작동 함수* 내부에서 가져와야 한다고 가정해 보겠습니다. + +이를 위해서는 요청에 직접 접근해야 합니다. + +{* ../../docs_src/using_request_directly/tutorial001.py hl[1,7:8] *} + +*경로 작동 함수* 매개변수를 `Request` 타입으로 선언하면 **FastAPI**가 해당 매개변수에 `Request` 객체를 전달하는 것을 알게 됩니다. + +/// tip | 팁 + +이 경우, 요청 매개변수와 함께 경로 매개변수를 선언한 것을 볼 수 있습니다. + +따라서, 경로 매개변수는 추출되고 검증되며 지정된 타입으로 변환되고 OpenAPI로 주석이 추가됩니다. + +이와 같은 방식으로, 다른 매개변수들을 평소처럼 선언하면서, 부가적으로 `Request`도 가져올 수 있습니다. + +/// + +## `Request` 설명서 + +여러분은 `Request` 객체에 대한 더 자세한 내용을 공식 Starlette 설명서 사이트에서 읽어볼 수 있습니다. + +/// note | 기술 세부사항 + +`from starlette.requests import Request`를 사용할 수도 있습니다. + +**FastAPI**는 여러분(개발자)를 위한 편의를 위해 이를 직접 제공하지만, 실제로는 Starlette에서 가져온 것입니다. + +/// diff --git a/docs/ko/docs/advanced/websockets.md b/docs/ko/docs/advanced/websockets.md new file mode 100644 index 000000000..fa60a428b --- /dev/null +++ b/docs/ko/docs/advanced/websockets.md @@ -0,0 +1,186 @@ +# WebSockets + +여러분은 **FastAPI**에서 WebSockets를 사용할 수 있습니다. + +## `WebSockets` 설치 + +[가상 환경](../virtual-environments.md){.internal-link target=_blank)를 생성하고 활성화한 다음, `websockets`를 설치하세요: + +
+ +```console +$ pip install websockets + +---> 100% +``` + +
+ +## WebSockets 클라이언트 + +### 프로덕션 환경에서 + +여러분의 프로덕션 시스템에서는 React, Vue.js 또는 Angular와 같은 최신 프레임워크로 생성된 프런트엔드를 사용하고 있을 가능성이 높습니다. + +백엔드와 WebSockets을 사용해 통신하려면 아마도 프런트엔드의 유틸리티를 사용할 것입니다. + +또는 네이티브 코드로 WebSocket 백엔드와 직접 통신하는 네이티브 모바일 응용 프로그램을 가질 수도 있습니다. + +혹은 WebSocket 엔드포인트와 통신할 수 있는 다른 방법이 있을 수도 있습니다. + +--- + +하지만 이번 예제에서는 일부 자바스크립트를 포함한 간단한 HTML 문서를 사용하겠습니다. 모든 것을 긴 문자열 안에 넣습니다. + +물론, 이는 최적의 방법이 아니며 프로덕션 환경에서는 사용하지 않을 것입니다. + +프로덕션 환경에서는 위에서 설명한 옵션 중 하나를 사용하는 것이 좋습니다. + +그러나 이는 WebSockets의 서버 측에 집중하고 동작하는 예제를 제공하는 가장 간단한 방법입니다: + +{* ../../docs_src/websockets/tutorial001.py hl[2,6:38,41:43] *} + +## `websocket` 생성하기 + +**FastAPI** 응용 프로그램에서 `websocket`을 생성합니다: + +{* ../../docs_src/websockets/tutorial001.py hl[1,46:47] *} + +/// note | 기술적 세부사항 + +`from starlette.websockets import WebSocket`을 사용할 수도 있습니다. + +**FastAPI**는 개발자를 위한 편의를 위해 동일한 `WebSocket`을 직접 제공합니다. 하지만 이는 Starlette에서 가져옵니다. + +/// + +## 메시지를 대기하고 전송하기 + +WebSocket 경로에서 메시지를 대기(`await`)하고 전송할 수 있습니다. + +{* ../../docs_src/websockets/tutorial001.py hl[48:52] *} + +여러분은 이진 데이터, 텍스트, JSON 데이터를 받을 수 있고 전송할 수 있습니다. + +## 시도해보기 + +파일 이름이 `main.py`라고 가정하고 응용 프로그램을 실행합니다: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +브라우저에서 http://127.0.0.1:8000을 열어보세요. + +간단한 페이지가 나타날 것입니다: + + + +입력창에 메시지를 입력하고 전송할 수 있습니다: + + + +**FastAPI** WebSocket 응용 프로그램이 응답을 돌려줄 것입니다: + + + +여러 메시지를 전송(그리고 수신)할 수 있습니다: + + + +모든 메시지는 동일한 WebSocket 연결을 사용합니다. + +## `Depends` 및 기타 사용하기 + +WebSocket 엔드포인트에서 `fastapi`에서 다음을 가져와 사용할 수 있습니다: + +* `Depends` +* `Security` +* `Cookie` +* `Header` +* `Path` +* `Query` + +이들은 다른 FastAPI 엔드포인트/*경로 작동*과 동일하게 동작합니다: + +{* ../../docs_src/websockets/tutorial002_an_py310.py hl[68:69,82] *} + +/// info | 정보 + +WebSocket에서는 `HTTPException`을 발생시키는 것이 적합하지 않습니다. 대신 `WebSocketException`을 발생시킵니다. + +명세서에 정의된 유효한 코드를 사용하여 종료 코드를 설정할 수 있습니다. + +/// + +### 종속성을 가진 WebSockets 테스트 + +파일 이름이 `main.py`라고 가정하고 응용 프로그램을 실행합니다: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +브라우저에서 http://127.0.0.1:8000을 열어보세요. + +다음과 같은 값을 설정할 수 있습니다: + +* 경로에 사용된 "Item ID". +* 쿼리 매개변수로 사용된 "Token". + +/// tip | 팁 + +쿼리 `token`은 종속성에 의해 처리됩니다. + +/// + +이제 WebSocket에 연결하고 메시지를 전송 및 수신할 수 있습니다: + + + +## 연결 해제 및 다중 클라이언트 처리 + +WebSocket 연결이 닫히면, `await websocket.receive_text()`가 `WebSocketDisconnect` 예외를 발생시킵니다. 이를 잡아 처리할 수 있습니다: + +{* ../../docs_src/websockets/tutorial003_py39.py hl[79:81] *} + +테스트해보기: + +* 여러 브라우저 탭에서 앱을 엽니다. +* 각 탭에서 메시지를 작성합니다. +* 한 탭을 닫아보세요. + +`WebSocketDisconnect` 예외가 발생하며, 다른 모든 클라이언트가 다음과 같은 메시지를 수신합니다: + +``` +Client #1596980209979 left the chat +``` + +/// tip | 팁 + +위 응용 프로그램은 여러 WebSocket 연결에 메시지를 브로드캐스트하는 방법을 보여주는 간단한 예제입니다. + +그러나 모든 것을 메모리의 단일 리스트로 처리하므로, 프로세스가 실행 중인 동안만 동작하며 단일 프로세스에서만 작동합니다. + +FastAPI와 쉽게 통합할 수 있으면서 더 견고하고 Redis, PostgreSQL 등을 지원하는 도구를 찾고 있다면, encode/broadcaster를 확인하세요. + +/// + +## 추가 정보 + +다음 옵션에 대한 자세한 내용을 보려면 Starlette의 문서를 확인하세요: + +* `WebSocket` 클래스. +* 클래스 기반 WebSocket 처리. diff --git a/docs/ko/docs/advanced/wsgi.md b/docs/ko/docs/advanced/wsgi.md new file mode 100644 index 000000000..3e9de3e6c --- /dev/null +++ b/docs/ko/docs/advanced/wsgi.md @@ -0,0 +1,35 @@ +# WSGI 포함하기 - Flask, Django 그 외 + +[서브 응용 프로그램 - 마운트](sub-applications.md){.internal-link target=_blank}, [프록시 뒤편에서](behind-a-proxy.md){.internal-link target=_blank}에서 보았듯이 WSGI 응용 프로그램들을 다음과 같이 마운트 할 수 있습니다. + +`WSGIMiddleware`를 사용하여 WSGI 응용 프로그램(예: Flask, Django 등)을 감쌀 수 있습니다. + +## `WSGIMiddleware` 사용하기 + +`WSGIMiddleware`를 불러와야 합니다. + +그런 다음, WSGI(예: Flask) 응용 프로그램을 미들웨어로 포장합니다. + +그 후, 해당 경로에 마운트합니다. + +{* ../../docs_src/wsgi/tutorial001.py hl[2:3,23] *} + +## 확인하기 + +이제 `/v1/` 경로에 있는 모든 요청은 Flask 응용 프로그램에서 처리됩니다. + +그리고 나머지는 **FastAPI**에 의해 처리됩니다. + +실행하면 http://localhost:8000/v1/으로 이동해서 Flask의 응답을 볼 수 있습니다: + +```txt +Hello, World from Flask! +``` + +그리고 다음으로 이동하면 http://localhost:8000/v2 Flask의 응답을 볼 수 있습니다: + +```JSON +{ + "message": "Hello World" +} +``` diff --git a/docs/ko/docs/async.md b/docs/ko/docs/async.md index 47dbaa1b0..fa0d20488 100644 --- a/docs/ko/docs/async.md +++ b/docs/ko/docs/async.md @@ -2,7 +2,7 @@ *경로 작동 함수*에서의 `async def` 문법에 대한 세부사항과 비동기 코드, 동시성 및 병렬성에 대한 배경 -## 바쁘신 경우 +## 바쁘신 경우 요약 @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! note "참고" - `async def`로 생성된 함수 내부에서만 `await`를 사용할 수 있습니다. +/// note | 참고 + +`async def`로 생성된 함수 내부에서만 `await`를 사용할 수 있습니다. + +/// --- @@ -263,7 +266,7 @@ CPU에 묶인 연산에 관한 흔한 예시는 복잡한 수학 처리를 필 파이썬이 **데이터 사이언스**, 머신러닝과 특히 딥러닝에 의 주된 언어라는 간단한 사실에 더해서, 이것은 FastAPI를 데이터 사이언스 / 머신러닝 웹 API와 응용프로그램에 (다른 것들보다) 좋은 선택지가 되게 합니다. -배포시 병렬을 어떻게 가능하게 하는지 알고싶다면, [배포](/ko/deployment){.internal-link target=_blank}문서를 참고하십시오. +배포시 병렬을 어떻게 가능하게 하는지 알고싶다면, [배포](deployment/index.md){.internal-link target=_blank}문서를 참고하십시오. ## `async`와 `await` @@ -366,12 +369,15 @@ FastAPI를 사용하지 않더라도, 높은 호환성 및 I/O를 수행하는 코드를 사용하지 않는 한 `async def`를 사용하는 편이 더 낫습니다. -하지만 두 경우 모두, FastAPI가 당신이 전에 사용하던 프레임워크보다 [더 빠를](/#performance){.internal-link target=_blank} (최소한 비견될) 확률이 높습니다. +하지만 두 경우 모두, FastAPI가 당신이 전에 사용하던 프레임워크보다 [더 빠를](index.md#_11){.internal-link target=_blank} (최소한 비견될) 확률이 높습니다. ### 의존성 @@ -401,4 +407,4 @@ FastAPI를 사용하지 않더라도, 높은 호환성 및 가장 빠른 Python 프레임워크 중 하나로 실행되며, Starlette와 Uvicorn 자체(내부적으로 FastAPI가 사용하는 도구)보다 조금 아래에 위치합니다. + +그러나 벤치마크와 비교를 확인할 때 다음 사항을 염두에 두어야 합니다. + +## 벤치마크와 속도 + +벤치마크를 확인할 때, 일반적으로 여러 가지 유형의 도구가 동등한 것으로 비교되는 것을 볼 수 있습니다. + +특히, Uvicorn, Starlette, FastAPI가 함께 비교되는 경우가 많습니다(다른 여러 도구와 함께). + +도구가 해결하는 문제가 단순할수록 성능이 더 좋아집니다. 그리고 대부분의 벤치마크는 도구가 제공하는 추가 기능을 테스트하지 않습니다. + +계층 구조는 다음과 같습니다: + +* **Uvicorn**: ASGI 서버 + * **Starlette**: (Uvicorn 사용) 웹 마이크로 프레임워크 + * **FastAPI**: (Starlette 사용) API 구축을 위한 데이터 검증 등 여러 추가 기능이 포함된 API 마이크로 프레임워크 + +* **Uvicorn**: + * 서버 자체 외에는 많은 추가 코드가 없기 때문에 최고의 성능을 발휘합니다. + * 직접 Uvicorn으로 응용 프로그램을 작성하지는 않을 것입니다. 즉, 사용자의 코드에는 적어도 Starlette(또는 **FastAPI**)에서 제공하는 모든 코드가 포함되어야 합니다. 그렇게 하면 최종 응용 프로그램은 프레임워크를 사용하고 앱 코드와 버그를 최소화하는 것과 동일한 오버헤드를 갖게 됩니다. + * Uvicorn을 비교할 때는 Daphne, Hypercorn, uWSGI 등의 응용 프로그램 서버와 비교하세요. +* **Starlette**: + * Uvicorn 다음으로 좋은 성능을 발휘합니다. 사실 Starlette는 Uvicorn을 사용하여 실행됩니다. 따라서 더 많은 코드를 실행해야 하기 때문에 Uvicorn보다 "느려질" 수밖에 없습니다. + * 하지만 경로 기반 라우팅 등 간단한 웹 응용 프로그램을 구축할 수 있는 도구를 제공합니다. + * Starlette를 비교할 때는 Sanic, Flask, Django 등의 웹 프레임워크(또는 마이크로 프레임워크)와 비교하세요. +* **FastAPI**: + * Starlette가 Uvicorn을 사용하므로 Uvicorn보다 빨라질 수 없는 것과 마찬가지로, **FastAPI**는 Starlette를 사용하므로 더 빠를 수 없습니다. + * FastAPI는 Starlette에 추가적으로 더 많은 기능을 제공합니다. API를 구축할 때 거의 항상 필요한 데이터 검증 및 직렬화와 같은 기능들이 포함되어 있습니다. 그리고 이를 사용하면 문서 자동화 기능도 제공됩니다(문서 자동화는 응용 프로그램 실행 시 오버헤드를 추가하지 않고 시작 시 생성됩니다). + * FastAPI를 사용하지 않고 직접 Starlette(또는 Sanic, Flask, Responder 등)를 사용했다면 데이터 검증 및 직렬화를 직접 구현해야 합니다. 따라서 최종 응용 프로그램은 FastAPI를 사용한 것과 동일한 오버헤드를 가지게 될 것입니다. 많은 경우 데이터 검증 및 직렬화가 응용 프로그램에서 작성된 코드 중 가장 많은 부분을 차지합니다. + * 따라서 FastAPI를 사용함으로써 개발 시간, 버그, 코드 라인을 줄일 수 있으며, FastAPI를 사용하지 않았을 때와 동일하거나 더 나은 성능을 얻을 수 있습니다(코드에서 모두 구현해야 하기 때문에). + * FastAPI를 비교할 때는 Flask-apispec, NestJS, Molten 등 데이터 검증, 직렬화 및 문서화가 통합된 자동 데이터 검증, 직렬화 및 문서화를 제공하는 웹 응용 프로그램 프레임워크(또는 도구 집합)와 비교하세요. diff --git a/docs/ko/docs/deployment/cloud.md b/docs/ko/docs/deployment/cloud.md index f2b965a91..2d6938e20 100644 --- a/docs/ko/docs/deployment/cloud.md +++ b/docs/ko/docs/deployment/cloud.md @@ -14,4 +14,3 @@ * Platform.sh * Porter -* Deta diff --git a/docs/ko/docs/deployment/docker.md b/docs/ko/docs/deployment/docker.md new file mode 100644 index 000000000..e8b2746c5 --- /dev/null +++ b/docs/ko/docs/deployment/docker.md @@ -0,0 +1,731 @@ +# 컨테이너의 FastAPI - 도커 + +FastAPI 어플리케이션을 배포할 때 일반적인 접근 방법은 **리눅스 컨테이너 이미지**를 생성하는 것입니다. 이 방법은 주로 **도커**를 사용해 이루어집니다. 그런 다음 해당 컨테이너 이미지를 몇가지 방법으로 배포할 수 있습니다. + +리눅스 컨테이너를 사용하는 데에는 **보안**, **반복 가능성**, **단순함** 등의 장점이 있습니다. + +/// tip | 팁 + +시간에 쫓기고 있고 이미 이런것들을 알고 있다면 [`Dockerfile`👇](#build-a-docker-image-for-fastapi)로 점프할 수 있습니다. + +/// + +
+도커파일 미리보기 👀 + +```Dockerfile +FROM python:3.9 + +WORKDIR /code + +COPY ./requirements.txt /code/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +COPY ./app /code/app + +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] + +# If running behind a proxy like Nginx or Traefik add --proxy-headers +# CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80", "--proxy-headers"] +``` + +
+ +## 컨테이너란 + +컨테이너(주로 리눅스 컨테이너)는 어플리케이션의 의존성과 필요한 파일들을 모두 패키징하는 매우 **가벼운** 방법입니다. 컨테이너는 같은 시스템에 있는 다른 컨테이너(다른 어플리케이션이나 요소들)와 독립적으로 유지됩니다. + +리눅스 컨테이너는 호스트(머신, 가상 머신, 클라우드 서버 등)와 같은 리눅스 커널을 사용해 실행됩니다. 이말은 리눅스 컨테이너가 (전체 운영체제를 모방하는 다른 가상 머신과 비교했을 때) 매우 가볍다는 것을 의미합니다. + +이 방법을 통해, 컨테이너는 직접 프로세스를 실행하는 것과 비슷한 정도의 **적은 자원**을 소비합니다 (가상 머신은 훨씬 많은 자원을 소비할 것입니다). + +컨테이너는 또한 그들만의 **독립된** 실행 프로세스 (일반적으로 하나의 프로세스로 충분합니다), 파일 시스템, 그리고 네트워크를 가지므로 배포, 보안, 개발 및 기타 과정을 단순화 합니다. + +## 컨테이너 이미지란 + +**컨테이너**는 **컨테이너 이미지**를 실행한 것 입니다. + +컨테이너 이미지란 컨테이너에 필요한 모든 파일, 환경 변수 그리고 디폴트 명령/프로그램의 **정적** 버전입니다. 여기서 **정적**이란 말은 컨테이너 **이미지**가 작동되거나 실행되지 않으며, 단지 패키지 파일과 메타 데이터라는 것을 의미합니다. + +저장된 정적 컨텐츠인 **컨테이너 이미지**와 대조되게, **컨테이너**란 보통 실행될 수 있는 작동 인스턴스를 의미합니다. + +**컨테이너**가 (**컨테이너 이미지**로 부터) 시작되고 실행되면, 컨테이너는 파일이나 환경 변수를 생성하거나 변경할 수 있습니다. 이러한 변화는 오직 컨테이너에서만 존재하며, 그 기반이 되는 컨테이너 이미지에는 지속되지 않습니다 (즉 디스크에는 저장되지 않습니다). + +컨테이너 이미지는 **프로그램** 파일과 컨텐츠, 즉 `python`과 어떤 파일 `main.py`에 비교할 수 있습니다. + +그리고 (**컨테이너 이미지**와 대비해서) **컨테이너**는 이미지의 실제 실행 인스턴스로 **프로세스**에 비교할 수 있습니다. 사실, 컨테이너는 **프로세스 러닝**이 있을 때만 실행됩니다 (그리고 보통 하나의 프로세스 입니다). 컨테이너는 내부에서 실행되는 프로세스가 없으면 종료됩니다. + +## 컨테이너 이미지 + +도커는 **컨테이너 이미지**와 **컨테이너**를 생성하고 관리하는데 주요 도구 중 하나가 되어왔습니다. + +그리고 도커 허브에 다양한 도구, 환경, 데이터베이스, 그리고 어플리케이션에 대해 미리 만들어진 **공식 컨테이너 이미지**가 공개되어 있습니다. + +예를 들어, 공식 파이썬 이미지가 있습니다. + +또한 다른 대상, 예를 들면 데이터베이스를 위한 이미지들도 있습니다: + +* PostgreSQL +* MySQL +* MongoDB +* Redis 등 + +미리 만들어진 컨테이너 이미지를 사용하면 서로 다른 도구들을 **결합**하기 쉽습니다. 대부분의 경우에, **공식 이미지들**을 사용하고 환경 변수를 통해 설정할 수 있습니다. + +이런 방법으로 대부분의 경우에 컨테이너와 도커에 대해 배울 수 있으며 다양한 도구와 요소들에 대한 지식을 재사용할 수 있습니다. + +따라서, 서로 다른 **다중 컨테이너**를 생성한 다음 이들을 연결할 수 있습니다. 예를 들어 데이터베이스, 파이썬 어플리케이션, 리액트 프론트엔드 어플리케이션을 사용하는 웹 서버에 대한 컨테이너를 만들어 이들의 내부 네트워크로 각 컨테이너를 연결할 수 있습니다. + +모든 컨테이너 관리 시스템(도커나 쿠버네티스)은 이러한 네트워킹 특성을 포함하고 있습니다. + +## 컨테이너와 프로세스 + +**컨테이너 이미지**는 보통 **컨테이너**를 시작하기 위해 필요한 메타데이터와 디폴트 커맨드/프로그램과 그 프로그램에 전달하기 위한 파라미터들을 포함합니다. 이는 커맨드 라인에서 프로그램을 실행할 때 필요한 값들과 유사합니다. + +**컨테이너**가 시작되면, 해당 커맨드/프로그램이 실행됩니다 (그러나 다른 커맨드/프로그램을 실행하도록 오버라이드 할 수 있습니다). + +컨테이너는 **메인 프로세스**(커맨드 또는 프로그램)이 실행되는 동안 실행됩니다. + +컨테이너는 일반적으로 **단일 프로세스**를 가지고 있지만, 메인 프로세스의 서브 프로세스를 시작하는 것도 가능하며, 이 방법으로 하나의 컨테이너에 **다중 프로세스**를 가질 수 있습니다. + +그러나 **최소한 하나의 실행중인 프로세스**를 가지지 않고서는 실행중인 컨테이너를 가질 수 없습니다. 만약 메인 프로세스가 중단되면, 컨테이너도 중단됩니다. + +## FastAPI를 위한 도커 이미지 빌드하기 + +이제 무언가를 만들어 봅시다! 🚀 + +**공식 파이썬** 이미지에 기반하여, FastAPI를 위한 **도커 이미지**를 **맨 처음부터** 생성하는 방법을 보이겠습니다. + +**대부분의 경우**에 다음과 같은 것들을 하게 됩니다. 예를 들면: + +* **쿠버네티스** 또는 유사한 도구 사용하기 +* **라즈베리 파이**로 실행하기 +* 컨테이너 이미지를 실행할 클라우드 서비스 사용하기 등 + +### 요구 패키지 + +일반적으로는 어플리케이션의 특정 파일을 위한 **패키지 요구 조건**이 있을 것입니다. + +그 요구 조건을 **설치**하는 방법은 여러분이 사용하는 도구에 따라 다를 것입니다. + +가장 일반적인 방법은 패키지 이름과 버전이 줄 별로 기록된 `requirements.txt` 파일을 만드는 것입니다. + +버전의 범위를 설정하기 위해서는 [FastAPI 버전들에 대하여](versions.md){.internal-link target=_blank}에 쓰여진 것과 같은 아이디어를 사용합니다. + +예를 들어, `requirements.txt` 파일은 다음과 같을 수 있습니다: + +``` +fastapi>=0.68.0,<0.69.0 +pydantic>=1.8.0,<2.0.0 +uvicorn>=0.15.0,<0.16.0 +``` + +그리고 일반적으로 패키지 종속성은 `pip`로 설치합니다. 예를 들어: + +
+ +```console +$ pip install -r requirements.txt +---> 100% +Successfully installed fastapi pydantic uvicorn +``` + +
+ +/// info | 정보 + +패키지 종속성을 정의하고 설치하기 위한 방법과 도구는 다양합니다. + +나중에 아래 세션에서 Poetry를 사용한 예시를 보이겠습니다. 👇 + +/// + +### **FastAPI** 코드 생성하기 + +* `app` 디렉터리를 생성하고 이동합니다. +* 빈 파일 `__init__.py`을 생성합니다. +* 다음과 같은 `main.py`을 생성합니다: + +```Python +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@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} +``` + +### 도커파일 + +이제 같은 프로젝트 디렉터리에 다음과 같은 파일 `Dockerfile`을 생성합니다: + +```{ .dockerfile .annotate } +# (1) +FROM python:3.9 + +# (2) +WORKDIR /code + +# (3) +COPY ./requirements.txt /code/requirements.txt + +# (4) +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +# (5) +COPY ./app /code/app + +# (6) +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] +``` + +1. 공식 파이썬 베이스 이미지에서 시작합니다. + +2. 현재 워킹 디렉터리를 `/code`로 설정합니다. + + 여기에 `requirements.txt` 파일과 `app` 디렉터리를 위치시킬 것입니다. + +3. 요구 조건과 파일을 `/code` 디렉터리로 복사합니다. + + 처음에는 **오직** 요구 조건이 필요한 파일만 복사하고, 이외의 코드는 그대로 둡니다. + + 이 파일이 **자주 바뀌지 않기 때문에**, 도커는 파일을 탐지하여 이 단계의 **캐시**를 사용하여 다음 단계에서도 캐시를 사용할 수 있도록 합니다. + +4. 요구 조건 파일에 있는 패키지 종속성을 설치합니다. + + `--no-cache-dir` 옵션은 `pip`에게 다운로드한 패키지들을 로컬 환경에 저장하지 않도록 전달합니다. 이는 마치 같은 패키지를 설치하기 위해 오직 `pip`만 다시 실행하면 될 것 같지만, 컨테이너로 작업하는 경우 그렇지는 않습니다. + + /// note | 노트 + + `--no-cache-dir` 는 오직 `pip`와 관련되어 있으며, 도커나 컨테이너와는 무관합니다. + + /// + + `--upgrade` 옵션은 `pip`에게 설치된 패키지들을 업데이트하도록 합니다. + + 이전 단계에서 파일을 복사한 것이 **도커 캐시**에 의해 탐지되기 때문에, 이 단계에서도 가능한 한 **도커 캐시**를 사용하게 됩니다. + + 이 단계에서 캐시를 사용하면 **매번** 모든 종속성을 다운로드 받고 설치할 필요가 없어, 개발 과정에서 이미지를 지속적으로 생성하는 데에 드는 **시간**을 많이 **절약**할 수 있습니다. + +5. `/code` 디렉터리에 `./app` 디렉터리를 복사합니다. + + **자주 변경되는** 모든 코드를 포함하고 있기 때문에, 도커 **캐시**는 이 단계나 **이후의 단계에서** 잘 사용되지 않습니다. + + 그러므로 컨테이너 이미지 빌드 시간을 최적화하기 위해 `Dockerfile`의 **거의 끝 부분**에 입력하는 것이 중요합니다. + +6. `uvicorn` 서버를 실행하기 위해 **커맨드**를 설정합니다. + + `CMD`는 문자열 리스트를 입력받고, 각 문자열은 커맨드 라인의 각 줄에 입력할 문자열입니다. + + 이 커맨드는 **현재 워킹 디렉터리**에서 실행되며, 이는 위에서 `WORKDIR /code`로 설정한 `/code` 디렉터리와 같습니다. + + 프로그램이 `/code`에서 시작하고 그 속에 `./app` 디렉터리가 여러분의 코드와 함께 들어있기 때문에, **Uvicorn**은 이를 보고 `app`을 `app.main`으로부터 **불러 올** 것입니다. + +/// tip | 팁 + +각 코드 라인을 코드의 숫자 버블을 클릭하여 리뷰할 수 있습니다. 👆 + +/// + +이제 여러분은 다음과 같은 디렉터리 구조를 가지고 있을 것입니다: + +``` +. +├── app +│   ├── __init__.py +│ └── main.py +├── Dockerfile +└── requirements.txt +``` + +#### TLS 종료 프록시의 배후 + +만약 여러분이 컨테이너를 Nginx 또는 Traefik과 같은 TLS 종료 프록시 (로드 밸런서) 뒤에서 실행하고 있다면, `--proxy-headers` 옵션을 더하는 것이 좋습니다. 이 옵션은 Uvicorn에게 어플리케이션이 HTTPS 등의 뒤에서 실행되고 있으므로 프록시에서 전송된 헤더를 신뢰할 수 있다고 알립니다. + +```Dockerfile +CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"] +``` + +#### 도커 캐시 + +이 `Dockerfile`에는 중요한 트릭이 있는데, 처음에는 **의존성이 있는 파일만** 복사하고, 나머지 코드는 그대로 둡니다. 왜 이런 방법을 써야하는지 설명하겠습니다. + +```Dockerfile +COPY ./requirements.txt /code/requirements.txt +``` + +도커와 다른 도구들은 컨테이너 이미지를 **증가하는 방식으로 빌드**합니다. `Dockerfile`의 맨 윗 부분부터 시작해, 레이어 위에 새로운 레이어를 더하는 방식으로, `Dockerfile`의 각 지시 사항으로 부터 생성된 어떤 파일이든 더해갑니다. + +도커 그리고 이와 유사한 도구들은 이미지 생성 시에 **내부 캐시**를 사용합니다. 만약 어떤 파일이 마지막으로 컨테이너 이미지를 빌드한 때로부터 바뀌지 않았다면, 파일을 다시 복사하여 새로운 레이어를 처음부터 생성하는 것이 아니라, 마지막에 생성했던 **같은 레이어를 재사용**합니다. + +단지 파일 복사를 지양하는 것으로 효율이 많이 향상되는 것은 아니지만, 그 단계에서 캐시를 사용했기 때문에, **다음 단계에서도 마찬가지로 캐시를 사용**할 수 있습니다. 예를 들어, 다음과 같은 의존성을 설치하는 지시 사항을 위한 캐시를 사용할 수 있습니다: + +```Dockerfile +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt +``` + +패키지를 포함하는 파일은 **자주 변경되지 않습니다**. 따라서 해당 파일만 복사하므로서, 도커는 그 단계의 **캐시를 사용**할 수 있습니다. + +그 다음으로, 도커는 **다음 단계에서** 의존성을 다운로드하고 설치하는 **캐시를 사용**할 수 있게 됩니다. 바로 이 과정에서 우리는 **많은 시간을 절약**하게 됩니다. ✨ ...그리고 기다리는 지루함도 피할 수 있습니다. 😪😆 + +패키지 의존성을 다운로드 받고 설치하는 데이는 **수 분이 걸릴 수 있지만**, **캐시**를 사용하면 최대 **수 초만에** 끝낼 수 있습니다. + +또한 여러분이 개발 과정에서 코드의 변경 사항이 반영되었는지 확인하기 위해 컨테이너 이미지를 계속해서 빌드하면, 절약된 시간은 축적되어 더욱 커질 것입니다. + +그리고 나서 `Dockerfile`의 거의 끝 부분에서, 모든 코드를 복사합니다. 이것이 **가장 빈번하게 변경**되는 부분이며, 대부분의 경우에 이 다음 단계에서는 캐시를 사용할 수 없기 때문에 가장 마지막에 둡니다. + +```Dockerfile +COPY ./app /code/app +``` + +### 도커 이미지 생성하기 + +이제 모든 파일이 제자리에 있으니, 컨테이너 이미지를 빌드합니다. + +* (여러분의 `Dockerfile`과 `app` 디렉터리가 위치한) 프로젝트 디렉터리로 이동합니다. +* FastAPI 이미지를 빌드합니다: + +
+ +```console +$ docker build -t myimage . + +---> 100% +``` + +
+ +/// tip | 팁 + +맨 끝에 있는 `.` 에 주목합시다. 이는 `./`와 동등하며, 도커에게 컨테이너 이미지를 빌드하기 위한 디렉터리를 알려줍니다. + +이 경우에는 현재 디렉터리(`.`)와 같습니다. + +/// + +### 도커 컨테이너 시작하기 + +* 여러분의 이미지에 기반하여 컨테이너를 실행합니다: + +
+ +```console +$ docker run -d --name mycontainer -p 80:80 myimage +``` + +
+ +## 체크하기 + +여러분의 도커 컨테이너 URL에서 실행 사항을 체크할 수 있습니다. 예를 들어: http://192.168.99.100/items/5?q=somequery 또는 http://127.0.0.1/items/5?q=somequery (또는 동일하게, 여러분의 도커 호스트를 이용해서 체크할 수도 있습니다). + +아래와 비슷한 것을 보게 될 것입니다: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +## 인터랙티브 API 문서 + +이제 여러분은 http://192.168.99.100/docs 또는 http://127.0.0.1/docs로 이동할 수 있습니다(또는, 여러분의 도커 호스트를 이용할 수 있습니다). + +여러분은 자동으로 생성된 인터랙티브 API(Swagger UI에서 제공된)를 볼 수 있습니다: + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +## 대안 API 문서 + +또한 여러분은 http://192.168.99.100/redoc 또는 http://127.0.0.1/redoc으로 이동할 수 있습니다(또는, 여러분의 도커 호스트를 이용할 수 있습니다). + +여러분은 자동으로 생성된 대안 문서(ReDoc에서 제공된)를 볼 수 있습니다: + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## 단일 파일 FastAPI로 도커 이미지 생성하기 + +만약 여러분의 FastAPI가 하나의 파일이라면, 예를 들어 `./app` 디렉터리 없이 `main.py` 파일만으로 이루어져 있다면, 파일 구조는 다음과 유사할 것입니다: + +``` +. +├── Dockerfile +├── main.py +└── requirements.txt +``` + +그러면 여러분들은 `Dockerfile` 내에 있는 파일을 복사하기 위해 그저 상응하는 경로를 바꾸기만 하면 됩니다: + +```{ .dockerfile .annotate hl_lines="10 13" } +FROM python:3.9 + +WORKDIR /code + +COPY ./requirements.txt /code/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +# (1) +COPY ./main.py /code/ + +# (2) +CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] +``` + +1. `main.py` 파일을 `/code` 디렉터리로 곧바로 복사합니다(`./app` 디렉터리는 고려하지 않습니다). + +2. Uvicorn을 실행해 `app` 객체를 (`app.main` 대신) `main`으로 부터 불러오도록 합니다. + +그 다음 Uvicorn 커맨드를 조정해서 FastAPI 객체를 불러오는데 `app.main` 대신에 새로운 모듈 `main`을 사용하도록 합니다. + +## 배포 개념 + +이제 컨테이너의 측면에서 [배포 개념](concepts.md){.internal-link target=_blank}에서 다루었던 것과 같은 배포 개념에 대해 이야기해 보겠습니다. + +컨테이너는 주로 어플리케이션을 빌드하고 배포하기 위한 과정을 단순화하는 도구이지만, **배포 개념**에 대한 특정한 접근법을 강요하지 않기 때문에 가능한 배포 전략에는 여러가지가 있습니다. + +**좋은 소식**은 서로 다른 전략들을 포괄하는 배포 개념이 있다는 점입니다. 🎉 + +컨테이너 측면에서 **배포 개념**을 리뷰해 보겠습니다: + +* HTTPS +* 구동하기 +* 재시작 +* 복제 (실행 중인 프로세스 개수) +* 메모리 +* 시작하기 전 단계들 + +## HTTPS + +만약 우리가 FastAPI 어플리케이션을 위한 **컨테이너 이미지**에만 집중한다면 (그리고 나중에 실행될 **컨테이너**에), HTTPS는 일반적으로 다른 도구에 의해 **외부적으로** 다루어질 것 입니다. + +**HTTPS**와 **인증서**의 **자동** 취득을 다루는 것은 다른 컨테이너가 될 수 있는데, 예를 들어 Traefik을 사용하는 것입니다. + +/// tip | 팁 + +Traefik은 도커, 쿠버네티스, 그리고 다른 도구와 통합되어 있어 여러분의 컨테이너를 포함하는 HTTPS를 셋업하고 설정하는 것이 매우 쉽습니다. + +/// + +대안적으로, HTTPS는 클라우드 제공자에 의해 서비스의 일환으로 다루어질 수도 있습니다 (이때도 어플리케이션은 여전히 컨테이너에서 실행될 것입니다). + +## 구동과 재시작 + +여러분의 컨테이너를 **시작하고 실행하는** 데에 일반적으로 사용되는 도구는 따로 있습니다. + +이는 **도커** 자체일 수도 있고, **도커 컴포즈**, **쿠버네티스**, **클라우드 서비스** 등이 될 수 있습니다. + +대부분 (또는 전체) 경우에, 컨테이너를 구동하거나 고장시에 재시작하도록 하는 간단한 옵션이 있습니다. 예를 들어, 도커에서는, 커맨드 라인 옵션 `--restart` 입니다. + +컨테이너를 사용하지 않고서는, 어플리케이션을 구동하고 재시작하는 것이 매우 번거롭고 어려울 수 있습니다. 하지만 **컨테이너를 사용한다면** 대부분의 경우에 이런 기능은 기본적으로 포함되어 있습니다. ✨ + +## 복제 - 프로세스 개수 + +만약 여러분이 **쿠버네티스**와 머신 클러스터, 도커 스왐 모드, 노마드, 또는 다른 여러 머신 위에 분산 컨테이너를 관리하는 복잡한 시스템을 다루고 있다면, 여러분은 각 컨테이너에서 (워커와 함께 사용하는 Gunicorn 같은) **프로세스 매니저** 대신 **클러스터 레벨**에서 **복제를 다루**고 싶을 것입니다. + +쿠버네티스와 같은 분산 컨테이너 관리 시스템 중 일부는 일반적으로 들어오는 요청에 대한 **로드 밸런싱**을 지원하면서 **컨테이너 복제**를 다루는 통합된 방법을 가지고 있습니다. 모두 **클러스터 레벨**에서 말이죠. + +이런 경우에, 여러분은 [위에서 묘사된 것](#dockerfile)처럼 **처음부터 도커 이미지를** 빌드해서, 의존성을 설치하고, Uvicorn 워커를 관리하는 Gunicorn 대신 **단일 Uvicorn 프로세스**를 실행하고 싶을 것입니다. + +### 로드 밸런서 + +컨테이너로 작업할 때, 여러분은 일반적으로 **메인 포트의 상황을 감지하는** 요소를 가지고 있을 것입니다. 이는 **HTTPS**를 다루는 **TLS 종료 프록시**와 같은 다른 컨테이너일 수도 있고, 유사한 다른 도구일 수도 있습니다. + +이 요소가 요청들의 **로드**를 읽어들이고 각 워커에게 (바라건대) **균형적으로** 분배한다면, 이 요소는 일반적으로 **로드 밸런서**라고 불립니다. + +/// tip | 팁 + +HTTPS를 위해 사용된 **TLS 종료 프록시** 요소 또한 **로드 밸런서**가 될 수 있습니다. + +/// + +또한 컨테이너로 작업할 때, 컨테이너를 시작하고 관리하기 위해 사용한 것과 동일한 시스템은 이미 해당 **로드 밸런서**로 부터 여러분의 앱에 해당하는 컨테이너로 **네트워크 통신**(예를 들어, HTTP 요청)을 전송하는 내부적인 도구를 가지고 있을 것입니다 (여기서도 로드 밸런서는 **TLS 종료 프록시**일 수 있습니다). + +### 하나의 로드 밸런서 - 다중 워커 컨테이너 + +**쿠버네티스**나 또는 다른 분산 컨테이너 관리 시스템으로 작업할 때, 시스템 내부의 네트워킹 메커니즘을 이용함으로써 메인 **포트**를 감지하고 있는 단일 **로드 밸런서**는 여러분의 앱에서 실행되고 있는 **여러개의 컨테이너**에 통신(요청들)을 전송할 수 있게 됩니다. + +여러분의 앱에서 실행되고 있는 각각의 컨테이너는 일반적으로 **하나의 프로세스**만 가질 것입니다 (예를 들어, FastAPI 어플리케이션에서 실행되는 하나의 Uvicorn 프로세스처럼). 이 컨테이너들은 모두 같은 것을 실행하는 점에서 **동일한 컨테이너**이지만, 프로세스, 메모리 등은 공유하지 않습니다. 이 방식으로 여러분은 CPU의 **서로 다른 코어들** 또는 **서로 다른 머신들**을 **병렬화**하는 이점을 얻을 수 있습니다. + +또한 **로드 밸런서**가 있는 분산 컨테이너 시스템은 여러분의 앱에 있는 컨테이너 각각에 **차례대로 요청을 분산**시킬 것 입니다. 따라서 각 요청은 여러분의 앱에서 실행되는 여러개의 **복제된 컨테이너들** 중 하나에 의해 다루어질 것 입니다. + +그리고 일반적으로 **로드 밸런서**는 여러분의 클러스터에 있는 *다른* 앱으로 가는 요청들도 다룰 수 있으며 (예를 들어, 다른 도메인으로 가거나 다른 URL 경로 접두사를 가지는 경우), 이 통신들을 클러스터에 있는 *바로 그 다른* 어플리케이션으로 제대로 전송할 수 있습니다. + +### 단일 프로세스를 가지는 컨테이너 + +이 시나리오의 경우, 여러분은 이미 클러스터 레벨에서 복제를 다루고 있을 것이므로 **컨테이너 당 단일 (Uvicorn) 프로세스**를 가지고자 할 것입니다. + +따라서, 여러분은 Gunicorn 이나 Uvicorn 워커, 또는 Uvicorn 워커를 사용하는 Uvicorn 매니저와 같은 프로세스 매니저를 가지고 싶어하지 **않을** 것입니다. 여러분은 컨테이너 당 **단일 Uvicorn 프로세스**를 가지고 싶어할 것입니다 (그러나 아마도 다중 컨테이너를 가질 것입니다). + +이미 여러분이 클러스터 시스템을 관리하고 있으므로, (Uvicorn 워커를 관리하는 Gunicorn 이나 Uvicorn 처럼) 컨테이너 내에 다른 프로세스 매니저를 가지는 것은 **불필요한 복잡성**만 더하게 될 것입니다. + +### 다중 프로세스를 가지는 컨테이너와 특수한 경우들 + +당연한 말이지만, 여러분이 내부적으로 **Uvicorn 워커 프로세스들**를 시작하는 **Gunicorn 프로세스 매니저**를 가지는 단일 컨테이너를 원하는 **특수한 경우**도 있을 것입니다. + +그런 경우에, 여러분들은 **Gunicorn**을 프로세스 매니저로 포함하는 **공식 도커 이미지**를 사용할 수 있습니다. 이 프로세스 매니저는 다중 **Uvicorn 워커 프로세스들**을 실행하며, 디폴트 세팅으로 현재 CPU 코어에 기반하여 자동으로 워커 개수를 조정합니다. 이 사항에 대해서는 아래의 [Gunicorn과 함께하는 공식 도커 이미지 - Uvicorn](#official-docker-image-with-gunicorn-uvicorn)에서 더 다루겠습니다. + +이런 경우에 해당하는 몇가지 예시가 있습니다: + +#### 단순한 앱 + +만약 여러분의 어플리케이션이 **충분히 단순**해서 (적어도 아직은) 프로세스 개수를 파인-튠 할 필요가 없거나 클러스터가 아닌 **단일 서버**에서 실행하고 있다면, 여러분은 컨테이너 내에 프로세스 매니저를 사용하거나 (공식 도커 이미지에서) 자동으로 설정되는 디폴트 값을 사용할 수 있습니다. + +#### 도커 구성 + +여러분은 **도커 컴포즈**로 (클러스터가 아닌) **단일 서버로** 배포할 수 있으며, 이 경우에 공유된 네트워크와 **로드 밸런싱**을 포함하는 (도커 컴포즈로) 컨테이너의 복제를 관리하는 단순한 방법이 없을 수도 있습니다. + +그렇다면 여러분은 **프로세스 매니저**와 함께 내부에 **몇개의 워커 프로세스들**을 시작하는 **단일 컨테이너**를 필요로 할 수 있습니다. + +#### Prometheus와 다른 이유들 + +여러분은 **단일 프로세스**를 가지는 **다중 컨테이너** 대신 **다중 프로세스**를 가지는 **단일 컨테이너**를 채택하는 **다른 이유**가 있을 수 있습니다. + +예를 들어 (여러분의 장치 설정에 따라) Prometheus 익스포터와 같이 같은 컨테이너에 들어오는 **각 요청에 대해** 접근권한을 가지는 도구를 사용할 수 있습니다. + +이 경우에 여러분이 **여러개의 컨테이너들**을 가지고 있다면, Prometheus가 **메트릭을 읽어 들일 때**, 디폴트로 **매번 하나의 컨테이너**(특정 리퀘스트를 관리하는 바로 그 컨테이너)로 부터 읽어들일 것입니다. 이는 모든 복제된 컨테이너에 대해 **축적된 메트릭들**을 읽어들이는 것과 대비됩니다. + +그렇다면 이 경우에는 **다중 프로세스**를 가지는 **하나의 컨테이너**를 두어서 같은 컨테이너에서 모든 내부 프로세스에 대한 Prometheus 메트릭을 수집하는 로컬 도구(예를 들어 Prometheus 익스포터 같은)를 두어서 이 메그릭들을 하나의 컨테이너에 내에서 공유하는 방법이 더 단순할 것입니다. + +--- + +요점은, 이 중의 **어느것도** 여러분들이 반드시 따라야하는 **확정된 사실**이 아니라는 것입니다. 여러분은 이 아이디어들을 **여러분의 고유한 이용 사례를 평가**하는데 사용하고, 여러분의 시스템에 가장 적합한 접근법이 어떤 것인지 결정하며, 다음의 개념들을 관리하는 방법을 확인할 수 있습니다: + +* 보안 - HTTPS +* 구동하기 +* 재시작 +* 복제 (실행 중인 프로세스 개수) +* 메모리 +* 시작하기 전 단계들 + +## 메모리 + +만약 여러분이 **컨테이너 당 단일 프로세스**를 실행한다면, 여러분은 각 컨테이너(복제된 경우에는 여러개의 컨테이너들)에 대해 잘 정의되고, 안정적이며, 제한된 용량의 메모리 소비량을 가지고 있을 것입니다. + +그러면 여러분의 컨테이너 관리 시스템(예를 들어 **쿠버네티스**) 설정에서 앞서 정의된 것과 같은 메모리 제한과 요구사항을 설정할 수 있습니다. 이런 방법으로 **가용 머신**이 필요로하는 메모리와 클러스터에 있는 가용 머신들을 염두에 두고 **컨테이너를 복제**할 수 있습니다. + +만약 여러분의 어플리케이션이 **단순**하다면, 이것은 **문제가 되지 않을** 것이고, 고정된 메모리 제한을 구체화할 필요도 없을 것입니다. 하지만 여러분의 어플리케이션이 (예를 들어 **머신 러닝** 모델같이) **많은 메모리를 소요한다면**, 어플리케이션이 얼마나 많은 양의 메모리를 사용하는지 확인하고 **각 머신에서** 사용하는 **컨테이너의 수**를 조정할 필요가 있습니다 (그리고 필요에 따라 여러분의 클러스터에 머신을 추가할 수 있습니다). + +만약 여러분이 **컨테이너 당 여러개의 프로세스**를 실행한다면 (예를 들어 공식 도커 이미지 처럼), 여러분은 시작된 프로세스 개수가 가용한 것 보다 **더 많은 메모리를 소비**하지 않는지 확인해야 합니다. + +## 시작하기 전 단계들과 컨테이너 + +만약 여러분이 컨테이너(예를 들어 도커, 쿠버네티스)를 사용한다면, 여러분이 접근할 수 있는 주요 방법은 크게 두가지가 있습니다. + +### 다중 컨테이너 + +만약 여러분이 **여러개의 컨테이너**를 가지고 있다면, 아마도 각각의 컨테이너는 **하나의 프로세스**를 가지고 있을 것입니다(예를 들어, **쿠버네티스** 클러스터에서). 그러면 여러분은 복제된 워커 컨테이너를 실행하기 **이전에**, 하나의 컨테이너에 있는 **이전의 단계들을** 수행하는 단일 프로세스를 가지는 **별도의 컨테이너들**을 가지고 싶을 것입니다. + +/// info | 정보 + +만약 여러분이 쿠버네티스를 사용하고 있다면, 아마도 이는 Init Container일 것입니다. + +/// + +만약 여러분의 이용 사례에서 이전 단계들을 **병렬적으로 여러번** 수행하는데에 문제가 없다면 (예를 들어 데이터베이스 이전을 실행하지 않고 데이터베이스가 준비되었는지 확인만 하는 경우), 메인 프로세스를 시작하기 전에 이 단계들을 각 컨테이너에 넣을 수 있습니다. + +### 단일 컨테이너 + +만약 여러분의 셋업이 **다중 프로세스**(또는 하나의 프로세스)를 시작하는 **하나의 컨테이너**를 가지는 단순한 셋업이라면, 사전 단계들을 앱을 포함하는 프로세스를 시작하기 직전에 같은 컨테이너에서 실행할 수 있습니다. 공식 도커 이미지는 이를 내부적으로 지원합니다. + +## Gunicorn과 함께하는 공식 도커 이미지 - Uvicorn + +앞 챕터에서 자세하게 설명된 것 처럼, Uvicorn 워커와 같이 실행되는 Gunicorn을 포함하는 공식 도커 이미지가 있습니다: [서버 워커 - Uvicorn과 함께하는 Gunicorn](server-workers.md){.internal-link target=_blank}. + +이 이미지는 주로 위에서 설명된 상황에서 유용할 것입니다: [다중 프로세스를 가지는 컨테이너와 특수한 경우들](#containers-with-multiple-processes-and-special-cases). + +* tiangolo/uvicorn-gunicorn-fastapi. + +/// warning | 경고 + +여러분이 이 베이스 이미지 또는 다른 유사한 이미지를 필요로 하지 **않을** 높은 가능성이 있으며, [위에서 설명된 것처럼: FastAPI를 위한 도커 이미지 빌드하기](#build-a-docker-image-for-fastapi) 처음부터 이미지를 빌드하는 것이 더 나을 수 있습니다. + +/// + +이 이미지는 가능한 CPU 코어에 기반한 **몇개의 워커 프로세스**를 설정하는 **자동-튜닝** 메커니즘을 포함하고 있습니다. + +이 이미지는 **민감한 디폴트** 값을 가지고 있지만, 여러분들은 여전히 **환경 변수** 또는 설정 파일을 통해 설정값을 수정하고 업데이트 할 수 있습니다. + +또한 스크립트를 통해 **시작하기 전 사전 단계**를 실행하는 것을 지원합니다. + +/// tip | 팁 + +모든 설정과 옵션을 보려면, 도커 이미지 페이지로 이동합니다: tiangolo/uvicorn-gunicorn-fastapi. + +/// + +### 공식 도커 이미지에 있는 프로세스 개수 + +이 이미지에 있는 **프로세스 개수**는 가용한 CPU **코어들**로 부터 **자동으로 계산**됩니다. + +이것이 의미하는 바는 이미지가 CPU로부터 **최대한의 성능**을 **쥐어짜낸다**는 것입니다. + +여러분은 이 설정 값을 **환경 변수**나 기타 방법들로 조정할 수 있습니다. + +그러나 프로세스의 개수가 컨테이너가 실행되고 있는 CPU에 의존한다는 것은 또한 **소요되는 메모리의 크기** 또한 이에 의존한다는 것을 의미합니다. + +그렇기 때문에, 만약 여러분의 어플리케이션이 많은 메모리를 요구하고 (예를 들어 머신러닝 모델처럼), 여러분의 서버가 CPU 코어 수는 많지만 **적은 메모리**를 가지고 있다면, 여러분의 컨테이너는 가용한 메모리보다 많은 메모리를 사용하려고 시도할 수 있으며, 결국 퍼포먼스를 크게 떨어뜨릴 수 있습니다(심지어 고장이 날 수도 있습니다). 🚨 + +### `Dockerfile` 생성하기 + +이 이미지에 기반해 `Dockerfile`을 생성하는 방법은 다음과 같습니다: + +```Dockerfile +FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9 + +COPY ./requirements.txt /app/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt + +COPY ./app /app +``` + +### 더 큰 어플리케이션 + +만약 여러분이 [다중 파일을 가지는 더 큰 어플리케이션](../tutorial/bigger-applications.md){.internal-link target=_blank}을 생성하는 섹션을 따랐다면, 여러분의 `Dockerfile`은 대신 이렇게 생겼을 것입니다: + +```Dockerfile hl_lines="7" +FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9 + +COPY ./requirements.txt /app/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt + +COPY ./app /app/app +``` + +### 언제 사용할까 + +여러분들이 **쿠버네티스**(또는 유사한 다른 도구) 사용하거나 클러스터 레벨에서 다중 컨테이너를 이용해 이미 **사본**을 설정하고 있다면, 공식 베이스 이미지(또는 유사한 다른 이미지)를 사용하지 **않는** 것 좋습니다. 그런 경우에 여러분은 다음에 설명된 것 처럼 **처음부터 이미지를 빌드하는 것**이 더 낫습니다: [FastAPI를 위한 도커 이미지 빌드하기](#build-a-docker-image-for-fastapi). + +이 이미지는 위의 [다중 프로세스를 가지는 컨테이너와 특수한 경우들](#containers-with-multiple-processes-and-special-cases)에서 설명된 특수한 경우에 대해서만 주로 유용할 것입니다. 예를 들어, 만약 여러분의 어플리케이션이 **충분히 단순**해서 CPU에 기반한 디폴트 프로세스 개수를 설정하는 것이 잘 작동한다면, 클러스터 레벨에서 수동으로 사본을 설정할 필요가 없을 것이고, 여러분의 앱에서 하나 이상의 컨테이너를 실행하지도 않을 것입니다. 또는 만약에 여러분이 **도커 컴포즈**로 배포하거나, 단일 서버에서 실행하거나 하는 경우에도 마찬가지입니다. + +## 컨테이너 이미지 배포하기 + +컨테이너 (도커) 이미지를 완성한 뒤에 이를 배포하는 방법에는 여러가지 방법이 있습니다. + +예를 들어: + +* 단일 서버에서 **도커 컴포즈**로 배포하기 +* **쿠버네티스** 클러스터로 배포하기 +* 도커 스왐 모드 클러스터로 배포하기 +* 노마드 같은 다른 도구로 배포하기 +* 여러분의 컨테이너 이미지를 배포해주는 클라우드 서비스로 배포하기 + +## Poetry의 도커 이미지 + +만약 여러분들이 프로젝트 의존성을 관리하기 위해 Poetry를 사용한다면, 도커의 멀티-스테이지 빌딩을 사용할 수 있습니다: + +```{ .dockerfile .annotate } +# (1) +FROM python:3.9 as requirements-stage + +# (2) +WORKDIR /tmp + +# (3) +RUN pip install poetry + +# (4) +COPY ./pyproject.toml ./poetry.lock* /tmp/ + +# (5) +RUN poetry export -f requirements.txt --output requirements.txt --without-hashes + +# (6) +FROM python:3.9 + +# (7) +WORKDIR /code + +# (8) +COPY --from=requirements-stage /tmp/requirements.txt /code/requirements.txt + +# (9) +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +# (10) +COPY ./app /code/app + +# (11) +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] +``` + +1. 첫 스테이지로, `requirements-stage`라고 이름 붙였습니다. + +2. `/tmp`를 현재의 워킹 디렉터리로 설정합니다. + + 이 위치에 우리는 `requirements.txt` 파일을 생성할 것입니다. + +3. 이 도커 스테이지에서 Poetry를 설치합니다. + +4. 파일 `pyproject.toml`와 `poetry.lock`를 `/tmp` 디렉터리로 복사합니다. + + `./poetry.lock*` (`*`로 끝나는) 파일을 사용하기 때문에, 파일이 아직 사용가능하지 않더라도 고장나지 않을 것입니다. + +5. `requirements.txt` 파일을 생성합니다. + +6. 이것이 마지막 스테이지로, 여기에 위치한 모든 것이 마지막 컨테이너 이미지에 포함될 것입니다. + +7. 현재의 워킹 디렉터리를 `/code`로 설정합니다. + +8. 파일 `requirements.txt`를 `/code` 디렉터리로 복사합니다. + + 이 파일은 오직 이전의 도커 스테이지에만 존재하며, 때문에 복사하기 위해서 `--from-requirements-stage` 옵션이 필요합니다. + +9. 생성된 `requirements.txt` 파일에 패키지 의존성을 설치합니다. + +10. `app` 디렉터리를 `/code` 디렉터리로 복사합니다. + +11. `uvicorn` 커맨드를 실행하여, `app.main`에서 불러온 `app` 객체를 사용하도록 합니다. + +/// tip | 팁 + +버블 숫자를 클릭해 각 줄이 하는 일을 알아볼 수 있습니다. + +/// + +**도커 스테이지**란 `Dockefile`의 일부로서 나중에 사용하기 위한 파일들을 생성하기 위한 **일시적인 컨테이너 이미지**로 작동합니다. + +첫 스테이지는 오직 **Poetry를 설치**하고 Poetry의 `pyproject.toml` 파일로부터 프로젝트 의존성을 위한 **`requirements.txt`를 생성**하기 위해 사용됩니다. + +이 `requirements.txt` 파일은 **다음 스테이지**에서 `pip`로 사용될 것입니다. + +마지막 컨테이너 이미지에는 **오직 마지막 스테이지만** 보존됩니다. 이전 스테이지(들)은 버려집니다. + +Poetry를 사용할 때 **도커 멀티-스테이지 빌드**를 사용하는 것이 좋은데, 여러분들의 프로젝트 의존성을 설치하기 위해 마지막 컨테이너 이미지에 **오직** `requirements.txt` 파일만 필요하지, Poetry와 그 의존성은 있을 필요가 없기 때문입니다. + +이 다음 (또한 마지막) 스테이지에서 여러분들은 이전에 설명된 것과 비슷한 방식으로 방식으로 이미지를 빌드할 수 있습니다. + +### TLS 종료 프록시의 배후 - Poetry + +이전에 언급한 것과 같이, 만약 여러분이 컨테이너를 Nginx 또는 Traefik과 같은 TLS 종료 프록시 (로드 밸런서) 뒤에서 실행하고 있다면, 커맨드에 `--proxy-headers` 옵션을 추가합니다: + +```Dockerfile +CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"] +``` + +## 요약 + +컨테이너 시스템(예를 들어 **도커**나 **쿠버네티스**)을 사용하여 모든 **배포 개념**을 다루는 것은 꽤 간단합니다: + +* HTTPS +* 구동하기 +* 재시작 +* 복제 (실행 중인 프로세스 개수) +* 메모리 +* 시작하기 전 단계들 + +대부분의 경우에서 여러분은 어떤 베이스 이미지도 사용하지 않고 공식 파이썬 도커 이미지에 기반해 **처음부터 컨테이너 이미지를 빌드**할 것입니다. + +`Dockerfile`에 있는 지시 사항을 **순서대로** 다루고 **도커 캐시**를 사용하는 것으로 여러분은 **빌드 시간을 최소화**할 수 있으며, 이로써 생산성을 최대화할 수 있습니다 (그리고 지루함을 피할 수 있죠) 😎 + +특별한 경우에는, FastAPI를 위한 공식 도커 이미지를 사용할 수도 있습니다. 🤓 diff --git a/docs/ko/docs/deployment/index.md b/docs/ko/docs/deployment/index.md new file mode 100644 index 000000000..87b05b68f --- /dev/null +++ b/docs/ko/docs/deployment/index.md @@ -0,0 +1,21 @@ +# 배포하기 - 들어가면서 + +**FastAPI**을 배포하는 것은 비교적 쉽습니다. + +## 배포의 의미 + +**배포**란 애플리케이션을 **사용자가 사용**할 수 있도록 하는 데 필요한 단계를 수행하는 것을 의미합니다. + +**웹 API**의 경우, 일반적으로 **사용자**가 중단이나 오류 없이 애플리케이션에 효율적으로 **접근**할 수 있도록 좋은 성능, 안정성 등을 제공하는 **서버 프로그램과** 함께 **원격 시스템**에 이를 설치하는 작업을 의미합니다. + +이는 지속적으로 코드를 변경하고, 지우고, 수정하고, 개발 서버를 중지했다가 다시 시작하는 등의 **개발** 단계와 대조됩니다. + +## 배포 전략 + +사용하는 도구나 특정 사례에 따라 여러 가지 방법이 있습니다. + +배포도구들을 사용하여 직접 **서버에 배포**하거나, 배포작업의 일부를 수행하는 **클라우드 서비스** 또는 다른 방법을 사용할 수도 있습니다. + +**FastAPI** 애플리케이션을 배포할 때 선택할 수 있는 몇 가지 주요 방법을 보여 드리겠습니다 (대부분 다른 유형의 웹 애플리케이션에도 적용됩니다). + +다음 차례에 자세한 내용과 이를 위한 몇 가지 기술을 볼 수 있습니다. ✨ diff --git a/docs/ko/docs/deployment/server-workers.md b/docs/ko/docs/deployment/server-workers.md new file mode 100644 index 000000000..b40b25cd8 --- /dev/null +++ b/docs/ko/docs/deployment/server-workers.md @@ -0,0 +1,183 @@ +# 서버 워커 - 구니콘과 유비콘 + +전단계에서의 배포 개념들을 다시 확인해보겠습니다: + +* 보안 - HTTPS +* 서버 시작과 동시에 실행하기 +* 재시작 +* **복제본 (실행 중인 프로세스의 숫자)** +* 메모리 +* 시작하기 전의 여러 단계들 + +지금까지 문서의 모든 튜토리얼을 참고하여 **단일 프로세스**로 Uvicorn과 같은 **서버 프로그램**을 실행했을 것입니다. + +애플리케이션을 배포할 때 **다중 코어**를 활용하고 더 많은 요청을 처리할 수 있도록 **프로세스 복제본**이 필요합니다. + +전 과정이었던 [배포 개념들](concepts.md){.internal-link target=_blank}에서 본 것처럼 여러가지 방법이 존재합니다. + +지금부터 **구니콘**을 **유비콘 워커 프로세스**와 함께 사용하는 방법을 알려드리겠습니다. + +/// info | 정보 + +만약 도커와 쿠버네티스 같은 컨테이너를 사용하고 있다면 다음 챕터 [FastAPI와 컨테이너 - 도커](docker.md){.internal-link target=_blank}에서 더 많은 정보를 얻을 수 있습니다. + +특히, 쿠버네티스에서 실행할 때는 구니콘을 사용하지 않고 대신 컨테이너당 하나의 유비콘 프로세스를 실행하는 것이 좋습니다. 이 장의 뒷부분에서 설명하겠습니다. + +/// + +## 구니콘과 유비콘 워커 + +**Gunicorn**은 **WSGI 표준**을 주로 사용하는 애플리케이션 서버입니다. 이것은 구니콘이 플라스크와 쟝고와 같은 애플리케이션을 제공할 수 있다는 것을 의미합니다. 구니콘 자체는 최신 **ASGI 표준**을 사용하기 때문에 FastAPI와 호환되지 않습니다. + +하지만 구니콘은 **프로세스 관리자**역할을 하고 사용자에게 특정 **워커 프로세스 클래스**를 알려줍니다. 그런 다음 구니콘은 해당 클래스를 사용하여 하나 이상의 **워커 프로세스**를 시작합니다. + +그리고 **유비콘**은 **구니콘과 호환되는 워커 클래스**가 있습니다. + +이 조합을 사용하여 구니콘은 **프로세스 관리자** 역할을 하며 **포트**와 **IP**를 관찰하고, **유비콘 클래스**를 실행하는 워커 프로세스로 통신 정보를 **전송**합니다. + +그리고 나서 구니콘과 호환되는 **유비콘 워커** 클래스는 구니콘이 보낸 데이터를 FastAPI에서 사용하기 위한 ASGI 표준으로 변환하는 일을 담당합니다. + +## 구니콘과 유비콘 설치하기 + +
+ +```console +$ pip install "uvicorn[standard]" gunicorn + +---> 100% +``` + +
+ +이 명령어는 유비콘 `standard` 추가 패키지(좋은 성능을 위한)와 구니콘을 설치할 것입니다. + +## 구니콘을 유비콘 워커와 함께 실행하기 + +설치 후 구니콘 실행하기: + +
+ +```console +$ gunicorn main:app --workers 4 --worker-class uvicorn.workers.UvicornWorker --bind 0.0.0.0:80 + +[19499] [INFO] Starting gunicorn 20.1.0 +[19499] [INFO] Listening at: http://0.0.0.0:80 (19499) +[19499] [INFO] Using worker: uvicorn.workers.UvicornWorker +[19511] [INFO] Booting worker with pid: 19511 +[19513] [INFO] Booting worker with pid: 19513 +[19514] [INFO] Booting worker with pid: 19514 +[19515] [INFO] Booting worker with pid: 19515 +[19511] [INFO] Started server process [19511] +[19511] [INFO] Waiting for application startup. +[19511] [INFO] Application startup complete. +[19513] [INFO] Started server process [19513] +[19513] [INFO] Waiting for application startup. +[19513] [INFO] Application startup complete. +[19514] [INFO] Started server process [19514] +[19514] [INFO] Waiting for application startup. +[19514] [INFO] Application startup complete. +[19515] [INFO] Started server process [19515] +[19515] [INFO] Waiting for application startup. +[19515] [INFO] Application startup complete. +``` + +
+ +각 옵션이 무엇을 의미하는지 살펴봅시다: + +* 이것은 유비콘과 똑같은 문법입니다. `main`은 파이썬 모듈 네임 "`main`"을 의미하므로 `main.py`파일을 뜻합니다. 그리고 `app`은 **FastAPI** 어플리케이션이 들어 있는 변수의 이름입니다. + * `main:app`이 파이썬의 `import` 문법과 흡사한 면이 있다는 걸 알 수 있습니다: + + ```Python + from main import app + ``` + + * 곧, `main:app`안에 있는 콜론의 의미는 파이썬에서 `from main import app`에서의 `import`와 같습니다. +* `--workers`: 사용할 워커 프로세스의 개수이며 숫자만큼의 유비콘 워커를 실행합니다. 이 예제에서는 4개의 워커를 실행합니다. +* `--worker-class`: 워커 프로세스에서 사용하기 위한 구니콘과 호환되는 워커클래스. + * 이런식으로 구니콘이 import하여 사용할 수 있는 클래스를 전달해줍니다: + + ```Python + import uvicorn.workers.UvicornWorker + ``` + +* `--bind`: 구니콘이 관찰할 IP와 포트를 의미합니다. 콜론 (`:`)을 사용하여 IP와 포트를 구분합니다. + * 만약에 `--bind 0.0.0.0:80` (구니콘 옵션) 대신 유비콘을 직접 실행하고 싶다면 `--host 0.0.0.0`과 `--port 80`을 사용해야 합니다. + +출력에서 각 프로세스에 대한 **PID** (process ID)를 확인할 수 있습니다. (단순한 숫자입니다) + +출력 내용: + +* 구니콘 **프로세스 매니저**는 PID `19499`로 실행됩니다. (직접 실행할 경우 숫자가 다를 수 있습니다) +* 다음으로 `Listening at: http://0.0.0.0:80`을 시작합니다. +* 그런 다음 사용해야할 `uvicorn.workers.UvicornWorker`의 워커클래스를 탐지합니다. +* 그리고 PID `19511`, `19513`, `19514`, 그리고 `19515`를 가진 **4개의 워커**를 실행합니다. + + +또한 구니콘은 워커의 수를 유지하기 위해 **죽은 프로세스**를 관리하고 **재시작**하는 작업을 책임집니다. 이것은 이번 장 상단 목록의 **재시작** 개념을 부분적으로 도와주는 것입니다. + +그럼에도 불구하고 필요할 경우 외부에서 **구니콘을 재시작**하고, 혹은 **서버를 시작할 때 실행**할 수 있도록 하고 싶어할 것입니다. + +## 유비콘과 워커 + +유비콘은 몇 개의 **워커 프로세스**와 함께 실행할 수 있는 선택지가 있습니다. + +그럼에도 불구하고, 유비콘은 워커 프로세스를 다루는 데에 있어서 구니콘보다 더 제한적입니다. 따라서 이 수준(파이썬 수준)의 프로세스 관리자를 사용하려면 구니콘을 프로세스 관리자로 사용하는 것이 좋습니다. + +보통 이렇게 실행할 수 있습니다: + +
+ +```console +$ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4 +INFO: Uvicorn running on http://0.0.0.0:8080 (Press CTRL+C to quit) +INFO: Started parent process [27365] +INFO: Started server process [27368] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Started server process [27369] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Started server process [27370] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Started server process [27367] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +새로운 옵션인 `--workers`은 유비콘에게 4개의 워커 프로세스를 사용한다고 알려줍니다. + +각 프로세스의 **PID**를 확인할 수 있습니다. `27365`는 상위 프로세스(**프로세스 매니저**), 그리고 각각의 워커프로세스는 `27368`, `27369`, `27370`, 그리고 `27367`입니다. + +## 배포 개념들 + +여기에서는 **유비콘 워커 프로세스**를 관리하는 **구니콘**(또는 유비콘)을 사용하여 애플리케이션을 **병렬화**하고, CPU **멀티 코어**의 장점을 활용하고, **더 많은 요청**을 처리할 수 있는 방법을 살펴보았습니다. + +워커를 사용하는 것은 배포 개념 목록에서 주로 **복제본** 부분과 **재시작**에 약간 도움이 되지만 다른 배포 개념들도 다루어야 합니다: + +* **보안 - HTTPS** +* **서버 시작과 동시에 실행하기** +* ***재시작*** +* 복제본 (실행 중인 프로세스의 숫자) +* **메모리** +* **시작하기 전의 여러 단계들** + + +## 컨테이너와 도커 + +다음 장인 [FastAPI와 컨테이너 - 도커](docker.md){.internal-link target=_blank}에서 다른 **배포 개념들**을 다루는 전략들을 알려드리겠습니다. + +또한 간단한 케이스에서 사용할 수 있는, **구니콘과 유비콘 워커**가 포함돼 있는 **공식 도커 이미지**와 함께 몇 가지 기본 구성을 보여드리겠습니다. + +그리고 단일 유비콘 프로세스(구니콘 없이)를 실행할 수 있도록 **사용자 자신의 이미지를 처음부터 구축**하는 방법도 보여드리겠습니다. 이는 간단한 과정이며, **쿠버네티스**와 같은 분산 컨테이너 관리 시스템을 사용할 때 수행할 작업입니다. + +## 요약 + +당신은 **구니콘**(또는 유비콘)을 유비콘 워커와 함께 프로세스 관리자로 사용하여 **멀티-코어 CPU**를 활용하는 **멀티 프로세스를 병렬로 실행**할 수 있습니다. + +다른 배포 개념을 직접 다루면서 **자신만의 배포 시스템**을 구성하는 경우 이러한 도구와 개념들을 활용할 수 있습니다. + +다음 장에서 컨테이너(예: 도커 및 쿠버네티스)와 함께하는 **FastAPI**에 대해 배워보세요. 이러한 툴에는 다른 **배포 개념**들을 간단히 해결할 수 있는 방법이 있습니다. ✨ diff --git a/docs/ko/docs/deployment/versions.md b/docs/ko/docs/deployment/versions.md index 074c15158..559a892ab 100644 --- a/docs/ko/docs/deployment/versions.md +++ b/docs/ko/docs/deployment/versions.md @@ -43,8 +43,11 @@ fastapi>=0.45.0,<0.46.0 FastAPI는 오류를 수정하고, 일반적인 변경사항을 위해 "패치"버전의 관습을 따릅니다. -!!! tip "팁" - 여기서 말하는 "패치"란 버전의 마지막 숫자로, 예를 들어 `0.2.3` 버전에서 "패치"는 `3`을 의미합니다. +/// tip | 팁 + +여기서 말하는 "패치"란 버전의 마지막 숫자로, 예를 들어 `0.2.3` 버전에서 "패치"는 `3`을 의미합니다. + +/// 따라서 다음과 같이 버전을 표시할 수 있습니다: @@ -54,8 +57,11 @@ fastapi>=0.45.0,<0.46.0 수정된 사항과 새로운 요소들이 "마이너" 버전에 추가되었습니다. -!!! tip "팁" - "마이너"란 버전 넘버의 가운데 숫자로, 예를 들어서 `0.2.3`의 "마이너" 버전은 `2`입니다. +/// tip | 팁 + +"마이너"란 버전 넘버의 가운데 숫자로, 예를 들어서 `0.2.3`의 "마이너" 버전은 `2`입니다. + +/// ## FastAPI 버전의 업그레이드 diff --git a/docs/ko/docs/environment-variables.md b/docs/ko/docs/environment-variables.md new file mode 100644 index 000000000..1e6af3ceb --- /dev/null +++ b/docs/ko/docs/environment-variables.md @@ -0,0 +1,298 @@ +# 환경 변수 + +/// tip | 팁 + +만약 "환경 변수"가 무엇이고, 어떻게 사용하는지 알고 계시다면, 이 챕터를 스킵하셔도 좋습니다. + +/// + +환경 변수는 파이썬 코드의 **바깥**인, **운영 체제**에 존재하는 변수입니다. 파이썬 코드나 다른 프로그램에서 읽을 수 있습니다. + +환경 변수는 애플리케이션 **설정**을 처리하거나, 파이썬의 **설치** 과정의 일부로 유용합니다. + +## 환경 변수를 만들고 사용하기 + +파이썬 없이도, **셸 (터미널)** 에서 환경 변수를 **생성** 하고 사용할 수 있습니다. + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// You could create an env var MY_NAME with +$ export MY_NAME="Wade Wilson" + +// Then you could use it with other programs, like +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// Create an env var MY_NAME +$ $Env:MY_NAME = "Wade Wilson" + +// Use it with other programs, like +$ echo "Hello $Env:MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +## 파이썬에서 환경 변수 읽기 + +파이썬 **바깥**인 터미널에서(다른 도구로도 가능) 환경 변수를 생성도 할 수도 있고, 이를 **파이썬에서 읽을 수 있습니다.** + +예를 들어 다음과 같은 `main.py` 파일이 있다고 합시다: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// tip | 팁 + +`os.getenv()` 의 두 번째 인자는 반환할 기본값입니다. + +여기서는 `"World"`를 넣었기에 기본값으로써 사용됩니다. 넣지 않으면 `None` 이 기본값으로 사용됩니다. + +/// + +그러면 해당 파이썬 프로그램을 다음과 같이 호출할 수 있습니다: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// Here we don't set the env var yet +$ python main.py + +// As we didn't set the env var, we get the default value + +Hello World from Python + +// But if we create an environment variable first +$ export MY_NAME="Wade Wilson" + +// And then call the program again +$ python main.py + +// Now it can read the environment variable + +Hello Wade Wilson from Python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// Here we don't set the env var yet +$ python main.py + +// As we didn't set the env var, we get the default value + +Hello World from Python + +// But if we create an environment variable first +$ $Env:MY_NAME = "Wade Wilson" + +// And then call the program again +$ python main.py + +// Now it can read the environment variable + +Hello Wade Wilson from Python +``` + +
+ +//// + +환경변수는 코드 바깥에서 설정될 수 있지만, 코드에서 읽을 수 있고, 나머지 파일과 함께 저장(`git`에 커밋)할 필요가 없으므로, 구성이나 **설정** 에 사용하는 것이 일반적입니다. + +**특정 프로그램 호출**에 대해서만 사용할 수 있는 환경 변수를 만들 수도 있습니다. 해당 프로그램에서만 사용할 수 있고, 해당 프로그램이 실행되는 동안만 사용할 수 있습니다. + +그렇게 하려면 프로그램 바로 앞, 같은 줄에 환경 변수를 만들어야 합니다: + +
+ +```console +// Create an env var MY_NAME in line for this program call +$ MY_NAME="Wade Wilson" python main.py + +// Now it can read the environment variable + +Hello Wade Wilson from Python + +// The env var no longer exists afterwards +$ python main.py + +Hello World from Python +``` + +
+ +/// tip | 팁 + +The Twelve-Factor App: Config 에서 좀 더 자세히 알아볼 수 있습니다. + +/// + +## 타입과 검증 + +이 환경변수들은 오직 **텍스트 문자열**로만 처리할 수 있습니다. 텍스트 문자열은 파이썬 외부에 있으며 다른 프로그램 및 나머지 시스템(Linux, Windows, macOS 등 다른 운영 체제)과 호환되어야 합니다. + +즉, 파이썬에서 환경 변수로부터 읽은 **모든 값**은 **`str`**이 되고, 다른 타입으로의 변환이나 검증은 코드에서 수행해야 합니다. + +**애플리케이션 설정**을 처리하기 위한 환경 변수 사용에 대한 자세한 내용은 [고급 사용자 가이드 - 설정 및 환경 변수](./advanced/settings.md){.internal-link target=\_blank} 에서 확인할 수 있습니다. + +## `PATH` 환경 변수 + +**`PATH`**라고 불리는, **특별한** 환경변수가 있습니다. 운영체제(Linux, Windows, macOS 등)에서 실행할 프로그램을 찾기위해 사용됩니다. + +변수 `PATH`의 값은 Linux와 macOS에서는 콜론 `:`, Windows에서는 세미콜론 `;`으로 구분된 디렉토리로 구성된 긴 문자열입니다. + +예를 들어, `PATH` 환경 변수는 다음과 같습니다: + +//// tab | Linux, macOS + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +이는 시스템이 다음 디렉토리에서 프로그램을 찾아야 함을 의미합니다: + +- `/usr/local/bin` +- `/usr/bin` +- `/bin` +- `/usr/sbin` +- `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32 +``` + +이는 시스템이 다음 디렉토리에서 프로그램을 찾아야 함을 의미합니다: + +- `C:\Program Files\Python312\Scripts` +- `C:\Program Files\Python312` +- `C:\Windows\System32` + +//// + +터미널에 **명령어**를 입력하면 운영 체제는 `PATH` 환경 변수에 나열된 **각 디렉토리**에서 프로그램을 **찾습니다.** + +예를 들어 터미널에 `python`을 입력하면 운영 체제는 해당 목록의 **첫 번째 디렉토리**에서 `python`이라는 프로그램을 찾습니다. + +찾으면 **사용합니다**. 그렇지 않으면 **다른 디렉토리**에서 계속 찾습니다. + +### 파이썬 설치와 `PATH` 업데이트 + +파이썬을 설치할 때, 아마 `PATH` 환경 변수를 업데이트 할 것이냐고 물어봤을 겁니다. + +//// tab | Linux, macOS + +파이썬을 설치하고 그것이 `/opt/custompython/bin` 디렉토리에 있다고 가정해 보겠습니다. + +`PATH` 환경 변수를 업데이트하도록 "예"라고 하면 설치 관리자가 `/opt/custompython/bin`을 `PATH` 환경 변수에 추가합니다. + +다음과 같이 보일 수 있습니다: + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin +``` + +이렇게 하면 터미널에 `python`을 입력할 때, 시스템이 `/opt/custompython/bin`(마지막 디렉토리)에서 파이썬 프로그램을 찾아 사용합니다. + +//// + +//// tab | Windows + +파이썬을 설치하고 그것이 `C:\opt\custompython\bin` 디렉토리에 있다고 가정해 보겠습니다. + +`PATH` 환경 변수를 업데이트하도록 "예"라고 하면 설치 관리자가 `C:\opt\custompython\bin`을 `PATH` 환경 변수에 추가합니다. + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin +``` + +이렇게 하면 터미널에 `python`을 입력할 때, 시스템이 `C:\opt\custompython\bin`(마지막 디렉토리)에서 파이썬 프로그램을 찾아 사용합니다. + +//// + +그래서, 다음과 같이 입력한다면: + +
+ +```console +$ python +``` + +
+ +//// tab | Linux, macOS + +시스템은 `/opt/custompython/bin`에서 `python` 프로그램을 **찾아** 실행합니다. + +다음과 같이 입력하는 것과 거의 같습니다: + +
+ +```console +$ /opt/custompython/bin/python +``` + +
+ +//// + +//// tab | Windows + +시스템은 `C:\opt\custompython\bin\python`에서 `python` 프로그램을 **찾아** 실행합니다. + +다음과 같이 입력하는 것과 거의 같습니다: + +
+ +```console +$ C:\opt\custompython\bin\python +``` + +
+ +//// + +이 정보는 [가상 환경](virtual-environments.md){.internal-link target=\_blank} 에 대해 알아볼 때 유용할 것입니다. + +## 결론 + +이 문서를 읽고 **환경 변수**가 무엇이고 파이썬에서 어떻게 사용하는지 기본적으로 이해하셨을 겁니다. + +또한 환경 변수에 대한 위키피디아(한국어)에서 이에 대해 자세히 알아볼 수 있습니다. + +많은 경우에서, 환경 변수가 어떻게 유용하고 적용 가능한지 바로 명확하게 알 수는 없습니다. 하지만 개발할 때 다양한 시나리오에서 계속 나타나므로 이에 대해 아는 것이 좋습니다. + +예를 들어, 다음 섹션인 [가상 환경](virtual-environments.md)에서 이 정보가 필요합니다. diff --git a/docs/ko/docs/fastapi-cli.md b/docs/ko/docs/fastapi-cli.md new file mode 100644 index 000000000..3a976af36 --- /dev/null +++ b/docs/ko/docs/fastapi-cli.md @@ -0,0 +1,83 @@ +# FastAPI CLI + +**FastAPI CLI**는 FastAPI 애플리케이션을 실행하고, 프로젝트를 관리하는 등 다양한 작업을 수행할 수 있는 커맨드 라인 프로그램입니다. + +FastAPI를 설치할 때 (예: `pip install "fastapi[standard]"` 명령어를 사용할 경우), `fastapi-cli`라는 패키지가 포함됩니다. 이 패키지는 터미널에서 사용할 수 있는 `fastapi` 명령어를 제공합니다. + +개발용으로 FastAPI 애플리케이션을 실행하려면 다음과 같이 `fastapi dev` 명령어를 사용할 수 있습니다: + +
+ +```console +$ fastapi dev main.py +INFO Using path main.py +INFO Resolved absolute path /home/user/code/awesomeapp/main.py +INFO Searching for package file structure from directories with __init__.py files +INFO Importing from /home/user/code/awesomeapp + + ╭─ Python module file ─╮ + │ │ + │ 🐍 main.py │ + │ │ + ╰──────────────────────╯ + +INFO Importing module main +INFO Found importable FastAPI app + + ╭─ Importable FastAPI app ─╮ + │ │ + │ from main import app │ + │ │ + ╰──────────────────────────╯ + +INFO Using import string main:app + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + fastapi run + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [2265862] using WatchFiles +INFO: Started server process [2265873] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +`fastapi`라고 불리는 명령어 프로그램은 **FastAPI CLI**입니다. + +FastAPI CLI는 Python 프로그램의 경로(예: `main.py`)를 인수로 받아, `FastAPI` 인스턴스(일반적으로 `app`으로 명명)를 자동으로 감지하고 올바른 임포트 과정을 결정한 후 이를 실행합니다. + +프로덕션 환경에서는 `fastapi run` 명령어를 사용합니다. 🚀 + +내부적으로, **FastAPI CLI**는 고성능의, 프로덕션에 적합한, ASGI 서버인 Uvicorn을 사용합니다. 😎 + +## `fastapi dev` + +`fastapi dev` 명령을 실행하면 개발 모드가 시작됩니다. + +기본적으로 **자동 재시작(auto-reload)** 기능이 활성화되어, 코드에 변경이 생기면 서버를 자동으로 다시 시작합니다. 하지만 이 기능은 리소스를 많이 사용하며, 비활성화했을 때보다 안정성이 떨어질 수 있습니다. 따라서 개발 환경에서만 사용하는 것이 좋습니다. 또한, 서버는 컴퓨터가 자체적으로 통신할 수 있는 IP 주소(`localhost`)인 `127.0.0.1`에서 연결을 대기합니다. + +## `fastapi run` + +`fastapi run` 명령을 실행하면 기본적으로 프로덕션 모드로 FastAPI가 시작됩니다. + +기본적으로 **자동 재시작(auto-reload)** 기능이 비활성화되어 있습니다. 또한, 사용 가능한 모든 IP 주소인 `0.0.0.0`에서 연결을 대기하므로 해당 컴퓨터와 통신할 수 있는 모든 사람이 공개적으로 액세스할 수 있습니다. 이는 일반적으로 컨테이너와 같은 프로덕션 환경에서 실행하는 방법입니다. + +애플리케이션을 배포하는 방식에 따라 다르지만, 대부분 "종료 프록시(termination proxy)"를 활용해 HTTPS를 처리하는 것이 좋습니다. 배포 서비스 제공자가 이 작업을 대신 처리해줄 수도 있고, 직접 설정해야 할 수도 있습니다. + +/// tip + +자세한 내용은 [deployment documentation](deployment/index.md){.internal-link target=\_blank}에서 확인할 수 있습니다. + +/// diff --git a/docs/ko/docs/features.md b/docs/ko/docs/features.md new file mode 100644 index 000000000..5e880c298 --- /dev/null +++ b/docs/ko/docs/features.md @@ -0,0 +1,201 @@ +# 기능 + +## FastAPI의 기능 + +**FastAPI**는 다음과 같은 기능을 제공합니다: + +### 개방형 표준을 기반으로 + +* 경로작동, 매개변수, 본문 요청, 보안 그 외의 선언을 포함한 API 생성을 위한 OpenAPI +* JSON Schema (OpenAPI 자체가 JSON Schema를 기반으로 하고 있습니다)를 사용한 자동 데이터 모델 문서화. +* 단순히 떠올려서 덧붙인 기능이 아닙니다. 세심한 검토를 거친 후, 이러한 표준을 기반으로 설계되었습니다. +* 이는 또한 다양한 언어로 자동적인 **클라이언트 코드 생성**을 사용할 수 있게 지원합니다. + +### 문서 자동화 + +대화형 API 문서와 웹 탐색 유저 인터페이스를 제공합니다. 프레임워크가 OpenAPI를 기반으로 하기에, 2가지 옵션이 기본적으로 들어간 여러 옵션이 존재합니다. + +* 대화형 탐색 Swagger UI를 이용해, 브라우저에서 바로 여러분의 API를 호출하거나 테스트할 수 있습니다. + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* ReDoc을 이용해 API 문서화를 대체할 수 있습니다. + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### 그저 현대 파이썬 + +(Pydantic 덕분에) FastAPI는 표준 **파이썬 3.6 타입** 선언에 기반하고 있습니다. 새로 배울 문법이 없습니다. 그저 표준적인 현대 파이썬입니다. + +만약 여러분이 파이썬 타입을 어떻게 사용하는지에 대한 2분 정도의 복습이 필요하다면 (비록 여러분이 FastAPI를 사용하지 않는다 하더라도), 다음의 짧은 자습서를 확인하세요: [파이썬 타입](python-types.md){.internal-link target=\_blank}. + +여러분은 타입을 이용한 표준 파이썬을 다음과 같이 적을 수 있습니다: + +```Python +from datetime import date + +from pydantic import BaseModel + +# 변수를 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) +``` + +/// info | 정보 + +`**second_user_data`가 뜻하는 것: + +`second_user_data` 딕셔너리의 키와 값을 키-값 인자로서 바로 넘겨줍니다. 다음과 동일합니다: `User(id=4, name="Mary", joined="2018-11-30")` + +/// + +### 편집기 지원 + +모든 프레임워크는 사용하기 쉽고 직관적으로 설계되었으며, 좋은 개발 경험을 보장하기 위해 개발을 시작하기도 전에 모든 결정들은 여러 편집기에서 테스트됩니다. + +최근 파이썬 개발자 설문조사에서 "자동 완성"이 가장 많이 사용되는 기능이라는 것이 밝혀졌습니다. + +**FastAPI** 프레임워크의 모든 부분은 이를 충족하기 위해 설계되었습니다. 자동완성은 어느 곳에서나 작동합니다. + +여러분은 문서로 다시 돌아올 일이 거의 없을 겁니다. + +다음은 편집기가 어떻게 여러분을 도와주는지 보여줍니다: + +* Visual Studio Code에서: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +* PyCharm에서: + +![editor support](https://fastapi.tiangolo.com/img/pycharm-completion.png) + +여러분이 이전에 불가능하다고 고려했던 코드도 완성할 수 있을 겁니다. 예를 들어, 요청에서 전달되는 (중첩될 수도 있는)JSON 본문 내부에 있는 `price` 키입니다. + +잘못된 키 이름을 적을 일도, 문서를 왔다 갔다할 일도 없으며, 혹은 마지막으로 `username` 또는 `user_name`을 사용했는지 찾기 위해 위 아래로 스크롤할 일도 없습니다. + +### 토막 정보 + +어느 곳에서나 선택적 구성이 가능한 모든 것에 합리적인 기본값이 설정되어 있습니다. 모든 매개변수는 여러분이 필요하거나, 원하는 API를 정의하기 위해 미세하게 조정할 수 있습니다. + +하지만 기본적으로 모든 것이 "그냥 작동합니다". + +### 검증 + +* 다음을 포함한, 대부분의 (혹은 모든?) 파이썬 **데이터 타입** 검증할 수 있습니다: + * JSON 객체 (`dict`). + * 아이템 타입을 정의하는 JSON 배열 (`list`). + * 최소 길이와 최대 길이를 정의하는 문자열 (`str`) 필드. + * 최솟값과 최댓값을 가지는 숫자 (`int`, `float`), 그 외. + +* 다음과 같이 더욱 이색적인 타입에 대해 검증할 수 있습니다: + * URL. + * 이메일. + * UUID. + * ...다른 것들. + +모든 검증은 견고하면서 잘 확립된 **Pydantic**에 의해 처리됩니다. + +### 보안과 인증 + +보안과 인증이 통합되어 있습니다. 데이터베이스나 데이터 모델과의 타협없이 사용할 수 있습니다. + +다음을 포함하는, 모든 보안 스키마가 OpenAPI에 정의되어 있습니다. + +* HTTP Basic. +* **OAuth2** (**JWT tokens** 또한 포함). [OAuth2 with JWT](tutorial/security/oauth2-jwt.md){.internal-link target=\_blank}에 있는 자습서를 확인해 보세요. +* 다음에 들어 있는 API 키: + * 헤더. + * 매개변수. + * 쿠키 및 그 외. + +추가적으로 (**세션 쿠키**를 포함한) 모든 보안 기능은 Starlette에 있습니다. + +모두 재사용할 수 있는 도구와 컴포넌트로 만들어져 있어 여러분의 시스템, 데이터 저장소, 관계형 및 NoSQL 데이터베이스 등과 쉽게 통합할 수 있습니다. + +### 의존성 주입 + +FastAPI는 사용하기 매우 간편하지만, 엄청난 의존성 주입시스템을 포함하고 있습니다. + +* 의존성은 의존성을 가질수도 있어, 이를 통해 의존성의 계층이나 **의존성의 "그래프"**를 형성합니다. +* 모든 것이 프레임워크에 의해 **자동적으로 처리됩니다**. +* 모든 의존성은 요청에서 데이터를 요구하여 자동 문서화와 **경로 작동 제약을 강화할 수 있습니다**. +* 의존성에서 정의된 _경로 작동_ 매개변수에 대해서도 **자동 검증**이 이루어 집니다. +* 복잡한 사용자의 인증 시스템, **데이터베이스 연결**, 등등을 지원합니다. +* 데이터베이스, 프론트엔드 등과 관련되어 **타협하지 않아도 됩니다**. 하지만 그 모든 것과 쉽게 통합이 가능합니다. + +### 제한 없는 "플러그인" + +또는 다른 방법으로, 그것들을 사용할 필요 없이 필요한 코드만 임포트할 수 있습니다. + +어느 통합도 (의존성과 함께) 사용하기 쉽게 설계되어 있어, *경로 작동*에 사용된 것과 동일한 구조와 문법을 사용하여 2줄의 코드로 여러분의 어플리케이션에 사용할 "플러그인"을 만들 수 있습니다. + +### 테스트 결과 + +* 100% 테스트 범위. +* 100% 타입이 명시된 코드 베이스. +* 상용 어플리케이션에서의 사용. + +## Starlette 기능 + +**FastAPI**는 Starlette를 기반으로 구축되었으며, 이와 완전히 호환됩니다. 따라서, 여러분이 보유하고 있는 어떤 추가적인 Starlette 코드도 작동할 것입니다. + +`FastAPI`는 실제로 `Starlette`의 하위 클래스입니다. 그래서, 여러분이 이미 Starlette을 알고 있거나 사용하고 있으면, 대부분의 기능이 같은 방식으로 작동할 것입니다. + +**FastAPI**를 사용하면 여러분은 **Starlette**의 기능 대부분을 얻게 될 것입니다(FastAPI가 단순히 Starlette를 강화했기 때문입니다): + +* 아주 인상적인 성능. 이는 **NodeJS**와 **Go**와 동등하게 사용 가능한 가장 빠른 파이썬 프레임워크 중 하나입니다. +* **WebSocket** 지원. +* 프로세스 내의 백그라운드 작업. +* 시작과 종료 이벤트. +* HTTPX 기반 테스트 클라이언트. +* **CORS**, GZip, 정적 파일, 스트리밍 응답. +* **세션과 쿠키** 지원. +* 100% 테스트 범위. +* 100% 타입이 명시된 코드 베이스. + +## Pydantic 기능 + +**FastAPI**는 Pydantic을 기반으로 하며 Pydantic과 완벽하게 호환됩니다. 그래서 어느 추가적인 Pydantic 코드를 여러분이 가지고 있든 작동할 것입니다. + +Pydantic을 기반으로 하는, 데이터베이스를 위한 ORM, ODM을 포함한 외부 라이브러리를 포함합니다. + +이는 모든 것이 자동으로 검증되기 때문에, 많은 경우에서 요청을 통해 얻은 동일한 객체를, **직접 데이터베이스로** 넘겨줄 수 있습니다. + +반대로도 마찬가지이며, 많은 경우에서 여러분은 **직접 클라이언트로** 그저 객체를 넘겨줄 수 있습니다. + +**FastAPI**를 사용하면 (모든 데이터 처리를 위해 FastAPI가 Pydantic을 기반으로 하기 있기에) **Pydantic**의 모든 기능을 얻게 됩니다: + +* **어렵지 않은 언어**: + * 새로운 스키마 정의 마이크로 언어를 배우지 않아도 됩니다. + * 여러분이 파이썬 타입을 안다면, 여러분은 Pydantic을 어떻게 사용하는지 아는 겁니다. +* 여러분의 **IDE/린터/뇌**와 잘 어울립니다: + * Pydantic 데이터 구조는 단순 여러분이 정의한 클래스의 인스턴스이기 때문에, 자동 완성, 린팅, mypy 그리고 여러분의 직관까지 여러분의 검증된 데이터와 올바르게 작동합니다. +* **복잡한 구조**를 검증합니다: + * 계층적인 Pydantic 모델, 파이썬 `typing`의 `List`와 `Dict`, 그 외를 사용합니다. + * 그리고 검증자는 복잡한 데이터 스키마를 명확하고 쉽게 정의 및 확인하며 JSON 스키마로 문서화합니다. + * 여러분은 깊게 **중첩된 JSON** 객체를 가질 수 있으며, 이 객체 모두 검증하고 설명을 붙일 수 있습니다. +* **확장 가능성**: + * Pydantic은 사용자 정의 데이터 타입을 정의할 수 있게 하거나, 검증자 데코레이터가 붙은 모델의 메소드를 사용하여 검증을 확장할 수 있습니다. +* 100% 테스트 범위. diff --git a/docs/ko/docs/help-fastapi.md b/docs/ko/docs/help-fastapi.md new file mode 100644 index 000000000..06435d4bb --- /dev/null +++ b/docs/ko/docs/help-fastapi.md @@ -0,0 +1,269 @@ +# FastAPI 지원 - 도움 받기 + +**FastAPI** 가 마음에 드시나요? + +FastAPI, 다른 사용자, 개발자를 응원하고 싶으신가요? + +혹은 **FastAPI** 에 대해 도움이 필요하신가요? + +아주 간단하게 응원할 수 있습니다 (몇 번의 클릭만으로). + +또한 도움을 받을 수 있는 방법도 몇 가지 있습니다. + +## 뉴스레터 구독 + +[**FastAPI and friends** 뉴스레터](newsletter.md){.internal-link target=\_blank}를 구독하여 최신 정보를 유지할 수 있습니다: + +* FastAPI and friends에 대한 뉴스 🚀 +* 가이드 📝 +* 기능 ✨ +* 획기적인 변화 🚨 +* 팁과 요령 ✅ + +## 트위터에서 FastAPI 팔로우하기 + +**Twitter**의 @fastapi를 팔로우하여 **FastAPI** 에 대한 최신 뉴스를 얻을 수 있습니다. 🐦 + +## Star **FastAPI** in GitHub + +GitHub에서 FastAPI에 "star"를 붙일 수 있습니다 (오른쪽 상단의 star 버튼을 클릭): https://github.com/fastapi/fastapi. ⭐️ + +스타를 늘림으로써, 다른 사용자들이 좀 더 쉽게 찾을 수 있고, 많은 사람들에게 유용한 것임을 나타낼 수 있습니다. + +## GitHub 저장소에서 릴리즈 확인 + +GitHub에서 FastAPI를 "watch"할 수 있습니다 (오른쪽 상단 watch 버튼을 클릭): https://github.com/fastapi/fastapi. 👀 + +여기서 "Releases only"을 선택할 수 있습니다. + +이렇게하면, **FastAPI** 의 버그 수정 및 새로운 기능의 구현 등의 새로운 자료 (최신 버전)이 있을 때마다 (이메일) 통지를 받을 수 있습니다. + +## 개발자와의 연결 + +개발자(Sebastián Ramírez / `tiangolo`)와 연락을 취할 수 있습니다. + +여러분은 할 수 있습니다: + +* **GitHub**에서 팔로우하기.. + * 당신에게 도움이 될 저의 다른 오픈소스 프로젝트를 확인하십시오. + * 새로운 오픈소스 프로젝트를 만들었을 때 확인하려면 팔로우 하십시오. +* **Twitter** 또는 Mastodon에서 팔로우하기. + * FastAPI의 사용 용도를 알려주세요 (그것을 듣는 것을 좋아합니다). + * 발표나 새로운 툴 출시 소식을 받아보십시오. + * **Twitter**의 @fastapi를 팔로우 (별도 계정에서) 할 수 있습니다. +* **LinkedIn**에서 팔로우하기.. + * 새로운 툴의 발표나 출시 소식을 받아보십시오. (단, Twitter를 더 자주 사용합니다 🤷‍♂). +* **Dev.to** 또는 **Medium**에서 제가 작성한 내용을 읽어 보십시오 (또는 팔로우). + * 다른 기사나 아이디어들을 읽고, 제가 만들어왔던 툴에 대해서도 읽으십시오. + * 새로운 기사를 읽기 위해 팔로우 하십시오. + +## **FastAPI**에 대한 트윗 + +**FastAPI**에 대해 트윗 하고 FastAPI가 마음에 드는 이유를 알려주세요. 🎉 + +**FastAPI**가 어떻게 사용되고 있는지, 어떤 점이 마음에 들었는지, 어떤 프로젝트/회사에서 사용하고 있는지 등에 대해 듣고 싶습니다. + +## FastAPI에 투표하기 + +* Slant에서 **FastAPI** 에 대해 투표하십시오. +* AlternativeTo에서 **FastAPI** 에 대해 투표하십시오. +* StackShare에서 **FastAPI** 에 대해 투표하십시오. + +## GitHub의 이슈로 다른사람 돕기 + +다른 사람들의 질문에 도움을 줄 수 있습니다: + +* GitHub 디스커션 +* GitHub 이슈 + +많은 경우, 여러분은 이미 그 질문에 대한 답을 알고 있을 수도 있습니다. 🤓 + +만약 많은 사람들의 문제를 도와준다면, 공식적인 [FastAPI 전문가](fastapi-people.md#fastapi-experts){.internal-link target=\_blank} 가 될 것입니다. 🎉 + +가장 중요한 점은: 친절하려고 노력하는 것입니다. 사람들은 좌절감을 안고 오며, 많은 경우 최선의 방식으로 질문하지 않을 수도 있습니다. 하지만 최대한 친절하게 대하려고 노력하세요. 🤗 + +**FastAPI** 커뮤니티의 목표는 친절하고 환영하는 것입니다. 동시에, 괴롭힘이나 무례한 행동을 받아들이지 마세요. 우리는 서로를 돌봐야 합니다. + +--- + +다른 사람들의 질문 (디스커션 또는 이슈에서) 해결을 도울 수 있는 방법은 다음과 같습니다. + +### 질문 이해하기 + +* 질문하는 사람이 가진 **목적**과 사용 사례를 이해할 수 있는지 확인하세요. + +* 질문 (대부분은 질문입니다)이 **명확**한지 확인하세요. + +* 많은 경우, 사용자가 가정한 해결책에 대한 질문을 하지만, 더 **좋은** 해결책이 있을 수 있습니다. 문제와 사용 사례를 더 잘 이해하면 더 나은 **대안적인 해결책**을 제안할 수 있습니다. + +* 질문을 이해할 수 없다면, 더 **자세한 정보**를 요청하세요. + +### 문제 재현하기 + +대부분의 경우, 질문은 질문자의 **원본 코드**와 관련이 있습니다. + +많은 경우, 코드의 일부만 복사해서 올리지만, 그것만으로는 **문제를 재현**하기에 충분하지 않습니다. + +* 질문자에게 최소한의 재현 가능한 예제를 제공해달라고 요청하세요. 이렇게 하면 코드를 **복사-붙여넣기**하여 직접 실행하고, 동일한 오류나 동작을 확인하거나 사용 사례를 더 잘 이해할 수 있습니다. + +* 너그러운 마음이 든다면, 문제 설명만을 기반으로 직접 **예제를 만들어**볼 수도 있습니다. 하지만, 이는 시간이 많이 걸릴 수 있으므로, 먼저 질문을 명확히 해달라고 요청하는 것이 좋습니다. + +### 해결책 제안하기 + +* 질문을 충분히 이해한 후에는 가능한 **답변**을 제공할 수 있습니다. + +* 많은 경우, 질문자의 **근본적인 문제나 사용 사례**를 이해하는 것이 중요합니다. 그들이 시도하는 방법보다 더 나은 해결책이 있을 수 있기 때문입니다. + +### 해결 요청하기 + +질문자가 답변을 확인하고 나면, 당신이 문제를 해결했을 가능성이 높습니다. 축하합니다, **당신은 영웅입니다**! 🦸 + +* 이제 문제를 해결했다면, 질문자에게 다음을 요청할 수 있습니다. + + * GitHub 디스커션에서: 댓글을 **답변**으로 표시하도록 요청하세요. + * GitHub 이슈에서: 이슈를 **닫아달라고** 요청하세요. + +## GitHub 저장소 보기 + +GitHub에서 FastAPI를 "watch"할 수 있습니다 (오른쪽 상단 watch 버튼을 클릭): https://github.com/fastapi/fastapi. 👀 + +"Releases only" 대신 "Watching"을 선택하면, 새로운 이슈나 질문이 생성될 때 알림을 받을 수 있습니다. 또한, 특정하게 새로운 이슈, 디스커션, PR 등만 알림 받도록 설정할 수도 있습니다. + +그런 다음 이런 이슈들을 해결 할 수 있도록 도움을 줄 수 있습니다. + +## 이슈 생성하기 + +GitHub 저장소에 새로운 이슈 생성을 할 수 있습니다, 예를들면 다음과 같습니다: + +* **질문**을 하거나 **문제**에 대해 질문합니다. +* 새로운 **기능**을 제안 합니다. + +**참고**: 만약 이슈를 생성한다면, 저는 여러분에게 다른 사람들을 도와달라고 부탁할 것입니다. 😉 + +## Pull Requests 리뷰하기 + +다른 사람들의 pull request를 리뷰하는 데 도움을 줄 수 있습니다. + +다시 한번 말하지만, 최대한 친절하게 리뷰해 주세요. 🤗 + +--- + +Pull Rrquest를 리뷰할 때 고려해야 할 사항과 방법은 다음과 같습니다: + +### 문제 이해하기 + +* 먼저, 해당 pull request가 해결하려는 **문제를 이해하는지** 확인하세요. GitHub 디스커션 또는 이슈에서 더 긴 논의가 있었을 수도 있습니다. + +* Pull request가 필요하지 않을 가능성도 있습니다. **다른 방식**으로 문제를 해결할 수 있다면, 그 방법을 제안하거나 질문할 수 있습니다. + +### 스타일에 너무 신경 쓰지 않기 + +* 커밋 메시지 스타일 같은 것에 너무 신경 쓰지 않아도 됩니다. 저는 직접 커밋을 수정하여 squash and merge를 수행할 것입니다. + +* 코드 스타일 규칙도 걱정할 필요 없습니다. 이미 자동화된 도구들이 이를 검사하고 있습니다. + +스타일이나 일관성 관련 요청이 필요한 경우, 제가 직접 요청하거나 필요한 변경 사항을 추가 커밋으로 수정할 것입니다. + +### 코드 확인하기 + +* 코드를 읽고, **논리적으로 타당**한지 확인한 후 로컬에서 실행하여 문제가 해결되는지 확인하세요. + +* 그런 다음, 확인했다고 **댓글**을 남겨 주세요. 그래야 제가 검토했음을 알 수 있습니다. + +/// info + +불행히도, 제가 단순히 여러 개의 승인만으로 PR을 신뢰할 수는 없습니다. + +3개, 5개 이상의 승인이 달린 PR이 실제로는 깨져 있거나, 버그가 있거나, 주장하는 문제를 해결하지 못하는 경우가 여러 번 있었습니다. 😅 + +따라서, 정말로 코드를 읽고 실행한 뒤, 댓글로 확인 내용을 남겨 주는 것이 매우 중요합니다. 🤓 + +/// + +* PR을 더 단순하게 만들 수 있다면 그렇게 요청할 수 있지만, 너무 까다로울 필요는 없습니다. 주관적인 견해가 많이 있을 수 있기 때문입니다 (그리고 저도 제 견해가 있을 거예요 🙈). 따라서 핵심적인 부분에 집중하는 것이 좋습니다. + +### 테스트 + +* PR에 **테스트**가 포함되어 있는지 확인하는 데 도움을 주세요. + +* PR을 적용하기 전에 테스트가 **실패**하는지 확인하세요. 🚨 + +* PR을 적용한 후 테스트가 **통과**하는지 확인하세요. ✅ + +* 많은 PR에는 테스트가 없습니다. 테스트를 추가하도록 **상기**시켜줄 수도 있고, 직접 테스트를 **제안**할 수도 있습니다. 이는 시간이 많이 소요되는 부분 중 하나이며, 그 부분을 많이 도와줄 수 있습니다. + +* 그리고 시도한 내용을 댓글로 남겨주세요. 그러면 제가 확인했다는 걸 알 수 있습니다. 🤓 + +## Pull Request를 만드십시오 + +Pull Requests를 이용하여 소스코드에 [컨트리뷰트](contributing.md){.internal-link target=\_blank} 할 수 있습니다. 예를 들면 다음과 같습니다: + +* 문서에서 발견한 오타를 수정할 때. +* FastAPI 관련 문서, 비디오 또는 팟캐스트를 작성했거나 발견하여 이 파일을 편집하여 공유할 때. + * 해당 섹션의 시작 부분에 링크를 추가해야 합니다. +* 당신의 언어로 [문서 번역하는데](contributing.md#translations){.internal-link target=\_blank} 기여할 때. + * 다른 사람이 작성한 번역을 검토하는 것도 도울 수 있습니다. +* 새로운 문서의 섹션을 제안할 때. +* 기존 문제/버그를 수정할 때. + * 테스트를 반드시 추가해야 합니다. +* 새로운 feature를 추가할 때. + * 테스트를 반드시 추가해야 합니다. + * 관련 문서가 필요하다면 반드시 추가해야 합니다. + +## FastAPI 유지 관리에 도움 주기 + +**FastAPI**의 유지 관리를 도와주세요! 🤓 + +할 일이 많고, 그 중 대부분은 **여러분**이 할 수 있습니다. + +지금 할 수 있는 주요 작업은: + +* [GitHub에서 다른 사람들의 질문에 도움 주기](#github_1){.internal-link target=_blank} (위의 섹션을 참조하세요). +* [Pull Request 리뷰하기](#pull-requests){.internal-link target=_blank} (위의 섹션을 참조하세요). + +이 두 작업이 **가장 많은 시간을 소모**하는 일입니다. 그것이 FastAPI 유지 관리의 주요 작업입니다. + +이 작업을 도와주신다면, **FastAPI 유지 관리에 도움을 주는 것**이며 그것이 **더 빠르고 더 잘 발전하는 것**을 보장하는 것입니다. 🚀 + +## 채팅에 참여하십시오 + +👥 디스코드 채팅 서버 👥 에 가입하고 FastAPI 커뮤니티에서 다른 사람들과 어울리세요. + +/// tip + +질문이 있는 경우, GitHub 디스커션 에서 질문하십시오, [FastAPI Experts](fastapi-people.md#fastapi-experts){.internal-link target=_blank} 의 도움을 받을 가능성이 높습니다. + +다른 일반적인 대화에서만 채팅을 사용하십시오. + +/// + +### 질문을 위해 채팅을 사용하지 마십시오 + +채팅은 더 많은 "자유로운 대화"를 허용하기 때문에, 너무 일반적인 질문이나 대답하기 어려운 질문을 쉽게 질문을 할 수 있으므로, 답변을 받지 못할 수 있습니다. + +GitHub 이슈에서의 템플릿은 올바른 질문을 작성하도록 안내하여 더 쉽게 좋은 답변을 얻거나 질문하기 전에 스스로 문제를 해결할 수도 있습니다. 그리고 GitHub에서는 시간이 조금 걸리더라도 항상 모든 것에 답할 수 있습니다. 채팅 시스템에서는 개인적으로 그렇게 할 수 없습니다. 😅 + +채팅 시스템에서의 대화 또한 GitHub에서 처럼 쉽게 검색할 수 없기 때문에 대화 중에 질문과 답변이 손실될 수 있습니다. 그리고 GitHub 이슈에 있는 것만 [FastAPI Expert](fastapi-people.md#fastapi-experts){.internal-link target=_blank}가 되는 것으로 간주되므로, GitHub 이슈에서 더 많은 관심을 받을 것입니다. + +반면, 채팅 시스템에는 수천 명의 사용자가 있기 때문에, 거의 항상 대화 상대를 찾을 가능성이 높습니다. 😄 + +## 개발자 스폰서가 되십시오 + +GitHub 스폰서 를 통해 개발자를 경제적으로 지원할 수 있습니다. + +감사하다는 말로 커피를 ☕️ 한잔 사줄 수 있습니다. 😄 + +또한 FastAPI의 실버 또는 골드 스폰서가 될 수 있습니다. 🏅🎉 + +## FastAPI를 강화하는 도구의 스폰서가 되십시오 + +문서에서 보았듯이, FastAPI는 Starlette과 Pydantic 라는 거인의 어깨에 타고 있습니다. + +다음의 스폰서가 될 수 있습니다 + +* Samuel Colvin (Pydantic) +* Encode (Starlette, Uvicorn) + +--- + +감사합니다! 🚀 diff --git a/docs/ko/docs/history-design-future.md b/docs/ko/docs/history-design-future.md new file mode 100644 index 000000000..6680a46e7 --- /dev/null +++ b/docs/ko/docs/history-design-future.md @@ -0,0 +1,81 @@ +# 역사, 디자인 그리고 미래 + +어느 날, [한 FastAPI 사용자](https://github.com/fastapi/fastapi/issues/3#issuecomment-454956920)가 이렇게 물었습니다: + +> 이 프로젝트의 역사를 알려 주실 수 있나요? 몇 주 만에 멋진 결과를 낸 것 같아요. [...] + +여기서 그 역사에 대해 간단히 설명하겠습니다. + +--- + +## 대안 + +저는 여러 해 동안 머신러닝, 분산 시스템, 비동기 작업, NoSQL 데이터베이스 같은 복잡한 요구사항을 가진 API를 개발하며 여러 팀을 이끌어 왔습니다. + +이 과정에서 많은 대안을 조사하고, 테스트하며, 사용해야 했습니다. **FastAPI**의 역사는 그 이전에 나왔던 여러 도구의 역사와 밀접하게 연관되어 있습니다. + +[대안](alternatives.md){.internal-link target=_blank} 섹션에서 언급된 것처럼: + +> **FastAPI**는 이전에 나왔던 많은 도구들의 노력 없이는 존재하지 않았을 것입니다. +> +> 이전에 개발된 여러 도구들이 이 프로젝트에 영감을 주었습니다. +> +> 저는 오랫동안 새로운 프레임워크를 만드는 것을 피하고자 했습니다. 처음에는 **FastAPI**가 제공하는 기능들을 다양한 프레임워크와 플러그인, 도구들을 조합해 해결하려 했습니다. +> +> 하지만 결국에는 이 모든 기능을 통합하는 도구가 필요해졌습니다. 이전 도구들로부터 최고의 아이디어들을 모으고, 이를 최적의 방식으로 조합해야만 했습니다. 이는 :term:Python 3.6+ 타입 힌트 와 같은, 이전에는 사용할 수 없었던 언어 기능이 가능했기 때문입니다. + +--- + +## 조사 + +여러 대안을 사용해 보며 다양한 도구에서 배운 점들을 모아 저와 개발팀에게 가장 적합한 방식을 찾았습니다. + +예를 들어, 표준 :term:Python 타입 힌트 에 기반하는 것이 이상적이라는 점이 명확했습니다. + +또한, 이미 존재하는 표준을 활용하는 것이 가장 좋은 접근법이라 판단했습니다. + +그래서 **FastAPI**의 코드를 작성하기 전에 몇 달 동안 OpenAPI, JSON Schema, OAuth2 명세를 연구하며 이들의 관계와 겹치는 부분, 차이점을 이해했습니다. + +--- + +## 디자인 + +그 후, **FastAPI** 사용자가 될 개발자로서 사용하고 싶은 개발자 "API"를 디자인했습니다. + +[Python Developer Survey](https://www.jetbrains.com/research/python-developers-survey-2018/#development-tools)에 따르면 약 80%의 Python 개발자가 PyCharm, VS Code, Jedi 기반 편집기 등에서 개발합니다. 이 과정에서 여러 아이디어를 테스트했습니다. + +대부분의 다른 편집기도 유사하게 동작하기 때문에, **FastAPI**의 이점은 거의 모든 편집기에서 누릴 수 있습니다. + +이 과정을 통해 코드 중복을 최소화하고, 모든 곳에서 자동 완성, 타입 검사, 에러 확인 기능이 제공되는 최적의 방식을 찾아냈습니다. + +이 모든 것은 개발자들에게 최고의 개발 경험을 제공하기 위해 설계되었습니다. + +--- + +## 필요조건 + +여러 대안을 테스트한 후, [Pydantic](https://docs.pydantic.dev/)을 사용하기로 결정했습니다. + +이후 저는 **Pydantic**이 JSON Schema와 완벽히 호환되도록 개선하고, 다양한 제약 조건 선언을 지원하며, 여러 편집기에서의 자동 완성과 타입 검사 기능을 향상하기 위해 기여했습니다. + +또한, 또 다른 주요 필요조건이었던 [Starlette](https://www.starlette.io/)에도 기여했습니다. + +--- + +## 개발 + +**FastAPI**를 개발하기 시작할 즈음에는 대부분의 준비가 이미 완료된 상태였습니다. 설계가 정의되었고, 필요조건과 도구가 준비되었으며, 표준과 명세에 대한 지식도 충분했습니다. + +--- + +## 미래 + +현시점에서 **FastAPI**가 많은 사람들에게 유용하다는 것이 명백해졌습니다. + +여러 용도에 더 적합한 도구로서 기존 대안보다 선호되고 있습니다. +이미 많은 개발자와 팀들이 **FastAPI**에 의존해 프로젝트를 진행 중입니다 (저와 제 팀도 마찬가지입니다). + +하지만 여전히 개선해야 할 점과 추가할 기능들이 많이 남아 있습니다. + +**FastAPI**는 밝은 미래로 나아가고 있습니다. +그리고 [여러분의 도움](help-fastapi.md){.internal-link target=_blank}은 큰 힘이 됩니다. diff --git a/docs/ko/docs/how-to/conditional-openapi.md b/docs/ko/docs/how-to/conditional-openapi.md new file mode 100644 index 000000000..79c7f0dd2 --- /dev/null +++ b/docs/ko/docs/how-to/conditional-openapi.md @@ -0,0 +1,61 @@ +# 조건부적인 OpenAPI + +필요한 경우, 설정 및 환경 변수를 사용하여 환경에 따라 조건부로 OpenAPI를 구성하고 완전히 비활성화할 수도 있습니다. + +## 보안, API 및 docs에 대해서 + +프로덕션에서, 문서화된 사용자 인터페이스(UI)를 숨기는 것이 API를 보호하는 방법이 *되어서는 안 됩니다*. + +이는 API에 추가적인 보안을 제공하지 않으며, *경로 작업*은 여전히 동일한 위치에서 사용 할 수 있습니다. + +코드에 보안 결함이 있다면, 그 결함은 여전히 존재할 것입니다. + +문서를 숨기는 것은 API와 상호작용하는 방법을 이해하기 어렵게 만들며, 프로덕션에서 디버깅을 더 어렵게 만들 수 있습니다. 이는 단순히 '모호성에 의한 보안'의 한 형태로 간주될 수 있습니다. + +API를 보호하고 싶다면, 예를 들어 다음과 같은 더 나은 방법들이 있습니다: + +* 요청 본문과 응답에 대해 잘 정의된 Pydantic 모델을 사용하도록 하세요. + +* 종속성을 사용하여 필요한 권한과 역할을 구성하세요. + +* 평문 비밀번호를 절대 저장하지 말고, 오직 암호화된 비밀번호만 저장하세요. + +* Passlib과 JWT 토큰과 같은 잘 알려진 암호화 도구들을 구현하고 사용하세요. + +* 필요한 곳에 OAuth2 범위를 사용하여 더 세분화된 권한 제어를 추가하세요. + +* 등등.... + +그럼에도 불구하고, 특정 환경(예: 프로덕션)에서 또는 환경 변수의 설정에 따라 API 문서를 비활성화해야 하는 매우 특정한 사용 사례가 있을 수 있습니다. + +## 설정 및 환경변수의 조건부 OpenAPI + +동일한 Pydantic 설정을 사용하여 생성된 OpenAPI 및 문서 UI를 쉽게 구성할 수 있습니다. + +예를 들어: + +{* ../../docs_src/conditional_openapi/tutorial001.py hl[6,11] *} + +여기서 `openapi_url` 설정을 기본값인 `"/openapi.json"`으로 선언합니다. + +그런 뒤, 우리는 `FastAPI` 앱을 만들 때 그것을 사용합니다. + +환경 변수 `OPENAPI_URL`을 빈 문자열로 설정하여 OpenAPI(문서 UI 포함)를 비활성화할 수도 있습니다. 예를 들어: + +
+ +```console +$ OPENAPI_URL= uvicorn main:app + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +그리고 `/openapi.json`, `/docs` 또는 `/redoc`의 URL로 이동하면 `404 Not Found`라는 오류가 다음과 같이 표시됩니다: + +```JSON +{ + "detail": "Not Found" +} +``` diff --git a/docs/ko/docs/how-to/configure-swagger-ui.md b/docs/ko/docs/how-to/configure-swagger-ui.md new file mode 100644 index 000000000..5a57342cf --- /dev/null +++ b/docs/ko/docs/how-to/configure-swagger-ui.md @@ -0,0 +1,70 @@ +# Swagger UI 구성 + +추가적인 Swagger UI 매개변수를 구성할 수 있습니다. + +구성을 하려면, `FastAPI()` 앱 객체를 생성할 때 또는 `get_swagger_ui_html()` 함수에 `swagger_ui_parameters` 인수를 전달하십시오. + +`swagger_ui_parameters`는 Swagger UI에 직접 전달된 구성을 포함하는 딕셔너리를 받습니다. + +FastAPI는 이 구성을 **JSON** 형식으로 변환하여 JavaScript와 호환되도록 합니다. 이는 Swagger UI에서 필요로 하는 형식입니다. + +## 구문 강조 비활성화 + +예를 들어, Swagger UI에서 구문 강조 기능을 비활성화할 수 있습니다. + +설정을 변경하지 않으면, 기본적으로 구문 강조 기능이 활성화되어 있습니다: + + + +그러나 `syntaxHighlight`를 `False`로 설정하여 구문 강조 기능을 비활성화할 수 있습니다: + +{* ../../docs_src/configure_swagger_ui/tutorial001.py hl[3] *} + +...그럼 Swagger UI에서 더 이상 구문 강조 기능이 표시되지 않습니다: + + + +## 테마 변경 + +동일한 방식으로 `"syntaxHighlight.theme"` 키를 사용하여 구문 강조 테마를 설정할 수 있습니다 (중간에 점이 포함된 것을 참고하십시오). + +{* ../../docs_src/configure_swagger_ui/tutorial002.py hl[3] *} + +이 설정은 구문 강조 색상 테마를 변경합니다: + + + +## 기본 Swagger UI 매개변수 변경 + +FastAPI는 대부분의 사용 사례에 적합한 몇 가지 기본 구성 매개변수를 포함하고 있습니다. + +기본 구성에는 다음이 포함됩니다: + +{* ../../fastapi/openapi/docs.py ln[8:23] hl[17:23] *} + +`swagger_ui_parameters` 인수에 다른 값을 설정하여 이러한 기본값 중 일부를 재정의할 수 있습니다. + +예를 들어, `deepLinking`을 비활성화하려면 `swagger_ui_parameters`에 다음 설정을 전달할 수 있습니다: + +{* ../../docs_src/configure_swagger_ui/tutorial003.py hl[3] *} + +## 기타 Swagger UI 매개변수 + +사용할 수 있는 다른 모든 구성 옵션을 확인하려면, Swagger UI 매개변수에 대한 공식 문서를 참조하십시오. + +## JavaScript 전용 설정 + +Swagger UI는 **JavaScript 전용** 객체(예: JavaScript 함수)로 다른 구성을 허용하기도 합니다. + +FastAPI는 이러한 JavaScript 전용 `presets` 설정을 포함하고 있습니다: + +```JavaScript +presets: [ + SwaggerUIBundle.presets.apis, + SwaggerUIBundle.SwaggerUIStandalonePreset +] +``` + +이들은 문자열이 아닌 **JavaScript** 객체이므로 Python 코드에서 직접 전달할 수 없습니다. + +이와 같은 JavaScript 전용 구성을 사용해야 하는 경우, 위의 방법 중 하나를 사용하여 모든 Swagger UI 경로 작업을 재정의하고 필요한 JavaScript를 수동으로 작성할 수 있습니다. diff --git a/docs/ko/docs/index.md b/docs/ko/docs/index.md index 594b092f7..0df2000fa 100644 --- a/docs/ko/docs/index.md +++ b/docs/ko/docs/index.md @@ -1,3 +1,9 @@ +# FastAPI + + +

FastAPI

@@ -5,30 +11,33 @@ FastAPI 프레임워크, 고성능, 간편한 학습, 빠른 코드 작성, 준비된 프로덕션

- - Test + + Test - - Coverage + + Coverage Package version + + Supported Python versions +

--- **문서**: https://fastapi.tiangolo.com -**소스 코드**: https://github.com/tiangolo/fastapi +**소스 코드**: https://github.com/fastapi/fastapi --- -FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트에 기초한 Python3.8+의 API를 빌드하기 위한 웹 프레임워크입니다. +FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트에 기초한 Python의 API를 빌드하기 위한 웹 프레임워크입니다. 주요 특징으로: -* **빠름**: (Starlette과 Pydantic 덕분에) **NodeJS** 및 **Go**와 대등할 정도로 매우 높은 성능. [사용 가능한 가장 빠른 파이썬 프레임워크 중 하나](#performance). +* **빠름**: (Starlette과 Pydantic 덕분에) **NodeJS** 및 **Go**와 대등할 정도로 매우 높은 성능. [사용 가능한 가장 빠른 파이썬 프레임워크 중 하나](#_11). * **빠른 코드 작성**: 약 200%에서 300%까지 기능 개발 속도 증가. * * **적은 버그**: 사람(개발자)에 의한 에러 약 40% 감소. * @@ -61,7 +70,7 @@ FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트 "_[...] 저는 요즘 **FastAPI**를 많이 사용하고 있습니다. [...] 사실 우리 팀의 **마이크로소프트 ML 서비스** 전부를 바꿀 계획입니다. 그중 일부는 핵심 **Windows**와 몇몇의 **Office** 제품들이 통합되고 있습니다._" -
Kabir Khan - 마이크로소프트 (ref)
+
Kabir Khan - 마이크로소프트 (ref)
--- @@ -107,12 +116,10 @@ FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트 ## 요구사항 -Python 3.8+ - FastAPI는 거인들의 어깨 위에 서 있습니다: * 웹 부분을 위한 Starlette. -* 데이터 부분을 위한 Pydantic. +* 데이터 부분을 위한 Pydantic. ## 설치 @@ -126,7 +133,7 @@ $ pip install fastapi -프로덕션을 위해 Uvicorn 또는 Hypercorn과 같은 ASGI 서버도 필요할 겁니다. +프로덕션을 위해 Uvicorn 또는 Hypercorn과 같은 ASGI 서버도 필요할 겁니다.
@@ -323,7 +330,7 @@ def update_item(item_id: int, item: Item): 새로운 문법, 특정 라이브러리의 메소드나 클래스 등을 배울 필요가 없습니다. -그저 표준 **Python 3.8+** 입니다. +그저 표준 **Python** 입니다. 예를 들어, `int`에 대해선: @@ -386,7 +393,7 @@ item: Item --- -우리는 그저 수박 겉핡기만 했을 뿐인데 여러분은 벌써 어떻게 작동하는지 알고 있습니다. +우리는 그저 수박 겉 핥기만 했을 뿐인데 여러분은 벌써 어떻게 작동하는지 알고 있습니다. 다음 줄을 바꿔보십시오: @@ -437,22 +444,22 @@ item: Item Pydantic이 사용하는: -* email_validator - 이메일 유효성 검사. +* email-validator - 이메일 유효성 검사. Starlette이 사용하는: * HTTPX - `TestClient`를 사용하려면 필요. * jinja2 - 기본 템플릿 설정을 사용하려면 필요. -* python-multipart - `request.form()`과 함께 "parsing"의 지원을 원하면 필요. +* python-multipart - `request.form()`과 함께 "parsing"의 지원을 원하면 필요. * itsdangerous - `SessionMiddleware` 지원을 위해 필요. * pyyaml - Starlette의 `SchemaGenerator` 지원을 위해 필요 (FastAPI와 쓸때는 필요 없을 것입니다). * graphene - `GraphQLApp` 지원을 위해 필요. -* ujson - `UJSONResponse`를 사용하려면 필요. FastAPI / Starlette이 사용하는: * uvicorn - 애플리케이션을 로드하고 제공하는 서버. * orjson - `ORJSONResponse`을 사용하려면 필요. +* ujson - `UJSONResponse`를 사용하려면 필요. `pip install fastapi[all]`를 통해 이 모두를 설치 할 수 있습니다. diff --git a/docs/ko/docs/learn/index.md b/docs/ko/docs/learn/index.md new file mode 100644 index 000000000..7ac3a99b6 --- /dev/null +++ b/docs/ko/docs/learn/index.md @@ -0,0 +1,5 @@ +# 배우기 + +여기 **FastAPI**를 배우기 위한 입문 자료와 자습서가 있습니다. + +여러분은 FastAPI를 배우기 위해 **책**, **강의**, **공식 자료** 그리고 추천받은 방법을 고려할 수 있습니다. 😎 diff --git a/docs/ko/docs/openapi-webhooks.md b/docs/ko/docs/openapi-webhooks.md new file mode 100644 index 000000000..96339aa96 --- /dev/null +++ b/docs/ko/docs/openapi-webhooks.md @@ -0,0 +1,55 @@ +# OpenAPI 웹훅(Webhooks) + +API **사용자**에게 특정 **이벤트**가 발생할 때 *그들*의 앱(시스템)에 요청을 보내 **알림**을 전달할 수 있다는 것을 알리고 싶은 경우가 있습니다. + +즉, 일반적으로 사용자가 API에 요청을 보내는 것과는 반대로, **API**(또는 앱)가 **사용자의 시스템**(그들의 API나 앱)으로 **요청을 보내는** 상황을 의미합니다. + +이를 흔히 **웹훅(Webhook)**이라고 부릅니다. + +## 웹훅 스텝 + +**코드에서** 웹훅으로 보낼 메시지, 즉 요청의 **바디(body)**를 정의하는 것이 일반적인 프로세스입니다. + +앱에서 해당 요청이나 이벤트를 전송할 **시점**을 정의합니다. + +**사용자**는 앱이 해당 요청을 보낼 **URL**을 정의합니다. (예: 웹 대시보드에서 설정) + +웹훅의 URL을 등록하는 방법과 이러한 요청을 실제로 전송하는 코드에 대한 모든 로직은 여러분에게 달려 있습니다. 원하는대로 **고유의 코드**를 작성하면 됩니다. + +## **FastAPI**와 OpenAPI로 웹훅 문서화하기 + +**FastAPI**를 사용하여 OpenAPI와 함께 웹훅의 이름, 앱이 보낼 수 있는 HTTP 작업 유형(예: `POST`, `PUT` 등), 그리고 보낼 요청의 **바디**를 정의할 수 있습니다. + +이를 통해 사용자가 **웹훅** 요청을 수신할 **API 구현**을 훨씬 쉽게 할 수 있으며, 경우에 따라 사용자 API 코드의 일부를 자동 생성할 수도 있습니다. + +/// info + +웹훅은 OpenAPI 3.1.0 이상에서 지원되며, FastAPI `0.99.0` 이상 버전에서 사용할 수 있습니다. + +/// + +## 웹훅이 포함된 앱 만들기 + +**FastAPI** 애플리케이션을 만들 때, `webhooks` 속성을 사용하여 *웹훅*을 정의할 수 있습니다. 이는 `@app.webhooks.post()`와 같은 방식으로 *경로(path) 작업*을 정의하는 것과 비슷합니다. + +{* ../../docs_src/openapi_webhooks/tutorial001.py hl[9:13,36:53] *} + +이렇게 정의한 웹훅은 **OpenAPI** 스키마와 자동 **문서화 UI**에 표시됩니다. + +/// info + +`app.webhooks` 객체는 사실 `APIRouter`일 뿐이며, 여러 파일로 앱을 구성할 때 사용하는 것과 동일한 타입입니다. + +/// + +웹훅에서는 실제 **경로(path)** (예: `/items/`)를 선언하지 않는 점에 유의해야 합니다. 여기서 전달하는 텍스트는 **식별자**로, 웹훅의 이름(이벤트 이름)입니다. 예를 들어, `@app.webhooks.post("new-subscription")`에서 웹훅 이름은 `new-subscription`입니다. + +이는 실제 **URL 경로**는 **사용자**가 다른 방법(예: 웹 대시보드)을 통해 지정하도록 기대되기 때문입니다. + +### 문서 확인하기 + +이제 앱을 시작하고 http://127.0.0.1:8000/docs로 이동해 봅시다. + +문서에서 기존 *경로 작업*뿐만 아니라 **웹훅**도 표시된 것을 확인할 수 있습니다: + + diff --git a/docs/ko/docs/project-generation.md b/docs/ko/docs/project-generation.md new file mode 100644 index 000000000..dd11fca70 --- /dev/null +++ b/docs/ko/docs/project-generation.md @@ -0,0 +1,28 @@ +# Full Stack FastAPI 템플릿 + +템플릿은 일반적으로 특정 설정과 함께 제공되지만, 유연하고 커스터마이징이 가능하게 디자인 되었습니다. 이 특성들은 여러분이 프로젝트의 요구사항에 맞춰 수정, 적용을 할 수 있게 해주고, 템플릿이 완벽한 시작점이 되게 해줍니다. 🏁 + +많은 초기 설정, 보안, 데이터베이스 및 일부 API 엔드포인트가 이미 준비되어 있으므로, 여러분은 이 템플릿을 (프로젝트를) 시작하는 데 사용할 수 있습니다. + +GitHub 저장소: Full Stack FastAPI 템플릿 + +## Full Stack FastAPI 템플릿 - 기술 스택과 기능들 + +- ⚡ [**FastAPI**](https://fastapi.tiangolo.com): Python 백엔드 API. + - 🧰 [SQLModel](https://sqlmodel.tiangolo.com): Python SQL 데이터 상호작용을 위한 (ORM). + - 🔍 [Pydantic](https://docs.pydantic.dev): FastAPI에 의해 사용되는, 데이터 검증과 설정관리. + - 💾 [PostgreSQL](https://www.postgresql.org): SQL 데이터베이스. +- 🚀 [React](https://react.dev): 프론트엔드. + - 💃 TypeScript, hooks, [Vite](https://vitejs.dev) 및 기타 현대적인 프론트엔드 스택을 사용. + - 🎨 [Chakra UI](https://chakra-ui.com): 프론트엔드 컴포넌트. + - 🤖 자동으로 생성된 프론트엔드 클라이언트. + - 🧪 E2E 테스트를 위한 [Playwright](https://playwright.dev). + - 🦇 다크 모드 지원. +- 🐋 [Docker Compose](https://www.docker.com): 개발 환경과 프로덕션(운영). +- 🔒 기본으로 지원되는 안전한 비밀번호 해싱. +- 🔑 JWT 토큰 인증. +- 📫 이메일 기반 비밀번호 복구. +- ✅ [Pytest]를 이용한 테스트(https://pytest.org). +- 📞 [Traefik](https://traefik.io): 리버스 프록시 / 로드 밸런서. +- 🚢 Docker Compose를 이용한 배포 지침: 자동 HTTPS 인증서를 처리하기 위한 프론트엔드 Traefik 프록시 설정 방법을 포함. +- 🏭 GitHub Actions를 기반으로 CI (지속적인 통합) 및 CD (지속적인 배포). diff --git a/docs/ko/docs/python-types.md b/docs/ko/docs/python-types.md new file mode 100644 index 000000000..18d4b341e --- /dev/null +++ b/docs/ko/docs/python-types.md @@ -0,0 +1,313 @@ +# 파이썬 타입 소개 + +파이썬은 선택적으로 "타입 힌트(type hints)"를 지원합니다. + +이러한 **타입 힌트**들은 변수의 타입을 선언할 수 있게 해주는 특수한 구문입니다. + +변수의 타입을 지정하면 에디터와 툴이 더 많은 도움을 줄 수 있게 됩니다. + +이 문서는 파이썬 타입 힌트에 대한 **빠른 자습서 / 내용환기** 수준의 문서입니다. 여기서는 **FastAPI**를 쓰기 위한 최소한의 내용만을 다룹니다. + +**FastAPI**는 타입 힌트에 기반을 두고 있으며, 이는 많은 장점과 이익이 있습니다. + +비록 **FastAPI**를 쓰지 않는다고 하더라도, 조금이라도 알아두면 도움이 될 것입니다. + +/// note | 참고 + +파이썬에 능숙하셔서 타입 힌트에 대해 모두 아신다면, 다음 챕터로 건너뛰세요. + +/// + +## 동기 부여 + +간단한 예제부터 시작해봅시다: + +{* ../../docs_src/python_types/tutorial001.py *} + + +이 프로그램을 실행한 결과값: + +``` +John Doe +``` + +함수는 아래와 같이 실행됩니다: + +* `first_name`과 `last_name`를 받습니다. +* `title()`로 각 첫 문자를 대문자로 변환시킵니다. +* 두 단어를 중간에 공백을 두고 연결합니다. + +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + + +### 코드 수정 + +이건 매우 간단한 프로그램입니다. + +그런데 처음부터 작성한다고 생각을 해봅시다. + +여러분은 매개변수를 준비했고, 함수를 정의하기 시작했을 겁니다. + +이때 "첫 글자를 대문자로 바꾸는 함수"를 호출해야 합니다. + +`upper`였나? 아니면 `uppercase`? `first_uppercase`? `capitalize`? + +그때 개발자들의 오랜 친구, 에디터 자동완성을 시도해봅니다. + +당신은 `first_name`를 입력한 뒤 점(`.`)을 입력하고 자동완성을 켜기 위해서 `Ctrl+Space`를 눌렀습니다. + +하지만 슬프게도 아무런 도움이 되지 않습니다: + + + +### 타입 추가하기 + +이전 버전에서 한 줄만 수정해봅시다. + +저희는 이 함수의 매개변수 부분: + +```Python + first_name, last_name +``` + +을 아래와 같이 바꿀 겁니다: + +```Python + first_name: str, last_name: str +``` + +이게 다입니다. + +이게 "타입 힌트"입니다: + +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + + +타입힌트는 다음과 같이 기본 값을 선언하는 것과는 다릅니다: + +```Python + first_name="john", last_name="doe" +``` + +이는 다른 것입니다. + +등호(`=`) 대신 콜론(`:`)을 쓰고 있습니다. + +일반적으로 타입힌트를 추가한다고 해서 특별하게 어떤 일이 일어나지도 않습니다. + +그렇지만 이제, 다시 함수를 만드는 도중이라고 생각해봅시다. 다만 이번엔 타입 힌트가 있습니다. + +같은 상황에서 `Ctrl+Space`로 자동완성을 작동시키면, + + + +아래와 같이 "그렇지!"하는 옵션이 나올때까지 스크롤을 내려서 볼 수 있습니다: + + + +## 더 큰 동기부여 + +아래 함수를 보면, 이미 타입 힌트가 적용되어 있는 걸 볼 수 있습니다: + +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + + +편집기가 변수의 타입을 알고 있기 때문에, 자동완성 뿐 아니라 에러도 확인할 수 있습니다: + + + +이제 고쳐야하는 걸 알기 때문에, `age`를 `str(age)`과 같이 문자열로 바꾸게 됩니다: + +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + + +## 타입 선언 + +방금 함수의 매개변수로써 타입 힌트를 선언하는 주요 장소를 보았습니다. + +이 위치는 여러분이 **FastAPI**와 함께 이를 사용하는 주요 장소입니다. + +### Simple 타입 + +`str`뿐 아니라 모든 파이썬 표준 타입을 선언할 수 있습니다. + +예를 들면: + +* `int` +* `float` +* `bool` +* `bytes` + +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + + +### 타입 매개변수를 활용한 Generic(제네릭) 타입 + +`dict`, `list`, `set`, `tuple`과 같은 값을 저장할 수 있는 데이터 구조가 있고, 내부의 값은 각자의 타입을 가질 수도 있습니다. + +타입과 내부 타입을 선언하기 위해서는 파이썬 표준 모듈인 `typing`을 이용해야 합니다. + +구체적으로는 아래 타입 힌트를 지원합니다. + +#### `List` + +예를 들면, `str`의 `list`인 변수를 정의해봅시다. + +`typing`에서 `List`(대문자 `L`)를 import 합니다. + +{* ../../docs_src/python_types/tutorial006.py hl[1] *} + + +콜론(`:`) 문법을 이용하여 변수를 선언합니다. + +타입으로는 `List`를 넣어줍니다. + +이때 배열은 내부 타입을 포함하는 타입이기 때문에 대괄호 안에 넣어줍니다. + +{* ../../docs_src/python_types/tutorial006.py hl[4] *} + + +/// tip | 팁 + +대괄호 안의 내부 타입은 "타입 매개변수(type paramters)"라고 합니다. + +이번 예제에서는 `str`이 `List`에 들어간 타입 매개변수 입니다. + +/// + +이는 "`items`은 `list`인데, 배열에 들어있는 아이템 각각은 `str`이다"라는 뜻입니다. + +이렇게 함으로써, 에디터는 배열에 들어있는 아이템을 처리할때도 도움을 줄 수 있게 됩니다: + + + +타입이 없으면 이건 거의 불가능이나 다름 없습니다. + +변수 `item`은 `items`의 개별 요소라는 사실을 알아두세요. + +그리고 에디터는 계속 `str`라는 사실을 알고 도와줍니다. + +#### `Tuple`과 `Set` + +`tuple`과 `set`도 동일하게 선언할 수 있습니다. + +{* ../../docs_src/python_types/tutorial007.py hl[1,4] *} + + +이 뜻은 아래와 같습니다: + +* 변수 `items_t`는, 차례대로 `int`, `int`, `str`인 `tuple`이다. +* 변수 `items_s`는, 각 아이템이 `bytes`인 `set`이다. + +#### `Dict` + +`dict`를 선언하려면 컴마로 구분된 2개의 파라미터가 필요합니다. + +첫 번째 매개변수는 `dict`의 키(key)이고, + +두 번째 매개변수는 `dict`의 값(value)입니다. + +{* ../../docs_src/python_types/tutorial008.py hl[1,4] *} + + +이 뜻은 아래와 같습니다: + +* 변수 `prices`는 `dict`이다: + * `dict`의 키(key)는 `str`타입이다. (각 아이템의 이름(name)) + * `dict`의 값(value)는 `float`타입이다. (각 아이템의 가격(price)) + +#### `Optional` + +`str`과 같이 타입을 선언할 때 `Optional`을 쓸 수도 있는데, "선택적(Optional)"이기때문에 `None`도 될 수 있습니다: + +```Python hl_lines="1 4" +{!../../docs_src/python_types/tutorial009.py!} +``` + +`Optional[str]`을 `str` 대신 쓰게 되면, 특정 값이 실제로는 `None`이 될 수도 있는데 항상 `str`이라고 가정하는 상황에서 에디터가 에러를 찾게 도와줄 수 있습니다. + +#### Generic(제네릭) 타입 + +이 타입은 대괄호 안에 매개변수를 가지며, 종류는: + +* `List` +* `Tuple` +* `Set` +* `Dict` +* `Optional` +* ...등등 + +위와 같은 타입은 **Generic(제네릭) 타입** 혹은 **Generics(제네릭스)**라고 불립니다. + +### 타입으로서의 클래스 + +변수의 타입으로 클래스를 선언할 수도 있습니다. + +이름(name)을 가진 `Person` 클래스가 있다고 해봅시다. + +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + + +그렇게 하면 변수를 `Person`이라고 선언할 수 있게 됩니다. + +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + + +그리고 역시나 모든 에디터 도움을 받게 되겠죠. + + + +## Pydantic 모델 + +Pydantic은 데이터 검증(Validation)을 위한 파이썬 라이브러리입니다. + +당신은 속성들을 포함한 클래스 형태로 "모양(shape)"을 선언할 수 있습니다. + +그리고 각 속성은 타입을 가지고 있습니다. + +이 클래스를 활용하여서 값을 가지고 있는 인스턴스를 만들게 되면, 필요한 경우에는 적당한 타입으로 변환까지 시키기도 하여 데이터가 포함된 객체를 반환합니다. + +그리고 결과 객체에 대해서는 에디터의 도움을 받을 수 있게 됩니다. + +Pydantic 공식 문서 예시: + +{* ../../docs_src/python_types/tutorial011.py *} + + +/// info | 정보 + +Pydantic<에 대해 더 배우고 싶다면 공식 문서를 참고하세요. + +/// + +**FastAPI**는 모두 Pydantic을 기반으로 되어 있습니다. + +이 모든 것이 실제로 어떻게 사용되는지에 대해서는 [자습서 - 사용자 안내서](tutorial/index.md){.internal-link target=_blank} 에서 더 많이 확인하실 수 있습니다. + +## **FastAPI**에서의 타입 힌트 + +**FastAPI**는 여러 부분에서 타입 힌트의 장점을 취하고 있습니다. + +**FastAPI**에서 타입 힌트와 함께 매개변수를 선언하면 장점은: + +* **에디터 도움**. +* **타입 확인**. + +...그리고 **FastAPI**는 같은 정의를 아래에도 적용합니다: + +* **요구사항 정의**: 요청 경로 매개변수, 쿼리 매개변수, 헤더, 바디, 의존성 등. +* **데이터 변환**: 요청에서 요구한 타입으로. +* **데이터 검증**: 각 요청마다: + * 데이터가 유효하지 않은 경우에는 **자동으로 에러**를 발생합니다. +* OpenAPI를 활용한 **API 문서화**: + * 자동으로 상호작용하는 유저 인터페이스에 쓰이게 됩니다. + +위 내용이 다소 추상적일 수도 있지만, 걱정마세요. [자습서 - 사용자 안내서](tutorial/index.md){.internal-link target=_blank}에서 전부 확인 가능합니다. + +가장 중요한 건, 표준 파이썬 타입을 한 곳에서(클래스를 더하거나, 데코레이터 사용하는 대신) 사용함으로써 **FastAPI**가 당신을 위해 많은 일을 해준다는 사실이죠. + +/// info | 정보 + +만약 모든 자습서를 다 보았음에도 타입에 대해서 더 보고자 방문한 경우에는 `mypy`에서 제공하는 "cheat sheet"이 좋은 자료가 될 겁니다. + +/// diff --git a/docs/ko/docs/resources/index.md b/docs/ko/docs/resources/index.md new file mode 100644 index 000000000..e804dd4d5 --- /dev/null +++ b/docs/ko/docs/resources/index.md @@ -0,0 +1,3 @@ +# 리소스 + +추가 리소스, 외부 링크, 기사 등. ✈️ diff --git a/docs/ko/docs/security/index.md b/docs/ko/docs/security/index.md new file mode 100644 index 000000000..5a6c733f0 --- /dev/null +++ b/docs/ko/docs/security/index.md @@ -0,0 +1,19 @@ +# 고급 보안 + +## 추가 기능 + +[자습서 - 사용자 가이드: 보안](../../tutorial/security/index.md){.internal-link target=_blank} 문서에서 다룬 내용 외에도 보안 처리를 위한 몇 가지 추가 기능이 있습니다. + +/// tip + +다음 섹션은 **반드시 "고급"** 기능은 아닙니다. + +그리고 여러분의 사용 사례에 따라, 적합한 해결책이 그 중 하나에 있을 가능성이 있습니다. + +/// + +## 먼저 자습서 읽기 + +다음 섹션은 이미 [자습서 - 사용자 가이드: 보안](../../tutorial/security/index.md){.internal-link target=_blank} 문서를 읽었다고 가정합니다. + +이 섹션들은 모두 동일한 개념을 바탕으로 하며, 추가 기능을 제공합니다. diff --git a/docs/ko/docs/tutorial/background-tasks.md b/docs/ko/docs/tutorial/background-tasks.md new file mode 100644 index 000000000..a2c4abbd9 --- /dev/null +++ b/docs/ko/docs/tutorial/background-tasks.md @@ -0,0 +1,84 @@ +# 백그라운드 작업 + +FastAPI에서는 응답을 반환한 후에 실행할 백그라운드 작업을 정의할 수 있습니다. + +백그라운드 작업은 클라이언트가 응답을 받기 위해 작업이 완료될 때까지 기다릴 필요가 없기 때문에 요청 후에 발생해야하는 작업에 매우 유용합니다. + +이러한 작업에는 다음이 포함됩니다. + +* 작업을 수행한 후 전송되는 이메일 알림 + * 이메일 서버에 연결하고 이메일을 전송하는 것은 (몇 초 정도) "느린" 경향이 있으므로, 응답은 즉시 반환하고 이메일 알림은 백그라운드에서 전송하는 게 가능합니다. +* 데이터 처리: + * 예를 들어 처리에 오랜 시간이 걸리는 데이터를 받았을 때 "Accepted" (HTTP 202)을 반환하고, 백그라운드에서 데이터를 처리할 수 있습니다. + +## `백그라운드 작업` 사용 + +먼저 아래와 같이 `BackgroundTasks`를 임포트하고, `BackgroundTasks`를 _경로 작동 함수_ 에서 매개변수로 가져오고 정의합니다. + +{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *} + +**FastAPI** 는 `BackgroundTasks` 개체를 생성하고, 매개 변수로 전달합니다. + +## 작업 함수 생성 + +백그라운드 작업으로 실행할 함수를 정의합니다. + +이것은 단순히 매개변수를 받을 수 있는 표준 함수일 뿐입니다. + +**FastAPI**는 이것이 `async def` 함수이든, 일반 `def` 함수이든 내부적으로 이를 올바르게 처리합니다. + +이 경우, 아래 작업은 파일에 쓰는 함수입니다. (이메일 보내기 시물레이션) + +그리고 이 작업은 `async`와 `await`를 사용하지 않으므로 일반 `def` 함수로 선언합니다. + +{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *} + +## 백그라운드 작업 추가 + +_경로 작동 함수_ 내에서 작업 함수를 `.add_task()` 함수 통해 _백그라운드 작업_ 개체에 전달합니다. + +{* ../../docs_src/background_tasks/tutorial001.py hl[14] *} + +`.add_task()` 함수는 다음과 같은 인자를 받습니다 : + +- 백그라운드에서 실행되는 작업 함수 (`write_notification`). +- 작업 함수에 순서대로 전달되어야 하는 일련의 인자 (`email`). +- 작업 함수에 전달되어야하는 모든 키워드 인자 (`message="some notification"`). + +## 의존성 주입 + +`BackgroundTasks`를 의존성 주입 시스템과 함께 사용하면 _경로 작동 함수_, 종속성, 하위 종속성 등 여러 수준에서 BackgroundTasks 유형의 매개변수를 선언할 수 있습니다. + +**FastAPI**는 각 경우에 수행할 작업과 동일한 개체를 내부적으로 재사용하기에, 모든 백그라운드 작업이 함께 병합되고 나중에 백그라운드에서 실행됩니다. + +{* ../../docs_src/background_tasks/tutorial002.py hl[13,15,22,25] *} + +이 예제에서는 응답이 반환된 후에 `log.txt` 파일에 메시지가 기록됩니다. + +요청에 쿼리가 있는 경우 백그라운드 작업의 로그에 기록됩니다. + +그리고 _경로 작동 함수_ 에서 생성된 또 다른 백그라운드 작업은 경로 매개 변수를 활용하여 사용하여 메시지를 작성합니다. + +## 기술적 세부사항 + +`BackgroundTasks` 클래스는 `starlette.background`에서 직접 가져옵니다. + +`BackgroundTasks` 클래스는 FastAPI에서 직접 임포트하거나 포함하기 때문에 실수로 `BackgroundTask` (끝에 `s`가 없음)을 임포트하더라도 starlette.background에서 `BackgroundTask`를 가져오는 것을 방지할 수 있습니다. + +(`BackgroundTask`가 아닌) `BackgroundTasks`를 사용하면, _경로 작동 함수_ 매개변수로 사용할 수 있게 되고 나머지는 **FastAPI**가 대신 처리하도록 할 수 있습니다. 이것은 `Request` 객체를 직접 사용하는 것과 같은 방식입니다. + +FastAPI에서 `BackgroundTask`를 단독으로 사용하는 것은 여전히 가능합니다. 하지만 객체를 코드에서 생성하고, 이 객체를 포함하는 Starlette `Response`를 반환해야 합니다. + +`Starlette의 공식 문서`에서 백그라운드 작업에 대한 자세한 내용을 확인할 수 있습니다. + +## 경고 + +만약 무거운 백그라운드 작업을 수행해야하고 동일한 프로세스에서 실행할 필요가 없는 경우 (예: 메모리, 변수 등을 공유할 필요가 없음) `Celery`와 같은 큰 도구를 사용하면 도움이 될 수 있습니다. + +RabbitMQ 또는 Redis와 같은 메시지/작업 큐 시스템 보다 복잡한 구성이 필요한 경향이 있지만, 여러 작업 프로세스를 특히 여러 서버의 백그라운드에서 실행할 수 있습니다. + +그러나 동일한 FastAPI 앱에서 변수 및 개체에 접근해야햐는 작은 백그라운드 수행이 필요한 경우 (예 : 알림 이메일 보내기) 간단하게 `BackgroundTasks`를 사용해보세요. + +## 요약 + +백그라운드 작업을 추가하기 위해 _경로 작동 함수_ 에 매개변수로 `BackgroundTasks`를 가져오고 사용합니다. diff --git a/docs/ko/docs/tutorial/body-fields.md b/docs/ko/docs/tutorial/body-fields.md new file mode 100644 index 000000000..4708e7099 --- /dev/null +++ b/docs/ko/docs/tutorial/body-fields.md @@ -0,0 +1,60 @@ +# 본문 - 필드 + +`Query`, `Path`와 `Body`를 사용해 *경로 작동 함수* 매개변수 내에서 추가적인 검증이나 메타데이터를 선언한 것처럼 Pydantic의 `Field`를 사용하여 모델 내에서 검증과 메타데이터를 선언할 수 있습니다. + +## `Field` 임포트 + +먼저 이를 임포트해야 합니다: + +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *} + +/// warning | 경고 + +`Field`는 다른 것들처럼 (`Query`, `Path`, `Body` 등) `fastapi`에서가 아닌 `pydantic`에서 바로 임포트 되는 점에 주의하세요. + +/// + +## 모델 어트리뷰트 선언 + +그 다음 모델 어트리뷰트와 함께 `Field`를 사용할 수 있습니다: + +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *} + +`Field`는 `Query`, `Path`와 `Body`와 같은 방식으로 동작하며, 모두 같은 매개변수들 등을 가집니다. + +/// note | 기술적 세부사항 + +실제로 `Query`, `Path`등, 여러분이 앞으로 볼 다른 것들은 공통 클래스인 `Param` 클래스의 서브클래스 객체를 만드는데, 그 자체로 Pydantic의 `FieldInfo` 클래스의 서브클래스입니다. + +그리고 Pydantic의 `Field` 또한 `FieldInfo`의 인스턴스를 반환합니다. + +`Body` 또한 `FieldInfo`의 서브클래스 객체를 직접적으로 반환합니다. 그리고 `Body` 클래스의 서브클래스인 것들도 여러분이 나중에 보게될 것입니다. + + `Query`, `Path`와 그 외 것들을 `fastapi`에서 임포트할 때, 이는 실제로 특별한 클래스를 반환하는 함수인 것을 기억해 주세요. + +/// + +/// tip | 팁 + +주목할 점은 타입, 기본 값 및 `Field`로 이루어진 각 모델 어트리뷰트가 `Path`, `Query`와 `Body`대신 `Field`를 사용하는 *경로 작동 함수*의 매개변수와 같은 구조를 가진다는 점 입니다. + +/// + +## 별도 정보 추가 + +`Field`, `Query`, `Body`, 그 외 안에 별도 정보를 선언할 수 있습니다. 이는 생성된 JSON 스키마에 포함됩니다. + +여러분이 예제를 선언할 때 나중에 이 공식 문서에서 별도 정보를 추가하는 방법을 배울 것입니다. + +/// warning | 경고 + +별도 키가 전달된 `Field` 또한 여러분의 어플리케이션의 OpenAPI 스키마에 나타날 것입니다. +이런 키가 OpenAPI 명세서, [the OpenAPI validator](https://validator.swagger.io/)같은 몇몇 OpenAPI 도구들에 포함되지 못할 수 있으며, 여러분이 생성한 스키마와 호환되지 않을 수 있습니다. + +/// + +## 요약 + +모델 어트리뷰트를 위한 추가 검증과 메타데이터 선언하기 위해 Pydantic의 `Field` 를 사용할 수 있습니다. + +또한 추가적인 JSON 스키마 메타데이터를 전달하기 위한 별도의 키워드 인자를 사용할 수 있습니다. diff --git a/docs/ko/docs/tutorial/body-multiple-params.md b/docs/ko/docs/tutorial/body-multiple-params.md new file mode 100644 index 000000000..edf892dfa --- /dev/null +++ b/docs/ko/docs/tutorial/body-multiple-params.md @@ -0,0 +1,169 @@ +# 본문 - 다중 매개변수 + +지금부터 `Path`와 `Query`를 어떻게 사용하는지 확인하겠습니다. + +요청 본문 선언에 대한 심화 사용법을 알아보겠습니다. + +## `Path`, `Query` 및 본문 매개변수 혼합 + +당연하게 `Path`, `Query` 및 요청 본문 매개변수 선언을 자유롭게 혼합해서 사용할 수 있고, **FastAPI**는 어떤 동작을 할지 압니다. + +또한, 기본 값을 `None`으로 설정해 본문 매개변수를 선택사항으로 선언할 수 있습니다. + +{* ../../docs_src/body_multiple_params/tutorial001.py hl[19:21] *} + +/// note | 참고 + +이 경우에는 본문으로 부터 가져온 ` item`은 기본값이 `None`이기 때문에, 선택사항이라는 점을 유의해야 합니다. + +/// + +## 다중 본문 매개변수 + +이전 예제에서 보듯이, *경로 작동*은 아래와 같이 `Item` 속성을 가진 JSON 본문을 예상합니다: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +하지만, 다중 본문 매개변수 역시 선언할 수 있습니다. 예. `item`과 `user`: + +{* ../../docs_src/body_multiple_params/tutorial002.py hl[22] *} + +이 경우에, **FastAPI**는 이 함수 안에 한 개 이상의 본문 매개변수(Pydantic 모델인 두 매개변수)가 있다고 알 것입니다. + +그래서, 본문의 매개변수 이름을 키(필드 명)로 사용할 수 있고, 다음과 같은 본문을 예측합니다: + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + } +} +``` + +/// note | 참고 + +이전과 같이 `item`이 선언 되었더라도, 본문 내의 `item` 키가 있을 것이라고 예측합니다. + +/// + +FastAPI는 요청을 자동으로 변환해, 매개변수의 `item`과 `user`를 특별한 내용으로 받도록 할 것입니다. + +복합 데이터의 검증을 수행하고 OpenAPI 스키마 및 자동 문서를 문서화합니다. + +## 본문 내의 단일 값 + +쿼리 및 경로 매개변수에 대한 추가 데이터를 정의하는 `Query`와 `Path`와 같이, **FastAPI**는 동등한 `Body`를 제공합니다. + +예를 들어 이전의 모델을 확장하면, `item`과 `user`와 동일한 본문에 또 다른 `importance`라는 키를 갖도록 할 수있습니다. + +단일 값을 그대로 선언한다면, **FastAPI**는 쿼리 매개변수로 가정할 것입니다. + +하지만, **FastAPI**의 `Body`를 사용해 다른 본문 키로 처리하도록 제어할 수 있습니다: + + +{* ../../docs_src/body_multiple_params/tutorial003.py hl[23] *} + +이 경우에는 **FastAPI**는 본문을 이와 같이 예측할 것입니다: + + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + }, + "importance": 5 +} +``` + +다시 말해, 데이터 타입, 검증, 문서 등을 변환합니다. + +## 다중 본문 매개변수와 쿼리 + +당연히, 필요할 때마다 추가적인 쿼리 매개변수를 선언할 수 있고, 이는 본문 매개변수에 추가됩니다. + +기본적으로 단일 값은 쿼리 매개변수로 해석되므로, 명시적으로 `Query`를 추가할 필요가 없고, 아래처럼 할 수 있습니다: + +{* ../../docs_src/body_multiple_params/tutorial004.py hl[27] *} + +이렇게: + +```Python +q: Optional[str] = None +``` + +/// info | 정보 + +`Body` 또한 `Query`, `Path` 그리고 이후에 볼 다른 것들처럼 동일한 추가 검증과 메타데이터 매개변수를 갖고 있습니다. + +/// + +## 단일 본문 매개변수 삽입하기 + +Pydantic 모델 `Item`의 `item`을 본문 매개변수로 오직 한개만 갖고있다고 하겠습니다. + +기본적으로 **FastAPI**는 직접 본문으로 예측할 것입니다. + +하지만, 만약 모델 내용에 `item `키를 가진 JSON으로 예측하길 원한다면, 추가적인 본문 매개변수를 선언한 것처럼 `Body`의 특별한 매개변수인 `embed`를 사용할 수 있습니다: + +{* ../../docs_src/body_multiple_params/tutorial005.py hl[17] *} + +아래 처럼: + +```Python +item: Item = Body(..., embed=True) +``` + +이 경우에 **FastAPI**는 본문을 아래 대신에: + +```JSON hl_lines="2" +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +아래 처럼 예측할 것 입니다: + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + } +} +``` + +## 정리 + +요청이 단 한개의 본문을 가지고 있더라도, *경로 작동 함수*로 다중 본문 매개변수를 추가할 수 있습니다. + +하지만, **FastAPI**는 이를 처리하고, 함수에 올바른 데이터를 제공하며, *경로 작동*으로 올바른 스키마를 검증하고 문서화 합니다. + +또한, 단일 값을 본문의 일부로 받도록 선언할 수 있습니다. + +그리고 **FastAPI**는 단 한개의 매개변수가 선언 되더라도, 본문 내의 키로 삽입 시킬 수 있습니다. diff --git a/docs/ko/docs/tutorial/body-nested-models.md b/docs/ko/docs/tutorial/body-nested-models.md new file mode 100644 index 000000000..ebd7b3ba6 --- /dev/null +++ b/docs/ko/docs/tutorial/body-nested-models.md @@ -0,0 +1,230 @@ +# 본문 - 중첩 모델 + +**FastAPI**를 이용하면 (Pydantic 덕분에) 단독으로 깊이 중첩된 모델을 정의, 검증, 문서화하며 사용할 수 있습니다. +## 리스트 필드 + +어트리뷰트를 서브타입으로 정의할 수 있습니다. 예를 들어 파이썬 `list`는: + +{* ../../docs_src/body_nested_models/tutorial001.py hl[14] *} + +이는 `tags`를 항목 리스트로 만듭니다. 각 항목의 타입을 선언하지 않더라도요. + +## 타입 매개변수가 있는 리스트 필드 + +하지만 파이썬은 내부의 타입이나 "타입 매개변수"를 선언할 수 있는 특정 방법이 있습니다: + +### typing의 `List` 임포트 + +먼저, 파이썬 표준 `typing` 모듈에서 `List`를 임포트합니다: + +{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *} + +### 타입 매개변수로 `List` 선언 + +`list`, `dict`, `tuple`과 같은 타입 매개변수(내부 타입)를 갖는 타입을 선언하려면: + +* `typing` 모듈에서 임포트 +* 대괄호를 사용하여 "타입 매개변수"로 내부 타입 전달: `[` 및 `]` + +```Python +from typing import List + +my_list: List[str] +``` + +이 모든 것은 타입 선언을 위한 표준 파이썬 문법입니다. + +내부 타입을 갖는 모델 어트리뷰트에 대해 동일한 표준 문법을 사용하세요. + +마찬가지로 예제에서 `tags`를 구체적으로 "문자열의 리스트"로 만들 수 있습니다: + +{* ../../docs_src/body_nested_models/tutorial002.py hl[14] *} + +## 집합 타입 + +그런데 생각해보니 태그는 반복되면 안 되고, 고유한(Unique) 문자열이어야 할 것 같습니다. + +그리고 파이썬은 집합을 위한 특별한 데이터 타입 `set`이 있습니다. + +그렇다면 `Set`을 임포트 하고 `tags`를 `str`의 `set`으로 선언할 수 있습니다: + +{* ../../docs_src/body_nested_models/tutorial003.py hl[1,14] *} + +덕분에 중복 데이터가 있는 요청을 수신하더라도 고유한 항목들의 집합으로 변환됩니다. + +그리고 해당 데이터를 출력 할 때마다 소스에 중복이 있더라도 고유한 항목들의 집합으로 출력됩니다. + +또한 그에 따라 주석이 생기고 문서화됩니다. + +## 중첩 모델 + +Pydantic 모델의 각 어트리뷰트는 타입을 갖습니다. + +그런데 해당 타입 자체로 또다른 Pydantic 모델의 타입이 될 수 있습니다. + +그러므로 특정한 어트리뷰트의 이름, 타입, 검증을 사용하여 깊게 중첩된 JSON "객체"를 선언할 수 있습니다. + +모든 것이 단독으로 중첩됩니다. + +### 서브모델 정의 + +예를 들어, `Image` 모델을 선언할 수 있습니다: + +{* ../../docs_src/body_nested_models/tutorial004.py hl[9:11] *} + +### 서브모듈을 타입으로 사용 + +그리고 어트리뷰트의 타입으로 사용할 수 있습니다: + +{* ../../docs_src/body_nested_models/tutorial004.py hl[20] *} + +이는 **FastAPI**가 다음과 유사한 본문을 기대한다는 것을 의미합니다: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2, + "tags": ["rock", "metal", "bar"], + "image": { + "url": "http://example.com/baz.jpg", + "name": "The Foo live" + } +} +``` + +다시 한번, **FastAPI**를 사용하여 해당 선언을 함으로써 얻는 것은: + +* 중첩 모델도 편집기 지원(자동완성 등) +* 데이터 변환 +* 데이터 검증 +* 자동 문서화 + +## 특별한 타입과 검증 + +`str`, `int`, `float` 등과 같은 단일 타입과는 별개로, `str`을 상속하는 더 복잡한 단일 타입을 사용할 수 있습니다. + +모든 옵션을 보려면, Pydantic's exotic types 문서를 확인하세요. 다음 장에서 몇가지 예제를 볼 수 있습니다. + +예를 들어 `Image` 모델 안에 `url` 필드를 `str` 대신 Pydantic의 `HttpUrl`로 선언할 수 있습니다: + +{* ../../docs_src/body_nested_models/tutorial005.py hl[4,10] *} + +이 문자열이 유효한 URL인지 검사하고 JSON 스키마/OpenAPI로 문서화 됩니다. + +## 서브모델 리스트를 갖는 어트리뷰트 + +`list`, `set` 등의 서브타입으로 Pydantic 모델을 사용할 수도 있습니다: + +{* ../../docs_src/body_nested_models/tutorial006.py hl[20] *} + +아래와 같은 JSON 본문으로 예상(변환, 검증, 문서화 등을)합니다: + +```JSON hl_lines="11" +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2, + "tags": [ + "rock", + "metal", + "bar" + ], + "images": [ + { + "url": "http://example.com/baz.jpg", + "name": "The Foo live" + }, + { + "url": "http://example.com/dave.jpg", + "name": "The Baz" + } + ] +} +``` + +/// info | 정보 + +`images` 키가 어떻게 이미지 객체 리스트를 갖는지 주목하세요. + +/// + +## 깊게 중첩된 모델 + +단독으로 깊게 중첩된 모델을 정의할 수 있습니다: + +{* ../../docs_src/body_nested_models/tutorial007.py hl[9,14,20,23,27] *} + +/// info | 정보 + +`Offer`가 선택사항 `Image` 리스트를 차례로 갖는 `Item` 리스트를 어떻게 가지고 있는지 주목하세요 + +/// + +## 순수 리스트의 본문 + +예상되는 JSON 본문의 최상위 값이 JSON `array`(파이썬 `list`)면, Pydantic 모델에서와 마찬가지로 함수의 매개변수에서 타입을 선언할 수 있습니다: + +```Python +images: List[Image] +``` + +이를 아래처럼: + +{* ../../docs_src/body_nested_models/tutorial008.py hl[15] *} + +## 어디서나 편집기 지원 + +그리고 어디서나 편집기 지원을 받을수 있습니다. + +리스트 내부 항목의 경우에도: + + + +Pydantic 모델 대신에 `dict`를 직접 사용하여 작업할 경우, 이러한 편집기 지원을 받을수 없습니다. + +하지만 수신한 딕셔너리가 자동으로 변환되고 출력도 자동으로 JSON으로 변환되므로 걱정할 필요는 없습니다. + +## 단독 `dict`의 본문 + +일부 타입의 키와 다른 타입의 값을 사용하여 `dict`로 본문을 선언할 수 있습니다. + +(Pydantic을 사용한 경우처럼) 유효한 필드/어트리뷰트 이름이 무엇인지 알 필요가 없습니다. + +아직 모르는 키를 받으려는 경우 유용합니다. + +--- + +다른 유용한 경우는 다른 타입의 키를 가질 때입니다. 예. `int`. + +여기서 그 경우를 볼 것입니다. + +이 경우, `float` 값을 가진 `int` 키가 있는 모든 `dict`를 받아들입니다: + +{* ../../docs_src/body_nested_models/tutorial009.py hl[15] *} + +/// tip | 팁 + +JSON은 오직 `str`형 키만 지원한다는 것을 염두에 두세요. + +하지만 Pydantic은 자동 데이터 변환이 있습니다. + +즉, API 클라이언트가 문자열을 키로 보내더라도 해당 문자열이 순수한 정수를 포함하는한 Pydantic은 이를 변환하고 검증합니다. + +그러므로 `weights`로 받은 `dict`는 실제로 `int` 키와 `float` 값을 가집니다. + +/// + +## 요약 + +**FastAPI**를 사용하면 Pydantic 모델이 제공하는 최대 유연성을 확보하면서 코드를 간단하고 짧게, 그리고 우아하게 유지할 수 있습니다. + +물론 아래의 이점도 있습니다: + +* 편집기 지원 (자동완성이 어디서나!) +* 데이터 변환 (일명 파싱/직렬화) +* 데이터 검증 +* 스키마 문서화 +* 자동 문서 diff --git a/docs/ko/docs/tutorial/body.md b/docs/ko/docs/tutorial/body.md new file mode 100644 index 000000000..b3914fa4b --- /dev/null +++ b/docs/ko/docs/tutorial/body.md @@ -0,0 +1,162 @@ +# 요청 본문 + +클라이언트(브라우저라고 해봅시다)로부터 여러분의 API로 데이터를 보내야 할 때, **요청 본문**으로 보냅니다. + +**요청** 본문은 클라이언트에서 API로 보내지는 데이터입니다. **응답** 본문은 API가 클라이언트로 보내는 데이터입니다. + +여러분의 API는 대부분의 경우 **응답** 본문을 보내야 합니다. 하지만 클라이언트는 **요청** 본문을 매 번 보낼 필요가 없습니다. + +**요청** 본문을 선언하기 위해서 모든 강력함과 이점을 갖춘 Pydantic 모델을 사용합니다. + +/// info | 정보 + +데이터를 보내기 위해, (좀 더 보편적인) `POST`, `PUT`, `DELETE` 혹은 `PATCH` 중에 하나를 사용하는 것이 좋습니다. + +`GET` 요청에 본문을 담아 보내는 것은 명세서에 정의되지 않은 행동입니다. 그럼에도 불구하고, 이 방식은 아주 복잡한/극한의 사용 상황에서만 FastAPI에 의해 지원됩니다. + +`GET` 요청에 본문을 담는 것은 권장되지 않기에, Swagger UI같은 대화형 문서에서는 `GET` 사용시 담기는 본문에 대한 문서를 표시하지 않으며, 중간에 있는 프록시는 이를 지원하지 않을 수도 있습니다. + +/// + +## Pydantic의 `BaseModel` 임포트 + +먼저 `pydantic`에서 `BaseModel`를 임포트해야 합니다: + +{* ../../docs_src/body/tutorial001_py310.py hl[2] *} + +## 여러분의 데이터 모델 만들기 + +`BaseModel`를 상속받은 클래스로 여러분의 데이터 모델을 선언합니다. + +모든 어트리뷰트에 대해 표준 파이썬 타입을 사용합니다: + +{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *} + +쿼리 매개변수를 선언할 때와 같이, 모델 어트리뷰트가 기본 값을 가지고 있어도 이는 필수가 아닙니다. 그외에는 필수입니다. 그저 `None`을 사용하여 선택적으로 만들 수 있습니다. + +예를 들면, 위의 이 모델은 JSON "`object`" (혹은 파이썬 `dict`)을 다음과 같이 선언합니다: + +```JSON +{ + "name": "Foo", + "description": "선택적인 설명란", + "price": 45.2, + "tax": 3.5 +} +``` + +...`description`과 `tax`는 (기본 값이 `None`으로 되어 있어) 선택적이기 때문에, 이 JSON "`object`"는 다음과 같은 상황에서도 유효합니다: + +```JSON +{ + "name": "Foo", + "price": 45.2 +} +``` + +## 매개변수로서 선언하기 + +여러분의 *경로 작동*에 추가하기 위해, 경로 매개변수 그리고 쿼리 매개변수에서 선언했던 것과 같은 방식으로 선언하면 됩니다. + +{* ../../docs_src/body/tutorial001_py310.py hl[16] *} + +...그리고 만들어낸 모델인 `Item`으로 타입을 선언합니다. + +## 결과 + +위에서의 단순한 파이썬 타입 선언으로, **FastAPI**는 다음과 같이 동작합니다: + +* 요청의 본문을 JSON으로 읽어 들입니다. +* (필요하다면) 대응되는 타입으로 변환합니다. +* 데이터를 검증합니다. + * 만약 데이터가 유효하지 않다면, 정확히 어떤 것이 그리고 어디에서 데이터가 잘 못 되었는지 지시하는 친절하고 명료한 에러를 반환할 것입니다. +* 매개변수 `item`에 포함된 수신 데이터를 제공합니다. + * 함수 내에서 매개변수를 `Item` 타입으로 선언했기 때문에, 모든 어트리뷰트와 그에 대한 타입에 대한 편집기 지원(완성 등)을 또한 받을 수 있습니다. +* 여러분의 모델을 위한 JSON 스키마 정의를 생성합니다. 여러분의 프로젝트에 적합하다면 여러분이 사용하고 싶은 곳 어디에서나 사용할 수 있습니다. +* 이러한 스키마는, 생성된 OpenAPI 스키마 일부가 될 것이며, 자동 문서화 UI에 사용됩니다. + +## 자동 문서화 + +모델의 JSON 스키마는 생성된 OpenAPI 스키마에 포함되며 대화형 API 문서에 표시됩니다: + + + +이를 필요로 하는 각각의 *경로 작동*내부의 API 문서에도 사용됩니다: + + + +## 편집기 지원 + +편집기에서, 함수 내에서 타입 힌트와 완성을 어디서나 (만약 Pydantic model 대신에 `dict`을 받을 경우 나타나지 않을 수 있습니다) 받을 수 있습니다: + + + +잘못된 타입 연산에 대한 에러 확인도 받을 수 있습니다: + + + +단순한 우연이 아닙니다. 프레임워크 전체가 이러한 디자인을 중심으로 설계되었습니다. + +그 어떤 실행 전에, 모든 편집기에서 작동할 수 있도록 보장하기 위해 설계 단계에서 혹독하게 테스트되었습니다. + +이를 지원하기 위해 Pydantic 자체에서 몇몇 변경점이 있었습니다. + +이전 스크린샷은 Visual Studio Code를 찍은 것입니다. + +하지만 똑같은 편집기 지원을 PyCharm에서 받을 수 있거나, 대부분의 다른 편집기에서도 받을 수 있습니다: + + + +/// tip | 팁 + +만약 PyCharm를 편집기로 사용한다면, Pydantic PyCharm Plugin을 사용할 수 있습니다. + +다음 사항을 포함해 Pydantic 모델에 대한 편집기 지원을 향상시킵니다: + +* 자동 완성 +* 타입 확인 +* 리팩토링 +* 검색 +* 점검 + +/// + +## 모델 사용하기 + +함수 안에서 모델 객체의 모든 어트리뷰트에 직접 접근 가능합니다: + +{* ../../docs_src/body/tutorial002_py310.py hl[19] *} + +## 요청 본문 + 경로 매개변수 + +경로 매개변수와 요청 본문을 동시에 선언할 수 있습니다. + +**FastAPI**는 경로 매개변수와 일치하는 함수 매개변수가 **경로에서 가져와야 한다**는 것을 인지하며, Pydantic 모델로 선언된 그 함수 매개변수는 **요청 본문에서 가져와야 한다**는 것을 인지할 것입니다. + +{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *} + +## 요청 본문 + 경로 + 쿼리 매개변수 + +**본문**, **경로** 그리고 **쿼리** 매개변수 모두 동시에 선언할 수도 있습니다. + +**FastAPI**는 각각을 인지하고 데이터를 옳바른 위치에 가져올 것입니다. + +{* ../../docs_src/body/tutorial004_py310.py hl[16] *} + +함수 매개변수는 다음을 따라서 인지하게 됩니다: + +* 만약 매개변수가 **경로**에도 선언되어 있다면, 이는 경로 매개변수로 사용될 것입니다. +* 만약 매개변수가 (`int`, `float`, `str`, `bool` 등과 같은) **유일한 타입**으로 되어있으면, **쿼리** 매개변수로 해석될 것입니다. +* 만약 매개변수가 **Pydantic 모델** 타입으로 선언되어 있으면, 요청 **본문**으로 해석될 것입니다. + +/// note | 참고 + +FastAPI는 `q`의 값이 필요없음을 알게 될 것입니다. 기본 값이 `= None`이기 때문입니다. + +`Union[str, None]`에 있는 `Union`은 FastAPI에 의해 사용된 것이 아니지만, 편집기로 하여금 더 나은 지원과 에러 탐지를 지원할 것입니다. + +/// + +## Pydantic없이 + +만약 Pydantic 모델을 사용하고 싶지 않다면, **Body** 매개변수를 사용할 수도 있습니다. [Body - 다중 매개변수: 본문에 있는 유일한 값](body-multiple-params.md#_2){.internal-link target=_blank} 문서를 확인하세요. diff --git a/docs/ko/docs/tutorial/cookie-param-models.md b/docs/ko/docs/tutorial/cookie-param-models.md new file mode 100644 index 000000000..e7eef0b1d --- /dev/null +++ b/docs/ko/docs/tutorial/cookie-param-models.md @@ -0,0 +1,76 @@ +# 쿠키 매개변수 모델 + +관련있는 **쿠키**들의 그룹이 있는 경우, **Pydantic 모델**을 생성하여 선언할 수 있습니다. 🍪 + +이를 통해 **여러 위치**에서 **모델을 재사용** 할 수 있고 모든 매개변수에 대한 유효성 검사 및 메타데이터를 한 번에 선언할 수도 있습니다. 😍 + +/// note | 참고 + +이 기능은 FastAPI 버전 `0.115.0` 이후부터 지원됩니다. 🤓 + +/// + +/// tip | 팁 + +동일한 기술이 `Query`, `Cookie`, 그리고 `Header`에 적용됩니다. 😎 + +/// + +## Pydantic 모델을 사용한 쿠키 + +**Pydantic 모델**에 필요한 **쿠키** 매개변수를 선언한 다음, 해당 매개변수를 `Cookie`로 선언합니다: + +{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *} + +**FastAPI**는 요청에서 받은 **쿠키**에서 **각 필드**에 대한 데이터를 **추출**하고 정의한 Pydantic 모델을 줍니다. + +## 문서 확인하기 + +문서 UI `/docs`에서 정의한 쿠키를 볼 수 있습니다: + +
+ +
+ +/// info | 정보 + +명심하세요, 내부적으로 **브라우저는 쿠키를 특별한 방식으로 처리**하기 때문에 **자바스크립트**가 쉽게 쿠키를 건드릴 수 **없습니다**. + +`/docs`에서 **API 문서 UI**로 이동하면 *경로 작업*에 대한 쿠키의 **문서**를 볼 수 있습니다. + +하지만 아무리 **데이터를 입력**하고 "실행(Execute)"을 클릭해도, 문서 UI는 **자바스크립트**로 작동하기 때문에 쿠키는 전송되지 않고, 아무 값도 쓰지 않은 것처럼 **오류** 메시지를 보게 됩니다. + +/// + +## 추가 쿠키 금지하기 + +일부 특별한 사용 사례(흔하지는 않겠지만)에서는 수신하려는 쿠키를 **제한**할 수 있습니다. + +이제 API는 자신의 쿠키 동의를 제어할 수 있는 권한을 갖게 되었습니다. 🤪🍪 + +Pydantic의 모델 구성을 사용하여 추가(`extra`) 필드를 금지(`forbid`)할 수 있습니다: + +{* ../../docs_src/cookie_param_models/tutorial002_an_py39.py hl[10] *} + +클라이언트가 **추가 쿠키**를 보내려고 시도하면, **오류** 응답을 받게 됩니다. + +API가 거부하는데도 동의를 얻기 위해 애쓰는 불쌍한 쿠키 배너(팝업)들. 🍪 + +예를 들어, 클라이언트가 `good-list-please` 값으로 `santa_tracker` 쿠키를 보내려고 하면 클라이언트는 `santa_tracker` 쿠키가 허용되지 않는다는 **오류** 응답을 받게 됩니다: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["cookie", "santa_tracker"], + "msg": "Extra inputs are not permitted", + "input": "good-list-please", + } + ] +} +``` + +## 요약 + +**Pydantic 모델**을 사용하여 **FastAPI**에서 **쿠키**를 선언할 수 있습니다. 😍 diff --git a/docs/ko/docs/tutorial/cookie-params.md b/docs/ko/docs/tutorial/cookie-params.md new file mode 100644 index 000000000..fba756d49 --- /dev/null +++ b/docs/ko/docs/tutorial/cookie-params.md @@ -0,0 +1,35 @@ +# 쿠키 매개변수 + +쿠키 매개변수를 `Query`와 `Path` 매개변수들과 같은 방식으로 정의할 수 있습니다. + +## `Cookie` 임포트 + +먼저 `Cookie`를 임포트합니다: + +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[3] *} + +## `Cookie` 매개변수 선언 + +그런 다음, `Path`와 `Query`처럼 동일한 구조를 사용하는 쿠키 매개변수를 선언합니다. + +첫 번째 값은 기본값이며, 추가 검증이나 어노테이션 매개변수 모두 전달할 수 있습니다: + +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9] *} + +/// note | 기술 세부사항 + +`Cookie`는 `Path` 및 `Query`의 "자매"클래스입니다. 이 역시 동일한 공통 `Param` 클래스를 상속합니다. + +`Query`, `Path`, `Cookie` 그리고 다른 것들은 `fastapi`에서 임포트 할 때, 실제로는 특별한 클래스를 반환하는 함수임을 기억하세요. + +/// + +/// info | 정보 + +쿠키를 선언하기 위해서는 `Cookie`를 사용해야 합니다. 그렇지 않으면 해당 매개변수를 쿼리 매개변수로 해석하기 때문입니다. + +/// + +## 요약 + +`Cookie`는 `Query`, `Path`와 동일한 패턴을 사용하여 선언합니다. diff --git a/docs/ko/docs/tutorial/cors.md b/docs/ko/docs/tutorial/cors.md index 39e9ea83f..1ef5a7480 100644 --- a/docs/ko/docs/tutorial/cors.md +++ b/docs/ko/docs/tutorial/cors.md @@ -46,9 +46,7 @@ * 특정한 HTTP 메소드(`POST`, `PUT`) 또는 와일드카드 `"*"` 를 사용한 모든 HTTP 메소드. * 특정한 HTTP 헤더 또는 와일드카드 `"*"` 를 사용한 모든 HTTP 헤더. -```Python hl_lines="2 6-11 13-19" -{!../../../docs_src/cors/tutorial001.py!} -``` +{* ../../docs_src/cors/tutorial001.py hl[2,6:11,13:19] *} `CORSMiddleware` 에서 사용하는 기본 매개변수는 제한적이므로, 브라우저가 교차-도메인 상황에서 특정한 출처, 메소드, 헤더 등을 사용할 수 있도록 하려면 이들을 명시적으로 허용해야 합니다. @@ -78,7 +76,10 @@ CORS에 대한 더 많은 정보를 알고싶다면, Mozilla CORS 문서를 참고하기 바랍니다. -!!! note "기술적 세부 사항" - `from starlette.middleware.cors import CORSMiddleware` 역시 사용할 수 있습니다. +/// note | 기술적 세부 사항 - **FastAPI**는 개발자인 당신의 편의를 위해 `fastapi.middleware` 에서 몇가지의 미들웨어를 제공합니다. 하지만 대부분의 미들웨어가 Stralette으로부터 직접 제공됩니다. +`from starlette.middleware.cors import CORSMiddleware` 역시 사용할 수 있습니다. + +**FastAPI**는 개발자인 당신의 편의를 위해 `fastapi.middleware` 에서 몇가지의 미들웨어를 제공합니다. 하지만 대부분의 미들웨어가 Stralette으로부터 직접 제공됩니다. + +/// diff --git a/docs/ko/docs/tutorial/debugging.md b/docs/ko/docs/tutorial/debugging.md new file mode 100644 index 000000000..e42f1ba88 --- /dev/null +++ b/docs/ko/docs/tutorial/debugging.md @@ -0,0 +1,113 @@ +# 디버깅 + +예를 들면 Visual Studio Code 또는 PyCharm을 사용하여 편집기에서 디버거를 연결할 수 있습니다. + +## `uvicorn` 호출 + +FastAPI 애플리케이션에서 `uvicorn`을 직접 임포트하여 실행합니다 + +{* ../../docs_src/debugging/tutorial001.py hl[1,15] *} + +### `__name__ == "__main__"` 에 대하여 + +`__name__ == "__main__"`의 주요 목적은 다음과 같이 파일이 호출될 때 실행되는 일부 코드를 갖는 것입니다. + +
+ +```console +$ python myapp.py +``` + +
+ +그러나 다음과 같이 다른 파일을 가져올 때는 호출되지 않습니다. + +```Python +from myapp import app +``` + +#### 추가 세부사항 + +파일 이름이 `myapp.py`라고 가정해 보겠습니다. + +다음과 같이 실행하면 + +
+ +```console +$ python myapp.py +``` + +
+ +Python에 의해 자동으로 생성된 파일의 내부 변수 `__name__`은 문자열 `"__main__"`을 값으로 갖게 됩니다. + +따라서 섹션 + +```Python + uvicorn.run(app, host="0.0.0.0", port=8000) +``` + +이 실행됩니다. + +--- + +해당 모듈(파일)을 가져오면 이런 일이 발생하지 않습니다 + +그래서 다음과 같은 다른 파일 `importer.py`가 있는 경우: + +```Python +from myapp import app + +# Some more code +``` + +이 경우 `myapp.py` 내부의 자동 변수에는 값이 `"__main__"`인 변수 `__name__`이 없습니다. + +따라서 다음 행 + +```Python + uvicorn.run(app, host="0.0.0.0", port=8000) +``` + +은 실행되지 않습니다. + +/// info | 정보 + +자세한 내용은 공식 Python 문서를 확인하세요 + +/// + +## 디버거로 코드 실행 + +코드에서 직접 Uvicorn 서버를 실행하고 있기 때문에 디버거에서 직접 Python 프로그램(FastAPI 애플리케이션)을 호출할 수 있습니다. + +--- + +예를 들어 Visual Studio Code에서 다음을 수행할 수 있습니다. + +* "Debug" 패널로 이동합니다. +* "Add configuration...". +* "Python"을 선택합니다. +* "`Python: Current File (Integrated Terminal)`" 옵션으로 디버거를 실행합니다. + +그런 다음 **FastAPI** 코드로 서버를 시작하고 중단점 등에서 중지합니다. + +다음과 같이 표시됩니다. + + + +--- + +Pycharm을 사용하는 경우 다음을 수행할 수 있습니다 + +* "Run" 메뉴를 엽니다 +* "Debug..." 옵션을 선택합니다. +* 그러면 상황에 맞는 메뉴가 나타납니다. +* 디버그할 파일을 선택합니다(이 경우 `main.py`). + +그런 다음 **FastAPI** 코드로 서버를 시작하고 중단점 등에서 중지합니다. + +다음과 같이 표시됩니다. + + diff --git a/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md index bbf3a8283..3e5cdcc8c 100644 --- a/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/ko/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,17 +6,7 @@ 이전 예제에서, 우리는 의존성(의존 가능한) 함수에서 `딕셔너리`객체를 반환하고 있었습니다: -=== "파이썬 3.6 이상" - - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` - -=== "파이썬 3.10 이상" - - ```Python hl_lines="7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +{* ../../docs_src/dependencies/tutorial001.py hl[9] *} 우리는 *경로 작동 함수*의 매개변수 `commons`에서 `딕셔너리` 객체를 얻습니다. @@ -71,51 +61,21 @@ fluffy = Cat(name="Mr Fluffy") FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래스 또는 다른 모든 것)과 정의된 매개변수들입니다. -"호출 가능"한 것을 의존성으로서 **FastAPI**에 전달하면, 그 "호출 가능"한 것의 매개변수들을 분석한 후 이를 *경로 동작 함수*를 위한 매개변수와 동일한 방식으로 처리합니다. 하위-의존성 또한 같은 방식으로 처리합니다. +"호출 가능"한 것을 의존성으로서 **FastAPI**에 전달하면, 그 "호출 가능"한 것의 매개변수들을 분석한 후 이를 *경로 작동 함수*를 위한 매개변수와 동일한 방식으로 처리합니다. 하위-의존성 또한 같은 방식으로 처리합니다. -매개변수가 없는 "호출 가능"한 것 역시 매개변수가 없는 *경로 동작 함수*와 동일한 방식으로 적용됩니다. +매개변수가 없는 "호출 가능"한 것 역시 매개변수가 없는 *경로 작동 함수*와 동일한 방식으로 적용됩니다. 그래서, 우리는 위 예제에서의 `common_paramenters` 의존성을 클래스 `CommonQueryParams`로 바꿀 수 있습니다. -=== "파이썬 3.6 이상" - - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` - -=== "파이썬 3.10 이상" - - ```Python hl_lines="9-13" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +{* ../../docs_src/dependencies/tutorial002.py hl[11:15] *} 클래스의 인스턴스를 생성하는 데 사용되는 `__init__` 메서드에 주목하기 바랍니다: -=== "파이썬 3.6 이상" - - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` - -=== "파이썬 3.10 이상" - - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +{* ../../docs_src/dependencies/tutorial002.py hl[12] *} ...이전 `common_parameters`와 동일한 매개변수를 가집니다: -=== "파이썬 3.6 이상" - - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` - -=== "파이썬 3.10 이상" - - ```Python hl_lines="6" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` +{* ../../docs_src/dependencies/tutorial001.py hl[9] *} 이 매개변수들은 **FastAPI**가 의존성을 "해결"하기 위해 사용할 것입니다 @@ -131,17 +91,7 @@ FastAPI가 실질적으로 확인하는 것은 "호출 가능성"(함수, 클래 이제 아래의 클래스를 이용해서 의존성을 정의할 수 있습니다. -=== "파이썬 3.6 이상" - - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` - -=== "파이썬 3.10 이상" - - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +{* ../../docs_src/dependencies/tutorial002.py hl[19] *} **FastAPI**는 `CommonQueryParams` 클래스를 호출합니다. 이것은 해당 클래스의 "인스턴스"를 생성하고 그 인스턴스는 함수의 매개변수 `commons`로 전달됩니다. @@ -180,17 +130,7 @@ commons = Depends(CommonQueryParams) ..전체적인 코드는 아래와 같습니다: -=== "파이썬 3.6 이상" - - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003.py!} - ``` - -=== "파이썬 3.10 이상" - - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial003_py310.py!} - ``` +{* ../../docs_src/dependencies/tutorial003.py hl[19] *} 그러나 자료형을 선언하면 에디터가 매개변수 `commons`로 전달될 것이 무엇인지 알게 되고, 이를 통해 코드 완성, 자료형 확인 등에 도움이 될 수 있으므로 권장됩니다. @@ -224,21 +164,14 @@ commons: CommonQueryParams = Depends() 아래에 같은 예제가 있습니다: -=== "파이썬 3.6 이상" - - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004.py!} - ``` +{* ../../docs_src/dependencies/tutorial004.py hl[19] *} -=== "파이썬 3.10 이상" +...이렇게 코드를 단축하여도 **FastAPI**는 무엇을 해야하는지 알고 있습니다. - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial004_py310.py!} - ``` +/// tip | 팁 -...이렇게 코드를 단축하여도 **FastAPI**는 무엇을 해야하는지 알고 있습니다. +만약 이것이 도움이 되기보다 더 헷갈리게 만든다면, 잊어버리십시오. 이것이 반드시 필요한 것은 아닙니다. -!!! tip "팁" - 만약 이것이 도움이 되기보다 더 헷갈리게 만든다면, 잊어버리십시오. 이것이 반드시 필요한 것은 아닙니다. +이것은 단지 손쉬운 방법일 뿐입니다. 왜냐하면 **FastAPI**는 코드 반복을 최소화할 수 있는 방법을 고민하기 때문입니다. - 이것은 단지 손쉬운 방법일 뿐입니다. 왜냐하면 **FastAPI**는 코드 반복을 최소화할 수 있는 방법을 고민하기 때문입니다. +/// diff --git a/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md new file mode 100644 index 000000000..4a3854cef --- /dev/null +++ b/docs/ko/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -0,0 +1,69 @@ +# 경로 작동 데코레이터에서의 의존성 + +몇몇 경우에는, *경로 작동 함수* 안에서 의존성의 반환 값이 필요하지 않습니다. + +또는 의존성이 값을 반환하지 않습니다. + +그러나 여전히 실행/해결될 필요가 있습니다. + +그런 경우에, `Depends`를 사용하여 *경로 작동 함수*의 매개변수로 선언하는 것보다 *경로 작동 데코레이터*에 `dependencies`의 `list`를 추가할 수 있습니다. + +## *경로 작동 데코레이터*에 `dependencies` 추가하기 + +*경로 작동 데코레이터*는 `dependencies`라는 선택적인 인자를 받습니다. + +`Depends()`로 된 `list`이어야합니다: + +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[19] *} + +이러한 의존성들은 기존 의존성들과 같은 방식으로 실행/해결됩니다. 그러나 값은 (무엇이든 반환한다면) *경로 작동 함수*에 제공되지 않습니다. + +/// tip | 팁 + +일부 편집기에서는 사용되지 않는 함수 매개변수를 검사하고 오류로 표시합니다. + +*경로 작동 데코레이터*에서 `dependencies`를 사용하면 편집기/도구 오류를 피하며 실행되도록 할 수 있습니다. + +또한 코드에서 사용되지 않는 매개변수를 보고 불필요하다고 생각할 수 있는 새로운 개발자의 혼란을 방지하는데 도움이 될 수 있습니다. + +/// + +/// info | 정보 + +이 예시에서 `X-Key`와 `X-Token`이라는 커스텀 헤더를 만들어 사용했습니다. + +그러나 실제로 보안을 구현할 때는 통합된 [보안 유틸리티 (다음 챕터)](../security/index.md){.internal-link target=_blank}를 사용하는 것이 더 많은 이점을 얻을 수 있습니다. + +/// + +## 의존성 오류와 값 반환하기 + +평소에 사용하던대로 같은 의존성 *함수*를 사용할 수 있습니다. + +### 의존성 요구사항 + +(헤더같은) 요청 요구사항이나 하위-의존성을 선언할 수 있습니다: + +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[8,13] *} + +### 오류 발생시키기 + +다음 의존성은 기존 의존성과 동일하게 예외를 `raise`를 일으킬 수 있습니다: + +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[10,15] *} + +### 값 반환하기 + +값을 반환하거나, 그러지 않을 수 있으며 값은 사용되지 않습니다. + +그래서 이미 다른 곳에서 사용된 (값을 반환하는) 일반적인 의존성을 재사용할 수 있고, 비록 값은 사용되지 않지만 의존성은 실행될 것입니다: + +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[11,16] *} + +## *경로 작동* 모음에 대한 의존성 + +나중에 여러 파일을 가지고 있을 수 있는 더 큰 애플리케이션을 구조화하는 법([더 큰 애플리케이션 - 여러 파일들](../../tutorial/bigger-applications.md){.internal-link target=_blank})을 읽을 때, *경로 작동* 모음에 대한 단일 `dependencies` 매개변수를 선언하는 법에 대해서 배우게 될 것입니다. + +## 전역 의존성 + +다음으로 각 *경로 작동*에 적용되도록 `FastAPI` 애플리케이션 전체에 의존성을 추가하는 법을 볼 것입니다. diff --git a/docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md new file mode 100644 index 000000000..ff174937d --- /dev/null +++ b/docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md @@ -0,0 +1,275 @@ +# yield를 사용하는 의존성 + +FastAPI는 작업 완료 후 추가 단계를 수행하는 의존성을 지원합니다. + +이를 구현하려면 `return` 대신 `yield`를 사용하고, 추가로 실행할 단계 (코드)를 그 뒤에 작성하세요. + +/// tip | 팁 + +각 의존성마다 `yield`는 한 번만 사용해야 합니다. + +/// + +/// note | 기술 세부사항 + +다음과 함께 사용할 수 있는 모든 함수: + +* `@contextlib.contextmanager` 또는 +* `@contextlib.asynccontextmanager` + +는 **FastAPI**의 의존성으로 사용할 수 있습니다. + +사실, FastAPI는 내부적으로 이 두 데코레이터를 사용합니다. + +/// + +## `yield`를 사용하는 데이터베이스 의존성 + +예를 들어, 이 기능을 사용하면 데이터베이스 세션을 생성하고 작업이 끝난 후에 세션을 종료할 수 있습니다. + +응답을 생성하기 전에는 `yield`문을 포함하여 그 이전의 코드만이 실행됩니다: + +{* ../../docs_src/dependencies/tutorial007.py hl[2:4] *} + +yield된 값은 *경로 작업* 및 다른 의존성들에 주입되는 값 입니다: + +{* ../../docs_src/dependencies/tutorial007.py hl[4] *} + +`yield`문 다음의 코드는 응답을 생성한 후 보내기 전에 실행됩니다: + +{* ../../docs_src/dependencies/tutorial007.py hl[5:6] *} + +/// tip | 팁 + +`async` 함수와 일반 함수 모두 사용할 수 있습니다. + +**FastAPI**는 일반 의존성과 마찬가지로 각각의 함수를 올바르게 처리할 것입니다. + +/// + +## `yield`와 `try`를 사용하는 의존성 + +`yield`를 사용하는 의존성에서 `try` 블록을 사용한다면, 의존성을 사용하는 도중 발생한 모든 예외를 받을 수 있습니다. + +예를 들어, 다른 의존성이나 *경로 작업*의 중간에 데이터베이스 트랜잭션 "롤백"이 발생하거나 다른 오류가 발생한다면, 해당 예외를 의존성에서 받을 수 있습니다. + +따라서, 의존성 내에서 `except SomeException`을 사용하여 특정 예외를 처리할 수 있습니다. + +마찬가지로, `finally`를 사용하여 예외 발생 여부와 관계 없이 종료 단계까 실행되도록 할 수 있습니다. + +{* ../../docs_src/dependencies/tutorial007.py hl[3,5] *} + +## `yield`를 사용하는 하위 의존성 + +모든 크기와 형태의 하위 의존성과 하위 의존성의 "트리"도 가질 수 있으며, 이들 모두가 `yield`를 사용할 수 있습니다. + +**FastAPI**는 `yield`를 사용하는 각 의존성의 "종료 코드"가 올바른 순서로 실행되도록 보장합니다. + +예를 들어, `dependency_c`는 `dependency_b`에 의존할 수 있고, `dependency_b`는 `dependency_a`에 의존할 수 있습니다. + +{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[6,14,22] *} + +이들 모두는 `yield`를 사용할 수 있습니다. + +이 경우 `dependency_c`는 종료 코드를 실행하기 위해, `dependency_b`의 값 (여기서는 `dep_b`로 명명)이 여전히 사용 가능해야 합니다. + +그리고, `dependency_b`는 종료 코드를 위해 `dependency_a`의 값 (여기서는 `dep_a`로 명명) 이 사용 가능해야 합니다. + +{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[18:19,26:27] *} + +같은 방식으로, `yield`를 사용하는 의존성과 `return`을 사용하는 의존성을 함께 사용할 수 있으며, 이들 중 일부가 다른 것들에 의존할 수 있습니다. + +그리고 `yield`를 사용하는 다른 여러 의존성을 필요로 하는 단일 의존성을 가질 수도 있습니다. + +원하는 의존성을 원하는 대로 조합할 수 있습니다. + +**FastAPI**는 모든 것이 올바른 순서로 실행되도록 보장합니다. + +/// note | 기술 세부사항 + +파이썬의 Context Managers 덕분에 이 기능이 작동합니다. + +**FastAPI**는 이를 내부적으로 컨텍스트 관리자를 사용하여 구현합니다. + +/// + +## `yield`와 `HTTPException`를 사용하는 의존성 + +`yield`와 `try` 블록이 있는 의존성을 사용하여 예외를 처리할 수 있다는 것을 알게 되었습니다. + +같은 방식으로, `yield` 이후의 종료 코드에서 `HTTPException`이나 유사한 예외를 발생시킬 수 있습니다. + +/// tip | 팁 + +이는 다소 고급 기술이며, 대부분의 경우 경로 연산 함수 등 나머지 애플리케이션 코드 내부에서 예외 (`HTTPException` 포함)를 발생시킬 수 있으므로 실제로는 필요하지 않을 것입니다. + +하지만 필요한 경우 사용할 수 있습니다. 🤓 + +/// + +{* ../../docs_src/dependencies/tutorial008b_an_py39.py hl[18:22,31] *} + +예외를 처리하고(또는 추가로 다른 `HTTPException`을 발생시키기 위해) 사용할 수 있는 또 다른 방법은 [사용자 정의 예외 처리기](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}를 생성하는 것 입니다. + +## `yield`와 `except`를 사용하는 의존성 + +`yield`를 사용하는 의존성에서 `except`를 사용하여 예외를 포착하고 예외를 다시 발생시키지 않거나 (또는 새 예외를 발생시키지 않으면), FastAPI는 해당 예외가 발생했는지 알 수 없습니다. 이는 일반적인 Python 방식과 동일합니다: + +{* ../../docs_src/dependencies/tutorial008c_an_py39.py hl[15:16] *} + +이 경우, `HTTPException`이나 유사한 예외를 발생시키지 않기 때문에 클라이언트는 HTTP 500 Internal Server Error 응답을 보게 되지만, 서버는 어떤 오류가 발생했는지에 대한 **로그**나 다른 표시를 전혀 가지지 않게 됩니다. 😱 + +### `yield`와 `except`를 사용하는 의존성에서 항상 `raise` 하기 + +`yield`가 있는 의존성에서 예외를 잡았을 때는 `HTTPException`이나 유사한 예외를 새로 발생시키지 않는 한, 반드시 원래의 예외를 다시 발생시켜야 합니다. + +`raise`를 사용하여 동일한 예외를 다시 발생시킬 수 있습니다: + +{* ../../docs_src/dependencies/tutorial008d_an_py39.py hl[17] *} + +이제 클라이언트는 동일한 *HTTP 500 Internal Server Error* 오류 응답을 받게 되지만, 서버 로그에는 사용자 정의 예외인 `InternalError"가 기록됩니다. 😎 + +## `yield`를 사용하는 의존성의 실행 순서 + +실행 순서는 아래 다이어그램과 거의 비슷합니다. 시간은 위에서 아래로 흐릅니다. 그리고 각 열은 상호 작용하거나 코드를 실행하는 부분 중 하나입니다. + +```mermaid +sequenceDiagram + +participant client as Client +participant handler as Exception handler +participant dep as Dep with yield +participant operation as Path Operation +participant tasks as Background tasks + + Note over client,operation: Can raise exceptions, including HTTPException + client ->> dep: Start request + Note over dep: Run code up to yield + opt raise Exception + dep -->> handler: Raise Exception + handler -->> client: HTTP error response + end + dep ->> operation: Run dependency, e.g. DB session + opt raise + operation -->> dep: Raise Exception (e.g. HTTPException) + opt handle + dep -->> dep: Can catch exception, raise a new HTTPException, raise other exception + end + handler -->> client: HTTP error response + end + + operation ->> client: Return response to client + Note over client,operation: Response is already sent, can't change it anymore + opt Tasks + operation -->> tasks: Send background tasks + end + opt Raise other exception + tasks -->> tasks: Handle exceptions in the background task code + end +``` + +/// info | 정보 + +클라이언트에 **하나의 응답** 만 전송됩니다. 이는 오류 응답 중 하나일 수도 있고,*경로 작업*에서 생성된 응답일 수도 있습니다. + +이러한 응답 중 하나가 전송된 후에는 다른 응답을 보낼 수 없습니다. + +/// + +/// tip | 팁 + +이 다이어그램은 `HTTPException`을 보여주지만, `yield`를 사용하는 의존성에서 처리한 예외나 [사용자 정의 예외처리기](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}.를 사용하여 처리한 다른 예외도 발생시킬 수 있습니다. + +어떤 예외가 발생하든, `HTTPException`을 포함하여 yield를 사용하는 의존성으로 전달됩니다. 대부분의 경우 예외를 다시 발생시키거나 새로운 예외를 발생시켜야 합니다. + +/// + +## `yield`, `HTTPException`, `except` 및 백그라운드 작업을 사용하는 의존성 + +/// warning | 경고 + +이러한 기술적 세부 사항은 대부분 필요하지 않으므로 이 섹션을 건너뛰고 아래에서 계속 진행해도 됩니다. + +이러한 세부 정보는 주로 FastAPI 0.106.0 이전 버전에서 `yield`가 있는 의존성의 리소스를 백그라운드 작업에서 사용했던 경우메 유용합니다. + +/// + +### `yield`와 `except`를 사용하는 의존성, 기술 세부사항 + +FastAPI 0.110.0 이전에는 `yield`가 포함된 의존성을 사용한 후 해당 의존성에서 `except`가 포함된 예외를 캡처하고 다시 예외를 발생시키지 않으면 예외가 자동으로 예외 핸들러 또는 내부 서버 오류 핸들러로 발생/전달되었습니다. + +이는 처리기 없이 전달된 예외(내부 서버 오류)에서 처리되지 않은 메모리 소비를 수정하고 일반 파이썬 코드의 동작과 일치하도록 하기 위해 0.110.0 버전에서 변경되었습니다. + +### 백그라운드 작업과 `yield`를 사용하는 의존성, 기술 세부사항 + +FastAPI 0.106.0 이전에는 `yield` 이후에 예외를 발생시키는 것이 불가능했습니다. `yield`가 있는 의존성 종료 코드는 응답이 전송된 이후에 실행되었기 때문에, [예외 처리기](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}가 이미 실행된 상태였습니다. + +이는 주로 백그라운드 작업 내에서 의존성에서 "yield된" 동일한 객체를 사용할 수 있도록 하기 위해 이런 방식으로 설계되었습니다. 종료 코드는 백그라운드 작업이 완료된 후에 실행되었기 때문입니다 + +하지만 이렇게 하면 리소스를 불필요하게 양보한 의존성(예: 데이터베이스 연결)에서 보유하면서 응답이 네트워크를 통해 이동할 때까지 기다리는 것을 의미하기 때문에 FastAPI 0.106.0에서 변경되었습니다. + +/// tip | 팁 + +또한 백그라운드 작업은 일반적으로 자체 리소스(예: 자체 데이터베이스 연결)를 사용하여 별도로 처리해야 하는 독립적인 로직 집합입니다. + +따라서 이렇게 하면 코드가 더 깔끔해집니다. + +/// + +만약 이전에 이러한 동작에 의존했다면, 이제는 백그라운드 작업 내부에서 백그라운드 작업을 위한 리소스를 생성하고, `yield`가 있는 의존성의 리소스에 의존하지 않는 데이터만 내부적으로 사용해야합니다. + +예를 들어, 동일한 데이터베이스 세션을 사용하는 대신, 백그라운드 작업 내부에서 새로운 데이터베이스 세션을 생성하고 이 새로운 세션을 사용하여 데이터베이스에서 객체를 가져와야 합니다. 그리고 데이터베이스 객체를 백그라운드 작업 함수의 매개변수로 직접 전달하는 대신, 해당 객체의 ID를 전달한 다음 백그라운드 작업 함수 내부에서 객체를 다시 가져와야 합니다 + +## 컨텍스트 관리자 + +### "컨텍스트 관리자"란? + +"컨텍스트 관리자"는 Python에서 `with` 문에서 사용할 수 있는 모든 객체를 의미합니다. + +예를 들어, `with`를 사용하여 파일을 읽을 수 있습니다: + +```Python +with open("./somefile.txt") as f: + contents = f.read() + print(contents) +``` + +내부적으로 `open("./somefile.txt")` 는 "컨텍스트 관리자(Context Manager)"라고 불리는 객체를 생성합니다. + +`with` 블록이 끝나면, 예외가 발생했더라도 파일을 닫도록 보장합니다. + +`yield`가 있는 의존성을 생성하면 **FastAPI**는 내부적으로 이를 위한 컨텍스트 매니저를 생성하고 다른 관련 도구들과 결합합니다. + +### `yield`를 사용하는 의존성에서 컨텍스트 관리자 사용하기 + +/// warning | 경고 + +이것은 어느 정도 "고급" 개념입니다. + +**FastAPI**를 처음 시작하는 경우 지금은 이 부분을 건너뛰어도 좋습니다. + +/// + +Python에서는 다음을 통해 컨텍스트 관리자를 생성할 수 있습니다. 두 가지 메서드가 있는 클래스를 생성합니다: `__enter__()` and `__exit__()`. + +**FastAPI**의 `yield`가 있는 의존성 내에서 +`with` 또는 `async with`문을 사용하여 이들을 활용할 수 있습니다: + +{* ../../docs_src/dependencies/tutorial010.py hl[1:9,13] *} + +/// tip | 팁 + +컨텍스트 관리자를 생성하는 또 다른 방법은 다음과 같습니다: + +* `@contextlib.contextmanager` 또는 +* `@contextlib.asynccontextmanager` + +이들은 단일 `yield`가 있는 함수를 꾸미는 데 사용합니다. + +이것이 **FastAPI**가 `yield`가 있는 의존성을 위해 내부적으로 사용하는 방식입니다. + +하지만 FastAPI 의존성에는 이러한 데코레이터를 사용할 필요가 없습니다(그리고 사용해서도 안됩니다). + +FastAPI가 내부적으로 이를 처리해 줄 것입니다. + +/// diff --git a/docs/ko/docs/tutorial/dependencies/global-dependencies.md b/docs/ko/docs/tutorial/dependencies/global-dependencies.md new file mode 100644 index 000000000..0d0e7684d --- /dev/null +++ b/docs/ko/docs/tutorial/dependencies/global-dependencies.md @@ -0,0 +1,15 @@ +# 전역 의존성 + +몇몇 애플리케이션에서는 애플리케이션 전체에 의존성을 추가하고 싶을 수 있습니다. + +[*경로 작동 데코레이터*에 `dependencies` 추가하기](dependencies-in-path-operation-decorators.md){.internal-link target=_blank}와 유사한 방법으로 `FastAPI` 애플리케이션에 그것들을 추가할 수 있습니다. + +그런 경우에, 애플리케이션의 모든 *경로 작동*에 적용될 것입니다: + +{* ../../docs_src/dependencies/tutorial012_an_py39.py hl[16] *} + +그리고 [*경로 작동 데코레이터*에 `dependencies` 추가하기](dependencies-in-path-operation-decorators.md){.internal-link target=_blank}에 대한 아이디어는 여전히 적용되지만 여기에서는 앱에 있는 모든 *경로 작동*에 적용됩니다. + +## *경로 작동* 모음에 대한 의존성 + +이후에 여러 파일들을 가지는 더 큰 애플리케이션을 구조화하는 법([더 큰 애플리케이션 - 여러 파일들](../../tutorial/bigger-applications.md){.internal-link target=_blank})을 읽을 때, *경로 작동* 모음에 대한 단일 `dependencies` 매개변수를 선언하는 법에 대해서 배우게 될 것입니다. diff --git a/docs/ko/docs/tutorial/dependencies/index.md b/docs/ko/docs/tutorial/dependencies/index.md new file mode 100644 index 000000000..b35a41e37 --- /dev/null +++ b/docs/ko/docs/tutorial/dependencies/index.md @@ -0,0 +1,250 @@ +# 의존성 + +**FastAPI**는 아주 강력하지만 직관적인 **의존성 주입** 시스템을 가지고 있습니다. + +이는 사용하기 아주 쉽게 설계했으며, 어느 개발자나 다른 컴포넌트와 **FastAPI**를 쉽게 통합할 수 있도록 만들었습니다. + +## "의존성 주입"은 무엇입니까? + +**"의존성 주입"**은 프로그래밍에서 여러분의 코드(이 경우, 경로 작동 함수)가 작동하고 사용하는 데 필요로 하는 것, 즉 "의존성"을 선언할 수 있는 방법을 의미합니다. + +그 후에, 시스템(이 경우 FastAPI)은 여러분의 코드가 요구하는 의존성을 제공하기 위해 필요한 모든 작업을 처리합니다.(의존성을 "주입"합니다) + +이는 여러분이 다음과 같은 사항을 필요로 할 때 매우 유용합니다: + +* 공용된 로직을 가졌을 경우 (같은 코드 로직이 계속 반복되는 경우). +* 데이터베이스 연결을 공유하는 경우. +* 보안, 인증, 역할 요구 사항 등을 강제하는 경우. +* 그리고 많은 다른 사항... + +이 모든 사항을 할 때 코드 반복을 최소화합니다. + +## 첫번째 단계 + +아주 간단한 예제를 봅시다. 너무 간단할 것이기에 지금 당장은 유용하지 않을 수 있습니다. + +하지만 이를 통해 **의존성 주입** 시스템이 어떻게 작동하는지에 중점을 둘 것입니다. + +### 의존성 혹은 "디펜더블" 만들기 + +의존성에 집중해 봅시다. + +*경로 작동 함수*가 가질 수 있는 모든 매개변수를 갖는 단순한 함수입니다: + +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *} + +이게 다입니다. + +**단 두 줄입니다**. + +그리고, 이 함수는 여러분의 모든 *경로 작동 함수*가 가지고 있는 것과 같은 형태와 구조를 가지고 있습니다. + +여러분은 이를 "데코레이터"가 없는 (`@app.get("/some-path")`가 없는) *경로 작동 함수*라고 생각할 수 있습니다. + +그리고 여러분이 원하는 무엇이든 반환할 수 있습니다. + +이 경우, 이 의존성은 다음과 같은 경우를 기대합니다: + +* 선택적인 쿼리 매개변수 `q`, `str`을 자료형으로 가집니다. +* 선택적인 쿼리 매개변수 `skip`, `int`를 자료형으로 가지며 기본 값은 `0`입니다. +* 선택적인 쿼리 매개변수 `limit`,`int`를 자료형으로 가지며 기본 값은 `100`입니다. + +그 후 위의 값을 포함한 `dict` 자료형으로 반환할 뿐입니다. + +/// info | 정보 + +FastAPI는 0.95.0 버전부터 `Annotated`에 대한 지원을 (그리고 이를 사용하기 권장합니다) 추가했습니다. + +옛날 버전을 가지고 있는 경우, `Annotated`를 사용하려 하면 에러를 맞이하게 될 것입니다. + +`Annotated`를 사용하기 전에 최소 0.95.1로 [FastAPI 버전 업그레이드](../../deployment/versions.md#fastapi_2){.internal-link target=_blank}를 확실하게 하세요. + +/// + +### `Depends` 불러오기 + +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *} + +### "의존자"에 의존성 명시하기 + +*경로 작동 함수*의 매개변수로 `Body`, `Query` 등을 사용하는 방식과 같이 새로운 매개변수로 `Depends`를 사용합니다: + +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *} + +비록 `Body`, `Query` 등을 사용하는 것과 같은 방식으로 여러분의 함수의 매개변수에 있는 `Depends`를 사용하지만, `Depends`는 약간 다르게 작동합니다. + +`Depends`에 단일 매개변수만 전달했습니다. + +이 매개변수는 함수같은 것이어야 합니다. + +여러분은 직접 **호출하지 않았습니다** (끝에 괄호를 치지 않았습니다), 단지 `Depends()`에 매개변수로 넘겨 줬을 뿐입니다. + +그리고 그 함수는 *경로 작동 함수*가 작동하는 것과 같은 방식으로 매개변수를 받습니다. + +/// tip | 팁 + +여러분은 다음 장에서 함수를 제외하고서, "다른 것들"이 어떻게 의존성으로 사용되는지 알게 될 것입니다. + +/// + +새로운 요청이 도착할 때마다, **FastAPI**는 다음을 처리합니다: + +* 올바른 매개변수를 가진 의존성("디펜더블") 함수를 호출합니다. +* 함수에서 결과를 받아옵니다. +* *경로 작동 함수*에 있는 매개변수에 그 결과를 할당합니다 + +```mermaid +graph TB + +common_parameters(["common_parameters"]) +read_items["/items/"] +read_users["/users/"] + +common_parameters --> read_items +common_parameters --> read_users +``` + +이렇게 하면 공용 코드를 한번만 적어도 되며, **FastAPI**는 *경로 작동*을 위해 이에 대한 호출을 처리합니다. + +/// check | 확인 + +특별한 클래스를 만들지 않아도 되며, 이러한 것 혹은 비슷한 종류를 **FastAPI**에 "등록"하기 위해 어떤 곳에 넘겨주지 않아도 됩니다. + +단순히 `Depends`에 넘겨주기만 하면 되며, **FastAPI**는 나머지를 어찌할지 알고 있습니다. + +/// + +## `Annotated`인 의존성 공유하기 + +위의 예제에서 몇몇 작은 **코드 중복**이 있다는 것을 보았을 겁니다. + +`common_parameters()`의존을 사용해야 한다면, 타입 명시와 `Depends()`와 함께 전체 매개변수를 적어야 합니다: + +```Python +commons: Annotated[dict, Depends(common_parameters)] +``` + +하지만 `Annotated`를 사용하고 있기에, `Annotated` 값을 변수에 저장하고 여러 장소에서 사용할 수 있습니다: + +{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *} + +/// tip | 팁 + +이는 그저 표준 파이썬이고 "type alias"라고 부르며 사실 **FastAPI**에 국한되는 것은 아닙니다. + +하지만, `Annotated`를 포함하여, **FastAPI**가 파이썬 표준을 기반으로 하고 있기에, 이를 여러분의 코드 트릭으로 사용할 수 있습니다. 😎 + +/// + +이 의존성은 계속해서 예상한대로 작동할 것이며, **제일 좋은 부분**은 **타입 정보가 보존된다는 것입니다**. 즉 여러분의 편집기가 **자동 완성**, **인라인 에러** 등을 계속해서 제공할 수 있다는 것입니다. `mypy`같은 다른 도구도 마찬가지입니다. + +이는 특히 **많은 *경로 작동***에서 **같은 의존성**을 계속해서 사용하는 **거대 코드 기반**안에서 사용하면 유용할 것입니다. + +## `async`하게, 혹은 `async`하지 않게 + +의존성이 (*경로 작동 함수*에서 처럼 똑같이) **FastAPI**에 의해 호출될 수 있으며, 함수를 정의할 때 동일한 규칙이 적용됩니다. + +`async def`을 사용하거나 혹은 일반적인 `def`를 사용할 수 있습니다. + +그리고 일반적인 `def` *경로 작동 함수* 안에 `async def`로 의존성을 선언할 수 있으며, `async def` *경로 작동 함수* 안에 `def`로 의존성을 선언하는 등의 방법이 있습니다. + +아무 문제 없습니다. **FastAPI**는 무엇을 할지 알고 있습니다. + +/// note | 참고 + +잘 모르시겠다면, [Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank} 문서에서 `async`와 `await`에 대해 확인할 수 있습니다. + +/// + +## OpenAPI와 통합 + +모든 요청 선언, 검증과 의존성(및 하위 의존성)에 대한 요구 사항은 동일한 OpenAPI 스키마에 통합됩니다. + +따라서 대화형 문서에 이러한 의존성에 대한 모든 정보 역시 포함하고 있습니다: + + + +## 간단한 사용법 + +이를 보면, *경로 작동 함수*는 *경로*와 *작동*이 매칭되면 언제든지 사용되도록 정의되었으며, **FastAPI**는 올바른 매개변수를 가진 함수를 호출하고 해당 요청에서 데이터를 추출합니다. + +사실, 모든 (혹은 대부분의) 웹 프레임워크는 이와 같은 방식으로 작동합니다. + +여러분은 이러한 함수들을 절대 직접 호출하지 않습니다. 프레임워크(이 경우 **FastAPI**)에 의해 호출됩니다. + +의존성 주입 시스템과 함께라면 **FastAPI**에게 여러분의 *경로 작동 함수*가 실행되기 전에 실행되어야 하는 무언가에 여러분의 *경로 작동 함수* 또한 "의존"하고 있음을 알릴 수 있으며, **FastAPI**는 이를 실행하고 결과를 "주입"할 것입니다. + +"의존성 주입"이라는 동일한 아이디어에 대한 다른 일반적인 용어는 다음과 같습니다: + +* 리소스 +* 제공자 +* 서비스 +* 인젝터블 +* 컴포넌트 + +## **FastAPI** 플러그인 + +통합과 "플러그인"은 **의존성 주입** 시스템을 사용하여 구축할 수 있습니다. 하지만 실제로 **"플러그인"을 만들 필요는 없습니다**, 왜냐하면 의존성을 사용함으로써 여러분의 *경로 작동 함수*에 통합과 상호 작용을 무한대로 선언할 수 있기 때문입니다. + +그리고 "말 그대로", 그저 필요로 하는 파이썬 패키지를 임포트하고 단 몇 줄의 코드로 여러분의 API 함수와 통합함으로써, 의존성을 아주 간단하고 직관적인 방법으로 만들 수 있습니다. + +관계형 및 NoSQL 데이터베이스, 보안 등, 이에 대한 예시를 다음 장에서 볼 수 있습니다. + +## **FastAPI** 호환성 + +의존성 주입 시스템의 단순함은 **FastAPI**를 다음과 같은 요소들과 호환할 수 있게 합니다: + +* 모든 관계형 데이터베이스 +* NoSQL 데이터베이스 +* 외부 패키지 +* 외부 API +* 인증 및 권한 부여 시스템 +* API 사용 모니터링 시스템 +* 응답 데이터 주입 시스템 +* 기타 등등. + +## 간편하고 강력하다 + +계층적인 의존성 주입 시스템은 정의하고 사용하기 쉽지만, 여전히 매우 강력합니다. + +여러분은 스스로를 의존하는 의존성을 정의할 수 있습니다. + +끝에는, 계층적인 나무로 된 의존성이 만들어지며, 그리고 **의존성 주입** 시스템은 (하위 의존성도 마찬가지로) 이러한 의존성들을 처리하고 각 단계마다 결과를 제공합니다(주입합니다). + +예를 들면, 여러분이 4개의 API 엔드포인트(*경로 작동*)를 가지고 있다고 해봅시다: + +* `/items/public/` +* `/items/private/` +* `/users/{user_id}/activate` +* `/items/pro/` + +그 다음 각각에 대해 그저 의존성과 하위 의존성을 사용하여 다른 권한 요구 사항을 추가할 수 있을 겁니다: + +```mermaid +graph TB + +current_user(["current_user"]) +active_user(["active_user"]) +admin_user(["admin_user"]) +paying_user(["paying_user"]) + +public["/items/public/"] +private["/items/private/"] +activate_user["/users/{user_id}/activate"] +pro_items["/items/pro/"] + +current_user --> active_user +active_user --> admin_user +active_user --> paying_user + +current_user --> public +active_user --> private +admin_user --> activate_user +paying_user --> pro_items +``` + +## **OpenAPI**와의 통합 + +이 모든 의존성은 각각의 요구사항을 선언하는 동시에, *경로 작동*에 매개변수, 검증 등을 추가합니다. + +**FastAPI**는 이 모든 것을 OpenAPI 스키마에 추가할 것이며, 이를 통해 대화형 문서 시스템에 나타날 것입니다. diff --git a/docs/ko/docs/tutorial/encoder.md b/docs/ko/docs/tutorial/encoder.md index 8b5fdb8b7..4323957f4 100644 --- a/docs/ko/docs/tutorial/encoder.md +++ b/docs/ko/docs/tutorial/encoder.md @@ -20,9 +20,7 @@ JSON 호환 가능 데이터만 수신하는 `fake_db` 데이터베이스가 존 Pydantic 모델과 같은 객체를 받고 JSON 호환 가능한 버전으로 반환합니다: -```Python hl_lines="5 22" -{!../../../docs_src/encoder/tutorial001.py!} -``` +{* ../../docs_src/encoder/tutorial001.py hl[5,22] *} 이 예시는 Pydantic 모델을 `dict`로, `datetime` 형식을 `str`로 변환합니다. @@ -30,5 +28,8 @@ Pydantic 모델과 같은 객체를 받고 JSON 호환 가능한 버전으로 길이가 긴 문자열 형태의 JSON 형식(문자열)의 데이터가 들어있는 상황에서는 `str`로 반환하지 않습니다. JSON과 모두 호환되는 값과 하위 값이 있는 Python 표준 데이터 구조 (예: `dict`)를 반환합니다. -!!! note "참고" - 실제로 `jsonable_encoder`는 **FastAPI** 에서 내부적으로 데이터를 변환하는 데 사용하지만, 다른 많은 곳에서도 이는 유용합니다. +/// note | 참고 + +실제로 `jsonable_encoder`는 **FastAPI** 에서 내부적으로 데이터를 변환하는 데 사용하지만, 다른 많은 곳에서도 이는 유용합니다. + +/// diff --git a/docs/ko/docs/tutorial/extra-data-types.md b/docs/ko/docs/tutorial/extra-data-types.md new file mode 100644 index 000000000..4a41ba0dc --- /dev/null +++ b/docs/ko/docs/tutorial/extra-data-types.md @@ -0,0 +1,62 @@ +# 추가 데이터 자료형 + +지금까지 일반적인 데이터 자료형을 사용했습니다. 예를 들면 다음과 같습니다: + +* `int` +* `float` +* `str` +* `bool` + +하지만 더 복잡한 데이터 자료형 또한 사용할 수 있습니다. + +그리고 지금까지와 같은 기능들을 여전히 사용할 수 있습니다. + +* 훌륭한 편집기 지원. +* 들어오는 요청의 데이터 변환. +* 응답 데이터의 데이터 변환. +* 데이터 검증. +* 자동 어노테이션과 문서화. + +## 다른 데이터 자료형 + +아래의 추가적인 데이터 자료형을 사용할 수 있습니다: + +* `UUID`: + * 표준 "범용 고유 식별자"로, 많은 데이터베이스와 시스템에서 ID로 사용됩니다. + * 요청과 응답에서 `str`로 표현됩니다. +* `datetime.datetime`: + * 파이썬의 `datetime.datetime`. + * 요청과 응답에서 `2008-09-15T15:53:00+05:00`와 같은 ISO 8601 형식의 `str`로 표현됩니다. +* `datetime.date`: + * 파이썬의 `datetime.date`. + * 요청과 응답에서 `2008-09-15`와 같은 ISO 8601 형식의 `str`로 표현됩니다. +* `datetime.time`: + * 파이썬의 `datetime.time`. + * 요청과 응답에서 `14:23:55.003`와 같은 ISO 8601 형식의 `str`로 표현됩니다. +* `datetime.timedelta`: + * 파이썬의 `datetime.timedelta`. + * 요청과 응답에서 전체 초(seconds)의 `float`로 표현됩니다. + * Pydantic은 "ISO 8601 시차 인코딩"으로 표현하는 것 또한 허용합니다. 더 많은 정보는 이 문서에서 확인하십시오.. +* `frozenset`: + * 요청과 응답에서 `set`와 동일하게 취급됩니다: + * 요청 시, 리스트를 읽어 중복을 제거하고 `set`로 변환합니다. + * 응답 시, `set`는 `list`로 변환됩니다. + * 생성된 스키마는 (JSON 스키마의 `uniqueItems`를 이용해) `set`의 값이 고유함을 명시합니다. +* `bytes`: + * 표준 파이썬의 `bytes`. + * 요청과 응답에서 `str`로 취급됩니다. + * 생성된 스키마는 이것이 `binary` "형식"의 `str`임을 명시합니다. +* `Decimal`: + * 표준 파이썬의 `Decimal`. + * 요청과 응답에서 `float`와 동일하게 다뤄집니다. +* 여기에서 모든 유효한 pydantic 데이터 자료형을 확인할 수 있습니다: Pydantic 데이터 자료형. + +## 예시 + +위의 몇몇 자료형을 매개변수로 사용하는 *경로 작동* 예시입니다. + +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *} + +함수 안의 매개변수가 그들만의 데이터 자료형을 가지고 있으며, 예를 들어, 다음과 같이 날짜를 조작할 수 있음을 참고하십시오: + +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *} diff --git a/docs/ko/docs/tutorial/first-steps.md b/docs/ko/docs/tutorial/first-steps.md index a669cb2ba..174f00d46 100644 --- a/docs/ko/docs/tutorial/first-steps.md +++ b/docs/ko/docs/tutorial/first-steps.md @@ -1,12 +1,10 @@ # 첫걸음 -가장 단순한 FastAPI 파일은 다음과 같이 보일 겁니다: +가장 단순한 FastAPI 파일은 다음과 같이 보일 것입니다: -```Python -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} -위를 `main.py`에 복사합니다. +위 코드를 `main.py`에 복사합니다. 라이브 서버를 실행합니다: @@ -24,14 +22,17 @@ $ uvicorn main:app --reload
-!!! note "참고" - `uvicorn main:app` 명령은 다음을 의미합니다: +/// note | 참고 + +`uvicorn main:app` 명령은 다음을 의미합니다: + +* `main`: 파일 `main.py` (파이썬 "모듈"). +* `app`: `main.py` 내부의 `app = FastAPI()` 줄에서 생성한 오브젝트. +* `--reload`: 코드 변경 시 자동으로 서버 재시작. 개발 시에만 사용. - * `main`: 파일 `main.py` (파이썬 "모듈"). - * `app`: `main.py` 내부의 `app = FastAPI()` 줄에서 생성한 오브젝트. - * `--reload`: 코드 변경 후 서버 재시작. 개발에만 사용. +/// -출력에 아래와 같은 줄이 있습니다: +출력되는 줄들 중에는 아래와 같은 내용이 있습니다: ```hl_lines="4" INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) @@ -75,7 +76,7 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) #### API "스키마" -이 경우, OpenAPI는 API의 스키마를 어떻게 정의하는지 지시하는 규격입니다. +OpenAPI는 API의 스키마를 어떻게 정의하는지 지시하는 규격입니다. 이 스키마 정의는 API 경로, 가능한 매개변수 등을 포함합니다. @@ -87,13 +88,13 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) #### OpenAPI와 JSON 스키마 -OpenAPI는 API에 대한 API 스키마를 정의합니다. 또한 이 스키마에는 JSON 데이터 스키마의 표준인 **JSON 스키마**를 사용하여 API에서 보내고 받은 데이터의 정의(또는 "스키마")를 포함합니다. +OpenAPI는 당신의 API에 대한 API 스키마를 정의합니다. 또한 이 스키마는 JSON 데이터 스키마의 표준인 **JSON 스키마**를 사용하여 당신의 API가 보내고 받는 데이터의 정의(또는 "스키마")를 포함합니다. #### `openapi.json` 확인 -가공되지 않은 OpenAPI 스키마가 어떻게 생겼는지 궁금하다면, FastAPI는 자동으로 API의 설명과 함께 JSON (스키마)를 생성합니다. +FastAPI는 자동으로 API의 설명과 함께 JSON (스키마)를 생성합니다. -여기에서 직접 볼 수 있습니다: http://127.0.0.1:8000/openapi.json. +가공되지 않은 OpenAPI 스키마가 어떻게 생겼는지 궁금하다면, 여기에서 직접 볼 수 있습니다: http://127.0.0.1:8000/openapi.json. 다음과 같이 시작하는 JSON을 확인할 수 있습니다: @@ -124,34 +125,33 @@ OpenAPI 스키마는 포함된 두 개의 대화형 문서 시스템을 제공 그리고 OpenAPI의 모든 것을 기반으로 하는 수십 가지 대안이 있습니다. **FastAPI**로 빌드한 애플리케이션에 이러한 대안을 쉽게 추가 할 수 있습니다. -API와 통신하는 클라이언트를 위해 코드를 자동으로 생성하는 데도 사용할 수 있습니다. 예로 프론트엔드, 모바일, IoT 애플리케이션이 있습니다. +API와 통신하는 클라이언트(프론트엔드, 모바일, IoT 애플리케이션 등)를 위해 코드를 자동으로 생성하는 데도 사용할 수 있습니다. ## 단계별 요약 ### 1 단계: `FastAPI` 임포트 -```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} + +`FastAPI`는 당신의 API를 위한 모든 기능을 제공하는 파이썬 클래스입니다. -`FastAPI`는 API에 대한 모든 기능을 제공하는 파이썬 클래스입니다. +/// note | 기술 세부사항 -!!! note "기술 세부사항" - `FastAPI`는 `Starlette`를 직접 상속하는 클래스입니다. +`FastAPI`는 `Starlette`를 직접 상속하는 클래스입니다. - `FastAPI`로 Starlette의 모든 기능을 사용할 수 있습니다. +`FastAPI`로 Starlette의 모든 기능을 사용할 수 있습니다. + +/// ### 2 단계: `FastAPI` "인스턴스" 생성 -```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[3] *} -여기 있는 `app` 변수는 `FastAPI` 클래스의 "인스턴스"가 됩니다. +여기에서 `app` 변수는 `FastAPI` 클래스의 "인스턴스"가 됩니다. -이것은 모든 API를 생성하기 위한 상호작용의 주요 지점이 될 것입니다. +이것은 당신의 모든 API를 생성하기 위한 상호작용의 주요 지점이 될 것입니다. -이 `app`은 다음 명령에서 `uvicorn`이 참조하고 것과 동일합니다: +이 `app`은 다음 명령에서 `uvicorn`이 참조하고 있는 것과 동일합니다:
@@ -165,9 +165,7 @@ $ uvicorn main:app --reload 아래처럼 앱을 만든다면: -```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} -``` +{* ../../docs_src/first_steps/tutorial002.py hl[3] *} 이를 `main.py` 파일에 넣고, `uvicorn`을 아래처럼 호출해야 합니다: @@ -181,11 +179,11 @@ $ uvicorn main:my_awesome_api --reload
-### 3 단계: *경로 동작* 생성 +### 3 단계: *경로 작동* 생성 #### 경로 -여기서 "경로"는 첫 번째 `/`에서 시작하는 URL의 마지막 부분을 나타냅니다. +여기서 "경로"는 첫 번째 `/`부터 시작하는 URL의 뒷부분을 의미합니다. 그러므로 아래와 같은 URL에서: @@ -199,14 +197,17 @@ https://example.com/items/foo /items/foo ``` -!!! info "정보" - "경로"는 일반적으로 "앤드포인트" 또는 "라우트"라고도 불립니다. +/// info | 정보 + +"경로"는 일반적으로 "엔드포인트" 또는 "라우트"라고도 불립니다. + +/// -API를 빌드하는 동안 "경로"는 "관심사"와 "리소스"를 분리하는 주요 방법입니다. +API를 설계할 때 "경로"는 "관심사"와 "리소스"를 분리하기 위한 주요한 방법입니다. -#### 동작 +#### 작동 -여기서 "동작(Operation)"은 HTTP "메소드" 중 하나를 나타냅니다. +"작동(Operation)"은 HTTP "메소드" 중 하나를 나타냅니다. 다음 중 하나이며: @@ -215,7 +216,7 @@ API를 빌드하는 동안 "경로"는 "관심사"와 "리소스"를 분리하 * `PUT` * `DELETE` -...이국적인 것들도 있습니다: +...흔히 사용되지 않는 것들도 있습니다: * `OPTIONS` * `HEAD` @@ -226,108 +227,109 @@ HTTP 프로토콜에서는 이러한 "메소드"를 하나(또는 이상) 사용 --- -API를 빌드하는 동안 일반적으로 특정 행동을 수행하기 위해 특정 HTTP 메소드를 사용합니다. +API를 설계할 때 일반적으로 특정 행동을 수행하기 위해 특정 HTTP 메소드를 사용합니다. -일반적으로 다음을 사용합니다: +일반적으로 다음과 같습니다: * `POST`: 데이터를 생성하기 위해. * `GET`: 데이터를 읽기 위해. -* `PUT`: 데이터를 업데이트하기 위해. +* `PUT`: 데이터를 수정하기 위해. * `DELETE`: 데이터를 삭제하기 위해. -그래서 OpenAPI에서는 각 HTTP 메소드들을 "동작"이라 부릅니다. +그래서 OpenAPI에서는 각 HTTP 메소드들을 "작동"이라 부릅니다. -이제부터 우리는 메소드를 "**동작**"이라고도 부를겁니다. +우리 역시 이제부터 메소드를 "**작동**"이라고 부를 것입니다. -#### *경로 동작 데코레이터* 정의 +#### *경로 작동 데코레이터* 정의 -```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[6] *} `@app.get("/")`은 **FastAPI**에게 바로 아래에 있는 함수가 다음으로 이동하는 요청을 처리한다는 것을 알려줍니다. * 경로 `/` -* get 동작 사용 +* get 작동 사용 + +/// info | `@decorator` 정보 + +이 `@something` 문법은 파이썬에서 "데코레이터"라 부릅니다. -!!! info "`@decorator` 정보" - 이 `@something` 문법은 파이썬에서 "데코레이터"라 부릅니다. +마치 예쁜 장식용(Decorative) 모자처럼(개인적으로 이 용어가 여기서 유래한 것 같습니다) 함수 맨 위에 놓습니다. - 함수 맨 위에 놓습니다. 마치 예쁜 장식용(Decorative) 모자처럼(개인적으로 이 용어가 여기서 유래한거 같습니다). +"데코레이터"는 아래 있는 함수를 받아 그것으로 무언가를 합니다. - "데코레이터" 아래 있는 함수를 받고 그걸 이용해 무언가 합니다. +우리의 경우, 이 데코레이터는 **FastAPI**에게 아래 함수가 **경로** `/`의 `get` **작동**에 해당한다고 알려줍니다. - 우리의 경우, 이 데코레이터는 **FastAPI**에게 아래 함수가 **경로** `/`에 해당하는 `get` **동작**하라고 알려줍니다. +이것이 "**경로 작동 데코레이터**"입니다. - 이것이 "**경로 동작 데코레이터**"입니다. +/// -다른 동작도 쓸 수 있습니다: +다른 작동도 사용할 수 있습니다: * `@app.post()` * `@app.put()` * `@app.delete()` -이국적인 것들도 있습니다: +흔히 사용되지 않는 것들도 있습니다: * `@app.options()` * `@app.head()` * `@app.patch()` * `@app.trace()` -!!! tip "팁" - 각 동작(HTTP 메소드)을 원하는 대로 사용해도 됩니다. +/// tip | 팁 + +각 작동(HTTP 메소드)을 원하는 대로 사용해도 됩니다. + +**FastAPI**는 특정 의미를 강제하지 않습니다. - **FastAPI**는 특정 의미를 강제하지 않습니다. +여기서 정보는 지침서일뿐 강제사항이 아닙니다. - 여기서 정보는 지침서일뿐 요구사항이 아닙니다. +예를 들어 GraphQL을 사용하는 경우, 일반적으로 `POST` 작동만 사용하여 모든 행동을 수행합니다. - 예를 들어 GraphQL을 사용할때 일반적으로 `POST` 동작만 사용하여 모든 행동을 수행합니다. +/// -### 4 단계: **경로 동작 함수** 정의 +### 4 단계: **경로 작동 함수** 정의 -다음은 우리의 "**경로 동작 함수**"입니다: +다음은 우리의 "**경로 작동 함수**"입니다: * **경로**: 는 `/`입니다. -* **동작**: 은 `get`입니다. +* **작동**: 은 `get`입니다. * **함수**: 는 "데코레이터" 아래에 있는 함수입니다 (`@app.get("/")` 아래). -```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[7] *} 이것은 파이썬 함수입니다. -`GET` 동작을 사용하여 URL "`/`"에 대한 요청을 받을 때마다 **FastAPI**에 의해 호출됩니다. +URL "`/`"에 대한 `GET` 작동을 사용하는 요청을 받을 때마다 **FastAPI**에 의해 호출됩니다. -위의 경우 `async` 함수입니다. +위의 예시에서 이 함수는 `async`(비동기) 함수입니다. --- -`async def` 대신 일반 함수로 정의할 수 있습니다: +`async def`을 이용하는 대신 일반 함수로 정의할 수 있습니다: -```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} -``` +{* ../../docs_src/first_steps/tutorial003.py hl[7] *} + +/// note | 참고 -!!! note 참고 - 차이점을 모르겠다면 [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}을 확인하세요. +차이점을 모르겠다면 [Async: *"바쁘신 경우"*](../async.md#_1){.internal-link target=_blank}을 확인하세요. + +/// ### 5 단계: 콘텐츠 반환 -```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[8] *} `dict`, `list`, 단일값을 가진 `str`, `int` 등을 반환할 수 있습니다. Pydantic 모델을 반환할 수도 있습니다(나중에 더 자세히 살펴봅니다). -JSON으로 자동 변환되는 객체들과 모델들이 많이 있습니다(ORM 등을 포함해서요). 가장 마음에 드는 것을 사용하세요, 이미 지원되고 있을 겁니다. +JSON으로 자동 변환되는 객체들과 모델들(ORM 등을 포함해서)이 많이 있습니다. 가장 마음에 드는 것을 사용하십시오, 이미 지원되고 있을 것입니다. ## 요약 * `FastAPI` 임포트. * `app` 인스턴스 생성. -* (`@app.get("/")`처럼) **경로 동작 데코레이터** 작성. -* (위에 있는 `def root(): ...`처럼) **경로 동작 함수** 작성. +* (`@app.get("/")`처럼) **경로 작동 데코레이터** 작성. +* (위에 있는 `def root(): ...`처럼) **경로 작동 함수** 작성. * (`uvicorn main:app --reload`처럼) 개발 서버 실행. diff --git a/docs/ko/docs/tutorial/header-param-models.md b/docs/ko/docs/tutorial/header-param-models.md new file mode 100644 index 000000000..bab7291e3 --- /dev/null +++ b/docs/ko/docs/tutorial/header-param-models.md @@ -0,0 +1,56 @@ +# 헤더 매개변수 모델 + +관련 있는 **헤더 매개변수** 그룹이 있는 경우, **Pydantic 모델**을 생성하여 선언할 수 있습니다. + +이를 통해 **여러 위치**에서 **모델을 재사용** 할 수 있고 모든 매개변수에 대한 유효성 검사 및 메타데이터를 한 번에 선언할 수도 있습니다. 😎 + +/// note | 참고 + +이 기능은 FastAPI 버전 `0.115.0` 이후부터 지원됩니다. 🤓 + +/// + +## Pydantic 모델을 사용한 헤더 매개변수 + +**Pydantic 모델**에 필요한 **헤더 매개변수**를 선언한 다음, 해당 매개변수를 `Header`로 선언합니다: + +{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *} + +**FastAPI**는 요청에서 받은 **헤더**에서 **각 필드**에 대한 데이터를 **추출**하고 정의한 Pydantic 모델을 줍니다. + +## 문서 확인하기 + +문서 UI `/docs`에서 필요한 헤더를 볼 수 있습니다: + +
+ +
+ +## 추가 헤더 금지하기 + +일부 특별한 사용 사례(흔하지는 않겠지만)에서는 수신하려는 헤더를 **제한**할 수 있습니다. + +Pydantic의 모델 구성을 사용하여 추가(`extra`) 필드를 금지(`forbid`)할 수 있습니다: + +{* ../../docs_src/header_param_models/tutorial002_an_py310.py hl[10] *} + +클라이언트가 **추가 헤더**를 보내려고 시도하면, **오류** 응답을 받게 됩니다. + +예를 들어, 클라이언트가 `plumbus` 값으로 `tool` 헤더를 보내려고 하면, 클라이언트는 헤더 매개변수 `tool`이 허용 되지 않는다는 **오류** 응답을 받게 됩니다: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["header", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus", + } + ] +} +``` + +## 요약 + +**Pydantic 모델**을 사용하여 **FastAPI**에서 **헤더**를 선언할 수 있습니다. 😎 diff --git a/docs/ko/docs/tutorial/header-params.md b/docs/ko/docs/tutorial/header-params.md index 484554e97..7379eb2a0 100644 --- a/docs/ko/docs/tutorial/header-params.md +++ b/docs/ko/docs/tutorial/header-params.md @@ -6,9 +6,7 @@ 먼저 `Header`를 임포트합니다: -```Python hl_lines="3" -{!../../../docs_src/header_params/tutorial001.py!} -``` +{* ../../docs_src/header_params/tutorial001.py hl[3] *} ## `Header` 매개변수 선언 @@ -16,17 +14,21 @@ 첫 번째 값은 기본값이며, 추가 검증이나 어노테이션 매개변수 모두 전달할 수 있습니다: -```Python hl_lines="9" -{!../../../docs_src/header_params/tutorial001.py!} -``` +{* ../../docs_src/header_params/tutorial001.py hl[9] *} + +/// note | 기술 세부사항 + +`Header`는 `Path`, `Query` 및 `Cookie`의 "자매"클래스입니다. 이 역시 동일한 공통 `Param` 클래스를 상속합니다. + +`Query`, `Path`, `Header` 그리고 다른 것들을 `fastapi`에서 임포트 할 때, 이들은 실제로 특별한 클래스를 반환하는 함수임을 기억하세요. -!!! note "기술 세부사항" - `Header`는 `Path`, `Query` 및 `Cookie`의 "자매"클래스입니다. 이 역시 동일한 공통 `Param` 클래스를 상속합니다. +/// - `Query`, `Path`, `Header` 그리고 다른 것들을 `fastapi`에서 임포트 할 때, 이들은 실제로 특별한 클래스를 반환하는 함수임을 기억하세요. +/// info | 정보 -!!! info "정보" - 헤더를 선언하기 위해서 `Header`를 사용해야 합니다. 그렇지 않으면 해당 매개변수를 쿼리 매개변수로 해석하기 때문입니다. +헤더를 선언하기 위해서 `Header`를 사용해야 합니다. 그렇지 않으면 해당 매개변수를 쿼리 매개변수로 해석하기 때문입니다. + +/// ## 자동 변환 @@ -44,12 +46,13 @@ 만약 언더스코어를 하이픈으로 자동 변환을 비활성화해야 할 어떤 이유가 있다면, `Header`의 `convert_underscores` 매개변수를 `False`로 설정하십시오: -```Python hl_lines="10" -{!../../../docs_src/header_params/tutorial002.py!} -``` +{* ../../docs_src/header_params/tutorial002.py hl[10] *} + +/// warning | 경고 -!!! warning "경고" - `convert_underscore`를 `False`로 설정하기 전에, 어떤 HTTP 프록시들과 서버들은 언더스코어가 포함된 헤더 사용을 허락하지 않는다는 것을 명심하십시오. +`convert_underscore`를 `False`로 설정하기 전에, 어떤 HTTP 프록시들과 서버들은 언더스코어가 포함된 헤더 사용을 허락하지 않는다는 것을 명심하십시오. + +/// ## 중복 헤더 @@ -61,9 +64,7 @@ 예를 들어, 두 번 이상 나타날 수 있는 `X-Token`헤더를 선언하려면, 다음과 같이 작성합니다: -```Python hl_lines="9" -{!../../../docs_src/header_params/tutorial003.py!} -``` +{* ../../docs_src/header_params/tutorial003.py hl[9] *} 다음과 같은 두 개의 HTTP 헤더를 전송하여 해당 *경로* 와 통신할 경우: diff --git a/docs/ko/docs/tutorial/index.md b/docs/ko/docs/tutorial/index.md index deb5ca8f2..9f5328992 100644 --- a/docs/ko/docs/tutorial/index.md +++ b/docs/ko/docs/tutorial/index.md @@ -1,16 +1,16 @@ # 자습서 - 사용자 안내서 -이 자습서는 **FastAPI**의 대부분의 기능을 단계별로 사용하는 방법을 보여줍니다. +이 자습서는 단계별로 **FastAPI**의 대부분의 기능에 대해 설명합니다. -각 섹션은 이전 섹션을 기반해서 점진적으로 만들어 졌지만, 주제에 따라 다르게 구성되었기 때문에 특정 API 요구사항을 해결하기 위해서라면 어느 특정 항목으로던지 직접 이동할 수 있습니다. +각 섹션은 이전 섹션에 기반하는 순차적인 구조로 작성되었지만, 각 주제로 구분되어 있기 때문에 필요에 따라 특정 섹션으로 바로 이동하여 필요한 내용을 바로 확인할 수 있습니다. -또한 향후 참조가 될 수 있도록 만들어졌습니다. +또한 향후에도 참조 자료로 쓰일 수 있도록 작성되었습니다. -그러므로 다시 돌아와서 정확히 필요한 것을 확인할 수 있습니다. +그러므로 필요할 때에 다시 돌아와서 원하는 것을 정확히 찾을 수 있습니다. ## 코드 실행하기 -모든 코드 블록은 복사하고 직접 사용할 수 있습니다(실제로 테스트한 파이썬 파일입니다). +모든 코드 블록은 복사하여 바로 사용할 수 있습니다(실제로 테스트된 파이썬 파일입니다). 예제를 실행하려면 코드를 `main.py` 파일에 복사하고 다음을 사용하여 `uvicorn`을 시작합니다: @@ -28,17 +28,18 @@ $ uvicorn main:app --reload -코드를 작성하거나 복사, 편집할 때, 로컬에서 실행하는 것을 **강력히 장려**합니다. +코드를 작성하거나 복사, 편집할 때, 로컬 환경에서 실행하는 것을 **강력히 권장**합니다. + +로컬 편집기에서 사용한다면, 모든 타입 검사와 자동완성 등 작성해야 하는 코드가 얼마나 적은지 보면서 FastAPI의 이점을 비로소 경험할 수 있습니다. -편집기에서 이렇게 사용한다면, 모든 타입 검사와 자동완성 등 작성해야 하는 코드가 얼마나 적은지 보면서 FastAPI의 장점을 실제로 확인할 수 있습니다. --- ## FastAPI 설치 -첫 번째 단계는 FastAPI 설치입니다. +첫 번째 단계는 FastAPI를 설치하는 것입니다. -자습시에는 모든 선택적인 의존성 및 기능을 사용하여 설치할 수 있습니다: +자습시에는 모든 선택적인 의존성 및 기능을 함께 설치하는 것을 추천합니다:
@@ -50,31 +51,34 @@ $ pip install "fastapi[all]"
-...코드를 실행하는 서버로 사용할 수 있는 `uvicorn` 역시 포함하고 있습니다. +...이는 코드를 실행하는 서버로 사용할 수 있는 `uvicorn` 또한 포함하고 있습니다. + +/// note | 참고 -!!! note "참고" - 부분적으로 설치할 수도 있습니다. +부분적으로 설치할 수도 있습니다. - 애플리케이션을 운영 환경에 배포하려는 경우 다음과 같이 합니다: +애플리케이션을 운영 환경에 배포하려는 경우 다음과 같이 합니다: - ``` - pip install fastapi - ``` +``` +pip install fastapi +``` - 추가로 서버 역할을 하는 `uvicorn`을 설치합니다: +추가로 서버 역할을 하는 `uvicorn`을 설치합니다: + +``` +pip install uvicorn +``` - ``` - pip install uvicorn - ``` +사용하려는 각 선택적인 의존성에 대해서도 동일합니다. - 사용하려는 각 선택적인 의존성에 대해서도 동일합니다. +/// ## 고급 사용자 안내서 이 **자습서 - 사용자 안내서** 다음에 읽을 수 있는 **고급 사용자 안내서**도 있습니다. -**고급 사용자 안내서**는 현재 문서를 기반으로 하고, 동일한 개념을 사용하며, 추가 기능들을 알려줍니다. +**고급 사용자 안내서**는 현재 문서를 기반으로 하고, 동일한 개념을 사용하며, 추가적인 기능들에 대해 설명합니다. -하지만 (지금 읽고 있는) **자습서 - 사용자 안내서**를 먼저 읽는게 좋습니다. +하지만 (지금 읽고 있는) **자습서 - 사용자 안내서**를 먼저 읽는 것을 권장합니다. -**자습서 - 사용자 안내서**만으로도 완전한 애플리케이션을 구축할 수 있으며, 필요에 따라 **고급 사용자 안내서**에서 제공하는 몇 가지 추가적인 기능을 사용하여 다양한 방식으로 확장할 수 있도록 설계되었습니다. +**자습서 - 사용자 안내서**만으로도 완전한 애플리케이션을 구축할 수 있도록 작성되었으며, 필요에 따라 **고급 사용자 안내서**의 추가적인 아이디어를 적용하여 다양한 방식으로 확장할 수 있습니다. diff --git a/docs/ko/docs/tutorial/metadata.md b/docs/ko/docs/tutorial/metadata.md new file mode 100644 index 000000000..a50dfa2e7 --- /dev/null +++ b/docs/ko/docs/tutorial/metadata.md @@ -0,0 +1,118 @@ +# 메타데이터 및 문서화 URL + +**FastAPI** 응용 프로그램에서 다양한 메타데이터 구성을 사용자 맞춤 설정할 수 있습니다. + +## API에 대한 메타데이터 + +OpenAPI 명세 및 자동화된 API 문서 UI에 사용되는 다음 필드를 설정할 수 있습니다: + +| 매개변수 | 타입 | 설명 | +|----------|------|-------| +| `title` | `str` | API의 제목입니다. | +| `summary` | `str` | API에 대한 짧은 요약입니다. OpenAPI 3.1.0, FastAPI 0.99.0부터 사용 가능 | +| `description` | `str` | API에 대한 짧은 설명입니다. 마크다운을 사용할 수 있습니다. | +| `version` | `string` | API의 버전입니다. OpenAPI의 버전이 아닌, 여러분의 애플리케이션의 버전을 나타냅니다. 예: `2.5.0` | +| `terms_of_service` | `str` | API 이용 약관의 URL입니다. 제공하는 경우 URL 형식이어야 합니다. | +| `contact` | `dict` | 노출된 API에 대한 연락처 정보입니다. 여러 필드를 포함할 수 있습니다.
contact 필드
매개변수타입설명
namestr연락처 인물/조직의 식별명입니다.
urlstr연락처 정보가 담긴 URL입니다. URL 형식이어야 합니다.
emailstr연락처 인물/조직의 이메일 주소입니다. 이메일 주소 형식이어야 합니다.
| +| `license_info` | `dict` | 노출된 API의 라이선스 정보입니다. 여러 필드를 포함할 수 있습니다.
license_info 필드
매개변수타입설명
namestr필수 (license_info가 설정된 경우). API에 사용된 라이선스 이름입니다.
identifierstrAPI에 대한 SPDX 라이선스 표현입니다. identifier 필드는 url 필드와 상호 배타적입니다. OpenAPI 3.1.0, FastAPI 0.99.0부터 사용 가능
urlstrAPI에 사용된 라이선스의 URL입니다. URL 형식이어야 합니다.
| + +다음과 같이 설정할 수 있습니다: + +{* ../../docs_src/metadata/tutorial001.py hl[3:16,19:32] *} + +/// tip + +`description` 필드에 마크다운을 사용할 수 있으며, 출력에서 렌더링됩니다. + +/// + +이 구성을 사용하면 문서 자동화(로 생성된) API 문서는 다음과 같이 보입니다: + + + +## 라이선스 식별자 + +OpenAPI 3.1.0 및 FastAPI 0.99.0부터 `license_info`에 `identifier`를 URL 대신 설정할 수 있습니다. + +예: + +{* ../../docs_src/metadata/tutorial001_1.py hl[31] *} + +## 태그에 대한 메타데이터 + +`openapi_tags` 매개변수를 사용하여 경로 작동을 그룹화하는 데 사용되는 태그에 추가 메타데이터를 추가할 수 있습니다. + +리스트는 각 태그에 대해 하나의 딕셔너리를 포함해야 합니다. + +각 딕셔너리에는 다음이 포함될 수 있습니다: + +* `name` (**필수**): `tags` 매개변수에서 *경로 작동*과 `APIRouter`에 사용된 태그 이름과 동일한 `str`입니다. +* `description`: 태그에 대한 간단한 설명을 담은 `str`입니다. 마크다운을 사용할 수 있으며 문서 UI에 표시됩니다. +* `externalDocs`: 외부 문서를 설명하는 `dict`이며: + * `description`: 외부 문서에 대한 간단한 설명을 담은 `str`입니다. + * `url` (**필수**): 외부 문서의 URL을 담은 `str`입니다. + +### 태그에 대한 메타데이터 생성 + +`users` 및 `items`에 대한 태그 예시와 함께 메타데이터를 생성하고 이를 `openapi_tags` 매개변수로 전달해 보겠습니다: + +{* ../../docs_src/metadata/tutorial004.py hl[3:16,18] *} + +설명 안에 마크다운을 사용할 수 있습니다. 예를 들어 "login"은 굵게(**login**) 표시되고, "fancy"는 기울임꼴(_fancy_)로 표시됩니다. + +/// tip + +사용 중인 모든 태그에 메타데이터를 추가할 필요는 없습니다. + +/// + +### 태그 사용 + +`tags` 매개변수를 *경로 작동* 및 `APIRouter`와 함께 사용하여 태그에 할당할 수 있습니다: + +{* ../../docs_src/metadata/tutorial004.py hl[21,26] *} + +/// info + +태그에 대한 자세한 내용은 [경로 작동 구성](path-operation-configuration.md#tags){.internal-link target=_blank}에서 읽어보세요. + +/// + +### 문서 확인 + +이제 문서를 확인하면 모든 추가 메타데이터가 표시됩니다: + + + +### 태그 순서 + +각 태그 메타데이터 딕셔너리의 순서는 문서 UI에 표시되는 순서를 정의합니다. + +예를 들어, 알파벳 순서상 `users`는 `items` 뒤에 오지만, 우리는 `users` 메타데이터를 리스트의 첫 번째 딕셔너리로 추가했기 때문에 먼저 표시됩니다. + +## OpenAPI URL + +OpenAPI 구조는 기본적으로 `/openapi.json`에서 제공됩니다. + +`openapi_url` 매개변수를 통해 이를 설정할 수 있습니다. + +예를 들어, 이를 `/api/v1/openapi.json`에 제공하도록 설정하려면: + +{* ../../docs_src/metadata/tutorial002.py hl[3] *} + +OpenAPI 구조를 완전히 비활성화하려면 `openapi_url=None`으로 설정할 수 있으며, 이를 사용하여 문서화 사용자 인터페이스도 비활성화됩니다. + +## 문서화 URL + +포함된 두 가지 문서화 사용자 인터페이스를 설정할 수 있습니다: + +* **Swagger UI**: `/docs`에서 제공됩니다. + * `docs_url` 매개변수로 URL을 설정할 수 있습니다. + * `docs_url=None`으로 설정하여 비활성화할 수 있습니다. +* **ReDoc**: `/redoc`에서 제공됩니다. + * `redoc_url` 매개변수로 URL을 설정할 수 있습니다. + * `redoc_url=None`으로 설정하여 비활성화할 수 있습니다. + +예를 들어, Swagger UI를 `/documentation`에서 제공하고 ReDoc을 비활성화하려면: + +{* ../../docs_src/metadata/tutorial003.py hl[3] *} diff --git a/docs/ko/docs/tutorial/middleware.md b/docs/ko/docs/tutorial/middleware.md new file mode 100644 index 000000000..3cd752a0e --- /dev/null +++ b/docs/ko/docs/tutorial/middleware.md @@ -0,0 +1,66 @@ +# 미들웨어 + +미들웨어를 **FastAPI** 응용 프로그램에 추가할 수 있습니다. + +"미들웨어"는 특정 *경로 작동*에 의해 처리되기 전, 모든 **요청**에 대해서 동작하는 함수입니다. 또한 모든 **응답**이 반환되기 전에도 동일하게 동작합니다. + +* 미들웨어는 응용 프로그램으로 오는 **요청**를 가져옵니다. +* **요청** 또는 다른 필요한 코드를 실행 시킬 수 있습니다. +* **요청**을 응용 프로그램의 *경로 작동*으로 전달하여 처리합니다. +* 애플리케이션의 *경로 작업*에서 생성한 **응답**를 받습니다. +* **응답** 또는 다른 필요한 코드를 실행시키는 동작을 할 수 있습니다. +* **응답**를 반환합니다. + +/// note | 기술 세부사항 + +만약 `yield`를 사용한 의존성을 가지고 있다면, 미들웨어가 실행되고 난 후에 exit이 실행됩니다. + +만약 (나중에 문서에서 다룰) 백그라운드 작업이 있다면, 모든 미들웨어가 실행되고 *난 후에* 실행됩니다. + +/// + +## 미들웨어 만들기 + +미들웨어를 작성하기 위해서 함수 상단에 `@app.middleware("http")` 데코레이터를 사용할 수 있습니다. + +미들웨어 함수는 다음 항목들을 받습니다: + +* `request`. +* `request`를 매개변수로 받는 `call_next` 함수. + * 이 함수는 `request`를 해당하는 *경로 작업*으로 전달합니다. + * 그런 다음, *경로 작업*에 의해 생성된 `response` 를 반환합니다. +* `response`를 반환하기 전에 추가로 `response`를 수정할 수 있습니다. + +{* ../../docs_src/middleware/tutorial001.py hl[8:9,11,14] *} + +/// tip | 팁 + +사용자 정의 헤더는 'X-' 접두사를 사용하여 추가할 수 있습니다. + +그러나 만약 클라이언트의 브라우저에서 볼 수 있는 사용자 정의 헤더를 가지고 있다면, 그것들을 CORS 설정([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank})에 Starlette CORS 문서에 명시된 `expose_headers` 매개변수를 이용하여 헤더들을 추가하여야합니다. + +/// + +/// note | 기술적 세부사항 + +`from starlette.requests import request`를 사용할 수도 있습니다. + +**FastAPI**는 개발자에게 편의를 위해 이를 제공합니다. 그러나 Starlette에서 직접 파생되었습니다. + +/// + +### `response`의 전과 후 + +*경로 작동*을 받기 전 `request`와 함께 작동할 수 있는 코드를 추가할 수 있습니다. + +그리고 `response` 또한 생성된 후 반환되기 전에 코드를 추가 할 수 있습니다. + +예를 들어, 요청을 수행하고 응답을 생성하는데 까지 걸린 시간 값을 가지고 있는 `X-Process-Time` 같은 사용자 정의 헤더를 추가할 수 있습니다. + +{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *} + +## 다른 미들웨어 + +미들웨어에 대한 더 많은 정보는 [숙련된 사용자 안내서: 향상된 미들웨어](../advanced/middleware.md){.internal-link target=\_blank}에서 확인할 수 있습니다. + +다음 부분에서 미들웨어와 함께 CORS를 어떻게 다루는지에 대해 확인할 것입니다. diff --git a/docs/ko/docs/tutorial/path-operation-configuration.md b/docs/ko/docs/tutorial/path-operation-configuration.md new file mode 100644 index 000000000..81914182a --- /dev/null +++ b/docs/ko/docs/tutorial/path-operation-configuration.md @@ -0,0 +1,97 @@ +# 경로 작동 설정 + +*경로 작동 데코레이터*를 설정하기 위해서 전달할수 있는 몇 가지 매개변수가 있습니다. + +/// warning | 경고 + +아래 매개변수들은 *경로 작동 함수*가 아닌 *경로 작동 데코레이터*에 직접 전달된다는 사실을 기억하십시오. + +/// + +## 응답 상태 코드 + +*경로 작동*의 응답에 사용될 (HTTP) `status_code`를 정의할수 있습니다. + +`404`와 같은 `int`형 코드를 직접 전달할수 있습니다. + +하지만 각 코드의 의미를 모른다면, `status`에 있는 단축 상수들을 사용할수 있습니다: + +{* ../../docs_src/path_operation_configuration/tutorial001.py hl[3,17] *} + +각 상태 코드들은 응답에 사용되며, OpenAPI 스키마에 추가됩니다. + +/// note | 기술적 세부사항 + +다음과 같이 임포트하셔도 좋습니다. `from starlette import status`. + +**FastAPI**는 개발자 여러분의 편의를 위해서 `starlette.status`와 동일한 `fastapi.status`를 제공합니다. 하지만 Starlette에서 직접 온 것입니다. + +/// + +## 태그 + +(보통 단일 `str`인) `str`로 구성된 `list`와 함께 매개변수 `tags`를 전달하여, `경로 작동`에 태그를 추가할 수 있습니다: + +{* ../../docs_src/path_operation_configuration/tutorial002.py hl[17,22,27] *} + +전달된 태그들은 OpenAPI의 스키마에 추가되며, 자동 문서 인터페이스에서 사용됩니다: + + + +## 요약과 기술 + +`summary`와 `description`을 추가할 수 있습니다: + +{* ../../docs_src/path_operation_configuration/tutorial003.py hl[20:21] *} + +## 독스트링으로 만든 기술 + +설명은 보통 길어지고 여러 줄에 걸쳐있기 때문에, *경로 작동* 기술을 함수 독스트링 에 선언할 수 있습니다, 이를 **FastAPI**가 독스트링으로부터 읽습니다. + +마크다운 문법으로 독스트링을 작성할 수 있습니다, 작성된 마크다운 형식의 독스트링은 (마크다운의 들여쓰기를 고려하여) 올바르게 화면에 출력됩니다. + +{* ../../docs_src/path_operation_configuration/tutorial004.py hl[19:27] *} + +이는 대화형 문서에서 사용됩니다: + + + +## 응답 기술 + +`response_description` 매개변수로 응답에 관한 설명을 명시할 수 있습니다: + +{* ../../docs_src/path_operation_configuration/tutorial005.py hl[21] *} + +/// info | 정보 + +`response_description`은 구체적으로 응답을 지칭하며, `description`은 일반적인 *경로 작동*을 지칭합니다. + +/// + +/// check | 확인 + +OpenAPI는 각 *경로 작동*이 응답에 관한 설명을 요구할 것을 명시합니다. + +따라서, 응답에 관한 설명이 없을경우, **FastAPI**가 자동으로 "성공 응답" 중 하나를 생성합니다. + +/// + + + +## 단일 *경로 작동* 지원중단 + +단일 *경로 작동*을 없애지 않고 지원중단을 해야한다면, `deprecated` 매개변수를 전달하면 됩니다. + +{* ../../docs_src/path_operation_configuration/tutorial006.py hl[16] *} + +대화형 문서에 지원중단이라고 표시됩니다. + + + +지원중단된 경우와 지원중단 되지 않은 경우에 대한 *경로 작동*이 어떻게 보이는 지 확인하십시오. + + + +## 정리 + +*경로 작동 데코레이터*에 매개변수(들)를 전달함으로 *경로 작동*을 설정하고 메타데이터를 추가할수 있습니다. diff --git a/docs/ko/docs/tutorial/path-params-numeric-validations.md b/docs/ko/docs/tutorial/path-params-numeric-validations.md index cadf543fc..f21c9290e 100644 --- a/docs/ko/docs/tutorial/path-params-numeric-validations.md +++ b/docs/ko/docs/tutorial/path-params-numeric-validations.md @@ -6,9 +6,7 @@ 먼저 `fastapi`에서 `Path`를 임포트합니다: -```Python hl_lines="3" -{!../../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial001.py hl[3] *} ## 메타데이터 선언 @@ -16,16 +14,17 @@ 예를 들어, `title` 메타데이터 값을 경로 매개변수 `item_id`에 선언하려면 다음과 같이 입력할 수 있습니다: -```Python hl_lines="10" -{!../../../docs_src/path_params_numeric_validations/tutorial001.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial001.py hl[10] *} -!!! note "참고" - 경로 매개변수는 경로의 일부여야 하므로 언제나 필수적입니다. +/// note | 참고 - 즉, `...`로 선언해서 필수임을 나타내는게 좋습니다. +경로 매개변수는 경로의 일부여야 하므로 언제나 필수적입니다. - 그럼에도 `None`으로 선언하거나 기본값을 지정할지라도 아무 영향을 끼치지 않으며 언제나 필수입니다. +즉, `...`로 선언해서 필수임을 나타내는게 좋습니다. + +그럼에도 `None`으로 선언하거나 기본값을 지정할지라도 아무 영향을 끼치지 않으며 언제나 필수입니다. + +/// ## 필요한 경우 매개변수 정렬하기 @@ -43,9 +42,7 @@ 따라서 함수를 다음과 같이 선언 할 수 있습니다: -```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial002.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial002.py hl[7] *} ## 필요한 경우 매개변수 정렬하기, 트릭 @@ -55,9 +52,7 @@ 파이썬은 `*`으로 아무런 행동도 하지 않지만, 따르는 매개변수들은 kwargs로도 알려진 키워드 인자(키-값 쌍)여야 함을 인지합니다. 기본값을 가지고 있지 않더라도 그렇습니다. -```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial003.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *} ## 숫자 검증: 크거나 같음 @@ -65,9 +60,7 @@ 여기서 `ge=1`인 경우, `item_id`는 `1`보다 "크거나(`g`reater) 같은(`e`qual)" 정수형 숫자여야 합니다. -```Python hl_lines="8" -{!../../../docs_src/path_params_numeric_validations/tutorial004.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial004.py hl[8] *} ## 숫자 검증: 크거나 같음 및 작거나 같음 @@ -76,9 +69,7 @@ * `gt`: 크거나(`g`reater `t`han) * `le`: 작거나 같은(`l`ess than or `e`qual) -```Python hl_lines="9" -{!../../../docs_src/path_params_numeric_validations/tutorial005.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial005.py hl[9] *} ## 숫자 검증: 부동소수, 크거나 및 작거나 @@ -90,9 +81,7 @@ lt 역시 마찬가지입니다. -```Python hl_lines="11" -{!../../../docs_src/path_params_numeric_validations/tutorial006.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial006.py hl[11] *} ## 요약 @@ -105,18 +94,24 @@ * `lt`: 작거나(`l`ess `t`han) * `le`: 작거나 같은(`l`ess than or `e`qual) -!!! info "정보" - `Query`, `Path`, 그리고 나중에게 보게될 것들은 (여러분이 사용할 필요가 없는) 공통 `Param` 클래스의 서브 클래스입니다. +/// info | 정보 + +`Query`, `Path`, 그리고 나중에게 보게될 것들은 (여러분이 사용할 필요가 없는) 공통 `Param` 클래스의 서브 클래스입니다. + +그리고 이들 모두는 여태까지 본 추가 검증과 메타데이터의 동일한 모든 매개변수를 공유합니다. + +/// + +/// note | 기술 세부사항 - 그리고 이들 모두는 여태까지 본 추가 검증과 메타데이터의 동일한 모든 매개변수를 공유합니다. +`fastapi`에서 `Query`, `Path` 등을 임포트 할 때, 이것들은 실제로 함수입니다. -!!! note "기술 세부사항" - `fastapi`에서 `Query`, `Path` 등을 임포트 할 때, 이것들은 실제로 함수입니다. +호출되면 동일한 이름의 클래스의 인스턴스를 반환합니다. - 호출되면 동일한 이름의 클래스의 인스턴스를 반환합니다. +즉, 함수인 `Query`를 임포트한 겁니다. 그리고 호출하면 `Query`라는 이름을 가진 클래스의 인스턴스를 반환합니다. - 즉, 함수인 `Query`를 임포트한 겁니다. 그리고 호출하면 `Query`라는 이름을 가진 클래스의 인스턴스를 반환합니다. +편집기에서 타입에 대한 오류를 표시하지 않도록 하기 위해 (클래스를 직접 사용하는 대신) 이러한 함수들이 있습니다. - 편집기에서 타입에 대한 오류를 표시하지 않도록 하기 위해 (클래스를 직접 사용하는 대신) 이러한 함수들이 있습니다. +이렇게 하면 오류를 무시하기 위한 사용자 설정을 추가하지 않고도 일반 편집기와 코딩 도구를 사용할 수 있습니다. - 이렇게 하면 오류를 무시하기 위한 사용자 설정을 추가하지 않고도 일반 편집기와 코딩 도구를 사용할 수 있습니다. +/// diff --git a/docs/ko/docs/tutorial/path-params.md b/docs/ko/docs/tutorial/path-params.md index 5cf397e7a..b72787e0b 100644 --- a/docs/ko/docs/tutorial/path-params.md +++ b/docs/ko/docs/tutorial/path-params.md @@ -1,10 +1,8 @@ # 경로 매개변수 -파이썬 포맷 문자열이 사용하는 동일한 문법으로 "매개변수" 또는 "변수"를 경로에 선언할 수 있습니다: +파이썬의 포맷 문자열 리터럴에서 사용되는 문법을 이용하여 경로 "매개변수" 또는 "변수"를 선언할 수 있습니다: -```Python hl_lines="6-7" -{!../../../docs_src/path_params/tutorial001.py!} -``` +{* ../../docs_src/path_params/tutorial001.py hl[6:7] *} 경로 매개변수 `item_id`의 값은 함수의 `item_id` 인자로 전달됩니다. @@ -18,14 +16,15 @@ 파이썬 표준 타입 어노테이션을 사용하여 함수에 있는 경로 매개변수의 타입을 선언할 수 있습니다: -```Python hl_lines="7" -{!../../../docs_src/path_params/tutorial002.py!} -``` +{* ../../docs_src/path_params/tutorial002.py hl[7] *} + +위의 예시에서, `item_id`는 `int`로 선언되었습니다. + +/// check | 확인 -지금과 같은 경우, `item_id`는 `int`로 선언 되었습니다. +이 기능은 함수 내에서 오류 검사, 자동완성 등의 편집기 기능을 활용할 수 있게 해줍니다. -!!! check "확인" - 이 기능은 함수 내에서 오류 검사, 자동완성 등을 편집기를 지원합니다 +/// ## 데이터 변환 @@ -35,14 +34,17 @@ {"item_id":3} ``` -!!! check "확인" - 함수가 받은(반환도 하는) 값은 문자열 `"3"`이 아니라 파이썬 `int` 형인 `3`입니다. +/// check | 확인 - 즉, 타입 선언을 하면 **FastAPI**는 자동으로 요청을 "파싱"합니다. +함수가 받은(반환도 하는) 값은 문자열 `"3"`이 아니라 파이썬 `int` 형인 `3`입니다. + +즉, 타입 선언을 하면 **FastAPI**는 자동으로 요청을 "파싱"합니다. + +/// ## 데이터 검증 -하지만 브라우저에서 http://127.0.0.1:8000/items/foo로 이동하면, 멋진 HTTP 오류를 볼 수 있습니다: +하지만 브라우저에서 http://127.0.0.1:8000/items/foo로 이동하면, HTTP 오류가 잘 뜨는 것을 확인할 수 있습니다: ```JSON { @@ -61,14 +63,17 @@ 경로 매개변수 `item_id`는 `int`가 아닌 `"foo"` 값이기 때문입니다. -`int` 대신 `float`을 전달하면 동일한 오류가 나타납니다: http://127.0.0.1:8000/items/4.2 +`int`가 아닌 `float`을 전달하는 경우에도 동일한 오류가 나타납니다: http://127.0.0.1:8000/items/4.2 + +/// check | 확인 -!!! check "확인" - 즉, 파이썬 타입 선언을 하면 **FastAPI**는 데이터 검증을 합니다. +즉, 파이썬 타입 선언을 하면 **FastAPI**는 데이터 검증을 합니다. - 오류는 검증을 통과하지 못한 지점도 정확하게 명시합니다. +오류에는 정확히 어느 지점에서 검증을 통과하지 못했는지 명시됩니다. - 이는 API와 상호 작용하는 코드를 개발하고 디버깅하는 데 매우 유용합니다. +이는 API와 상호 작용하는 코드를 개발하고 디버깅하는 데 매우 유용합니다. + +/// ## 문서화 @@ -76,12 +81,15 @@ -!!! check "확인" - 다시 한번, 그저 파이썬 타입 선언을 하기만 하면 **FastAPI**는 자동 대화식 API 문서(Swagger UI 통합)를 제공합니다. +/// check | 확인 + +그저 파이썬 타입 선언을 하기만 하면 **FastAPI**는 자동 대화형 API 문서(Swagger UI)를 제공합니다. + +경로 매개변수가 정수형으로 명시된 것을 확인할 수 있습니다. - 경로 매개변수는 정수형으로 선언됐음을 주목하세요. +/// -## 표준 기반의 이점, 대체 문서화 +## 표준 기반의 이점, 대체 문서 그리고 생성된 스키마는 OpenAPI 표준에서 나온 것이기 때문에 호환되는 도구가 많이 있습니다. @@ -89,65 +97,65 @@ -이와 마찬가지로 호환되는 도구가 많이 있습니다. 다양한 언어에 대한 코드 생성 도구를 포함합니다. +이와 마찬가지로 다양한 언어에 대한 코드 생성 도구를 포함하여 여러 호환되는 도구가 있습니다. ## Pydantic -모든 데이터 검증은 Pydantic에 의해 내부적으로 수행되므로 이로 인한 모든 이점을 얻을 수 있습니다. 여러분은 관리를 잘 받고 있음을 느낄 수 있습니다. +모든 데이터 검증은 Pydantic에 의해 내부적으로 수행되므로 이로 인한 이점을 모두 얻을 수 있습니다. 여러분은 관리를 잘 받고 있음을 느낄 수 있습니다. -`str`, `float`, `bool`과 다른 복잡한 데이터 타입 선언을 할 수 있습니다. +`str`, `float`, `bool`, 그리고 다른 여러 복잡한 데이터 타입 선언을 할 수 있습니다. -이 중 몇 가지는 자습서의 다음 장에서 살펴봅니다. +이 중 몇 가지는 자습서의 다음 장에 설명되어 있습니다. ## 순서 문제 -*경로 동작*을 만들때 고정 경로를 갖고 있는 상황들을 맞닦뜨릴 수 있습니다. +*경로 작동*을 만들때 고정 경로를 갖고 있는 상황들을 맞닥뜨릴 수 있습니다. `/users/me`처럼, 현재 사용자의 데이터를 가져온다고 합시다. 사용자 ID를 이용해 특정 사용자의 정보를 가져오는 경로 `/users/{user_id}`도 있습니다. -*경로 동작*은 순차적으로 평가되기 때문에 `/users/{user_id}` 이전에 `/users/me`를 먼저 선언해야 합니다: +*경로 작동*은 순차적으로 실행되기 때문에 `/users/{user_id}` 이전에 `/users/me`를 먼저 선언해야 합니다: -```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003.py!} -``` +{* ../../docs_src/path_params/tutorial003.py hl[6,11] *} -그렇지 않으면 `/users/{user_id}`는 매개변수 `user_id`의 값을 `"me"`라고 "생각하여" `/users/me`도 연결합니다. +그렇지 않으면 `/users/{user_id}`는 `/users/me` 요청 또한 매개변수 `user_id`의 값이 `"me"`인 것으로 "생각하게" 됩니다. ## 사전정의 값 -만약 *경로 매개변수*를 받는 *경로 동작*이 있지만, 유효하고 미리 정의할 수 있는 *경로 매개변수* 값을 원한다면 파이썬 표준 `Enum`을 사용할 수 있습니다. +만약 *경로 매개변수*를 받는 *경로 작동*이 있지만, *경로 매개변수*로 가능한 값들을 미리 정의하고 싶다면 파이썬 표준 `Enum`을 사용할 수 있습니다. ### `Enum` 클래스 생성 `Enum`을 임포트하고 `str`과 `Enum`을 상속하는 서브 클래스를 만듭니다. -`str`을 상속함으로써 API 문서는 값이 `string` 형이어야 하는 것을 알게 되고 제대로 렌더링 할 수 있게 됩니다. +`str`을 상속함으로써 API 문서는 값이 `string` 형이어야 하는 것을 알게 되고 이는 문서에 제대로 표시됩니다. -고정값으로 사용할 수 있는 유효한 클래스 어트리뷰트를 만듭니다: +가능한 값들에 해당하는 고정된 값의 클래스 어트리뷰트들을 만듭니다: -```Python hl_lines="1 6-9" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *} + +/// info | 정보 -!!! info "정보" - 열거형(또는 enums)은 파이썬 버전 3.4 이후로 사용가능합니다. +열거형(또는 enums)은 파이썬 버전 3.4 이후로 사용 가능합니다. -!!! tip "팁" - 혹시 헷갈린다면, "AlexNet", "ResNet", 그리고 "LeNet"은 그저 기계 학습 모델들의 이름입니다. +/// + +/// tip | 팁 + +혹시 궁금하다면, "AlexNet", "ResNet", 그리고 "LeNet"은 그저 기계 학습 모델들의 이름입니다. + +/// ### *경로 매개변수* 선언 생성한 열거형 클래스(`ModelName`)를 사용하는 타입 어노테이션으로 *경로 매개변수*를 만듭니다: -```Python hl_lines="16" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[16] *} ### 문서 확인 -*경로 매개변수*에 사용할 수 있는 값은 미리 정의되어 있으므로 대화형 문서에서 멋지게 표시됩니다: +*경로 매개변수*에 사용할 수 있는 값은 미리 정의되어 있으므로 대화형 문서에서 잘 표시됩니다: @@ -157,32 +165,29 @@ #### *열거형 멤버* 비교 -열거체 `ModelName`의 *열거형 멤버*를 비교할 수 있습니다: +열거형 `ModelName`의 *열거형 멤버*를 비교할 수 있습니다: -```Python hl_lines="17" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[17] *} #### *열거형 값* 가져오기 -`model_name.value` 또는 일반적으로 `your_enum_member.value`를 이용하여 실제값(지금의 경우 `str`)을 가져올 수 있습니다: +`model_name.value` 또는 일반적으로 `your_enum_member.value`를 이용하여 실제 값(위 예시의 경우 `str`)을 가져올 수 있습니다: -```Python hl_lines="20" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[20] *} -!!! tip "팁" - `ModelName.lenet.value`로도 값 `"lenet"`에 접근할 수 있습니다. +/// tip | 팁 + +`ModelName.lenet.value`로도 값 `"lenet"`에 접근할 수 있습니다. + +/// #### *열거형 멤버* 반환 -*경로 동작*에서 중첩 JSON 본문(예: `dict`) 역시 *열거형 멤버*를 반환할 수 있습니다. +*경로 작동*에서 *열거형 멤버*를 반환할 수 있습니다. 이는 중첩 JSON 본문(예: `dict`)내의 값으로도 가능합니다. 클라이언트에 반환하기 전에 해당 값(이 경우 문자열)으로 변환됩니다: -```Python hl_lines="18 21 23" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *} 클라이언트는 아래의 JSON 응답을 얻습니다: @@ -195,50 +200,51 @@ ## 경로를 포함하는 경로 매개변수 -`/files/{file_path}`가 있는 *경로 동작*이 있다고 해봅시다. +경로를 포함하는 *경로 작동* `/files/{file_path}`이 있다고 해봅시다. -그런데 여러분은 `home/johndoe/myfile.txt`처럼 *path*에 들어있는 `file_path` 자체가 필요합니다. +그런데 이 경우 `file_path` 자체가 `home/johndoe/myfile.txt`와 같은 경로를 포함해야 합니다. -따라서 해당 파일의 URL은 다음처럼 됩니다: `/files/home/johndoe/myfile.txt`. +이때 해당 파일의 URL은 다음처럼 됩니다: `/files/home/johndoe/myfile.txt`. ### OpenAPI 지원 테스트와 정의가 어려운 시나리오로 이어질 수 있으므로 OpenAPI는 *경로*를 포함하는 *경로 매개변수*를 내부에 선언하는 방법을 지원하지 않습니다. -그럼에도 Starlette의 내부 도구중 하나를 사용하여 **FastAPI**에서는 할 수 있습니다. +그럼에도 Starlette의 내부 도구중 하나를 사용하여 **FastAPI**에서는 이가 가능합니다. -매개변수에 경로가 포함되어야 한다는 문서를 추가하지 않아도 문서는 계속 작동합니다. +문서에 매개변수에 경로가 포함되어야 한다는 정보가 명시되지는 않지만 여전히 작동합니다. ### 경로 변환기 -Starlette에서 직접 옵션을 사용하면 다음과 같은 URL을 사용하여 *path*를 포함하는 *경로 매개변수*를 선언 할 수 있습니다: +Starlette의 옵션을 직접 이용하여 다음과 같은 URL을 사용함으로써 *path*를 포함하는 *경로 매개변수*를 선언할 수 있습니다: ``` /files/{file_path:path} ``` -이러한 경우 매개변수의 이름은 `file_path`이고 마지막 부분 `:path`는 매개변수가 *경로*와 일치해야함을 알려줍니다. +이러한 경우 매개변수의 이름은 `file_path`이며, 마지막 부분 `:path`는 매개변수가 *경로*와 일치해야 함을 명시합니다. -그러므로 다음과 같이 사용할 수 있습니다: +따라서 다음과 같이 사용할 수 있습니다: -```Python hl_lines="6" -{!../../../docs_src/path_params/tutorial004.py!} -``` +{* ../../docs_src/path_params/tutorial004.py hl[6] *} + +/// tip | 팁 + +매개변수가 가져야 하는 값이 `/home/johndoe/myfile.txt`와 같이 슬래시로 시작(`/`)해야 할 수 있습니다. -!!! tip "팁" - 매개변수가 `/home/johndoe/myfile.txt`를 갖고 있어 슬래시로 시작(`/`)해야 할 수 있습니다. +이 경우 URL은: `/files//home/johndoe/myfile.txt`이며 `files`과 `home` 사이에 이중 슬래시(`//`)가 생깁니다. - 이 경우 URL은: `/files//home/johndoe/myfile.txt`이며 `files`과 `home` 사이에 이중 슬래시(`//`)가 생깁니다. +/// ## 요약 -**FastAPI**과 함께라면 짧고 직관적인 표준 파이썬 타입 선언을 사용하여 다음을 얻을 수 있습니다: +**FastAPI**를 이용하면 짧고 직관적인 표준 파이썬 타입 선언을 사용하여 다음을 얻을 수 있습니다: * 편집기 지원: 오류 검사, 자동완성 등 * 데이터 "파싱" * 데이터 검증 * API 주석(Annotation)과 자동 문서 -위 사항들을 그저 한번에 선언하면 됩니다. +단 한번의 선언만으로 위 사항들을 모두 선언할 수 있습니다. -이는 (원래 성능과는 별개로) 대체 프레임워크와 비교했을 때 **FastAPI**의 주요 가시적 장점일 것입니다. +이는 대체 프레임워크와 비교했을 때 (엄청나게 빠른 성능 외에도) **FastAPI**의 주요한 장점일 것입니다. diff --git a/docs/ko/docs/tutorial/query-param-models.md b/docs/ko/docs/tutorial/query-param-models.md new file mode 100644 index 000000000..2ca65a331 --- /dev/null +++ b/docs/ko/docs/tutorial/query-param-models.md @@ -0,0 +1,68 @@ +# 쿼리 매개변수 모델 + +연관된 쿼리 **매개변수** 그룹이 있다면 **Pydantic 모델** 을 사용해 선언할 수 있습니다. + +이렇게 하면 **여러 곳**에서 **모델을 재사용**할 수 있을 뿐만 아니라, 매개변수에 대한 검증 및 메타데이터도 한 번에 선언할 수 있습니다. 😎 + +/// note | 참고 + +이 기능은 FastAPI 버전 `0.115.0`부터 제공됩니다. 🤓 + +/// + +## 쿼리 매개변수와 Pydantic 모델 + +필요한 **쿼리 매개변수**를 **Pydantic 모델** 안에 선언한 다음, 모델을 `Query`로 선언합니다. + +{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *} + +**FastAPI**는 요청의 **쿼리 매개변수**에서 **각 필드**의 데이터를 **추출**해 정의한 Pydantic 모델로 제공합니다. + +## 문서 확인하기 + +`/docs` 경로의 API 문서에서 매개변수를 확인할 수 있습니다. + +
+ +
+ +## 추가 쿼리 매개변수 금지 + +몇몇의 특이한 경우에 (흔치 않지만), 허용할 쿼리 매개변수를 **제한**해야할 수 있습니다. + +Pydantic 모델 설정에서 `extra` 필드를 `forbid` 로 설정할 수 있습니다. + +{* ../../docs_src/query_param_models/tutorial002_an_py310.py hl[10] *} + +만약 클라이언트가 쿼리 매개변수로 **추가적인** 데이터를 보내려고 하면, 클라이언트는 **에러** 응답을 받게 됩니다. + +예를 들어, 아래와 같이 만약 클라이언트가 `tool` 쿼리 매개변수에 `plumbus` 라는 값을 추가해서 보내려고 하면, + +```http +https://example.com/items/?limit=10&tool=plumbus +``` + +클라이언트는 쿼리 매개변수 `tool` 이 허용되지 않는다는 **에러** 응답을 받게 됩니다. + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["query", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus" + } + ] +} +``` + +## 요약 + +**FastAPI** 에서 **쿼리 매개변수** 를 선언할 때 **Pydantic 모델** 을 사용할 수 있습니다. 😎 + +/// tip | 팁 + +스포일러 경고: Pydantic 모델을 쿠키와 헤더에도 적용할 수 있습니다. 이에 대해서는 이후 튜토리얼에서 다룰 예정입니다. 🤫 + +/// diff --git a/docs/ko/docs/tutorial/query-params-str-validations.md b/docs/ko/docs/tutorial/query-params-str-validations.md new file mode 100644 index 000000000..f2ca453ac --- /dev/null +++ b/docs/ko/docs/tutorial/query-params-str-validations.md @@ -0,0 +1,296 @@ +# 쿼리 매개변수와 문자열 검증 + +**FastAPI**를 사용하면 매개변수에 대한 추가 정보 및 검증을 선언할 수 있습니다. + +이 응용 프로그램을 예로 들어보겠습니다: + +{* ../../docs_src/query_params_str_validations/tutorial001.py hl[9] *} + +쿼리 매개변수 `q`는 `Optional[str]` 자료형입니다. 즉, `str` 자료형이지만 `None` 역시 될 수 있음을 뜻하고, 실제로 기본값은 `None`이기 때문에 FastAPI는 이 매개변수가 필수가 아니라는 것을 압니다. + +/// note | 참고 + +FastAPI는 `q`의 기본값이 `= None`이기 때문에 필수가 아님을 압니다. + +`Optional[str]`에 있는 `Optional`은 FastAPI가 사용하는게 아니지만, 편집기에게 더 나은 지원과 오류 탐지를 제공하게 해줍니다. + +/// + +## 추가 검증 + +`q`가 선택적이지만 값이 주어질 때마다 **값이 50 글자를 초과하지 않게** 강제하려 합니다. + +### `Query` 임포트 + +이를 위해 먼저 `fastapi`에서 `Query`를 임포트합니다: + +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[3] *} + +## 기본값으로 `Query` 사용 + +이제 `Query`를 매개변수의 기본값으로 사용하여 `max_length` 매개변수를 50으로 설정합니다: + +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[9] *} + +기본값 `None`을 `Query(None)`으로 바꿔야 하므로, `Query`의 첫 번째 매개변수는 기본값을 정의하는 것과 같은 목적으로 사용됩니다. + +그러므로: + +```Python +q: Optional[str] = Query(None) +``` + +...위 코드는 아래와 동일하게 매개변수를 선택적으로 만듭니다: + +```Python +q: Optional[str] = None +``` + +하지만 명시적으로 쿼리 매개변수를 선언합니다. + +/// info | 정보 + +FastAPI는 다음 부분에 관심이 있습니다: + +```Python += None +``` + +또는: + +```Python += Query(None) +``` + +그리고 `None`을 사용하여 쿼라 매개변수가 필수적이지 않다는 것을 파악합니다. + +`Optional` 부분은 편집기에게 더 나은 지원을 제공하기 위해서만 사용됩니다. + +/// + +또한 `Query`로 더 많은 매개변수를 전달할 수 있습니다. 지금의 경우 문자열에 적용되는 `max_length` 매개변수입니다: + +```Python +q: str = Query(None, max_length=50) +``` + +이는 데이터를 검증할 것이고, 데이터가 유효하지 않다면 명백한 오류를 보여주며, OpenAPI 스키마 *경로 작동*에 매개변수를 문서화 합니다. + +## 검증 추가 + +매개변수 `min_length` 또한 추가할 수 있습니다: + +{* ../../docs_src/query_params_str_validations/tutorial003.py hl[9] *} + +## 정규식 추가 + +매개변수와 일치해야 하는 정규표현식을 정의할 수 있습니다: + +{* ../../docs_src/query_params_str_validations/tutorial004.py hl[10] *} + +이 특정 정규표현식은 전달 받은 매개변수 값을 검사합니다: + +* `^`: 이전에 문자가 없고 뒤따르는 문자로 시작합니다. +* `fixedquery`: 정확히 `fixedquery` 값을 갖습니다. +* `$`: 여기서 끝나고 `fixedquery` 이후로 아무 문자도 갖지 않습니다. + +**"정규표현식"** 개념에 대해 상실감을 느꼈다면 걱정하지 않아도 됩니다. 많은 사람에게 어려운 주제입니다. 아직은 정규표현식 없이도 많은 작업들을 할 수 있습니다. + +하지만 언제든지 가서 배울수 있고, **FastAPI**에서 직접 사용할 수 있다는 사실을 알고 있어야 합니다. + +## 기본값 + +기본값으로 사용하는 첫 번째 인자로 `None`을 전달하듯이, 다른 값을 전달할 수 있습니다. + +`min_length`가 `3`이고, 기본값이 `"fixedquery"`인 쿼리 매개변수 `q`를 선언해봅시다: + +{* ../../docs_src/query_params_str_validations/tutorial005.py hl[7] *} + +/// note | 참고 + +기본값을 갖는 것만으로 매개변수는 선택적이 됩니다. + +/// + +## 필수로 만들기 + +더 많은 검증이나 메타데이터를 선언할 필요가 없는 경우, 다음과 같이 기본값을 선언하지 않고 쿼리 매개변수 `q`를 필수로 만들 수 있습니다: + +```Python +q: str +``` + +아래 대신: + +```Python +q: Optional[str] = None +``` + +그러나 이제 다음과 같이 `Query`로 선언합니다: + +```Python +q: Optional[str] = Query(None, min_length=3) +``` + +그래서 `Query`를 필수값으로 만들어야 할 때면, 첫 번째 인자로 `...`를 사용할 수 있습니다: + +{* ../../docs_src/query_params_str_validations/tutorial006.py hl[7] *} + +/// info | 정보 + +이전에 `...`를 본적이 없다면: 특별한 단일값으로, 파이썬의 일부이며 "Ellipsis"라 부릅니다. + +/// + +이렇게 하면 **FastAPI**가 이 매개변수는 필수임을 알 수 있습니다. + +## 쿼리 매개변수 리스트 / 다중값 + +쿼리 매개변수를 `Query`와 함께 명시적으로 선언할 때, 값들의 리스트나 다른 방법으로 여러 값을 받도록 선언 할 수도 있습니다. + +예를 들어, URL에서 여러번 나오는 `q` 쿼리 매개변수를 선언하려면 다음과 같이 작성할 수 있습니다: + +{* ../../docs_src/query_params_str_validations/tutorial011.py hl[9] *} + +아래와 같은 URL을 사용합니다: + +``` +http://localhost:8000/items/?q=foo&q=bar +``` + +여러 `q` *쿼리 매개변수* 값들을 (`foo` 및 `bar`) 파이썬 `list`로 *경로 작동 함수* 내 *함수 매개변수* `q`로 전달 받습니다. + +따라서 해당 URL에 대한 응답은 다음과 같습니다: + +```JSON +{ + "q": [ + "foo", + "bar" + ] +} +``` + +/// tip | 팁 + +위의 예와 같이 `list` 자료형으로 쿼리 매개변수를 선언하려면 `Query`를 명시적으로 사용해야 합니다. 그렇지 않으면 요청 본문으로 해석됩니다. + +/// + +대화형 API 문서는 여러 값을 허용하도록 수정 됩니다: + + + +### 쿼리 매개변수 리스트 / 기본값을 사용하는 다중값 + +그리고 제공된 값이 없으면 기본 `list` 값을 정의할 수도 있습니다: + +{* ../../docs_src/query_params_str_validations/tutorial012.py hl[9] *} + +아래로 이동한다면: + +``` +http://localhost:8000/items/ +``` + +`q`의 기본값은: `["foo", "bar"]`이며 응답은 다음이 됩니다: + +```JSON +{ + "q": [ + "foo", + "bar" + ] +} +``` + +#### `list` 사용하기 + +`List[str]` 대신 `list`를 직접 사용할 수도 있습니다: + +{* ../../docs_src/query_params_str_validations/tutorial013.py hl[7] *} + +/// note | 참고 + +이 경우 FastAPI는 리스트의 내용을 검사하지 않음을 명심하기 바랍니다. + +예를 들어, `List[int]`는 리스트 내용이 정수인지 검사(및 문서화)합니다. 하지만 `list` 단독일 경우는 아닙니다. + +/// + +## 더 많은 메타데이터 선언 + +매개변수에 대한 정보를 추가할 수 있습니다. + +해당 정보는 생성된 OpenAPI에 포함되고 문서 사용자 인터페이스 및 외부 도구에서 사용됩니다. + +/// note | 참고 + +도구에 따라 OpenAPI 지원 수준이 다를 수 있음을 명심하기 바랍니다. + +일부는 아직 선언된 추가 정보를 모두 표시하지 않을 수 있지만, 대부분의 경우 누락된 기능은 이미 개발 계획이 있습니다. + +/// + +`title`을 추가할 수 있습니다: + +{* ../../docs_src/query_params_str_validations/tutorial007.py hl[10] *} + +그리고 `description`도 추가할 수 있습니다: + +{* ../../docs_src/query_params_str_validations/tutorial008.py hl[13] *} + +## 별칭 매개변수 + +매개변수가 `item-query`이길 원한다고 가정해 봅시다. + +마치 다음과 같습니다: + +``` +http://127.0.0.1:8000/items/?item-query=foobaritems +``` + +그러나 `item-query`은 유효한 파이썬 변수 이름이 아닙니다. + +가장 가까운 것은 `item_query`일 겁니다. + +하지만 정확히`item-query`이길 원합니다... + +이럴 경우 `alias`를 선언할 수 있으며, 해당 별칭은 매개변수 값을 찾는 데 사용됩니다: + +{* ../../docs_src/query_params_str_validations/tutorial009.py hl[9] *} + +## 매개변수 사용하지 않게 하기 + +이제는 더이상 이 매개변수를 마음에 들어하지 않는다고 가정해 봅시다. + +이 매개변수를 사용하는 클라이언트가 있기 때문에 한동안은 남겨둬야 하지만, 사용되지 않는다(deprecated)고 확실하게 문서에서 보여주고 싶습니다. + +그렇다면 `deprecated=True` 매개변수를 `Query`로 전달합니다: + +{* ../../docs_src/query_params_str_validations/tutorial010.py hl[18] *} + +문서가 아래와 같이 보일겁니다: + + + +## 요약 + +매개변수에 검증과 메타데이터를 추가 선언할 수 있습니다. + +제네릭 검증과 메타데이터: + +* `alias` +* `title` +* `description` +* `deprecated` + +특정 문자열 검증: + +* `min_length` +* `max_length` +* `regex` + +예제에서 `str` 값의 검증을 어떻게 추가하는지 살펴보았습니다. + +숫자와 같은 다른 자료형에 대한 검증을 어떻게 선언하는지 확인하려면 다음 장을 확인하기 바랍니다. diff --git a/docs/ko/docs/tutorial/query-params.md b/docs/ko/docs/tutorial/query-params.md index bb631e6ff..d5b9837c4 100644 --- a/docs/ko/docs/tutorial/query-params.md +++ b/docs/ko/docs/tutorial/query-params.md @@ -1,14 +1,12 @@ # 쿼리 매개변수 -경로 매개변수의 일부가 아닌 다른 함수 매개변수를 선언할 때, "쿼리" 매개변수로 자동 해석합니다. +경로 매개변수의 일부가 아닌 다른 함수 매개변수를 선언하면 "쿼리" 매개변수로 자동 해석합니다. -```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial001.py!} -``` +{* ../../docs_src/query_params/tutorial001.py hl[9] *} 쿼리는 URL에서 `?` 후에 나오고 `&`으로 구분되는 키-값 쌍의 집합입니다. -예를 들어, URL에서: +예를 들어, 아래 URL에서: ``` http://127.0.0.1:8000/items/?skip=0&limit=10 @@ -21,7 +19,7 @@ http://127.0.0.1:8000/items/?skip=0&limit=10 URL의 일부이므로 "자연스럽게" 문자열입니다. -하지만 파이썬 타입과 함께 선언할 경우(위 예에서 `int`), 해당 타입으로 변환되고 이에 대해 검증합니다. +하지만 파이썬 타입과 함께 선언할 경우(위 예에서 `int`), 해당 타입으로 변환 및 검증됩니다. 경로 매개변수에 적용된 동일한 프로세스가 쿼리 매개변수에도 적용됩니다: @@ -36,13 +34,13 @@ URL의 일부이므로 "자연스럽게" 문자열입니다. 위 예에서 `skip=0`과 `limit=10`은 기본값을 갖고 있습니다. -그러므로 URL로 이동하면: +그러므로 URL로 이동하는 것은: ``` http://127.0.0.1:8000/items/ ``` -아래로 이동한 것과 같습니다: +아래로 이동하는 것과 같습니다: ``` http://127.0.0.1:8000/items/?skip=0&limit=10 @@ -63,27 +61,29 @@ http://127.0.0.1:8000/items/?skip=20 같은 방법으로 기본값을 `None`으로 설정하여 선택적 매개변수를 선언할 수 있습니다: -```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial002.py!} -``` +{* ../../docs_src/query_params/tutorial002.py hl[9] *} 이 경우 함수 매개변수 `q`는 선택적이며 기본값으로 `None` 값이 됩니다. -!!! check "확인" - **FastAPI**는 `item_id`가 경로 매개변수이고 `q`는 경로 매개변수가 아닌 쿼리 매개변수라는 것을 알 정도로 충분히 똑똑합니다. +/// check | 확인 + +**FastAPI**는 `item_id`가 경로 매개변수이고 `q`는 경로 매개변수가 아닌 쿼리 매개변수라는 것을 알 정도로 충분히 똑똑합니다. + +/// + +/// note | 참고 + +FastAPI는 `q`가 `= None`이므로 선택적이라는 것을 인지합니다. -!!! note "참고" - FastAPI는 `q`가 `= None`이므로 선택적이라는 것을 인지합니다. +`Union[str, None]`에 있는 `Union`은 FastAPI(FastAPI는 `str` 부분만 사용합니다)가 사용하는게 아니지만, `Union[str, None]`은 편집기에게 코드에서 오류를 찾아낼 수 있게 도와줍니다. - `Union[str, None]`에 있는 `Union`은 FastAPI(FastAPI는 `str` 부분만 사용합니다)가 사용하는게 아니지만, `Union[str, None]`은 편집기에게 코드에서 오류를 찾아낼 수 있게 도와줍니다. +/// ## 쿼리 매개변수 형변환 `bool` 형으로 선언할 수도 있고, 아래처럼 변환됩니다: -```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial003.py!} -``` +{* ../../docs_src/query_params/tutorial003.py hl[9] *} 이 경우, 아래로 이동하면: @@ -126,9 +126,7 @@ http://127.0.0.1:8000/items/foo?short=yes 매개변수들은 이름으로 감지됩니다: -```Python hl_lines="8 10" -{!../../../docs_src/query_params/tutorial004.py!} -``` +{* ../../docs_src/query_params/tutorial004.py hl[8,10] *} ## 필수 쿼리 매개변수 @@ -136,15 +134,13 @@ http://127.0.0.1:8000/items/foo?short=yes 특정값을 추가하지 않고 선택적으로 만들기 위해선 기본값을 `None`으로 설정하면 됩니다. -그러나 쿼리 매개변수를 필수로 만들려면 기본값을 선언할 수 없습니다: +그러나 쿼리 매개변수를 필수로 만들려면 단순히 기본값을 선언하지 않으면 됩니다: -```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} -``` +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} 여기 쿼리 매개변수 `needy`는 `str`형인 필수 쿼리 매개변수입니다. -브라우저에서 URL을 아래처럼 연다면: +브라우저에서 아래와 같은 URL을 연다면: ``` http://127.0.0.1:8000/items/foo-item @@ -184,15 +180,16 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy 그리고 물론, 일부 매개변수는 필수로, 다른 일부는 기본값을, 또 다른 일부는 선택적으로 선언할 수 있습니다: -```Python hl_lines="10" -{!../../../docs_src/query_params/tutorial006.py!} -``` +{* ../../docs_src/query_params/tutorial006.py hl[10] *} -이 경우 3가지 쿼리 매개변수가 있습니다: +위 예시에서는 3가지 쿼리 매개변수가 있습니다: * `needy`, 필수적인 `str`. * `skip`, 기본값이 `0`인 `int`. * `limit`, 선택적인 `int`. -!!! tip "팁" - [경로 매개변수](path-params.md#predefined-values){.internal-link target=_blank}와 마찬가지로 `Enum`을 사용할 수 있습니다. +/// tip | 팁 + +[경로 매개변수](path-params.md#_8){.internal-link target=_blank}와 마찬가지로 `Enum`을 사용할 수 있습니다. + +/// diff --git a/docs/ko/docs/tutorial/request-files.md b/docs/ko/docs/tutorial/request-files.md index decefe981..9162b353c 100644 --- a/docs/ko/docs/tutorial/request-files.md +++ b/docs/ko/docs/tutorial/request-files.md @@ -2,36 +2,41 @@ `File`을 사용하여 클라이언트가 업로드할 파일들을 정의할 수 있습니다. -!!! info "정보" - 업로드된 파일을 전달받기 위해 먼저 `python-multipart`를 설치해야합니다. +/// info | 정보 - 예시) `pip install python-multipart`. +업로드된 파일을 전달받기 위해 먼저 `python-multipart`를 설치해야합니다. - 업로드된 파일들은 "폼 데이터"의 형태로 전송되기 때문에 이 작업이 필요합니다. +예시) `pip install python-multipart`. + +업로드된 파일들은 "폼 데이터"의 형태로 전송되기 때문에 이 작업이 필요합니다. + +/// ## `File` 임포트 `fastapi` 에서 `File` 과 `UploadFile` 을 임포트 합니다: -```Python hl_lines="1" -{!../../../docs_src/request_files/tutorial001.py!} -``` +{* ../../docs_src/request_files/tutorial001.py hl[1] *} ## `File` 매개변수 정의 `Body` 및 `Form` 과 동일한 방식으로 파일의 매개변수를 생성합니다: -```Python hl_lines="7" -{!../../../docs_src/request_files/tutorial001.py!} -``` +{* ../../docs_src/request_files/tutorial001.py hl[7] *} + +/// info | 정보 + +`File` 은 `Form` 으로부터 직접 상속된 클래스입니다. -!!! info "정보" - `File` 은 `Form` 으로부터 직접 상속된 클래스입니다. +하지만 `fastapi`로부터 `Query`, `Path`, `File` 등을 임포트 할 때, 이것들은 특별한 클래스들을 반환하는 함수라는 것을 기억하기 바랍니다. - 하지만 `fastapi`로부터 `Query`, `Path`, `File` 등을 임포트 할 때, 이것들은 특별한 클래스들을 반환하는 함수라는 것을 기억하기 바랍니다. +/// -!!! tip "팁" - File의 본문을 선언할 때, 매개변수가 쿼리 매개변수 또는 본문(JSON) 매개변수로 해석되는 것을 방지하기 위해 `File` 을 사용해야합니다. +/// tip | 팁 + +File의 본문을 선언할 때, 매개변수가 쿼리 매개변수 또는 본문(JSON) 매개변수로 해석되는 것을 방지하기 위해 `File` 을 사용해야합니다. + +/// 파일들은 "폼 데이터"의 형태로 업로드 됩니다. @@ -45,9 +50,7 @@ `File` 매개변수를 `UploadFile` 타입으로 정의합니다: -```Python hl_lines="12" -{!../../../docs_src/request_files/tutorial001.py!} -``` +{* ../../docs_src/request_files/tutorial001.py hl[12] *} `UploadFile` 을 사용하는 것은 `bytes` 과 비교해 다음과 같은 장점이 있습니다: @@ -89,11 +92,17 @@ contents = await myfile.read() contents = myfile.file.read() ``` -!!! note "`async` 기술적 세부사항" - `async` 메소드들을 사용할 때 **FastAPI**는 스레드풀에서 파일 메소드들을 실행하고 그들을 기다립니다. +/// note | "`async` 기술적 세부사항" + +`async` 메소드들을 사용할 때 **FastAPI**는 스레드풀에서 파일 메소드들을 실행하고 그들을 기다립니다. + +/// -!!! note "Starlette 기술적 세부사항" - **FastAPI**의 `UploadFile` 은 **Starlette**의 `UploadFile` 을 직접적으로 상속받지만, **Pydantic** 및 FastAPI의 다른 부분들과의 호환성을 위해 필요한 부분들이 추가되었습니다. +/// note | Starlette 기술적 세부사항 + +**FastAPI**의 `UploadFile` 은 **Starlette**의 `UploadFile` 을 직접적으로 상속받지만, **Pydantic** 및 FastAPI의 다른 부분들과의 호환성을 위해 필요한 부분들이 추가되었습니다. + +/// ## "폼 데이터"란 @@ -101,17 +110,23 @@ HTML의 폼들(`
`)이 서버에 데이터를 전송하는 방식은 **FastAPI**는 JSON 대신 올바른 위치에서 데이터를 읽을 수 있도록 합니다. -!!! note "기술적 세부사항" - 폼의 데이터는 파일이 포함되지 않은 경우 일반적으로 "미디어 유형" `application/x-www-form-urlencoded` 을 사용해 인코딩 됩니다. +/// note | 기술적 세부사항 + +폼의 데이터는 파일이 포함되지 않은 경우 일반적으로 "미디어 유형" `application/x-www-form-urlencoded` 을 사용해 인코딩 됩니다. + +하지만 파일이 포함된 경우, `multipart/form-data`로 인코딩됩니다. `File`을 사용하였다면, **FastAPI**는 본문의 적합한 부분에서 파일을 가져와야 한다는 것을 인지합니다. + +인코딩과 폼 필드에 대해 더 알고싶다면, POST에 관한MDN웹 문서 를 참고하기 바랍니다,. + +/// - 하지만 파일이 포함된 경우, `multipart/form-data`로 인코딩됩니다. `File`을 사용하였다면, **FastAPI**는 본문의 적합한 부분에서 파일을 가져와야 한다는 것을 인지합니다. +/// warning | 경고 - 인코딩과 폼 필드에 대해 더 알고싶다면, POST에 관한MDN웹 문서 를 참고하기 바랍니다,. +다수의 `File` 과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json` 가 아닌 `multipart/form-data` 로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다. -!!! warning "주의" - 다수의 `File` 과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json` 가 아닌 `multipart/form-data` 로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다. +이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다. - 이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다. +/// ## 다중 파일 업로드 @@ -121,23 +136,27 @@ HTML의 폼들(`
`)이 서버에 데이터를 전송하는 방식은 이 기능을 사용하기 위해 , `bytes` 의 `List` 또는 `UploadFile` 를 선언하기 바랍니다: -```Python hl_lines="10 15" -{!../../../docs_src/request_files/tutorial002.py!} -``` +{* ../../docs_src/request_files/tutorial002.py hl[10,15] *} 선언한대로, `bytes` 의 `list` 또는 `UploadFile` 들을 전송받을 것입니다. -!!! note "참고" - 2019년 4월 14일부터 Swagger UI가 하나의 폼 필드로 다수의 파일을 업로드하는 것을 지원하지 않습니다. 더 많은 정보를 원하면, #4276#3641을 참고하세요. +/// note | 참고 + +2019년 4월 14일부터 Swagger UI가 하나의 폼 필드로 다수의 파일을 업로드하는 것을 지원하지 않습니다. 더 많은 정보를 원하면, #4276#3641을 참고하세요. + +그럼에도, **FastAPI**는 표준 Open API를 사용해 이미 호환이 가능합니다. + +따라서 Swagger UI 또는 기타 그 외의 OpenAPI를 지원하는 툴이 다중 파일 업로드를 지원하는 경우, 이들은 **FastAPI**와 호환됩니다. + +/// - 그럼에도, **FastAPI**는 표준 Open API를 사용해 이미 호환이 가능합니다. +/// note | 기술적 세부사항 - 따라서 Swagger UI 또는 기타 그 외의 OpenAPI를 지원하는 툴이 다중 파일 업로드를 지원하는 경우, 이들은 **FastAPI**와 호환됩니다. +`from starlette.responses import HTMLResponse` 역시 사용할 수 있습니다. -!!! note "기술적 세부사항" - `from starlette.responses import HTMLResponse` 역시 사용할 수 있습니다. +**FastAPI**는 개발자의 편의를 위해 `fastapi.responses` 와 동일한 `starlette.responses` 도 제공합니다. 하지만 대부분의 응답들은 Starlette로부터 직접 제공됩니다. - **FastAPI**는 개발자의 편의를 위해 `fastapi.responses` 와 동일한 `starlette.responses` 도 제공합니다. 하지만 대부분의 응답들은 Starlette로부터 직접 제공됩니다. +/// ## 요약 diff --git a/docs/ko/docs/tutorial/request-form-models.md b/docs/ko/docs/tutorial/request-form-models.md new file mode 100644 index 000000000..3316a93d5 --- /dev/null +++ b/docs/ko/docs/tutorial/request-form-models.md @@ -0,0 +1,78 @@ +# 폼 모델 + +FastAPI에서 **Pydantic 모델**을 이용하여 **폼 필드**를 선언할 수 있습니다. + +/// info | 정보 + +폼(Form)을 사용하려면, 먼저 `python-multipart`를 설치하세요. + +[가상 환경](../virtual-environments.md){.internal-link target=_blank}을 생성하고 활성화한 다음, 아래와 같이 설치할 수 있습니다: + +```console +$ pip install python-multipart +``` + +/// + +/// note | 참고 + +이 기능은 FastAPI 버전 `0.113.0` 이후부터 지원됩니다. 🤓 + +/// + +## Pydantic 모델을 사용한 폼 + +**폼 필드**로 받고 싶은 필드를 **Pydantic 모델**로 선언한 다음, 매개변수를 `Form`으로 선언하면 됩니다: + +{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *} + +**FastAPI**는 요청에서 받은 **폼 데이터**에서 **각 필드**에 대한 데이터를 **추출**하고 정의한 Pydantic 모델을 줍니다. + +## 문서 확인하기 + +문서 UI `/docs`에서 확인할 수 있습니다: + +
+ +
+ +## 추가 폼 필드 금지하기 + +일부 특별한 사용 사례(흔하지는 않겠지만)에서는 Pydantic 모델에서 정의한 폼 필드를 **제한**하길 원할 수도 있습니다. 그리고 **추가** 필드를 **금지**할 수도 있습니다. + +/// note | 참고 + +이 기능은 FastAPI 버전 `0.114.0` 이후부터 지원됩니다. 🤓 + +/// + +Pydantic의 모델 구성을 사용하여 추가(`extra`) 필드를 금지(`forbid`)할 수 있습니다: + +{* ../../docs_src/request_form_models/tutorial002_an_py39.py hl[12] *} + +클라이언트가 추가 데이터를 보내려고 하면 **오류** 응답을 받게 됩니다. + +예를 들어, 클라이언트가 폼 필드를 보내려고 하면: + +* `username`: `Rick` +* `password`: `Portal Gun` +* `extra`: `Mr. Poopybutthole` + +`extra` 필드가 허용되지 않는다는 오류 응답을 받게 됩니다: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["body", "extra"], + "msg": "Extra inputs are not permitted", + "input": "Mr. Poopybutthole" + } + ] +} +``` + +## 요약 + +Pydantic 모델을 사용하여 FastAPI에서 폼 필드를 선언할 수 있습니다. 😎 diff --git a/docs/ko/docs/tutorial/request-forms-and-files.md b/docs/ko/docs/tutorial/request-forms-and-files.md index ddf232e7f..dc1bda21a 100644 --- a/docs/ko/docs/tutorial/request-forms-and-files.md +++ b/docs/ko/docs/tutorial/request-forms-and-files.md @@ -2,33 +2,35 @@ `File` 과 `Form` 을 사용하여 파일과 폼을 함께 정의할 수 있습니다. -!!! info "정보" - 파일과 폼 데이터를 함께, 또는 각각 업로드하기 위해 먼저 `python-multipart`를 설치해야합니다. +/// info | 정보 - 예 ) `pip install python-multipart`. +파일과 폼 데이터를 함께, 또는 각각 업로드하기 위해 먼저 `python-multipart`를 설치해야합니다. + +예 ) `pip install python-multipart`. + +/// ## `File` 및 `Form` 업로드 -```Python hl_lines="1" -{!../../../docs_src/request_forms_and_files/tutorial001.py!} -``` +{* ../../docs_src/request_forms_and_files/tutorial001.py hl[1] *} ## `File` 및 `Form` 매개변수 정의 `Body` 및 `Query`와 동일한 방식으로 파일과 폼의 매개변수를 생성합니다: -```Python hl_lines="8" -{!../../../docs_src/request_forms_and_files/tutorial001.py!} -``` +{* ../../docs_src/request_forms_and_files/tutorial001.py hl[8] *} 파일과 폼 필드는 폼 데이터 형식으로 업로드되어 파일과 폼 필드로 전달됩니다. 어떤 파일들은 `bytes`로, 또 어떤 파일들은 `UploadFile`로 선언할 수 있습니다. -!!! warning "주의" - 다수의 `File`과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json`가 아닌 `multipart/form-data`로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다. +/// warning | 경고 + +다수의 `File`과 `Form` 매개변수를 한 *경로 작동*에 선언하는 것이 가능하지만, 요청의 본문이 `application/json`가 아닌 `multipart/form-data`로 인코딩 되기 때문에 JSON으로 받아야하는 `Body` 필드를 함께 선언할 수는 없습니다. + +이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다. - 이는 **FastAPI**의 한계가 아니라, HTTP 프로토콜에 의한 것입니다. +/// ## 요약 diff --git a/docs/ko/docs/tutorial/request-forms.md b/docs/ko/docs/tutorial/request-forms.md new file mode 100644 index 000000000..5ca17b0d6 --- /dev/null +++ b/docs/ko/docs/tutorial/request-forms.md @@ -0,0 +1,74 @@ +# 폼 데이터 + +JSON 대신 폼 필드를 받아야 하는 경우 `Form`을 사용할 수 있습니다. + +/// info | 정보 + +폼을 사용하려면, 먼저 `python-multipart`를 설치하세요. + +[가상 환경](../virtual-environments.md){.internal-link target=_blank}을 생성하고 활성화한 다음, 아래와 같이 설치할 수 있습니다: + +```console +$ pip install python-multipart +``` + +/// + +## `Form` 임포트하기 + +`fastapi`에서 `Form`을 임포트합니다: + +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[3] *} + +## `Form` 매개변수 정의하기 + +`Body` 또는 `Query`와 동일한 방식으로 폼 매개변수를 만듭니다: + +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[9] *} + +예를 들어, OAuth2 사양을 사용할 수 있는 방법 중 하나("패스워드 플로우"라고 함)로 `username`과 `password`를 폼 필드로 보내야 합니다. + +사양에서는 필드 이름이 `username` 및 `password`로 정확하게 명명되어야 하고, JSON이 아닌 폼 필드로 전송해야 합니다. + +`Form`을 사용하면 유효성 검사, 예제, 별칭(예: `username` 대신 `user-name`) 등을 포함하여 `Body`(및 `Query`, `Path`, `Cookie`)와 동일한 구성을 선언할 수 있습니다. + +/// info | 정보 + +`Form`은 `Body`에서 직접 상속되는 클래스입니다. + +/// + +/// tip | 팁 + +폼 본문을 선언할 때, 폼이 없으면 매개변수가 쿼리 매개변수나 본문(JSON) 매개변수로 해석(interpret)되기 때문에 `Form`을 명시적으로 사용해야 합니다. + +/// + +## "폼 필드"에 대해 + +HTML 폼(`
`)이 데이터를 서버로 보내는 방식은 일반적으로 해당 데이터에 대해 "특수" 인코딩을 사용하며, 이는 JSON과 다릅니다. + +**FastAPI**는 JSON 대신 올바른 위치에서 해당 데이터를 읽습니다. + +/// note | 기술 세부사항 + +폼의 데이터는 일반적으로 "미디어 유형(media type)" `application/x-www-form-urlencoded`를 사용하여 인코딩합니다. + +그러나 폼에 파일이 포함된 경우, `multipart/form-data`로 인코딩합니다. 다음 장에서 파일 처리에 대해 읽을 겁니다. + + +이러한 인코딩 및 폼 필드에 대해 더 읽고 싶다면, POST에 대한 MDN 웹 문서를 참조하세요. + +/// + +/// warning | 경고 + +*경로 작업*에서 여러 `Form` 매개변수를 선언할 수 있지만, JSON으로 수신할 것으로 예상되는 `Body` 필드와 함께 선언할 수 없습니다. 요청 본문은 `application/json` 대신에 `application/x-www-form-urlencoded`를 사용하여 인코딩되기 때문입니다. + +이는 **FastAPI**의 제한 사항이 아니며 HTTP 프로토콜의 일부입니다. + +/// + +## 요약 + +폼 데이터 입력 매개변수를 선언하려면 `Form`을 사용하세요. diff --git a/docs/ko/docs/tutorial/response-model.md b/docs/ko/docs/tutorial/response-model.md new file mode 100644 index 000000000..a71d649f9 --- /dev/null +++ b/docs/ko/docs/tutorial/response-model.md @@ -0,0 +1,214 @@ +# 응답 모델 + +어떤 *경로 작동*이든 매개변수 `response_model`를 사용하여 응답을 위한 모델을 선언할 수 있습니다: + +* `@app.get()` +* `@app.post()` +* `@app.put()` +* `@app.delete()` +* 기타. + +{* ../../docs_src/response_model/tutorial001.py hl[17] *} + +/// note | 참고 + +`response_model`은 "데코레이터" 메소드(`get`, `post`, 등)의 매개변수입니다. 모든 매개변수들과 본문(body)처럼 *경로 작동 함수*가 아닙니다. + +/// + +Pydantic 모델 어트리뷰트를 선언한 것과 동일한 타입을 수신하므로 Pydantic 모델이 될 수 있지만, `List[Item]`과 같이 Pydantic 모델들의 `list`일 수도 있습니다. + +FastAPI는 이 `response_model`를 사용하여: + +* 출력 데이터를 타입 선언으로 변환. +* 데이터 검증. +* OpenAPI *경로 작동*의 응답에 JSON 스키마 추가. +* 자동 생성 문서 시스템에 사용. + +하지만 가장 중요한 것은: + +* 해당 모델의 출력 데이터 제한. 이것이 얼마나 중요한지 아래에서 볼 것입니다. + +/// note | 기술 세부사항 + +응답 모델은 함수의 타입 어노테이션 대신 이 매개변수로 선언하는데, 경로 함수가 실제 응답 모델을 반환하지 않고 `dict`, 데이터베이스 객체나 기타 다른 모델을 `response_model`을 사용하여 필드 제한과 직렬화를 수행하고 반환할 수 있기 때문입니다 + +/// + +## 동일한 입력 데이터 반환 + +여기서 우리는 평문 비밀번호를 포함하는 `UserIn` 모델을 선언합니다: + +{* ../../docs_src/response_model/tutorial002.py hl[9,11] *} + +그리고 이 모델을 사용하여 입력을 선언하고 같은 모델로 출력을 선언합니다: + +{* ../../docs_src/response_model/tutorial002.py hl[17:18] *} + +이제 브라우저가 비밀번호로 사용자를 만들 때마다 API는 응답으로 동일한 비밀번호를 반환합니다. + +이 경우, 사용자가 스스로 비밀번호를 발신했기 때문에 문제가 되지 않을 수 있습니다. + +그러나 동일한 모델을 다른 *경로 작동*에서 사용할 경우, 모든 클라이언트에게 사용자의 비밀번호를 발신할 수 있습니다. + +/// danger | 위험 + +절대로 사용자의 평문 비밀번호를 저장하거나 응답으로 발신하지 마십시오. + +/// + +## 출력 모델 추가 + +대신 평문 비밀번호로 입력 모델을 만들고 해당 비밀번호 없이 출력 모델을 만들 수 있습니다: + +{* ../../docs_src/response_model/tutorial003.py hl[9,11,16] *} + +여기서 *경로 작동 함수*가 비밀번호를 포함하는 동일한 입력 사용자를 반환할지라도: + +{* ../../docs_src/response_model/tutorial003.py hl[24] *} + +...`response_model`을 `UserOut` 모델로 선언했기 때문에 비밀번호를 포함하지 않습니다: + +{* ../../docs_src/response_model/tutorial003.py hl[22] *} + +따라서 **FastAPI**는 출력 모델에서 선언하지 않은 모든 데이터를 (Pydantic을 사용하여) 필터링합니다. + +## 문서에서 보기 + +자동 생성 문서를 보면 입력 모델과 출력 모델이 각자의 JSON 스키마를 가지고 있음을 확인할 수 있습니다: + + + +그리고 두 모델 모두 대화형 API 문서에 사용됩니다: + + + +## 응답 모델 인코딩 매개변수 + +응답 모델은 아래와 같이 기본값을 가질 수 있습니다: + +{* ../../docs_src/response_model/tutorial004.py hl[11,13:14] *} + +* `description: Optional[str] = None`은 기본값으로 `None`을 갖습니다. +* `tax: float = 10.5`는 기본값으로 `10.5`를 갖습니다. +* `tags: List[str] = []` 빈 리스트의 기본값으로: `[]`. + +그러나 실제로 저장되지 않았을 경우 결과에서 값을 생략하고 싶을 수 있습니다. + +예를 들어, NoSQL 데이터베이스에 많은 선택적 속성이 있는 모델이 있지만, 기본값으로 가득 찬 매우 긴 JSON 응답을 보내고 싶지 않습니다. + +### `response_model_exclude_unset` 매개변수 사용 + +*경로 작동 데코레이터* 매개변수를 `response_model_exclude_unset=True`로 설정 할 수 있습니다: + +{* ../../docs_src/response_model/tutorial004.py hl[24] *} + +이러한 기본값은 응답에 포함되지 않고 실제로 설정된 값만 포함됩니다. + +따라서 해당 *경로 작동*에 ID가 `foo`인 항목(items)을 요청으로 보내면 (기본값을 제외한) 응답은 다음과 같습니다: + +```JSON +{ + "name": "Foo", + "price": 50.2 +} +``` + +/// info | 정보 + +FastAPI는 이를 위해 Pydantic 모델의 `.dict()`의 `exclude_unset` 매개변수를 사용합니다. + +/// + +/// info | 정보 + +아래 또한 사용할 수 있습니다: + +* `response_model_exclude_defaults=True` +* `response_model_exclude_none=True` + +Pydantic 문서에서 `exclude_defaults` 및 `exclude_none`에 대해 설명한 대로 사용할 수 있습니다. + +/// + +#### 기본값이 있는 필드를 갖는 값의 데이터 + +하지만 모델의 필드가 기본값이 있어도 ID가 `bar`인 항목(items)처럼 데이터가 값을 갖는다면: + +```Python hl_lines="3 5" +{ + "name": "Bar", + "description": "The bartenders", + "price": 62, + "tax": 20.2 +} +``` + +응답에 해당 값들이 포함됩니다. + +#### 기본값과 동일한 값을 갖는 데이터 + +If the data has the same values as the default ones, like the item with ID `baz`: +ID가 `baz`인 항목(items)처럼 기본값과 동일한 값을 갖는다면: + +```Python hl_lines="3 5-6" +{ + "name": "Baz", + "description": None, + "price": 50.2, + "tax": 10.5, + "tags": [] +} +``` + +`description`, `tax` 그리고 `tags`가 기본값과 같더라도 (기본값에서 가져오는 대신) 값들이 명시적으로 설정되었다는 것을 인지할 정도로 FastAPI는 충분히 똑똑합니다(사실, Pydantic이 충분히 똑똑합니다). + +따라서 JSON 스키마에 포함됩니다. + +/// tip | 팁 + +`None` 뿐만 아니라 다른 어떤 것도 기본값이 될 수 있습니다. + +리스트(`[]`), `float`인 `10.5` 등이 될 수 있습니다. + +/// + +### `response_model_include` 및 `response_model_exclude` + +*경로 작동 데코레이터* 매개변수 `response_model_include` 및 `response_model_exclude`를 사용할 수 있습니다. + +이들은 포함(나머지 생략)하거나 제외(나머지 포함) 할 어트리뷰트의 이름과 `str`의 `set`을 받습니다. + +Pydantic 모델이 하나만 있고 출력에서 ​​일부 데이터를 제거하려는 경우 빠른 지름길로 사용할 수 있습니다. + +/// tip | 팁 + +하지만 이러한 매개변수 대신 여러 클래스를 사용하여 위 아이디어를 사용하는 것을 추천합니다. + +이는 일부 어트리뷰트를 생략하기 위해 `response_model_include` 또는 `response_model_exclude`를 사용하더라도 앱의 OpenAPI(및 문서)가 생성한 JSON 스키마가 여전히 전체 모델에 대한 스키마이기 때문입니다. + +비슷하게 작동하는 `response_model_by_alias` 역시 마찬가지로 적용됩니다. + +/// + +{* ../../docs_src/response_model/tutorial005.py hl[31,37] *} + +/// tip | 팁 + +문법 `{"name", "description"}`은 두 값을 갖는 `set`을 만듭니다. + +이는 `set(["name", "description"])`과 동일합니다. + +/// + +#### `set` 대신 `list` 사용하기 + +`list` 또는 `tuple` 대신 `set`을 사용하는 법을 잊었더라도, FastAPI는 `set`으로 변환하고 정상적으로 작동합니다: + +{* ../../docs_src/response_model/tutorial006.py hl[31,37] *} + +## 요약 + +응답 모델을 정의하고 개인정보가 필터되는 것을 보장하기 위해 *경로 작동 데코레이터*의 매개변수 `response_model`을 사용하세요. + +명시적으로 설정된 값만 반환하려면 `response_model_exclude_unset`을 사용하세요. diff --git a/docs/ko/docs/tutorial/response-status-code.md b/docs/ko/docs/tutorial/response-status-code.md index f92c057be..bcaf7843b 100644 --- a/docs/ko/docs/tutorial/response-status-code.md +++ b/docs/ko/docs/tutorial/response-status-code.md @@ -8,17 +8,21 @@ * `@app.delete()` * 기타 -```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} -!!! note "참고" - `status_code` 는 "데코레이터" 메소드(`get`, `post` 등)의 매개변수입니다. 모든 매개변수들과 본문처럼 *경로 작동 함수*가 아닙니다. +/// note | 참고 + +`status_code` 는 "데코레이터" 메소드(`get`, `post` 등)의 매개변수입니다. 모든 매개변수들과 본문처럼 *경로 작동 함수*가 아닙니다. + +/// `status_code` 매개변수는 HTTP 상태 코드를 숫자로 입력받습니다. -!!! info "정보" - `status_code` 는 파이썬의 `http.HTTPStatus` 와 같은 `IntEnum` 을 입력받을 수도 있습니다. +/// info | 정보 + +`status_code` 는 파이썬의 `http.HTTPStatus` 와 같은 `IntEnum` 을 입력받을 수도 있습니다. + +/// `status_code` 매개변수는: @@ -27,15 +31,21 @@ -!!! note "참고" - 어떤 응답 코드들은 해당 응답에 본문이 없다는 것을 의미하기도 합니다 (다음 항목 참고). +/// note | 참고 + +어떤 응답 코드들은 해당 응답에 본문이 없다는 것을 의미하기도 합니다 (다음 항목 참고). + +이에 따라 FastAPI는 응답 본문이 없음을 명시하는 OpenAPI를 생성합니다. - 이에 따라 FastAPI는 응답 본문이 없음을 명시하는 OpenAPI를 생성합니다. +/// ## HTTP 상태 코드에 대하여 -!!! note "참고" - 만약 HTTP 상태 코드에 대하여 이미 알고있다면, 다음 항목으로 넘어가십시오. +/// note | 참고 + +만약 HTTP 상태 코드에 대하여 이미 알고있다면, 다음 항목으로 넘어가십시오. + +/// HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다. @@ -43,27 +53,28 @@ HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다 요약하자면: -* `**1xx**` 상태 코드는 "정보"용입니다. 이들은 직접적으로는 잘 사용되지는 않습니다. 이 상태 코드를 갖는 응답들은 본문을 가질 수 없습니다. -* `**2xx**` 상태 코드는 "성공적인" 응답을 위해 사용됩니다. 가장 많이 사용되는 유형입니다. +* `1xx` 상태 코드는 "정보"용입니다. 이들은 직접적으로는 잘 사용되지는 않습니다. 이 상태 코드를 갖는 응답들은 본문을 가질 수 없습니다. +* **`2xx`** 상태 코드는 "성공적인" 응답을 위해 사용됩니다. 가장 많이 사용되는 유형입니다. * `200` 은 디폴트 상태 코드로, 모든 것이 "성공적임"을 의미합니다. * 다른 예로는 `201` "생성됨"이 있습니다. 일반적으로 데이터베이스에 새로운 레코드를 생성한 후 사용합니다. * 단, `204` "내용 없음"은 특별한 경우입니다. 이것은 클라이언트에게 반환할 내용이 없는 경우 사용합니다. 따라서 응답은 본문을 가질 수 없습니다. -* `**3xx**` 상태 코드는 "리다이렉션"용입니다. 본문을 가질 수 없는 `304` "수정되지 않음"을 제외하고, 이 상태 코드를 갖는 응답에는 본문이 있을 수도, 없을 수도 있습니다. -* `**4xx**` 상태 코드는 "클라이언트 오류" 응답을 위해 사용됩니다. 이것은 아마 가장 많이 사용하게 될 두번째 유형입니다. +* **`3xx`** 상태 코드는 "리다이렉션"용입니다. 본문을 가질 수 없는 `304` "수정되지 않음"을 제외하고, 이 상태 코드를 갖는 응답에는 본문이 있을 수도, 없을 수도 있습니다. +* **`4xx`** 상태 코드는 "클라이언트 오류" 응답을 위해 사용됩니다. 이것은 아마 가장 많이 사용하게 될 두번째 유형입니다. * 일례로 `404` 는 "찾을 수 없음" 응답을 위해 사용합니다. * 일반적인 클라이언트 오류의 경우 `400` 을 사용할 수 있습니다. -* `**5xx**` 상태 코드는 서버 오류에 사용됩니다. 이것들을 직접 사용할 일은 거의 없습니다. 응용 프로그램 코드나 서버의 일부에서 문제가 발생하면 자동으로 이들 상태 코드 중 하나를 반환합니다. +* `5xx` 상태 코드는 서버 오류에 사용됩니다. 이것들을 직접 사용할 일은 거의 없습니다. 응용 프로그램 코드나 서버의 일부에서 문제가 발생하면 자동으로 이들 상태 코드 중 하나를 반환합니다. + +/// tip | 팁 -!!! tip "팁" - 각각의 상태 코드와 이들이 의미하는 내용에 대해 더 알고싶다면 MDN HTTP 상태 코드에 관한 문서 를 확인하십시오. +각각의 상태 코드와 이들이 의미하는 내용에 대해 더 알고싶다면 MDN HTTP 상태 코드에 관한 문서 를 확인하십시오. + +/// ## 이름을 기억하는 쉬운 방법 상기 예시 참고: -```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} `201` 은 "생성됨"를 의미하는 상태 코드입니다. @@ -71,18 +82,19 @@ HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다 `fastapi.status` 의 편의 변수를 사용할 수 있습니다. -```Python hl_lines="1 6" -{!../../../docs_src/response_status_code/tutorial002.py!} -``` +{* ../../docs_src/response_status_code/tutorial002.py hl[1,6] *} 이것은 단순히 작업을 편리하게 하기 위한 것으로, HTTP 상태 코드와 동일한 번호를 갖고있지만, 이를 사용하면 편집기의 자동완성 기능을 사용할 수 있습니다: -!!! note "기술적 세부사항" - `from starlette import status` 역시 사용할 수 있습니다. +/// note | 기술적 세부사항 + +`from starlette import status` 역시 사용할 수 있습니다. + +**FastAPI**는 개발자인 여러분의 편의를 위해 `fastapi.status` 와 동일한 `starlette.status` 도 제공합니다. 하지만 이것은 Starlette로부터 직접 제공됩니다. - **FastAPI**는 개발자인 당신의 편의를 위해 `fastapi.status` 와 동일한 `starlette.status` 도 제공합니다. 하지만 이것은 Starlette로부터 직접 제공됩니다. +/// ## 기본값 변경 diff --git a/docs/ko/docs/tutorial/schema-extra-example.md b/docs/ko/docs/tutorial/schema-extra-example.md new file mode 100644 index 000000000..77e94db72 --- /dev/null +++ b/docs/ko/docs/tutorial/schema-extra-example.md @@ -0,0 +1,224 @@ +# 요청 예제 데이터 선언 + +여러분의 앱이 받을 수 있는 데이터 예제를 선언할 수 있습니다. + +여기 이를 위한 몇가지 방식이 있습니다. + +## Pydantic 모델 속 추가 JSON 스키마 데이터 + +생성된 JSON 스키마에 추가될 Pydantic 모델을 위한 `examples`을 선언할 수 있습니다. + +//// tab | Pydantic v2 + +{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:24] *} + +//// + +//// tab | Pydantic v1 + +{* ../../docs_src/schema_extra_example/tutorial001_pv1_py310.py hl[13:23] *} + +//// + +추가 정보는 있는 그대로 해당 모델의 **JSON 스키마** 결과에 추가되고, API 문서에서 사용합니다. + +//// tab | Pydantic v2 + +Pydantic 버전 2에서 Pydantic 공식 문서: Model Config에 나와 있는 것처럼 `dict`를 받는 `model_config` 어트리뷰트를 사용할 것입니다. + +`"json_schema_extra"`를 생성된 JSON 스키마에서 보여주고 싶은 별도의 데이터와 `examples`를 포함하는 `dict`으로 설정할 수 있습니다. + +//// + +//// tab | Pydantic v1 + +Pydantic v1에서 Pydantic 공식 문서: Schema customization에서 설명하는 것처럼, 내부 클래스인 `Config`와 `schema_extra`를 사용할 것입니다. + +`schema_extra`를 생성된 JSON 스키마에서 보여주고 싶은 별도의 데이터와 `examples`를 포함하는 `dict`으로 설정할 수 있습니다. + +//// + +/// tip | 팁 + +JSON 스키마를 확장하고 여러분의 별도의 자체 데이터를 추가하기 위해 같은 기술을 사용할 수 있습니다. + +예를 들면, 프론트엔드 사용자 인터페이스에 메타데이터를 추가하는 등에 사용할 수 있습니다. + +/// + +/// info | 정보 + +(FastAPI 0.99.0부터 쓰이기 시작한) OpenAPI 3.1.0은 **JSON 스키마** 표준의 일부인 `examples`에 대한 지원을 추가했습니다. + +그 전에는, 하나의 예제만 가능한 `example` 키워드만 지원했습니다. 이는 아직 OpenAPI 3.1.0에서 지원하지만, 지원이 종료될 것이며 JSON 스키마 표준에 포함되지 않습니다. 그렇기에 `example`을 `examples`으로 이전하는 것을 추천합니다. 🤓 + +이 문서 끝에 더 많은 읽을거리가 있습니다. + +/// + +## `Field` 추가 인자 + +Pydantic 모델과 같이 `Field()`를 사용할 때 추가적인 `examples`를 선언할 수 있습니다: + +{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *} + +## JSON Schema에서의 `examples` - OpenAPI + +이들 중에서 사용합니다: + +* `Path()` +* `Query()` +* `Header()` +* `Cookie()` +* `Body()` +* `Form()` +* `File()` + +**OpenAPI**의 **JSON 스키마**에 추가될 부가적인 정보를 포함한 `examples` 모음을 선언할 수 있습니다. + +### `examples`를 포함한 `Body` + +여기, `Body()`에 예상되는 예제 데이터 하나를 포함한 `examples`를 넘겼습니다: + +{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:29] *} + +### 문서 UI 예시 + +위의 어느 방법과 함께라면 `/docs`에서 다음과 같이 보일 것입니다: + + + +### 다중 `examples`를 포함한 `Body` + +물론 여러 `examples`를 넘길 수 있습니다: + +{* ../../docs_src/schema_extra_example/tutorial004_an_py310.py hl[23:38] *} + +이와 같이 하면 이 예제는 그 본문 데이터를 위한 내부 **JSON 스키마**의 일부가 될 것입니다. + +그럼에도 불구하고, 지금 이 문서를 작성하는 시간에, 문서 UI를 보여주는 역할을 맡은 Swagger UI는 **JSON 스키마** 속 데이터를 위한 여러 예제의 표현을 지원하지 않습니다. 하지만 해결 방안을 밑에서 읽어보세요. + +### OpenAPI-특화 `examples` + +**JSON 스키마**가 `examples`를 지원하기 전 부터, OpenAPI는 `examples`이라 불리는 다른 필드를 지원해 왔습니다. + +이 **OpenAPI-특화** `examples`는 OpenAPI 명세서의 다른 구역으로 들어갑니다. 각 JSON 스키마 내부가 아니라 **각 *경로 작동* 세부 정보**에 포함됩니다. + +그리고 Swagger UI는 이 특정한 `examples` 필드를 한동안 지원했습니다. 그래서, 이를 다른 **문서 UI에 있는 예제**를 **표시**하기 위해 사용할 수 있습니다. + +이 OpenAPI-특화 필드인 `examples`의 형태는 (`list`대신에) **다중 예제**가 포함된 `dict`이며, 각각의 별도 정보 또한 **OpenAPI**에 추가될 것입니다. + +이는 OpenAPI에 포함된 JSON 스키마 안으로 포함되지 않으며, *경로 작동*에 직접적으로 포함됩니다. + +### `openapi_examples` 매개변수 사용하기 + +다음 예시 속에 OpenAPI-특화 `examples`를 FastAPI 안에서 매개변수 `openapi_examples` 매개변수와 함께 선언할 수 있습니다: + +* `Path()` +* `Query()` +* `Header()` +* `Cookie()` +* `Body()` +* `Form()` +* `File()` + +`dict`의 키가 또 다른 `dict`인 각 예제와 값을 구별합니다. + +각각의 특정 `examples` 속 `dict` 예제는 다음을 포함할 수 있습니다: + +* `summary`: 예제에 대한 짧은 설명문. +* `description`: 마크다운 텍스트를 포함할 수 있는 긴 설명문. +* `value`: 실제로 보여지는 예시, 예를 들면 `dict`. +* `externalValue`: `value`의 대안이며 예제를 가르키는 URL. 비록 `value`처럼 많은 도구를 지원하지 못할 수 있습니다. + +이를 다음과 같이 사용할 수 있습니다: + +{* ../../docs_src/schema_extra_example/tutorial005_an_py310.py hl[23:49] *} + +### 문서 UI에서의 OpenAPI 예시 + +`Body()`에 추가된 `openapi_examples`를 포함한 `/docs`는 다음과 같이 보일 것입니다: + + + +## 기술적 세부 사항 + +/// tip | 팁 + +이미 **FastAPI**의 **0.99.0 혹은 그 이상** 버전을 사용하고 있다면, 이 세부 사항을 **스킵**해도 상관 없을 것입니다. + +세부 사항은 OpenAPI 3.1.0이 사용가능하기 전, 예전 버전과 더 관련있습니다. + +간략한 OpenAPI와 JSON 스키마 **역사 강의**로 생각할 수 있습니다. 🤓 + +/// + +/// warning | 경고 + +표준 **JSON 스키마**와 **OpenAPI**에 대한 아주 기술적인 세부사항입니다. + +만약 위의 생각이 작동한다면, 그것으로 충분하며 이 세부 사항은 필요없을 것이니, 마음 편하게 스킵하셔도 됩니다. + +/// + +OpenAPI 3.1.0 전에 OpenAPI는 오래된 **JSON 스키마**의 수정된 버전을 사용했습니다. + +JSON 스키마는 `examples`를 가지고 있지 않았고, 따라서 OpenAPI는 그들만의 `example` 필드를 수정된 버전에 추가했습니다. + +OpenAPI는 또한 `example`과 `examples` 필드를 명세서의 다른 부분에 추가했습니다: + +* `(명세서에 있는) Parameter Object`는 FastAPI의 다음 기능에서 쓰였습니다: + * `Path()` + * `Query()` + * `Header()` + * `Cookie()` +* (명세서에 있는)`Media Type Object`속 `content`에 있는 `Request Body Object`는 FastAPI의 다음 기능에서 쓰였습니다: + * `Body()` + * `File()` + * `Form()` + +/// info | 정보 + +이 예전 OpenAPI-특화 `examples` 매개변수는 이제 FastAPI `0.103.0`부터 `openapi_examples`입니다. + +/// + +### JSON 스키마의 `examples` 필드 + +하지만, 후에 JSON 스키마는 `examples`필드를 명세서의 새 버전에 추가했습니다. + +그리고 새로운 OpenAPI 3.1.0은 이 새로운 `examples` 필드가 포함된 최신 버전 (JSON 스키마 2020-12)을 기반으로 했습니다. + +이제 새로운 `examples` 필드는 이전의 단일 (그리고 커스텀) `example` 필드보다 우선되며, `example`은 사용하지 않는 것이 좋습니다. + +JSON 스키마의 새로운 `examples` 필드는 예제 속 **단순한 `list`**이며, (위에서 상술한 것처럼) OpenAPI의 다른 곳에 존재하는 dict으로 된 추가적인 메타데이터가 아닙니다. + +/// info | 정보 + +더 쉽고 새로운 JSON 스키마와의 통합과 함께 OpenAPI 3.1.0가 배포되었지만, 잠시동안 자동 문서 생성을 제공하는 도구인 Swagger UI는 OpenAPI 3.1.0을 지원하지 않았습니다 (5.0.0 버전부터 지원합니다 🎉). + +이로인해, FastAPI 0.99.0 이전 버전은 아직 OpenAPI 3.1.0 보다 낮은 버전을 사용했습니다. + +/// + +### Pydantic과 FastAPI `examples` + +`examples`를 Pydantic 모델 속에 추가할 때, `schema_extra` 혹은 `Field(examples=["something"])`를 사용하면 Pydantic 모델의 **JSON 스키마**에 해당 예시가 추가됩니다. + +그리고 Pydantic 모델의 **JSON 스키마**는 API의 **OpenAPI**에 포함되고, 그 후 문서 UI 속에서 사용됩니다. + +FastAPI 0.99.0 이전 버전에서 (0.99.0 이상 버전은 새로운 OpenAPI 3.1.0을 사용합니다), `example` 혹은 `examples`를 다른 유틸리티(`Query()`, `Body()` 등)와 함께 사용했을 때, 저러한 예시는 데이터를 설명하는 JSON 스키마에 추가되지 않으며 (심지어 OpenAPI의 자체 JSON 스키마에도 포함되지 않습니다), OpenAPI의 *경로 작동* 선언에 직접적으로 추가됩니다 (JSON 스키마를 사용하는 OpenAPI 부분 외에도). + +하지만 지금은 FastAPI 0.99.0 및 이후 버전에서는 JSON 스키마 2020-12를 사용하는 OpenAPI 3.1.0과 Swagger UI 5.0.0 및 이후 버전을 사용하며, 모든 것이 더 일관성을 띄고 예시는 JSON 스키마에 포함됩니다. + +### Swagger UI와 OpenAPI-특화 `examples` + +현재 (2023-08-26), Swagger UI가 다중 JSON 스키마 예시를 지원하지 않으며, 사용자는 다중 예시를 문서에 표시하는 방법이 없었습니다. + +이를 해결하기 위해, FastAPI `0.103.0`은 새로운 매개변수인 `openapi_examples`를 포함하는 예전 **OpenAPI-특화** `examples` 필드를 선언하기 위한 **지원을 추가**했습니다. 🤓 + +### 요약 + +저는 역사를 그다지 좋아하는 편이 아니라고 말하고는 했지만... "기술 역사" 강의를 가르치는 지금의 저를 보세요. + +요약하자면 **FastAPI 0.99.0 혹은 그 이상의 버전**으로 업그레이드하는 것은 많은 것들이 더 **쉽고, 일관적이며 직관적이게** 되며, 여러분은 이 모든 역사적 세부 사항을 알 필요가 없습니다. 😎 diff --git a/docs/ko/docs/tutorial/security/get-current-user.md b/docs/ko/docs/tutorial/security/get-current-user.md new file mode 100644 index 000000000..98ef3885e --- /dev/null +++ b/docs/ko/docs/tutorial/security/get-current-user.md @@ -0,0 +1,105 @@ +# 현재 사용자 가져오기 + +이전 장에서 (의존성 주입 시스템을 기반으로 한)보안 시스템은 *경로 작동 함수*에서 `str`로 `token`을 제공했습니다: + +{* ../../docs_src/security/tutorial001.py hl[10] *} + +그러나 아직도 유용하지 않습니다. + +현재 사용자를 제공하도록 합시다. + +## 유저 모델 생성하기 + +먼저 Pydantic 유저 모델을 만들어 보겠습니다. + +Pydantic을 사용하여 본문을 선언하는 것과 같은 방식으로 다른 곳에서 사용할 수 있습니다. + +{* ../../docs_src/security/tutorial002.py hl[5,12:16] *} + +## `get_current_user` 의존성 생성하기 + +의존성 `get_current_user`를 만들어 봅시다. + +의존성이 하위 의존성을 가질 수 있다는 것을 기억하십니까? + +`get_current_user`는 이전에 생성한 것과 동일한 `oauth2_scheme`과 종속성을 갖게 됩니다. + +이전에 *경로 작동*에서 직접 수행했던 것과 동일하게 새 종속성 `get_current_user`는 하위 종속성 `oauth2_scheme`에서 `str`로 `token`을 수신합니다. + +{* ../../docs_src/security/tutorial002.py hl[25] *} + +## 유저 가져오기 + +`get_current_user`는 토큰을 `str`로 취하고 Pydantic `User` 모델을 반환하는 우리가 만든 (가짜) 유틸리티 함수를 사용합니다. + +{* ../../docs_src/security/tutorial002.py hl[19:22,26:27] *} + +## 현재 유저 주입하기 + +이제 *경로 작동*에서 `get_current_user`와 동일한 `Depends`를 사용할 수 있습니다. + +{* ../../docs_src/security/tutorial002.py hl[31] *} + +Pydantic 모델인 `User`로 `current_user`의 타입을 선언하는 것을 알아야 합니다. + +이것은 모든 완료 및 타입 검사를 통해 함수 내부에서 우리를 도울 것입니다. + +/// tip | 팁 + +요청 본문도 Pydantic 모델로 선언된다는 것을 기억할 것입니다. + +여기서 **FastAPI**는 `Depends`를 사용하고 있기 때문에 혼동되지 않습니다. + +/// + +/// check | 확인 + +이 의존성 시스템이 설계된 방식은 모두 `User` 모델을 반환하는 다양한 의존성(다른 "의존적인")을 가질 수 있도록 합니다. + +해당 타입의 데이터를 반환할 수 있는 의존성이 하나만 있는 것으로 제한되지 않습니다. + +/// + +## 다른 모델 + +이제 *경로 작동 함수*에서 현재 사용자를 직접 가져올 수 있으며 `Depends`를 사용하여 **의존성 주입** 수준에서 보안 메커니즘을 처리할 수 있습니다. + +그리고 보안 요구 사항에 대한 모든 모델 또는 데이터를 사용할 수 있습니다(이 경우 Pydantic 모델 `User`). + +그러나 일부 특정 데이터 모델, 클래스 또는 타입을 사용하도록 제한되지 않습니다. + +모델에 `id`와 `email`이 있고 `username`이 없길 원하십니까? 맞습니다. 이들은 동일한 도구를 사용할 수 있습니다. + +`str`만 갖고 싶습니까? 아니면 그냥 `dict`를 갖고 싶습니까? 아니면 데이터베이스 클래스 모델 인스턴스를 직접 갖고 싶습니까? 그들은 모두 같은 방식으로 작동합니다. + +실제로 애플리케이션에 로그인하는 사용자가 없지만 액세스 토큰만 있는 로봇, 봇 또는 기타 시스템이 있습니까? 다시 말하지만 모두 동일하게 작동합니다. + +애플리케이션에 필요한 모든 종류의 모델, 모든 종류의 클래스, 모든 종류의 데이터베이스를 사용하십시오. **FastAPI**는 의존성 주입 시스템을 다루었습니다. + +## 코드 사이즈 + +이 예는 장황해 보일 수 있습니다. 동일한 파일에서 보안, 데이터 모델, 유틸리티 기능 및 *경로 작동*을 혼합하고 있음을 염두에 두십시오. + +그러나 이게 키포인트입니다. + +보안과 종속성 주입 항목을 한 번만 작성하면 됩니다. + +그리고 원하는 만큼 복잡하게 만들 수 있습니다. 그래도 유연성과 함께 한 곳에 한 번에 작성할 수 있습니다. + +그러나 동일한 보안 시스템을 사용하여 수천 개의 엔드포인트(*경로 작동*)를 가질 수 있습니다. + +그리고 그들 모두(또는 원하는 부분)는 이러한 의존성 또는 생성한 다른 의존성을 재사용하는 이점을 얻을 수 있습니다. + +그리고 이 수천 개의 *경로 작동*은 모두 3줄 정도로 줄일 수 있습니다. + +{* ../../docs_src/security/tutorial002.py hl[30:32] *} + +## 요약 + +이제 *경로 작동 함수*에서 현재 사용자를 직접 가져올 수 있습니다. + +우리는 이미 이들 사이에 있습니다. + +사용자/클라이언트가 실제로 `username`과 `password`를 보내려면 *경로 작동*을 추가하기만 하면 됩니다. + +다음 장을 확인해 봅시다. diff --git a/docs/ko/docs/tutorial/security/simple-oauth2.md b/docs/ko/docs/tutorial/security/simple-oauth2.md new file mode 100644 index 000000000..f10c4f588 --- /dev/null +++ b/docs/ko/docs/tutorial/security/simple-oauth2.md @@ -0,0 +1,295 @@ +# 패스워드와 Bearer를 이용한 간단한 OAuth2 + +이제 이전 장에서 빌드하고 누락된 부분을 추가하여 완전한 보안 흐름을 갖도록 하겠습니다. + +## `username`와 `password` 얻기 + +**FastAPI** 보안 유틸리티를 사용하여 `username` 및 `password`를 가져올 것입니다. + +OAuth2는 (우리가 사용하고 있는) "패스워드 플로우"을 사용할 때 클라이언트/유저가 `username` 및 `password` 필드를 폼 데이터로 보내야 함을 지정합니다. + +그리고 사양에는 필드의 이름을 그렇게 지정해야 한다고 나와 있습니다. 따라서 `user-name` 또는 `email`은 작동하지 않습니다. + +하지만 걱정하지 않아도 됩니다. 프런트엔드에서 최종 사용자에게 원하는 대로 표시할 수 있습니다. + +그리고 데이터베이스 모델은 원하는 다른 이름을 사용할 수 있습니다. + +그러나 로그인 *경로 작동*의 경우 사양과 호환되도록 이러한 이름을 사용해야 합니다(예를 들어 통합 API 문서 시스템을 사용할 수 있어야 합니다). + +사양에는 또한 `username`과 `password`가 폼 데이터로 전송되어야 한다고 명시되어 있습니다(따라서 여기에는 JSON이 없습니다). + +### `scope` + +사양에는 클라이언트가 다른 폼 필드 "`scope`"를 보낼 수 있다고 나와 있습니다. + +폼 필드 이름은 `scope`(단수형)이지만 실제로는 공백으로 구분된 "범위"가 있는 긴 문자열입니다. + +각 "범위"는 공백이 없는 문자열입니다. + +일반적으로 특정 보안 권한을 선언하는 데 사용됩니다. 다음을 봅시다: + +* `users:read` 또는 `users:write`는 일반적인 예시입니다. +* `instagram_basic`은 페이스북/인스타그램에서 사용합니다. +* `https://www.googleapis.com/auth/drive`는 Google에서 사용합니다. + +/// info | 정보 + +OAuth2에서 "범위"는 필요한 특정 권한을 선언하는 문자열입니다. + +`:`과 같은 다른 문자가 있는지 또는 URL인지는 중요하지 않습니다. + +이러한 세부 사항은 구현에 따라 다릅니다. + +OAuth2의 경우 문자열일 뿐입니다. + +/// + +## `username`과 `password`를 가져오는 코드 + +이제 **FastAPI**에서 제공하는 유틸리티를 사용하여 이를 처리해 보겠습니다. + +### `OAuth2PasswordRequestForm` + +먼저 `OAuth2PasswordRequestForm`을 가져와 `/token`에 대한 *경로 작동*에서 `Depends`의 의존성으로 사용합니다. + +{* ../../docs_src/security/tutorial003.py hl[4,76] *} + +`OAuth2PasswordRequestForm`은 다음을 사용하여 폼 본문을 선언하는 클래스 의존성입니다: + +* `username`. +* `password`. +* `scope`는 선택적인 필드로 공백으로 구분된 문자열로 구성된 큰 문자열입니다. +* `grant_type`(선택적으로 사용). + +/// tip | 팁 + +OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` 필드를 *요구*하지만 `OAuth2PasswordRequestForm`은 이를 강요하지 않습니다. + +사용해야 한다면 `OAuth2PasswordRequestForm` 대신 `OAuth2PasswordRequestFormStrict`를 사용하면 됩니다. + +/// + +* `client_id`(선택적으로 사용) (예제에서는 필요하지 않습니다). +* `client_secret`(선택적으로 사용) (예제에서는 필요하지 않습니다). + +/// info | 정보 + +`OAuth2PasswordRequestForm`은 `OAuth2PasswordBearer`와 같이 **FastAPI**에 대한 특수 클래스가 아닙니다. + +`OAuth2PasswordBearer`는 **FastAPI**가 보안 체계임을 알도록 합니다. 그래서 OpenAPI에 그렇게 추가됩니다. + +그러나 `OAuth2PasswordRequestForm`은 직접 작성하거나 `Form` 매개변수를 직접 선언할 수 있는 클래스 의존성일 뿐입니다. + +그러나 일반적인 사용 사례이므로 더 쉽게 하기 위해 **FastAPI**에서 직접 제공합니다. + +/// + +### 폼 데이터 사용하기 + +/// tip | 팁 + +종속성 클래스 `OAuth2PasswordRequestForm`의 인스턴스에는 공백으로 구분된 긴 문자열이 있는 `scope` 속성이 없고 대신 전송된 각 범위에 대한 실제 문자열 목록이 있는 `scopes` 속성이 있습니다. + +이 예제에서는 `scopes`를 사용하지 않지만 필요한 경우, 기능이 있습니다. + +/// + +이제 폼 필드의 `username`을 사용하여 (가짜) 데이터베이스에서 유저 데이터를 가져옵니다. + +해당 사용자가 없으면 "잘못된 사용자 이름 또는 패스워드"라는 오류가 반환됩니다. + +오류의 경우 `HTTPException` 예외를 사용합니다: + +{* ../../docs_src/security/tutorial003.py hl[3,77:79] *} + +### 패스워드 확인하기 + +이 시점에서 데이터베이스의 사용자 데이터 형식을 확인했지만 암호를 확인하지 않았습니다. + +먼저 데이터를 Pydantic `UserInDB` 모델에 넣겠습니다. + +일반 텍스트 암호를 저장하면 안 되니 (가짜) 암호 해싱 시스템을 사용합니다. + +두 패스워드가 일치하지 않으면 동일한 오류가 반환됩니다. + +#### 패스워드 해싱 + +"해싱"은 일부 콘텐츠(이 경우 패스워드)를 횡설수설하는 것처럼 보이는 일련의 바이트(문자열)로 변환하는 것을 의미합니다. + +정확히 동일한 콘텐츠(정확히 동일한 패스워드)를 전달할 때마다 정확히 동일한 횡설수설이 발생합니다. + +그러나 횡설수설에서 암호로 다시 변환할 수는 없습니다. + +##### 패스워드 해싱을 사용해야 하는 이유 + +데이터베이스가 유출된 경우 해커는 사용자의 일반 텍스트 암호가 아니라 해시만 갖게 됩니다. + +따라서 해커는 다른 시스템에서 동일한 암호를 사용하려고 시도할 수 없습니다(많은 사용자가 모든 곳에서 동일한 암호를 사용하므로 이는 위험할 수 있습니다). + +//// tab | 파이썬 3.7 이상 + +{* ../../docs_src/security/tutorial003.py hl[80:83] *} + +//// + +{* ../../docs_src/security/tutorial003_py310.py hl[78:81] *} + +#### `**user_dict`에 대해 + +`UserInDB(**user_dict)`는 다음을 의미한다: + +*`user_dict`의 키와 값을 다음과 같은 키-값 인수로 직접 전달합니다:* + +```Python +UserInDB( + username = user_dict["username"], + email = user_dict["email"], + full_name = user_dict["full_name"], + disabled = user_dict["disabled"], + hashed_password = user_dict["hashed_password"], +) +``` + +/// info | 정보 + +`**user_dict`에 대한 자세한 설명은 [**추가 모델** 문서](../extra-models.md#about-user_indict){.internal-link target=_blank}를 다시 읽어봅시다. + +/// + +## 토큰 반환하기 + +`token` 엔드포인트의 응답은 JSON 객체여야 합니다. + +`token_type`이 있어야 합니다. 여기서는 "Bearer" 토큰을 사용하므로 토큰 유형은 "`bearer`"여야 합니다. + +그리고 액세스 토큰을 포함하는 문자열과 함께 `access_token`이 있어야 합니다. + +이 간단한 예제에서는 완전히 안전하지 않고, 동일한 `username`을 토큰으로 반환합니다. + +/// tip | 팁 + +다음 장에서는 패스워드 해싱 및 JWT 토큰을 사용하여 실제 보안 구현을 볼 수 있습니다. + +하지만 지금은 필요한 세부 정보에 집중하겠습니다. + +/// + +{* ../../docs_src/security/tutorial003.py hl[85] *} + +/// tip | 팁 + +사양에 따라 이 예제와 동일하게 `access_token` 및 `token_type`이 포함된 JSON을 반환해야 합니다. + +이는 코드에서 직접 수행해야 하며 해당 JSON 키를 사용해야 합니다. + +사양을 준수하기 위해 스스로 올바르게 수행하기 위해 거의 유일하게 기억해야 하는 것입니다. + +나머지는 **FastAPI**가 처리합니다. + +/// + +## 의존성 업데이트하기 + +이제 의존성을 업데이트를 할 겁니다. + +이 사용자가 활성화되어 있는 *경우에만* `current_user`를 가져올 겁니다. + +따라서 `get_current_user`를 의존성으로 사용하는 추가 종속성 `get_current_active_user`를 만듭니다. + +이러한 의존성 모두, 사용자가 존재하지 않거나 비활성인 경우 HTTP 오류를 반환합니다. + +따라서 엔드포인트에서는 사용자가 존재하고 올바르게 인증되었으며 활성 상태인 경우에만 사용자를 얻습니다: + +{* ../../docs_src/security/tutorial003.py hl[58:66,69:72,90] *} + +/// info | 정보 + +여기서 반환하는 값이 `Bearer`인 추가 헤더 `WWW-Authenticate`도 사양의 일부입니다. + +모든 HTTP(오류) 상태 코드 401 "UNAUTHORIZED"는 `WWW-Authenticate` 헤더도 반환해야 합니다. + +베어러 토큰의 경우(지금의 경우) 해당 헤더의 값은 `Bearer`여야 합니다. + +실제로 추가 헤더를 건너뛸 수 있으며 여전히 작동합니다. + +그러나 여기에서는 사양을 준수하도록 제공됩니다. + +또한 이를 예상하고 (현재 또는 미래에) 사용하는 도구가 있을 수 있으며, 현재 또는 미래에 자신 혹은 자신의 유저들에게 유용할 것입니다. + +그것이 표준의 이점입니다 ... + +/// + +## 확인하기 + +대화형 문서 열기: http://127.0.0.1:8000/docs. + +### 인증하기 + +"Authorize" 버튼을 눌러봅시다. + +자격 증명을 사용합니다. + +유저명: `johndoe` + +패스워드: `secret` + + + +시스템에서 인증하면 다음과 같이 표시됩니다: + + + +### 자신의 유저 데이터 가져오기 + +이제 `/users/me` 경로에 `GET` 작업을 진행합시다. + +다음과 같은 사용자 데이터를 얻을 수 있습니다: + +```JSON +{ + "username": "johndoe", + "email": "johndoe@example.com", + "full_name": "John Doe", + "disabled": false, + "hashed_password": "fakehashedsecret" +} +``` + + + +잠금 아이콘을 클릭하고 로그아웃한 다음 동일한 작업을 다시 시도하면 다음과 같은 HTTP 401 오류가 발생합니다. + +```JSON +{ + "detail": "Not authenticated" +} +``` + +### 비활성된 유저 + +이제 비활성된 사용자로 시도하고, 인증해봅시다: + +유저명: `alice` + +패스워드: `secret2` + +그리고 `/users/me` 경로와 함께 `GET` 작업을 사용해 봅시다. + +다음과 같은 "Inactive user" 오류가 발생합니다: + +```JSON +{ + "detail": "Inactive user" +} +``` + +## 요약 + +이제 API에 대한 `username` 및 `password`를 기반으로 완전한 보안 시스템을 구현할 수 있는 도구가 있습니다. + +이러한 도구를 사용하여 보안 시스템을 모든 데이터베이스 및 모든 사용자 또는 데이터 모델과 호환되도록 만들 수 있습니다. + +유일한 오점은 아직 실제로 "안전"하지 않다는 것입니다. + +다음 장에서는 안전한 패스워드 해싱 라이브러리와 JWT 토큰을 사용하는 방법을 살펴보겠습니다. diff --git a/docs/ko/docs/tutorial/sql-databases.md b/docs/ko/docs/tutorial/sql-databases.md new file mode 100644 index 000000000..58c7017d6 --- /dev/null +++ b/docs/ko/docs/tutorial/sql-databases.md @@ -0,0 +1,360 @@ +# SQL (관계형) 데이터베이스 + +**FastAPI**에서 SQL(관계형) 데이터베이스 사용은 필수가 아닙니다. 여러분이 원하는 **어떤 데이터베이스든** 사용할 수 있습니다. + +여기서는 SQLModel을 사용하는 예제를 살펴보겠습니다. + +**SQLModel**은 SQLAlchemy와 Pydantic을 기반으로 구축되었습니다.SQLModel은 **SQL 데이터베이스**를 사용하는 FastAPI 애플리케이션에 완벽히 어울리도록 **FastAPI**의 제작자가 설계한 도구입니다. + +/// tip | 팁 + +다른 SQL 또는 NoSQL 데이터베이스 라이브러리를 사용할 수도 있습니다 (일부는 "ORM"이라고도 불립니다), FastAPI는 특정 라이브러리의 사용을 강요하지 않습니다. 😎 + +/// + +SQLModel은 SQLAlchemy를 기반으로 하므로, SQLAlchemy에서 **지원하는 모든 데이터베이스**를 손쉽게 사용할 수 있습니다(SQLModel에서도 동일하게 지원됩니다). 예를 들면: + +* PostgreSQL +* MySQL +* SQLite +* Oracle +* Microsoft SQL Server 등. + +이 예제에서는 **SQLite**를 사용합니다. SQLite는 단일 파일을 사용하고 파이썬에서 기본적으로 지원하기 때문입니다. 따라서 이 예제를 그대로 복사하여 실행할 수 있습니다. + +나중에 실제 프로덕션 애플리케이션에서는 **PostgreSQL**과 같은 데이터베이스 서버를 사용하는 것이 좋습니다. + +/// tip | 팁 + +**FastAPI**와 **PostgreSQL**를 포함하여 프론트엔드와 다양한 도구를 제공하는 공식 프로젝트 생성기가 있습니다: https://github.com/fastapi/full-stack-fastapi-template + +/// + +이 튜토리얼은 매우 간단하고 짧습니다. 데이터베이스 기본 개념, SQL, 또는 더 복잡한 기능에 대해 배우고 싶다면, SQLModel 문서를 참고하세요. + +## `SQLModel` 설치하기 + +먼저, [가상 환경](../virtual-environments.md){.internal-link target=_blank}을 생성하고 활성화한 다음, `sqlmodel`을 설치하세요: + +
+ +```console +$ pip install sqlmodel +---> 100% +``` + +
+ +## 단일 모델로 애플리케이션 생성하기 + +우선 단일 **SQLModel** 모델을 사용하여 애플리케이션의 가장 간단한 첫 번째 버전을 생성해보겠습니다. + +이후 **다중 모델**을 추가하여 보안과 유연성을 강화할 것입니다. 🤓 + +### 모델 생성하기 + +`SQLModel`을 가져오고 데이터베이스 모델을 생성합니다: + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[1:11] hl[7:11] *} + +`Hero` 클래스는 Pydantic 모델과 매우 유사합니다 (실제로 내부적으로 *Pydantic 모델이기도 합니다*). + +몇 가지 차이점이 있습니다: + +* `table=True`는 SQLModel에 이 모델이 *테이블 모델*이며, 단순한 데이터 모델이 아니라 SQL 데이터베이스의 **테이블**을 나타낸다는 것을 알려줍니다. (다른 일반적인 Pydantic 클래스처럼) 단순한 *데이터 모델*이 아닙니다. + +* `Field(primary_key=True)`는 SQLModel에 `id`가 SQL 데이터베이스의 **기본 키**임을 알려줍니다 (SQL 기본 키에 대한 자세한 내용은 SQLModel 문서를 참고하세요). + + `int | None` 유형으로 설정하면, SQLModel은 해당 열이 SQL 데이터베이스에서 `INTEGER` 유형이며 `NULLABLE` 값이어야 한다는 것을 알 수 있습니다. + +* `Field(index=True)`는 SQLModel에 해당 열에 대해 **SQL 인덱스**를 생성하도록 지시합니다. 이를 통해 데이터베이스에서 이 열으로 필터링된 데이터를 읽을 때 더 빠르게 조회할 수 있습니다. + + SQLModel은 `str`으로 선언된 항목이 SQL 데이터베이스에서 `TEXT` (또는 데이터베이스에 따라 `VARCHAR`) 유형의 열로 저장된다는 것을 인식합니다. + +### 엔진 생성하기 + +SQLModel의 `engine` (내부적으로는 SQLAlchemy `engine`)은 데이터베이스에 대한 **연결을 유지**하는 역할을 합니다. + +**하나의 단일 engine 객체**를 통해 코드 전체에서 동일한 데이터베이스에 연결할 수 있습니다. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[14:18] hl[14:15,17:18] *} + +`check_same_thread=False`를 사용하면 FastAPI에서 여러 스레드에서 동일한 SQLite 데이터베이스를 사용할 수 있습니다. 이는 **하나의 단일 요청**이 **여러 스레드**를 사용할 수 있기 때문에 필요합니다(예: 의존성에서 사용되는 경우). + +걱정하지 마세요. 코드가 구조화된 방식으로 인해, 이후에 **각 요청마다 단일 SQLModel *세션*을 사용**하도록 보장할 것입니다. 실제로 그것이 `check_same_thread`가 하려는 것입니다. + +### 테이블 생성하기 + +그 다음 `SQLModel.metadata.create_all(engine)`을 사용하여 모든 *테이블 모델*의 **테이블을 생성**하는 함수를 추가합니다. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[21:22] hl[21:22] *} + +### 세션 의존성 생성하기 + +**`Session`**은 **메모리에 객체**를 저장하고 데이터에 필요한 모든 변경 사항을 추적한 후, **`engine`을 통해** 데이터베이스와 통신합니다. + +`yield`를 사용해 FastAPI의 **의존성**을 생성하여 각 요청마다 새로운 `Session`을 제공합니다. 이는 요청당 하나의 세션만 사용되도록 보장합니다. 🤓 + +그런 다음 이 의존성을 사용하는 코드를 간소화하기 위해 `Annotated` 의존성 `SessionDep`을 생성합니다. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[25:30] hl[25:27,30] *} + +### 시작 시 데이터베이스 테이블 생성하기 + +애플리케이션 시작 시 데이터베이스 테이블을 생성합니다. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[32:37] hl[35:37] *} + +여기서는 애플리케이션 시작 이벤트 시 테이블을 생성합니다. + +프로덕션 환경에서는 애플리케이션을 시작하기 전에 실행되는 마이그레이션 스크립트를 사용할 가능성이 높습니다. 🤓 + +/// tip | 팁 + +SQLModel은 Alembic을 감싸는 마이그레이션 유틸리티를 제공할 예정입니다. 하지만 현재 Alembic을 직접 사용할 수 있습니다. + +/// + +### Hero 생성하기 + +각 SQLModel 모델은 Pydantic 모델이기도 하므로, Pydantic 모델을 사용할 수 있는 **타입 어노테이**션에서 동일하게 사용할 수 있습니다. + +예를 들어, 파라미터를 `Hero` 타입으로 선언하면 **JSON 본문**에서 값을 읽어옵니다. + +마찬가지로, 함수의 **반환 타입**으로 선언하면 해당 데이터의 구조가 자동으로 생성되는 API 문서의 UI에 나타납니다. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[40:45] hl[40:45] *} + + + +여기서 `SessionDep` 의존성 (즉, `Session`)을 사용하여 새로운 `Hero`를 `Session` 인스턴스에 추가하고, 데이터베이스에 변경 사항을 커밋하고, `hero` 데이터의 최신 상태를 갱신한 다음 이를 반환합니다. + +### Heroes 조회하기 + +`select()`를 사용하여 데이터베이스에서 `Hero`를 **조회**할 수 있습니다. 결과에 페이지네이션을 적용하기 위해 `limit`와 `offset`을 포함할 수 있습니다. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[48:55] hl[51:52,54] *} + +### 단일 Hero 조회하기 + +단일 `Hero`를 **조회**할 수도 있습니다. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[58:63] hl[60] *} + +### Hero 삭제하기 + +`Hero`를 **삭제**하는 것도 가능합니다. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[66:73] hl[71] *} + +### 애플리케이션 실행하기 + +애플리케이션을 실행하려면 다음 명령을 사용합니다: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +그런 다음 `/docs` UI로 이동하면, **FastAPI**가 해당 **model들**을 사용하여 API **문서를 생성**하는 것으르 확인할 수 있습니다. 또한 이 모델들은 데이터를 직렬화하고 검증하는 데에도 사용됩니다. + +
+ +
+ +## 여러 모델로 애플리케이션 업데이트 + +이제 애플리케이션을 약간 **리팩토링**하여 **보안**과 **유연성**을 개선해 보겠습니다. + +이전 애플리케이션의 UI를 보면, 지금까지는 클라이언트가 생성할 `Hero`의 `id`를 직접 지정할 수 있다는 것을 알 수 있습니다. 😱 + +이는 허용되어선 안 됩니다. 클라이언트가 이미 데이터베이스에 저장된 `id`를 덮어쓸 위험이 있기 때문입니다. `id`는 **백엔드** 또는 **데이터베이스**가 결정해야 하며, **클라이언트**가 결정해서는 안 됩니다. + +또한 hero의 `secret_name`을 생성하긴 했지만, 지금까지는 이 값을 어디에서나 반환하고 있습니다. 이는 그다지 **비밀스럽지** 않습니다... 😅 + +이러한 문제를 해결하기 위해 몇 가지 **추가 모델**을 추가할 것입니다. 바로 여기서 SQLModel이 빛을 발하게 됩니다. ✨ + +### 여러 모델 생성하기 + +**SQLModel**에서 `table=True`가 설정된 모델 클래스는 **테이블 모델**입니다. + +`table=True`가 없는 모델 클래스는 **데이터 모델**로, 이는 실제로 몇 가지 추가 기능이 포함된 Pydantic 모델에 불과합니다. 🤓 + +SQLModel을 사용하면 **상속**을 통해 모든 경우에 필드를 **중복 선언하지 않아도** 됩니다. + +#### `HeroBase` - 기본 클래스 + +모든 모델에서 **공유되는 필드**를 가진 `HeroBase` 모델을 시작해 봅시다: + +* `name` +* `age` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:9] hl[7:9] *} + +#### `Hero` - *테이블 모델* + +다음으로 실제 *테이블 모델*인 `Hero`를 생성합니다. 이 모델은 다른 모델에는 항상 포함되는 건 아닌 **추가 필드**를 포함합니다: + +* `id` +* `secret_name` + +`Hero`는 `HeroBase`를 상속하므로 `HeroBase`에 선언된 필드도 포함합니다. 따라서 `Hero`는 다음 **필드들도** 가지게 됩니다: + +* `id` +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:14] hl[12:14] *} + +#### `HeroPublic` - 공개 *데이터 모델* + +다음으로 `HeroPublic` 모델을 생성합니다. 이 모델은 API 클라이언트에 **반환**되는 모델입니다. + +`HeroPublic`은 `HeroBase`와 동일한 필드를 가지며, `secret_name`은 포함하지 않습니다. + +마침내 우리의 heroes의 정체가 보호됩니다! 🥷 + +또한 `id: int`를 다시 선언합니다. 이를 통해, API 클라이언트와 **계약**을 맺어 `id`가 항상 존재하며 항상 `int` 타입이라는 것을 보장합니다(`None`이 될 수 없습니다). + +/// tip | 팁 + +반환 모델이 값이 항상 존재하고 항상 `int`(`None`이 아님)를 보장하는 것은 API 클라이언트에게 매우 유용합니다. 이를 통해 API와 통신하는 개발자가 훨씬 더 간단한 코드를 작성할 수 있습니다. + +또한 **자동으로 생성된 클라이언트**는 더 단순한 인터페이스를 제공하므로, API와 소통하는 개발자들이 훨씬 수월하게 작업할 수 있습니다. 😎 + +/// + +`HeroPublic`의 모든 필드는 `HeroBase`와 동일하며, `id`는 `int`로 선언됩니다(`None`이 아님): + +* `id` +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:18] hl[17:18] *} + +#### `HeroCreate` - hero 생성용 *데이터 모델* + +이제 `HeroCreate` 모델을 생성합니다. 이 모델은 클라이언트로부터 받은 데이터를 **검증**하는 역할을 합니다. + +`HeroCreate`는 `HeroBase와` 동일한 필드를 가지며, 추가로 `secret_name을` 포함합니다. + +클라이언트가 **새 hero을 생성**할 때 `secret_name`을 보내고, 이는 데이터베이스에 저장되지만, 해당 비밀 이름은 API를 통해 클라이언트에게 반환되지 않습니다. + +/// tip | 팁 + +이 방식은 **비밀번호**를 처리하는 방법과 동일합니다. 비밀번호를 받지만, 이를 API에서 반환하지는 않습니다. + +비밀번호 값을 저장하기 전에 **해싱**하여 저장하고, **평문으로 저장하지 마십시오**. + +/// + +`HeroCreate`의 필드는 다음과 같습니다: + +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:22] hl[21:22] *} + +#### `HeroUpdate` - hero 수정용 *데이터 모델* + +이전 애플리케이션에서는 **hero를 수정**할 방법이 없었지만, 이제 **다중 모델**을 통해 수정 기능을 추가할 수 있습니다. 🎉 + +`HeroUpdate` *데이터 모델*은 약간 특별한데, 새 hero을 생성할 때 필요한 **모든 동일한 필드**를 가지지만, 모든 필드가 **선택적**(기본값이 있음)입니다. 이렇게 하면 hero을 수정할 때 수정하려는 필드만 보낼 수 있습니다. + +모든 **필드가 변경되기** 때문에(타입이 `None`을 포함하고, 기본값이 `None`으로 설정됨), 모든 필드를 **다시 선언**해야 합니다. + +엄밀히 말하면 `HeroBase`를 상속할 필요는 없습니다. 모든 필드를 다시 선언하기 때문입니다. 일관성을 위해 상속을 유지하긴 했지만, 필수는 아닙니다. 이는 개인적인 취향의 문제입니다. 🤷 + +`HeroUpdate`의 필드는 다음과 같습니다: + +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:28] hl[25:28] *} + +### `HeroCreate`로 생성하고 `HeroPublic` 반환하기 + +이제 **다중 모델**을 사용하므로 애플리케이션의 관련 부분을 업데이트할 수 있습니다. + +요청에서 `HeroCreate` *데이터 모델*을 받아 이를 기반으로 `Hero` *테이블 모델*을 생성합니다. + +이 새 *테이블 모델* `Hero`는 클라이언트에서 보낸 필드를 가지며, 데이터베이스에서 생성된 `id`도 포함합니다. + +그런 다음 함수를 통해 동일한 *테이블 모델* `Hero`를 반환합니다. 하지만 `response_model`로 `HeroPublic` *데이터 모델*을 선언했기 때문에, **FastAPI**는 `HeroPublic`을 사용하여 데이터를 검증하고 직렬화합니다. + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[56:62] hl[56:58] *} + +/// tip | 팁 + +이제 **반환 타입 주석** `-> HeroPublic` 대신 `response_model=HeroPublic`을 사용합니다. 반환하는 값이 실제로 `HeroPublic`이 *아니기* 때문입니다. + +만약 `-> HeroPublic`으로 선언했다면, 에디터와 린터에서 반환값이 `HeroPublic`이 아니라 `Hero`라고 경고했을 것입니다. 이는 적절한 경고입니다. + +`response_model`에 선언함으로써 **FastAPI**가 이를 처리하도록 하고, 타입 어노테이션과 에디터 및 다른 도구의 도움에는 영향을 미치지 않도록 설정합니다. + +/// + +### `HeroPublic`으로 Heroes 조회하기 + +이전과 동일하게 `Hero`를 **조회**할 수 있습니다. 이번에도 `response_model=list[HeroPublic]`을 사용하여 데이터가 올바르게 검증되고 직렬화되도록 보장합니다. + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[65:72] hl[65] *} + +### `HeroPublic`으로 단일 Hero 조회하기 + +단일 hero을 **조회**할 수도 있습니다: + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[75:80] hl[77] *} + +### `HeroUpdate`로 Hero 수정하기 + +**hero를 수정**할 수도 있습니다. 이를 위해 HTTP `PATCH` 작업을 사용합니다. + +코드에서는 클라이언트가 보낸 데이터를 딕셔너리 형태(`dict`)로 가져옵니다. 이는 **클라이언트가 보낸 데이터만 포함**하며, 기본값으로 들어가는 값은 제외합니다. 이를 위해 `exclude_unset=True`를 사용합니다. 이것이 주요 핵심입니다. 🪄 + +그런 다음, `hero_db.sqlmodel_update(hero_data)`를 사용하여 `hero_data`의 데이터를 `hero_db`에 업데이트합니다. + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[83:93] hl[83:84,88:89] *} + +### Hero 다시 삭제하기 + +hero **삭제**는 이전과 거의 동일합니다. + +이번에는 모든 것을 리팩토링하고 싶은 욕구를 만족시키지 못할 것 같습니다. 😅 + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[96:103] hl[101] *} + +### 애플리케이션 다시 실행하기 + +다음 명령을 사용해 애플리케이션을 다시 실행할 수 있습니다: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +`/docs` API UI로 이동하면 업데이트된 것을 확인할 수 있습니다. 클라이언트가 영웅을 생성할 때 `id`를 제공할 필요가 없게 되는 등의 변화도 보입니다. + +
+ +
+ +## 요약 + +**SQLModel**을 사용하여 SQL 데이터베이스와 상호작용하고, *데이터 모델* 및 *테이블 모델*로 코드를 간소화할 수 있습니다. + +더 많은 내용을 배우고 싶다면, **SQLModel** 문서를 참고하세요. SQLModel을 **FastAPI**와 함께 사용하는 것에 대한 더 긴 미니 튜토리얼도 제공합니다. 🚀 diff --git a/docs/ko/docs/tutorial/static-files.md b/docs/ko/docs/tutorial/static-files.md new file mode 100644 index 000000000..9db5e1c67 --- /dev/null +++ b/docs/ko/docs/tutorial/static-files.md @@ -0,0 +1,41 @@ +# 정적 파일 + +'StaticFiles'를 사용하여 디렉토리에서 정적 파일을 자동으로 제공할 수 있습니다. + +## `StaticFiles` 사용 + +* `StaticFiles` 임포트합니다. +* 특정 경로에 `StaticFiles()` 인스턴스를 "마운트" 합니다. + +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} + +/// note | 기술적 세부사항 + +`from starlette.staticfiles import StaticFiles` 를 사용할 수도 있습니다. + +**FastAPI**는 단지 개발자인, 당신에게 편의를 제공하기 위해 `fastapi.static files` 와 동일한 `starlett.static files`를 제공합니다. 하지만 사실 이것은 Starlett에서 직접 온 것입니다. + +/// + +### "마운팅" 이란 + +"마운팅"은 특정 경로에 완전히 "독립적인" 애플리케이션을 추가하는 것을 의미하는데, 그 후 모든 하위 경로에 대해서도 적용됩니다. + +마운트된 응용 프로그램은 완전히 독립적이기 때문에 `APIRouter`를 사용하는 것과는 다릅니다. OpenAPI 및 응용 프로그램의 문서는 마운트된 응용 프로그램 등에서 어떤 것도 포함하지 않습니다. + +자세한 내용은 **숙련된 사용자 안내서**에서 확인할 수 있습니다. + +## 세부사항 + +첫 번째 `"/static"`은 이 "하위 응용 프로그램"이 "마운트"될 하위 경로를 가리킵니다. 따라서 `"/static"`으로 시작하는 모든 경로는 `"/static"`으로 처리됩니다. + +`'directory="static"`은 정적 파일이 들어 있는 디렉토리의 이름을 나타냅니다. + +`name="static"`은 **FastAPI**에서 내부적으로 사용할 수 있는 이름을 제공합니다. + +이 모든 매개변수는 "`static`"과 다를 수 있으며, 사용자 응용 프로그램의 요구 사항 및 구체적인 세부 정보에 따라 매개변수를 조정할 수 있습니다. + + +## 추가 정보 + +자세한 내용과 선택 사항을 보려면 Starlette의 정적 파일에 관한 문서를 확인하십시오. diff --git a/docs/ko/docs/tutorial/testing.md b/docs/ko/docs/tutorial/testing.md new file mode 100644 index 000000000..a483cbf00 --- /dev/null +++ b/docs/ko/docs/tutorial/testing.md @@ -0,0 +1,243 @@ +# 테스팅 + +Starlette 덕분에 **FastAPI** 를 테스트하는 일은 쉽고 즐거운 일이 되었습니다. + +Starlette는 HTTPX를 기반으로 하며, 이는 Requests를 기반으로 설계되었기 때문에 매우 친숙하고 직관적입니다. + +이를 사용하면 FastAPI에서 pytest를 직접 사용할 수 있습니다. + +## `TestClient` 사용하기 + +/// info | 정보 + +`TestClient` 사용하려면, 우선 `httpx` 를 설치해야 합니다. + +[virtual environment](../virtual-environments.md){.internal-link target=_blank} 를 만들고, 활성화 시킨 뒤에 설치하세요. 예시: + +```console +$ pip install httpx +``` + +/// + +`TestClient` 를 임포트하세요. + +**FastAPI** 어플리케이션을 전달하여 `TestClient` 를 만드세요. + +이름이 `test_` 로 시작하는 함수를 만드세요(`pytest` 의 표준적인 관례입니다). + +`httpx` 를 사용하는 것과 같은 방식으로 `TestClient` 객체를 사용하세요. + +표준적인 파이썬 문법을 이용하여 확인이 필요한 곳에 간단한 `assert` 문장을 작성하세요(역시 표준적인 `pytest` 관례입니다). + +{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *} + +/// tip | 팁 + +테스트를 위한 함수는 `async def` 가 아니라 `def` 로 작성됨에 주의하세요. + +그리고 클라이언트에 대한 호출도 `await` 를 사용하지 않는 일반 호출입니다. + +이렇게 하여 복잡한 과정 없이 `pytest` 를 직접적으로 사용할 수 있습니다. + +/// + +/// note | 기술 세부사항 + +`from starlette.testclient import TestClient` 역시 사용할 수 있습니다. + +**FastAPI** 는 개발자의 편의를 위해 `starlette.testclient` 를 `fastapi.testclient` 로도 제공할 뿐입니다. 이는 단지 `Starlette` 에서 직접 가져오는지의 차이일 뿐입니다. + +/// + +/// tip | 팁 + +FastAPI 애플리케이션에 요청을 보내는 것 외에도 테스트에서 `async` 함수를 호출하고 싶다면 (예: 비동기 데이터베이스 함수), 심화 튜토리얼의 [Async Tests](../advanced/async-tests.md){.internal-link target=_blank} 를 참조하세요. + +/// + +## 테스트 분리하기 + +실제 애플리케이션에서는 테스트를 별도의 파일로 나누는 경우가 많습니다. + + +그리고 **FastAPI** 애플리케이션도 여러 파일이나 모듈 등으로 구성될 수 있습니다. + +### **FastAPI** app 파일 + +[Bigger Applications](bigger-applications.md){.internal-link target=_blank} 에 묘사된 파일 구조를 가지고 있는 것으로 가정해봅시다. + +``` +. +├── app +│   ├── __init__.py +│   └── main.py +``` + +`main.py` 파일 안에 **FastAPI** app 을 만들었습니다: + +{* ../../docs_src/app_testing/main.py *} + +### 테스트 파일 + +테스트를 위해 `test_main.py` 라는 파일을 생성할 수 있습니다. 이 파일은 동일한 Python 패키지(즉, `__init__.py` 파일이 있는 동일한 디렉터리)에 위치할 수 있습니다. + +``` hl_lines="5" +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +파일들이 동일한 패키지에 위치해 있으므로, 상대 참조를 사용하여 `main` 에서 `app` 객체를 임포트 해올 수 있습니다. + +{* ../../docs_src/app_testing/test_main.py hl[3] *} + + +...그리고 이전에 작성했던 것과 같은 테스트 코드를 작성할 수 있습니다. + +## 테스트: 확장된 예시 + +이제 위의 예시를 확장하고 더 많은 세부 사항을 추가하여 다양한 부분을 어떻게 테스트하는지 살펴보겠습니다. + +### 확장된 FastAPI 애플리케이션 파일 + +이전과 같은 파일 구조를 계속 사용해 보겠습니다. + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +이제 **FastAPI** 앱이 있는 `main.py` 파일에 몇 가지 다른 **경로 작업** 이 추가된 경우를 생각해봅시다. + +단일 오류를 반환할 수 있는 `GET` 작업이 있습니다. + +여러 다른 오류를 반환할 수 있는 `POST` 작업이 있습니다. + +두 *경로 작업* 모두 `X-Token` 헤더를 요구합니다. + +//// tab | Python 3.10+ + +```Python +{!> ../../docs_src/app_testing/app_b_an_py310/main.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python +{!> ../../docs_src/app_testing/app_b_an_py39/main.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python +{!> ../../docs_src/app_testing/app_b_an/main.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | 팁 + +될 수 있으면 `Annotated` 버전 사용을 권장합나다. + +/// + +```Python +{!> ../../docs_src/app_testing/app_b_py310/main.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | 팁 + +될 수 있으면 `Annotated` 버전 사용을 권장합나다. + +/// + +```Python +{!> ../../docs_src/app_testing/app_b/main.py!} +``` + +//// + +### 확장된 테스트 파일 + +이제는 `test_main.py` 를 확장된 테스트들로 수정할 수 있습니다: + +{* ../../docs_src/app_testing/app_b/test_main.py *} + + +클라이언트가 요청에 정보를 전달해야 하는데 방법을 모르겠다면, `httpx`에서 해당 작업을 수행하는 방법을 검색(Google)하거나, `requests`에서의 방법을 검색해보세요. HTTPX는 Requests의 디자인을 기반으로 설계되었습니다. + +그 후, 테스트에서도 동일하게 적용하면 됩니다. + +예시: + +* *경로* 혹은 *쿼리* 매개변수를 전달하려면, URL 자체에 추가한다. +* JSON 본문을 전달하려면, 파이썬 객체 (예를들면 `dict`) 를 `json` 파라미터로 전달한다. +* JSON 대신 *폼 데이터* 를 보내야한다면, `data` 파라미터를 대신 전달한다. +* *헤더* 를 전달하려면, `headers` 파라미터에 `dict` 를 전달한다. +* *쿠키* 를 전달하려면, `cookies` 파라미터에 `dict` 를 전달한다. + +백엔드로 데이터를 어떻게 보내는지 정보를 더 얻으려면 (`httpx` 혹은 `TestClient` 를 이용해서) HTTPX documentation 를 확인하세요. + +/// info | 정보 + +`TestClient` 는 Pydantic 모델이 아니라 JSON 으로 변환될 수 있는 데이터를 받습니다. + +만약 테스트중 Pydantic 모델을 어플리케이션으로에 보내고 싶다면, [JSON 호환 가능 인코더](encoder.md){.internal-link target=_blank} 에 설명되어 있는 `jsonable_encoder` 를 사용할 수 있습니다. + +/// + +## 실행하기 + +테스트 코드를 작성하고, `pytest` 를 설치해야합니다. + +[virtual environment](../virtual-environments.md){.internal-link target=_blank} 를 만들고, 활성화 시킨 뒤에 설치하세요. 예시: + +
+ +```console +$ pip install pytest + +---> 100% +``` + +
+ +`pytest` 파일과 테스트를 자동으로 감지하고 실행한 다음, 결과를 보고할 것입니다. + +테스트를 다음 명령어로 실행하세요. + +
+ +```console +$ pytest + +================ test session starts ================ +platform linux -- Python 3.6.9, pytest-5.3.5, py-1.8.1, pluggy-0.13.1 +rootdir: /home/user/code/superawesome-cli/app +plugins: forked-1.1.3, xdist-1.31.0, cov-2.8.1 +collected 6 items + +---> 100% + +test_main.py ...... [100%] + +================= 1 passed in 0.03s ================= +``` + +
diff --git a/docs/language_names.yml b/docs/language_names.yml index 7c37ff2b1..c5a15ddd9 100644 --- a/docs/language_names.yml +++ b/docs/language_names.yml @@ -178,6 +178,6 @@ xh: isiXhosa yi: ייִדיש yo: Yorùbá za: Saɯ cueŋƅ -zh: 汉语 +zh: 简体中文 zh-hant: 繁體中文 zu: isiZulu diff --git a/docs/missing-translation.md b/docs/missing-translation.md index 32b6016f9..c2882e90e 100644 --- a/docs/missing-translation.md +++ b/docs/missing-translation.md @@ -1,4 +1,7 @@ -!!! warning - The current page still doesn't have a translation for this language. +/// warning - But you can help translating it: [Contributing](https://fastapi.tiangolo.com/contributing/){.internal-link target=_blank}. +The current page still doesn't have a translation for this language. + +But you can help translating it: [Contributing](https://fastapi.tiangolo.com/contributing/){.internal-link target=_blank}. + +/// diff --git a/docs/nl/docs/environment-variables.md b/docs/nl/docs/environment-variables.md new file mode 100644 index 000000000..f6b3d285b --- /dev/null +++ b/docs/nl/docs/environment-variables.md @@ -0,0 +1,298 @@ +# Omgevingsvariabelen + +/// tip + +Als je al weet wat "omgevingsvariabelen" zijn en hoe je ze kunt gebruiken, kun je deze stap gerust overslaan. + +/// + +Een omgevingsvariabele (ook bekend als "**env var**") is een variabele die **buiten** de Python-code leeft, in het **besturingssysteem** en die door je Python-code (of door andere programma's) kan worden gelezen. + +Omgevingsvariabelen kunnen nuttig zijn voor het bijhouden van applicatie **instellingen**, als onderdeel van de **installatie** van Python, enz. + +## Omgevingsvariabelen maken en gebruiken + +Je kunt omgevingsvariabelen **maken** en gebruiken in de **shell (terminal)**, zonder dat je Python nodig hebt: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// Je zou een omgevingsvariabele MY_NAME kunnen maken met +$ export MY_NAME="Wade Wilson" + +// Dan zou je deze met andere programma's kunnen gebruiken, zoals +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// Maak een omgevingsvariabel MY_NAME +$ $Env:MY_NAME = "Wade Wilson" + +// Gebruik het met andere programma's, zoals +$ echo "Hello $Env:MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +## Omgevingsvariabelen uitlezen in Python + +Je kunt omgevingsvariabelen **buiten** Python aanmaken, in de terminal (of met een andere methode) en ze vervolgens **in Python uitlezen**. + +Je kunt bijvoorbeeld een bestand `main.py` hebben met: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// tip + +Het tweede argument van `os.getenv()` is de standaardwaarde die wordt geretourneerd. + +Als je dit niet meegeeft, is de standaardwaarde `None`. In dit geval gebruiken we standaard `"World"`. + +/// + +Dan zou je dat Python-programma kunnen aanroepen: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// Hier stellen we de omgevingsvariabelen nog niet in +$ python main.py + +// Omdat we de omgevingsvariabelen niet hebben ingesteld, krijgen we de standaardwaarde + +Hello World from Python + +// Maar als we eerst een omgevingsvariabele aanmaken +$ export MY_NAME="Wade Wilson" + +// en het programma dan opnieuw aanroepen +$ python main.py + +// kan het de omgevingsvariabele nu wel uitlezen + +Hello Wade Wilson from Python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// Hier stellen we de omgevingsvariabelen nog niet in +$ python main.py + +// Omdat we de omgevingsvariabelen niet hebben ingesteld, krijgen we de standaardwaarde + +Hello World from Python + +// Maar als we eerst een omgevingsvariabele aanmaken +$ $Env:MY_NAME = "Wade Wilson" + +// en het programma dan opnieuw aanroepen +$ python main.py + +// kan het de omgevingsvariabele nu wel uitlezen + +Hello Wade Wilson from Python +``` + +
+ +//// + +Omdat omgevingsvariabelen buiten de code kunnen worden ingesteld, maar wel door de code kunnen worden gelezen en niet hoeven te worden opgeslagen (gecommit naar `git`) met de rest van de bestanden, worden ze vaak gebruikt voor configuraties of **instellingen**. + +Je kunt ook een omgevingsvariabele maken die alleen voor een **specifieke programma-aanroep** beschikbaar is, die alleen voor dat programma beschikbaar is en alleen voor de duur van dat programma. + +Om dat te doen, maak je het vlak voor het programma zelf aan, op dezelfde regel: + +
+ +```console +// Maak een omgevingsvariabele MY_NAME in de regel voor deze programma-aanroep +$ MY_NAME="Wade Wilson" python main.py + +// Nu kan het de omgevingsvariabele lezen + +Hello Wade Wilson from Python + +// De omgevingsvariabelen bestaan daarna niet meer +$ python main.py + +Hello World from Python +``` + +
+ +/// tip + +Je kunt er meer over lezen op The Twelve-Factor App: Config. + +/// + +## Types en Validatie + +Deze omgevingsvariabelen kunnen alleen **tekstuele gegevens** verwerken, omdat ze extern zijn aan Python, compatibel moeten zijn met andere programma's en de rest van het systeem (zelfs met verschillende besturingssystemen, zoals Linux, Windows en macOS). + +Dat betekent dat **elke waarde** die in Python uit een omgevingsvariabele wordt gelezen **een `str` zal zijn** en dat elke conversie naar een ander type of elke validatie in de code moet worden uitgevoerd. + +Meer informatie over het gebruik van omgevingsvariabelen voor het verwerken van **applicatie instellingen** vind je in de [Geavanceerde gebruikershandleiding - Instellingen en Omgevingsvariabelen](./advanced/settings.md){.internal-link target=_blank}. + +## `PATH` Omgevingsvariabele + +Er is een **speciale** omgevingsvariabele met de naam **`PATH`**, die door de besturingssystemen (Linux, macOS, Windows) wordt gebruikt om programma's te vinden die uitgevoerd kunnen worden. + +De waarde van de variabele `PATH` is een lange string die bestaat uit mappen die gescheiden worden door een dubbele punt `:` op Linux en macOS en door een puntkomma `;` op Windows. + +De omgevingsvariabele `PATH` zou er bijvoorbeeld zo uit kunnen zien: + +//// tab | Linux, macOS + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +Dit betekent dat het systeem naar programma's zoekt in de mappen: + +* `/usr/local/bin` +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32 +``` + +Dit betekent dat het systeem naar programma's zoekt in de mappen: + +* `C:\Program Files\Python312\Scripts` +* `C:\Program Files\Python312` +* `C:\Windows\System32` + +//// + +Wanneer je een **opdracht** in de terminal typt, **zoekt** het besturingssysteem naar het programma in **elk van de mappen** die vermeld staan in de omgevingsvariabele `PATH`. + +Wanneer je bijvoorbeeld `python` in de terminal typt, zoekt het besturingssysteem naar een programma met de naam `python` in de **eerste map** in die lijst. + +Zodra het gevonden wordt, zal het dat programma **gebruiken**. Anders blijft het in de **andere mappen** zoeken. + +### Python installeren en `PATH` bijwerken + +Wanneer je Python installeert, word je mogelijk gevraagd of je de omgevingsvariabele `PATH` wilt bijwerken. + +//// tab | Linux, macOS + +Stel dat je Python installeert en het komt terecht in de map `/opt/custompython/bin`. + +Als je kiest om de `PATH` omgevingsvariabele bij te werken, zal het installatieprogramma `/opt/custompython/bin` toevoegen aan de `PATH` omgevingsvariabele. + +Dit zou er zo uit kunnen zien: + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin +``` + +Op deze manier zal het systeem, wanneer je `python` in de terminal typt, het Python-programma in `/opt/custompython/bin` (de laatste map) vinden en dat gebruiken. + +//// + +//// tab | Windows + +Stel dat je Python installeert en het komt terecht in de map `C:\opt\custompython\bin`. + +Als je kiest om de `PATH` omgevingsvariabele bij te werken, zal het installatieprogramma `C:\opt\custompython\bin` toevoegen aan de `PATH` omgevingsvariabele. + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin +``` + +Op deze manier zal het systeem, wanneer je `python` in de terminal typt, het Python-programma in `C:\opt\custompython\bin` (de laatste map) vinden en dat gebruiken. + +//// + +Dus als je typt: + +
+ +```console +$ python +``` + +
+ +//// tab | Linux, macOS + +Zal het systeem het `python`-programma in `/opt/custompython/bin` **vinden** en uitvoeren. + +Het zou ongeveer hetzelfde zijn als het typen van: + +
+ +```console +$ /opt/custompython/bin/python +``` + +
+ +//// + +//// tab | Windows + +Zal het systeem het `python`-programma in `C:\opt\custompython\bin\python` **vinden** en uitvoeren. + +Het zou ongeveer hetzelfde zijn als het typen van: + +
+ +```console +$ C:\opt\custompython\bin\python +``` + +
+ +//// + +Deze informatie is handig wanneer je meer wilt weten over [virtuele omgevingen](virtual-environments.md){.internal-link target=_blank}. + +## Conclusion + +Hiermee heb je basiskennis van wat **omgevingsvariabelen** zijn en hoe je ze in Python kunt gebruiken. + +Je kunt er ook meer over lezen op de Wikipedia over omgevingsvariabelen. + +In veel gevallen is het niet direct duidelijk hoe omgevingsvariabelen nuttig zijn en hoe je ze moet toepassen. Maar ze blijven in veel verschillende scenario's opduiken als je aan het ontwikkelen bent, dus het is goed om er meer over te weten. + +Je hebt deze informatie bijvoorbeeld nodig in de volgende sectie, over [Virtuele Omgevingen](virtual-environments.md). diff --git a/docs/nl/docs/features.md b/docs/nl/docs/features.md new file mode 100644 index 000000000..848b155ec --- /dev/null +++ b/docs/nl/docs/features.md @@ -0,0 +1,201 @@ +# Functionaliteit + +## FastAPI functionaliteit + +**FastAPI** biedt je het volgende: + +### Gebaseerd op open standaarden + +* OpenAPI voor het maken van API's, inclusief declaraties van padbewerkingen, parameters, request bodies, beveiliging, enz. +* Automatische datamodel documentatie met JSON Schema (aangezien OpenAPI zelf is gebaseerd op JSON Schema). +* Ontworpen op basis van deze standaarden, na zorgvuldig onderzoek. In plaats van achteraf deze laag er bovenop te bouwen. +* Dit maakt het ook mogelijk om automatisch **clientcode te genereren** in verschillende programmeertalen. + +### Automatische documentatie + +Interactieve API-documentatie en verkenning van webgebruikersinterfaces. Aangezien dit framework is gebaseerd op OpenAPI, zijn er meerdere documentatie opties mogelijk, waarvan er standaard 2 zijn inbegrepen. + +* Swagger UI, met interactieve interface, maakt het mogelijk je API rechtstreeks vanuit de browser aan te roepen en te testen. + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* Alternatieve API-documentatie met ReDoc. + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### Gewoon Moderne Python + +Het is allemaal gebaseerd op standaard **Python type** declaraties (dankzij Pydantic). Je hoeft dus geen nieuwe syntax te leren. Het is gewoon standaard moderne Python. + +Als je een opfriscursus van 2 minuten nodig hebt over het gebruik van Python types (zelfs als je FastAPI niet gebruikt), bekijk dan deze korte tutorial: [Python Types](python-types.md){.internal-link target=_blank}. + +Je schrijft gewoon standaard Python met types: + +```Python +from datetime import date + +from pydantic import BaseModel + +# Declareer een variabele als een str +# en krijg editorondersteuning in de functie +def main(user_id: str): + return user_id + + +# Een Pydantic model +class User(BaseModel): + id: int + name: str + joined: date +``` + +Vervolgens kan je het op deze manier gebruiken: + +```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) +``` + +/// info + +`**second_user_data` betekent: + +Geef de sleutels (keys) en waarden (values) van de `second_user_data` dict direct door als sleutel-waarden argumenten, gelijk aan: `User(id=4, name=“Mary”, joined=“2018-11-30”)` + +/// + +### Editor-ondersteuning + +Het gehele framework is ontworpen om eenvoudig en intuïtief te zijn in gebruik. Alle beslissingen zijn getest op meerdere code-editors nog voordat het daadwerkelijke ontwikkelen begon, om zo de beste ontwikkelervaring te garanderen. + +Uit enquêtes onder Python ontwikkelaars blijkt maar al te duidelijk dat "(automatische) code aanvulling" een van de meest gebruikte functionaliteiten is. + +Het hele **FastAPI** framework is daarop gebaseerd. Automatische code aanvulling werkt overal. + +Je hoeft zelden terug te vallen op de documentatie. + +Zo kan je editor je helpen: + +* in Visual Studio Code: + +![editor ondersteuning](https://fastapi.tiangolo.com/img/vscode-completion.png) + +* in PyCharm: + +![editor ondersteuning](https://fastapi.tiangolo.com/img/pycharm-completion.png) + +Je krijgt autocomletion die je voorheen misschien zelfs voor onmogelijk had gehouden. Zoals bijvoorbeeld de `price` key in een JSON body (die genest had kunnen zijn) die afkomstig is van een request. + +Je hoeft niet langer de verkeerde keys in te typen, op en neer te gaan tussen de documentatie, of heen en weer te scrollen om te checken of je `username` of toch `user_name` had gebruikt. + +### Kort + +Dit framework heeft voor alles verstandige **standaardinstellingen**, met overal optionele configuraties. Alle parameters kunnen worden verfijnd zodat het past bij wat je nodig hebt, om zo de API te kunnen definiëren die jij nodig hebt. + +Maar standaard werkt alles **“gewoon”**. + +### Validatie + +* Validatie voor de meeste (of misschien wel alle?) Python **datatypes**, inclusief: + * JSON objecten (`dict`). + * JSON array (`list`) die itemtypes definiëren. + * String (`str`) velden, die min en max lengtes hebben. + * Getallen (`int`, `float`) met min en max waarden, enz. + +* Validatie voor meer exotische typen, zoals: + * URL. + * E-mail. + * UUID. + * ...en anderen. + +Alle validatie wordt uitgevoerd door het beproefde en robuuste **Pydantic**. + +### Beveiliging en authenticatie + +Beveiliging en authenticatie is geïntegreerd. Zonder compromissen te doen naar databases of datamodellen. + +Alle beveiligingsschema's gedefinieerd in OpenAPI, inclusief: + +* HTTP Basic. +* **OAuth2** (ook met **JWT tokens**). Bekijk de tutorial over [OAuth2 with JWT](tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. +* API keys in: + * Headers. + * Query parameters. + * Cookies, enz. + +Plus alle beveiligingsfuncties van Starlette (inclusief **sessiecookies**). + +Gebouwd als een herbruikbare tool met componenten die makkelijk te integreren zijn in en met je systemen, datastores, relationele en NoSQL databases, enz. + +### Dependency Injection + +FastAPI bevat een uiterst eenvoudig, maar uiterst krachtig Dependency Injection systeem. + +* Zelfs dependencies kunnen dependencies hebben, waardoor een hiërarchie of **“graph” van dependencies** ontstaat. +* Allemaal **automatisch afgehandeld** door het framework. +* Alle dependencies kunnen data nodig hebben van request, de vereiste **padoperaties veranderen** en automatische documentatie verstrekken. +* **Automatische validatie** zelfs voor *padoperatie* parameters gedefinieerd in dependencies. +* Ondersteuning voor complexe gebruikersauthenticatiesystemen, **databaseverbindingen**, enz. +* **Geen compromisen** met databases, gebruikersinterfaces, enz. Maar eenvoudige integratie met ze allemaal. + +### Ongelimiteerde "plug-ins" + +Of anders gezegd, je hebt ze niet nodig, importeer en gebruik de code die je nodig hebt. + +Elke integratie is ontworpen om eenvoudig te gebruiken (met afhankelijkheden), zodat je een “plug-in" kunt maken in 2 regels code, met dezelfde structuur en syntax die wordt gebruikt voor je *padbewerkingen*. + +### Getest + +* 100% van de code is getest. +* 100% type geannoteerde codebase. +* Wordt gebruikt in productietoepassingen. + +## Starlette functies + +**FastAPI** is volledig verenigbaar met (en gebaseerd op) Starlette. + +`FastAPI` is eigenlijk een subklasse van `Starlette`. Dus als je Starlette al kent of gebruikt, zal de meeste functionaliteit op dezelfde manier werken. + +Met **FastAPI** krijg je alle functies van **Starlette** (FastAPI is gewoon Starlette op steroïden): + +* Zeer indrukwekkende prestaties. Het is een van de snelste Python frameworks, vergelijkbaar met **NodeJS** en **Go**. +* **WebSocket** ondersteuning. +* Taken in de achtergrond tijdens het proces. +* Opstart- en afsluit events. +* Test client gebouwd op HTTPX. +* **CORS**, GZip, Statische bestanden, Streaming reacties. +* **Sessie en Cookie** ondersteuning. +* 100% van de code is getest. +* 100% type geannoteerde codebase. + +## Pydantic functionaliteit + +**FastAPI** is volledig verenigbaar met (en gebaseerd op) Pydantic. Dus alle extra Pydantic code die je nog hebt werkt ook. + +Inclusief externe pakketten die ook gebaseerd zijn op Pydantic, zoals ORMs, ODMs voor databases. + +Dit betekent ook dat je in veel gevallen het object dat je van een request krijgt **direct naar je database** kunt sturen, omdat alles automatisch wordt gevalideerd. + +Hetzelfde geldt ook andersom, in veel gevallen kun je dus het object dat je krijgt van de database **direct doorgeven aan de client**. + +Met **FastAPI** krijg je alle functionaliteit van **Pydantic** (omdat FastAPI is gebaseerd op Pydantic voor alle dataverwerking): + +* **Geen brainfucks**: + * Je hoeft geen nieuwe microtaal voor schemadefinities te leren. + * Als je bekend bent Python types, weet je hoe je Pydantic moet gebruiken. +* Werkt goed samen met je **IDE/linter/hersenen**: + * Doordat pydantic's datastructuren enkel instanties zijn van klassen, die je definieert, werkt automatische aanvulling, linting, mypy en je intuïtie allemaal goed met je gevalideerde data. +* Valideer **complexe structuren**: + * Gebruik van hiërarchische Pydantic modellen, Python `typing`'s `List` en `Dict`, enz. + * Met validators kunnen complexe dataschema's duidelijk en eenvoudig worden gedefinieerd, gecontroleerd en gedocumenteerd als JSON Schema. + * Je kunt diep **geneste JSON** objecten laten valideren en annoteren. +* **Uitbreidbaar**: + * Met Pydantic kunnen op maat gemaakte datatypen worden gedefinieerd of je kunt validatie uitbreiden met methoden op een model dat is ingericht met de decorator validator. +* 100% van de code is getest. diff --git a/docs/nl/docs/index.md b/docs/nl/docs/index.md new file mode 100644 index 000000000..32b20e31e --- /dev/null +++ b/docs/nl/docs/index.md @@ -0,0 +1,494 @@ +# FastAPI + + + +

+ FastAPI +

+

+ FastAPI framework, zeer goede prestaties, eenvoudig te leren, snel te programmeren, klaar voor productie +

+

+ + Test + + + Coverage + + + Package version + + + Supported Python versions + +

+ +--- + +**Documentatie**: https://fastapi.tiangolo.com + +**Broncode**: https://github.com/tiangolo/fastapi + +--- + +FastAPI is een modern, snel (zeer goede prestaties), web framework voor het bouwen van API's in Python, gebruikmakend van standaard Python type-hints. + +De belangrijkste kenmerken zijn: + +* **Snel**: Zeer goede prestaties, vergelijkbaar met **NodeJS** en **Go** (dankzij Starlette en Pydantic). [Een van de snelste beschikbare Python frameworks](#prestaties). +* **Snel te programmeren**: Verhoog de snelheid om functionaliteit te ontwikkelen met ongeveer 200% tot 300%. * +* **Minder bugs**: Verminder ongeveer 40% van de door mensen (ontwikkelaars) veroorzaakte fouten. * +* **Intuïtief**: Buitengewoon goede ondersteuning voor editors. Overal automische code aanvulling. Minder tijd kwijt aan debuggen. +* **Eenvoudig**: Ontworpen om gemakkelijk te gebruiken en te leren. Minder tijd nodig om documentatie te lezen. +* **Kort**: Minimaliseer codeduplicatie. Elke parameterdeclaratie ondersteunt meerdere functionaliteiten. Minder bugs. +* **Robust**: Code gereed voor productie. Met automatische interactieve documentatie. +* **Standards-based**: Gebaseerd op (en volledig verenigbaar met) open standaarden voor API's: OpenAPI (voorheen bekend als Swagger) en JSON Schema. + +* schatting op basis van testen met een intern ontwikkelteam en bouwen van productieapplicaties. + +## Sponsors + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} + +{% endfor -%} +{%- for sponsor in sponsors.silver -%} + +{% endfor %} +{% endif %} + + + +Overige sponsoren + +## Meningen + +"_[...] Ik gebruik **FastAPI** heel vaak tegenwoordig. [...] Ik ben van plan om het te gebruiken voor alle **ML-services van mijn team bij Microsoft**. Sommige van deze worden geïntegreerd in het kernproduct van **Windows** en sommige **Office**-producten._" + +
Kabir Khan - Microsoft (ref)
+ +--- + +"_We hebben de **FastAPI** library gebruikt om een **REST** server te maken die bevraagd kan worden om **voorspellingen** te maken. [voor Ludwig]_" + +
Piero Molino, Yaroslav Dudin en Sai Sumanth Miryala - Uber (ref)
+ +--- + +"_**Netflix** is verheugd om een open-source release aan te kondigen van ons **crisismanagement**-orkestratieframework: **Dispatch**! [gebouwd met **FastAPI**]_" + +
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (ref)
+ +--- + +"_Ik ben super enthousiast over **FastAPI**. Het is zo leuk!_" + +
Brian Okken - Python Bytes podcast presentator (ref)
+ +--- + +"_Wat je hebt gebouwd ziet er echt super solide en gepolijst uit. In veel opzichten is het wat ik wilde dat **Hug** kon zijn - het is echt inspirerend om iemand dit te zien bouwen._" + +
Timothy Crosley - Hug creator (ref)
+ +--- + +"Wie geïnteresseerd is in een **modern framework** voor het bouwen van REST API's, bekijkt best eens **FastAPI** [...] Het is snel, gebruiksvriendelijk en gemakkelijk te leren [...]_" + +"_We zijn overgestapt naar **FastAPI** voor onze **API's** [...] Het gaat jou vast ook bevallen [...]_" + +
Ines Montani - Matthew Honnibal - Explosion AI oprichters - spaCy ontwikkelaars (ref) - (ref)
+ +--- + +"_Wie een Python API wil bouwen voor productie, kan ik ten stelligste **FastAPI** aanraden. Het is **prachtig ontworpen**, **eenvoudig te gebruiken** en **gemakkelijk schaalbaar**, het is een **cruciale component** geworden in onze strategie om API's centraal te zetten, en het vereenvoudigt automatisering en diensten zoals onze Virtual TAC Engineer._" + +
Deon Pillsbury - Cisco (ref)
+ +--- + +## **Typer**, de FastAPI van CLIs + + + +Als je een CLI-app bouwt die in de terminal moet worden gebruikt in plaats van een web-API, gebruik dan **Typer**. + +**Typer** is het kleine broertje van FastAPI. En het is bedoeld als de **FastAPI van CLI's**. ️ + +## Vereisten + +FastAPI staat op de schouders van reuzen: + +* Starlette voor de webonderdelen. +* Pydantic voor de datadelen. + +## Installatie + +
+ +```console +$ pip install "fastapi[standard]" + +---> 100% +``` + +
+ +**Opmerking**: Zet `"fastapi[standard]"` tussen aanhalingstekens om ervoor te zorgen dat het werkt in alle terminals. + +## Voorbeeld + +### Creëer het + +* Maak het bestand `main.py` aan met daarin: + +```Python +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@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} +``` + +
+Of maak gebruik van async def... + +Als je code gebruik maakt van `async` / `await`, gebruik dan `async def`: + +```Python hl_lines="9 14" +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +async def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +async def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +**Opmerking**: + +Als je het niet weet, kijk dan in het gedeelte _"Heb je haast?"_ over `async` en `await` in de documentatie. + +
+ +### Voer het uit + +Run de server met: + +
+ +```console +$ fastapi dev main.py + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + │ fastapi run │ + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [2248755] using WatchFiles +INFO: Started server process [2248757] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +
+Over het commando fastapi dev main.py... + +Het commando `fastapi dev` leest het `main.py` bestand, detecteert de **FastAPI** app, en start een server met Uvicorn. + +Standaard zal dit commando `fastapi dev` starten met "auto-reload" geactiveerd voor ontwikkeling op het lokale systeem. + +Je kan hier meer over lezen in de FastAPI CLI documentatie. + +
+ +### Controleer het + +Open je browser op http://127.0.0.1:8000/items/5?q=somequery. + +Je zult een JSON response zien: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +Je hebt een API gemaakt die: + +* HTTP verzoeken kan ontvangen op de _paden_ `/` en `/items/{item_id}`. +* Beide _paden_ hebben `GET` operaties (ook bekend als HTTP _methoden_). +* Het _pad_ `/items/{item_id}` heeft een _pad parameter_ `item_id` dat een `int` moet zijn. +* Het _pad_ `/items/{item_id}` heeft een optionele `str` _query parameter_ `q`. + +### Interactieve API documentatie + +Ga naar http://127.0.0.1:8000/docs. + +Je ziet de automatische interactieve API documentatie (verstrekt door Swagger UI): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### Alternatieve API documentatie + +Ga vervolgens naar http://127.0.0.1:8000/redoc. + +Je ziet de automatische interactieve API documentatie (verstrekt door ReDoc): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## Voorbeeld upgrade + +Pas nu het bestand `main.py` aan om de body van een `PUT` request te ontvangen. + +Dankzij Pydantic kunnen we de body declareren met standaard Python types. + +```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} +``` + +De `fastapi dev` server zou automatisch moeten herladen. + +### Interactieve API documentatie upgrade + +Ga nu naar http://127.0.0.1:8000/docs. + +* De interactieve API-documentatie wordt automatisch bijgewerkt, inclusief de nieuwe body: + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* Klik op de knop "Try it out", hiermee kan je de parameters invullen en direct met de API interacteren: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) + +* Klik vervolgens op de knop "Execute", de gebruikersinterface zal communiceren met jouw API, de parameters verzenden, de resultaten ophalen en deze op het scherm tonen: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) + +### Alternatieve API documentatie upgrade + +Ga vervolgens naar http://127.0.0.1:8000/redoc. + +* De alternatieve documentatie zal ook de nieuwe queryparameter en body weergeven: + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### Samenvatting + +Samengevat declareer je **eenmalig** de types van parameters, body, etc. als functieparameters. + +Dat doe je met standaard moderne Python types. + +Je hoeft geen nieuwe syntax te leren, de methods of klassen van een specifieke bibliotheek, etc. + +Gewoon standaard **Python**. + +Bijvoorbeeld, voor een `int`: + +```Python +item_id: int +``` + +of voor een complexer `Item` model: + +```Python +item: Item +``` + +...en met die ene verklaring krijg je: + +* Editor ondersteuning, inclusief: + * Code aanvulling. + * Type validatie. +* Validatie van data: + * Automatische en duidelijke foutboodschappen wanneer de data ongeldig is. + * Validatie zelfs voor diep geneste JSON objecten. +* Conversie van invoergegevens: afkomstig van het netwerk naar Python-data en -types. Zoals: + * JSON. + * Pad parameters. + * Query parameters. + * Cookies. + * Headers. + * Formulieren. + * Bestanden. +* Conversie van uitvoergegevens: converstie van Python-data en -types naar netwerkgegevens (zoals JSON): + * Converteer Python types (`str`, `int`, `float`, `bool`, `list`, etc). + * `datetime` objecten. + * `UUID` objecten. + * Database modellen. + * ...en nog veel meer. +* Automatische interactieve API-documentatie, inclusief 2 alternatieve gebruikersinterfaces: + * Swagger UI. + * ReDoc. + +--- + +Terugkomend op het vorige code voorbeeld, **FastAPI** zal: + +* Valideren dat er een `item_id` bestaat in het pad voor `GET` en `PUT` verzoeken. +* Valideren dat het `item_id` van het type `int` is voor `GET` en `PUT` verzoeken. + * Wanneer dat niet het geval is, krijgt de cliënt een nuttige, duidelijke foutmelding. +* Controleren of er een optionele query parameter is met de naam `q` (zoals in `http://127.0.0.1:8000/items/foo?q=somequery`) voor `GET` verzoeken. + * Aangezien de `q` parameter werd gedeclareerd met `= None`, is deze optioneel. + * Zonder de `None` declaratie zou deze verplicht zijn (net als bij de body in het geval met `PUT`). +* Voor `PUT` verzoeken naar `/items/{item_id}`, lees de body als JSON: + * Controleer of het een verplicht attribuut `naam` heeft en dat dat een `str` is. + * Controleer of het een verplicht attribuut `price` heeft en dat dat een`float` is. + * Controleer of het een optioneel attribuut `is_offer` heeft, dat een `bool` is wanneer het aanwezig is. + * Dit alles werkt ook voor diep geneste JSON objecten. +* Converteer automatisch van en naar JSON. +* Documenteer alles met OpenAPI, dat gebruikt kan worden door: + * Interactieve documentatiesystemen. + * Automatische client code generatie systemen, voor vele talen. +* Biedt 2 interactieve documentatie-webinterfaces aan. + +--- + +Dit was nog maar een snel overzicht, maar je zou nu toch al een idee moeten hebben over hoe het allemaal werkt. + +Probeer deze regel te veranderen: + +```Python + return {"item_name": item.name, "item_id": item_id} +``` + +...van: + +```Python + ... "item_name": item.name ... +``` + +...naar: + +```Python + ... "item_price": item.price ... +``` + +...en zie hoe je editor de attributen automatisch invult en hun types herkent: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +Voor een vollediger voorbeeld met meer mogelijkheden, zie de Tutorial - Gebruikershandleiding. + +**Spoiler alert**: de tutorial - gebruikershandleiding bevat: + +* Declaratie van **parameters** op andere plaatsen zoals: **headers**, **cookies**, **formuliervelden** en **bestanden**. +* Hoe stel je **validatie restricties** in zoals `maximum_length` of een `regex`. +* Een zeer krachtig en eenvoudig te gebruiken **Dependency Injection** systeem. +* Beveiliging en authenticatie, inclusief ondersteuning voor **OAuth2** met **JWT-tokens** en **HTTP Basic** auth. +* Meer geavanceerde (maar even eenvoudige) technieken voor het declareren van **diep geneste JSON modellen** (dankzij Pydantic). +* **GraphQL** integratie met Strawberry en andere packages. +* Veel extra functies (dankzij Starlette) zoals: + * **WebSockets** + * uiterst gemakkelijke tests gebaseerd op HTTPX en `pytest` + * **CORS** + * **Cookie Sessions** + * ...en meer. + +## Prestaties + +Onafhankelijke TechEmpower benchmarks tonen **FastAPI** applicaties draaiend onder Uvicorn aan als een van de snelste Python frameworks beschikbaar, alleen onder Starlette en Uvicorn zelf (intern gebruikt door FastAPI). (*) + +Zie de sectie Benchmarks om hier meer over te lezen. + +## Afhankelijkheden + +FastAPI maakt gebruik van Pydantic en Starlette. + +### `standard` Afhankelijkheden + +Wanneer je FastAPI installeert met `pip install "fastapi[standard]"`, worden de volgende `standard` optionele afhankelijkheden geïnstalleerd: + +Gebruikt door Pydantic: + +* email_validator - voor email validatie. + +Gebruikt door Starlette: + +* httpx - Vereist indien je de `TestClient` wil gebruiken. +* jinja2 - Vereist als je de standaard templateconfiguratie wil gebruiken. +* python-multipart - Vereist indien je "parsen" van formulieren wil ondersteunen met `requests.form()`. + +Gebruikt door FastAPI / Starlette: + +* uvicorn - voor de server die jouw applicatie laadt en bedient. +* `fastapi-cli` - om het `fastapi` commando te voorzien. + +### Zonder `standard` Afhankelijkheden + +Indien je de optionele `standard` afhankelijkheden niet wenst te installeren, kan je installeren met `pip install fastapi` in plaats van `pip install "fastapi[standard]"`. + +### Bijkomende Optionele Afhankelijkheden + +Er zijn nog een aantal bijkomende afhankelijkheden die je eventueel kan installeren. + +Bijkomende optionele afhankelijkheden voor Pydantic: + +* pydantic-settings - voor het beheren van settings. +* pydantic-extra-types - voor extra data types die gebruikt kunnen worden met Pydantic. + +Bijkomende optionele afhankelijkheden voor FastAPI: + +* orjson - Vereist indien je `ORJSONResponse` wil gebruiken. +* ujson - Vereist indien je `UJSONResponse` wil gebruiken. + +## Licentie + +Dit project is gelicenseerd onder de voorwaarden van de MIT licentie. diff --git a/docs/nl/docs/python-types.md b/docs/nl/docs/python-types.md new file mode 100644 index 000000000..fb8b1e5fd --- /dev/null +++ b/docs/nl/docs/python-types.md @@ -0,0 +1,587 @@ +# Introductie tot Python Types + +Python biedt ondersteuning voor optionele "type hints" (ook wel "type annotaties" genoemd). + +Deze **"type hints"** of annotaties zijn een speciale syntax waarmee het type van een variabele kan worden gedeclareerd. + +Door types voor je variabelen te declareren, kunnen editors en hulpmiddelen je beter ondersteunen. + +Dit is slechts een **korte tutorial/opfrisser** over Python type hints. Het behandelt enkel het minimum dat nodig is om ze te gebruiken met **FastAPI**... en dat is relatief weinig. + +**FastAPI** is helemaal gebaseerd op deze type hints, ze geven veel voordelen. + +Maar zelfs als je **FastAPI** nooit gebruikt, heb je er baat bij om er iets over te leren. + +/// note + +Als je een Python expert bent en alles al weet over type hints, sla dan dit hoofdstuk over. + +/// + +## Motivatie + +Laten we beginnen met een eenvoudig voorbeeld: + +{* ../../docs_src/python_types/tutorial001.py *} + + +Het aanroepen van dit programma leidt tot het volgende resultaat: + +``` +John Doe +``` + +De functie voert het volgende uit: + +* Neem een `first_name` en een `last_name` +* Converteer de eerste letter van elk naar een hoofdletter met `title()`. +`` +* Voeg samen met een spatie in het midden. + +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + + +### Bewerk het + +Dit is een heel eenvoudig programma. + +Maar stel je nu voor dat je het vanaf nul zou moeten maken. + +Op een gegeven moment zou je aan de definitie van de functie zijn begonnen, je had de parameters klaar... + +Maar dan moet je “die methode die de eerste letter naar hoofdletters converteert” aanroepen. + +Was het `upper`? Was het `uppercase`? `first_uppercase`? `capitalize`? + +Dan roep je de hulp in van je oude programmeursvriend, (automatische) code aanvulling in je editor. + +Je typt de eerste parameter van de functie, `first_name`, dan een punt (`.`) en drukt dan op `Ctrl+Spatie` om de aanvulling te activeren. + +Maar helaas krijg je niets bruikbaars: + + + +### Types toevoegen + +Laten we een enkele regel uit de vorige versie aanpassen. + +We zullen precies dit fragment, de parameters van de functie, wijzigen van: + +```Python + first_name, last_name +``` + +naar: + +```Python + first_name: str, last_name: str +``` + +Dat is alles. + +Dat zijn de "type hints": + +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + + +Dit is niet hetzelfde als het declareren van standaardwaarden zoals bij: + +```Python + first_name="john", last_name="doe" +``` + +Het is iets anders. + +We gebruiken dubbele punten (`:`), geen gelijkheidstekens (`=`). + +Het toevoegen van type hints verandert normaal gesproken niet wat er gebeurt in je programma t.o.v. wat er zonder type hints zou gebeuren. + +Maar stel je voor dat je weer bezig bent met het maken van een functie, maar deze keer met type hints. + +Op hetzelfde moment probeer je de automatische aanvulling te activeren met `Ctrl+Spatie` en je ziet: + + + +Nu kun je de opties bekijken en er doorheen scrollen totdat je de optie vindt die “een belletje doet rinkelen”: + + + +### Meer motivatie + +Bekijk deze functie, deze heeft al type hints: + +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + + +Omdat de editor de types van de variabelen kent, krijgt u niet alleen aanvulling, maar ook controles op fouten: + + + +Nu weet je hoe je het moet oplossen, converteer `age` naar een string met `str(age)`: + +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + + +## Types declareren + +Je hebt net de belangrijkste plek om type hints te declareren gezien. Namelijk als functieparameters. + +Dit is ook de belangrijkste plek waar je ze gebruikt met **FastAPI**. + +### Eenvoudige types + +Je kunt alle standaard Python types declareren, niet alleen `str`. + +Je kunt bijvoorbeeld het volgende gebruiken: + +* `int` +* `float` +* `bool` +* `bytes` + +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + + +### Generieke types met typeparameters + +Er zijn enkele datastructuren die andere waarden kunnen bevatten, zoals `dict`, `list`, `set` en `tuple` en waar ook de interne waarden hun eigen type kunnen hebben. + +Deze types die interne types hebben worden “**generieke**” types genoemd. Het is mogelijk om ze te declareren, zelfs met hun interne types. + +Om deze types en de interne types te declareren, kun je de standaard Python module `typing` gebruiken. Deze module is speciaal gemaakt om deze type hints te ondersteunen. + +#### Nieuwere versies van Python + +De syntax met `typing` is **verenigbaar** met alle versies, van Python 3.6 tot aan de nieuwste, inclusief Python 3.9, Python 3.10, enz. + +Naarmate Python zich ontwikkelt, worden **nieuwere versies**, met verbeterde ondersteuning voor deze type annotaties, beschikbaar. In veel gevallen hoef je niet eens de `typing` module te importeren en te gebruiken om de type annotaties te declareren. + +Als je een recentere versie van Python kunt kiezen voor je project, kun je profiteren van die extra eenvoud. + +In alle documentatie staan voorbeelden die compatibel zijn met elke versie van Python (als er een verschil is). + +Bijvoorbeeld “**Python 3.6+**” betekent dat het compatibel is met Python 3.6 of hoger (inclusief 3.7, 3.8, 3.9, 3.10, etc). En “**Python 3.9+**” betekent dat het compatibel is met Python 3.9 of hoger (inclusief 3.10, etc). + +Als je de **laatste versies van Python** kunt gebruiken, gebruik dan de voorbeelden voor de laatste versie, die hebben de **beste en eenvoudigste syntax**, bijvoorbeeld “**Python 3.10+**”. + +#### List + +Laten we bijvoorbeeld een variabele definiëren als een `list` van `str`. + +//// tab | Python 3.9+ + +Declareer de variabele met dezelfde dubbele punt (`:`) syntax. + +Als type, vul `list` in. + +Doordat de list een type is dat enkele interne types bevat, zet je ze tussen vierkante haakjes: + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial006_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +Van `typing`, importeer `List` (met een hoofdletter `L`): + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial006.py!} +``` + +Declareer de variabele met dezelfde dubbele punt (`:`) syntax. + +Zet als type de `List` die je hebt geïmporteerd uit `typing`. + +Doordat de list een type is dat enkele interne types bevat, zet je ze tussen vierkante haakjes: + +```Python hl_lines="4" +{!> ../../docs_src/python_types/tutorial006.py!} +``` + +//// + +/// info + +De interne types tussen vierkante haakjes worden “typeparameters” genoemd. + +In dit geval is `str` de typeparameter die wordt doorgegeven aan `List` (of `list` in Python 3.9 en hoger). + +/// + +Dat betekent: “de variabele `items` is een `list`, en elk van de items in deze list is een `str`”. + +/// tip + +Als je Python 3.9 of hoger gebruikt, hoef je `List` niet te importeren uit `typing`, je kunt in plaats daarvan hetzelfde reguliere `list` type gebruiken. + +/// + +Door dat te doen, kan je editor ondersteuning bieden, zelfs tijdens het verwerken van items uit de list: + + + +Zonder types is dat bijna onmogelijk om te bereiken. + +Merk op dat de variabele `item` een van de elementen is in de lijst `items`. + +Toch weet de editor dat het een `str` is, en biedt daar vervolgens ondersteuning voor aan. + +#### Tuple en Set + +Je kunt hetzelfde doen om `tuple`s en `set`s te declareren: + +//// tab | Python 3.9+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial007_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial007.py!} +``` + +//// + +Dit betekent: + +* De variabele `items_t` is een `tuple` met 3 items, een `int`, nog een `int`, en een `str`. +* De variabele `items_s` is een `set`, en elk van de items is van het type `bytes`. + +#### Dict + +Om een `dict` te definiëren, geef je 2 typeparameters door, gescheiden door komma's. + +De eerste typeparameter is voor de sleutels (keys) van de `dict`. + +De tweede typeparameter is voor de waarden (values) van het `dict`: + +//// tab | Python 3.9+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial008_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial008.py!} +``` + +//// + +Dit betekent: + +* De variabele `prices` is een `dict`: + * De sleutels van dit `dict` zijn van het type `str` (bijvoorbeeld de naam van elk item). + * De waarden van dit `dict` zijn van het type `float` (bijvoorbeeld de prijs van elk item). + +#### Union + +Je kunt een variable declareren die van **verschillende types** kan zijn, bijvoorbeeld een `int` of een `str`. + +In Python 3.6 en hoger (inclusief Python 3.10) kun je het `Union`-type van `typing` gebruiken en de mogelijke types die je wilt accepteren, tussen de vierkante haakjes zetten. + +In Python 3.10 is er ook een **nieuwe syntax** waarin je de mogelijke types kunt scheiden door een verticale balk (`|`). + +//// tab | Python 3.10+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial008b_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial008b.py!} +``` + +//// + +In beide gevallen betekent dit dat `item` een `int` of een `str` kan zijn. + +#### Mogelijk `None` + +Je kunt declareren dat een waarde een type kan hebben, zoals `str`, maar dat het ook `None` kan zijn. + +In Python 3.6 en hoger (inclusief Python 3.10) kun je het declareren door `Optional` te importeren en te gebruiken vanuit de `typing`-module. + +```Python hl_lines="1 4" +{!../../docs_src/python_types/tutorial009.py!} +``` + +Door `Optional[str]` te gebruiken in plaats van alleen `str`, kan de editor je helpen fouten te detecteren waarbij je ervan uit zou kunnen gaan dat een waarde altijd een `str` is, terwijl het in werkelijkheid ook `None` zou kunnen zijn. + +`Optional[EenType]` is eigenlijk een snelkoppeling voor `Union[EenType, None]`, ze zijn equivalent. + +Dit betekent ook dat je in Python 3.10 `EenType | None` kunt gebruiken: + +//// tab | Python 3.10+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial009_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial009.py!} +``` + +//// + +//// tab | Python 3.8+ alternative + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial009b.py!} +``` + +//// + +#### Gebruik van `Union` of `Optional` + +Als je een Python versie lager dan 3.10 gebruikt, is dit een tip vanuit mijn **subjectieve** standpunt: + +* 🚨 Vermijd het gebruik van `Optional[EenType]`. +* Gebruik in plaats daarvan **`Union[EenType, None]`** ✨. + +Beide zijn gelijkwaardig en onderliggend zijn ze hetzelfde, maar ik zou `Union` aanraden in plaats van `Optional` omdat het woord “**optional**” lijkt te impliceren dat de waarde optioneel is, en het eigenlijk betekent “het kan `None` zijn”, zelfs als het niet optioneel is en nog steeds vereist is. + +Ik denk dat `Union[SomeType, None]` explicieter is over wat het betekent. + +Het gaat alleen om de woorden en naamgeving. Maar die naamgeving kan invloed hebben op hoe jij en je teamgenoten over de code denken. + +Laten we als voorbeeld deze functie nemen: + +{* ../../docs_src/python_types/tutorial009c.py hl[1,4] *} + + +De parameter `name` is gedefinieerd als `Optional[str]`, maar is **niet optioneel**, je kunt de functie niet aanroepen zonder de parameter: + +```Python +say_hi() # Oh, nee, dit geeft een foutmelding! 😱 +``` + +De `name` parameter is **nog steeds vereist** (niet *optioneel*) omdat het geen standaardwaarde heeft. Toch accepteert `name` `None` als waarde: + +```Python +say_hi(name=None) # Dit werkt, None is geldig 🎉 +``` + +Het goede nieuws is dat als je eenmaal Python 3.10 gebruikt, je je daar geen zorgen meer over hoeft te maken, omdat je dan gewoon `|` kunt gebruiken om unions van types te definiëren: + +{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *} + + +Dan hoef je je geen zorgen te maken over namen als `Optional` en `Union`. 😎 + +#### Generieke typen + +De types die typeparameters in vierkante haakjes gebruiken, worden **Generieke types** of **Generics** genoemd, bijvoorbeeld: + +//// tab | Python 3.10+ + +Je kunt dezelfde ingebouwde types gebruiken als generics (met vierkante haakjes en types erin): + +* `list` +* `tuple` +* `set` +* `dict` + +Hetzelfde als bij Python 3.8, uit de `typing`-module: + +* `Union` +* `Optional` (hetzelfde als bij Python 3.8) +* ...en anderen. + +In Python 3.10 kun je , als alternatief voor de generieke `Union` en `Optional`, de verticale lijn (`|`) gebruiken om unions van typen te voorzien, dat is veel beter en eenvoudiger. + +//// + +//// tab | Python 3.9+ + +Je kunt dezelfde ingebouwde types gebruiken als generieke types (met vierkante haakjes en types erin): + +* `list` +* `tuple` +* `set` +* `dict` + +En hetzelfde als met Python 3.8, vanuit de `typing`-module: + +* `Union` +* `Optional` +* ...en anderen. + +//// + +//// tab | Python 3.8+ + +* `List` +* `Tuple` +* `Set` +* `Dict` +* `Union` +* `Optional` +* ...en anderen. + +//// + +### Klassen als types + +Je kunt een klasse ook declareren als het type van een variabele. + +Stel dat je een klasse `Person` hebt, met een naam: + +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + + +Vervolgens kun je een variabele van het type `Persoon` declareren: + +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + + +Dan krijg je ook nog eens volledige editorondersteuning: + + + +Merk op dat dit betekent dat "`one_person` een **instantie** is van de klasse `Person`". + +Dit betekent niet dat `one_person` de **klasse** is met de naam `Person`. + +## Pydantic modellen + +Pydantic is een Python-pakket voor het uitvoeren van datavalidatie. + +Je declareert de "vorm" van de data als klassen met attributen. + +Elk attribuut heeft een type. + +Vervolgens maak je een instantie van die klasse met een aantal waarden en het valideert de waarden, converteert ze naar het juiste type (als dat het geval is) en geeft je een object met alle data terug. + +Daarnaast krijg je volledige editorondersteuning met dat resulterende object. + +Een voorbeeld uit de officiële Pydantic-documentatie: + +//// tab | Python 3.10+ + +```Python +{!> ../../docs_src/python_types/tutorial011_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python +{!> ../../docs_src/python_types/tutorial011_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python +{!> ../../docs_src/python_types/tutorial011.py!} +``` + +//// + +/// info + +Om meer te leren over Pydantic, bekijk de documentatie. + +/// + +**FastAPI** is volledig gebaseerd op Pydantic. + +Je zult veel meer van dit alles in de praktijk zien in de [Tutorial - Gebruikershandleiding](tutorial/index.md){.internal-link target=_blank}. + +/// tip + +Pydantic heeft een speciaal gedrag wanneer je `Optional` of `Union[EenType, None]` gebruikt zonder een standaardwaarde, je kunt er meer over lezen in de Pydantic-documentatie over Verplichte optionele velden. + +/// + +## Type Hints met Metadata Annotaties + +Python heeft ook een functie waarmee je **extra metadata** in deze type hints kunt toevoegen met behulp van `Annotated`. + +//// tab | Python 3.9+ + +In Python 3.9 is `Annotated` onderdeel van de standaardpakket, dus je kunt het importeren vanuit `typing`. + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial013_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +In versies lager dan Python 3.9 importeer je `Annotated` vanuit `typing_extensions`. + +Het wordt al geïnstalleerd met **FastAPI**. + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial013.py!} +``` + +//// + +Python zelf doet niets met deze `Annotated` en voor editors en andere hulpmiddelen is het type nog steeds een `str`. + +Maar je kunt deze ruimte in `Annotated` gebruiken om **FastAPI** te voorzien van extra metadata over hoe je wilt dat je applicatie zich gedraagt. + +Het belangrijkste om te onthouden is dat **de eerste *typeparameter*** die je doorgeeft aan `Annotated` het **werkelijke type** is. De rest is gewoon metadata voor andere hulpmiddelen. + +Voor nu hoef je alleen te weten dat `Annotated` bestaat en dat het standaard Python is. 😎 + +Later zul je zien hoe **krachtig** het kan zijn. + +/// tip + +Het feit dat dit **standaard Python** is, betekent dat je nog steeds de **best mogelijke ontwikkelaarservaring** krijgt in je editor, met de hulpmiddelen die je gebruikt om je code te analyseren en te refactoren, enz. ✨ + +Daarnaast betekent het ook dat je code zeer verenigbaar zal zijn met veel andere Python-hulpmiddelen en -pakketten. 🚀 + +/// + +## Type hints in **FastAPI** + +**FastAPI** maakt gebruik van type hints om verschillende dingen te doen. + +Met **FastAPI** declareer je parameters met type hints en krijg je: + +* **Editor ondersteuning**. +* **Type checks**. + +...en **FastAPI** gebruikt dezelfde declaraties om: + +* **Vereisten te definïeren **: van request pad parameters, query parameters, headers, bodies, dependencies, enz. +* **Data te converteren**: van de request naar het vereiste type. +* **Data te valideren**: afkomstig van elke request: + * **Automatische foutmeldingen** te genereren die naar de client worden geretourneerd wanneer de data ongeldig is. +* De API met OpenAPI te **documenteren**: + * die vervolgens wordt gebruikt door de automatische interactieve documentatie gebruikersinterfaces. + +Dit klinkt misschien allemaal abstract. Maak je geen zorgen. Je ziet dit allemaal in actie in de [Tutorial - Gebruikershandleiding](tutorial/index.md){.internal-link target=_blank}. + +Het belangrijkste is dat door standaard Python types te gebruiken, op één plek (in plaats van meer klassen, decorators, enz. toe te voegen), **FastAPI** een groot deel van het werk voor je doet. + +/// info + +Als je de hele tutorial al hebt doorgenomen en terug bent gekomen om meer te weten te komen over types, is een goede bron het "cheat sheet" van `mypy`. + +/// diff --git a/docs/nl/mkdocs.yml b/docs/nl/mkdocs.yml new file mode 100644 index 000000000..de18856f4 --- /dev/null +++ b/docs/nl/mkdocs.yml @@ -0,0 +1 @@ +INHERIT: ../en/mkdocs.yml diff --git a/docs/pl/docs/features.md b/docs/pl/docs/features.md index ed10af9bc..80d3bdece 100644 --- a/docs/pl/docs/features.md +++ b/docs/pl/docs/features.md @@ -63,10 +63,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` oznacza: +/// info - Przekaż klucze i wartości słownika `second_user_data` bezpośrednio jako argumenty klucz-wartość, co jest równoznaczne z: `User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` oznacza: + +Przekaż klucze i wartości słownika `second_user_data` bezpośrednio jako argumenty klucz-wartość, co jest równoznaczne z: `User(id=4, name="Mary", joined="2018-11-30")` + +/// ### Wsparcie edytora @@ -174,7 +177,7 @@ Dzięki **FastAPI** otrzymujesz wszystkie funkcje **Starlette** (ponieważ FastA ## Cechy Pydantic -**FastAPI** jest w pełni kompatybilny z (oraz bazuje na) Pydantic. Tak więc każdy dodatkowy kod Pydantic, który posiadasz, również będzie działał. +**FastAPI** jest w pełni kompatybilny z (oraz bazuje na) Pydantic. Tak więc każdy dodatkowy kod Pydantic, który posiadasz, również będzie działał. Wliczając w to zewnętrzne biblioteki, również oparte o Pydantic, takie jak ORM, ODM dla baz danych. @@ -189,8 +192,6 @@ Dzięki **FastAPI** otrzymujesz wszystkie funkcje **Pydantic** (ponieważ FastAP * Jeśli znasz adnotacje typów Pythona to wiesz jak używać Pydantic. * Dobrze współpracuje z Twoim **IDE/linterem/mózgiem**: * Ponieważ struktury danych Pydantic to po prostu instancje klas, które definiujesz; autouzupełnianie, linting, mypy i twoja intuicja powinny działać poprawnie z Twoimi zwalidowanymi danymi. -* **Szybkość**: - * w benchmarkach Pydantic jest szybszy niż wszystkie inne testowane biblioteki. * Walidacja **złożonych struktur**: * Wykorzystanie hierarchicznych modeli Pydantic, Pythonowego modułu `typing` zawierającego `List`, `Dict`, itp. * Walidatory umożliwiają jasne i łatwe definiowanie, sprawdzanie złożonych struktur danych oraz dokumentowanie ich jako JSON Schema. diff --git a/docs/pl/docs/help-fastapi.md b/docs/pl/docs/help-fastapi.md index 3d02a8741..3ea328dc2 100644 --- a/docs/pl/docs/help-fastapi.md +++ b/docs/pl/docs/help-fastapi.md @@ -12,7 +12,7 @@ Istnieje również kilka sposobów uzyskania pomocy. ## Zapisz się do newslettera -Możesz zapisać się do rzadkiego [newslettera o **FastAPI i jego przyjaciołach**](/newsletter/){.internal-link target=_blank}, aby być na bieżąco z: +Możesz zapisać się do rzadkiego [newslettera o **FastAPI i jego przyjaciołach**](newsletter.md){.internal-link target=_blank}, aby być na bieżąco z: * Aktualnościami o FastAPI i przyjaciołach 🚀 * Przewodnikami 📝 @@ -26,13 +26,13 @@ Możesz zapisać się do rzadkiego [newslettera o **FastAPI i jego przyjaciołac ## Dodaj gwiazdkę **FastAPI** na GitHubie -Możesz "dodać gwiazdkę" FastAPI na GitHubie (klikając przycisk gwiazdki w prawym górnym rogu): https://github.com/tiangolo/fastapi. ⭐️ +Możesz "dodać gwiazdkę" FastAPI na GitHubie (klikając przycisk gwiazdki w prawym górnym rogu): https://github.com/fastapi/fastapi. ⭐️ Dodając gwiazdkę, inni użytkownicy będą mogli łatwiej znaleźć projekt i zobaczyć, że był już przydatny dla innych. ## Obserwuj repozytorium GitHub w poszukiwaniu nowych wydań -Możesz "obserwować" FastAPI na GitHubie (klikając przycisk "obserwuj" w prawym górnym rogu): https://github.com/tiangolo/fastapi. 👀 +Możesz "obserwować" FastAPI na GitHubie (klikając przycisk "obserwuj" w prawym górnym rogu): https://github.com/fastapi/fastapi. 👀 Wybierz opcję "Tylko wydania". @@ -59,7 +59,7 @@ Możesz: ## Napisz tweeta o **FastAPI** -Napisz tweeta o **FastAPI** i powiedz czemu Ci się podoba. 🎉 +Napisz tweeta o **FastAPI** i powiedz czemu Ci się podoba. 🎉 Uwielbiam czytać w jaki sposób **FastAPI** jest używane, co Ci się w nim podobało, w jakim projekcie/firmie go używasz itp. @@ -73,12 +73,12 @@ Uwielbiam czytać w jaki sposób **FastAPI** jest używane, co Ci się w nim pod Możesz spróbować pomóc innym, odpowiadając w: -* Dyskusjach na GitHubie -* Problemach na GitHubie +* Dyskusjach na GitHubie +* Problemach na GitHubie W wielu przypadkach możesz już znać odpowiedź na te pytania. 🤓 -Jeśli pomożesz wielu ludziom, możesz zostać oficjalnym [Ekspertem FastAPI](fastapi-people.md#experts){.internal-link target=_blank}. 🎉 +Jeśli pomożesz wielu ludziom, możesz zostać oficjalnym [Ekspertem FastAPI](fastapi-people.md#fastapi-experts){.internal-link target=_blank}. 🎉 Pamiętaj tylko o najważniejszym: bądź życzliwy. Ludzie przychodzą sfrustrowani i w wielu przypadkach nie zadają pytań w najlepszy sposób, ale mimo to postaraj się być dla nich jak najbardziej życzliwy. 🤗 @@ -125,7 +125,7 @@ Jeśli odpowiedzą, jest duża szansa, że rozwiązałeś ich problem, gratulacj ## Obserwuj repozytorium na GitHubie -Możesz "obserwować" FastAPI na GitHubie (klikając przycisk "obserwuj" w prawym górnym rogu): https://github.com/tiangolo/fastapi. 👀 +Możesz "obserwować" FastAPI na GitHubie (klikając przycisk "obserwuj" w prawym górnym rogu): https://github.com/fastapi/fastapi. 👀 Jeśli wybierzesz "Obserwuj" zamiast "Tylko wydania", otrzymasz powiadomienia, gdy ktoś utworzy nowy problem lub pytanie. Możesz również określić, że chcesz być powiadamiany tylko o nowych problemach, dyskusjach, PR-ach itp. @@ -133,7 +133,7 @@ Następnie możesz spróbować pomóc rozwiązać te problemy. ## Zadawaj pytania -Możesz utworzyć nowe pytanie w repozytorium na GitHubie, na przykład aby: +Możesz utworzyć nowe pytanie w repozytorium na GitHubie, na przykład aby: * Zadać **pytanie** lub zapytać o **problem**. * Zaproponować nową **funkcję**. @@ -170,12 +170,15 @@ A jeśli istnieje jakaś konkretna potrzeba dotycząca stylu lub spójności, sa * Następnie dodaj **komentarz** z informacją o tym, że sprawdziłeś kod, dzięki temu będę miał pewność, że faktycznie go sprawdziłeś. -!!! info - Niestety, nie mogę ślepo ufać PR-om, nawet jeśli mają kilka zatwierdzeń. +/// info - Kilka razy zdarzyło się, że PR-y miały 3, 5 lub więcej zatwierdzeń (prawdopodobnie dlatego, że opis obiecuje rozwiązanie ważnego problemu), ale gdy sam sprawdziłem danego PR-a, okazał się być zbugowany lub nie rozwiązywał problemu, który rzekomo miał rozwiązywać. 😅 +Niestety, nie mogę ślepo ufać PR-om, nawet jeśli mają kilka zatwierdzeń. - Dlatego tak ważne jest, abyś faktycznie przeczytał i uruchomił kod oraz napisał w komentarzu, że to zrobiłeś. 🤓 +Kilka razy zdarzyło się, że PR-y miały 3, 5 lub więcej zatwierdzeń (prawdopodobnie dlatego, że opis obiecuje rozwiązanie ważnego problemu), ale gdy sam sprawdziłem danego PR-a, okazał się być zbugowany lub nie rozwiązywał problemu, który rzekomo miał rozwiązywać. 😅 + +Dlatego tak ważne jest, abyś faktycznie przeczytał i uruchomił kod oraz napisał w komentarzu, że to zrobiłeś. 🤓 + +/// * Jeśli PR można uprościć w jakiś sposób, możesz o to poprosić, ale nie ma potrzeby być zbyt wybrednym, może być wiele subiektywnych punktów widzenia (a ja też będę miał swój 🙈), więc lepiej żebyś skupił się na kluczowych rzeczach. @@ -196,7 +199,7 @@ A jeśli istnieje jakaś konkretna potrzeba dotycząca stylu lub spójności, sa Możesz [wnieść wkład](contributing.md){.internal-link target=_blank} do kodu źródłowego za pomocą Pull Requestu, na przykład: * Naprawić literówkę, którą znalazłeś w dokumentacji. -* Podzielić się artykułem, filmem lub podcastem, który stworzyłeś lub znalazłeś na temat FastAPI, edytując ten plik. +* Podzielić się artykułem, filmem lub podcastem, który stworzyłeś lub znalazłeś na temat FastAPI, edytując ten plik. * Upewnij się, że dodajesz swój link na początku odpowiedniej sekcji. * Pomóc w [tłumaczeniu dokumentacji](contributing.md#translations){.internal-link target=_blank} na Twój język. * Możesz również pomóc w weryfikacji tłumaczeń stworzonych przez innych. @@ -215,8 +218,8 @@ Jest wiele pracy do zrobienia, a w większości przypadków **TY** możesz to zr Główne zadania, które możesz wykonać teraz to: -* [Pomóc innym z pytaniami na GitHubie](#help-others-with-questions-in-github){.internal-link target=_blank} (zobacz sekcję powyżej). -* [Oceniać Pull Requesty](#review-pull-requests){.internal-link target=_blank} (zobacz sekcję powyżej). +* [Pomóc innym z pytaniami na GitHubie](#pomagaj-innym-odpowiadajac-na-ich-pytania-na-githubie){.internal-link target=_blank} (zobacz sekcję powyżej). +* [Oceniać Pull Requesty](#przegladaj-pull-requesty){.internal-link target=_blank} (zobacz sekcję powyżej). Te dwie czynności **zajmują najwięcej czasu**. To główna praca związana z utrzymaniem FastAPI. @@ -226,10 +229,13 @@ Jeśli możesz mi w tym pomóc, **pomożesz mi utrzymać FastAPI** i zapewnisz Dołącz do 👥 serwera czatu na Discordzie 👥 i spędzaj czas z innymi w społeczności FastAPI. -!!! wskazówka - Jeśli masz pytania, zadaj je w Dyskusjach na GitHubie, jest dużo większa szansa, że otrzymasz pomoc od [Ekspertów FastAPI](fastapi-people.md#experts){.internal-link target=_blank}. +/// tip | Wskazówka + +Jeśli masz pytania, zadaj je w Dyskusjach na GitHubie, jest dużo większa szansa, że otrzymasz pomoc od [Ekspertów FastAPI](fastapi-people.md#fastapi-experts){.internal-link target=_blank}. + +Używaj czatu tylko do innych ogólnych rozmów. - Używaj czatu tylko do innych ogólnych rozmów. +/// ### Nie zadawaj pytań na czacie @@ -237,7 +243,7 @@ Miej na uwadze, że ponieważ czaty pozwalają na bardziej "swobodną rozmowę", Na GitHubie szablon poprowadzi Cię do napisania odpowiedniego pytania, dzięki czemu łatwiej uzyskasz dobrą odpowiedź, a nawet rozwiążesz problem samodzielnie, zanim zapytasz. Ponadto na GitHubie mogę się upewnić, że zawsze odpowiadam na wszystko, nawet jeśli zajmuje to trochę czasu. Osobiście nie mogę tego zrobić z systemami czatu. 😅 -Rozmów w systemach czatu nie można tak łatwo przeszukiwać, jak na GitHubie, więc pytania i odpowiedzi mogą zaginąć w rozmowie. A tylko te na GitHubie liczą się do zostania [Ekspertem FastAPI](fastapi-people.md#experts){.internal-link target=_blank}, więc najprawdopodobniej otrzymasz więcej uwagi na GitHubie. +Rozmów w systemach czatu nie można tak łatwo przeszukiwać, jak na GitHubie, więc pytania i odpowiedzi mogą zaginąć w rozmowie. A tylko te na GitHubie liczą się do zostania [Ekspertem FastAPI](fastapi-people.md#fastapi-experts){.internal-link target=_blank}, więc najprawdopodobniej otrzymasz więcej uwagi na GitHubie. Z drugiej strony w systemach czatu są tysiące użytkowników, więc jest duża szansa, że znajdziesz tam kogoś do rozmowy, prawie w każdej chwili. 😄 diff --git a/docs/pl/docs/index.md b/docs/pl/docs/index.md index 49f5c2b01..0e13d2631 100644 --- a/docs/pl/docs/index.md +++ b/docs/pl/docs/index.md @@ -1,3 +1,9 @@ +# FastAPI + + +

FastAPI

@@ -5,26 +11,29 @@ FastAPI to szybki, prosty w nauce i gotowy do użycia w produkcji framework

- - Test + + Test - - Coverage + + Coverage Package version + + Supported Python versions +

--- **Dokumentacja**: https://fastapi.tiangolo.com -**Kod żródłowy**: https://github.com/tiangolo/fastapi +**Kod żródłowy**: https://github.com/fastapi/fastapi --- -FastAPI to nowoczesny, wydajny framework webowy do budowania API z użyciem Pythona 3.8+ bazujący na standardowym typowaniu Pythona. +FastAPI to nowoczesny, wydajny framework webowy do budowania API z użyciem Pythona bazujący na standardowym typowaniu Pythona. Kluczowe cechy: @@ -60,7 +69,7 @@ Kluczowe cechy: "_[...] 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._" -
Kabir Khan - Microsoft (ref)
+
Kabir Khan - Microsoft (ref)
--- @@ -84,7 +93,7 @@ Kluczowe cechy: "_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- @@ -106,12 +115,10 @@ Jeżeli tworzysz aplikacje CLI< ## Wymagania -Python 3.8+ - FastAPI oparty jest na: * Starlette dla części webowej. -* Pydantic dla części obsługujących dane. +* Pydantic dla części obsługujących dane. ## Instalacja @@ -125,7 +132,7 @@ $ pip install fastapi -Na serwerze produkcyjnym będziesz także potrzebował serwera ASGI, np. Uvicorn lub Hypercorn. +Na serwerze produkcyjnym będziesz także potrzebował serwera ASGI, np. Uvicorn lub Hypercorn.
@@ -321,7 +328,7 @@ Robisz to tak samo jak ze standardowymi typami w Pythonie. Nie musisz sie uczyć żadnej nowej składni, metod lub klas ze specyficznych bibliotek itp. -Po prostu standardowy **Python 3.8+**. +Po prostu standardowy **Python**. Na przykład, dla danych typu `int`: @@ -435,23 +442,23 @@ Aby dowiedzieć się o tym więcej, zobacz sekcję email_validator - dla walidacji adresów email. +* email-validator - dla walidacji adresów email. Używane przez Starlette: * httpx - Wymagane jeżeli chcesz korzystać z `TestClient`. * aiofiles - Wymagane jeżeli chcesz korzystać z `FileResponse` albo `StaticFiles`. * jinja2 - Wymagane jeżeli chcesz używać domyślnej konfiguracji szablonów. -* python-multipart - Wymagane jeżelich chcesz wsparcie "parsowania" formularzy, używając `request.form()`. +* python-multipart - Wymagane jeżelich chcesz wsparcie "parsowania" formularzy, używając `request.form()`. * itsdangerous - Wymagany dla wsparcia `SessionMiddleware`. * pyyaml - Wymagane dla wsparcia `SchemaGenerator` z Starlette (z FastAPI prawdopodobnie tego nie potrzebujesz). * graphene - Wymagane dla wsparcia `GraphQLApp`. -* ujson - Wymagane jeżeli chcesz korzystać z `UJSONResponse`. Używane przez FastAPI / Starlette: * uvicorn - jako serwer, który ładuje i obsługuje Twoją aplikację. * orjson - Wymagane jeżeli chcesz używać `ORJSONResponse`. +* ujson - Wymagane jeżeli chcesz korzystać z `UJSONResponse`. Możesz zainstalować wszystkie te aplikacje przy pomocy `pip install fastapi[all]`. diff --git a/docs/pl/docs/tutorial/first-steps.md b/docs/pl/docs/tutorial/first-steps.md index 9406d703d..8fa4c75ad 100644 --- a/docs/pl/docs/tutorial/first-steps.md +++ b/docs/pl/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ Najprostszy plik FastAPI może wyglądać tak: -```Python -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} Skopiuj to do pliku `main.py`. @@ -24,12 +22,15 @@ $ uvicorn main:app --reload
-!!! note - Polecenie `uvicorn main:app` odnosi się do: +/// note + +Polecenie `uvicorn main:app` odnosi się do: + +* `main`: plik `main.py` ("moduł" Python). +* `app`: obiekt utworzony w pliku `main.py` w lini `app = FastAPI()`. +* `--reload`: sprawia, że serwer uruchamia się ponownie po zmianie kodu. Używany tylko w trakcie tworzenia oprogramowania. - * `main`: plik `main.py` ("moduł" Python). - * `app`: obiekt utworzony w pliku `main.py` w lini `app = FastAPI()`. - * `--reload`: sprawia, że serwer uruchamia się ponownie po zmianie kodu. Używany tylko w trakcie tworzenia oprogramowania. +/// Na wyjściu znajduje się linia z czymś w rodzaju: @@ -130,23 +131,21 @@ Możesz go również użyć do automatycznego generowania kodu dla klientów, kt ### Krok 1: zaimportuj `FastAPI` -```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI` jest klasą, która zapewnia wszystkie funkcjonalności Twojego API. -!!! note "Szczegóły techniczne" - `FastAPI` jest klasą, która dziedziczy bezpośrednio z `Starlette`. +/// note | Szczegóły techniczne + +`FastAPI` jest klasą, która dziedziczy bezpośrednio z `Starlette`. - Oznacza to, że możesz korzystać ze wszystkich funkcjonalności Starlette również w `FastAPI`. +Oznacza to, że możesz korzystać ze wszystkich funkcjonalności Starlette również w `FastAPI`. +/// ### Krok 2: utwórz instancję `FastAPI` -```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{*../../docs_src/first_steps/tutorial001.py hl[3] *} Zmienna `app` będzie tutaj "instancją" klasy `FastAPI`. @@ -166,9 +165,7 @@ $ uvicorn main:app --reload Jeśli stworzysz swoją aplikację, np.: -```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} -``` +{* ../../docs_src/first_steps/tutorial002.py hl[3] *} I umieścisz to w pliku `main.py`, to będziesz mógł tak wywołać `uvicorn`: @@ -200,8 +197,11 @@ https://example.com/items/foo /items/foo ``` -!!! info - "Ścieżka" jest zazwyczaj nazywana "path", "endpoint" lub "route'. +/// info + +"Ścieżka" jest zazwyczaj nazywana "path", "endpoint" lub "route'. + +/// Podczas budowania API, "ścieżka" jest głównym sposobem na oddzielenie "odpowiedzialności" i „zasobów”. @@ -242,25 +242,26 @@ Będziemy je również nazywali "**operacjami**". #### Zdefiniuj *dekorator operacji na ścieżce* -```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[6] *} `@app.get("/")` mówi **FastAPI** że funkcja poniżej odpowiada za obsługę żądań, które trafiają do: * ścieżki `/` * używając operacji get -!!! info "`@decorator` Info" - Składnia `@something` jest w Pythonie nazywana "dekoratorem". +/// info | `@decorator` Info - Umieszczasz to na szczycie funkcji. Jak ładną ozdobną czapkę (chyba stąd wzięła się nazwa). +Składnia `@something` jest w Pythonie nazywana "dekoratorem". - "Dekorator" przyjmuje funkcję znajdującą się poniżej jego i coś z nią robi. +Umieszczasz to na szczycie funkcji. Jak ładną ozdobną czapkę (chyba stąd wzięła się nazwa). - W naszym przypadku dekorator mówi **FastAPI**, że poniższa funkcja odpowiada **ścieżce** `/` z **operacją** `get`. +"Dekorator" przyjmuje funkcję znajdującą się poniżej jego i coś z nią robi. - Jest to "**dekorator operacji na ścieżce**". +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: @@ -275,14 +276,17 @@ Oraz tych bardziej egzotycznych: * `@app.patch()` * `@app.trace()` -!!! tip - Możesz dowolnie używać każdej operacji (metody HTTP). +/// tip + +Możesz dowolnie używać każdej operacji (metody HTTP). - **FastAPI** nie narzuca żadnego konkretnego znaczenia. +**FastAPI** nie narzuca żadnego konkretnego znaczenia. - Informacje tutaj są przedstawione jako wskazówka, a nie wymóg. +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`. +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ę** @@ -292,9 +296,7 @@ To jest nasza "**funkcja obsługująca ścieżkę**": * **operacja**: to `get`. * **funkcja**: to funkcja poniżej "dekoratora" (poniżej `@app.get("/")`). -```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[7] *} Jest to funkcja Python. @@ -306,18 +308,17 @@ 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!} -``` +{* ../../docs_src/first_steps/tutorial003.py hl[7] *} + +/// note -!!! note - Jeśli nie znasz różnicy, sprawdź [Async: *"In a hurry?"*](/async/#in-a-hurry){.internal-link target=_blank}. +Jeśli nie znasz różnicy, sprawdź [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}. + +/// ### Krok 5: zwróć zawartość -```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[8] *} Możesz zwrócić `dict`, `list`, pojedynczą wartość jako `str`, `int`, itp. diff --git a/docs/pl/docs/tutorial/index.md b/docs/pl/docs/tutorial/index.md index f8c5c6022..66f7c6d62 100644 --- a/docs/pl/docs/tutorial/index.md +++ b/docs/pl/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ...wliczając w to `uvicorn`, który będzie służył jako serwer wykonujacy Twój kod. -!!! note - Możesz również wykonać instalację "krok po kroku". +/// note - Prawdopodobnie zechcesz to zrobić, kiedy będziesz wdrażać swoją aplikację w środowisku produkcyjnym: +Możesz również wykonać instalację "krok po kroku". - ``` - pip install fastapi - ``` +Prawdopodobnie zechcesz to zrobić, kiedy będziesz wdrażać swoją aplikację w środowisku produkcyjnym: - Zainstaluj też `uvicorn`, który będzie służył jako serwer: +``` +pip install fastapi +``` + +Zainstaluj też `uvicorn`, który będzie służył jako serwer: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +Tak samo możesz zainstalować wszystkie dodatkowe biblioteki, których chcesz użyć. - Tak samo możesz zainstalować wszystkie dodatkowe biblioteki, których chcesz użyć. +/// ## Zaawansowany poradnik diff --git a/docs/pt/docs/about/index.md b/docs/pt/docs/about/index.md new file mode 100644 index 000000000..1f42e8831 --- /dev/null +++ b/docs/pt/docs/about/index.md @@ -0,0 +1,3 @@ +# Sobre + +Sobre o FastAPI, seus padrões, inspirações e muito mais. 🤓 diff --git a/docs/pt/docs/advanced/additional-responses.md b/docs/pt/docs/advanced/additional-responses.md new file mode 100644 index 000000000..1060d18af --- /dev/null +++ b/docs/pt/docs/advanced/additional-responses.md @@ -0,0 +1,247 @@ +# Retornos Adicionais no OpenAPI + +/// warning | Aviso + +Este é um tema bem avançado. + +Se você está começando com o **FastAPI**, provavelmente você não precisa disso. + +/// + +Você pode declarar retornos adicionais, com códigos de status adicionais, media types, descrições, etc. + +Essas respostas adicionais serão incluídas no esquema do OpenAPI, e também aparecerão na documentação da API. + +Porém para as respostas adicionais, você deve garantir que está retornando um `Response` como por exemplo o `JSONResponse` diretamente, junto com o código de status e o conteúdo. + +## Retorno Adicional com `model` + +Você pode fornecer o parâmetro `responses` aos seus *decoradores de caminho*. + +Este parâmetro recebe um `dict`, as chaves são os códigos de status para cada retorno, como por exemplo `200`, e os valores são um outro `dict` com a informação de cada um deles. + +Cada um desses `dict` de retorno pode ter uma chave `model`, contendo um modelo do Pydantic, assim como o `response_model`. + +O **FastAPI** pegará este modelo, gerará o esquema JSON dele e incluirá no local correto do OpenAPI. + +Por exemplo, para declarar um outro retorno com o status code `404` e um modelo do Pydantic chamado `Message`, você pode escrever: + +{* ../../docs_src/additional_responses/tutorial001.py hl[18,22] *} + +/// note | Nota + +Lembre-se que você deve retornar o `JSONResponse` diretamente. + +/// + +/// info | Informação + +A chave `model` não é parte do OpenAPI. + +O **FastAPI** pegará o modelo do Pydantic, gerará o `JSON Schema`, e adicionará no local correto. + +O local correto é: + +* Na chave `content`, que tem como valor um outro objeto JSON (`dict`) que contém: + * Uma chave com o media type, como por exemplo `application/json`, que contém como valor um outro objeto JSON, contendo:: + * Uma chave `schema`, que contém como valor o JSON Schema do modelo, sendo este o local correto. + * O **FastAPI** adiciona aqui a referência dos esquemas JSON globais que estão localizados em outro lugar, ao invés de incluí-lo diretamente. Deste modo, outras aplicações e clientes podem utilizar estes esquemas JSON diretamente, fornecer melhores ferramentas de geração de código, etc. + +/// + +O retorno gerado no OpenAI para esta *operação de caminho* será: + +```JSON hl_lines="3-12" +{ + "responses": { + "404": { + "description": "Additional Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Message" + } + } + } + }, + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Item" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } +} +``` + +Os esquemas são referenciados em outro local dentro do esquema OpenAPI: + +```JSON hl_lines="4-16" +{ + "components": { + "schemas": { + "Message": { + "title": "Message", + "required": [ + "message" + ], + "type": "object", + "properties": { + "message": { + "title": "Message", + "type": "string" + } + } + }, + "Item": { + "title": "Item", + "required": [ + "id", + "value" + ], + "type": "object", + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "value": { + "title": "Value", + "type": "string" + } + } + }, + "ValidationError": { + "title": "ValidationError", + "required": [ + "loc", + "msg", + "type" + ], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "type": "string" + } + }, + "msg": { + "title": "Message", + "type": "string" + }, + "type": { + "title": "Error Type", + "type": "string" + } + } + }, + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": { + "$ref": "#/components/schemas/ValidationError" + } + } + } + } + } + } +} +``` + +## Media types adicionais para o retorno principal + +Você pode utilizar o mesmo parâmetro `responses` para adicionar diferentes media types para o mesmo retorno principal. + +Por exemplo, você pode adicionar um media type adicional de `image/png`, declarando que a sua *operação de caminho* pode retornar um objeto JSON (com o media type `application/json`) ou uma imagem PNG: + +{* ../../docs_src/additional_responses/tutorial002.py hl[19:24,28] *} + +/// note | Nota + +Note que você deve retornar a imagem utilizando um `FileResponse` diretamente. + +/// + +/// info | Informação + +A menos que você especifique um media type diferente explicitamente em seu parâmetro `responses`, o FastAPI assumirá que o retorno possui o mesmo media type contido na classe principal de retorno (padrão `application/json`). + +Porém se você especificou uma classe de retorno com o valor `None` como media type, o FastAPI utilizará `application/json` para qualquer retorno adicional que possui um modelo associado. + +/// + +## Combinando informações + +Você também pode combinar informações de diferentes lugares, incluindo os parâmetros `response_model`, `status_code`, e `responses`. + +Você pode declarar um `response_model`, utilizando o código de status padrão `200` (ou um customizado caso você precise), e depois adicionar informações adicionais para esse mesmo retorno em `responses`, diretamente no esquema OpenAPI. + +O **FastAPI** manterá as informações adicionais do `responses`, e combinará com o esquema JSON do seu modelo. + +Por exemplo, você pode declarar um retorno com o código de status `404` que utiliza um modelo do Pydantic que possui um `description` customizado. + +E um retorno com o código de status `200` que utiliza o seu `response_model`, porém inclui um `example` customizado: + +{* ../../docs_src/additional_responses/tutorial003.py hl[20:31] *} + +Isso será combinado e incluído em seu OpenAPI, e disponibilizado na documentação da sua API: + + + +## Combinar retornos predefinidos e personalizados + +Você pode querer possuir alguns retornos predefinidos que são aplicados para diversas *operações de caminho*, porém você deseja combinar com retornos personalizados que são necessários para cada *operação de caminho*. + +Para estes casos, você pode utilizar a técnica do Python de "desempacotamento" de um `dict` utilizando `**dict_to_unpack`: + +```Python +old_dict = { + "old key": "old value", + "second old key": "second old value", +} +new_dict = {**old_dict, "new key": "new value"} +``` + +Aqui, o `new_dict` terá todos os pares de chave-valor do `old_dict` mais o novo par de chave-valor: + +```Python +{ + "old key": "old value", + "second old key": "second old value", + "new key": "new value", +} +``` + +Você pode utilizar essa técnica para reutilizar alguns retornos predefinidos nas suas *operações de caminho* e combiná-las com personalizações adicionais. + +Por exemplo: + +{* ../../docs_src/additional_responses/tutorial004.py hl[13:17,26] *} + +## Mais informações sobre retornos OpenAPI + +Para verificar exatamente o que você pode incluir nos retornos, você pode conferir estas seções na especificação do OpenAPI: + +* Objeto de Retorno OpenAPI, inclui o `Response Object`. +* Objeto de Retorno OpenAPI, você pode incluir qualquer coisa dele diretamente em cada retorno dentro do seu parâmetro `responses`. Incluindo `description`, `headers`, `content` (dentro dele que você declara diferentes media types e esquemas JSON), e `links`. diff --git a/docs/pt/docs/advanced/additional-status-codes.md b/docs/pt/docs/advanced/additional-status-codes.md new file mode 100644 index 000000000..06d619151 --- /dev/null +++ b/docs/pt/docs/advanced/additional-status-codes.md @@ -0,0 +1,41 @@ +# Códigos de status adicionais + +Por padrão, o **FastAPI** retornará as respostas utilizando o `JSONResponse`, adicionando o conteúdo do retorno da sua *operação de caminho* dentro do `JSONResponse`. + +Ele usará o código de status padrão ou o que você definir na sua *operação de caminho*. + +## Códigos de status adicionais + +Caso você queira retornar códigos de status adicionais além do código principal, você pode fazer isso retornando um `Response` diretamente, como por exemplo um `JSONResponse`, e definir os códigos de status adicionais diretamente. + +Por exemplo, vamos dizer que você deseja ter uma *operação de caminho* que permita atualizar itens, e retornar um código de status HTTP 200 "OK" quando for bem sucedido. + +Mas você também deseja aceitar novos itens. E quando os itens não existiam, ele os cria, e retorna o código de status HTTP 201 "Created. + +Para conseguir isso, importe `JSONResponse` e retorne o seu conteúdo diretamente, definindo o `status_code` que você deseja: + +{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *} + +/// warning | Aviso + +Quando você retorna um `Response` diretamente, como no exemplo acima, ele será retornado diretamente. + +Ele não será serializado com um modelo, etc. + +Garanta que ele tenha toda informação que você deseja, e que os valores sejam um JSON válido (caso você esteja usando `JSONResponse`). + +/// + +/// note | Detalhes técnicos + +Você também pode utilizar `from starlette.responses import JSONResponse`. + +O **FastAPI** disponibiliza o `starlette.responses` como `fastapi.responses` apenas por conveniência para você, o programador. Porém a maioria dos retornos disponíveis vem diretamente do Starlette. O mesmo com `status`. + +/// + +## OpenAPI e documentação da API + +Se você retorna códigos de status adicionais e retornos diretamente, eles não serão incluídos no esquema do OpenAPI (a documentação da API), porque o FastAPI não tem como saber de antemão o que será retornado. + +Mas você pode documentar isso no seu código, utilizando: [Retornos Adicionais](additional-responses.md){.internal-link target=_blank}. diff --git a/docs/pt/docs/advanced/advanced-dependencies.md b/docs/pt/docs/advanced/advanced-dependencies.md new file mode 100644 index 000000000..f57abba61 --- /dev/null +++ b/docs/pt/docs/advanced/advanced-dependencies.md @@ -0,0 +1,65 @@ +# Dependências avançadas + +## Dependências parametrizadas + +Todas as dependências que vimos até agora são funções ou classes fixas. + +Mas podem ocorrer casos onde você deseja ser capaz de definir parâmetros na dependência, sem ter a necessidade de declarar diversas funções ou classes. + +Vamos imaginar que queremos ter uma dependência que verifica se o parâmetro de consulta `q` possui um valor fixo. + +Porém nós queremos poder parametrizar o conteúdo fixo. + +## Uma instância "chamável" + +Em Python existe uma maneira de fazer com que uma instância de uma classe seja um "chamável". + +Não propriamente a classe (que já é um chamável), mas a instância desta classe. + +Para fazer isso, nós declaramos o método `__call__`: + +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[12] *} + +Neste caso, o `__call__` é o que o **FastAPI** utilizará para verificar parâmetros adicionais e sub dependências, e isso é o que será chamado para passar o valor ao parâmetro na sua *função de operação de rota* posteriormente. + +## Parametrizar a instância + +E agora, nós podemos utilizar o `__init__` para declarar os parâmetros da instância que podemos utilizar para "parametrizar" a dependência: + +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[9] *} + +Neste caso, o **FastAPI** nunca tocará ou se importará com o `__init__`, nós vamos utilizar diretamente em nosso código. + +## Crie uma instância + +Nós poderíamos criar uma instância desta classe com: + +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[18] *} + +E deste modo nós podemos "parametrizar" a nossa dependência, que agora possui `"bar"` dentro dele, como o atributo `checker.fixed_content`. + +## Utilize a instância como dependência + +Então, nós podemos utilizar este `checker` em um `Depends(checker)`, no lugar de `Depends(FixedContentQueryChecker)`, porque a dependência é a instância, `checker`, e não a própria classe. + +E quando a dependência for resolvida, o **FastAPI** chamará este `checker` como: + +```Python +checker(q="somequery") +``` + +...e passar o que quer que isso retorne como valor da dependência em nossa *função de operação de rota* como o parâmetro `fixed_content_included`: + +{* ../../docs_src/dependencies/tutorial011_an_py39.py hl[22] *} + +/// tip | Dica + +Tudo isso parece não ser natural. E pode não estar muito claro ou aparentar ser útil ainda. + +Estes exemplos são intencionalmente simples, porém mostram como tudo funciona. + +Nos capítulos sobre segurança, existem funções utilitárias que são implementadas desta maneira. + +Se você entendeu tudo isso, você já sabe como essas funções utilitárias para segurança funcionam por debaixo dos panos. + +/// diff --git a/docs/pt/docs/advanced/async-tests.md b/docs/pt/docs/advanced/async-tests.md new file mode 100644 index 000000000..a2b79426c --- /dev/null +++ b/docs/pt/docs/advanced/async-tests.md @@ -0,0 +1,99 @@ +# Testes Assíncronos + +Você já viu como testar as suas aplicações **FastAPI** utilizando o `TestClient` que é fornecido. Até agora, você viu apenas como escrever testes síncronos, sem utilizar funções `async`. + +Ser capaz de utilizar funções assíncronas em seus testes pode ser útil, por exemplo, quando você está realizando uma consulta em seu banco de dados de maneira assíncrona. Imagine que você deseja testar realizando requisições para a sua aplicação FastAPI e depois verificar que a sua aplicação inseriu corretamente as informações no banco de dados, ao utilizar uma biblioteca assíncrona para banco de dados. + +Vamos ver como nós podemos fazer isso funcionar. + +## pytest.mark.anyio + +Se quisermos chamar funções assíncronas em nossos testes, as nossas funções de teste precisam ser assíncronas. O AnyIO oferece um plugin bem legal para isso, que nos permite especificar que algumas das nossas funções de teste precisam ser chamadas de forma assíncrona. + +## HTTPX + +Mesmo que a sua aplicação **FastAPI** utilize funções normais com `def` no lugar de `async def`, ela ainda é uma aplicação `async` por baixo dos panos. + +O `TestClient` faz algumas mágicas para invocar a aplicação FastAPI assíncrona em suas funções `def` normais, utilizando o pytest padrão. Porém a mágica não acontece mais quando nós estamos utilizando dentro de funções assíncronas. Ao executar os nossos testes de forma assíncrona, nós não podemos mais utilizar o `TestClient` dentro das nossas funções de teste. + +O `TestClient` é baseado no HTTPX, e felizmente nós podemos utilizá-lo diretamente para testar a API. + +## Exemplo + +Para um exemplos simples, vamos considerar uma estrutura de arquivos semelhante ao descrito em [Bigger Applications](../tutorial/bigger-applications.md){.internal-link target=_blank} e [Testing](../tutorial/testing.md){.internal-link target=_blank}: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +O arquivo `main.py` teria: + +{* ../../docs_src/async_tests/main.py *} + +O arquivo `test_main.py` teria os testes para para o arquivo `main.py`, ele poderia ficar assim: + +{* ../../docs_src/async_tests/test_main.py *} + +## Executá-lo + +Você pode executar os seus testes normalmente via: + +
+ +```console +$ pytest + +---> 100% +``` + +
+ +## Em Detalhes + +O marcador `@pytest.mark.anyio` informa ao pytest que esta função de teste deve ser invocada de maneira assíncrona: + +{* ../../docs_src/async_tests/test_main.py hl[7] *} + +/// tip | Dica + +Note que a função de teste é `async def` agora, no lugar de apenas `def` como quando estávamos utilizando o `TestClient` anteriormente. + +/// + +Então podemos criar um `AsyncClient` com a aplicação, e enviar requisições assíncronas para ela utilizando `await`. + +{* ../../docs_src/async_tests/test_main.py hl[9:12] *} + +Isso é equivalente a: + +```Python +response = client.get('/') +``` + +...que nós utilizamos para fazer as nossas requisições utilizando o `TestClient`. + +/// tip | Dica + +Note que nós estamos utilizando async/await com o novo `AsyncClient` - a requisição é assíncrona. + +/// + +/// warning | Aviso + +Se a sua aplicação depende dos eventos de vida útil (*lifespan*), o `AsyncClient` não acionará estes eventos. Para garantir que eles são acionados, utilize o `LifespanManager` do florimondmanca/asgi-lifespan. + +/// + +## Outras Chamadas de Funções Assíncronas + +Como a função de teste agora é assíncrona, você pode chamar (e `esperar`) outras funções `async` além de enviar requisições para a sua aplicação FastAPI em seus testes, exatamente como você as chamaria em qualquer outro lugar do seu código. + +/// tip | Dica + +Se você se deparar com um `RuntimeError: Task attached to a different loop` ao integrar funções assíncronas em seus testes (e.g. ao utilizar o MotorClient do MongoDB) Lembre-se de instanciar objetos que precisam de um loop de eventos (*event loop*) apenas em funções assíncronas, e.g. um *"callback"* `'@app.on_event("startup")`. + +/// diff --git a/docs/pt/docs/advanced/behind-a-proxy.md b/docs/pt/docs/advanced/behind-a-proxy.md new file mode 100644 index 000000000..6837c9542 --- /dev/null +++ b/docs/pt/docs/advanced/behind-a-proxy.md @@ -0,0 +1,361 @@ +# Atrás de um Proxy + +Em algumas situações, você pode precisar usar um servidor **proxy** como Traefik ou Nginx com uma configuração que adiciona um prefixo de caminho extra que não é visto pela sua aplicação. + +Nesses casos, você pode usar `root_path` para configurar sua aplicação. + +O `root_path` é um mecanismo fornecido pela especificação ASGI (que o FastAPI utiliza, através do Starlette). + +O `root_path` é usado para lidar com esses casos específicos. + +E também é usado internamente ao montar sub-aplicações. + +## Proxy com um prefixo de caminho removido + +Ter um proxy com um prefixo de caminho removido, nesse caso, significa que você poderia declarar um caminho em `/app` no seu código, mas então, você adiciona uma camada no topo (o proxy) que colocaria sua aplicação **FastAPI** sob um caminho como `/api/v1`. + +Nesse caso, o caminho original `/app` seria servido em `/api/v1/app`. + +Embora todo o seu código esteja escrito assumindo que existe apenas `/app`. + +{* ../../docs_src/behind_a_proxy/tutorial001.py hl[6] *} + +E o proxy estaria **"removendo"** o **prefixo do caminho** dinamicamente antes de transmitir a solicitação para o servidor da aplicação (provavelmente Uvicorn via CLI do FastAPI), mantendo sua aplicação convencida de que está sendo servida em `/app`, para que você não precise atualizar todo o seu código para incluir o prefixo `/api/v1`. + +Até aqui, tudo funcionaria normalmente. + +Mas então, quando você abre a interface de documentação integrada (o frontend), ele esperaria obter o OpenAPI schema em `/openapi.json`, em vez de `/api/v1/openapi.json`. + +Então, o frontend (que roda no navegador) tentaria acessar `/openapi.json` e não conseguiria obter o OpenAPI schema. + +Como temos um proxy com um prefixo de caminho de `/api/v1` para nossa aplicação, o frontend precisa buscar o OpenAPI schema em `/api/v1/openapi.json`. + +```mermaid +graph LR + +browser("Browser") +proxy["Proxy on http://0.0.0.0:9999/api/v1/app"] +server["Server on http://127.0.0.1:8000/app"] + +browser --> proxy +proxy --> server +``` + +/// tip | Dica + +O IP `0.0.0.0` é comumente usado para significar que o programa escuta em todos os IPs disponíveis naquela máquina/servidor. + +/// + +A interface de documentação também precisaria do OpenAPI schema para declarar que API `server` está localizado em `/api/v1` (atrás do proxy). Por exemplo: + +```JSON hl_lines="4-8" +{ + "openapi": "3.1.0", + // Mais coisas aqui + "servers": [ + { + "url": "/api/v1" + } + ], + "paths": { + // Mais coisas aqui + } +} +``` + +Neste exemplo, o "Proxy" poderia ser algo como **Traefik**. E o servidor seria algo como CLI do FastAPI com **Uvicorn**, executando sua aplicação FastAPI. + +### Fornecendo o `root_path` + +Para conseguir isso, você pode usar a opção de linha de comando `--root-path` assim: + +
+ +```console +$ fastapi run main.py --root-path /api/v1 + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Se você usar Hypercorn, ele também tem a opção `--root-path`. + +/// note | Detalhes Técnicos + +A especificação ASGI define um `root_path` para esse caso de uso. + +E a opção de linha de comando `--root-path` fornece esse `root_path`. + +/// + +### Verificando o `root_path` atual + +Você pode obter o `root_path` atual usado pela sua aplicação para cada solicitação, ele faz parte do dicionário `scope` (que faz parte da especificação ASGI). + +Aqui estamos incluindo ele na mensagem apenas para fins de demonstração. + +{* ../../docs_src/behind_a_proxy/tutorial001.py hl[8] *} + +Então, se você iniciar o Uvicorn com: + +
+ +```console +$ fastapi run main.py --root-path /api/v1 + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +A resposta seria algo como: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +### Configurando o `root_path` na aplicação FastAPI + +Alternativamente, se você não tiver uma maneira de fornecer uma opção de linha de comando como `--root-path` ou equivalente, você pode definir o parâmetro `--root-path` ao criar sua aplicação FastAPI: + +{* ../../docs_src/behind_a_proxy/tutorial002.py hl[3] *} + +Passar o `root_path`h para `FastAPI` seria o equivalente a passar a opção de linha de comando `--root-path` para Uvicorn ou Hypercorn. + +### Sobre `root_path` + +Tenha em mente que o servidor (Uvicorn) não usará esse `root_path` para nada além de passá-lo para a aplicação. + +Mas se você acessar com seu navegador http://127.0.0.1:8000/app você verá a resposta normal: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +Portanto, ele não esperará ser acessado em `http://127.0.0.1:8000/api/v1/app`. + +O Uvicorn esperará que o proxy acesse o Uvicorn em `http://127.0.0.1:8000/app`, e então seria responsabilidade do proxy adicionar o prefixo extra `/api/v1` no topo. + +## Sobre proxies com um prefixo de caminho removido + +Tenha em mente que um proxy com prefixo de caminho removido é apenas uma das maneiras de configurá-lo. + +Provavelmente, em muitos casos, o padrão será que o proxy não tenha um prefixo de caminho removido. + +Em um caso como esse (sem um prefixo de caminho removido), o proxy escutaria em algo como `https://myawesomeapp.com`, e então se o navegador acessar `https://myawesomeapp.com/api/v1/app` e seu servidor (por exemplo, Uvicorn) escutar em `http://127.0.0.1:8000` o proxy (sem um prefixo de caminho removido) acessaria o Uvicorn no mesmo caminho: `http://127.0.0.1:8000/api/v1/app`. + +## Testando localmente com Traefik + +Você pode facilmente executar o experimento localmente com um prefixo de caminho removido usando Traefik. + +Faça o download do Traefik., Ele é um único binário e você pode extrair o arquivo compactado e executá-lo diretamente do terminal. + +Então, crie um arquivo `traefik.toml` com: + +```TOML hl_lines="3" +[entryPoints] + [entryPoints.http] + address = ":9999" + +[providers] + [providers.file] + filename = "routes.toml" +``` + +Isso diz ao Traefik para escutar na porta 9999 e usar outro arquivo `routes.toml`. + +/// tip | Dica + +Estamos usando a porta 9999 em vez da porta padrão HTTP 80 para que você não precise executá-lo com privilégios de administrador (`sudo`). + +/// + +Agora crie esse outro arquivo `routes.toml`: + +```TOML hl_lines="5 12 20" +[http] + [http.middlewares] + + [http.middlewares.api-stripprefix.stripPrefix] + prefixes = ["/api/v1"] + + [http.routers] + + [http.routers.app-http] + entryPoints = ["http"] + service = "app" + rule = "PathPrefix(`/api/v1`)" + middlewares = ["api-stripprefix"] + + [http.services] + + [http.services.app] + [http.services.app.loadBalancer] + [[http.services.app.loadBalancer.servers]] + url = "http://127.0.0.1:8000" +``` + +Esse arquivo configura o Traefik para usar o prefixo de caminho `/api/v1`. + +E então ele redirecionará suas solicitações para seu Uvicorn rodando em `http://127.0.0.1:8000`. + +Agora inicie o Traefik: + +
+ +```console +$ ./traefik --configFile=traefik.toml + +INFO[0000] Configuration loaded from file: /home/user/awesomeapi/traefik.toml +``` + +
+ +E agora inicie sua aplicação, usando a opção `--root-path`: + +
+ +```console +$ fastapi run main.py --root-path /api/v1 + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +### Verifique as respostas + +Agora, se você for ao URL com a porta para o Uvicorn: http://127.0.0.1:8000/app, você verá a resposta normal: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +/// tip | Dica + +Perceba que, mesmo acessando em `http://127.0.0.1:8000/app`, ele mostra o `root_path` de `/api/v1`, retirado da opção `--root-path`. + +/// + +E agora abra o URL com a porta para o Traefik, incluindo o prefixo de caminho: http://127.0.0.1:9999/api/v1/app. + +Obtemos a mesma resposta: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +mas desta vez no URL com o prefixo de caminho fornecido pelo proxy: `/api/v1`. + +Claro, a ideia aqui é que todos acessariam a aplicação através do proxy, então a versão com o prefixo de caminho `/api/v1` é a "correta". + +E a versão sem o prefixo de caminho (`http://127.0.0.1:8000/app`), fornecida diretamente pelo Uvicorn, seria exclusivamente para o _proxy_ (Traefik) acessá-la. + +Isso demonstra como o Proxy (Traefik) usa o prefixo de caminho e como o servidor (Uvicorn) usa o `root_path` da opção `--root-path`. + +### Verifique a interface de documentação + +Mas aqui está a parte divertida. ✨ + +A maneira "oficial" de acessar a aplicação seria através do proxy com o prefixo de caminho que definimos. Então, como esperaríamos, se você tentar a interface de documentação servida diretamente pelo Uvicorn, sem o prefixo de caminho no URL, ela não funcionará, porque espera ser acessada através do proxy. + +Você pode verificar em http://127.0.0.1:8000/docs: + + + +Mas se acessarmos a interface de documentação no URL "oficial" usando o proxy com a porta `9999`, em `/api/v1/docs`, ela funciona corretamente! 🎉 + +Você pode verificar em http://127.0.0.1:9999/api/v1/docs: + + + +Exatamente como queríamos. ✔️ + +Isso porque o FastAPI usa esse `root_path` para criar o `server` padrão no OpenAPI com o URL fornecido pelo `root_path`. + +## Servidores adicionais + +/// warning | Aviso + +Este é um caso de uso mais avançado. Sinta-se à vontade para pular. + +/// + +Por padrão, o **FastAPI** criará um `server` no OpenAPI schema com o URL para o `root_path`. + +Mas você também pode fornecer outros `servers` alternativos, por exemplo, se quiser que a *mesma* interface de documentação interaja com ambientes de staging e produção. + +Se você passar uma lista personalizada de `servers` e houver um `root_path` (porque sua API está atrás de um proxy), o **FastAPI** inserirá um "server" com esse `root_path` no início da lista. + +Por exemplo: + +{* ../../docs_src/behind_a_proxy/tutorial003.py hl[4:7] *} + +Gerará um OpenAPI schema como: + +```JSON hl_lines="5-7" +{ + "openapi": "3.1.0", + // Mais coisas aqui + "servers": [ + { + "url": "/api/v1" + }, + { + "url": "https://stag.example.com", + "description": "Staging environment" + }, + { + "url": "https://prod.example.com", + "description": "Production environment" + } + ], + "paths": { + // Mais coisas aqui + } +} +``` + +/// tip | Dica + +Perceba o servidor gerado automaticamente com um valor `url` de `/api/v1`, retirado do `root_path`. + +/// + +Na interface de documentação em http://127.0.0.1:9999/api/v1/docs parecerá: + + + +/// tip | Dica + +A interface de documentação interagirá com o servidor que você selecionar. + +/// + +### Desabilitar servidor automático de `root_path` + +Se você não quiser que o **FastAPI** inclua um servidor automático usando o `root_path`, você pode usar o parâmetro `root_path_in_servers=False`: + +{* ../../docs_src/behind_a_proxy/tutorial004.py hl[9] *} + +e então ele não será incluído no OpenAPI schema. + +## Montando uma sub-aplicação + +Se você precisar montar uma sub-aplicação (como descrito em [Sub Aplicações - Montagens](sub-applications.md){.internal-link target=_blank}) enquanto também usa um proxy com `root_path`, você pode fazer isso normalmente, como esperaria. + +O FastAPI usará internamente o `root_path` de forma inteligente, então tudo funcionará. ✨ diff --git a/docs/pt/docs/advanced/custom-response.md b/docs/pt/docs/advanced/custom-response.md new file mode 100644 index 000000000..a0bcc2b97 --- /dev/null +++ b/docs/pt/docs/advanced/custom-response.md @@ -0,0 +1,314 @@ +# Resposta Personalizada - HTML, Stream, File e outras + +Por padrão, o **FastAPI** irá retornar respostas utilizando `JSONResponse`. + +Mas você pode sobrescrever esse comportamento utilizando `Response` diretamente, como visto em [Retornando uma Resposta Diretamente](response-directly.md){.internal-link target=_blank}. + +Mas se você retornar uma `Response` diretamente (ou qualquer subclasse, como `JSONResponse`), os dados não serão convertidos automaticamente (mesmo que você declare um `response_model`), e a documentação não será gerada automaticamente (por exemplo, incluindo o "media type", no cabeçalho HTTP `Content-Type` como parte do esquema OpenAPI gerado). + +Mas você também pode declarar a `Response` que você deseja utilizar (e.g. qualquer subclasse de `Response`), em um *decorador de operação de rota* utilizando o parâmetro `response_class`. + +Os conteúdos que você retorna em sua *função de operador de rota* serão colocados dentro dessa `Response`. + +E se a `Response` tiver um media type JSON (`application/json`), como é o caso com `JSONResponse` e `UJSONResponse`, os dados que você retornar serão automaticamente convertidos (e filtrados) com qualquer `response_model` do Pydantic que for declarado em sua *função de operador de rota*. + +/// note | Nota + +Se você utilizar uma classe de Resposta sem media type, o FastAPI esperará que sua resposta não tenha conteúdo, então ele não irá documentar o formato da resposta na documentação OpenAPI gerada. + +/// + +## Utilizando `ORJSONResponse` + +Por exemplo, se você precisa bastante de performance, você pode instalar e utilizar o `orjson` e definir a resposta para ser uma `ORJSONResponse`. + +Importe a classe, ou subclasse, de `Response` que você deseja utilizar e declare ela no *decorador de operação de rota*. + +Para respostas grandes, retornar uma `Response` diretamente é muito mais rápido que retornar um dicionário. + +Isso ocorre por que, por padrão, o FastAPI irá verificar cada item dentro do dicionário e garantir que ele seja serializável para JSON, utilizando o mesmo[Codificador Compatível com JSON](../tutorial/encoder.md){.internal-link target=_blank} explicado no tutorial. Isso permite que você retorne **objetos abstratos**, como modelos do banco de dados, por exemplo. + +Mas se você tem certeza que o conteúdo que você está retornando é **serializável com JSON**, você pode passá-lo diretamente para a classe de resposta e evitar o trabalho extra que o FastAPI teria ao passar o conteúdo pelo `jsonable_encoder` antes de passar para a classe de resposta. + +{* ../../docs_src/custom_response/tutorial001b.py hl[2,7] *} + +/// info | Informação + +O parâmetro `response_class` também será usado para definir o "media type" da resposta. + +Neste caso, o cabeçalho HTTP `Content-Type` irá ser definido como `application/json`. + +E será documentado como tal no OpenAPI. + +/// + +/// tip | Dica + +A `ORJSONResponse` está disponível apenas no FastAPI, e não no Starlette. + +/// + +## Resposta HTML + +Para retornar uma resposta com HTML diretamente do **FastAPI**, utilize `HTMLResponse`. + +* Importe `HTMLResponse` +* Passe `HTMLResponse` como o parâmetro de `response_class` do seu *decorador de operação de rota*. + +{* ../../docs_src/custom_response/tutorial002.py hl[2,7] *} + +/// info | Informação + +O parâmetro `response_class` também será usado para definir o "media type" da resposta. + +Neste caso, o cabeçalho HTTP `Content-Type` será definido como `text/html`. + +E será documentado como tal no OpenAPI. + +/// + +### Retornando uma `Response` + +Como visto em [Retornando uma Resposta Diretamente](response-directly.md){.internal-link target=_blank}, você também pode sobrescrever a resposta diretamente na sua *operação de rota*, ao retornar ela. + +O mesmo exemplo de antes, retornando uma `HTMLResponse`, poderia parecer com: + +{* ../../docs_src/custom_response/tutorial003.py hl[2,7,19] *} + +/// warning | Aviso + +Uma `Response` retornada diretamente em sua *função de operação de rota* não será documentada no OpenAPI (por exemplo, o `Content-Type` não será documentado) e não será visível na documentação interativa automática. + +/// + +/// info | Informação + +Obviamente, o cabeçalho `Content-Type`, o código de status, etc, virão do objeto `Response` que você retornou. + +/// + +### Documentar no OpenAPI e sobrescrever `Response` + +Se você deseja sobrescrever a resposta dentro de uma função, mas ao mesmo tempo documentar o "media type" no OpenAPI, você pode utilizar o parâmetro `response_class` E retornar um objeto `Response`. + +A `response_class` será usada apenas para documentar o OpenAPI da *operação de rota*, mas sua `Response` será usada como foi definida. + +##### Retornando uma `HTMLResponse` diretamente + +Por exemplo, poderia ser algo como: + +{* ../../docs_src/custom_response/tutorial004.py hl[7,21,23] *} + +Neste exemplo, a função `generate_html_response()` já cria e retorna uma `Response` em vez de retornar o HTML em uma `str`. + +Ao retornar o resultado chamando `generate_html_response()`, você já está retornando uma `Response` que irá sobrescrever o comportamento padrão do **FastAPI**. + +Mas se você passasse uma `HTMLResponse` em `response_class` também, o **FastAPI** saberia como documentar isso no OpenAPI e na documentação interativa como um HTML com `text/html`: + + + +## Respostas disponíveis + +Aqui estão algumas dos tipos de resposta disponíveis. + +Lembre-se que você pode utilizar `Response` para retornar qualquer outra coisa, ou até mesmo criar uma subclasse personalizada. + +/// note | Detalhes Técnicos + +Você também pode utilizar `from starlette.responses import HTMLResponse`. + +O **FastAPI** provê a mesma `starlette.responses` como `fastapi.responses` apenas como uma facilidade para você, desenvolvedor. Mas a maioria das respostas disponíveis vêm diretamente do Starlette. + +/// + +### `Response` + +A classe principal de respostas, todas as outras respostas herdam dela. + +Você pode retorná-la diretamente. + +Ela aceita os seguintes parâmetros: + +* `content` - Uma sequência de caracteres (`str`) ou `bytes`. +* `status_code` - Um código de status HTTP do tipo `int`. +* `headers` - Um dicionário `dict` de strings. +* `media_type` - Uma `str` informando o media type. E.g. `"text/html"`. + +O FastAPI (Starlette, na verdade) irá incluir o cabeçalho Content-Length automaticamente. Ele também irá incluir o cabeçalho Content-Type, baseado no `media_type` e acrescentando uma codificação para tipos textuais. + +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} + +### `HTMLResponse` + +Usa algum texto ou sequência de bytes e retorna uma resposta HTML. Como você leu acima. + +### `PlainTextResponse` + +Usa algum texto ou sequência de bytes para retornar uma resposta de texto não formatado. + +{* ../../docs_src/custom_response/tutorial005.py hl[2,7,9] *} + +### `JSONResponse` + +Pega alguns dados e retorna uma resposta com codificação `application/json`. + +É a resposta padrão utilizada no **FastAPI**, como você leu acima. + +### `ORJSONResponse` + +Uma alternativa mais rápida de resposta JSON utilizando o `orjson`, como você leu acima. + +/// info | Informação + +Essa resposta requer a instalação do pacote `orjson`, com o comando `pip install orjson`, por exemplo. + +/// + +### `UJSONResponse` + +Uma alternativa de resposta JSON utilizando a biblioteca `ujson`. + +/// info | Informação + +Essa resposta requer a instalação do pacote `ujson`, com o comando `pip install ujson`, por exemplo. + +/// + +/// warning | Aviso + +`ujson` é menos cauteloso que a implementação nativa do Python na forma que os casos especiais são tratados + +/// + +{* ../../docs_src/custom_response/tutorial001.py hl[2,7] *} + +/// tip | Dica + +É possível que `ORJSONResponse` seja uma alternativa mais rápida. + +/// + +### `RedirectResponse` + +Retorna um redirecionamento HTTP. Utiliza o código de status 307 (Redirecionamento Temporário) por padrão. + +Você pode retornar uma `RedirectResponse` diretamente: + +{* ../../docs_src/custom_response/tutorial006.py hl[2,9] *} + +--- + +Ou você pode utilizá-la no parâmetro `response_class`: + +{* ../../docs_src/custom_response/tutorial006b.py hl[2,7,9] *} + +Se você fizer isso, então você pode retornar a URL diretamente da sua *função de operação de rota* + +Neste caso, o `status_code` utilizada será o padrão de `RedirectResponse`, que é `307`. + +--- + +Você também pode utilizar o parâmetro `status_code` combinado com o parâmetro `response_class`: + +{* ../../docs_src/custom_response/tutorial006c.py hl[2,7,9] *} + +### `StreamingResponse` + +Recebe uma gerador assíncrono ou um gerador/iterador comum e retorna o corpo da requisição continuamente (stream). + +{* ../../docs_src/custom_response/tutorial007.py hl[2,14] *} + +#### Utilizando `StreamingResponse` com objetos semelhantes a arquivos + +Se você tiver um objeto semelhante a um arquivo (e.g. o objeto retornado por `open()`), você pode criar uma função geradora para iterar sobre esse objeto. + +Dessa forma, você não precisa ler todo o arquivo na memória primeiro, e você pode passar essa função geradora para `StreamingResponse` e retorná-la. + +Isso inclui muitas bibliotecas que interagem com armazenamento em nuvem, processamento de vídeos, entre outras. + +```{ .python .annotate hl_lines="2 10-12 14" } +{!../../docs_src/custom_response/tutorial008.py!} +``` + +1. Essa é a função geradora. É definida como "função geradora" porque contém declarações `yield` nela. +2. Ao utilizar o bloco `with`, nós garantimos que o objeto semelhante a um arquivo é fechado após a função geradora ser finalizada. Isto é, após a resposta terminar de ser enivada. +3. Essa declaração `yield from` informa a função para iterar sobre essa coisa nomeada de `file_like`. E então, para cada parte iterada, fornece essa parte como se viesse dessa função geradora (`iterfile`). + + Então, é uma função geradora que transfere o trabalho de "geração" para alguma outra coisa interna. + + Fazendo dessa forma, podemos colocá-la em um bloco `with`, e assim garantir que o objeto semelhante a um arquivo é fechado quando a função termina. + +/// tip | Dica + +Perceba que aqui estamos utilizando o `open()` da biblioteca padrão que não suporta `async` e `await`, e declaramos a operação de rota com o `def` básico. + +/// + +### `FileResponse` + +Envia um arquivo de forma assíncrona e contínua (stream). +* +Recebe um conjunto de argumentos do construtor diferente dos outros tipos de resposta: + +* `path` - O caminho do arquivo que será transmitido +* `headers` - quaisquer cabeçalhos que serão incluídos, como um dicionário. +* `media_type` - Uma string com o media type. Se não for definida, o media type é inferido a partir do nome ou caminho do arquivo. +* `filename` - Se for definido, é incluído no cabeçalho `Content-Disposition`. + +Respostas de Arquivos incluem o tamanho do arquivo, data da última modificação e ETags apropriados, nos cabeçalhos `Content-Length`, `Last-Modified` e `ETag`, respectivamente. + +{* ../../docs_src/custom_response/tutorial009.py hl[2,10] *} + +Você também pode usar o parâmetro `response_class`: + +{* ../../docs_src/custom_response/tutorial009b.py hl[2,8,10] *} + +Nesse caso, você pode retornar o caminho do arquivo diretamente da sua *função de operação de rota*. + +## Classe de resposta personalizada + +Você pode criar sua própria classe de resposta, herdando de `Response` e usando essa nova classe. + +Por exemplo, vamos supor que você queira utilizar o `orjson`, mas com algumas configurações personalizadas que não estão incluídas na classe `ORJSONResponse`. + +Vamos supor também que você queira retornar um JSON indentado e formatado, então você quer utilizar a opção `orjson.OPT_INDENT_2` do orjson. + +Você poderia criar uma classe `CustomORJSONResponse`. A principal coisa a ser feita é sobrecarregar o método render da classe Response, `Response.render(content)`, que retorna o conteúdo em bytes, para retornar o conteúdo que você deseja: + +{* ../../docs_src/custom_response/tutorial009c.py hl[9:14,17] *} + +Agora em vez de retornar: + +```json +{"message": "Hello World"} +``` + +...essa resposta retornará: + +```json +{ + "message": "Hello World" +} +``` + +Obviamente, você provavelmente vai encontrar maneiras muito melhores de se aproveitar disso do que a formatação de JSON. 😉 + +## Classe de resposta padrão + +Quando você criar uma instância da classe **FastAPI** ou um `APIRouter` você pode especificar qual classe de resposta utilizar por padrão. + +O padrão que define isso é o `default_response_class`. + +No exemplo abaixo, o **FastAPI** irá utilizar `ORJSONResponse` por padrão, em todas as *operações de rota*, em vez de `JSONResponse`. + +{* ../../docs_src/custom_response/tutorial010.py hl[2,4] *} + +/// tip | Dica + +Você ainda pode substituir `response_class` em *operações de rota* como antes. + +/// + +## Documentação adicional + +Você também pode declarar o media type e muitos outros detalhes no OpenAPI utilizando `responses`: [Retornos Adicionais no OpenAPI](additional-responses.md){.internal-link target=_blank}. diff --git a/docs/pt/docs/advanced/dataclasses.md b/docs/pt/docs/advanced/dataclasses.md new file mode 100644 index 000000000..600c8c268 --- /dev/null +++ b/docs/pt/docs/advanced/dataclasses.md @@ -0,0 +1,97 @@ +# Usando Dataclasses + +FastAPI é construído em cima do **Pydantic**, e eu tenho mostrado como usar modelos Pydantic para declarar requisições e respostas. + +Mas o FastAPI também suporta o uso de `dataclasses` da mesma forma: + +{* ../../docs_src/dataclasses/tutorial001.py hl[1,7:12,19:20] *} + +Isso ainda é suportado graças ao **Pydantic**, pois ele tem suporte interno para `dataclasses`. + +Então, mesmo com o código acima que não usa Pydantic explicitamente, o FastAPI está usando Pydantic para converter essas dataclasses padrão para a versão do Pydantic. + +E claro, ele suporta o mesmo: + +* validação de dados +* serialização de dados +* documentação de dados, etc. + +Isso funciona da mesma forma que com os modelos Pydantic. E na verdade é alcançado da mesma maneira por baixo dos panos, usando Pydantic. + +/// info | Informação + +Lembre-se de que dataclasses não podem fazer tudo o que os modelos Pydantic podem fazer. + +Então, você ainda pode precisar usar modelos Pydantic. + +Mas se você tem um monte de dataclasses por aí, este é um truque legal para usá-las para alimentar uma API web usando FastAPI. 🤓 + +/// + +## Dataclasses em `response_model` + +Você também pode usar `dataclasses` no parâmetro `response_model`: + +{* ../../docs_src/dataclasses/tutorial002.py hl[1,7:13,19] *} + +A dataclass será automaticamente convertida para uma dataclass Pydantic. + +Dessa forma, seu esquema aparecerá na interface de documentação da API: + + + +## Dataclasses em Estruturas de Dados Aninhadas + +Você também pode combinar `dataclasses` com outras anotações de tipo para criar estruturas de dados aninhadas. + +Em alguns casos, você ainda pode ter que usar a versão do Pydantic das `dataclasses`. Por exemplo, se você tiver erros com a documentação da API gerada automaticamente. + +Nesse caso, você pode simplesmente trocar as `dataclasses` padrão por `pydantic.dataclasses`, que é um substituto direto: + +```{ .python .annotate hl_lines="1 5 8-11 14-17 23-25 28" } +{!../../docs_src/dataclasses/tutorial003.py!} +``` + +1. Ainda importamos `field` das `dataclasses` padrão. + +2. `pydantic.dataclasses` é um substituto direto para `dataclasses`. + +3. A dataclass `Author` inclui uma lista de dataclasses `Item`. + +4. A dataclass `Author` é usada como o parâmetro `response_model`. + +5. Você pode usar outras anotações de tipo padrão com dataclasses como o corpo da requisição. + + Neste caso, é uma lista de dataclasses `Item`. + +6. Aqui estamos retornando um dicionário que contém `items`, que é uma lista de dataclasses. + + O FastAPI ainda é capaz de serializar os dados para JSON. + +7. Aqui o `response_model` está usando uma anotação de tipo de uma lista de dataclasses `Author`. + + Novamente, você pode combinar `dataclasses` com anotações de tipo padrão. + +8. Note que esta *função de operação de rota* usa `def` regular em vez de `async def`. + + Como sempre, no FastAPI você pode combinar `def` e `async def` conforme necessário. + + Se você precisar de uma atualização sobre quando usar qual, confira a seção _"Com pressa?"_ na documentação sobre [`async` e `await`](../async.md#in-a-hurry){.internal-link target=_blank}. + +9. Esta *função de operação de rota* não está retornando dataclasses (embora pudesse), mas uma lista de dicionários com dados internos. + + O FastAPI usará o parâmetro `response_model` (que inclui dataclasses) para converter a resposta. + +Você pode combinar `dataclasses` com outras anotações de tipo em muitas combinações diferentes para formar estruturas de dados complexas. + +Confira as dicas de anotação no código acima para ver mais detalhes específicos. + +## Saiba Mais + +Você também pode combinar `dataclasses` com outros modelos Pydantic, herdar deles, incluí-los em seus próprios modelos, etc. + +Para saber mais, confira a documentação do Pydantic sobre dataclasses. + +## Versão + +Isso está disponível desde a versão `0.67.0` do FastAPI. 🔖 diff --git a/docs/pt/docs/advanced/events.md b/docs/pt/docs/advanced/events.md index 7f6cb6f5d..504b6db57 100644 --- a/docs/pt/docs/advanced/events.md +++ b/docs/pt/docs/advanced/events.md @@ -31,26 +31,25 @@ Vamos iniciar com um exemplo e ver isso detalhadamente. Nós criamos uma função assíncrona chamada `lifespan()` com `yield` como este: -```Python hl_lines="16 19" -{!../../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[16,19] *} Aqui nós estamos simulando a *inicialização* custosa do carregamento do modelo colocando a (falsa) função de modelo no dicionário com modelos de _machine learning_ antes do `yield`. Este código será executado **antes** da aplicação **começar a receber requisições**, durante a *inicialização*. E então, logo após o `yield`, descarregaremos o modelo. Esse código será executado **após** a aplicação **terminar de lidar com as requisições**, pouco antes do *encerramento*. Isso poderia, por exemplo, liberar recursos como memória ou GPU. -!!! tip "Dica" - O `shutdown` aconteceria quando você estivesse **encerrando** a aplicação. +/// tip | Dica + +O `shutdown` aconteceria quando você estivesse **encerrando** a aplicação. - Talvez você precise inicializar uma nova versão, ou apenas cansou de executá-la. 🤷 +Talvez você precise inicializar uma nova versão, ou apenas cansou de executá-la. 🤷 + +/// ### Função _lifespan_ A primeira coisa a notar, é que estamos definindo uma função assíncrona com `yield`. Isso é muito semelhante à Dependências com `yield`. -```Python hl_lines="14-19" -{!../../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[14:19] *} A primeira parte da função, antes do `yield`, será executada **antes** da aplicação inicializar. @@ -62,9 +61,7 @@ Se você verificar, a função está decorada com um `@asynccontextmanager`. Que converte a função em algo chamado de "**Gerenciador de Contexto Assíncrono**". -```Python hl_lines="1 13" -{!../../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[1,13] *} Um **gerenciador de contexto** em Python é algo que você pode usar em uma declaração `with`, por exemplo, `open()` pode ser usado como um gerenciador de contexto: @@ -86,16 +83,17 @@ No nosso exemplo de código acima, nós não usamos ele diretamente, mas nós pa O parâmetro `lifespan` da aplicação `FastAPI` usa um **Gerenciador de Contexto Assíncrono**, então nós podemos passar nosso novo gerenciador de contexto assíncrono do `lifespan` para ele. -```Python hl_lines="22" -{!../../../docs_src/events/tutorial003.py!} -``` +{* ../../docs_src/events/tutorial003.py hl[22] *} ## Eventos alternativos (deprecados) -!!! warning "Aviso" - A maneira recomendada para lidar com a *inicialização* e o *encerramento* é usando o parâmetro `lifespan` da aplicação `FastAPI` como descrito acima. +/// warning | Aviso + +A maneira recomendada para lidar com a *inicialização* e o *encerramento* é usando o parâmetro `lifespan` da aplicação `FastAPI` como descrito acima. + +Você provavelmente pode pular essa parte. - Você provavelmente pode pular essa parte. +/// Existe uma forma alternativa para definir a execução dessa lógica durante *inicialização* e durante *encerramento*. @@ -107,9 +105,7 @@ Essas funções podem ser declaradas com `async def` ou `def` normal. Para adicionar uma função que deve rodar antes da aplicação iniciar, declare-a com o evento `"startup"`: -```Python hl_lines="8" -{!../../../docs_src/events/tutorial001.py!} -``` +{* ../../docs_src/events/tutorial001.py hl[8] *} Nesse caso, a função de manipulação de evento `startup` irá inicializar os itens do "banco de dados" (só um `dict`) com alguns valores. @@ -121,23 +117,27 @@ E sua aplicação não irá começar a receber requisições até que todos os m Para adicionar uma função que deve ser executada quando a aplicação estiver encerrando, declare ela com o evento `"shutdown"`: -```Python hl_lines="6" -{!../../../docs_src/events/tutorial002.py!} -``` +{* ../../docs_src/events/tutorial002.py hl[6] *} Aqui, a função de manipulação de evento `shutdown` irá escrever uma linha de texto `"Application shutdown"` no arquivo `log.txt`. -!!! info "Informação" - Na função `open()`, o `mode="a"` significa "acrescentar", então, a linha irá ser adicionada depois de qualquer coisa que esteja naquele arquivo, sem sobrescrever o conteúdo anterior. +/// info | Informação + +Na função `open()`, o `mode="a"` significa "acrescentar", então, a linha irá ser adicionada depois de qualquer coisa que esteja naquele arquivo, sem sobrescrever o conteúdo anterior. + +/// -!!! tip "Dica" - Perceba que nesse caso nós estamos usando a função padrão do Python `open()` que interage com um arquivo. +/// tip | Dica - Então, isso envolve I/O (input/output), que exige "esperar" que coisas sejam escritas em disco. +Perceba que nesse caso nós estamos usando a função padrão do Python `open()` que interage com um arquivo. - Mas `open()` não usa `async` e `await`. +Então, isso envolve I/O (input/output), que exige "esperar" que coisas sejam escritas em disco. - Então, nós declaramos uma função de manipulação de evento com o padrão `def` ao invés de `async def`. +Mas `open()` não usa `async` e `await`. + +Então, nós declaramos uma função de manipulação de evento com o padrão `def` ao invés de `async def`. + +/// ### `startup` e `shutdown` juntos @@ -153,11 +153,14 @@ Só um detalhe técnico para nerds curiosos. 🤓 Por baixo, na especificação técnica ASGI, essa é a parte do Protocolo Lifespan, e define eventos chamados `startup` e `shutdown`. -!!! info "Informação" - Você pode ler mais sobre o manipulador `lifespan` do Starlette na Documentação do Lifespan Starlette. +/// info | Informação + +Você pode ler mais sobre o manipulador `lifespan` do Starlette na Documentação do Lifespan Starlette. + +Incluindo como manipular estado do lifespan que pode ser usado em outras áreas do seu código. - Incluindo como manipular estado do lifespan que pode ser usado em outras áreas do seu código. +/// ## Sub Aplicações -🚨 Tenha em mente que esses eventos de lifespan (de inicialização e desligamento) irão somente ser executados para a aplicação principal, não para [Sub Aplicações - Montagem](./sub-applications.md){.internal-link target=_blank}. +🚨 Tenha em mente que esses eventos de lifespan (de inicialização e desligamento) irão somente ser executados para a aplicação principal, não para [Sub Aplicações - Montagem](sub-applications.md){.internal-link target=_blank}. diff --git a/docs/pt/docs/advanced/generate-clients.md b/docs/pt/docs/advanced/generate-clients.md new file mode 100644 index 000000000..04d7c0071 --- /dev/null +++ b/docs/pt/docs/advanced/generate-clients.md @@ -0,0 +1,261 @@ +# Generate Clients + +Como o **FastAPI** é baseado na especificação **OpenAPI**, você obtém compatibilidade automática com muitas ferramentas, incluindo a documentação automática da API (fornecida pelo Swagger UI). + +Uma vantagem particular que nem sempre é óbvia é que você pode **gerar clientes** (às vezes chamados de **SDKs**) para a sua API, para muitas **linguagens de programação** diferentes. + +## Geradores de Clientes OpenAPI + +Existem muitas ferramentas para gerar clientes a partir do **OpenAPI**. + +Uma ferramenta comum é o OpenAPI Generator. + +Se voce está construindo um **frontend**, uma alternativa muito interessante é o openapi-ts. + +## Geradores de Clientes e SDKs - Patrocinadores + +Existem também alguns geradores de clientes e SDKs baseados na OpenAPI (FastAPI) **patrocinados por empresas**, em alguns casos eles podem oferecer **recursos adicionais** além de SDKs/clientes gerados de alta qualidade. + +Alguns deles também ✨ [**patrocinam o FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, isso garante o **desenvolvimento** contínuo e saudável do FastAPI e seu **ecossistema**. + +E isso mostra o verdadeiro compromisso deles com o FastAPI e sua **comunidade** (você), pois eles não apenas querem fornecer um **bom serviço**, mas também querem garantir que você tenha um **framework bom e saudável**, o FastAPI. 🙇 + +Por exemplo, você pode querer experimentar: + +* Speakeasy +* Stainless +* liblab + +Existem também várias outras empresas que oferecem serviços semelhantes que você pode pesquisar e encontrar online. 🤓 + +## Gerar um Cliente Frontend TypeScript + +Vamos começar com um aplicativo **FastAPI** simples: + +{* ../../docs_src/generate_clients/tutorial001_py39.py hl[7:9,12:13,16:17,21] *} + +Note que as *operações de rota* definem os modelos que usam para o corpo da requisição e o corpo da resposta, usando os modelos `Item` e `ResponseMessage`. + +### Documentação da API + +Se você acessar a documentação da API, verá que ela tem os **schemas** para os dados a serem enviados nas requisições e recebidos nas respostas: + + + +Você pode ver esses schemas porque eles foram declarados com os modelos no app. + +Essas informações estão disponíveis no **OpenAPI schema** do app e são mostradas na documentação da API (pelo Swagger UI). + +E essas mesmas informações dos modelos que estão incluídas no OpenAPI são o que pode ser usado para **gerar o código do cliente**. + +### Gerar um Cliente TypeScript + +Agora que temos o app com os modelos, podemos gerar o código do cliente para o frontend. + +#### Instalar o `openapi-ts` + +Você pode instalar o `openapi-ts` no seu código frontend com: + +
+ +```console +$ npm install @hey-api/openapi-ts --save-dev + +---> 100% +``` + +
+ +#### Gerar o Código do Cliente + +Para gerar o código do cliente, você pode usar a aplicação de linha de comando `openapi-ts` que agora está instalada. + +Como ela está instalada no projeto local, você provavelmente não conseguiria chamar esse comando diretamente, mas você o colocaria no seu arquivo `package.json`. + +Poderia ser assim: + +```JSON hl_lines="7" +{ + "name": "frontend-app", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "generate-client": "openapi-ts --input http://localhost:8000/openapi.json --output ./src/client --client axios" + }, + "author": "", + "license": "", + "devDependencies": { + "@hey-api/openapi-ts": "^0.27.38", + "typescript": "^4.6.2" + } +} +``` + +Depois de ter esse script NPM `generate-client` lá, você pode executá-lo com: + +
+ +```console +$ npm run generate-client + +frontend-app@1.0.0 generate-client /home/user/code/frontend-app +> openapi-ts --input http://localhost:8000/openapi.json --output ./src/client --client axios +``` + +
+ +Esse comando gerará o código em `./src/client` e usará o `axios` (a biblioteca HTTP frontend) internamente. + +### Experimente o Código do Cliente + +Agora você pode importar e usar o código do cliente, ele poderia ser assim, observe que você obtém preenchimento automático para os métodos: + + + +Você também obterá preenchimento automático para o corpo a ser enviado: + + + +/// tip | Dica + +Observe o preenchimento automático para `name` e `price`, que foi definido no aplicativo FastAPI, no modelo `Item`. + +/// + +Você terá erros em linha para os dados que você envia: + + + +O objeto de resposta também terá preenchimento automático: + + + +## App FastAPI com Tags + +Em muitos casos seu app FastAPI será maior, e você provavelmente usará tags para separar diferentes grupos de *operações de rota*. + +Por exemplo, você poderia ter uma seção para **items** e outra seção para **users**, e elas poderiam ser separadas por tags: + +{* ../../docs_src/generate_clients/tutorial002_py39.py hl[21,26,34] *} + +### Gerar um Cliente TypeScript com Tags + +Se você gerar um cliente para um app FastAPI usando tags, normalmente também separará o código do cliente com base nas tags. + +Dessa forma, você poderá ter as coisas ordenadas e agrupadas corretamente para o código do cliente: + + + +Nesse caso você tem: + +* `ItemsService` +* `UsersService` + +### Nomes dos Métodos do Cliente + +Agora os nomes dos métodos gerados como `createItemItemsPost` não parecem muito "limpos": + +```TypeScript +ItemsService.createItemItemsPost({name: "Plumbus", price: 5}) +``` + +...isto ocorre porque o gerador de clientes usa o **operation ID** interno do OpenAPI para cada *operação de rota*. + +O OpenAPI exige que cada operation ID seja único em todas as *operações de rota*, então o FastAPI usa o **nome da função**, o **caminho** e o **método/operacao HTTP** para gerar esse operation ID, porque dessa forma ele pode garantir que os operation IDs sejam únicos. + +Mas eu vou te mostrar como melhorar isso a seguir. 🤓 + +### IDs de Operação Personalizados e Melhores Nomes de Método + +Você pode **modificar** a maneira como esses IDs de operação são **gerados** para torná-los mais simples e ter **nomes de método mais simples** nos clientes. + +Neste caso, você terá que garantir que cada ID de operação seja **único** de alguma outra maneira. + +Por exemplo, você poderia garantir que cada *operação de rota* tenha uma tag, e então gerar o ID da operação com base na **tag** e no **nome** da *operação de rota* (o nome da função). + +### Função Personalizada para Gerar IDs de Operação Únicos + +O FastAPI usa um **ID único** para cada *operação de rota*, ele é usado para o **ID da operação** e também para os nomes de quaisquer modelos personalizados necessários, para requisições ou respostas. + +Você pode personalizar essa função. Ela recebe uma `APIRoute` e gera uma string. + +Por exemplo, aqui está usando a primeira tag (você provavelmente terá apenas uma tag) e o nome da *operação de rota* (o nome da função). + +Você pode então passar essa função personalizada para o **FastAPI** como o parâmetro `generate_unique_id_function`: + +{* ../../docs_src/generate_clients/tutorial003_py39.py hl[6:7,10] *} + +### Gerar um Cliente TypeScript com IDs de Operação Personalizados + +Agora, se você gerar o cliente novamente, verá que ele tem os nomes dos métodos melhorados: + + + +Como você pode ver, os nomes dos métodos agora têm a tag e, em seguida, o nome da função. Agora eles não incluem informações do caminho da URL e da operação HTTP. + +### Pré-processar a Especificação OpenAPI para o Gerador de Clientes + +O código gerado ainda tem algumas **informações duplicadas**. + +Nós já sabemos que esse método está relacionado aos **items** porque essa palavra está no `ItemsService` (retirada da tag), mas ainda temos o nome da tag prefixado no nome do método também. 😕 + +Provavelmente ainda queremos mantê-lo para o OpenAPI em geral, pois isso garantirá que os IDs de operação sejam **únicos**. + +Mas para o cliente gerado, poderíamos **modificar** os IDs de operação do OpenAPI logo antes de gerar os clientes, apenas para tornar esses nomes de método mais **simples**. + +Poderíamos baixar o JSON do OpenAPI para um arquivo `openapi.json` e então poderíamos **remover essa tag prefixada** com um script como este: + +{* ../../docs_src/generate_clients/tutorial004.py *} + +//// tab | Node.js + +```Javascript +{!> ../../docs_src/generate_clients/tutorial004.js!} +``` + +//// + +Com isso, os IDs de operação seriam renomeados de coisas como `items-get_items` para apenas `get_items`, dessa forma o gerador de clientes pode gerar nomes de métodos mais simples. + +### Gerar um Cliente TypeScript com o OpenAPI Pré-processado + +Agora, como o resultado final está em um arquivo `openapi.json`, você modificaria o `package.json` para usar esse arquivo local, por exemplo: + +```JSON hl_lines="7" +{ + "name": "frontend-app", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "generate-client": "openapi-ts --input ./openapi.json --output ./src/client --client axios" + }, + "author": "", + "license": "", + "devDependencies": { + "@hey-api/openapi-ts": "^0.27.38", + "typescript": "^4.6.2" + } +} +``` + +Depois de gerar o novo cliente, você teria agora **nomes de métodos "limpos"**, com todo o **preenchimento automático**, **erros em linha**, etc: + + + +## Benefícios + +Ao usar os clientes gerados automaticamente, você teria **preenchimento automático** para: + +* Métodos. +* Corpo de requisições, parâmetros da query, etc. +* Corpo de respostas. + +Você também teria **erros em linha** para tudo. + +E sempre que você atualizar o código do backend, e **regenerar** o frontend, ele teria quaisquer novas *operações de rota* disponíveis como métodos, as antigas removidas, e qualquer outra alteração seria refletida no código gerado. 🤓 + +Isso também significa que se algo mudar, será **refletido** no código do cliente automaticamente. E se você **construir** o cliente, ele dará erro se houver alguma **incompatibilidade** nos dados usados. + +Então, você **detectaria vários erros** muito cedo no ciclo de desenvolvimento, em vez de ter que esperar que os erros apareçam para seus usuários finais em produção e então tentar depurar onde está o problema. ✨ diff --git a/docs/pt/docs/advanced/index.md b/docs/pt/docs/advanced/index.md index 7e276f732..22ba2bf4a 100644 --- a/docs/pt/docs/advanced/index.md +++ b/docs/pt/docs/advanced/index.md @@ -2,18 +2,21 @@ ## Recursos Adicionais -O [Tutorial - Guia de Usuário](../tutorial/){.internal-link target=_blank} deve ser o suficiente para dar a você um tour por todos os principais recursos do **FastAPI**. +O [Tutorial - Guia de Usuário](../tutorial/index.md){.internal-link target=_blank} deve ser o suficiente para dar a você um tour por todos os principais recursos do **FastAPI**. Na próxima seção você verá outras opções, configurações, e recursos adicionais. -!!! tip "Dica" - As próximas seções **não são necessáriamente "avançadas"** +/// tip | Dica - E é possível que para seu caso de uso, a solução esteja em uma delas. +As próximas seções **não são necessáriamente "avançadas"** + +E é possível que para seu caso de uso, a solução esteja em uma delas. + +/// ## Leia o Tutorial primeiro -Você ainda pode usar a maior parte dos recursos no **FastAPI** com o conhecimento do [Tutorial - Guia de Usuário](../tutorial/){.internal-link target=_blank}. +Você ainda pode usar a maior parte dos recursos no **FastAPI** com o conhecimento do [Tutorial - Guia de Usuário](../tutorial/index.md){.internal-link target=_blank}. E as próximas seções assumem que você já leu ele, e que você conhece suas ideias principais. diff --git a/docs/pt/docs/advanced/middleware.md b/docs/pt/docs/advanced/middleware.md new file mode 100644 index 000000000..8167f7d27 --- /dev/null +++ b/docs/pt/docs/advanced/middleware.md @@ -0,0 +1,96 @@ +# Middleware Avançado + +No tutorial principal você leu como adicionar [Middleware Personalizado](../tutorial/middleware.md){.internal-link target=_blank} à sua aplicação. + +E então você também leu como lidar com [CORS com o `CORSMiddleware`](../tutorial/cors.md){.internal-link target=_blank}. + +Nesta seção, veremos como usar outros middlewares. + +## Adicionando middlewares ASGI + +Como o **FastAPI** é baseado no Starlette e implementa a especificação ASGI, você pode usar qualquer middleware ASGI. + +O middleware não precisa ser feito para o FastAPI ou Starlette para funcionar, desde que siga a especificação ASGI. + +No geral, os middlewares ASGI são classes que esperam receber um aplicativo ASGI como o primeiro argumento. + +Então, na documentação de middlewares ASGI de terceiros, eles provavelmente dirão para você fazer algo como: + +```Python +from unicorn import UnicornMiddleware + +app = SomeASGIApp() + +new_app = UnicornMiddleware(app, some_config="rainbow") +``` + +Mas, o FastAPI (na verdade, o Starlette) fornece uma maneira mais simples de fazer isso que garante que os middlewares internos lidem com erros do servidor e que os manipuladores de exceções personalizados funcionem corretamente. + +Para isso, você usa `app.add_middleware()` (como no exemplo para CORS). + +```Python +from fastapi import FastAPI +from unicorn import UnicornMiddleware + +app = FastAPI() + +app.add_middleware(UnicornMiddleware, some_config="rainbow") +``` + +`app.add_middleware()` recebe uma classe de middleware como o primeiro argumento e quaisquer argumentos adicionais a serem passados para o middleware. + +## Middlewares Integrados + +**FastAPI** inclui vários middlewares para casos de uso comuns, veremos a seguir como usá-los. + +/// note | Detalhes Técnicos + +Para o próximo exemplo, você também poderia usar `from starlette.middleware.something import SomethingMiddleware`. + +**FastAPI** fornece vários middlewares em `fastapi.middleware` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria dos middlewares disponíveis vem diretamente do Starlette. + +/// + +## `HTTPSRedirectMiddleware` + +Garante que todas as requisições devem ser `https` ou `wss`. + +Qualquer requisição para `http` ou `ws` será redirecionada para o esquema seguro. + +{* ../../docs_src/advanced_middleware/tutorial001.py hl[2,6] *} + +## `TrustedHostMiddleware` + +Garante que todas as requisições recebidas tenham um cabeçalho `Host` corretamente configurado, a fim de proteger contra ataques de cabeçalho de host HTTP. + +{* ../../docs_src/advanced_middleware/tutorial002.py hl[2,6:8] *} + +Os seguintes argumentos são suportados: + +* `allowed_hosts` - Uma lista de nomes de domínio que são permitidos como nomes de host. Domínios com coringa, como `*.example.com`, são suportados para corresponder a subdomínios. Para permitir qualquer nome de host, use `allowed_hosts=["*"]` ou omita o middleware. + +Se uma requisição recebida não for validada corretamente, uma resposta `400` será enviada. + +## `GZipMiddleware` + +Gerencia respostas GZip para qualquer requisição que inclua `"gzip"` no cabeçalho `Accept-Encoding`. + +O middleware lidará com respostas padrão e de streaming. + +{* ../../docs_src/advanced_middleware/tutorial003.py hl[2,6] *} + +Os seguintes argumentos são suportados: + +* `minimum_size` - Não comprima respostas menores que este tamanho mínimo em bytes. O padrão é `500`. +* `compresslevel` - Usado durante a compressão GZip. É um inteiro variando de 1 a 9. O padrão é `9`. Um valor menor resulta em uma compressão mais rápida, mas em arquivos maiores, enquanto um valor maior resulta em uma compressão mais lenta, mas em arquivos menores. + +## Outros middlewares + +Há muitos outros middlewares ASGI. + +Por exemplo: + +* Uvicorn's `ProxyHeadersMiddleware` +* MessagePack + +Para checar outros middlewares disponíveis, confira Documentação de Middlewares do Starlette e a Lista Incrível do ASGI. diff --git a/docs/pt/docs/advanced/openapi-callbacks.md b/docs/pt/docs/advanced/openapi-callbacks.md new file mode 100644 index 000000000..b0659d3d6 --- /dev/null +++ b/docs/pt/docs/advanced/openapi-callbacks.md @@ -0,0 +1,186 @@ +# Callbacks na OpenAPI + +Você poderia criar uma API com uma *operação de rota* que poderia acionar uma solicitação a uma *API externa* criada por outra pessoa (provavelmente o mesmo desenvolvedor que estaria *usando* sua API). + +O processo que acontece quando seu aplicativo de API chama a *API externa* é chamado de "callback". Porque o software que o desenvolvedor externo escreveu envia uma solicitação para sua API e então sua API *chama de volta*, enviando uma solicitação para uma *API externa* (que provavelmente foi criada pelo mesmo desenvolvedor). + +Nesse caso, você poderia querer documentar como essa API externa *deveria* ser. Que *operação de rota* ela deveria ter, que corpo ela deveria esperar, que resposta ela deveria retornar, etc. + +## Um aplicativo com callbacks + +Vamos ver tudo isso com um exemplo. + +Imagine que você tem um aplicativo que permite criar faturas. + +Essas faturas terão um `id`, `title` (opcional), `customer` e `total`. + +O usuário da sua API (um desenvolvedor externo) criará uma fatura em sua API com uma solicitação POST. + +Então sua API irá (vamos imaginar): + +* Enviar uma solicitação de pagamento para o desenvolvedor externo. +* Coletar o dinheiro. +* Enviar a notificação de volta para o usuário da API (o desenvolvedor externo). +* Isso será feito enviando uma solicitação POST (de *sua API*) para alguma *API externa* fornecida por esse desenvolvedor externo (este é o "callback"). + +## O aplicativo **FastAPI** normal + +Vamos primeiro ver como o aplicativo da API normal se pareceria antes de adicionar o callback. + +Ele terá uma *operação de rota* que receberá um corpo `Invoice`, e um parâmetro de consulta `callback_url` que conterá a URL para o callback. + +Essa parte é bastante normal, a maior parte do código provavelmente já é familiar para você: + +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[9:13,36:53] *} + +/// tip | Dica + +O parâmetro de consulta `callback_url` usa um tipo Pydantic Url. + +/// + +A única coisa nova é o argumento `callbacks=invoices_callback_router.routes` no decorador da *operação de rota*. Veremos o que é isso a seguir. + +## Documentando o callback + +O código real do callback dependerá muito do seu próprio aplicativo de API. + +E provavelmente variará muito de um aplicativo para o outro. + +Poderia ser apenas uma ou duas linhas de código, como: + +```Python +callback_url = "https://example.com/api/v1/invoices/events/" +httpx.post(callback_url, json={"description": "Invoice paid", "paid": True}) +``` + +Mas possivelmente a parte mais importante do callback é garantir que o usuário da sua API (o desenvolvedor externo) implemente a *API externa* corretamente, de acordo com os dados que *sua API* vai enviar no corpo da solicitação do callback, etc. + +Então, o que faremos a seguir é adicionar o código para documentar como essa *API externa* deve ser para receber o callback de *sua API*. + +A documentação aparecerá na interface do Swagger em `/docs` em sua API, e permitirá que os desenvolvedores externos saibam como construir a *API externa*. + +Esse exemplo não implementa o callback em si (que poderia ser apenas uma linha de código), apenas a parte da documentação. + +/// tip | Dica + +O callback real é apenas uma solicitação HTTP. + +Quando implementando o callback por você mesmo, você pode usar algo como HTTPX ou Requisições. + +/// + +## Escrevendo o código de documentação do callback + +Esse código não será executado em seu aplicativo, nós só precisamos dele para *documentar* como essa *API externa* deveria ser. + +Mas, você já sabe como criar facilmente documentação automática para uma API com o **FastAPI**. + +Então vamos usar esse mesmo conhecimento para documentar como a *API externa* deveria ser... criando as *operações de rota* que a *API externa* deveria implementar (as que sua API irá chamar). + +/// tip | Dica + +Quando escrever o código para documentar um callback, pode ser útil imaginar que você é aquele *desenvolvedor externo*. E que você está atualmente implementando a *API externa*, não *sua API*. + +Adotar temporariamente esse ponto de vista (do *desenvolvedor externo*) pode ajudar a sentir que é mais óbvio onde colocar os parâmetros, o modelo Pydantic para o corpo, para a resposta, etc. para essa *API externa*. + +/// + +### Criar um `APIRouter` para o callback + +Primeiramente crie um novo `APIRouter` que conterá um ou mais callbacks. + +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[3,25] *} + +### Crie a *operação de rota* do callback + +Para criar a *operação de rota* do callback, use o mesmo `APIRouter` que você criou acima. + +Ele deve parecer exatamente como uma *operação de rota* normal do FastAPI: + +* Ele provavelmente deveria ter uma declaração do corpo que deveria receber, por exemplo. `body: InvoiceEvent`. +* E também deveria ter uma declaração de um código de status de resposta, por exemplo. `response_model=InvoiceEventReceived`. + +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[16:18,21:22,28:32] *} + +Há 2 diferenças principais de uma *operação de rota* normal: + +* Ela não necessita ter nenhum código real, porque seu aplicativo nunca chamará esse código. Ele é usado apenas para documentar a *API externa*. Então, a função poderia ter apenas `pass`. +* A *rota* pode conter uma expressão OpenAPI 3 (veja mais abaixo) onde pode usar variáveis com parâmetros e partes da solicitação original enviada para *sua API*. + +### A expressão do caminho do callback + +A *rota* do callback pode ter uma expressão OpenAPI 3 que pode conter partes da solicitação original enviada para *sua API*. + +Nesse caso, é a `str`: + +```Python +"{$callback_url}/invoices/{$request.body.id}" +``` + +Então, se o usuário da sua API (o desenvolvedor externo) enviar uma solicitação para *sua API* para: + +``` +https://yourapi.com/invoices/?callback_url=https://www.external.org/events +``` + +com um corpo JSON de: + +```JSON +{ + "id": "2expen51ve", + "customer": "Mr. Richie Rich", + "total": "9999" +} +``` + +então *sua API* processará a fatura e, em algum momento posterior, enviará uma solicitação de callback para o `callback_url` (a *API externa*): + +``` +https://www.external.org/events/invoices/2expen51ve +``` + +com um corpo JSON contendo algo como: + +```JSON +{ + "description": "Payment celebration", + "paid": true +} +``` + +e esperaria uma resposta daquela *API externa* com um corpo JSON como: + +```JSON +{ + "ok": true +} +``` + +/// tip | Dica + +Perceba como a URL de callback usada contém a URL recebida como um parâmetro de consulta em `callback_url` (`https://www.external.org/events`) e também o `id` da fatura de dentro do corpo JSON (`2expen51ve`). + +/// + +### Adicionar o roteador de callback + +Nesse ponto você tem a(s) *operação de rota de callback* necessária(s) (a(s) que o *desenvolvedor externo* deveria implementar na *API externa*) no roteador de callback que você criou acima. + +Agora use o parâmetro `callbacks` no decorador da *operação de rota de sua API* para passar o atributo `.routes` (que é na verdade apenas uma `list` de rotas/*operações de rota*) do roteador de callback que você criou acima: + +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[35] *} + +/// tip | Dica + +Perceba que você não está passando o roteador em si (`invoices_callback_router`) para `callback=`, mas o atributo `.routes`, como em `invoices_callback_router.routes`. + +/// + +### Verifique a documentação + +Agora você pode iniciar seu aplicativo e ir para http://127.0.0.1:8000/docs. + +Você verá sua documentação incluindo uma seção "Callbacks" para sua *operação de rota* que mostra como a *API externa* deveria ser: + + diff --git a/docs/pt/docs/advanced/openapi-webhooks.md b/docs/pt/docs/advanced/openapi-webhooks.md new file mode 100644 index 000000000..f35922234 --- /dev/null +++ b/docs/pt/docs/advanced/openapi-webhooks.md @@ -0,0 +1,55 @@ +# Webhooks OpenAPI + +Existem situações onde você deseja informar os **usuários** da sua API que a sua aplicação pode chamar a aplicação *deles* (enviando uma requisição) com alguns dados, normalmente para **notificar** algum tipo de **evento**. + +Isso significa que no lugar do processo normal de seus usuários enviarem requisições para a sua API, é a **sua API** (ou sua aplicação) que poderia **enviar requisições para o sistema deles** (para a API deles, a aplicação deles). + +Isso normalmente é chamado de **webhook**. + +## Etapas dos Webhooks + +Normalmente, o processo é que **você define** em seu código qual é a mensagem que você irá mandar, o **corpo da sua requisição**. + +Você também define de alguma maneira em quais **momentos** a sua aplicação mandará essas requisições ou eventos. + +E os **seus usuários** definem de alguma forma (em algum painel por exemplo) a **URL** que a sua aplicação deve enviar essas requisições. + +Toda a **lógica** sobre como cadastrar as URLs para os webhooks e o código para enviar de fato as requisições cabe a você definir. Você escreve da maneira que você desejar no **seu próprio código**. + +## Documentando webhooks com o FastAPI e OpenAPI + +Com o **FastAPI**, utilizando o OpenAPI, você pode definir os nomes destes webhooks, os tipos das operações HTTP que a sua aplicação pode enviar (e.g. `POST`, `PUT`, etc.) e os **corpos** da requisição que a sua aplicação enviaria. + +Isto pode facilitar bastante para os seus usuários **implementarem as APIs deles** para receber as requisições dos seus **webhooks**, eles podem inclusive ser capazes de gerar parte do código da API deles. + +/// info | Informação + +Webhooks estão disponíveis a partir do OpenAPI 3.1.0, e possui suporte do FastAPI a partir da versão `0.99.0`. + +/// + +## Uma aplicação com webhooks + +Quando você cria uma aplicação com o **FastAPI**, existe um atributo chamado `webhooks`, que você utilizar para defini-los da mesma maneira que você definiria as suas **operações de rotas**, utilizando por exemplo `@app.webhooks.post()`. + +{* ../../docs_src/openapi_webhooks/tutorial001.py hl[9:13,36:53] *} + +Os webhooks que você define aparecerão no esquema do **OpenAPI** e na **página de documentação** gerada automaticamente. + +/// info | Informação + +O objeto `app.webhooks` é na verdade apenas um `APIRouter`, o mesmo tipo que você utilizaria ao estruturar a sua aplicação com diversos arquivos. + +/// + +Note que utilizando webhooks você não está de fato declarando uma **rota** (como `/items/`), o texto que informa é apenas um **identificador** do webhook (o nome do evento), por exemplo em `@app.webhooks.post("new-subscription")`, o nome do webhook é `new-subscription`. + +Isto porque espera-se que os **seus usuários** definam o verdadeiro **caminho da URL** onde eles desejam receber a requisição do webhook de algum outra maneira. (e.g. um painel). + +### Confira a documentação + +Agora você pode iniciar a sua aplicação e ir até http://127.0.0.1:8000/docs. + +Você verá que a sua documentação possui as *operações de rota* normais e agora também possui alguns **webhooks**: + + diff --git a/docs/pt/docs/advanced/path-operation-advanced-configuration.md b/docs/pt/docs/advanced/path-operation-advanced-configuration.md new file mode 100644 index 000000000..411d0f9a7 --- /dev/null +++ b/docs/pt/docs/advanced/path-operation-advanced-configuration.md @@ -0,0 +1,204 @@ +# Configuração Avançada da Operação de Rota + +## operationId do OpenAPI + +/// warning | Aviso + +Se você não é um "especialista" no OpenAPI, você provavelmente não precisa disso. + +/// + +Você pode definir o `operationId` do OpenAPI que será utilizado na sua *operação de rota* com o parâmetro `operation_id`. + +Você precisa ter certeza que ele é único para cada operação. + +{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *} + +### Utilizando o nome da *função de operação de rota* como o operationId + +Se você quiser utilizar o nome das funções da sua API como `operationId`s, você pode iterar sobre todos esses nomes e sobrescrever o `operationId` em cada *operação de rota* utilizando o `APIRoute.name` dela. + +Você deve fazer isso depois de adicionar todas as suas *operações de rota*. + +{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2,12:21,24] *} + +/// tip | Dica + +Se você chamar `app.openapi()` manualmente, os `operationId`s devem ser atualizados antes dessa chamada. + +/// + +/// warning | Aviso + +Se você fizer isso, você tem que ter certeza de que cada uma das suas *funções de operação de rota* tem um nome único. + +Mesmo que elas estejam em módulos (arquivos Python) diferentes. + +/// + +## Excluir do OpenAPI + +Para excluir uma *operação de rota* do esquema OpenAPI gerado (e por consequência, dos sistemas de documentação automáticos), utilize o parâmetro `include_in_schema` e defina ele como `False`: + +{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *} + +## Descrição avançada a partir de docstring + +Você pode limitar as linhas utilizadas a partir de uma docstring de uma *função de operação de rota* para o OpenAPI. + +Adicionar um `\f` (um caractere de escape para alimentação de formulário) faz com que o **FastAPI** restrinja a saída utilizada pelo OpenAPI até esse ponto. + +Ele não será mostrado na documentação, mas outras ferramentas (como o Sphinx) serão capazes de utilizar o resto do texto. + +{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19:29] *} + +## Respostas Adicionais + +Você provavelmente já viu como declarar o `response_model` e `status_code` para uma *operação de rota*. + +Isso define os metadados sobre a resposta principal da *operação de rota*. + +Você também pode declarar respostas adicionais, com seus modelos, códigos de status, etc. + +Existe um capítulo inteiro da nossa documentação sobre isso, você pode ler em [Retornos Adicionais no OpenAPI](additional-responses.md){.internal-link target=_blank}. + +## Extras do OpenAPI + +Quando você declara uma *operação de rota* na sua aplicação, o **FastAPI** irá gerar os metadados relevantes da *operação de rota* automaticamente para serem incluídos no esquema do OpenAPI. + +/// note | Nota + +Na especificação do OpenAPI, isso é chamado de um Objeto de Operação. + +/// + +Ele possui toda a informação sobre a *operação de rota* e é usado para gerar a documentação automaticamente. + +Ele inclui os atributos `tags`, `parameters`, `requestBody`, `responses`, etc. + +Esse esquema específico para uma *operação de rota* normalmente é gerado automaticamente pelo **FastAPI**, mas você também pode estender ele. + +/// tip | Dica + +Esse é um ponto de extensão de baixo nível. + +Caso você só precise declarar respostas adicionais, uma forma conveniente de fazer isso é com [Retornos Adicionais no OpenAPI](additional-responses.md){.internal-link target=_blank}. + +/// + +Você pode estender o esquema do OpenAPI para uma *operação de rota* utilizando o parâmetro `openapi_extra`. + +### Extensões do OpenAPI + +Esse parâmetro `openapi_extra` pode ser útil, por exemplo, para declarar [Extensões do OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions): + +{* ../../docs_src/path_operation_advanced_configuration/tutorial005.py hl[6] *} + +Se você abrir os documentos criados automaticamente para a API, sua extensão aparecerá no final da *operação de rota* específica. + + + +E se você olhar o esquema OpenAPI resultante (na rota `/openapi.json` da sua API), você verá que a sua extensão também faz parte da *operação de rota* específica: + +```JSON hl_lines="22" +{ + "openapi": "3.1.0", + "info": { + "title": "FastAPI", + "version": "0.1.0" + }, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + } + }, + "x-aperture-labs-portal": "blue" + } + } + } +} +``` + +### Esquema de *operação de rota* do OpenAPI personalizado + +O dicionário em `openapi_extra` vai ter todos os seus níveis mesclados dentro do esquema OpenAPI gerado automaticamente para a *operação de rota*. + +Então, você pode adicionar dados extras para o esquema gerado automaticamente. + +Por exemplo, você poderia optar por ler e validar a requisição com seu próprio código, sem utilizar funcionalidades automatizadas do FastAPI com o Pydantic, mas você ainda pode quere definir a requisição no esquema OpenAPI. + +Você pode fazer isso com `openapi_extra`: + +{* ../../docs_src/path_operation_advanced_configuration/tutorial006.py hl[19:36,39:40] *} + +Nesse exemplo, nós não declaramos nenhum modelo do Pydantic. Na verdade, o corpo da requisição não está nem mesmo analisado como JSON, ele é lido diretamente como `bytes` e a função `magic_data_reader()` seria a responsável por analisar ele de alguma forma. + +De toda forma, nós podemos declarar o esquema esperado para o corpo da requisição. + +### Tipo de conteúdo do OpenAPI personalizado + +Utilizando esse mesmo truque, você pode utilizar um modelo Pydantic para definir o esquema JSON que é então incluído na seção do esquema personalizado do OpenAPI na *operação de rota*. + +E você pode fazer isso até mesmo quando os dados da requisição não seguem o formato JSON. + +Por exemplo, nesta aplicação nós não usamos a funcionalidade integrada ao FastAPI de extrair o esquema JSON dos modelos Pydantic nem a validação automática do JSON. Na verdade, estamos declarando o tipo do conteúdo da requisição como YAML, em vez de JSON: + +//// tab | Pydantic v2 + +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[17:22,24] *} + +//// + +//// tab | Pydantic v1 + +{* ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py hl[17:22,24] *} + +//// + +/// info | Informação + +Na versão 1 do Pydantic, o método para obter o esquema JSON de um modelo é `Item.schema()`, na versão 2 do Pydantic, o método é `Item.model_json_schema()` + +/// + +Entretanto, mesmo que não utilizemos a funcionalidade integrada por padrão, ainda estamos usando um modelo Pydantic para gerar um esquema JSON manualmente para os dados que queremos receber no formato YAML. + +Então utilizamos a requisição diretamente, e extraímos o corpo como `bytes`. Isso significa que o FastAPI não vai sequer tentar analisar o corpo da requisição como JSON. + +E então no nosso código, nós analisamos o conteúdo YAML diretamente, e estamos utilizando o mesmo modelo Pydantic para validar o conteúdo YAML: + +//// tab | Pydantic v2 + +{* ../../docs_src/path_operation_advanced_configuration/tutorial007.py hl[26:33] *} + +//// + +//// tab | Pydantic v1 + +{* ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1.py hl[26:33] *} + +//// + +/// info | Informação + +Na versão 1 do Pydantic, o método para analisar e validar um objeto era `Item.parse_obj()`, na versão 2 do Pydantic, o método é chamado de `Item.model_validate()`. + +/// + +///tip | Dica + +Aqui reutilizamos o mesmo modelo do Pydantic. + +Mas da mesma forma, nós poderíamos ter validado de alguma outra forma. + +/// diff --git a/docs/pt/docs/advanced/response-change-status-code.md b/docs/pt/docs/advanced/response-change-status-code.md new file mode 100644 index 000000000..358c12d54 --- /dev/null +++ b/docs/pt/docs/advanced/response-change-status-code.md @@ -0,0 +1,31 @@ +# Retorno - Altere o Código de Status + +Você provavelmente leu anteriormente que você pode definir um [Código de Status do Retorno](../tutorial/response-status-code.md){.internal-link target=_blank} padrão. + +Porém em alguns casos você precisa retornar um código de status diferente do padrão. + +## Caso de uso + +Por exemplo, imagine que você deseja retornar um código de status HTTP de "OK" `200` por padrão. + +Mas se o dado não existir, você quer criá-lo e retornar um código de status HTTP de "CREATED" `201`. + +Mas você ainda quer ser capaz de filtrar e converter o dado que você retornará com um `response_model`. + +Para estes casos, você pode utilizar um parâmetro `Response`. + +## Use um parâmetro `Response` + +Você pode declarar um parâmetro do tipo `Response` em sua *função de operação de rota* (assim como você pode fazer para cookies e headers). + +E então você pode definir o `status_code` neste objeto de retorno temporal. + +{* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *} + +E então você pode retornar qualquer objeto que você precise, como você faria normalmente (um `dict`, um modelo de banco de dados, etc.). + +E se você declarar um `response_model`, ele ainda será utilizado para filtrar e converter o objeto que você retornou. + +O **FastAPI** utilizará este retorno *temporal* para extrair o código de status (e também cookies e headers), e irá colocá-los no retorno final que contém o valor que você retornou, filtrado por qualquer `response_model`. + +Você também pode declarar o parâmetro `Response` nas dependências, e definir o código de status nelas. Mas lembre-se que o último que for definido é o que prevalecerá. diff --git a/docs/pt/docs/advanced/response-cookies.md b/docs/pt/docs/advanced/response-cookies.md new file mode 100644 index 000000000..eed69f222 --- /dev/null +++ b/docs/pt/docs/advanced/response-cookies.md @@ -0,0 +1,51 @@ +# Cookies de Resposta + +## Usando um parâmetro `Response` + +Você pode declarar um parâmetro do tipo `Response` na sua *função de operação de rota*. + +E então você pode definir cookies nesse objeto de resposta *temporário*. + +{* ../../docs_src/response_cookies/tutorial002.py hl[1,8:9] *} + +Em seguida, você pode retornar qualquer objeto que precise, como normalmente faria (um `dict`, um modelo de banco de dados, etc). + +E se você declarou um `response_model`, ele ainda será usado para filtrar e converter o objeto que você retornou. + +**FastAPI** usará essa resposta *temporária* para extrair os cookies (também os cabeçalhos e código de status) e os colocará na resposta final que contém o valor que você retornou, filtrado por qualquer `response_model`. + +Você também pode declarar o parâmetro `Response` em dependências e definir cookies (e cabeçalhos) nelas. + +## Retornando uma `Response` diretamente + +Você também pode criar cookies ao retornar uma `Response` diretamente no seu código. + +Para fazer isso, você pode criar uma resposta como descrito em [Retornando uma Resposta Diretamente](response-directly.md){.internal-link target=_blank}. + +Então, defina os cookies nela e a retorne: + +{* ../../docs_src/response_cookies/tutorial001.py hl[10:12] *} + +/// tip | Dica + +Lembre-se de que se você retornar uma resposta diretamente em vez de usar o parâmetro `Response`, FastAPI a retornará diretamente. + +Portanto, você terá que garantir que seus dados sejam do tipo correto. E.g. será compatível com JSON se você estiver retornando um `JSONResponse`. + +E também que você não esteja enviando nenhum dado que deveria ter sido filtrado por um `response_model`. + +/// + +### Mais informações + +/// note | Detalhes Técnicos + +Você também poderia usar `from starlette.responses import Response` ou `from starlette.responses import JSONResponse`. + +**FastAPI** fornece as mesmas `starlette.responses` em `fastapi.responses` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria das respostas disponíveis vem diretamente do Starlette. + +E como o `Response` pode ser usado frequentemente para definir cabeçalhos e cookies, o **FastAPI** também o fornece em `fastapi.Response`. + +/// + +Para ver todos os parâmetros e opções disponíveis, verifique a documentação no Starlette. diff --git a/docs/pt/docs/advanced/response-directly.md b/docs/pt/docs/advanced/response-directly.md new file mode 100644 index 000000000..ea717be00 --- /dev/null +++ b/docs/pt/docs/advanced/response-directly.md @@ -0,0 +1,66 @@ +# Retornando uma Resposta Diretamente + +Quando você cria uma *operação de rota* no **FastAPI** você pode retornar qualquer dado nela: um dicionário (`dict`), uma lista (`list`), um modelo do Pydantic ou do seu banco de dados, etc. + +Por padrão, o **FastAPI** irá converter automaticamente o valor do retorno para JSON utilizando o `jsonable_encoder` explicado em [JSON Compatible Encoder](../tutorial/encoder.md){.internal-link target=_blank}. + +Então, por baixo dos panos, ele incluiria esses dados compatíveis com JSON (e.g. um `dict`) dentro de uma `JSONResponse` que é utilizada para enviar uma resposta para o cliente. + +Mas você pode retornar a `JSONResponse` diretamente nas suas *operações de rota*. + +Pode ser útil para retornar cabeçalhos e cookies personalizados, por exemplo. + +## Retornando uma `Response` + +Na verdade, você pode retornar qualquer `Response` ou subclasse dela. + +/// tip | Dica + +A própria `JSONResponse` é uma subclasse de `Response`. + +/// + +E quando você retorna uma `Response`, o **FastAPI** vai repassá-la diretamente. + +Ele não vai fazer conversões de dados com modelos do Pydantic, não irá converter a tipagem de nenhum conteúdo, etc. + +Isso te dá bastante flexibilidade. Você pode retornar qualquer tipo de dado, sobrescrever qualquer declaração e validação nos dados, etc. + +## Utilizando o `jsonable_encoder` em uma `Response` + +Como o **FastAPI** não realiza nenhuma mudança na `Response` que você retorna, você precisa garantir que o conteúdo dela está pronto para uso. + +Por exemplo, você não pode colocar um modelo do Pydantic em uma `JSONResponse` sem antes convertê-lo em um `dict` com todos os tipos de dados (como `datetime`, `UUID`, etc) convertidos para tipos compatíveis com JSON. + +Para esses casos, você pode usar o `jsonable_encoder` para converter seus dados antes de repassá-los para a resposta: + +{* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *} + +/// note | Detalhes Técnicos + +Você também pode utilizar `from starlette.responses import JSONResponse`. + +**FastAPI** utiliza a mesma `starlette.responses` como `fastapi.responses` apenas como uma conveniência para você, desenvolvedor. Mas maior parte das respostas disponíveis vem diretamente do Starlette. + +/// + +## Retornando uma `Response` + +O exemplo acima mostra todas as partes que você precisa, mas ainda não é muito útil, já que você poderia ter retornado o `item` diretamente, e o **FastAPI** colocaria em uma `JSONResponse` para você, convertendo em um `dict`, etc. Tudo isso por padrão. + +Agora, vamos ver como você pode usar isso para retornar uma resposta personalizada. + +Vamos dizer quer retornar uma resposta XML. + +Você pode colocar o seu conteúdo XML em uma string, colocar em uma `Response`, e retorná-lo: + +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} + +## Notas + +Quando você retorna uma `Response` diretamente os dados não são validados, convertidos (serializados) ou documentados automaticamente. + +Mas você ainda pode documentar como descrito em [Retornos Adicionais no OpenAPI +](additional-responses.md){.internal-link target=_blank}. + +Você pode ver nas próximas seções como usar/declarar essas `Responses` customizadas enquanto mantém a conversão e documentação automática dos dados. diff --git a/docs/pt/docs/advanced/response-headers.md b/docs/pt/docs/advanced/response-headers.md new file mode 100644 index 000000000..a8034a7a4 --- /dev/null +++ b/docs/pt/docs/advanced/response-headers.md @@ -0,0 +1,41 @@ +# Cabeçalhos de resposta + +## Usando um parâmetro `Response` + +Você pode declarar um parâmetro do tipo `Response` na sua *função de operação de rota* (assim como você pode fazer para cookies). + +Então você pode definir os cabeçalhos nesse objeto de resposta *temporário*. + +{* ../../docs_src/response_headers/tutorial002.py hl[1,7:8] *} + +Em seguida você pode retornar qualquer objeto que precisar, da maneira que faria normalmente (um `dict`, um modelo de banco de dados, etc.). + +Se você declarou um `response_model`, ele ainda será utilizado para filtrar e converter o objeto que você retornou. + +**FastAPI** usará essa resposta *temporária* para extrair os cabeçalhos (cookies e código de status também) e os colocará na resposta final que contém o valor que você retornou, filtrado por qualquer `response_model`. + +Você também pode declarar o parâmetro `Response` em dependências e definir cabeçalhos (e cookies) nelas. + +## Retornar uma `Response` diretamente + +Você também pode adicionar cabeçalhos quando retornar uma `Response` diretamente. + +Crie uma resposta conforme descrito em [Retornar uma resposta diretamente](response-directly.md){.internal-link target=_blank} e passe os cabeçalhos como um parâmetro adicional: + +{* ../../docs_src/response_headers/tutorial001.py hl[10:12] *} + +/// note | Detalhes técnicos + +Você também pode usar `from starlette.responses import Response` ou `from starlette.responses import JSONResponse`. + +**FastAPI** fornece as mesmas `starlette.responses` como `fastapi.responses` apenas como uma conveniência para você, desenvolvedor. Mas a maioria das respostas disponíveis vem diretamente do Starlette. + +E como a `Response` pode ser usada frequentemente para definir cabeçalhos e cookies, **FastAPI** também a fornece em `fastapi.Response`. + +/// + +## Cabeçalhos personalizados + +Tenha em mente que cabeçalhos personalizados proprietários podem ser adicionados usando o prefixo 'X-'. + +Porém, se voce tiver cabeçalhos personalizados que deseja que um cliente no navegador possa ver, você precisa adicioná-los às suas configurações de CORS (saiba mais em [CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md){.internal-link target=_blank}), usando o parâmetro `expose_headers` descrito na documentação de CORS do Starlette. diff --git a/docs/pt/docs/advanced/security/http-basic-auth.md b/docs/pt/docs/advanced/security/http-basic-auth.md new file mode 100644 index 000000000..331513927 --- /dev/null +++ b/docs/pt/docs/advanced/security/http-basic-auth.md @@ -0,0 +1,108 @@ +# HTTP Basic Auth + +Para os casos mais simples, você pode utilizar o HTTP Basic Auth. + +No HTTP Basic Auth, a aplicação espera um cabeçalho que contém um usuário e uma senha. + +Caso ela não receba, ela retorna um erro HTTP 401 "Unauthorized" (*Não Autorizado*). + +E retorna um cabeçalho `WWW-Authenticate` com o valor `Basic`, e um parâmetro opcional `realm`. + +Isso sinaliza ao navegador para mostrar o prompt integrado para um usuário e senha. + +Então, quando você digitar o usuário e senha, o navegador os envia automaticamente no cabeçalho. + +## HTTP Basic Auth Simples + +* Importe `HTTPBasic` e `HTTPBasicCredentials`. +* Crie um "esquema `security`" utilizando `HTTPBasic`. +* Utilize o `security` com uma dependência em sua *operação de rota*. +* Isso retorna um objeto do tipo `HTTPBasicCredentials`: + * Isto contém o `username` e o `password` enviado. + +{* ../../docs_src/security/tutorial006_an_py39.py hl[4,8,12] *} + +Quando você tentar abrir a URL pela primeira vez (ou clicar no botão "Executar" nos documentos) o navegador vai pedir pelo seu usuário e senha: + + + +## Verifique o usuário + +Aqui está um exemplo mais completo. + +Utilize uma dependência para verificar se o usuário e a senha estão corretos. + +Para isso, utilize o módulo padrão do Python `secrets` para verificar o usuário e senha. + +O `secrets.compare_digest()` necessita receber `bytes` ou `str` que possuem apenas caracteres ASCII (os em inglês). Isso significa que não funcionaria com caracteres como o `á`, como em `Sebastián`. + +Para lidar com isso, primeiramente nós convertemos o `username` e o `password` para `bytes`, codificando-os com UTF-8. + +Então nós podemos utilizar o `secrets.compare_digest()` para garantir que o `credentials.username` é `"stanleyjobson"`, e que o `credentials.password` é `"swordfish"`. + +{* ../../docs_src/security/tutorial007_an_py39.py hl[1,12:24] *} + +Isso seria parecido com: + +```Python +if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"): + # Return some error + ... +``` + +Porém, ao utilizar o `secrets.compare_digest()`, isso estará seguro contra um tipo de ataque chamado "timing attacks" (ataques de temporização). + +### Ataques de Temporização + +Mas o que é um "timing attack" (ataque de temporização)? + +Vamos imaginar que alguns invasores estão tentando adivinhar o usuário e a senha. + +E eles enviam uma requisição com um usuário `johndoe` e uma senha `love123`. + +Então o código Python em sua aplicação seria equivalente a algo como: + +```Python +if "johndoe" == "stanleyjobson" and "love123" == "swordfish": + ... +``` + +Mas no exato momento que o Python compara o primeiro `j` em `johndoe` contra o primeiro `s` em `stanleyjobson`, ele retornará `False`, porque ele já sabe que aquelas duas strings não são a mesma, pensando que "não existe a necessidade de desperdiçar mais poder computacional comparando o resto das letras". E a sua aplicação dirá "Usuário ou senha incorretos". + +Então os invasores vão tentar com o usuário `stanleyjobsox` e a senha `love123`. + +E a sua aplicação faz algo como: + +```Python +if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": + ... +``` + +O Python terá que comparar todo o `stanleyjobso` tanto em `stanleyjobsox` como em `stanleyjobson` antes de perceber que as strings não são a mesma. Então isso levará alguns microssegundos a mais para retornar "Usuário ou senha incorretos". + +#### O tempo para responder ajuda os invasores + +Neste ponto, ao perceber que o servidor demorou alguns microssegundos a mais para enviar o retorno "Usuário ou senha incorretos", os invasores irão saber que eles acertaram _alguma coisa_, algumas das letras iniciais estavam certas. + +E eles podem tentar de novo sabendo que provavelmente é algo mais parecido com `stanleyjobsox` do que com `johndoe`. + +#### Um ataque "profissional" + +Claro, os invasores não tentariam tudo isso de forma manual, eles escreveriam um programa para fazer isso, possivelmente com milhares ou milhões de testes por segundo. E obteriam apenas uma letra a mais por vez. + +Mas fazendo isso, em alguns minutos ou horas os invasores teriam adivinhado o usuário e senha corretos, com a "ajuda" da nossa aplicação, apenas usando o tempo levado para responder. + +#### Corrija com o `secrets.compare_digest()` + +Mas em nosso código já estamos utilizando o `secrets.compare_digest()`. + +Resumindo, levará o mesmo tempo para comparar `stanleyjobsox` com `stanleyjobson` do que comparar `johndoe` com `stanleyjobson`. E o mesmo para a senha. + +Deste modo, ao utilizar `secrets.compare_digest()` no código de sua aplicação, ela estará a salvo contra toda essa gama de ataques de segurança. + + +### Retorne o erro + +Após detectar que as credenciais estão incorretas, retorne um `HTTPException` com o status 401 (o mesmo retornado quando nenhuma credencial foi informada) e adicione o cabeçalho `WWW-Authenticate` para fazer com que o navegador mostre o prompt de login novamente: + +{* ../../docs_src/security/tutorial007_an_py39.py hl[26:30] *} diff --git a/docs/pt/docs/advanced/security/index.md b/docs/pt/docs/advanced/security/index.md new file mode 100644 index 000000000..6c7becb67 --- /dev/null +++ b/docs/pt/docs/advanced/security/index.md @@ -0,0 +1,19 @@ +# Segurança Avançada + +## Funcionalidades Adicionais + +Existem algumas funcionalidades adicionais para lidar com segurança além das cobertas em [Tutorial - Guia de Usuário: Segurança](../../tutorial/security/index.md){.internal-link target=_blank}. + +/// tip | Dica + +As próximas seções **não são necessariamente "avançadas"**. + +E é possível que para o seu caso de uso, a solução está em uma delas. + +/// + +## Leia o Tutorial primeiro + +As próximas seções pressupõem que você já leu o principal [Tutorial - Guia de Usuário: Segurança](../../tutorial/security/index.md){.internal-link target=_blank}. + +Todas elas são baseadas nos mesmos conceitos, mas permitem algumas funcionalidades extras. diff --git a/docs/pt/docs/advanced/security/oauth2-scopes.md b/docs/pt/docs/advanced/security/oauth2-scopes.md new file mode 100644 index 000000000..1d53f42d8 --- /dev/null +++ b/docs/pt/docs/advanced/security/oauth2-scopes.md @@ -0,0 +1,274 @@ +# Escopos OAuth2 + +Você pode utilizar escopos do OAuth2 diretamente com o **FastAPI**, eles são integrados para funcionar perfeitamente. + +Isso permitiria que você tivesse um sistema de permissionamento mais refinado, seguindo o padrão do OAuth2 integrado na sua aplicação OpenAPI (e as documentações da API). + +OAuth2 com escopos é o mecanismo utilizado por muitos provedores de autenticação, como o Facebook, Google, GitHub, Microsoft, Twitter, etc. Eles utilizam isso para prover permissões específicas para os usuários e aplicações. + +Toda vez que você "se autentica com" Facebook, Google, GitHub, Microsoft, Twitter, aquela aplicação está utilizando o OAuth2 com escopos. + +Nesta seção, você verá como gerenciar a autenticação e autorização com os mesmos escopos do OAuth2 em sua aplicação **FastAPI**. + +/// warning | Aviso + +Isso é uma seção mais ou menos avançada. Se você está apenas começando, você pode pular. + +Você não necessariamente precisa de escopos do OAuth2, e você pode lidar com autenticação e autorização da maneira que você achar melhor. + +Mas o OAuth2 com escopos pode ser integrado de maneira fácil em sua API (com OpenAPI) e a sua documentação de API. + +No entando, você ainda aplica estes escopos, ou qualquer outro requisito de segurança/autorização, conforme necessário, em seu código. + +Em muitos casos, OAuth2 com escopos pode ser um exagero. + +Mas se você sabe que precisa, ou está curioso, continue lendo. + +/// + +## Escopos OAuth2 e OpenAPI + +A especificação OAuth2 define "escopos" como uma lista de strings separadas por espaços. + +O conteúdo de cada uma dessas strings pode ter qualquer formato, mas não devem possuir espaços. + +Estes escopos representam "permissões". + +No OpenAPI (e.g. os documentos da API), você pode definir "esquemas de segurança". + +Quando um desses esquemas de segurança utiliza OAuth2, você pode também declarar e utilizar escopos. + +Cada "escopo" é apenas uma string (sem espaços). + +Eles são normalmente utilizados para declarar permissões de segurança específicas, como por exemplo: + +* `users:read` or `users:write` são exemplos comuns. +* `instagram_basic` é utilizado pelo Facebook / Instagram. +* `https://www.googleapis.com/auth/drive` é utilizado pelo Google. + +/// info | Informação + +No OAuth2, um "escopo" é apenas uma string que declara uma permissão específica necessária. + +Não importa se ela contém outros caracteres como `:` ou se ela é uma URL. + +Estes detalhes são específicos da implementação. + +Para o OAuth2, eles são apenas strings. + +/// + +## Visão global + +Primeiro, vamos olhar rapidamente as partes que mudam dos exemplos do **Tutorial - Guia de Usuário** para [OAuth2 com Senha (e hash), Bearer com tokens JWT](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. Agora utilizando escopos OAuth2: + +{* ../../docs_src/security/tutorial005_an_py310.py hl[5,9,13,47,65,106,108:116,122:125,129:135,140,156] *} + +Agora vamos revisar essas mudanças passo a passo. + +## Esquema de segurança OAuth2 + +A primeira mudança é que agora nós estamos declarando o esquema de segurança OAuth2 com dois escopos disponíveis, `me` e `items`. + +O parâmetro `scopes` recebe um `dict` contendo cada escopo como chave e a descrição como valor: + +{* ../../docs_src/security/tutorial005_an_py310.py hl[63:66] *} + +Pelo motivo de estarmos declarando estes escopos, eles aparecerão nos documentos da API quando você se autenticar/autorizar. + +E você poderá selecionar quais escopos você deseja dar acesso: `me` e `items`. + +Este é o mesmo mecanismo utilizado quando você adiciona permissões enquanto se autentica com o Facebook, Google, GitHub, etc: + + + +## Token JWT com escopos + +Agora, modifique o *caminho de rota* para retornar os escopos solicitados. + +Nós ainda estamos utilizando o mesmo `OAuth2PasswordRequestForm`. Ele inclui a propriedade `scopes` com uma `list` de `str`, com cada escopo que ele recebeu na requisição. + +E nós retornamos os escopos como parte do token JWT. + +/// danger | Cuidado + +Para manter as coisas simples, aqui nós estamos apenas adicionando os escopos recebidos diretamente ao token. + +Porém em sua aplicação, por segurança, você deve garantir que você apenas adiciona os escopos que o usuário possui permissão de fato, ou aqueles que você predefiniu. + +/// + +{* ../../docs_src/security/tutorial005_an_py310.py hl[156] *} + +## Declare escopos em *operações de rota* e dependências + +Agora nós declaramos que a *operação de rota* para `/users/me/items/` exige o escopo `items`. + +Para isso, nós importamos e utilizamos `Security` de `fastapi`. + +Você pode utilizar `Security` para declarar dependências (assim como `Depends`), porém o `Security` também recebe o parâmetros `scopes` com uma lista de escopos (strings). + +Neste caso, nós passamos a função `get_current_active_user` como dependência para `Security` (da mesma forma que nós faríamos com `Depends`). + +Mas nós também passamos uma `list` de escopos, neste caso com apenas um escopo: `items` (poderia ter mais). + +E a função de dependência `get_current_active_user` também pode declarar subdependências, não apenas com `Depends`, mas também com `Security`. Ao declarar sua própria função de subdependência (`get_current_user`), e mais requisitos de escopo. + +Neste caso, ele requer o escopo `me` (poderia requerer mais de um escopo). + +/// note | Nota + +Você não necessariamente precisa adicionar diferentes escopos em diferentes lugares. + +Nós estamos fazendo isso aqui para demonstrar como o **FastAPI** lida com escopos declarados em diferentes níveis. + +/// + +{* ../../docs_src/security/tutorial005_an_py310.py hl[5,140,171] *} + +/// info | Informações Técnicas + +`Security` é na verdade uma subclasse de `Depends`, e ele possui apenas um parâmetro extra que veremos depois. + +Porém ao utilizar `Security` no lugar de `Depends`, o **FastAPI** saberá que ele pode declarar escopos de segurança, utilizá-los internamente, e documentar a API com o OpenAPI. + +Mas quando você importa `Query`, `Path`, `Depends`, `Security` entre outros de `fastapi`, eles são na verdade funções que retornam classes especiais. + +/// + +## Utilize `SecurityScopes` + +Agora atualize a dependência `get_current_user`. + +Este é o usado pelas dependências acima. + +Aqui é onde estamos utilizando o mesmo esquema OAuth2 que nós declaramos antes, declarando-o como uma dependência: `oauth2_scheme`. + +Porque esta função de dependência não possui nenhum requerimento de escopo, nós podemos utilizar `Depends` com o `oauth2_scheme`. Nós não precisamos utilizar `Security` quando nós não precisamos especificar escopos de segurança. + +Nós também declaramos um parâmetro especial do tipo `SecurityScopes`, importado de `fastapi.security`. + +A classe `SecurityScopes` é semelhante à classe `Request` (`Request` foi utilizada para obter o objeto da requisição diretamente). + +{* ../../docs_src/security/tutorial005_an_py310.py hl[9,106] *} + +## Utilize os `scopes` + +O parâmetro `security_scopes` será do tipo `SecurityScopes`. + +Ele terá a propriedade `scopes` com uma lista contendo todos os escopos requeridos por ele e todas as dependências que utilizam ele como uma subdependência. Isso significa, todos os "dependentes"... pode soar meio confuso, e isso será explicado novamente mais adiante. + +O objeto `security_scopes` (da classe `SecurityScopes`) também oferece um atributo `scope_str` com uma única string, contendo os escopos separados por espaços (nós vamos utilizar isso). + +Nós criamos uma `HTTPException` que nós podemos reutilizar (`raise`) mais tarde em diversos lugares. + +Nesta exceção, nós incluímos os escopos necessários (se houver algum) como uma string separada por espaços (utilizando `scope_str`). Nós colocamos esta string contendo os escopos no cabeçalho `WWW-Authenticate` (isso é parte da especificação). + +{* ../../docs_src/security/tutorial005_an_py310.py hl[106,108:116] *} + +## Verifique o `username` e o formato dos dados + +Nós verificamos que nós obtemos um `username`, e extraímos os escopos. + +E depois nós validamos esse dado com o modelo Pydantic (capturando a exceção `ValidationError`), e se nós obtemos um erro ao ler o token JWT ou validando os dados com o Pydantic, nós levantamos a exceção `HTTPException` que criamos anteriormente. + +Para isso, nós atualizamos o modelo Pydantic `TokenData` com a nova propriedade `scopes`. + +Ao validar os dados com o Pydantic nós podemos garantir que temos, por exemplo, exatamente uma `list` de `str` com os escopos e uma `str` com o `username`. + +No lugar de, por exemplo, um `dict`, ou alguma outra coisa, que poderia quebrar a aplicação em algum lugar mais tarde, tornando isso um risco de segurança. + +Nós também verificamos que nós temos um usuário com o "*username*", e caso contrário, nós levantamos a mesma exceção que criamos anteriormente. + +{* ../../docs_src/security/tutorial005_an_py310.py hl[47,117:128] *} + +## Verifique os `scopes` + +Nós verificamos agora que todos os escopos necessários, por essa dependência e todos os dependentes (incluindo as *operações de rota*) estão incluídas nos escopos fornecidos pelo token recebido, caso contrário, levantamos uma `HTTPException`. + +Para isso, nós utilizamos `security_scopes.scopes`, que contém uma `list` com todos esses escopos como uma `str`. + +{* ../../docs_src/security/tutorial005_an_py310.py hl[129:135] *} + +## Árvore de dependência e escopos + +Vamos rever novamente essa árvore de dependência e os escopos. + +Como a dependência `get_current_active_user` possui uma subdependência em `get_current_user`, o escopo `"me"` declarado em `get_current_active_user` será incluído na lista de escopos necessários em `security_scopes.scopes` passado para `get_current_user`. + +A própria *operação de rota* também declara o escopo, `"items"`, então ele também estará na lista de `security_scopes.scopes` passado para o `get_current_user`. + +Aqui está como a hierarquia de dependências e escopos parecem: + +* A *operação de rota* `read_own_items` possui: + * Escopos necessários `["items"]` com a dependência: + * `get_current_active_user`: + * A função de dependência `get_current_active_user` possui: + * Escopos necessários `["me"]` com a dependência: + * `get_current_user`: + * A função de dependência `get_current_user` possui: + * Nenhum escopo necessário. + * Uma dependência utilizando `oauth2_scheme`. + * Um parâmetro `security_scopes` do tipo `SecurityScopes`: + * Este parâmetro `security_scopes` possui uma propriedade `scopes` com uma `list` contendo todos estes escopos declarados acima, então: + * `security_scopes.scopes` terá `["me", "items"]` para a *operação de rota* `read_own_items`. + * `security_scopes.scopes` terá `["me"]` para a *operação de rota* `read_users_me`, porque ela declarou na dependência `get_current_active_user`. + * `security_scopes.scopes` terá `[]` (nada) para a *operação de rota* `read_system_status`, porque ele não declarou nenhum `Security` com `scopes`, e sua dependência, `get_current_user`, não declara nenhum `scopes` também. + +/// tip | Dica + +A coisa importante e "mágica" aqui é que `get_current_user` terá diferentes listas de `scopes` para validar para cada *operação de rota*. + +Tudo depende dos `scopes` declarados em cada *operação de rota* e cada dependência da árvore de dependências para aquela *operação de rota* específica. + +/// + +## Mais detalhes sobre `SecurityScopes` + +Você pode utilizar `SecurityScopes` em qualquer lugar, e em diversos lugares. Ele não precisa estar na dependência "raiz". + +Ele sempre terá os escopos de segurança declarados nas dependências atuais de `Security` e todos os dependentes para **aquela** *operação de rota* **específica** e **aquela** árvore de dependência **específica**. + +Porque o `SecurityScopes` terá todos os escopos declarados por dependentes, você pode utilizá-lo para verificar se o token possui os escopos necessários em uma função de dependência central, e depois declarar diferentes requisitos de escopo em diferentes *operações de rota*. + +Todos eles serão validados independentemente para cada *operação de rota*. + +## Verifique + +Se você abrir os documentos da API, você pode antenticar e especificar quais escopos você quer autorizar. + + + +Se você não selecionar nenhum escopo, você terá "autenticado", mas quando você tentar acessar `/users/me/` ou `/users/me/items/`, você vai obter um erro dizendo que você não possui as permissões necessárias. Você ainda poderá acessar `/status/`. + +E se você selecionar o escopo `me`, mas não o escopo `items`, você poderá acessar `/users/me/`, mas não `/users/me/items/`. + +Isso é o que aconteceria se uma aplicação terceira que tentou acessar uma dessas *operações de rota* com um token fornecido por um usuário, dependendo de quantas permissões o usuário forneceu para a aplicação. + +## Sobre integrações de terceiros + +Neste exemplos nós estamos utilizando o fluxo de senha do OAuth2. + +Isso é apropriado quando nós estamos autenticando em nossa própria aplicação, provavelmente com o nosso próprio "*frontend*". + +Porque nós podemos confiar nele para receber o `username` e o `password`, pois nós controlamos isso. + +Mas se nós estamos construindo uma aplicação OAuth2 que outros poderiam conectar (i.e., se você está construindo um provedor de autenticação equivalente ao Facebook, Google, GitHub, etc.) você deveria utilizar um dos outros fluxos. + +O mais comum é o fluxo implícito. + +O mais seguro é o fluxo de código, mas ele é mais complexo para implementar, pois ele necessita mais passos. Como ele é mais complexo, muitos provedores terminam sugerindo o fluxo implícito. + +/// note | Nota + +É comum que cada provedor de autenticação nomeie os seus fluxos de forma diferente, para torná-lo parte de sua marca. + +Mas no final, eles estão implementando o mesmo padrão OAuth2. + +/// + +O **FastAPI** inclui utilitários para todos esses fluxos de autenticação OAuth2 em `fastapi.security.oauth2`. + +## `Security` em docoradores de `dependências` + +Da mesma forma que você pode definir uma `list` de `Depends` no parâmetro de `dependencias` do decorador (como explicado em [Dependências em decoradores de operações de rota](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}), você também pode utilizar `Security` com escopos lá. diff --git a/docs/pt/docs/advanced/settings.md b/docs/pt/docs/advanced/settings.md new file mode 100644 index 000000000..cdc6400ad --- /dev/null +++ b/docs/pt/docs/advanced/settings.md @@ -0,0 +1,464 @@ +# Configurações e Variáveis de Ambiente + +Em muitos casos a sua aplicação pode precisar de configurações externas, como chaves secretas, credenciais de banco de dados, credenciais para serviços de email, etc. + +A maioria dessas configurações é variável (podem mudar), como URLs de bancos de dados. E muitas delas podem conter dados sensíveis, como tokens secretos. + +Por isso é comum prover essas configurações como variáveis de ambiente que são utilizidas pela aplicação. + +## Variáveis de Ambiente + +/// tip | Dica + +Se você já sabe o que são variáveis de ambiente e como utilizá-las, sinta-se livre para avançar para o próximo tópico. + +/// + +Uma variável de ambiente (abreviada em inglês para "env var") é uma variável definida fora do código Python, no sistema operacional, e pode ser lida pelo seu código Python (ou por outros programas). + +Você pode criar e utilizar variáveis de ambiente no terminal, sem precisar utilizar Python: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// Você pode criar uma env var MY_NAME usando +$ export MY_NAME="Wade Wilson" + +// E utilizá-la em outros programas, como +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// Criando env var MY_NAME +$ $Env:MY_NAME = "Wade Wilson" + +// Usando em outros programas, como +$ echo "Hello $Env:MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +### Lendo variáveis de ambiente com Python + +Você também pode criar variáveis de ambiente fora do Python, no terminal (ou com qualquer outro método), e realizar a leitura delas no Python. + +Por exemplo, você pode definir um arquivo `main.py` com o seguinte código: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// tip | Dica + +O segundo parâmetro em `os.getenv()` é o valor padrão para o retorno. + +Se nenhum valor for informado, `None` é utilizado por padrão, aqui definimos `"World"` como o valor padrão a ser utilizado. + +/// + +E depois você pode executar esse arquivo: + +
+ +```console +// Aqui ainda não definimos a env var +$ python main.py + +// Por isso obtemos o valor padrão + +Hello World from Python + +// Mas se definirmos uma variável de ambiente primeiro +$ export MY_NAME="Wade Wilson" + +// E executarmos o programa novamente +$ python main.py + +// Agora ele pode ler a variável de ambiente + +Hello Wade Wilson from Python +``` + +
+ +Como variáveis de ambiente podem ser definidas fora do código da aplicação, mas acessadas pela aplicação, e não precisam ser armazenadas (versionadas com `git`) junto dos outros arquivos, é comum utilizá-las para guardar configurações. + +Você também pode criar uma variável de ambiente específica para uma invocação de um programa, que é acessível somente para esse programa, e somente enquanto ele estiver executando. + +Para fazer isso, crie a variável imediatamente antes de iniciar o programa, na mesma linha: + +
+ +```console +// Criando uma env var MY_NAME na mesma linha da execução do programa +$ MY_NAME="Wade Wilson" python main.py + +// Agora a aplicação consegue ler a variável de ambiente + +Hello Wade Wilson from Python + +// E a variável deixa de existir após isso +$ python main.py + +Hello World from Python +``` + +
+ +/// tip | Dica + +Você pode ler mais sobre isso em: The Twelve-Factor App: Configurações. + +/// + +### Tipagem e Validação + +Essas variáveis de ambiente suportam apenas strings, por serem externas ao Python e por que precisam ser compatíveis com outros programas e o resto do sistema (e até mesmo com outros sistemas operacionais, como Linux, Windows e macOS). + +Isso significa que qualquer valor obtido de uma variável de ambiente em Python terá o tipo `str`, e qualquer conversão para um tipo diferente ou validação deve ser realizada no código. + +## Pydantic `Settings` + +Por sorte, o Pydantic possui uma funcionalidade para lidar com essas configurações vindas de variáveis de ambiente utilizando Pydantic: Settings management. + +### Instalando `pydantic-settings` + +Primeiro, instale o pacote `pydantic-settings`: + +
+ +```console +$ pip install pydantic-settings +---> 100% +``` + +
+ +Ele também está incluído no fastapi quando você instala com a opção `all`: + +
+ +```console +$ pip install "fastapi[all]" +---> 100% +``` + +
+ +/// info + +Na v1 do Pydantic ele estava incluído no pacote principal. Agora ele está distribuido como um pacote independente para que você possa optar por instalar ou não caso você não precise dessa funcionalidade. + +/// + +### Criando o objeto `Settings` + +Importe a classe `BaseSettings` do Pydantic e crie uma nova subclasse, de forma parecida com um modelo do Pydantic. + +Os atributos da classe são declarados com anotações de tipo, e possíveis valores padrão, da mesma maneira que os modelos do Pydantic. + +Você pode utilizar todas as ferramentas e funcionalidades de validação que são utilizadas nos modelos do Pydantic, como tipos de dados diferentes e validações adicionei com `Field()`. + +//// tab | Pydantic v2 + +{* ../../docs_src/settings/tutorial001.py hl[2,5:8,11] *} + +//// + +//// tab | Pydantic v1 + +/// info + +Na versão 1 do Pydantic você importaria `BaseSettings` diretamente do módulo `pydantic` em vez do módulo `pydantic_settings`. + +/// + +{* ../../docs_src/settings/tutorial001_pv1.py hl[2,5:8,11] *} + +//// + +/// tip | Dica + +Se você quiser algo pronto para copiar e colar na sua aplicação, não use esse exemplo, mas sim o exemplo abaixo. + +/// + +Portanto, quando você cria uma instância da classe `Settings` (nesse caso, o objeto `settings`), o Pydantic lê as variáveis de ambiente sem diferenciar maiúsculas e minúsculas, por isso, uma variável maiúscula `APP_NAME` será usada para o atributo `app_name`. + +Depois ele irá converter e validar os dados. Assim, quando você utilizar aquele objeto `settings`, os dados terão o tipo que você declarou (e.g. `items_per_user` será do tipo `int`). + +### Usando o objeto `settings` + +Depois, Você pode utilizar o novo objeto `settings` na sua aplicação: + +{* ../../docs_src/settings/tutorial001.py hl[18:20] *} + +### Executando o servidor + +No próximo passo, você pode inicializar o servidor passando as configurações em forma de variáveis de ambiente, por exemplo, você poderia definir `ADMIN_EMAIL` e `APP_NAME` da seguinte forma: + +
+ +```console +$ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" fastapi run main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +/// tip | Dica + +Para definir múltiplas variáveis de ambiente para um único comando basta separá-las utilizando espaços, e incluir todas elas antes do comando. + +/// + +Assim, o atributo `admin_email` seria definido como `"deadpool@example.com"`. + +`app_name` seria `"ChimichangApp"`. + +E `items_per_user` manteria o valor padrão de `50`. + +## Configurações em um módulo separado + +Você também pode incluir essas configurações em um arquivo de um módulo separado como visto em [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=\_blank}. + +Por exemplo, você pode adicionar um arquivo `config.py` com: + +{* ../../docs_src/settings/app01/config.py *} + +E utilizar essa configuração em `main.py`: + +{* ../../docs_src/settings/app01/main.py hl[3,11:13] *} + +/// tip | Dica + +Você também precisa incluir um arquivo `__init__.py` como visto em [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=\_blank}. + +/// + +## Configurações em uma dependência + +Em certas ocasiões, pode ser útil fornecer essas configurações a partir de uma dependência, em vez de definir um objeto global `settings` que é utilizado em toda a aplicação. + +Isso é especialmente útil durante os testes, já que é bastante simples sobrescrever uma dependência com suas configurações personalizadas. + +### O arquivo de configuração + +Baseando-se no exemplo anterior, seu arquivo `config.py` seria parecido com isso: + +{* ../../docs_src/settings/app02/config.py hl[10] *} + +Perceba que dessa vez não criamos uma instância padrão `settings = Settings()`. + +### O arquivo principal da aplicação + +Agora criamos a dependência que retorna um novo objeto `config.Settings()`. + +{* ../../docs_src/settings/app02_an_py39/main.py hl[6,12:13] *} + +/// tip | Dica + +Vamos discutir sobre `@lru_cache` logo mais. + +Por enquanto, você pode considerar `get_settings()` como uma função normal. + +/// + +E então podemos declarar essas configurações como uma dependência na função de operação da rota e utilizar onde for necessário. + +{* ../../docs_src/settings/app02_an_py39/main.py hl[17,19:21] *} + +### Configurações e testes + +Então seria muito fácil fornecer uma configuração diferente durante a execução dos testes sobrescrevendo a dependência de `get_settings`: + +{* ../../docs_src/settings/app02/test_main.py hl[9:10,13,21] *} + +Na sobrescrita da dependência, definimos um novo valor para `admin_email` quando instanciamos um novo objeto `Settings`, e então retornamos esse novo objeto. + +Após isso, podemos testar se o valor está sendo utilizado. + +## Lendo um arquivo `.env` + +Se você tiver muitas configurações que variem bastante, talvez em ambientes distintos, pode ser útil colocá-las em um arquivo e depois lê-las como se fossem variáveis de ambiente. + +Essa prática é tão comum que possui um nome, essas variáveis de ambiente normalmente são colocadas em um arquivo `.env`, e esse arquivo é chamado de "dotenv". + +/// tip | Dica + +Um arquivo iniciando com um ponto final (`.`) é um arquivo oculto em sistemas baseados em Unix, como Linux e MacOS. + +Mas um arquivo dotenv não precisa ter esse nome exato. + +/// + +Pydantic suporta a leitura desses tipos de arquivos utilizando uma biblioteca externa. Você pode ler mais em Pydantic Settings: Dotenv (.env) support. + +/// tip | Dica + +Para que isso funcione você precisa executar `pip install python-dotenv`. + +/// + +### O arquivo `.env` + +Você pode definir um arquivo `.env` com o seguinte conteúdo: + +```bash +ADMIN_EMAIL="deadpool@example.com" +APP_NAME="ChimichangApp" +``` + +### Obtendo configurações do `.env` + +E então adicionar o seguinte código em `config.py`: + +//// tab | Pydantic v2 + +{* ../../docs_src/settings/app03_an/config.py hl[9] *} + +/// tip | Dica + +O atributo `model_config` é usado apenas para configuração do Pydantic. Você pode ler mais em Pydantic Model Config. + +/// + +//// + +//// tab | Pydantic v1 + +{* ../../docs_src/settings/app03_an/config_pv1.py hl[9:10] *} + +/// tip | Dica + +A classe `Config` é usada apenas para configuração do Pydantic. Você pode ler mais em Pydantic Model Config. + +/// + +//// + +/// info + +Na versão 1 do Pydantic a configuração é realizada por uma classe interna `Config`, na versão 2 do Pydantic isso é feito com o atributo `model_config`. Esse atributo recebe um `dict`, para utilizar o autocomplete e checagem de erros do seu editor de texto você pode importar e utilizar `SettingsConfigDict` para definir esse `dict`. + +/// + +Aqui definimos a configuração `env_file` dentro da classe `Settings` do Pydantic, e definimos o valor como o nome do arquivo dotenv que queremos utilizar. + +### Declarando `Settings` apenas uma vez com `lru_cache` + +Ler o conteúdo de um arquivo em disco normalmente é uma operação custosa (lenta), então você provavelmente quer fazer isso apenas um vez e reutilizar o mesmo objeto settings depois, em vez de ler os valores a cada requisição. + +Mas cada vez que fazemos: + +```Python +Settings() +``` + +um novo objeto `Settings` é instanciado, e durante a instanciação, o arquivo `.env` é lido novamente. + +Se a função da dependência fosse apenas: + +```Python +def get_settings(): + return Settings() +``` + +Iriamos criar um novo objeto a cada requisição, e estaríamos lendo o arquivo `.env` a cada requisição. ⚠️ + +Mas como estamos utilizando o decorador `@lru_cache` acima, o objeto `Settings` é criado apenas uma vez, na primeira vez que a função é chamada. ✔️ + +{* ../../docs_src/settings/app03_an_py39/main.py hl[1,11] *} + +Dessa forma, todas as chamadas da função `get_settings()` nas dependências das próximas requisições, em vez de executar o código interno de `get_settings()` e instanciar um novo objeto `Settings`, irão retornar o mesmo objeto que foi retornado na primeira chamada, de novo e de novo. + +#### Detalhes Técnicos de `lru_cache` + +`@lru_cache` modifica a função decorada para retornar o mesmo valor que foi retornado na primeira vez, em vez de calculá-lo novamente, executando o código da função toda vez. + +Assim, a função abaixo do decorador é executada uma única vez para cada combinação dos argumentos passados. E os valores retornados para cada combinação de argumentos são sempre reutilizados para cada nova chamada da função com a mesma combinação de argumentos. + +Por exemplo, se você definir uma função: + +```Python +@lru_cache +def say_hi(name: str, salutation: str = "Ms."): + return f"Hello {salutation} {name}" +``` + +Seu programa poderia executar dessa forma: + +```mermaid +sequenceDiagram + +participant code as Código +participant function as say_hi() +participant execute as Executar Função + + rect rgba(0, 255, 0, .1) + code ->> function: say_hi(name="Camila") + function ->> execute: executar código da função + execute ->> code: retornar o resultado + end + + rect rgba(0, 255, 255, .1) + code ->> function: say_hi(name="Camila") + function ->> code: retornar resultado armazenado + end + + rect rgba(0, 255, 0, .1) + code ->> function: say_hi(name="Rick") + function ->> execute: executar código da função + execute ->> code: retornar o resultado + end + + rect rgba(0, 255, 0, .1) + code ->> function: say_hi(name="Rick", salutation="Mr.") + function ->> execute: executar código da função + execute ->> code: retornar o resultado + end + + rect rgba(0, 255, 255, .1) + code ->> function: say_hi(name="Rick") + function ->> code: retornar resultado armazenado + end + + rect rgba(0, 255, 255, .1) + code ->> function: say_hi(name="Camila") + function ->> code: retornar resultado armazenado + end +``` + +No caso da nossa dependência `get_settings()`, a função não recebe nenhum argumento, então ela sempre retorna o mesmo valor. + +Dessa forma, ela se comporta praticamente como uma variável global, mas ao ser utilizada como uma função de uma dependência, pode facilmente ser sobrescrita durante os testes. + +`@lru_cache` é definido no módulo `functools` que faz parte da biblioteca padrão do Python, você pode ler mais sobre esse decorador no link Python Docs sobre `@lru_cache`. + +## Recapitulando + +Você pode usar o módulo Pydantic Settings para gerenciar as configurações de sua aplicação, utilizando todo o poder dos modelos Pydantic. + +- Utilizar dependências simplifica os testes. +- Você pode utilizar arquivos .env junto das configurações do Pydantic. +- Utilizar o decorador `@lru_cache` evita que o arquivo .env seja lido de novo e de novo para cada requisição, enquanto permite que você sobrescreva durante os testes. diff --git a/docs/pt/docs/advanced/sub-applications.md b/docs/pt/docs/advanced/sub-applications.md new file mode 100644 index 000000000..efc6bef64 --- /dev/null +++ b/docs/pt/docs/advanced/sub-applications.md @@ -0,0 +1,67 @@ +# Sub Aplicações - Montagens + +Se você precisar ter duas aplicações FastAPI independentes, cada uma com seu próprio OpenAPI e suas próprias interfaces de documentação, você pode ter um aplicativo principal e "montar" uma (ou mais) sub-aplicações. + +## Montando uma aplicação **FastAPI** + +"Montar" significa adicionar uma aplicação completamente "independente" em um caminho específico, que então se encarrega de lidar com tudo sob esse caminho, com as operações de rota declaradas nessa sub-aplicação. + +### Aplicação de nível superior + +Primeiro, crie a aplicação principal, de nível superior, **FastAPI**, e suas *operações de rota*: + +{* ../../docs_src/sub_applications/tutorial001.py hl[3,6:8] *} + +### Sub-aplicação + +Em seguida, crie sua sub-aplicação e suas *operações de rota*. + +Essa sub-aplicação é apenas outra aplicação FastAPI padrão, mas esta é a que será "montada": + +{* ../../docs_src/sub_applications/tutorial001.py hl[11,14:16] *} + +### Monte a sub-aplicação + +Na sua aplicação de nível superior, `app`, monte a sub-aplicação, `subapi`. + +Neste caso, ela será montada no caminho `/subapi`: + +{* ../../docs_src/sub_applications/tutorial001.py hl[11,19] *} + +### Verifique a documentação automática da API + +Agora, execute `uvicorn` com a aplicação principal, se o seu arquivo for `main.py`, seria: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +E abra a documentação em http://127.0.0.1:8000/docs. + +Você verá a documentação automática da API para a aplicação principal, incluindo apenas suas próprias _operações de rota_: + + + +E então, abra a documentação para a sub-aplicação, em http://127.0.0.1:8000/subapi/docs. + +Você verá a documentação automática da API para a sub-aplicação, incluindo apenas suas próprias _operações de rota_, todas sob o prefixo de sub-caminho correto `/subapi`: + + + +Se você tentar interagir com qualquer uma das duas interfaces de usuário, elas funcionarão corretamente, porque o navegador será capaz de se comunicar com cada aplicação ou sub-aplicação específica. + +### Detalhes Técnicos: `root_path` + +Quando você monta uma sub-aplicação como descrito acima, o FastAPI se encarrega de comunicar o caminho de montagem para a sub-aplicação usando um mecanismo da especificação ASGI chamado `root_path`. + +Dessa forma, a sub-aplicação saberá usar esse prefixo de caminho para a interface de documentação. + +E a sub-aplicação também poderia ter suas próprias sub-aplicações montadas e tudo funcionaria corretamente, porque o FastAPI lida com todos esses `root_path`s automaticamente. + +Você aprenderá mais sobre o `root_path` e como usá-lo explicitamente na seção sobre [Atrás de um Proxy](behind-a-proxy.md){.internal-link target=_blank}. diff --git a/docs/pt/docs/advanced/templates.md b/docs/pt/docs/advanced/templates.md new file mode 100644 index 000000000..4d22bfbbf --- /dev/null +++ b/docs/pt/docs/advanced/templates.md @@ -0,0 +1,124 @@ +# Templates + +Você pode usar qualquer template engine com o **FastAPI**. + +Uma escolha comum é o Jinja2, o mesmo usado pelo Flask e outras ferramentas. + +Existem utilitários para configurá-lo facilmente que você pode usar diretamente em sua aplicação **FastAPI** (fornecidos pelo Starlette). + +## Instalação de dependências + +Para instalar o `jinja2`, siga o código abaixo: + +
+ +```console +$ pip install jinja2 +``` + +
+ +## Usando `Jinja2Templates` + +* Importe `Jinja2Templates`. +* Crie um `templates` que você possa reutilizar posteriormente. +* Declare um parâmetro `Request` no *path operation* que retornará um template. +* Use o `template` que você criou para renderizar e retornar uma `TemplateResponse`, passe o nome do template, o request object, e um "context" dict com pares chave-valor a serem usados dentro do template do Jinja2. + +{* ../../docs_src/templates/tutorial001.py hl[4,11,15:18] *} + +/// note + +Antes do FastAPI 0.108.0, Starlette 0.29.0, `name` era o primeiro parâmetro. + +Além disso, em versões anteriores, o objeto `request` era passado como parte dos pares chave-valor no "context" dict para o Jinja2. + +/// + +/// tip | Dica + +Ao declarar `response_class=HTMLResponse`, a documentação entenderá que a resposta será HTML. + +/// + +/// note | Detalhes Técnicos + +Você também poderia usar `from starlette.templating import Jinja2Templates`. + +**FastAPI** fornece o mesmo `starlette.templating` como `fastapi.templating` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria das respostas disponíveis vêm diretamente do Starlette. O mesmo acontece com `Request` e `StaticFiles`. + +/// + +## Escrevendo Templates + +Então você pode escrever um template em `templates/item.html`, por exemplo: + +```jinja hl_lines="7" +{!../../docs_src/templates/templates/item.html!} +``` + +### Interpolação de Valores no Template + +No código HTML que contém: + +{% raw %} + +```jinja +Item ID: {{ id }} +``` + +{% endraw %} + +...aparecerá o `id` obtido do "context" `dict` que você passou: + +```Python +{"id": id} +``` + +Por exemplo, dado um ID de valor `42`, aparecerá: + +```html +Item ID: 42 +``` + +### Argumentos do `url_for` + +Você também pode usar `url_for()` dentro do template, ele recebe como argumentos os mesmos argumentos que seriam usados pela sua *path operation function*. + +Logo, a seção com: + +{% raw %} + +```jinja + +``` + +{% endraw %} + +...irá gerar um link para a mesma URL que será tratada pela *path operation function* `read_item(id=id)`. + +Por exemplo, com um ID de `42`, isso renderizará: + +```html + +``` + +## Templates e Arquivos Estáticos + +Você também pode usar `url_for()` dentro do template e usá-lo, por examplo, com o `StaticFiles` que você montou com o `name="static"`. + +```jinja hl_lines="4" +{!../../docs_src/templates/templates/item.html!} +``` + +Neste exemplo, ele seria vinculado a um arquivo CSS em `static/styles.css` com: + +```CSS hl_lines="4" +{!../../docs_src/templates/static/styles.css!} +``` + +E como você está usando `StaticFiles`, este arquivo CSS será automaticamente servido pela sua aplicação FastAPI na URL `/static/styles.css`. + +## Mais detalhes + +Para obter mais detalhes, incluindo como testar templates, consulte a documentação da Starlette sobre templates. diff --git a/docs/pt/docs/advanced/testing-dependencies.md b/docs/pt/docs/advanced/testing-dependencies.md new file mode 100644 index 000000000..3ede4741d --- /dev/null +++ b/docs/pt/docs/advanced/testing-dependencies.md @@ -0,0 +1,53 @@ +# Testando Dependências com Sobreposição (Overrides) + +## Sobrepondo dependências durante os testes + +Existem alguns cenários onde você deseje sobrepor uma dependência durante os testes. + +Você não quer que a dependência original execute (e nenhuma das subdependências que você possa ter). + +Em vez disso, você deseja fornecer uma dependência diferente que será usada somente durante os testes (possivelmente apenas para alguns testes específicos) e fornecerá um valor que pode ser usado onde o valor da dependência original foi usado. + +### Casos de uso: serviço externo + +Um exemplo pode ser que você possua um provedor de autenticação externo que você precisa chamar. + +Você envia ao serviço um *token* e ele retorna um usuário autenticado. + +Este provedor pode cobrar por requisição, e chamá-lo pode levar mais tempo do que se você tivesse um usuário fixo para os testes. + +Você provavelmente quer testar o provedor externo uma vez, mas não necessariamente chamá-lo em todos os testes que executarem. + +Neste caso, você pode sobrepor (*override*) a dependência que chama o provedor, e utilizar uma dependência customizada que retorna um *mock* do usuário, apenas para os seus testes. + +### Utilize o atributo `app.dependency_overrides` + +Para estes casos, a sua aplicação **FastAPI** possui o atributo `app.dependency_overrides`. Ele é um simples `dict`. + +Para sobrepor a dependência para os testes, você coloca como chave a dependência original (a função), e como valor, a sua sobreposição da dependência (outra função). + +E então o **FastAPI** chamará a sobreposição no lugar da dependência original. + +{* ../../docs_src/dependency_testing/tutorial001_an_py310.py hl[26:27,30] *} + +/// tip | Dica + +Você pode definir uma sobreposição de dependência para uma dependência que é utilizada em qualquer lugar da sua aplicação **FastAPI**. + +A dependência original pode estar sendo utilizada em uma *função de operação de rota*, um *docorador de operação de rota* (quando você não utiliza o valor retornado), uma chamada ao `.include_router()`, etc. + +O FastAPI ainda poderá sobrescrevê-lo. + +/// + +E então você pode redefinir as suas sobreposições (removê-las) definindo o `app.dependency_overrides` como um `dict` vazio: + +```Python +app.dependency_overrides = {} +``` + +/// tip | Dica + +Se você quer sobrepor uma dependência apenas para alguns testes, você pode definir a sobreposição no início do testes (dentro da função de teste) e reiniciá-la ao final (no final da função de teste). + +/// diff --git a/docs/pt/docs/advanced/testing-events.md b/docs/pt/docs/advanced/testing-events.md new file mode 100644 index 000000000..6113c9913 --- /dev/null +++ b/docs/pt/docs/advanced/testing-events.md @@ -0,0 +1,5 @@ +# Testando Eventos: inicialização - encerramento + +Quando você precisa que os seus manipuladores de eventos (`startup` e `shutdown`) sejam executados em seus testes, você pode utilizar o `TestClient` usando a instrução `with`: + +{* ../../docs_src/app_testing/tutorial003.py hl[9:12,20:24] *} diff --git a/docs/pt/docs/advanced/testing-websockets.md b/docs/pt/docs/advanced/testing-websockets.md new file mode 100644 index 000000000..942771bc9 --- /dev/null +++ b/docs/pt/docs/advanced/testing-websockets.md @@ -0,0 +1,13 @@ +# Testando WebSockets + +Você pode usar o mesmo `TestClient` para testar WebSockets. + +Para isso, você utiliza o `TestClient` dentro de uma instrução `with`, conectando com o WebSocket: + +{* ../../docs_src/app_testing/tutorial002.py hl[27:31] *} + +/// note | Nota + +Para mais detalhes, confira a documentação do Starlette para testar WebSockets. + +/// diff --git a/docs/pt/docs/advanced/using-request-directly.md b/docs/pt/docs/advanced/using-request-directly.md new file mode 100644 index 000000000..f31e2ed15 --- /dev/null +++ b/docs/pt/docs/advanced/using-request-directly.md @@ -0,0 +1,56 @@ +# Utilizando o Request diretamente + +Até agora você declarou as partes da requisição que você precisa utilizando os seus tipos. + +Obtendo dados de: + +* Os parâmetros das rotas. +* Cabeçalhos (*Headers*). +* Cookies. +* etc. + +E ao fazer isso, o **FastAPI** está validando as informações, convertendo-as e gerando documentação para a sua API automaticamente. + +Porém há situações em que você possa precisar acessar o objeto `Request` diretamente. + +## Detalhes sobre o objeto `Request` + +Como o **FastAPI** é na verdade o **Starlette** por baixo, com camadas de diversas funcionalidades por cima, você pode utilizar o objeto `Request` do Starlette diretamente quando precisar. + +Isso significaria também que se você obtiver informações do objeto `Request` diretamente (ler o corpo da requisição por exemplo), as informações não serão validadas, convertidas ou documentadas (com o OpenAPI, para a interface de usuário automática da API) pelo FastAPI. + +Embora qualquer outro parâmetro declarado normalmente (o corpo da requisição com um modelo Pydantic, por exemplo) ainda seria validado, convertido, anotado, etc. + +Mas há situações específicas onde é útil utilizar o objeto `Request`. + +## Utilize o objeto `Request` diretamente + +Vamos imaginar que você deseja obter o endereço de IP/host do cliente dentro da sua *função de operação de rota*. + +Para isso você precisa acessar a requisição diretamente. + +{* ../../docs_src/using_request_directly/tutorial001.py hl[1,7:8] *} + +Ao declarar o parâmetro com o tipo sendo um `Request` em sua *função de operação de rota*, o **FastAPI** saberá como passar o `Request` neste parâmetro. + +/// tip | Dica + +Note que neste caso, nós estamos declarando o parâmetro da rota ao lado do parâmetro da requisição. + +Assim, o parâmetro da rota será extraído, validado, convertido para o tipo especificado e anotado com OpenAPI. + +Do mesmo jeito, você pode declarar qualquer outro parâmetro normalmente, e além disso, obter o `Request` também. + +/// + +## Documentação do `Request` + +Você pode ler mais sobre os detalhes do objeto `Request` no site da documentação oficial do Starlette.. + +/// note | Detalhes Técnicos + +Você também pode utilizar `from starlette.requests import Request`. + +O **FastAPI** fornece isso diretamente apenas como uma conveniência para você, o desenvolvedor. Mas ele vem diretamente do Starlette. + +/// diff --git a/docs/pt/docs/advanced/websockets.md b/docs/pt/docs/advanced/websockets.md new file mode 100644 index 000000000..82e443886 --- /dev/null +++ b/docs/pt/docs/advanced/websockets.md @@ -0,0 +1,186 @@ +# WebSockets + +Você pode usar WebSockets com **FastAPI**. + +## Instalando `WebSockets` + +Garanta que você criou um [ambiente virtual](../virtual-environments.md){.internal-link target=_blank}, o ativou e instalou o `websockets`: + +
+ +```console +$ pip install websockets + +---> 100% +``` + +
+ +## Cliente WebSockets + +### Em produção + +Em seu sistema de produção, você provavelmente tem um frontend criado com um framework moderno como React, Vue.js ou Angular. + +E para comunicar usando WebSockets com seu backend, você provavelmente usaria as utilidades do seu frontend. + +Ou você pode ter um aplicativo móvel nativo que se comunica diretamente com seu backend WebSocket, em código nativo. + +Ou você pode ter qualquer outra forma de comunicar com o endpoint WebSocket. + +--- + +Mas para este exemplo, usaremos um documento HTML muito simples com algum JavaScript, tudo dentro de uma string longa. + +Esse, é claro, não é o ideal e você não o usaria para produção. + +Na produção, você teria uma das opções acima. + +Mas é a maneira mais simples de focar no lado do servidor de WebSockets e ter um exemplo funcional: + +{* ../../docs_src/websockets/tutorial001.py hl[2,6:38,41:43] *} + +## Criando um `websocket` + +Em sua aplicação **FastAPI**, crie um `websocket`: + +{*../../docs_src/websockets/tutorial001.py hl[46:47]*} + +/// note | Detalhes Técnicos + +Você também poderia usar `from starlette.websockets import WebSocket`. + +A **FastAPI** fornece o mesmo `WebSocket` diretamente apenas como uma conveniência para você, o desenvolvedor. Mas ele vem diretamente do Starlette. + +/// + +## Aguardar por mensagens e enviar mensagens + +Em sua rota WebSocket você pode esperar (`await`) por mensagens e enviar mensagens. + +{*../../docs_src/websockets/tutorial001.py hl[48:52]*} + +Você pode receber e enviar dados binários, de texto e JSON. + +## Tente você mesmo + +Se seu arquivo for nomeado `main.py`, execute sua aplicação com: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Abra seu navegador em: http://127.0.0.1:8000. + +Você verá uma página simples como: + + + +Você pode digitar mensagens na caixa de entrada e enviá-las: + + + +E sua aplicação **FastAPI** com WebSockets responderá de volta: + + + +Você pode enviar (e receber) muitas mensagens: + + + +E todas elas usarão a mesma conexão WebSocket. + +## Usando `Depends` e outros + +Nos endpoints WebSocket você pode importar do `fastapi` e usar: + +* `Depends` +* `Security` +* `Cookie` +* `Header` +* `Path` +* `Query` + +Eles funcionam da mesma forma que para outros endpoints FastAPI/*operações de rota*: + +{*../../docs_src/websockets/tutorial002_an_py310.py hl[68:69,82]*} + +/// info | Informação + +Como isso é um WebSocket, não faz muito sentido levantar uma `HTTPException`, em vez disso levantamos uma `WebSocketException`. + +Você pode usar um código de fechamento dos códigos válidos definidos na especificação. + +/// + +### Tente os WebSockets com dependências + +Se seu arquivo for nomeado `main.py`, execute sua aplicação com: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Abrar seu browser em: http://127.0.0.1:8000. + +Lá você pode definir: + +* O "Item ID", usado na rota. +* O "Token" usado como um parâmetro de consulta. + +/// tip | Dica + +Perceba que a consulta `token` será manipulada por uma dependência. + +/// + +Com isso você pode conectar o WebSocket e então enviar e receber mensagens: + + + +## Lidando com desconexões e múltiplos clientes + +Quando uma conexão WebSocket é fechada, o `await websocket.receive_text()` levantará uma exceção `WebSocketDisconnect`, que você pode então capturar e lidar como neste exemplo. + +{*../../docs_src/websockets/tutorial003_py39.py hl[79:81]*} + +Para testar: + +* Abrar o aplicativo com várias abas do navegador. +* Escreva mensagens a partir delas. +* Então feche uma das abas. + +Isso levantará a exceção `WebSocketDisconnect`, e todos os outros clientes receberão uma mensagem como: + +``` +Client #1596980209979 left the chat +``` + +/// tip | Dica + +O app acima é um exemplo mínimo e simples para demonstrar como lidar e transmitir mensagens para várias conexões WebSocket. + +Mas tenha em mente que, como tudo é manipulado na memória, em uma única lista, ele só funcionará enquanto o processo estiver em execução e só funcionará com um único processo. + +Se você precisa de algo fácil de integrar com o FastAPI, mas que seja mais robusto, suportado por Redis, PostgreSQL ou outros, verifique o encode/broadcaster. + +/// + +## Mais informações + +Para aprender mais sobre as opções, verifique a documentação do Starlette para: + +* A classe `WebSocket`. +* Manipulação de WebSockets baseada em classes. diff --git a/docs/pt/docs/advanced/wsgi.md b/docs/pt/docs/advanced/wsgi.md new file mode 100644 index 000000000..a36261e5e --- /dev/null +++ b/docs/pt/docs/advanced/wsgi.md @@ -0,0 +1,35 @@ +# Adicionando WSGI - Flask, Django, entre outros + +Como você viu em [Sub Applications - Mounts](sub-applications.md){.internal-link target=_blank} e [Behind a Proxy](behind-a-proxy.md){.internal-link target=_blank}, você pode **"montar"** aplicações WSGI. + +Para isso, você pode utilizar o `WSGIMiddleware` para encapsular a sua aplicação WSGI, como por exemplo Flask, Django, etc. + +## Usando o `WSGIMiddleware` + +Você precisa importar o `WSGIMiddleware`. + +Em seguinda, encapsular a aplicação WSGI (e.g. Flask) com o middleware. + +E então **"montar"** em um caminho de rota. + +{* ../../docs_src/wsgi/tutorial001.py hl[2:3,23] *} + +## Conferindo + +Agora todas as requisições sob o caminho `/v1/` serão manipuladas pela aplicação utilizando Flask. + +E o resto será manipulado pelo **FastAPI**. + +Se você rodar a aplicação e ir até http://localhost:8000/v1/, você verá o retorno do Flask: + +```txt +Hello, World from Flask! +``` + +E se você for até http://localhost:8000/v2, você verá o retorno do FastAPI: + +```JSON +{ + "message": "Hello World" +} +``` diff --git a/docs/pt/docs/alternatives.md b/docs/pt/docs/alternatives.md index 61ee4f900..29c9693bb 100644 --- a/docs/pt/docs/alternatives.md +++ b/docs/pt/docs/alternatives.md @@ -1,6 +1,6 @@ # Alternativas, Inspiração e Comparações -O que inspirou **FastAPI**, como ele se compara a outras alternativas e o que FastAPI aprendeu delas. +O que inspirou o **FastAPI**, como ele se compara às alternativas e o que FastAPI aprendeu delas. ## Introdução @@ -30,11 +30,17 @@ Ele é utilizado por muitas companhias incluindo Mozilla, Red Hat e Eventbrite. Ele foi um dos primeiros exemplos de **documentação automática de API**, e essa foi especificamente uma das primeiras idéias que inspirou "a busca por" **FastAPI**. -!!! note "Nota" - Django REST Framework foi criado por Tom Christie. O mesmo criador de Starlette e Uvicorn, nos quais **FastAPI** é baseado. +/// note | Nota -!!! check "**FastAPI** inspirado para" - Ter uma documentação automática da API em interface web. +Django REST Framework foi criado por Tom Christie. O mesmo criador de Starlette e Uvicorn, nos quais **FastAPI** é baseado. + +/// + +/// check | **FastAPI** inspirado para + +Ter uma documentação automática da API em interface web. + +/// ### Flask @@ -50,10 +56,13 @@ Esse desacoplamento de partes, e sendo um "microframework" que pode ser extendid Dada a simplicidade do Flask, parecia uma ótima opção para construção de APIs. A próxima coisa a procurar era um "Django REST Framework" para Flask. -!!! check "**FastAPI** inspirado para" - Ser um microframework. Fazer ele fácil para misturar e combinar com ferramentas e partes necessárias. +/// check | **FastAPI** inspirado para - Ser simples e com sistema de roteamento fácil de usar. +Ser um microframework. Fazer ele fácil para misturar e combinar com ferramentas e partes necessárias. + +Ser simples e com sistema de roteamento fácil de usar. + +/// ### Requests @@ -89,10 +98,13 @@ def read_url(): Veja as similaridades em `requests.get(...)` e `@app.get(...)`. -!!! check "**FastAPI** inspirado para" - * Ter uma API simples e intuitiva. - * Utilizar nomes de métodos HTTP (operações) diretamente, de um jeito direto e intuitivo. - * Ter padrões sensíveis, mas customizações poderosas. +/// check | **FastAPI** inspirado para + +* Ter uma API simples e intuitiva. +* Utilizar nomes de métodos HTTP (operações) diretamente, de um jeito direto e intuitivo. +* Ter padrões sensíveis, mas customizações poderosas. + +/// ### Swagger / OpenAPI @@ -106,15 +118,18 @@ Em algum ponto, Swagger foi dado para a Fundação Linux, e foi renomeado OpenAP Isso acontece porquê quando alguém fala sobre a versão 2.0 é comum dizer "Swagger", e para a versão 3+, "OpenAPI". -!!! check "**FastAPI** inspirado para" - Adotar e usar um padrão aberto para especificações API, ao invés de algum esquema customizado. +/// check | **FastAPI** inspirado para + +Adotar e usar um padrão aberto para especificações API, ao invés de algum esquema customizado. + +E integrar ferramentas de interface para usuários baseado nos padrões: - E integrar ferramentas de interface para usuários baseado nos padrões: +* Swagger UI +* ReDoc - * Swagger UI - * ReDoc +Esses dois foram escolhidos por serem bem populares e estáveis, mas fazendo uma pesquisa rápida, você pode encontrar dúzias de interfaces alternativas adicionais para OpenAPI (assim você poderá utilizar com **FastAPI**). - Esses dois foram escolhidos por serem bem populares e estáveis, mas fazendo uma pesquisa rápida, você pode encontrar dúzias de interfaces alternativas adicionais para OpenAPI (assim você poderá utilizar com **FastAPI**). +/// ### Flask REST frameworks @@ -132,8 +147,11 @@ Esses recursos são o que Marshmallow foi construído para fornecer. Ele é uma Mas ele foi criado antes da existência do _type hints_ do Python. Então, para definir todo o _schema_ você precisa utilizar específicas ferramentas e classes fornecidas pelo Marshmallow. -!!! check "**FastAPI** inspirado para" - Usar código para definir "schemas" que forneçam, automaticamente, tipos de dados e validação. +/// check | **FastAPI** inspirado para + +Usar código para definir "schemas" que forneçam, automaticamente, tipos de dados e validação. + +/// ### Webargs @@ -145,11 +163,17 @@ Ele utiliza Marshmallow por baixo para validação de dados. E ele foi criado pe Ele é uma grande ferramenta e eu também a utilizei muito, antes de ter o **FastAPI**. -!!! info - Webargs foi criado pelos mesmos desenvolvedores do Marshmallow. +/// info + +Webargs foi criado pelos mesmos desenvolvedores do Marshmallow. -!!! check "**FastAPI** inspirado para" - Ter validação automática de dados vindos de requisições. +/// + +/// check | **FastAPI** inspirado para + +Ter validação automática de dados vindos de requisições. + +/// ### APISpec @@ -169,11 +193,17 @@ Mas então, nós temos novamente o problema de ter uma micro-sintaxe, dentro de O editor não poderá ajudar muito com isso. E se nós modificarmos os parâmetros dos _schemas_ do Marshmallow e esquecer de modificar também aquela _docstring_ YAML, o _schema_ gerado pode ficar obsoleto. -!!! info - APISpec foi criado pelos mesmos desenvolvedores do Marshmallow. +/// info + +APISpec foi criado pelos mesmos desenvolvedores do Marshmallow. + +/// + +/// check | **FastAPI** inspirado para -!!! check "**FastAPI** inspirado para" - Dar suporte a padrões abertos para APIs, OpenAPI. +Dar suporte a padrões abertos para APIs, OpenAPI. + +/// ### Flask-apispec @@ -185,7 +215,7 @@ Ele utiliza a informação do Webargs e Marshmallow para gerar automaticamente _ Isso resolveu o problema de ter que escrever YAML (outra sintaxe) dentro das _docstrings_ Python. -Essa combinação de Flask, Flask-apispec com Marshmallow e Webargs foi meu _backend stack_ favorito até construir **FastAPI**. +Essa combinação de Flask, Flask-apispec com Marshmallow e Webargs foi meu _backend stack_ favorito até construir o **FastAPI**. Usando essa combinação levou a criação de vários geradores Flask _full-stack_. Há muitas _stacks_ que eu (e vários times externos) estou utilizando até agora: @@ -195,11 +225,17 @@ Usando essa combinação levou a criação de vários geradores Flask _full-stac E esses mesmos geradores _full-stack_ foram a base dos [Geradores de Projetos **FastAPI**](project-generation.md){.internal-link target=_blank}. -!!! info - Flask-apispec foi criado pelos mesmos desenvolvedores do Marshmallow. +/// info + +Flask-apispec foi criado pelos mesmos desenvolvedores do Marshmallow. + +/// -!!! check "**FastAPI** inspirado para" - Gerar _schema_ OpenAPI automaticamente, a partir do mesmo código que define serialização e validação. +/// check | **FastAPI** inspirado para + +Gerar _schema_ OpenAPI automaticamente, a partir do mesmo código que define serialização e validação. + +/// ### NestJS (and Angular) @@ -207,7 +243,7 @@ NestJS, que não é nem Python, é um framework NodeJS JavaScript (TypeScript) i Ele alcança de uma forma similar ao que pode ser feito com o Flask-apispec. -Ele tem um sistema de injeção de dependência integrado, inspirado pelo Angular dois. É necessário fazer o pré-registro dos "injetáveis" (como todos os sistemas de injeção de dependência que conheço), então, adicionando verbosidade e repetição de código. +Ele tem um sistema de injeção de dependência integrado, inspirado pelo Angular 2. É necessário fazer o pré-registro dos "injetáveis" (como todos os sistemas de injeção de dependência que conheço), então, adicionando verbosidade e repetição de código. Como os parâmetros são descritos com tipos TypeScript (similar aos _type hints_ do Python), o suporte ao editor é muito bom. @@ -215,24 +251,33 @@ Mas como os dados TypeScript não são preservados após a compilação para o J Ele também não controla modelos aninhados muito bem. Então, se o corpo JSON na requisição for um objeto JSON que contém campos internos que contém objetos JSON aninhados, ele não consegue ser validado e documentado apropriadamente. -!!! check "**FastAPI** inspirado para" - Usar tipos Python para ter um ótimo suporte do editor. +/// check | **FastAPI** inspirado para + +Usar tipos Python para ter um ótimo suporte do editor. - Ter um sistema de injeção de dependência poderoso. Achar um jeito de minimizar repetição de código. +Ter um sistema de injeção de dependência poderoso. Achar um jeito de minimizar repetição de código. + +/// ### Sanic Ele foi um dos primeiros frameworks Python extremamente rápido baseado em `asyncio`. Ele foi feito para ser muito similar ao Flask. -!!! note "Detalhes técnicos" - Ele utiliza `uvloop` ao invés do '_loop_' `asyncio` padrão do Python. É isso que deixa ele tão rápido. +/// note | Detalhes técnicos + +Ele utiliza `uvloop` ao invés do '_loop_' `asyncio` padrão do Python. É isso que deixa ele tão rápido. + +Ele claramente inspirou Uvicorn e Starlette, que são atualmente mais rápidos que o Sanic em testes de performance abertos. + +/// - Ele claramente inspirou Uvicorn e Starlette, que são atualmente mais rápidos que o Sanic em testes de performance abertos. +/// check | **FastAPI** inspirado para -!!! check "**FastAPI** inspirado para" - Achar um jeito de ter uma performance insana. +Achar um jeito de ter uma performance insana. - É por isso que o **FastAPI** é baseado em Starlette, para que ele seja o framework mais rápido disponível (performance testada por terceiros). +É por isso que o **FastAPI** é baseado em Starlette, para que ele seja o framework mais rápido disponível (performance testada por terceiros). + +/// ### Falcon @@ -244,12 +289,15 @@ Ele é projetado para ter funções que recebem dois parâmetros, uma "requisiç Então, validação de dados, serialização e documentação tem que ser feitos no código, não automaticamente. Ou eles terão que ser implementados como um framework acima do Falcon, como o Hug. Essa mesma distinção acontece em outros frameworks que são inspirados pelo design do Falcon, tendo um objeto de requisição e um objeto de resposta como parâmetros. -!!! check "**FastAPI** inspirado para" - Achar jeitos de conseguir melhor performance. +/// check | **FastAPI** inspirado para + +Achar jeitos de conseguir melhor performance. + +Juntamente com Hug (como Hug é baseado no Falcon) inspirou **FastAPI** para declarar um parâmetro de `resposta` nas funções. - Juntamente com Hug (como Hug é baseado no Falcon) inspirou **FastAPI** para declarar um parâmetro de `resposta`nas funções. +Embora no FastAPI seja opcional, é utilizado principalmente para configurar cabeçalhos, cookies e códigos de status alternativos. - Embora no FastAPI seja opcional, é utilizado principalmente para configurar cabeçalhos, cookies e códigos de status alternativos. +/// ### Molten @@ -267,12 +315,15 @@ O sistema de injeção de dependência exige pré-registro das dependências e a Rotas são declaradas em um único lugar, usando funções declaradas em outros lugares (ao invés de usar decoradores que possam ser colocados diretamente acima da função que controla o _endpoint_). Isso é mais perto de como o Django faz isso do que como Flask (e Starlette) faz. Ele separa no código coisas que são relativamente amarradas. -!!! check "**FastAPI** inspirado para" - Definir validações extras para tipos de dados usando valores "padrão" de atributos dos modelos. Isso melhora o suporte do editor, e não estava disponível no Pydantic antes. +/// check | **FastAPI** inspirado para - Isso na verdade inspirou a atualização de partes do Pydantic, para dar suporte ao mesmo estilo de declaração da validação (toda essa funcionalidade já está disponível no Pydantic). +Definir validações extras para tipos de dados usando valores "padrão" de atributos dos modelos. Isso melhora o suporte do editor, e não estava disponível no Pydantic antes. -### Hug +Isso na verdade inspirou a atualização de partes do Pydantic, para dar suporte ao mesmo estilo de declaração da validação (toda essa funcionalidade já está disponível no Pydantic). + +/// + +### Hug Hug foi um dos primeiros frameworks a implementar a declaração de tipos de parâmetros usando Python _type hints_. Isso foi uma ótima idéia que inspirou outras ferramentas a fazer o mesmo. @@ -286,15 +337,21 @@ Hug tinha um incomum, interessante recurso: usando o mesmo framework, é possív Como é baseado nos padrões anteriores de frameworks web síncronos (WSGI), ele não pode controlar _Websockets_ e outras coisas, embora ele ainda tenha uma alta performance também. -!!! info - Hug foi criado por Timothy Crosley, o mesmo criador do `isort`, uma grande ferramenta para ordenação automática de _imports_ em arquivos Python. +/// info + +Hug foi criado por Timothy Crosley, o mesmo criador do `isort`, uma grande ferramenta para ordenação automática de _imports_ em arquivos Python. + +/// + +/// check | Idéias inspiradas para o **FastAPI** + +Hug inspirou partes do APIStar, e foi uma das ferramentas que eu achei mais promissora, ao lado do APIStar. -!!! check "Idéias inspiradas para o **FastAPI**" - Hug inspirou partes do APIStar, e foi uma das ferramentas que eu achei mais promissora, ao lado do APIStar. +Hug ajudou a inspirar o **FastAPI** a usar _type hints_ do Python para declarar parâmetros, e para gerar um _schema_ definindo a API automaticamente. - Hug ajudou a inspirar o **FastAPI** a usar _type hints_ do Python para declarar parâmetros, e para gerar um _schema_ definindo a API automaticamente. +Hug inspirou **FastAPI** a declarar um parâmetro de `resposta` em funções para definir cabeçalhos e cookies. - Hug inspirou **FastAPI** a declarar um parâmetro de `resposta` em funções para definir cabeçalhos e cookies. +/// ### APIStar (<= 0.5) @@ -320,27 +377,33 @@ Ele não era mais um framework web API, como o criador precisava focar no Starle Agora APIStar é um conjunto de ferramentas para validar especificações OpenAPI, não um framework web. -!!! info - APIStar foi criado por Tom Christie. O mesmo cara que criou: +/// info - * Django REST Framework - * Starlette (no qual **FastAPI** é baseado) - * Uvicorn (usado por Starlette e **FastAPI**) +APIStar foi criado por Tom Christie. O mesmo cara que criou: -!!! check "**FastAPI** inspirado para" - Existir. +* Django REST Framework +* Starlette (no qual **FastAPI** é baseado) +* Uvicorn (usado por Starlette e **FastAPI**) - A idéia de declarar múltiplas coisas (validação de dados, serialização e documentação) com os mesmos tipos Python, que ao mesmo tempo fornecesse grande suporte ao editor, era algo que eu considerava uma brilhante idéia. +/// - E após procurar por um logo tempo por um framework similar e testar muitas alternativas diferentes, APIStar foi a melhor opção disponível. +/// check | **FastAPI** inspirado para - Então APIStar parou de existir como um servidor e Starlette foi criado, e foi uma nova melhor fundação para tal sistema. Essa foi a inspiração final para construir **FastAPI**. +Existir. - Eu considero **FastAPI** um "sucessor espiritual" para o APIStar, evoluindo e melhorando os recursos, sistema de tipagem e outras partes, baseado na aprendizagem de todas essas ferramentas acima. +A idéia de declarar múltiplas coisas (validação de dados, serialização e documentação) com os mesmos tipos Python, que ao mesmo tempo fornecesse grande suporte ao editor, era algo que eu considerava uma brilhante idéia. + +E após procurar por um logo tempo por um framework similar e testar muitas alternativas diferentes, APIStar foi a melhor opção disponível. + +Então APIStar parou de existir como um servidor e Starlette foi criado, e foi uma nova melhor fundação para tal sistema. Essa foi a inspiração final para construir **FastAPI**. + +Eu considero **FastAPI** um "sucessor espiritual" para o APIStar, evoluindo e melhorando os recursos, sistema de tipagem e outras partes, baseado na aprendizagem de todas essas ferramentas acima. + +/// ## Usados por **FastAPI** -### Pydantic +### Pydantic Pydantic é uma biblioteca para definir validação de dados, serialização e documentação (usando JSON Schema) baseado nos Python _type hints_. @@ -348,10 +411,13 @@ Isso faz dele extremamente intuitivo. Ele é comparável ao Marshmallow. Embora ele seja mais rápido que Marshmallow em testes de performance. E ele é baseado nos mesmos Python _type hints_, o suporte ao editor é ótimo. -!!! check "**FastAPI** usa isso para" - Controlar toda a validação de dados, serialização de dados e modelo de documentação automática (baseado no JSON Schema). +/// check | **FastAPI** usa isso para + +Controlar toda a validação de dados, serialização de dados e modelo de documentação automática (baseado no JSON Schema). + +**FastAPI** então pega dados do JSON Schema e coloca eles no OpenAPI, à parte de todas as outras coisas que ele faz. - **FastAPI** então pega dados do JSON Schema e coloca eles no OpenAPI, à parte de todas as outras coisas que ele faz. +/// ### Starlette @@ -366,7 +432,7 @@ Ele tem: * Suporte a GraphQL. * Tarefas de processamento interno por trás dos panos. * Eventos de inicialização e encerramento. -* Cliente de testes construído com requests. +* Cliente de testes construído com HTTPX. * Respostas CORS, GZip, Arquivos Estáticos, Streaming. * Suporte para Sessão e Cookie. * 100% coberto por testes. @@ -381,17 +447,23 @@ Mas ele não fornece validação de dados automática, serialização e document Essa é uma das principais coisas que **FastAPI** adiciona no topo, tudo baseado em Python _type hints_ (usando Pydantic). Isso, mais o sistema de injeção de dependência, utilidades de segurança, geração de _schema_ OpenAPI, etc. -!!! note "Detalhes Técnicos" - ASGI é um novo "padrão" sendo desenvolvido pelos membros do time central do Django. Ele ainda não está como "Padrão Python" (PEP), embora eles estejam em processo de fazer isso. +/// note | Detalhes Técnicos - No entanto, ele já está sendo utilizado como "padrão" por diversas ferramentas. Isso melhora enormemente a interoperabilidade, como você poderia trocar Uvicorn por qualquer outro servidor ASGI (como Daphne ou Hypercorn), ou você poderia adicionar ferramentas compatíveis com ASGI, como `python-socketio`. +ASGI é um novo "padrão" sendo desenvolvido pelos membros do time central do Django. Ele ainda não está como "Padrão Python" (PEP), embora eles estejam em processo de fazer isso. -!!! check "**FastAPI** usa isso para" - Controlar todas as partes web centrais. Adiciona recursos no topo. +No entanto, ele já está sendo utilizado como "padrão" por diversas ferramentas. Isso melhora enormemente a interoperabilidade, como você poderia trocar Uvicorn por qualquer outro servidor ASGI (como Daphne ou Hypercorn), ou você poderia adicionar ferramentas compatíveis com ASGI, como `python-socketio`. - A classe `FastAPI` em si herda `Starlette`. +/// - Então, qualquer coisa que você faz com Starlette, você pode fazer diretamente com **FastAPI**, pois ele é basicamente um Starlette com esteróides. +/// check | **FastAPI** usa isso para + +Controlar todas as partes web centrais. Adiciona recursos no topo. + +A classe `FastAPI` em si herda `Starlette`. + +Então, qualquer coisa que você faz com Starlette, você pode fazer diretamente com **FastAPI**, pois ele é basicamente um Starlette com esteróides. + +/// ### Uvicorn @@ -401,12 +473,15 @@ Ele não é um framework web, mas sim um servidor. Por exemplo, ele não fornece Ele é o servidor recomendado para Starlette e **FastAPI**. -!!! check "**FastAPI** recomenda isso para" - O principal servidor web para rodar aplicações **FastAPI**. +/// check | **FastAPI** recomenda isso para + +O principal servidor web para rodar aplicações **FastAPI**. + +Você pode combinar ele com o Gunicorn, para ter um servidor multi-processos assíncrono. - Você pode combinar ele com o Gunicorn, para ter um servidor multi-processos assíncrono. +Verifique mais detalhes na seção [Deployment](deployment/index.md){.internal-link target=_blank}. - Verifique mais detalhes na seção [Deployment](deployment/index.md){.internal-link target=_blank}. +/// ## Performance e velocidade diff --git a/docs/pt/docs/async.md b/docs/pt/docs/async.md index be1278a1b..0d6bdbf0e 100644 --- a/docs/pt/docs/async.md +++ b/docs/pt/docs/async.md @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! note - Você só pode usar `await` dentro de funções criadas com `async def`. +/// note + +Você só pode usar `await` dentro de funções criadas com `async def`. + +/// --- @@ -261,7 +264,7 @@ Mas você também pode explorar os benefícios do paralelismo e multiprocessamen Isso, mais o simples fato que Python é a principal linguagem para **Data Science**, Machine Learning e especialmente Deep Learning, faz do FastAPI uma ótima escolha para APIs web e aplicações com Data Science / Machine Learning (entre muitas outras). -Para ver como alcançar esse paralelismo em produção veja a seção sobre [Deployment](deployment.md){.internal-link target=_blank}. +Para ver como alcançar esse paralelismo em produção veja a seção sobre [Deployment](deployment/index.md){.internal-link target=_blank}. ## `async` e `await` @@ -356,12 +359,15 @@ Tudo isso é o que deixa o FastAPI poderoso (através do Starlette) e que o faz ## Detalhes muito técnicos -!!! warning - Você pode provavelmente pular isso. +/// warning + +Você pode provavelmente pular isso. + +Esses são detalhes muito técnicos de como **FastAPI** funciona por baixo do capô. - Esses são detalhes muito técnicos de como **FastAPI** funciona por baixo do capô. +Se você tem algum conhecimento técnico (corrotinas, threads, blocking etc) e está curioso sobre como o FastAPI controla o `async def` vs normal `def`, vá em frente. - Se você tem algum conhecimento técnico (corrotinas, threads, blocking etc) e está curioso sobre como o FastAPI controla o `async def` vs normal `def`, vá em frente. +/// ### Funções de operação de rota @@ -369,7 +375,7 @@ Quando você declara uma *função de operação de rota* com `def` normal ao in Se você está chegando de outro framework assíncrono que não faz o trabalho descrito acima e você está acostumado a definir triviais *funções de operação de rota* com simples `def` para ter um mínimo ganho de performance (cerca de 100 nanosegundos), por favor observe que no **FastAPI** o efeito pode ser bem o oposto. Nesses casos, é melhor usar `async def` a menos que suas *funções de operação de rota* utilizem código que performem bloqueamento IO. -Ainda, em ambas as situações, as chances são que o **FastAPI** será [ainda mais rápido](/#performance){.internal-link target=_blank} do que (ou ao menos comparável a) seus frameworks antecessores. +Ainda, em ambas as situações, as chances são que o **FastAPI** será [ainda mais rápido](index.md#performance){.internal-link target=_blank} do que (ou ao menos comparável a) seus frameworks antecessores. ### Dependências diff --git a/docs/pt/docs/contributing.md b/docs/pt/docs/contributing.md deleted file mode 100644 index 02895fcfc..000000000 --- a/docs/pt/docs/contributing.md +++ /dev/null @@ -1,479 +0,0 @@ -# Desenvolvimento - Contribuindo - -Primeiramente, você deveria ver os meios básicos para [ajudar FastAPI e pedir ajuda](help-fastapi.md){.internal-link target=_blank}. - -## Desenvolvendo - -Se você já clonou o repositório e precisa mergulhar no código, aqui estão algumas orientações para configurar seu ambiente. - -### Ambiente virtual com `venv` - -Você pode criar um ambiente virtual em um diretório utilizando o módulo `venv` do Python: - -
- -```console -$ python -m venv env -``` - -
- -Isso criará o diretório `./env/` com os binários Python e então você será capaz de instalar pacotes nesse ambiente isolado. - -### Ativar o ambiente - -Ative o novo ambiente com: - -=== "Linux, macOS" - -
- - ```console - $ source ./env/bin/activate - ``` - -
- -=== "Windows PowerShell" - -
- - ```console - $ .\env\Scripts\Activate.ps1 - ``` - -
- -=== "Windows Bash" - - Ou se você usa Bash para Windows (por exemplo Git Bash): - -
- - ```console - $ source ./env/Scripts/activate - ``` - -
- -Para verificar se funcionou, use: - -=== "Linux, macOS, Windows Bash" - -
- - ```console - $ which pip - - some/directory/fastapi/env/bin/pip - ``` - -
- -=== "Windows PowerShell" - -
- - ```console - $ Get-Command pip - - some/directory/fastapi/env/bin/pip - ``` - -
- -Se ele exibir o binário `pip` em `env/bin/pip` então funcionou. 🎉 - - - -!!! tip - Toda vez que você instalar um novo pacote com `pip` nesse ambiente, ative o ambiente novamente. - - Isso garante que se você usar um programa instalado por aquele pacote, você utilizará aquele de seu ambiente local e não outro que possa estar instalado globalmente. - -### pip - -Após ativar o ambiente como descrito acima: - -
- -```console -$ pip install -r requirements.txt - ----> 100% -``` - -
- -Isso irá instalar todas as dependências e seu FastAPI local em seu ambiente local. - -#### Usando seu FastAPI local - -Se você cria um arquivo Python que importa e usa FastAPI, e roda com Python de seu ambiente local, ele irá utilizar o código fonte de seu FastAPI local. - -E se você atualizar o código fonte do FastAPI local, como ele é instalado com `-e`, quando você rodar aquele arquivo Python novamente, ele irá utilizar a nova versão do FastAPI que você acabou de editar. - -Desse modo, você não tem que "instalar" sua versão local para ser capaz de testar cada mudança. - -### Formato - -Tem um arquivo que você pode rodar que irá formatar e limpar todo o seu código: - -
- -```console -$ bash scripts/format.sh -``` - -
- -Ele irá organizar também todos os seus imports. - -Para que ele organize os imports corretamente, você precisa ter o FastAPI instalado localmente em seu ambiente, com o comando na seção acima usando `-e`. - -### Formato dos imports - -Tem outro _script_ que formata todos os imports e garante que você não tenha imports não utilizados: - -
- -```console -$ bash scripts/format-imports.sh -``` - -
- -Como ele roda um comando após o outro, modificando e revertendo muitos arquivos, ele demora um pouco para concluir, então pode ser um pouco mais fácil utilizar `scripts/format.sh` frequentemente e `scripts/format-imports.sh` somente após "commitar uma branch". - -## Documentação - -Primeiro, tenha certeza de configurar seu ambiente como descrito acima, isso irá instalar todas as requisições. - -A documentação usa MkDocs. - -E existem ferramentas/_scripts_ extras para controlar as traduções em `./scripts/docs.py`. - -!!! tip - Você não precisa ver o código em `./scripts/docs.py`, você apenas o utiliza na linha de comando. - -Toda a documentação está no formato Markdown no diretório `./docs/pt/`. - -Muitos dos tutoriais tem blocos de código. - -Na maioria dos casos, esse blocos de código são aplicações completas que podem ser rodadas do jeito que estão apresentados. - -De fato, esses blocos de código não estão escritos dentro do Markdown, eles são arquivos Python dentro do diretório `./docs_src/`. - -E esses arquivos Python são incluídos/injetados na documentação quando se gera o site. - -### Testes para Documentação - -A maioria dos testes na verdade rodam encima dos arquivos fonte na documentação. - -Isso ajuda a garantir: - -* Que a documentação esteja atualizada. -* Que os exemplos da documentação possam ser rodadas do jeito que estão apresentadas. -* A maior parte dos recursos é coberta pela documentação, garantida por cobertura de testes. - -Durante o desenvolvimento local, existe um _script_ que constrói o site e procura por quaisquer mudanças, carregando na hora: - -
- -```console -$ python ./scripts/docs.py live - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -Isso irá servir a documentação em `http://127.0.0.1:8008`. - -Desse jeito, você poderá editar a documentação/arquivos fonte e ver as mudanças na hora. - -#### Typer CLI (opcional) - -As instruções aqui mostram como utilizar _scripts_ em `./scripts/docs.py` com o programa `python` diretamente. - -Mas você pode usar também Typer CLI, e você terá auto-completação para comandos no seu terminal após instalar o _completion_. - -Se você instalou Typer CLI, você pode instalar _completion_ com: - -
- -```console -$ typer --install-completion - -zsh completion installed in /home/user/.bashrc. -Completion will take effect once you restart the terminal. -``` - -
- -### Aplicações e documentação ao mesmo tempo - -Se você rodar os exemplos com, por exemplo: - -
- -```console -$ uvicorn tutorial001:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -como Uvicorn utiliza por padrão a porta `8000`, a documentação na porta `8008` não dará conflito. - -### Traduções - -Ajuda com traduções É MUITO apreciada! E essa tarefa não pode ser concluída sem a ajuda da comunidade. 🌎 🚀 - -Aqui estão os passos para ajudar com as traduções. - -#### Dicas e orientações - -* Verifique sempre os _pull requests_ existentes para a sua linguagem e faça revisões das alterações e aprove elas. - -!!! tip - Você pode adicionar comentários com sugestões de alterações para _pull requests_ existentes. - - Verifique as documentações sobre adicionar revisão ao _pull request_ para aprovação ou solicitação de alterações. - -* Verifique em _issues_ para ver se existe alguém coordenando traduções para a sua linguagem. - -* Adicione um único _pull request_ por página traduzida. Isso tornará muito mais fácil a revisão para as outras pessoas. - -Para as linguagens que eu não falo, vou esperar por várias pessoas revisarem a tradução antes de _mergear_. - -* Você pode verificar também se há traduções para sua linguagem e adicionar revisão para elas, isso irá me ajudar a saber que a tradução está correta e eu possa _mergear_. - -* Utilize os mesmos exemplos Python e somente traduza o texto na documentação. Você não tem que alterar nada no código para que funcione. - -* Utilize as mesmas imagens, nomes de arquivo e links. Você não tem que alterar nada disso para que funcione. - -* Para verificar o código de duas letras para a linguagem que você quer traduzir, você pode usar a Lista de códigos ISO 639-1. - -#### Linguagem existente - -Vamos dizer que você queira traduzir uma página para uma linguagem que já tenha traduções para algumas páginas, como o Espanhol. - -No caso do Espanhol, o código de duas letras é `es`. Então, o diretório para traduções em Espanhol está localizada em `docs/es/`. - -!!! tip - A principal ("oficial") linguagem é o Inglês, localizado em `docs/en/`. - -Agora rode o _servidor ao vivo_ para as documentações em Espanhol: - -
- -```console -// Use o comando "live" e passe o código da linguagem como um argumento de linha de comando -$ python ./scripts/docs.py live es - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -Agora você pode ir em http://127.0.0.1:8008 e ver suas mudanças ao vivo. - -Se você procurar no site da documentação do FastAPI, você verá que toda linguagem tem todas as páginas. Mas algumas páginas não estão traduzidas e tem notificação sobre a falta da tradução. - -Mas quando você rodar localmente como descrito acima, você somente verá as páginas que já estão traduzidas. - -Agora vamos dizer que você queira adicionar uma tradução para a seção [Recursos](features.md){.internal-link target=_blank}. - -* Copie o arquivo em: - -``` -docs/en/docs/features.md -``` - -* Cole ele exatamente no mesmo local mas para a linguagem que você quer traduzir, por exemplo: - -``` -docs/es/docs/features.md -``` - -!!! tip - Observe que a única mudança na rota é o código da linguagem, de `en` para `es`. - -* Agora abra o arquivo de configuração MkDocs para Inglês em: - -``` -docs/en/docs/mkdocs.yml -``` - -* Procure o lugar onde `docs/features.md` está localizado no arquivo de configuração. Algum lugar como: - -```YAML hl_lines="8" -site_name: FastAPI -# Mais coisas -nav: -- FastAPI: index.md -- Languages: - - en: / - - es: /es/ -- features.md -``` - -* Abra o arquivo de configuração MkDocs para a linguagem que você está editando, por exemplo: - -``` -docs/es/docs/mkdocs.yml -``` - -* Adicione no mesmo local que está no arquivo em Inglês, por exemplo: - -```YAML hl_lines="8" -site_name: FastAPI -# Mais coisas -nav: -- FastAPI: index.md -- Languages: - - en: / - - es: /es/ -- features.md -``` - -Tenha certeza que se existem outras entradas, a nova entrada com sua tradução esteja exatamente na mesma ordem como na versão em Inglês. - -Se você for no seu navegador verá que agora a documentação mostra sua nova seção. 🎉 - -Agora você poderá traduzir tudo e ver como está toda vez que salva o arquivo. - -#### Nova linguagem - -Vamos dizer que você queira adicionar traduções para uma linguagem que ainda não foi traduzida, nem sequer uma página. - -Vamos dizer que você queira adicionar tradução para Haitiano, e ainda não tenha na documentação. - -Verificando o link acima, o código para "Haitiano" é `ht`. - -O próximo passo é rodar o _script_ para gerar um novo diretório de tradução: - -
- -```console -// Use o comando new-lang, passe o código da linguagem como um argumento de linha de comando -$ python ./scripts/docs.py new-lang ht - -Successfully initialized: docs/ht -Updating ht -Updating en -``` - -
- -Agora você pode verificar em seu editor de código o mais novo diretório criado `docs/ht/`. - -!!! tip - Crie um primeiro _pull request_ com apenas isso, para iniciar a configuração da nova linguagem, antes de adicionar traduções. - - Desse modo outros poderão ajudar com outras páginas enquanto você trabalha na primeira. 🚀 - -Inicie traduzindo a página principal, `docs/ht/index.md`. - -Então você pode continuar com as instruções anteriores, para uma "Linguagem Existente". - -##### Nova linguagem não suportada - -Se quando rodar o _script_ do _servidor ao vivo_ você pega um erro sobre linguagem não suportada, alguma coisa como: - -``` - raise TemplateNotFound(template) -jinja2.exceptions.TemplateNotFound: partials/language/xx.html -``` - -Isso significa que o tema não suporta essa linguagem (nesse caso, com um código falso de duas letras `xx`). - -Mas não se preocupe, você pode configurar o tema de linguagem para Inglês e então traduzir o conteúdo da documentação. - -Se você precisar fazer isso, edite o `mkdocs.yml` para sua nova linguagem, teremos algo como: - -```YAML hl_lines="5" -site_name: FastAPI -# Mais coisas -theme: - # Mais coisas - language: xx -``` - -Altere essa linguagem de `xx` (do seu código de linguagem) para `en`. - -Então você poderá iniciar novamente o _servidor ao vivo_. - -#### Pré-visualize o resultado - -Quando você usa o _script_ em `./scripts/docs.py` com o comando `live` ele somente exibe os arquivos e traduções disponíveis para a linguagem atual. - -Mas uma vez que você tenha concluído, você poderá testar tudo como se parecesse _online_. - -Para fazer isso, primeiro construa toda a documentação: - -
- -```console -// Use o comando "build-all", isso leverá um tempinho -$ python ./scripts/docs.py build-all - -Updating es -Updating en -Building docs for: en -Building docs for: es -Successfully built docs for: es -Copying en index.md to README.md -``` - -
- -Isso gera toda a documentação em `./docs_build/` para cada linguagem. Isso inclui a adição de quaisquer arquivos com tradução faltando, com uma nota dizendo que "esse arquivo ainda não tem tradução". Mas você não tem que fazer nada com esse diretório. - -Então ele constrói todos aqueles _sites_ independentes MkDocs para cada linguagem, combina eles, e gera a saída final em `./site/`. - -Então você poderá "servir" eles com o comando `serve`: - -
- -```console -// Use o comando "serve" após rodar "build-all" -$ python ./scripts/docs.py serve - -Warning: this is a very simple server. For development, use mkdocs serve instead. -This is here only to preview a site with translations already built. -Make sure you run the build-all command first. -Serving at: http://127.0.0.1:8008 -``` - -
- -## Testes - -Tem um _script_ que você pode rodar localmente para testar todo o código e gerar relatórios de cobertura em HTML: - -
- -```console -$ bash scripts/test-cov-html.sh -``` - -
- -Esse comando gera um diretório `./htmlcov/`, se você abrir o arquivo `./htmlcov/index.html` no seu navegador, poderá explorar interativamente as regiões de código que estão cobertas pelos testes, e observar se existe alguma região faltando. - -### Testes no seu editor - -Se você quer usar os testes integrados em seu editor adicione `./docs_src` na sua variável `PYTHONPATH`. - -Por exemplo, no VS Code você pode criar um arquivo `.env` com: - -```env -PYTHONPATH=./docs_src -``` diff --git a/docs/pt/docs/deployment.md b/docs/pt/docs/deployment.md deleted file mode 100644 index 2272467fd..000000000 --- a/docs/pt/docs/deployment.md +++ /dev/null @@ -1,394 +0,0 @@ -# Implantação - -Implantar uma aplicação **FastAPI** é relativamente fácil. - -Existem vários modos de realizar o _deploy_ dependendo de seu caso de uso específico e as ferramentas que você utiliza. - -Você verá mais sobre alguns modos de fazer o _deploy_ nas próximas seções. - -## Versões do FastAPI - -**FastAPI** já está sendo utilizado em produção em muitas aplicações e sistemas. E a cobertura de teste é mantida a 100%. Mas seu desenvolvimento continua andando rapidamente. - -Novos recursos são adicionados frequentemente, _bugs_ são corrigidos regularmente, e o código está continuamente melhorando. - -É por isso que as versões atuais estão ainda no `0.x.x`, isso reflete que cada versão poderia ter potencialmente alterações que podem quebrar. Isso segue as convenções de Versionamento Semântico. - -Você pode criar aplicações para produção com **FastAPI** bem agora (e você provavelmente já faça isso por um tempo), você tem que ter certeza de utilizar uma versão que funcione corretamente com o resto do seu código. - -### Anote sua versão `fastapi` - -A primeira coisa que você deve fazer é "fixar" a versão do **FastAPI** que está utilizando para a última versão específica que você sabe que funciona corretamente para a sua aplicação. - -Por exemplo, vamos dizer que você esteja utilizando a versão `0.45.0` no seu _app_. - -Se você usa um arquivo `requirements.txt`, dá para especificar a versão assim: - -```txt -fastapi==0.45.0 -``` - -isso significa que você pode usar exatamente a versão `0.45.0`. - -Ou você poderia fixar assim: - -```txt -fastapi>=0.45.0,<0.46.0 -``` - -o que significa que você pode usar as versões `0.45.0` ou acima, mas menor que `0.46.0`. Por exemplo, a versão `0.45.2` poderia ser aceita. - -Se você usa qualquer outra ferramenta para gerenciar suas instalações, como Poetry, Pipenv ou outro, todos terão um modo que você possa usar para definir versões específicas para seus pacotes. - -### Versões disponíveis - -Você pode ver as versões disponíveis (por exemplo, para verificar qual é a versão atual) nas [Notas de Lançamento](release-notes.md){.internal-link target=_blank}. - -### Sobre as versões - -Seguindo as convenções do Versionamento Semântico, qualquer versão abaixo de `1.0.0` pode potencialmente adicionar mudanças que quebrem. - -FastAPI também segue a convenção que qualquer versão de _"PATCH"_ seja para ajustes de _bugs_ e mudanças que não quebrem a aplicação. - -!!! tip - O _"PATCH"_ é o último número, por exemplo, em `0.2.3`, a versão do _PATCH_ é `3`. - -Então, você poderia ser capaz de fixar para uma versão como: - -```txt -fastapi>=0.45.0,<0.46.0 -``` - -Mudanças que quebram e novos recursos são adicionados em versões _"MINOR"_. - -!!! tip - O _"MINOR"_ é o número do meio, por exemplo, em `0.2.3`, a versão _MINOR_ é `2`. - -### Atualizando as versões FastAPI - -Você pode adicionar testes em sua aplicação. - -Com o **FastAPI** é muito fácil (graças ao Starlette), verifique a documentação: [Testando](tutorial/testing.md){.internal-link target=_blank} - -Após você ter os testes, então você pode fazer o _upgrade_ da versão **FastAPI** para uma mais recente, e ter certeza que todo seu código esteja funcionando corretamente rodando seus testes. - -Se tudo estiver funcionando, ou após você fazer as alterações necessárias, e todos seus testes estiverem passando, então você poderá fixar o `fastapi` para a versão mais recente. - -### Sobre Starlette - -Você não deve fixar a versão do `starlette`. - -Versões diferentes do **FastAPI** irão utilizar uma versão mais nova específica do Starlette. - -Então, você pode deixar que o **FastAPI** use a versão correta do Starlette. - -### Sobre Pydantic - -Pydantic inclui os testes para **FastAPI** em seus próprios testes, então novas versões do Pydantic (acima de `1.0.0`) são sempre compatíveis com FastAPI. - -Você pode fixar o Pydantic para qualquer versão acima de `1.0.0` e abaixo de `2.0.0` que funcionará. - -Por exemplo: - -```txt -pydantic>=1.2.0,<2.0.0 -``` - -## Docker - -Nessa seção você verá instruções e _links_ para guias de saber como: - -* Fazer uma imagem/container da sua aplicação **FastAPI** com máxima performance. Em aproximadamente **5 min**. -* (Opcionalmente) entender o que você, como desenvolvedor, precisa saber sobre HTTPS. -* Inicializar um _cluster_ Docker Swarm Mode com HTTPS automático, mesmo em um simples servidor de $5 dólares/mês. Em aproximadamente **20 min**. -* Gere e implante uma aplicação **FastAPI** completa, usando seu _cluster_ Docker Swarm, com HTTPS etc. Em aproxiamadamente **10 min**. - -Você pode usar **Docker** para implantação. Ele tem várias vantagens como segurança, replicabilidade, desenvolvimento simplificado etc. - -Se você está usando Docker, você pode utilizar a imagem Docker oficial: - -### tiangolo/uvicorn-gunicorn-fastapi - -Essa imagem tem um mecanismo incluído de "auto-ajuste", para que você possa apenas adicionar seu código e ter uma alta performance automaticamente. E sem fazer sacrifícios. - -Mas você pode ainda mudar e atualizar todas as configurações com variáveis de ambiente ou arquivos de configuração. - -!!! tip - Para ver todas as configurações e opções, vá para a página da imagem do Docker: tiangolo/uvicorn-gunicorn-fastapi. - -### Crie um `Dockerfile` - -* Vá para o diretório de seu projeto. -* Crie um `Dockerfile` com: - -```Dockerfile -FROM tiangolo/uvicorn-gunicorn-fastapi:python3.7 - -COPY ./app /app -``` - -#### Grandes aplicações - -Se você seguiu a seção sobre criação de [Grandes Aplicações com Múltiplos Arquivos](tutorial/bigger-applications.md){.internal-link target=_blank}, seu `Dockerfile` poderia parecer como: - -```Dockerfile -FROM tiangolo/uvicorn-gunicorn-fastapi:python3.7 - -COPY ./app /app/app -``` - -#### Raspberry Pi e outras arquiteturas - -Se você estiver rodando Docker em um Raspberry Pi (que possui um processador ARM) ou qualquer outra arquitetura, você pode criar um `Dockerfile` do zero, baseado em uma imagem base Python (que é multi-arquitetural) e utilizar Uvicorn sozinho. - -Nesse caso, seu `Dockerfile` poderia parecer assim: - -```Dockerfile -FROM python:3.7 - -RUN pip install fastapi uvicorn - -EXPOSE 80 - -COPY ./app /app - -CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] -``` - -### Crie o código **FastAPI** - -* Crie um diretório `app` e entre nele. -* Crie um arquivo `main.py` com: - -```Python -from fastapi import FastAPI - -app = FastAPI() - - -@app.get("/") -def read_root(): - return {"Hello": "World"} - - -@app.get("/items/{item_id}") -def read_item(item_id: int, q: str = None): - return {"item_id": item_id, "q": q} -``` - -* Você deve ter uma estrutura de diretórios assim: - -``` -. -├── app -│ └── main.py -└── Dockerfile -``` - -### Construa a imagem Docker - -* Vá para o diretório do projeto (onde seu `Dockerfile` está, contendo seu diretório `app`. -* Construa sua imagem FastAPI: - -
- -```console -$ docker build -t myimage . - ----> 100% -``` - -
- -### Inicie o container Docker - -* Rode um container baseado em sua imagem: - -
- -```console -$ docker run -d --name mycontainer -p 80:80 myimage -``` - -
- -Agora você tem um servidor FastAPI otimizado em um container Docker. Auto-ajustado para seu servidor atual (e número de núcleos de CPU). - -### Verifique - -Você deve ser capaz de verificar na URL de seu container Docker, por exemplo: http://192.168.99.100/items/5?q=somequery ou http://127.0.0.1/items/5?q=somequery (ou equivalente, usando seu _host_ Docker). - -Você verá algo como: - -```JSON -{"item_id": 5, "q": "somequery"} -``` - -### API interativa de documetação - -Agora você pode ir para http://192.168.99.100/docs ou http://127.0.0.1/docs (ou equivalente, usando seu _host_ Docker). - -Você verá a API interativa de documentação (fornecida por Swagger UI): - -![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) - -### APIs alternativas de documentação - -E você pode também ir para http://192.168.99.100/redoc ou http://127.0.0.1/redoc (ou equivalente, usando seu _host_ Docker). - -Você verá a documentação automática alternativa (fornecida por ReDoc): - -![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) - -## HTTPS - -### Sobre HTTPS - -É fácil assumir que HTTPS seja algo que esteja apenas "habilitado" ou não. - -Mas ele é um pouquinho mais complexo do que isso. - -!!! tip - Se você está com pressa ou não se importa, continue na próxima seção com instruções passo a passo para configurar tudo. - -Para aprender o básico de HTTPS, pela perspectiva de um consumidor, verifique https://howhttps.works/. - -Agora, pela perspectiva de um desenvolvedor, aqui estão algumas coisas para se ter em mente enquanto se pensa sobre HTTPS: - -* Para HTTPS, o servidor precisa ter "certificados" gerados por terceiros. - * Esses certificados são na verdade adquiridos por terceiros, não "gerados". -* Certificados tem um prazo de uso. - * Eles expiram. - * E então eles precisam ser renovados, adquiridos novamente por terceiros. -* A encriptação da conexão acontece no nível TCP. - * TCP é uma camada abaixo do HTTP. - * Então, o controle de certificado e encriptação é feito antes do HTTP. -* TCP não conhece nada sobre "domínios". Somente sobre endereços IP. - * A informação sobre o domínio requisitado vai nos dados HTTP. -* Os certificados HTTPS "certificam" um certo domínio, mas o protocolo e a encriptação acontecem no nível TCP, antes de saber qual domínio está sendo lidado. -* Por padrão, isso significa que você pode ter somente um certificado HTTPS por endereço IP. - * Não importa quão grande é seu servidor ou quão pequena cada aplicação que você tenha possar ser. - * No entanto, existe uma solução para isso. -* Existe uma extensão para o protocolo TLS (o que controla a encriptação no nível TCP, antes do HTTP) chamada SNI. - * Essa extensão SNI permite um único servidor (com um único endereço IP) a ter vários certificados HTTPS e servir múltiplas aplicações/domínios HTTPS. - * Para que isso funcione, um único componente (programa) rodando no servidor, ouvindo no endereço IP público, deve ter todos os certificados HTTPS no servidor. -* Após obter uma conexão segura, o protocolo de comunicação ainda é HTTP. - * O conteúdo está encriptado, mesmo embora ele esteja sendo enviado com o protocolo HTTP. - -É uma prática comum ter um servidor HTTP/programa rodando no servidor (a máquina, _host_ etc.) e gerenciar todas as partes HTTP: enviar as requisições HTTP decriptadas para a aplicação HTTP rodando no mesmo servidor (a aplicação **FastAPI**, nesse caso), pega a resposta HTTP da aplicação, encripta utilizando o certificado apropriado e enviando de volta para o cliente usando HTTPS. Esse servidor é frequentemente chamado TLS _Termination Proxy_. - -### Vamos encriptar - -Antes de encriptar, esses certificados HTTPS foram vendidos por terceiros de confiança. - -O processo para adquirir um desses certificados costumava ser chato, exigia muita papelada e eram bem caros. - -Mas então _Let's Encrypt_ foi criado. - -É um projeto da Fundação Linux.Ele fornece certificados HTTPS de graça. De um jeito automatizado. Esses certificados utilizam todos os padrões de segurança criptográfica, e tem vida curta (cerca de 3 meses), para que a segurança seja melhor devido ao seu curto período de vida. - -Os domínios são seguramente verificados e os certificados são gerados automaticamente. Isso também permite automatizar a renovação desses certificados. - -A idéia é automatizar a aquisição e renovação desses certificados, para que você possa ter um HTTPS seguro, grátis, para sempre. - -### Traefik - -Traefik é um _proxy_ reverso / _load balancer_ de alta performance. Ele pode fazer o trabalho do _"TLS Termination Proxy"_ (à parte de outros recursos). - -Ele tem integração com _Let's Encrypt_. Assim, ele pode controlar todas as partes HTTPS, incluindo a aquisição e renovação de certificados. - -Ele também tem integrações com Docker. Assim, você pode declarar seus domínios em cada configuração de aplicação e leitura dessas configurações, gerando os certificados HTTPS e servindo o HTTPS para sua aplicação automaticamente, sem exigir qualquer mudança em sua configuração. - ---- - -Com essas ferramentas e informações, continue com a próxima seção para combinar tudo. - -## _Cluster_ de Docker Swarm Mode com Traefik e HTTPS - -Você pode ter um _cluster_ de Docker Swarm Mode configurado em minutos (cerca de 20) com o Traefik controlando HTTPS (incluindo aquisição e renovação de certificados). - -Utilizando o Docker Swarm Mode, você pode iniciar com um _"cluster"_ de apenas uma máquina (que pode até ser um servidor por 5 dólares / mês) e então você pode aumentar conforme a necessidade adicionando mais servidores. - -Para configurar um _cluster_ Docker Swarm Mode com Traefik controlando HTTPS, siga essa orientação: - -### Docker Swarm Mode and Traefik for an HTTPS cluster - -### Faça o _deploy_ de uma aplicação FastAPI - -O jeito mais fácil de configurar tudo pode ser utilizando o [Gerador de Projetos **FastAPI**](project-generation.md){.internal-link target=_blank}. - -Ele é designado para ser integrado com esse _cluster_ Docker Swarm com Traefik e HTTPS descrito acima. - -Você pode gerar um projeto em cerca de 2 minutos. - -O projeto gerado tem instruções para fazer o _deploy_, fazendo isso leva outros 2 minutos. - -## Alternativamente, faça o _deploy_ **FastAPI** sem Docker - -Você pode fazer o _deploy_ do **FastAPI** diretamente sem o Docker também. - -Você apenas precisa instalar um servidor ASGI compatível como: - -=== "Uvicorn" - - * Uvicorn, um servidor ASGI peso leve, construído sobre uvloop e httptools. - -
- - ```console - $ pip install "uvicorn[standard]" - - ---> 100% - ``` - -
- -=== "Hypercorn" - - * Hypercorn, um servidor ASGI também compatível com HTTP/2. - -
- - ```console - $ pip install hypercorn - - ---> 100% - ``` - -
- - ...ou qualquer outro servidor ASGI. - -E rode sua applicação do mesmo modo que você tem feito nos tutoriais, mas sem a opção `--reload`, por exemplo: - -=== "Uvicorn" - -
- - ```console - $ uvicorn main:app --host 0.0.0.0 --port 80 - - INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) - ``` - -
- -=== "Hypercorn" - -
- - ```console - $ hypercorn main:app --bind 0.0.0.0:80 - - Running on 0.0.0.0:8080 over http (CTRL + C to quit) - ``` - -
- -Você deve querer configurar mais algumas ferramentas para ter certeza que ele seja reinicializado automaticamante se ele parar. - -Você também deve querer instalar Gunicorn e utilizar ele como um gerenciador para o Uvicorn, ou usar Hypercorn com múltiplos _workers_. - -Tenha certeza de ajustar o número de _workers_ etc. - -Mas se você estiver fazendo tudo isso, você pode apenas usar uma imagem Docker que fará isso automaticamente. diff --git a/docs/pt/docs/deployment/cloud.md b/docs/pt/docs/deployment/cloud.md new file mode 100644 index 000000000..e6522f50f --- /dev/null +++ b/docs/pt/docs/deployment/cloud.md @@ -0,0 +1,17 @@ +# Implantar FastAPI em provedores de nuvem + +Você pode usar praticamente **qualquer provedor de nuvem** para implantar seu aplicativo FastAPI. + +Na maioria dos casos, os principais provedores de nuvem têm guias para implantar o FastAPI com eles. + +## Provedores de Nuvem - Patrocinadores + +Alguns provedores de nuvem ✨ [**patrocinam o FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, o que garante o **desenvolvimento** contínuo e saudável do FastAPI e seu **ecossistema**. + +E isso mostra seu verdadeiro comprometimento com o FastAPI e sua **comunidade** (você), pois eles não querem apenas fornecer a você um **bom serviço**, mas também querem ter certeza de que você tenha uma **estrutura boa e saudável**, o FastAPI. 🙇 + +Talvez você queira experimentar os serviços deles e seguir os guias: + +* Platform.sh +* Porter +* Coherence diff --git a/docs/pt/docs/deployment/concepts.md b/docs/pt/docs/deployment/concepts.md new file mode 100644 index 000000000..8cf70d0b4 --- /dev/null +++ b/docs/pt/docs/deployment/concepts.md @@ -0,0 +1,321 @@ +# Conceitos de Implantações + +Ao implantar um aplicativo **FastAPI**, ou na verdade, qualquer tipo de API da web, há vários conceitos com os quais você provavelmente se importa e, usando-os, você pode encontrar a maneira **mais apropriada** de **implantar seu aplicativo**. + +Alguns dos conceitos importantes são: + +* Segurança - HTTPS +* Executando na inicialização +* Reinicializações +* Replicação (o número de processos em execução) +* Memória +* Etapas anteriores antes de iniciar + +Veremos como eles afetariam as **implantações**. + +No final, o principal objetivo é ser capaz de **atender seus clientes de API** de uma forma **segura**, **evitar interrupções** e usar os **recursos de computação** (por exemplo, servidores remotos/máquinas virtuais) da forma mais eficiente possível. 🚀 + +Vou lhe contar um pouco mais sobre esses **conceitos** aqui, e espero que isso lhe dê a **intuição** necessária para decidir como implantar sua API em ambientes muito diferentes, possivelmente até mesmo em **futuros** ambientes que ainda não existem. + +Ao considerar esses conceitos, você será capaz de **avaliar e projetar** a melhor maneira de implantar **suas próprias APIs**. + +Nos próximos capítulos, darei a você mais **receitas concretas** para implantar aplicativos FastAPI. + +Mas por enquanto, vamos verificar essas importantes **ideias conceituais**. Esses conceitos também se aplicam a qualquer outro tipo de API da web. 💡 + +## Segurança - HTTPS + +No [capítulo anterior sobre HTTPS](https.md){.internal-link target=_blank} aprendemos como o HTTPS fornece criptografia para sua API. + +Também vimos que o HTTPS normalmente é fornecido por um componente **externo** ao seu servidor de aplicativos, um **Proxy de terminação TLS**. + +E tem que haver algo responsável por **renovar os certificados HTTPS**, pode ser o mesmo componente ou pode ser algo diferente. + +### Ferramentas de exemplo para HTTPS + +Algumas das ferramentas que você pode usar como um proxy de terminação TLS são: + +* Traefik + * Lida automaticamente com renovações de certificados ✨ +* Caddy + * Lida automaticamente com renovações de certificados ✨ +* Nginx + * Com um componente externo como o Certbot para renovações de certificados +* HAProxy + * Com um componente externo como o Certbot para renovações de certificados +* Kubernetes com um controlador Ingress como o Nginx + * Com um componente externo como cert-manager para renovações de certificados +* Gerenciado internamente por um provedor de nuvem como parte de seus serviços (leia abaixo 👇) + +Outra opção é que você poderia usar um **serviço de nuvem** que faz mais do trabalho, incluindo a configuração de HTTPS. Ele pode ter algumas restrições ou cobrar mais, etc. Mas, nesse caso, você não teria que configurar um Proxy de terminação TLS sozinho. + +Mostrarei alguns exemplos concretos nos próximos capítulos. + +--- + +Os próximos conceitos a serem considerados são todos sobre o programa que executa sua API real (por exemplo, Uvicorn). + +## Programa e Processo + +Falaremos muito sobre o "**processo**" em execução, então é útil ter clareza sobre o que ele significa e qual é a diferença com a palavra "**programa**". + +### O que é um Programa + +A palavra **programa** é comumente usada para descrever muitas coisas: + +* O **código** que você escreve, os **arquivos Python**. +* O **arquivo** que pode ser **executado** pelo sistema operacional, por exemplo: `python`, `python.exe` ou `uvicorn`. +* Um programa específico enquanto está **em execução** no sistema operacional, usando a CPU e armazenando coisas na memória. Isso também é chamado de **processo**. + +### O que é um Processo + +A palavra **processo** normalmente é usada de forma mais específica, referindo-se apenas ao que está sendo executado no sistema operacional (como no último ponto acima): + +* Um programa específico enquanto está **em execução** no sistema operacional. + * Isso não se refere ao arquivo, nem ao código, refere-se **especificamente** à coisa que está sendo **executada** e gerenciada pelo sistema operacional. +* Qualquer programa, qualquer código, **só pode fazer coisas** quando está sendo **executado**. Então, quando há um **processo em execução**. +* O processo pode ser **terminado** (ou "morto") por você, ou pelo sistema operacional. Nesse ponto, ele para de rodar/ser executado, e ele **não pode mais fazer coisas**. +* Cada aplicativo que você tem em execução no seu computador tem algum processo por trás dele, cada programa em execução, cada janela, etc. E normalmente há muitos processos em execução **ao mesmo tempo** enquanto um computador está ligado. +* Pode haver **vários processos** do **mesmo programa** em execução ao mesmo tempo. + +Se você verificar o "gerenciador de tarefas" ou o "monitor do sistema" (ou ferramentas semelhantes) no seu sistema operacional, poderá ver muitos desses processos em execução. + +E, por exemplo, você provavelmente verá que há vários processos executando o mesmo programa de navegador (Firefox, Chrome, Edge, etc.). Eles normalmente executam um processo por aba, além de alguns outros processos extras. + + + +--- + +Agora que sabemos a diferença entre os termos **processo** e **programa**, vamos continuar falando sobre implantações. + +## Executando na inicialização + +Na maioria dos casos, quando você cria uma API web, você quer que ela esteja **sempre em execução**, ininterrupta, para que seus clientes possam sempre acessá-la. Isso é claro, a menos que você tenha um motivo específico para querer que ela seja executada somente em certas situações, mas na maioria das vezes você quer que ela esteja constantemente em execução e **disponível**. + +### Em um servidor remoto + +Ao configurar um servidor remoto (um servidor em nuvem, uma máquina virtual, etc.), a coisa mais simples que você pode fazer é usar `fastapi run` (que usa Uvicorn) ou algo semelhante, manualmente, da mesma forma que você faz ao desenvolver localmente. + +E funcionará e será útil **durante o desenvolvimento**. + +Mas se sua conexão com o servidor for perdida, o **processo em execução** provavelmente morrerá. + +E se o servidor for reiniciado (por exemplo, após atualizações ou migrações do provedor de nuvem), você provavelmente **não notará**. E por causa disso, você nem saberá que precisa reiniciar o processo manualmente. Então, sua API simplesmente permanecerá inativa. 😱 + +### Executar automaticamente na inicialização + +Em geral, você provavelmente desejará que o programa do servidor (por exemplo, Uvicorn) seja iniciado automaticamente na inicialização do servidor e, sem precisar de nenhuma **intervenção humana**, tenha um processo sempre em execução com sua API (por exemplo, Uvicorn executando seu aplicativo FastAPI). + +### Programa separado + +Para conseguir isso, você normalmente terá um **programa separado** que garantiria que seu aplicativo fosse executado na inicialização. E em muitos casos, ele também garantiria que outros componentes ou aplicativos também fossem executados, por exemplo, um banco de dados. + +### Ferramentas de exemplo para executar na inicialização + +Alguns exemplos de ferramentas que podem fazer esse trabalho são: + +* Docker +* Kubernetes +* Docker Compose +* Docker em Modo Swarm +* Systemd +* Supervisor +* Gerenciado internamente por um provedor de nuvem como parte de seus serviços +* Outros... + +Darei exemplos mais concretos nos próximos capítulos. + +## Reinicializações + +Semelhante a garantir que seu aplicativo seja executado na inicialização, você provavelmente também deseja garantir que ele seja **reiniciado** após falhas. + +### Nós cometemos erros + +Nós, como humanos, cometemos **erros** o tempo todo. O software quase *sempre* tem **bugs** escondidos em lugares diferentes. 🐛 + +E nós, como desenvolvedores, continuamos aprimorando o código à medida que encontramos esses bugs e implementamos novos recursos (possivelmente adicionando novos bugs também 😅). + +### Pequenos erros são tratados automaticamente + +Ao criar APIs da web com FastAPI, se houver um erro em nosso código, o FastAPI normalmente o conterá na única solicitação que acionou o erro. 🛡 + +O cliente receberá um **Erro Interno do Servidor 500** para essa solicitação, mas o aplicativo continuará funcionando para as próximas solicitações em vez de travar completamente. + +### Erros maiores - Travamentos + +No entanto, pode haver casos em que escrevemos algum código que **trava todo o aplicativo**, fazendo com que o Uvicorn e o Python travem. 💥 + +E ainda assim, você provavelmente não gostaria que o aplicativo permanecesse inativo porque houve um erro em um lugar, você provavelmente quer que ele **continue em execução** pelo menos para as *operações de caminho* que não estão quebradas. + +### Reiniciar após falha + +Mas nos casos com erros realmente graves que travam o **processo** em execução, você vai querer um componente externo que seja responsável por **reiniciar** o processo, pelo menos algumas vezes... + +/// tip | Dica + +...Embora se o aplicativo inteiro estiver **travando imediatamente**, provavelmente não faça sentido reiniciá-lo para sempre. Mas nesses casos, você provavelmente notará isso durante o desenvolvimento, ou pelo menos logo após a implantação. + +Então, vamos nos concentrar nos casos principais, onde ele pode travar completamente em alguns casos específicos **no futuro**, e ainda faz sentido reiniciá-lo. + +/// + +Você provavelmente gostaria de ter a coisa responsável por reiniciar seu aplicativo como um **componente externo**, porque a essa altura, o mesmo aplicativo com Uvicorn e Python já havia travado, então não há nada no mesmo código do mesmo aplicativo que possa fazer algo a respeito. + +### Ferramentas de exemplo para reiniciar automaticamente + +Na maioria dos casos, a mesma ferramenta usada para **executar o programa na inicialização** também é usada para lidar com **reinicializações** automáticas. + +Por exemplo, isso poderia ser resolvido por: + +* Docker +* Kubernetes +* Docker Compose +* Docker no Modo Swarm +* Systemd +* Supervisor +* Gerenciado internamente por um provedor de nuvem como parte de seus serviços +* Outros... + +## Replicação - Processos e Memória + +Com um aplicativo FastAPI, usando um programa de servidor como o comando `fastapi` que executa o Uvicorn, executá-lo uma vez em **um processo** pode atender a vários clientes simultaneamente. + +Mas em muitos casos, você desejará executar vários processos de trabalho ao mesmo tempo. + +### Processos Múltiplos - Trabalhadores + +Se você tiver mais clientes do que um único processo pode manipular (por exemplo, se a máquina virtual não for muito grande) e tiver **vários núcleos** na CPU do servidor, você poderá ter **vários processos** em execução com o mesmo aplicativo ao mesmo tempo e distribuir todas as solicitações entre eles. + +Quando você executa **vários processos** do mesmo programa de API, eles são comumente chamados de **trabalhadores**. + +### Processos do Trabalhador e Portas + +Lembra da documentação [Sobre HTTPS](https.md){.internal-link target=_blank} que diz que apenas um processo pode escutar em uma combinação de porta e endereço IP em um servidor? + +Isso ainda é verdade. + +Então, para poder ter **vários processos** ao mesmo tempo, tem que haver um **único processo escutando em uma porta** que então transmite a comunicação para cada processo de trabalho de alguma forma. + +### Memória por Processo + +Agora, quando o programa carrega coisas na memória, por exemplo, um modelo de aprendizado de máquina em uma variável, ou o conteúdo de um arquivo grande em uma variável, tudo isso **consome um pouco da memória (RAM)** do servidor. + +E vários processos normalmente **não compartilham nenhuma memória**. Isso significa que cada processo em execução tem suas próprias coisas, variáveis ​​e memória. E se você estiver consumindo uma grande quantidade de memória em seu código, **cada processo** consumirá uma quantidade equivalente de memória. + +### Memória do servidor + +Por exemplo, se seu código carrega um modelo de Machine Learning com **1 GB de tamanho**, quando você executa um processo com sua API, ele consumirá pelo menos 1 GB de RAM. E se você iniciar **4 processos** (4 trabalhadores), cada um consumirá 1 GB de RAM. Então, no total, sua API consumirá **4 GB de RAM**. + +E se o seu servidor remoto ou máquina virtual tiver apenas 3 GB de RAM, tentar carregar mais de 4 GB de RAM causará problemas. 🚨 + +### Processos Múltiplos - Um Exemplo + +Neste exemplo, há um **Processo Gerenciador** que inicia e controla dois **Processos de Trabalhadores**. + +Este Processo de Gerenciador provavelmente seria o que escutaria na **porta** no IP. E ele transmitiria toda a comunicação para os processos de trabalho. + +Esses processos de trabalho seriam aqueles que executariam seu aplicativo, eles executariam os cálculos principais para receber uma **solicitação** e retornar uma **resposta**, e carregariam qualquer coisa que você colocasse em variáveis ​​na RAM. + + + +E, claro, a mesma máquina provavelmente teria **outros processos** em execução, além do seu aplicativo. + +Um detalhe interessante é que a porcentagem da **CPU usada** por cada processo pode **variar** muito ao longo do tempo, mas a **memória (RAM)** normalmente fica mais ou menos **estável**. + +Se você tiver uma API que faz uma quantidade comparável de cálculos todas as vezes e tiver muitos clientes, então a **utilização da CPU** provavelmente *também será estável* (em vez de ficar constantemente subindo e descendo rapidamente). + +### Exemplos de ferramentas e estratégias de replicação + +Pode haver várias abordagens para conseguir isso, e falarei mais sobre estratégias específicas nos próximos capítulos, por exemplo, ao falar sobre Docker e contêineres. + +A principal restrição a ser considerada é que tem que haver um **único** componente manipulando a **porta** no **IP público**. E então tem que ter uma maneira de **transmitir** a comunicação para os **processos/trabalhadores** replicados. + +Aqui estão algumas combinações e estratégias possíveis: + +* **Uvicorn** com `--workers` + * Um **gerenciador de processos** Uvicorn escutaria no **IP** e na **porta** e iniciaria **vários processos de trabalho Uvicorn**. +* **Kubernetes** e outros **sistemas de contêineres** distribuídos + * Algo na camada **Kubernetes** escutaria no **IP** e na **porta**. A replicação seria por ter **vários contêineres**, cada um com **um processo Uvicorn** em execução. +* **Serviços de nuvem** que cuidam disso para você + * O serviço de nuvem provavelmente **cuidará da replicação para você**. Ele possivelmente deixaria você definir **um processo para executar**, ou uma **imagem de contêiner** para usar, em qualquer caso, provavelmente seria **um único processo Uvicorn**, e o serviço de nuvem seria responsável por replicá-lo. + +/// tip | Dica + +Não se preocupe se alguns desses itens sobre **contêineres**, Docker ou Kubernetes ainda não fizerem muito sentido. + +Falarei mais sobre imagens de contêiner, Docker, Kubernetes, etc. em um capítulo futuro: [FastAPI em contêineres - Docker](docker.md){.internal-link target=_blank}. + +/// + +## Etapas anteriores antes de começar + +Há muitos casos em que você deseja executar algumas etapas **antes de iniciar** sua aplicação. + +Por exemplo, você pode querer executar **migrações de banco de dados**. + +Mas na maioria dos casos, você precisará executar essas etapas apenas **uma vez**. + +Portanto, você vai querer ter um **processo único** para executar essas **etapas anteriores** antes de iniciar o aplicativo. + +E você terá que se certificar de que é um único processo executando essas etapas anteriores *mesmo* se depois, você iniciar **vários processos** (vários trabalhadores) para o próprio aplicativo. Se essas etapas fossem executadas por **vários processos**, eles **duplicariam** o trabalho executando-o em **paralelo**, e se as etapas fossem algo delicado como uma migração de banco de dados, elas poderiam causar conflitos entre si. + +Claro, há alguns casos em que não há problema em executar as etapas anteriores várias vezes; nesse caso, é muito mais fácil de lidar. + +/// tip | Dica + +Além disso, tenha em mente que, dependendo da sua configuração, em alguns casos você **pode nem precisar de nenhuma etapa anterior** antes de iniciar sua aplicação. + +Nesse caso, você não precisaria se preocupar com nada disso. 🤷 + +/// + +### Exemplos de estratégias de etapas anteriores + +Isso **dependerá muito** da maneira como você **implanta seu sistema** e provavelmente estará conectado à maneira como você inicia programas, lida com reinicializações, etc. + +Aqui estão algumas ideias possíveis: + +* Um "Init Container" no Kubernetes que roda antes do seu app container +* Um script bash que roda os passos anteriores e então inicia seu aplicativo + * Você ainda precisaria de uma maneira de iniciar/reiniciar *aquele* script bash, detectar erros, etc. + +/// tip | Dica + +Darei exemplos mais concretos de como fazer isso com contêineres em um capítulo futuro: [FastAPI em contêineres - Docker](docker.md){.internal-link target=_blank}. + +/// + +## Utilização de recursos + +Seu(s) servidor(es) é(são) um **recurso** que você pode consumir ou **utilizar**, com seus programas, o tempo de computação nas CPUs e a memória RAM disponível. + +Quanto dos recursos do sistema você quer consumir/utilizar? Pode ser fácil pensar "não muito", mas, na realidade, você provavelmente vai querer consumir **o máximo possível sem travar**. + +Se você está pagando por 3 servidores, mas está usando apenas um pouco de RAM e CPU, você provavelmente está **desperdiçando dinheiro** 💸, e provavelmente **desperdiçando energia elétrica do servidor** 🌎, etc. + +Nesse caso, seria melhor ter apenas 2 servidores e usar uma porcentagem maior de seus recursos (CPU, memória, disco, largura de banda de rede, etc). + +Por outro lado, se você tem 2 servidores e está usando **100% da CPU e RAM deles**, em algum momento um processo pedirá mais memória, e o servidor terá que usar o disco como "memória" (o que pode ser milhares de vezes mais lento), ou até mesmo **travar**. Ou um processo pode precisar fazer alguma computação e teria que esperar até que a CPU esteja livre novamente. + +Nesse caso, seria melhor obter **um servidor extra** e executar alguns processos nele para que todos tenham **RAM e tempo de CPU suficientes**. + +Também há a chance de que, por algum motivo, você tenha um **pico** de uso da sua API. Talvez ela tenha se tornado viral, ou talvez alguns outros serviços ou bots comecem a usá-la. E você pode querer ter recursos extras para estar seguro nesses casos. + +Você poderia colocar um **número arbitrário** para atingir, por exemplo, algo **entre 50% a 90%** da utilização de recursos. O ponto é que essas são provavelmente as principais coisas que você vai querer medir e usar para ajustar suas implantações. + +Você pode usar ferramentas simples como `htop` para ver a CPU e a RAM usadas no seu servidor ou a quantidade usada por cada processo. Ou você pode usar ferramentas de monitoramento mais complexas, que podem ser distribuídas entre servidores, etc. + +## Recapitular + +Você leu aqui alguns dos principais conceitos que provavelmente precisa ter em mente ao decidir como implantar seu aplicativo: + +* Segurança - HTTPS +* Executando na inicialização +* Reinicializações +* Replicação (o número de processos em execução) +* Memória +* Etapas anteriores antes de iniciar + +Entender essas ideias e como aplicá-las deve lhe dar a intuição necessária para tomar qualquer decisão ao configurar e ajustar suas implantações. 🤓 + +Nas próximas seções, darei exemplos mais concretos de possíveis estratégias que você pode seguir. 🚀 diff --git a/docs/pt/docs/deployment/docker.md b/docs/pt/docs/deployment/docker.md index 42c31db29..cf18bb153 100644 --- a/docs/pt/docs/deployment/docker.md +++ b/docs/pt/docs/deployment/docker.md @@ -4,9 +4,11 @@ Ao fazer o deploy de aplicações FastAPI uma abordagem comum é construir uma * Usando contêineres Linux você tem diversas vantagens incluindo **segurança**, **replicabilidade**, **simplicidade**, entre outras. -!!! Dica - Está com pressa e já sabe dessas coisas? Pode ir direto para [`Dockerfile` abaixo 👇](#build-a-docker-image-for-fastapi). +/// tip | Dica +Está com pressa e já sabe dessas coisas? Pode ir direto para [`Dockerfile` abaixo 👇](#construindo-uma-imagem-docker-para-fastapi). + +///
Visualização do Dockerfile 👀 @@ -109,7 +111,7 @@ Isso pode depender principalmente da ferramenta que você usa para **instalar** O caminho mais comum de fazer isso é ter um arquivo `requirements.txt` com os nomes dos pacotes e suas versões, um por linha. -Você, naturalmente, usaria as mesmas ideias que você leu em [Sobre Versões do FastAPI](./versions.md){.internal-link target=_blank} para definir os intervalos de versões. +Você, naturalmente, usaria as mesmas ideias que você leu em [Sobre Versões do FastAPI](versions.md){.internal-link target=_blank} para definir os intervalos de versões. Por exemplo, seu `requirements.txt` poderia parecer com: @@ -131,10 +133,13 @@ Successfully installed fastapi pydantic uvicorn -!!! info - Há outros formatos e ferramentas para definir e instalar dependências de pacote. +/// info + +Há outros formatos e ferramentas para definir e instalar dependências de pacote. + +Eu vou mostrar um exemplo depois usando Poetry em uma seção abaixo. 👇 - Eu vou mostrar um exemplo depois usando Poetry em uma seção abaixo. 👇 +/// ### Criando o Código do **FastAPI** @@ -200,8 +205,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] A opção `--no-cache-dir` diz ao `pip` para não salvar os pacotes baixados localmente, pois isso só aconteceria se `pip` fosse executado novamente para instalar os mesmos pacotes, mas esse não é o caso quando trabalhamos com contêineres. - !!! note - `--no-cache-dir` é apenas relacionado ao `pip`, não tem nada a ver com Docker ou contêineres. + /// note + + `--no-cache-dir` é apenas relacionado ao `pip`, não tem nada a ver com Docker ou contêineres. + + /// A opção `--upgrade` diz ao `pip` para atualizar os pacotes se eles já estiverem instalados. @@ -223,8 +231,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] Porque o programa será iniciado em `/code` e dentro dele está o diretório `./app` com seu código, o **Uvicorn** será capaz de ver e **importar** `app` de `app.main`. -!!! tip - Revise o que cada linha faz clicando em cada bolha com o número no código. 👆 +/// tip + +Revise o que cada linha faz clicando em cada bolha com o número no código. 👆 + +/// Agora você deve ter uma estrutura de diretório como: @@ -294,10 +305,13 @@ $ docker build -t myimage . -!!! tip - Note o `.` no final, é equivalente a `./`, ele diz ao Docker o diretório a ser usado para construir a imagem do contêiner. +/// tip + +Note o `.` no final, é equivalente a `./`, ele diz ao Docker o diretório a ser usado para construir a imagem do contêiner. + +Nesse caso, é o mesmo diretório atual (`.`). - Nesse caso, é o mesmo diretório atual (`.`). +/// ### Inicie o contêiner Docker @@ -374,7 +388,7 @@ Então ajuste o comando Uvicorn para usar o novo módulo `main` em vez de `app.m ## Conceitos de Implantação -Vamos falar novamente sobre alguns dos mesmos [Conceitos de Implantação](./concepts.md){.internal-link target=_blank} em termos de contêineres. +Vamos falar novamente sobre alguns dos mesmos [Conceitos de Implantação](concepts.md){.internal-link target=_blank} em termos de contêineres. Contêineres são principalmente uma ferramenta para simplificar o processo de **construção e implantação** de um aplicativo, mas eles não impõem uma abordagem particular para lidar com esses **conceitos de implantação** e existem várias estratégias possíveis. @@ -395,8 +409,11 @@ Se nos concentrarmos apenas na **imagem do contêiner** para um aplicativo FastA Isso poderia ser outro contêiner, por exemplo, com Traefik, lidando com **HTTPS** e aquisição **automática** de **certificados**. -!!! tip - Traefik tem integrações com Docker, Kubernetes e outros, portanto, é muito fácil configurar e configurar o HTTPS para seus contêineres com ele. +/// tip + +Traefik tem integrações com Docker, Kubernetes e outros, portanto, é muito fácil configurar e configurar o HTTPS para seus contêineres com ele. + +/// Alternativamente, o HTTPS poderia ser tratado por um provedor de nuvem como um de seus serviços (enquanto ainda executasse o aplicativo em um contêiner). @@ -424,8 +441,11 @@ Quando usando contêineres, normalmente você terá algum componente **escutando Como esse componente assumiria a **carga** de solicitações e distribuiria isso entre os trabalhadores de uma maneira (esperançosamente) **balanceada**, ele também é comumente chamado de **Balanceador de Carga**. -!!! tip - O mesmo componente **Proxy de Terminação TLS** usado para HTTPS provavelmente também seria um **Balanceador de Carga**. +/// tip + +O mesmo componente **Proxy de Terminação TLS** usado para HTTPS provavelmente também seria um **Balanceador de Carga**. + +/// E quando trabalhar com contêineres, o mesmo sistema que você usa para iniciar e gerenciá-los já terá ferramentas internas para transmitir a **comunicação de rede** (por exemplo, solicitações HTTP) do **balanceador de carga** (que também pode ser um **Proxy de Terminação TLS**) para o(s) contêiner(es) com seu aplicativo. @@ -504,8 +524,11 @@ Se você estiver usando contêineres (por exemplo, Docker, Kubernetes), existem Se você tiver **múltiplos contêineres**, provavelmente cada um executando um **único processo** (por exemplo, em um cluster do **Kubernetes**), então provavelmente você gostaria de ter um **contêiner separado** fazendo o trabalho dos **passos anteriores** em um único contêiner, executando um único processo, **antes** de executar os contêineres trabalhadores replicados. -!!! info - Se você estiver usando o Kubernetes, provavelmente será um Init Container. +/// info + +Se você estiver usando o Kubernetes, provavelmente será um Init Container. + +/// Se no seu caso de uso não houver problema em executar esses passos anteriores **em paralelo várias vezes** (por exemplo, se você não estiver executando migrações de banco de dados, mas apenas verificando se o banco de dados está pronto), então você também pode colocá-los em cada contêiner logo antes de iniciar o processo principal. @@ -515,14 +538,17 @@ Se você tiver uma configuração simples, com um **único contêiner** que ent ## Imagem Oficial do Docker com Gunicorn - Uvicorn -Há uma imagem oficial do Docker que inclui o Gunicorn executando com trabalhadores Uvicorn, conforme detalhado em um capítulo anterior: [Server Workers - Gunicorn com Uvicorn](./server-workers.md){.internal-link target=_blank}. +Há uma imagem oficial do Docker que inclui o Gunicorn executando com trabalhadores Uvicorn, conforme detalhado em um capítulo anterior: [Server Workers - Gunicorn com Uvicorn](server-workers.md){.internal-link target=_blank}. -Essa imagem seria útil principalmente nas situações descritas acima em: [Contêineres com Múltiplos Processos e Casos Especiais](#contêineres-com-múltiplos-processos-e-casos-Especiais). +Essa imagem seria útil principalmente nas situações descritas acima em: [Contêineres com Múltiplos Processos e Casos Especiais](#conteineres-com-multiplos-processos-e-casos-especiais). * tiangolo/uvicorn-gunicorn-fastapi. -!!! warning - Existe uma grande chance de que você **não** precise dessa imagem base ou de qualquer outra semelhante, e seria melhor construir a imagem do zero, como [descrito acima em: Construa uma Imagem Docker para o FastAPI](#construa-uma-imagem-docker-para-o-fastapi). +/// warning + +Existe uma grande chance de que você **não** precise dessa imagem base ou de qualquer outra semelhante, e seria melhor construir a imagem do zero, como [descrito acima em: Construa uma Imagem Docker para o FastAPI](#construindo-uma-imagem-docker-para-fastapi). + +/// Essa imagem tem um mecanismo de **auto-ajuste** incluído para definir o **número de processos trabalhadores** com base nos núcleos de CPU disponíveis. @@ -530,8 +556,11 @@ Isso tem **padrões sensíveis**, mas você ainda pode alterar e atualizar todas Há também suporte para executar **passos anteriores antes de iniciar** com um script. -!!! tip - Para ver todas as configurações e opções, vá para a página da imagem Docker: tiangolo/uvicorn-gunicorn-fastapi. +/// tip + +Para ver todas as configurações e opções, vá para a página da imagem Docker: tiangolo/uvicorn-gunicorn-fastapi. + +/// ### Número de Processos na Imagem Oficial do Docker @@ -579,7 +608,7 @@ COPY ./app /app/app Você provavelmente **não** deve usar essa imagem base oficial (ou qualquer outra semelhante) se estiver usando **Kubernetes** (ou outros) e já estiver definindo **replicação** no nível do cluster, com vários **contêineres**. Nesses casos, é melhor **construir uma imagem do zero** conforme descrito acima: [Construindo uma Imagem Docker para FastAPI](#construindo-uma-imagem-docker-para-fastapi). -Essa imagem seria útil principalmente nos casos especiais descritos acima em [Contêineres com Múltiplos Processos e Casos Especiais](#contêineres-com-múltiplos-processos-e-casos-Especiais). Por exemplo, se sua aplicação for **simples o suficiente** para que a configuração padrão de número de processos com base na CPU funcione bem, você não quer se preocupar com a configuração manual da replicação no nível do cluster e não está executando mais de um contêiner com seu aplicativo. Ou se você estiver implantando com **Docker Compose**, executando em um único servidor, etc. +Essa imagem seria útil principalmente nos casos especiais descritos acima em [Contêineres com Múltiplos Processos e Casos Especiais](#conteineres-com-multiplos-processos-e-casos-especiais). Por exemplo, se sua aplicação for **simples o suficiente** para que a configuração padrão de número de processos com base na CPU funcione bem, você não quer se preocupar com a configuração manual da replicação no nível do cluster e não está executando mais de um contêiner com seu aplicativo. Ou se você estiver implantando com **Docker Compose**, executando em um único servidor, etc. ## Deploy da Imagem do Contêiner @@ -660,8 +689,11 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 11. Execute o comando `uvicorn`, informando-o para usar o objeto `app` importado de `app.main`. -!!! tip - Clique nos números das bolhas para ver o que cada linha faz. +/// tip + +Clique nos números das bolhas para ver o que cada linha faz. + +/// Um **estágio do Docker** é uma parte de um `Dockerfile` que funciona como uma **imagem temporária do contêiner** que só é usada para gerar alguns arquivos para serem usados posteriormente. diff --git a/docs/pt/docs/deployment/https.md b/docs/pt/docs/deployment/https.md index f85861e92..9ad419934 100644 --- a/docs/pt/docs/deployment/https.md +++ b/docs/pt/docs/deployment/https.md @@ -4,45 +4,196 @@ Mas é bem mais complexo do que isso. -!!! tip "Dica" - Se você está com pressa ou não se importa, continue com as seções seguintes para instruções passo a passo para configurar tudo com diferentes técnicas. +/// tip | Dica + +Se você está com pressa ou não se importa, continue com as seções seguintes para instruções passo a passo para configurar tudo com diferentes técnicas. + +/// Para aprender o básico de HTTPS de uma perspectiva do usuário, verifique https://howhttps.works/pt-br/. Agora, a partir de uma perspectiva do desenvolvedor, aqui estão algumas coisas para ter em mente ao pensar em HTTPS: -* Para HTTPS, o servidor precisa ter certificados gerados por um terceiro. - * Esses certificados são adquiridos de um terceiro, eles não são simplesmente "gerados". -* Certificados têm um tempo de vida. - * Eles expiram. - * E então eles precisam ser renovados, adquirindo-os novamente de um terceiro. -* A criptografia da conexão acontece no nível TCP. - * Essa é uma camada abaixo do HTTP. - * Portanto, o manuseio do certificado e da criptografia é feito antes do HTTP. -* O TCP não sabe sobre "domínios". Apenas sobre endereços IP. - * As informações sobre o domínio solicitado vão nos dados HTTP. -* Os certificados HTTPS “certificam” um determinado domínio, mas o protocolo e a encriptação acontecem ao nível do TCP, antes de sabermos de que domínio se trata. -* Por padrão, isso significa que você só pode ter um certificado HTTPS por endereço IP. +* Para HTTPS, **o servidor** precisa ter certificados gerados por **um terceiro**. + * Esses certificados são na verdade **adquiridos** de um terceiro, eles não são simplesmente "gerados". +* Certificados têm um **tempo de vida**. + * Eles **expiram**. + * E então eles precisam ser **renovados**, **adquirindo-os novamente** de um terceiro. +* A criptografia da conexão acontece no **nível TCP**. + * Essa é uma camada **abaixo do HTTP**. + * Portanto, o manuseio do **certificado e da criptografia** é feito **antes do HTTP**. +* **O TCP não sabe sobre "domínios"**. Apenas sobre endereços IP. + * As informações sobre o **domínio solicitado** vão nos **dados HTTP**. +* Os **certificados HTTPS** “certificam” um **determinado domínio**, mas o protocolo e a encriptação acontecem ao nível do TCP, **antes de sabermos** de que domínio se trata. +* **Por padrão**, isso significa que você só pode ter **um certificado HTTPS por endereço IP**. * Não importa o tamanho do seu servidor ou quão pequeno cada aplicativo que você tem nele possa ser. - * No entanto, existe uma solução para isso. -* Há uma extensão para o protocolo TLS (aquele que lida com a criptografia no nível TCP, antes do HTTP) chamado SNI. - * Esta extensão SNI permite que um único servidor (com um único endereço IP) tenha vários certificados HTTPS e atenda a vários domínios / aplicativos HTTPS. - * Para que isso funcione, um único componente (programa) em execução no servidor, ouvindo no endereço IP público, deve ter todos os certificados HTTPS no servidor. -* Depois de obter uma conexão segura, o protocolo de comunicação ainda é HTTP. - * Os conteúdos são criptografados, embora sejam enviados com o protocolo HTTP. + * No entanto, existe uma **solução** para isso. +* Há uma **extensão** para o protocolo **TLS** (aquele que lida com a criptografia no nível TCP, antes do HTTP) chamado **SNI**. + * Esta extensão SNI permite que um único servidor (com um **único endereço IP**) tenha **vários certificados HTTPS** e atenda a **vários domínios / aplicativos HTTPS**. + * Para que isso funcione, um **único** componente (programa) em execução no servidor, ouvindo no **endereço IP público**, deve ter **todos os certificados HTTPS** no servidor. +* **Depois** de obter uma conexão segura, o protocolo de comunicação **ainda é HTTP**. + * Os conteúdos são **criptografados**, embora sejam enviados com o **protocolo HTTP**. + +É uma prática comum ter um **programa/servidor HTTP** em execução no servidor (máquina, host, etc.) e **gerenciar todas as partes HTTPS**: **recebendo as requisições encriptadas**, enviando as **solicitações HTTP descriptografadas** para o aplicativo HTTP real em execução no mesmo servidor (a aplicação **FastAPI**, neste caso), pegue a **resposta HTTP** do aplicativo, **criptografe-a** usando o **certificado HTTPS** apropriado e envie-a de volta ao cliente usando **HTTPS**. Este servidor é frequentemente chamado de **Proxy de Terminação TLS**. -É uma prática comum ter um programa/servidor HTTP em execução no servidor (máquina, host, etc.) e gerenciar todas as partes HTTPS: enviando as solicitações HTTP descriptografadas para o aplicativo HTTP real em execução no mesmo servidor (a aplicação **FastAPI**, neste caso), pegue a resposta HTTP do aplicativo, criptografe-a usando o certificado apropriado e envie-a de volta ao cliente usando HTTPS. Este servidor é frequentemente chamado de TLS Termination Proxy. +Algumas das opções que você pode usar como Proxy de Terminação TLS são: + +* Traefik (que também pode gerenciar a renovação de certificados) +* Caddy (que também pode gerenciar a renovação de certificados) +* Nginx +* HAProxy ## Let's Encrypt -Antes de Let's Encrypt, esses certificados HTTPS eram vendidos por terceiros confiáveis. +Antes de Let's Encrypt, esses **certificados HTTPS** eram vendidos por terceiros confiáveis. O processo de aquisição de um desses certificados costumava ser complicado, exigia bastante papelada e os certificados eram bastante caros. -Mas então Let's Encrypt foi criado. +Mas então o **Let's Encrypt** foi criado. -Ele é um projeto da Linux Foundation que fornece certificados HTTPS gratuitamente. De forma automatizada. Esses certificados usam toda a segurança criptográfica padrão e têm vida curta (cerca de 3 meses), então a segurança é realmente melhor por causa de sua vida útil reduzida. +Ele é um projeto da Linux Foundation que fornece **certificados HTTPS gratuitamente** . De forma automatizada. Esses certificados usam toda a segurança criptográfica padrão e têm vida curta (cerca de 3 meses), então a **segurança é, na verdade, melhor** por causa de sua vida útil reduzida. Os domínios são verificados com segurança e os certificados são gerados automaticamente. Isso também permite automatizar a renovação desses certificados. -A ideia é automatizar a aquisição e renovação desses certificados, para que você tenha HTTPS seguro, de graça e para sempre. +A ideia é automatizar a aquisição e renovação desses certificados, para que você tenha **HTTPS seguro, de graça e para sempre**. + +## HTTPS para Desenvolvedores + +Aqui está um exemplo de como uma API HTTPS poderia ser estruturada, passo a passo, com foco principal nas ideias relevantes para desenvolvedores. + +### Nome do domínio + +A etapa inicial provavelmente seria **adquirir** algum **nome de domínio**. Então, você iria configurá-lo em um servidor DNS (possivelmente no mesmo provedor em nuvem). + +Você provavelmente usaria um servidor em nuvem (máquina virtual) ou algo parecido, e ele teria fixed **Endereço IP público**. + +No(s) servidor(es) DNS, você configuraria um registro (`registro A`) para apontar **seu domínio** para o **endereço IP público do seu servidor**. + +Você provavelmente fará isso apenas uma vez, na primeira vez em que tudo estiver sendo configurado. + +/// tip | Dica + +Essa parte do Nome do Domínio se dá muito antes do HTTPS, mas como tudo depende do domínio e endereço IP público, vale a pena mencioná-la aqui. + +/// + +### DNS + +Agora vamos focar em todas as partes que realmente fazem parte do HTTPS. + +Primeiro, o navegador iria verificar com os **servidores DNS** qual o **IP do domínio**, nesse caso, `someapp.example.com`. + +Os servidores DNS iriam informar o navegador para utilizar algum **endereço IP** específico. Esse seria o endereço IP público em uso no seu servidor, que você configurou nos servidores DNS. + + + +### Início do Handshake TLS + +O navegador então irá comunicar-se com esse endereço IP na **porta 443** (a porta HTTPS). + +A primeira parte dessa comunicação é apenas para estabelecer a conexão entre o cliente e o servidor e para decidir as chaves criptográficas a serem utilizadas, etc. + + + +Esse interação entre o cliente e o servidor para estabelecer uma conexão TLS é chamada de **Handshake TLS**. + +### TLS com a Extensão SNI + +**Apenas um processo** no servidor pode se conectar a uma **porta** em um **endereço IP**. Poderiam existir outros processos conectados em outras portas desse mesmo endereço IP, mas apenas um para cada combinação de endereço IP e porta. + +TLS (HTTPS) usa a porta `443` por padrão. Então essa é a porta que precisamos. + +Como apenas um único processo pode se comunicar com essa porta, o processo que faria isso seria o **Proxy de Terminação TLS**. + +O Proxy de Terminação TLS teria acesso a um ou mais **certificados TLS** (certificados HTTPS). + +Utilizando a **extensão SNI** discutida acima, o Proxy de Terminação TLS iria checar qual dos certificados TLS (HTTPS) disponíveis deve ser usado para essa conexão, utilizando o que corresponda ao domínio esperado pelo cliente. + +Nesse caso, ele usaria o certificado para `someapp.example.com`. + + + +O cliente já **confia** na entidade que gerou o certificado TLS (nesse caso, o Let's Encrypt, mas veremos sobre isso mais tarde), então ele pode **verificar** que o certificado é válido. + +Então, utilizando o certificado, o cliente e o Proxy de Terminação TLS **decidem como encriptar** o resto da **comunicação TCP**. Isso completa a parte do **Handshake TLS**. + +Após isso, o cliente e o servidor possuem uma **conexão TCP encriptada**, que é provida pelo TLS. E então eles podem usar essa conexão para começar a **comunicação HTTP** propriamente dita. + +E isso resume o que é **HTTPS**, apenas **HTTP** simples dentro de uma **conexão TLS segura** em vez de uma conexão TCP pura (não encriptada). + +/// tip | Dica + +Percebe que a encriptação da comunicação acontece no **nível do TCP**, não no nível do HTTP. + +/// + +### Solicitação HTTPS + +Agora que o cliente e servidor (especialmente o navegador e o Proxy de Terminação TLS) possuem uma **conexão TCP encriptada**, eles podem iniciar a **comunicação HTTP**. + +Então, o cliente envia uma **solicitação HTTPS**. Que é apenas uma solicitação HTTP sobre uma conexão TLS encriptada. + + + +### Desencriptando a Solicitação + +O Proxy de Terminação TLS então usaria a encriptação combinada para **desencriptar a solicitação**, e transmitiria a **solicitação básica (desencriptada)** para o processo executando a aplicação (por exemplo, um processo com Uvicorn executando a aplicação FastAPI). + + + +### Resposta HTTP + +A aplicação processaria a solicitação e retornaria uma **resposta HTTP básica (não encriptada)** para o Proxy de Terminação TLS. + + + +### Resposta HTTPS + +O Proxy de Terminação TLS iria **encriptar a resposta** utilizando a criptografia combinada anteriormente (que foi definida com o certificado para `someapp.example.com`), e devolveria para o navegador. + +No próximo passo, o navegador verifica que a resposta é válida e encriptada com a chave criptográfica correta, etc. E depois **desencripta a resposta** e a processa. + + + +O cliente (navegador) saberá que a resposta vem do servidor correto por que ela usa a criptografia que foi combinada entre eles usando o **certificado HTTPS** anterior. + +### Múltiplas Aplicações + +Podem existir **múltiplas aplicações** em execução no mesmo servidor (ou servidores), por exemplo: outras APIs ou um banco de dados. + +Apenas um processo pode estar vinculado a um IP e porta (o Proxy de Terminação TLS, por exemplo), mas outras aplicações/processos também podem estar em execução no(s) servidor(es), desde que não tentem usar a mesma **combinação de IP público e porta**. + + + +Dessa forma, o Proxy de Terminação TLS pode gerenciar o HTTPS e os certificados de **múltiplos domínios**, para múltiplas aplicações, e então transmitir as requisições para a aplicação correta em cada caso. + +### Renovação de Certificados + +Em algum momento futuro, cada certificado irá **expirar** (aproximadamente 3 meses após a aquisição). + +E então, haverá outro programa (em alguns casos pode ser o próprio Proxy de Terminação TLS) que irá interagir com o Let's Encrypt e renovar o(s) certificado(s). + + + +Os **certificados TLS** são **associados com um nome de domínio**, e não a um endereço IP. + +Então para renovar os certificados, o programa de renovação precisa **provar** para a autoridade (Let's Encrypt) que ele realmente **possui e controla esse domínio**> + +Para fazer isso, e acomodar as necessidades de diferentes aplicações, existem diferentes opções para esse programa. Algumas escolhas populares são: + +* **Modificar alguns registros DNS** + * Para isso, o programa de renovação precisa ter suporte as APIs do provedor DNS, então, dependendo do provedor DNS que você utilize, isso pode ou não ser uma opção viável. +* **Executar como um servidor** (ao menos durante o processo de aquisição do certificado) no endereço IP público associado com o domínio. + * Como dito anteriormente, apenas um processo pode estar ligado a uma porta e IP específicos. + * Essa é uma dos motivos que fazem utilizar o mesmo Proxy de Terminação TLS para gerenciar a renovação de certificados ser tão útil. + * Caso contrário, você pode ter que parar a execução do Proxy de Terminação TLS momentaneamente, inicializar o programa de renovação para renovar os certificados, e então reiniciar o Proxy de Terminação TLS. Isso não é o ideal, já que sua(s) aplicação(ões) não vão estar disponíveis enquanto o Proxy de Terminação TLS estiver desligado. + +Todo esse processo de renovação, enquanto o aplicativo ainda funciona, é uma das principais razões para preferir um **sistema separado para gerenciar HTTPS** com um Proxy de Terminação TLS em vez de usar os certificados TLS no servidor da aplicação diretamente (e.g. com o Uvicorn). + +## Recapitulando + +Possuir **HTTPS** habilitado na sua aplicação é bastante importante, e até **crítico** na maioria dos casos. A maior parte do esforço que você tem que colocar sobre o HTTPS como desenvolvedor está em **entender esses conceitos** e como eles funcionam. + +Mas uma vez que você saiba o básico de **HTTPS para desenvolvedores**, você pode combinar e configurar diferentes ferramentas facilmente para gerenciar tudo de uma forma simples. + +Em alguns dos próximos capítulos, eu mostrarei para você vários exemplos concretos de como configurar o **HTTPS** para aplicações **FastAPI**. 🔒 diff --git a/docs/pt/docs/deployment/manually.md b/docs/pt/docs/deployment/manually.md new file mode 100644 index 000000000..46e580807 --- /dev/null +++ b/docs/pt/docs/deployment/manually.md @@ -0,0 +1,157 @@ +# Execute um Servidor Manualmente + +## Utilize o comando `fastapi run` + +Em resumo, utilize o comando `fastapi run` para inicializar sua aplicação FastAPI: + +
+ +```console +$ fastapi run main.py + + FastAPI Starting production server 🚀 + + Searching for package file structure from directories + with __init__.py files + Importing from /home/user/code/awesomeapp + + module 🐍 main.py + + code Importing the FastAPI app object from the module with + the following code: + + from main import app + + app Using import string: main:app + + server Server started at http://0.0.0.0:8000 + server Documentation at http://0.0.0.0:8000/docs + + Logs: + + INFO Started server process [2306215] + INFO Waiting for application startup. + INFO Application startup complete. + INFO Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C + to quit) +``` + +
+ +Isto deve funcionar para a maioria dos casos. 😎 + +Você pode utilizar esse comando, por exemplo, para iniciar sua aplicação **FastAPI** em um contêiner, em um servidor, etc. + +## Servidores ASGI + +Vamos nos aprofundar um pouco mais em detalhes. + +FastAPI utiliza um padrão para construir frameworks e servidores web em Python chamado ASGI. FastAPI é um framework web ASGI. + +A principal coisa que você precisa para executar uma aplicação **FastAPI** (ou qualquer outra aplicação ASGI) em uma máquina de servidor remoto é um programa de servidor ASGI como o **Uvicorn**, que é o que vem por padrão no comando `fastapi`. + +Existem diversas alternativas, incluindo: + +* Uvicorn: um servidor ASGI de alta performance. +* Hypercorn: um servidor ASGI compátivel com HTTP/2, Trio e outros recursos. +* Daphne: servidor ASGI construído para Django Channels. +* Granian: um servidor HTTP Rust para aplicações Python. +* NGINX Unit: NGINX Unit é um runtime de aplicação web leve e versátil. + +## Máquina Servidora e Programa Servidor + +Existe um pequeno detalhe sobre estes nomes para se manter em mente. 💡 + +A palavra "**servidor**" é comumente usada para se referir tanto ao computador remoto/nuvem (a máquina física ou virtual) quanto ao programa que está sendo executado nessa máquina (por exemplo, Uvicorn). + +Apenas tenha em mente que quando você ler "servidor" em geral, isso pode se referir a uma dessas duas coisas. + +Quando se refere à máquina remota, é comum chamá-la de **servidor**, mas também de **máquina**, **VM** (máquina virtual), **nó**. Todos esses termos se referem a algum tipo de máquina remota, normalmente executando Linux, onde você executa programas. + +## Instale o Programa Servidor + +Quando você instala o FastAPI, ele vem com um servidor de produção, o Uvicorn, e você pode iniciá-lo com o comando `fastapi run`. + +Mas você também pode instalar um servidor ASGI manualmente. + +Certifique-se de criar um [ambiente virtual](../virtual-environments.md){.internal-link target=_blank}, ativá-lo e, em seguida, você pode instalar a aplicação do servidor. + +Por exemplo, para instalar o Uvicorn: + +
+ +```console +$ pip install "uvicorn[standard]" + +---> 100% +``` + +
+ +Um processo semelhante se aplicaria a qualquer outro programa de servidor ASGI. + +/// tip | Dica + +Adicionando o `standard`, o Uvicorn instalará e usará algumas dependências extras recomendadas. + +Isso inclui o `uvloop`, a substituição de alto desempenho para `asyncio`, que fornece um grande aumento de desempenho de concorrência. + +Quando você instala o FastAPI com algo como `pip install "fastapi[standard]"`, você já obtém `uvicorn[standard]` também. + +/// + +## Execute o Programa Servidor + +Se você instalou um servidor ASGI manualmente, normalmente precisará passar uma string de importação em um formato especial para que ele importe sua aplicação FastAPI: + +
+ +```console +$ uvicorn main:app --host 0.0.0.0 --port 80 + +INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) +``` + +
+ +/// note | Nota + +O comando `uvicorn main:app` refere-se a: + +* `main`: o arquivo `main.py` (o "módulo" Python). +* `app`: o objeto criado dentro de `main.py` com a linha `app = FastAPI()`. + +É equivalente a: + +```Python +from main import app +``` + +/// + +Cada programa de servidor ASGI alternativo teria um comando semelhante, você pode ler mais na documentação respectiva. + +/// warning | Aviso + +Uvicorn e outros servidores suportam a opção `--reload` que é útil durante o desenvolvimento. + +A opção `--reload` consome muito mais recursos, é mais instável, etc. + +Ela ajuda muito durante o **desenvolvimento**, mas você **não deve** usá-la em **produção**. + +/// + +## Conceitos de Implantação + +Esses exemplos executam o programa do servidor (por exemplo, Uvicorn), iniciando **um único processo**, ouvindo em todos os IPs (`0.0.0.0`) em uma porta predefinida (por exemplo, `80`). + +Esta é a ideia básica. Mas você provavelmente vai querer cuidar de algumas coisas adicionais, como: + +* Segurança - HTTPS +* Executando na inicialização +* Reinicializações +* Replicação (o número de processos em execução) +* Memória +* Passos anteriores antes de começar + +Vou te contar mais sobre cada um desses conceitos, como pensar sobre eles e alguns exemplos concretos com estratégias para lidar com eles nos próximos capítulos. 🚀 diff --git a/docs/pt/docs/deployment/server-workers.md b/docs/pt/docs/deployment/server-workers.md new file mode 100644 index 000000000..a0db1bea4 --- /dev/null +++ b/docs/pt/docs/deployment/server-workers.md @@ -0,0 +1,139 @@ +# Trabalhadores do Servidor - Uvicorn com Trabalhadores + +Vamos rever os conceitos de implantação anteriores: + +* Segurança - HTTPS +* Executando na inicialização +* Reinicializações +* **Replicação (o número de processos em execução)** +* Memória +* Etapas anteriores antes de iniciar + +Até este ponto, com todos os tutoriais nos documentos, você provavelmente estava executando um **programa de servidor**, por exemplo, usando o comando `fastapi`, que executa o Uvicorn, executando um **único processo**. + +Ao implantar aplicativos, você provavelmente desejará ter alguma **replicação de processos** para aproveitar **vários núcleos** e poder lidar com mais solicitações. + +Como você viu no capítulo anterior sobre [Conceitos de implantação](concepts.md){.internal-link target=_blank}, há várias estratégias que você pode usar. + +Aqui mostrarei como usar o **Uvicorn** com **processos de trabalho** usando o comando `fastapi` ou o comando `uvicorn` diretamente. + +/// info | Informação + +Se você estiver usando contêineres, por exemplo com Docker ou Kubernetes, falarei mais sobre isso no próximo capítulo: [FastAPI em contêineres - Docker](docker.md){.internal-link target=_blank}. + +Em particular, ao executar no **Kubernetes** você provavelmente **não** vai querer usar vários trabalhadores e, em vez disso, executar **um único processo Uvicorn por contêiner**, mas falarei sobre isso mais adiante neste capítulo. + +/// + +## Vários trabalhadores + +Você pode iniciar vários trabalhadores com a opção de linha de comando `--workers`: + +//// tab | `fastapi` + +Se você usar o comando `fastapi`: + +
+ +```console +$ fastapi run --workers 4 main.py + + FastAPI Starting production server 🚀 + + Searching for package file structure from directories with + __init__.py files + Importing from /home/user/code/awesomeapp + + module 🐍 main.py + + code Importing the FastAPI app object from the module with the + following code: + + from main import app + + app Using import string: main:app + + server Server started at http://0.0.0.0:8000 + server Documentation at http://0.0.0.0:8000/docs + + Logs: + + INFO Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to + quit) + INFO Started parent process [27365] + INFO Started server process [27368] + INFO Started server process [27369] + INFO Started server process [27370] + INFO Started server process [27367] + INFO Waiting for application startup. + INFO Waiting for application startup. + INFO Waiting for application startup. + INFO Waiting for application startup. + INFO Application startup complete. + INFO Application startup complete. + INFO Application startup complete. + INFO Application startup complete. +``` + +
+ +//// + +//// tab | `uvicorn` + +Se você preferir usar o comando `uvicorn` diretamente: + +
+ +```console +$ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4 +INFO: Uvicorn running on http://0.0.0.0:8080 (Press CTRL+C to quit) +INFO: Started parent process [27365] +INFO: Started server process [27368] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Started server process [27369] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Started server process [27370] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Started server process [27367] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +//// + +A única opção nova aqui é `--workers` informando ao Uvicorn para iniciar 4 processos de trabalho. + +Você também pode ver que ele mostra o **PID** de cada processo, `27365` para o processo pai (este é o **gerenciador de processos**) e um para cada processo de trabalho: `27368`, `27369`, `27370` e `27367`. + +## Conceitos de Implantação + +Aqui você viu como usar vários **trabalhadores** para **paralelizar** a execução do aplicativo, aproveitar **vários núcleos** na CPU e conseguir atender **mais solicitações**. + +Da lista de conceitos de implantação acima, o uso de trabalhadores ajudaria principalmente com a parte da **replicação** e um pouco com as **reinicializações**, mas você ainda precisa cuidar dos outros: + +* **Segurança - HTTPS** +* **Executando na inicialização** +* ***Reinicializações*** +* Replicação (o número de processos em execução) +* **Memória** +* **Etapas anteriores antes de iniciar** + +## Contêineres e Docker + +No próximo capítulo sobre [FastAPI em contêineres - Docker](docker.md){.internal-link target=_blank}, explicarei algumas estratégias que você pode usar para lidar com os outros **conceitos de implantação**. + +Vou mostrar como **construir sua própria imagem do zero** para executar um único processo Uvicorn. É um processo simples e provavelmente é o que você gostaria de fazer ao usar um sistema de gerenciamento de contêineres distribuídos como o **Kubernetes**. + +## Recapitular + +Você pode usar vários processos de trabalho com a opção CLI `--workers` com os comandos `fastapi` ou `uvicorn` para aproveitar as vantagens de **CPUs multi-core** e executar **vários processos em paralelo**. + +Você pode usar essas ferramentas e ideias se estiver configurando **seu próprio sistema de implantação** enquanto cuida dos outros conceitos de implantação. + +Confira o próximo capítulo para aprender sobre **FastAPI** com contêineres (por exemplo, Docker e Kubernetes). Você verá que essas ferramentas têm maneiras simples de resolver os outros **conceitos de implantação** também. ✨ diff --git a/docs/pt/docs/deployment/versions.md b/docs/pt/docs/deployment/versions.md index 77d9bab69..323ddbd45 100644 --- a/docs/pt/docs/deployment/versions.md +++ b/docs/pt/docs/deployment/versions.md @@ -42,8 +42,11 @@ Seguindo as convenções de controle de versão semântica, qualquer versão aba FastAPI também segue a convenção de que qualquer alteração de versão "PATCH" é para correção de bugs e alterações não significativas. -!!! tip "Dica" - O "PATCH" é o último número, por exemplo, em `0.2.3`, a versão PATCH é `3`. +/// tip | Dica + +O "PATCH" é o último número, por exemplo, em `0.2.3`, a versão PATCH é `3`. + +/// Logo, você deveria conseguir fixar a versão, como: @@ -53,8 +56,11 @@ fastapi>=0.45.0,<0.46.0 Mudanças significativas e novos recursos são adicionados em versões "MINOR". -!!! tip "Dica" - O "MINOR" é o número que está no meio, por exemplo, em `0.2.3`, a versão MINOR é `2`. +/// tip | Dica + +O "MINOR" é o número que está no meio, por exemplo, em `0.2.3`, a versão MINOR é `2`. + +/// ## Atualizando as versões do FastAPI diff --git a/docs/pt/docs/environment-variables.md b/docs/pt/docs/environment-variables.md new file mode 100644 index 000000000..432f78af0 --- /dev/null +++ b/docs/pt/docs/environment-variables.md @@ -0,0 +1,298 @@ +# Variáveis de Ambiente + +/// tip | Dica + +Se você já sabe o que são "variáveis de ambiente" e como usá-las, pode pular esta seção. + +/// + +Uma variável de ambiente (também conhecida como "**env var**") é uma variável que existe **fora** do código Python, no **sistema operacional**, e pode ser lida pelo seu código Python (ou por outros programas também). + +Variáveis de ambiente podem ser úteis para lidar com **configurações** do aplicativo, como parte da **instalação** do Python, etc. + +## Criar e Usar Variáveis de Ambiente + +Você pode **criar** e usar variáveis de ambiente no **shell (terminal)**, sem precisar do Python: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// Você pode criar uma variável de ambiente MY_NAME com +$ export MY_NAME="Wade Wilson" + +// Então você pode usá-la com outros programas, como +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// Criar uma variável de ambiente MY_NAME +$ $Env:MY_NAME = "Wade Wilson" + +// Usá-la com outros programas, como +$ echo "Hello $Env:MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +## Ler Variáveis de Ambiente no Python + +Você também pode criar variáveis de ambiente **fora** do Python, no terminal (ou com qualquer outro método) e depois **lê-las no Python**. + +Por exemplo, você poderia ter um arquivo `main.py` com: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// tip | Dica + +O segundo argumento para `os.getenv()` é o valor padrão a ser retornado. + +Se não for fornecido, é `None` por padrão, Aqui fornecemos `"World"` como o valor padrão a ser usado. + +/// + +Então você poderia chamar esse programa Python: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// Aqui ainda não definimos a variável de ambiente +$ python main.py + +// Como não definimos a variável de ambiente, obtemos o valor padrão + +Hello World from Python + +// Mas se criarmos uma variável de ambiente primeiro +$ export MY_NAME="Wade Wilson" + +// E então chamar o programa novamente +$ python main.py + +// Agora ele pode ler a variável de ambiente + +Hello Wade Wilson from Python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// Aqui ainda não definimos a variável de ambiente +$ python main.py + +// Como não definimos a variável de ambiente, obtemos o valor padrão + +Hello World from Python + +// Mas se criarmos uma variável de ambiente primeiro +$ $Env:MY_NAME = "Wade Wilson" + +// E então chamar o programa novamente +$ python main.py + +// Agora ele pode ler a variável de ambiente + +Hello Wade Wilson from Python +``` + +
+ +//// + +Como as variáveis de ambiente podem ser definidas fora do código, mas podem ser lidas pelo código e não precisam ser armazenadas (com versão no `git`) com o restante dos arquivos, é comum usá-las para configurações ou **definições**. + +Você também pode criar uma variável de ambiente apenas para uma **invocação específica do programa**, que só está disponível para aquele programa e apenas pela duração dele. + +Para fazer isso, crie-a na mesma linha, antes do próprio programa: + +
+ +```console +// Criar uma variável de ambiente MY_NAME para esta chamada de programa +$ MY_NAME="Wade Wilson" python main.py + +// Agora ele pode ler a variável de ambiente + +Hello Wade Wilson from Python + +// A variável de ambiente não existe mais depois +$ python main.py + +Hello World from Python +``` + +
+ +/// tip | Dica + +Você pode ler mais sobre isso em The Twelve-Factor App: Config. + +/// + +## Tipos e Validação + +Essas variáveis de ambiente só podem lidar com **strings de texto**, pois são externas ao Python e precisam ser compatíveis com outros programas e com o resto do sistema (e até mesmo com diferentes sistemas operacionais, como Linux, Windows, macOS). + +Isso significa que **qualquer valor** lido em Python de uma variável de ambiente **será uma `str`**, e qualquer conversão para um tipo diferente ou qualquer validação precisa ser feita no código. + +Você aprenderá mais sobre como usar variáveis de ambiente para lidar com **configurações do aplicativo** no [Guia do Usuário Avançado - Configurações e Variáveis de Ambiente](./advanced/settings.md){.internal-link target=_blank}. + +## Variável de Ambiente `PATH` + +Existe uma variável de ambiente **especial** chamada **`PATH`** que é usada pelos sistemas operacionais (Linux, macOS, Windows) para encontrar programas para executar. + +O valor da variável `PATH` é uma longa string composta por diretórios separados por dois pontos `:` no Linux e macOS, e por ponto e vírgula `;` no Windows. + +Por exemplo, a variável de ambiente `PATH` poderia ter esta aparência: + +//// tab | Linux, macOS + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +Isso significa que o sistema deve procurar programas nos diretórios: + +* `/usr/local/bin` +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32 +``` + +Isso significa que o sistema deve procurar programas nos diretórios: + +* `C:\Program Files\Python312\Scripts` +* `C:\Program Files\Python312` +* `C:\Windows\System32` + +//// + +Quando você digita um **comando** no terminal, o sistema operacional **procura** o programa em **cada um dos diretórios** listados na variável de ambiente `PATH`. + +Por exemplo, quando você digita `python` no terminal, o sistema operacional procura um programa chamado `python` no **primeiro diretório** dessa lista. + +Se ele o encontrar, então ele o **usará**. Caso contrário, ele continua procurando nos **outros diretórios**. + +### Instalando o Python e Atualizando o `PATH` + +Durante a instalação do Python, você pode ser questionado sobre a atualização da variável de ambiente `PATH`. + +//// tab | Linux, macOS + +Vamos supor que você instale o Python e ele fique em um diretório `/opt/custompython/bin`. + +Se você concordar em atualizar a variável de ambiente `PATH`, o instalador adicionará `/opt/custompython/bin` para a variável de ambiente `PATH`. + +Poderia parecer assim: + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin +``` + +Dessa forma, ao digitar `python` no terminal, o sistema encontrará o programa Python em `/opt/custompython/bin` (último diretório) e o utilizará. + +//// + +//// tab | Windows + +Digamos que você instala o Python e ele acaba em um diretório `C:\opt\custompython\bin`. + +Se você disser sim para atualizar a variável de ambiente `PATH`, o instalador adicionará `C:\opt\custompython\bin` à variável de ambiente `PATH`. + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin +``` + +Dessa forma, quando você digitar `python` no terminal, o sistema encontrará o programa Python em `C:\opt\custompython\bin` (o último diretório) e o utilizará. + +//// + +Então, se você digitar: + +
+ +```console +$ python +``` + +
+ +//// tab | Linux, macOS + +O sistema **encontrará** o programa `python` em `/opt/custompython/bin` e o executará. + +Seria aproximadamente equivalente a digitar: + +
+ +```console +$ /opt/custompython/bin/python +``` + +
+ +//// + +//// tab | Windows + +O sistema **encontrará** o programa `python` em `C:\opt\custompython\bin\python` e o executará. + +Seria aproximadamente equivalente a digitar: + +
+ +```console +$ C:\opt\custompython\bin\python +``` + +
+ +//// + +Essas informações serão úteis ao aprender sobre [Ambientes Virtuais](virtual-environments.md){.internal-link target=_blank}. + +## Conclusão + +Com isso, você deve ter uma compreensão básica do que são **variáveis ​​de ambiente** e como usá-las em Python. + +Você também pode ler mais sobre elas na Wikipedia para Variáveis ​​de Ambiente. + +Em muitos casos, não é muito óbvio como as variáveis ​​de ambiente seriam úteis e aplicáveis ​​imediatamente. Mas elas continuam aparecendo em muitos cenários diferentes quando você está desenvolvendo, então é bom saber sobre elas. + +Por exemplo, você precisará dessas informações na próxima seção, sobre [Ambientes Virtuais](virtual-environments.md). diff --git a/docs/pt/docs/external-links.md b/docs/pt/docs/external-links.md deleted file mode 100644 index 77ec32351..000000000 --- a/docs/pt/docs/external-links.md +++ /dev/null @@ -1,33 +0,0 @@ -# Links externos e Artigos - -**FastAPI** tem uma grande comunidade em crescimento constante. - -Existem muitas postagens, artigos, ferramentas e projetos relacionados ao **FastAPI**. - -Aqui tem uma lista, incompleta, de algumas delas. - -!!! tip "Dica" - Se você tem um artigo, projeto, ferramenta ou qualquer coisa relacionada ao **FastAPI** que ainda não está listada aqui, crie um _Pull Request_ adicionando ele. - -{% for section_name, section_content in external_links.items() %} - -## {{ section_name }} - -{% for lang_name, lang_content in section_content.items() %} - -### {{ lang_name }} - -{% for item in lang_content %} - -* {{ item.title }} by {{ item.author }}. - -{% endfor %} -{% endfor %} -{% endfor %} - -## Projetos - -Últimos projetos no GitHub com o tópico `fastapi`: - -
-
diff --git a/docs/pt/docs/fastapi-cli.md b/docs/pt/docs/fastapi-cli.md new file mode 100644 index 000000000..829686631 --- /dev/null +++ b/docs/pt/docs/fastapi-cli.md @@ -0,0 +1,87 @@ +# FastAPI CLI + +**FastAPI CLI** é uma interface por linha de comando do `fastapi` que você pode usar para rodar sua app FastAPI, gerenciar seu projeto FastAPI e mais. + +Quando você instala o FastAPI (ex.: com `pip install fastapi`), isso inclui um pacote chamado `fastapi-cli`. Esse pacote disponibiliza o comando `fastapi` no terminal. + +Para rodar seu app FastAPI em desenvolvimento, você pode usar o comando `fastapi dev`: + +
+ +```console +$ fastapi dev main.py +INFO Using path main.py +INFO Resolved absolute path /home/user/code/awesomeapp/main.py +INFO Searching for package file structure from directories with __init__.py files +INFO Importing from /home/user/code/awesomeapp + + ╭─ Python module file ─╮ + │ │ + │ 🐍 main.py │ + │ │ + ╰──────────────────────╯ + +INFO Importing module main +INFO Found importable FastAPI app + + ╭─ Importable FastAPI app ─╮ + │ │ + │ from main import app │ + │ │ + ╰──────────────────────────╯ + +INFO Using import string main:app + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + fastapi run + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [2265862] using WatchFiles +INFO: Started server process [2265873] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +Aquele commando por linha de programa chamado `fastapi` é o **FastAPI CLI**. + +O FastAPI CLI recebe o caminho do seu programa Python, detecta automaticamente a variável com o FastAPI (comumente nomeada `app`) e como importá-la, e então a serve. + +Para produção você usaria `fastapi run` no lugar. 🚀 + +Internamente, **FastAPI CLI** usa Uvicorn, um servidor ASGI de alta performance e pronto para produção. 😎 + +## `fastapi dev` + +Quando você roda `fastapi dev`, isso vai executar em modo de desenvolvimento. + +Por padrão, teremos o **recarregamento automático** ativo, então o programa irá recarregar o servidor automaticamente toda vez que você fizer mudanças no seu código. Isso usa muitos recursos e pode ser menos estável. Você deve apenas usá-lo em modo de desenvolvimento. + +O servidor de desenvolvimento escutará no endereço de IP `127.0.0.1` por padrão, este é o IP que sua máquina usa para se comunicar com ela mesma (`localhost`). + +## `fastapi run` + +Quando você rodar `fastapi run`, isso executará em modo de produção por padrão. + +Este modo terá **recarregamento automático desativado** por padrão. + +Isso irá escutar no endereço de IP `0.0.0.0`, o que significa todos os endereços IP disponíveis, dessa forma o programa estará acessível publicamente para qualquer um que consiga se comunicar com a máquina. Isso é como você normalmente roda em produção em um contêiner, por exemplo. + +Em muitos casos você pode ter (e deveria ter) um "proxy de saída" tratando HTTPS no topo, isso dependerá de como você fará o deploy da sua aplicação, seu provedor pode fazer isso pra você ou talvez seja necessário fazer você mesmo. + +/// tip + +Você pode aprender mais sobre em [documentação de deployment](deployment/index.md){.internal-link target=_blank}. + +/// diff --git a/docs/pt/docs/fastapi-people.md b/docs/pt/docs/fastapi-people.md deleted file mode 100644 index 964cac68f..000000000 --- a/docs/pt/docs/fastapi-people.md +++ /dev/null @@ -1,178 +0,0 @@ -# Pessoas do FastAPI - -FastAPI possue uma comunidade incrível que recebe pessoas de todos os níveis. - -## Criador - Mantenedor - -Ei! 👋 - -Este sou eu: - -{% if people %} -
-{% for user in people.maintainers %} - -
@{{ user.login }}
Respostas: {{ user.answers }}
Pull Requests: {{ user.prs }}
-{% endfor %} - -
-{% endif %} - -Eu sou o criador e mantenedor do **FastAPI**. Você pode ler mais sobre isso em [Help FastAPI - Get Help - Connect with the author](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. - -...Mas aqui eu quero mostrar a você a comunidade. - ---- - -**FastAPI** recebe muito suporte da comunidade. E quero destacar suas contribuições. - -Estas são as pessoas que: - -* [Help others with issues (questions) in GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}. -* [Create Pull Requests](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. -* Revisar Pull Requests, [especially important for translations](contributing.md#translations){.internal-link target=_blank}. - -Uma salva de palmas para eles. 👏 🙇 - -## Usuários mais ativos do ultimo mês - -Estes são os usuários que estão [helping others the most with issues (questions) in GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank} durante o ultimo mês. ☕ - -{% if people %} -
-{% for user in people.last_month_active %} - -
@{{ user.login }}
Issues respondidas: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Especialistas - -Aqui está os **Especialistas do FastAPI**. 🤓 - - -Estes são os usuários que [helped others the most with issues (questions) in GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank} em *todo o tempo*. - -Eles provaram ser especialistas ajudando muitos outros. ✨ - -{% if people %} -
-{% for user in people.experts %} - -
@{{ user.login }}
Issues respondidas: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Top Contribuidores - -Aqui está os **Top Contribuidores**. 👷 - -Esses usuários têm [created the most Pull Requests](help-fastapi.md#create-a-pull-request){.internal-link target=_blank} que tem sido *mergeado*. - -Eles contribuíram com o código-fonte, documentação, traduções, etc. 📦 - -{% if people %} -
-{% for user in people.top_contributors %} - -
@{{ user.login }}
Pull Requests: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -Existem muitos outros contribuidores (mais de uma centena), você pode ver todos eles em Página de Contribuidores do FastAPI no GitHub. 👷 - -## Top Revisores - -Esses usuários são os **Top Revisores**. 🕵️ - -### Revisões para Traduções - -Eu só falo algumas línguas (e não muito bem 😅). Então, os revisores são aqueles que têm o [**poder de aprovar traduções**](contributing.md#translations){.internal-link target=_blank} da documentação. Sem eles, não haveria documentação em vários outros idiomas. - ---- - -Os **Top Revisores** 🕵️ revisaram a maior parte de Pull Requests de outros, garantindo a qualidade do código, documentação, e especialmente, as **traduções**. - -{% if people %} -
-{% for user in people.top_reviewers %} - -
@{{ user.login }}
Revisões: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Patrocinadores - -Esses são os **Patrocinadores**. 😎 - -Eles estão apoiando meu trabalho **FastAPI** (e outros), principalmente através de GitHub Sponsors. - -{% if sponsors %} -{% if sponsors.gold %} - -### Patrocinadores Ouro - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Patrocinadores Prata - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Patrocinadores Bronze - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -### Patrocinadores Individuais - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
- -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
- -{% endfor %} -{% endif %} - -{% endif %} - -## Sobre os dados - detalhes técnicos - -A principal intenção desta página é destacar o esforço da comunidade para ajudar os outros. - -Especialmente incluindo esforços que normalmente são menos visíveis, e em muitos casos mais árduo, como ajudar os outros com issues e revisando Pull Requests com traduções. - -Os dados são calculados todo mês, você pode ler o código fonte aqui. - -Aqui também estou destacando contribuições de patrocinadores. - -Eu também me reservo o direito de atualizar o algoritmo, seções, limites, etc (só para prevenir 🤷). diff --git a/docs/pt/docs/features.md b/docs/pt/docs/features.md index 822992c5b..a90a8094b 100644 --- a/docs/pt/docs/features.md +++ b/docs/pt/docs/features.md @@ -63,10 +63,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` quer dizer: +/// info - Passe as chaves e valores do dicionário `second_user_data` diretamente como argumentos chave-valor, equivalente a: `User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` quer dizer: + +Passe as chaves e valores do dicionário `second_user_data` diretamente como argumentos chave-valor, equivalente a: `User(id=4, name="Mary", joined="2018-11-30")` + +/// ### Suporte de editores @@ -175,7 +178,7 @@ Com **FastAPI**, você terá todos os recursos do **Starlette** (já que FastAPI ## Recursos do Pydantic -**FastAPI** é totalmente compatível com (e baseado no) Pydantic. Então, qualquer código Pydantic adicional que você tiver, também funcionará. +**FastAPI** é totalmente compatível com (e baseado no) Pydantic. Então, qualquer código Pydantic adicional que você tiver, também funcionará. Incluindo bibliotecas externas também baseadas no Pydantic, como ORMs e ODMs para bancos de dados. @@ -190,8 +193,6 @@ Com **FastAPI** você terá todos os recursos do **Pydantic** (já que FastAPI u * Se você conhece os tipos do Python, você sabe como usar o Pydantic. * Vai bem com o/a seu/sua **IDE/linter/cérebro**: * Como as estruturas de dados do Pydantic são apenas instâncias de classes que você define, a auto completação, _linting_, _mypy_ e a sua intuição devem funcionar corretamente com seus dados validados. -* **Rápido**: - * em _benchmarks_, o Pydantic é mais rápido que todas as outras bibliotecas testadas. * Valida **estruturas complexas**: * Use modelos hierárquicos do Pydantic, `List` e `Dict` do `typing` do Python, etc. * Validadores permitem que esquemas de dados complexos sejam limpos e facilmente definidos, conferidos e documentados como JSON Schema. diff --git a/docs/pt/docs/help-fastapi.md b/docs/pt/docs/help-fastapi.md index d04905197..3d6e1f9d2 100644 --- a/docs/pt/docs/help-fastapi.md +++ b/docs/pt/docs/help-fastapi.md @@ -12,7 +12,7 @@ E também existem vários modos de se conseguir ajuda. ## Inscreva-se na newsletter -Você pode se inscrever (pouco frequente) [**FastAPI e amigos** newsletter](/newsletter/){.internal-link target=_blank} para receber atualizações: +Você pode se inscrever (pouco frequente) [**FastAPI e amigos** newsletter](newsletter.md){.internal-link target=_blank} para receber atualizações: * Notícias sobre FastAPI e amigos 🚀 * Tutoriais 📝 @@ -26,13 +26,13 @@ Você pode se inscrever (pouco frequente) [**FastAPI e amigos** newsletter](/new ## Favorite o **FastAPI** no GitHub -Você pode "favoritar" o FastAPI no GitHub (clicando na estrela no canto superior direito): https://github.com/tiangolo/fastapi. ⭐️ +Você pode "favoritar" o FastAPI no GitHub (clicando na estrela no canto superior direito): https://github.com/fastapi/fastapi. ⭐️ Favoritando, outros usuários poderão encontrar mais facilmente e verão que já foi útil para muita gente. ## Acompanhe novos updates no repositorio do GitHub -Você pode "acompanhar" (watch) o FastAPI no GitHub (clicando no botão com um "olho" no canto superior direito): https://github.com/tiangolo/fastapi. 👀 +Você pode "acompanhar" (watch) o FastAPI no GitHub (clicando no botão com um "olho" no canto superior direito): https://github.com/fastapi/fastapi. 👀 Podendo selecionar apenas "Novos Updates". @@ -59,7 +59,7 @@ Você pode: ## Tweete sobre **FastAPI** -Tweete sobre o **FastAPI** e compartilhe comigo e com os outros o porque de gostar do FastAPI. 🎉 +Tweete sobre o **FastAPI** e compartilhe comigo e com os outros o porque de gostar do FastAPI. 🎉 Adoro ouvir sobre como o **FastAPI** é usado, o que você gosta nele, em qual projeto/empresa está sendo usado, etc. @@ -70,13 +70,13 @@ Adoro ouvir sobre como o **FastAPI** é usado, o que você gosta nele, em qual p ## Responda perguntas no GitHub -Você pode acompanhar as perguntas existentes e tentar ajudar outros, . 🤓 +Você pode acompanhar as perguntas existentes e tentar ajudar outros, . 🤓 -Ajudando a responder as questões de varias pessoas, você pode se tornar um [Expert em FastAPI](fastapi-people.md#experts){.internal-link target=_blank} oficial. 🎉 +Ajudando a responder as questões de varias pessoas, você pode se tornar um [Expert em FastAPI](fastapi-people.md#especialistas){.internal-link target=_blank} oficial. 🎉 ## Acompanhe o repositório do GitHub -Você pode "acompanhar" (watch) o FastAPI no GitHub (clicando no "olho" no canto superior direito): https://github.com/tiangolo/fastapi. 👀 +Você pode "acompanhar" (watch) o FastAPI no GitHub (clicando no "olho" no canto superior direito): https://github.com/fastapi/fastapi. 👀 Se você selecionar "Acompanhando" (Watching) em vez de "Apenas Lançamentos" (Releases only) você receberá notificações quando alguém tiver uma nova pergunta. @@ -84,7 +84,7 @@ Assim podendo tentar ajudar a resolver essas questões. ## Faça perguntas -É possível criar uma nova pergunta no repositório do GitHub, por exemplo: +É possível criar uma nova pergunta no repositório do GitHub, por exemplo: * Faça uma **pergunta** ou pergunte sobre um **problema**. * Sugira novos **recursos**. @@ -96,9 +96,9 @@ Assim podendo tentar ajudar a resolver essas questões. É possível [contribuir](contributing.md){.internal-link target=_blank} no código fonte fazendo Pull Requests, por exemplo: * Para corrigir um erro de digitação que você encontrou na documentação. -* Para compartilhar um artigo, video, ou podcast criados por você sobre o FastAPI editando este arquivo. +* Para compartilhar um artigo, video, ou podcast criados por você sobre o FastAPI editando este arquivo. * Não se esqueça de adicionar o link no começo da seção correspondente. -* Para ajudar [traduzir a documentação](contributing.md#translations){.internal-link target=_blank} para sua lingua. +* Para ajudar [traduzir a documentação](contributing.md#traducoes){.internal-link target=_blank} para sua lingua. * Também é possivel revisar as traduções já existentes. * Para propor novas seções na documentação. * Para corrigir um bug/questão. @@ -109,10 +109,13 @@ Assim podendo tentar ajudar a resolver essas questões. Entre no 👥 server de conversa do Discord 👥 e conheça novas pessoas da comunidade do FastAPI. -!!! dica - Para perguntas, pergunte nas questões do GitHub, lá tem um chance maior de você ser ajudado sobre o FastAPI [FastAPI Experts](fastapi-people.md#experts){.internal-link target=_blank}. +/// tip | Dica - Use o chat apenas para outro tipo de assunto. +Para perguntas, pergunte nas questões do GitHub, lá tem um chance maior de você ser ajudado sobre o FastAPI [FastAPI Experts](fastapi-people.md#especialistas){.internal-link target=_blank}. + +Use o chat apenas para outro tipo de assunto. + +/// ### Não faça perguntas no chat @@ -120,7 +123,7 @@ Tenha em mente que os chats permitem uma "conversa mais livre", dessa forma é m Nas questões do GitHub o template irá te guiar para que você faça a sua pergunta de um jeito mais correto, fazendo com que você receba respostas mais completas, e até mesmo que você mesmo resolva o problema antes de perguntar. E no GitHub eu garanto que sempre irei responder todas as perguntas, mesmo que leve um tempo. Eu pessoalmente não consigo fazer isso via chat. 😅 -Conversas no chat não são tão fáceis de serem encontrados quanto no GitHub, então questões e respostas podem se perder dentro da conversa. E apenas as que estão nas questões do GitHub contam para você se tornar um [Expert em FastAPI](fastapi-people.md#experts){.internal-link target=_blank}, então você receberá mais atenção nas questões do GitHub. +Conversas no chat não são tão fáceis de serem encontrados quanto no GitHub, então questões e respostas podem se perder dentro da conversa. E apenas as que estão nas questões do GitHub contam para você se tornar um [Expert em FastAPI](fastapi-people.md#especialistas){.internal-link target=_blank}, então você receberá mais atenção nas questões do GitHub. Por outro lado, existem milhares de usuários no chat, então tem uma grande chance de você encontrar alguém para trocar uma idéia por lá em qualquer horário. 😄 diff --git a/docs/pt/docs/history-design-future.md b/docs/pt/docs/history-design-future.md index 45427ec63..4ec217405 100644 --- a/docs/pt/docs/history-design-future.md +++ b/docs/pt/docs/history-design-future.md @@ -1,6 +1,6 @@ # História, Design e Futuro -Há algum tempo, um usuário **FastAPI** perguntou: +Há algum tempo, um usuário **FastAPI** perguntou: > Qual é a história desse projeto? Parece que surgiu do nada e se tornou incrível em poucas semanas [...] @@ -54,7 +54,7 @@ Tudo de uma forma que oferecesse a melhor experiência de desenvolvimento para t ## Requisitos -Após testar várias alternativas, eu decidi que usaria o **Pydantic** por suas vantagens. +Após testar várias alternativas, eu decidi que usaria o **Pydantic** por suas vantagens. Então eu contribuí com ele, para deixá-lo completamente de acordo com o JSON Schema, para dar suporte a diferentes maneiras de definir declarações de restrições, e melhorar o suporte a editores (conferências de tipos, auto completações) baseado nos testes em vários editores. diff --git a/docs/pt/docs/how-to/conditional-openapi.md b/docs/pt/docs/how-to/conditional-openapi.md new file mode 100644 index 000000000..6b44e9c81 --- /dev/null +++ b/docs/pt/docs/how-to/conditional-openapi.md @@ -0,0 +1,56 @@ +# OpenAPI condicional + +Se necessário, você pode usar configurações e variáveis ​​de ambiente para configurar o OpenAPI condicionalmente, dependendo do ambiente, e até mesmo desativá-lo completamente. + +## Sobre segurança, APIs e documentos + +Ocultar suas interfaces de usuário de documentação na produção *não deveria* ser a maneira de proteger sua API. + +Isso não adiciona nenhuma segurança extra à sua API; as *operações de rotas* ainda estarão disponíveis onde estão. + +Se houver uma falha de segurança no seu código, ela ainda existirá. + +Ocultar a documentação apenas torna mais difícil entender como interagir com sua API e pode dificultar sua depuração na produção. Pode ser considerado simplesmente uma forma de Segurança através da obscuridade. + +Se você quiser proteger sua API, há várias coisas melhores que você pode fazer, por exemplo: + +* Certifique-se de ter modelos Pydantic bem definidos para seus corpos de solicitação e respostas. +* Configure quaisquer permissões e funções necessárias usando dependências. +* Nunca armazene senhas em texto simples, apenas hashes de senha. +* Implemente e use ferramentas criptográficas bem conhecidas, como tokens JWT e Passlib, etc. +* Adicione controles de permissão mais granulares com escopos OAuth2 quando necessário. +* ...etc. + +No entanto, você pode ter um caso de uso muito específico em que realmente precisa desabilitar a documentação da API para algum ambiente (por exemplo, para produção) ou dependendo de configurações de variáveis ​​de ambiente. + +## OpenAPI condicional com configurações e variáveis ​​de ambiente + +Você pode usar facilmente as mesmas configurações do Pydantic para configurar sua OpenAPI gerada e as interfaces de usuário de documentos. + +Por exemplo: + +{* ../../docs_src/conditional_openapi/tutorial001.py hl[6,11] *} + +Aqui declaramos a configuração `openapi_url` com o mesmo padrão de `"/openapi.json"`. + +E então o usamos ao criar o aplicativo `FastAPI`. + +Então você pode desabilitar o OpenAPI (incluindo os documentos da interface do usuário) definindo a variável de ambiente `OPENAPI_URL` como uma string vazia, como: + +
+ +```console +$ OPENAPI_URL= uvicorn main:app + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Então, se você acessar as URLs em `/openapi.json`, `/docs` ou `/redoc`, você receberá apenas um erro `404 Não Encontrado` como: + +```JSON +{ + "detail": "Not Found" +} +``` diff --git a/docs/pt/docs/how-to/configure-swagger-ui.md b/docs/pt/docs/how-to/configure-swagger-ui.md new file mode 100644 index 000000000..915b2b5c5 --- /dev/null +++ b/docs/pt/docs/how-to/configure-swagger-ui.md @@ -0,0 +1,70 @@ +# Configurar Swagger UI + +Você pode configurar alguns parâmetros extras da UI do Swagger. + +Para configurá-los, passe o argumento `swagger_ui_parameters` ao criar o objeto de aplicativo `FastAPI()` ou para a função `get_swagger_ui_html()`. + +`swagger_ui_parameters` recebe um dicionário com as configurações passadas diretamente para o Swagger UI. + +O FastAPI converte as configurações para **JSON** para torná-las compatíveis com JavaScript, pois é disso que o Swagger UI precisa. + +## Desabilitar realce de sintaxe + +Por exemplo, você pode desabilitar o destaque de sintaxe na UI do Swagger. + +Sem alterar as configurações, o destaque de sintaxe é habilitado por padrão: + + + +Mas você pode desabilitá-lo definindo `syntaxHighlight` como `False`: + +{* ../../docs_src/configure_swagger_ui/tutorial001.py hl[3] *} + +...e então o Swagger UI não mostrará mais o destaque de sintaxe: + + + +## Alterar o tema + +Da mesma forma que você pode definir o tema de destaque de sintaxe com a chave `"syntaxHighlight.theme"` (observe que há um ponto no meio): + +{* ../../docs_src/configure_swagger_ui/tutorial002.py hl[3] *} + +Essa configuração alteraria o tema de cores de destaque de sintaxe: + + + +## Alterar parâmetros de UI padrão do Swagger + +O FastAPI inclui alguns parâmetros de configuração padrão apropriados para a maioria dos casos de uso. + +Inclui estas configurações padrão: + +{* ../../fastapi/openapi/docs.py ln[7:23] *} + +Você pode substituir qualquer um deles definindo um valor diferente no argumento `swagger_ui_parameters`. + +Por exemplo, para desabilitar `deepLinking` você pode passar essas configurações para `swagger_ui_parameters`: + +{* ../../docs_src/configure_swagger_ui/tutorial003.py hl[3] *} + +## Outros parâmetros da UI do Swagger + +Para ver todas as outras configurações possíveis que você pode usar, leia a documentação oficial dos parâmetros da UI do Swagger. + +## Configurações somente JavaScript + +A interface do usuário do Swagger também permite que outras configurações sejam objetos **somente JavaScript** (por exemplo, funções JavaScript). + +O FastAPI também inclui estas configurações de `predefinições` somente para JavaScript: + +```JavaScript +presets: [ + SwaggerUIBundle.presets.apis, + SwaggerUIBundle.SwaggerUIStandalonePreset +] +``` + +Esses são objetos **JavaScript**, não strings, então você não pode passá-los diretamente do código Python. + +Se você precisar usar configurações somente JavaScript como essas, você pode usar um dos métodos acima. Sobrescreva todas as *operações de rotas* do Swagger UI e escreva manualmente qualquer JavaScript que você precisar. diff --git a/docs/pt/docs/how-to/custom-docs-ui-assets.md b/docs/pt/docs/how-to/custom-docs-ui-assets.md new file mode 100644 index 000000000..3adc7529e --- /dev/null +++ b/docs/pt/docs/how-to/custom-docs-ui-assets.md @@ -0,0 +1,191 @@ +# Recursos Estáticos Personalizados para a UI de Documentação (Hospedagem Própria) + +A documentação da API usa **Swagger UI** e **ReDoc**, e cada um deles precisa de alguns arquivos JavaScript e CSS. + +Por padrão, esses arquivos são fornecidos por um CDN. + +Mas é possível personalizá-los, você pode definir um CDN específico ou providenciar os arquivos você mesmo. + +## CDN Personalizado para JavaScript e CSS + +Vamos supor que você deseja usar um CDN diferente, por exemplo, você deseja usar `https://unpkg.com/`. + +Isso pode ser útil se, por exemplo, você mora em um país que restringe algumas URLs. + +### Desativar a documentação automática + +O primeiro passo é desativar a documentação automática, pois por padrão, ela usa o CDN padrão. + +Para desativá-los, defina suas URLs como `None` ao criar seu aplicativo `FastAPI`: + +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[8] *} + +### Incluir a documentação personalizada + +Agora você pode criar as *operações de rota* para a documentação personalizada. + +Você pode reutilizar as funções internas do FastAPI para criar as páginas HTML para a documentação e passar os argumentos necessários: + +* `openapi_url`: a URL onde a página HTML para a documentação pode obter o esquema OpenAPI para a sua API. Você pode usar aqui o atributo `app.openapi_url`. +* `title`: o título da sua API. +* `oauth2_redirect_url`: você pode usar `app.swagger_ui_oauth2_redirect_url` aqui para usar o padrão. +* `swagger_js_url`: a URL onde a página HTML para a sua documentação do Swagger UI pode obter o arquivo **JavaScript**. Este é o URL do CDN personalizado. +* `swagger_css_url`: a URL onde a página HTML para a sua documentação do Swagger UI pode obter o arquivo **CSS**. Este é o URL do CDN personalizado. + +E de forma semelhante para o ReDoc... + +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[2:6,11:19,22:24,27:33] *} + +/// tip | Dica + +A *operação de rota* para `swagger_ui_redirect` é um auxiliar para quando você usa OAuth2. + +Se você integrar sua API com um provedor OAuth2, você poderá autenticar e voltar para a documentação da API com as credenciais adquiridas. E interagir com ela usando a autenticação OAuth2 real. + +Swagger UI lidará com isso nos bastidores para você, mas ele precisa desse auxiliar de "redirecionamento". + +/// + +### Criar uma *operação de rota* para testar + +Agora, para poder testar se tudo funciona, crie uma *operação de rota*: + +{* ../../docs_src/custom_docs_ui/tutorial001.py hl[36:38] *} + +### Teste + +Agora, você deve ser capaz de ir para a documentação em http://127.0.0.1:8000/docs, e recarregar a página, ela carregará esses recursos do novo CDN. + +## Hospedagem Própria de JavaScript e CSS para a documentação + +Hospedar o JavaScript e o CSS pode ser útil se, por exemplo, você precisa que seu aplicativo continue funcionando mesmo offline, sem acesso aberto à Internet, ou em uma rede local. + +Aqui você verá como providenciar esses arquivos você mesmo, no mesmo aplicativo FastAPI, e configurar a documentação para usá-los. + +### Estrutura de Arquivos do Projeto + +Vamos supor que a estrutura de arquivos do seu projeto se pareça com isso: + +``` +. +├── app +│ ├── __init__.py +│ ├── main.py +``` + +Agora crie um diretório para armazenar esses arquivos estáticos. + +Sua nova estrutura de arquivos poderia se parecer com isso: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +└── static/ +``` + +### Baixe os arquivos + +Baixe os arquivos estáticos necessários para a documentação e coloque-os no diretório `static/`. + +Você provavelmente pode clicar com o botão direito em cada link e selecionar uma opção semelhante a `Salvar link como...`. + +**Swagger UI** usa os arquivos: + +* `swagger-ui-bundle.js` +* `swagger-ui.css` + +E o **ReDoc** usa os arquivos: + +* `redoc.standalone.js` + +Depois disso, sua estrutura de arquivos deve se parecer com: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +└── static + ├── redoc.standalone.js + ├── swagger-ui-bundle.js + └── swagger-ui.css +``` + +### Prover os arquivos estáticos + +* Importe `StaticFiles`. +* "Monte" a instância `StaticFiles()` em um caminho específico. + +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[7,11] *} + +### Teste os arquivos estáticos + +Inicialize seu aplicativo e vá para http://127.0.0.1:8000/static/redoc.standalone.js. + +Você deverá ver um arquivo JavaScript muito longo para o **ReDoc**. + +Esse arquivo pode começar com algo como: + +```JavaScript +/*! + * ReDoc - OpenAPI/Swagger-generated API Reference Documentation + * ------------------------------------------------------------- + * Version: "2.0.0-rc.18" + * Repo: https://github.com/Redocly/redoc + */ +!function(e,t){"object"==typeof exports&&"object"==typeof m + +... +``` + +Isso confirma que você está conseguindo fornecer arquivos estáticos do seu aplicativo e que você colocou os arquivos estáticos para a documentação no local correto. + +Agora, podemos configurar o aplicativo para usar esses arquivos estáticos para a documentação. + +### Desativar a documentação automática para arquivos estáticos + +Da mesma forma que ao usar um CDN personalizado, o primeiro passo é desativar a documentação automática, pois ela usa o CDN padrão. + +Para desativá-los, defina suas URLs como `None` ao criar seu aplicativo `FastAPI`: + +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[9] *} + +### Incluir a documentação personalizada para arquivos estáticos + +E da mesma forma que com um CDN personalizado, agora você pode criar as *operações de rota* para a documentação personalizada. + +Novamente, você pode reutilizar as funções internas do FastAPI para criar as páginas HTML para a documentação e passar os argumentos necessários: + +* `openapi_url`: a URL onde a página HTML para a documentação pode obter o esquema OpenAPI para a sua API. Você pode usar aqui o atributo `app.openapi_url`. +* `title`: o título da sua API. +* `oauth2_redirect_url`: Você pode usar `app.swagger_ui_oauth2_redirect_url` aqui para usar o padrão. +* `swagger_js_url`: a URL onde a página HTML para a sua documentação do Swagger UI pode obter o arquivo **JavaScript**. Este é o URL do CDN personalizado. **Este é o URL que seu aplicativo está fornecendo**. +* `swagger_css_url`: a URL onde a página HTML para a sua documentação do Swagger UI pode obter o arquivo **CSS**. **Esse é o que seu aplicativo está fornecendo**. + +E de forma semelhante para o ReDoc... + +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[2:6,14:22,25:27,30:36] *} + +/// tip | Dica + +A *operação de rota* para `swagger_ui_redirect` é um auxiliar para quando você usa OAuth2. + +Se você integrar sua API com um provedor OAuth2, você poderá autenticar e voltar para a documentação da API com as credenciais adquiridas. E, então, interagir com ela usando a autenticação OAuth2 real. + +Swagger UI lidará com isso nos bastidores para você, mas ele precisa desse auxiliar de "redirect". + +/// + +### Criar uma *operação de rota* para testar arquivos estáticos + +Agora, para poder testar se tudo funciona, crie uma *operação de rota*: + +{* ../../docs_src/custom_docs_ui/tutorial002.py hl[39:41] *} + +### Teste a UI de Arquivos Estáticos + +Agora, você deve ser capaz de desconectar o WiFi, ir para a documentação em http://127.0.0.1:8000/docs, e recarregar a página. + +E mesmo sem Internet, você será capaz de ver a documentação da sua API e interagir com ela. diff --git a/docs/pt/docs/how-to/custom-request-and-route.md b/docs/pt/docs/how-to/custom-request-and-route.md new file mode 100644 index 000000000..8f432f6fe --- /dev/null +++ b/docs/pt/docs/how-to/custom-request-and-route.md @@ -0,0 +1,109 @@ +# Requisições Personalizadas e Classes da APIRoute + +Em algum casos, você pode querer sobreescrever a lógica usada pelas classes `Request`e `APIRoute`. + +Em particular, isso pode ser uma boa alternativa para uma lógica em um middleware + +Por exemplo, se você quiser ler ou manipular o corpo da requisição antes que ele seja processado pela sua aplicação. + +/// danger | Perigo + +Isso é um recurso "avançado". + +Se você for um iniciante em **FastAPI** você deve considerar pular essa seção. + +/// + +## Casos de Uso + +Alguns casos de uso incluem: + +* Converter requisições não-JSON para JSON (por exemplo, `msgpack`). +* Descomprimir corpos de requisição comprimidos com gzip. +* Registrar automaticamente todos os corpos de requisição. + +## Manipulando codificações de corpo de requisição personalizadas + +Vamos ver como usar uma subclasse personalizada de `Request` para descomprimir requisições gzip. + +E uma subclasse de `APIRoute` para usar essa classe de requisição personalizada. + +### Criar uma classe `GzipRequest` personalizada + +/// tip | Dica + +Isso é um exemplo de brincadeira para demonstrar como funciona, se você precisar de suporte para Gzip, você pode usar o [`GzipMiddleware`](../advanced/middleware.md#gzipmiddleware){.internal-link target=_blank} fornecido. + +/// + +Primeiro, criamos uma classe `GzipRequest`, que irá sobrescrever o método `Request.body()` para descomprimir o corpo na presença de um cabeçalho apropriado. + +Se não houver `gzip` no cabeçalho, ele não tentará descomprimir o corpo. + +Dessa forma, a mesma classe de rota pode lidar com requisições comprimidas ou não comprimidas. + +{* ../../docs_src/custom_request_and_route/tutorial001.py hl[8:15] *} + +### Criar uma classe `GzipRoute` personalizada + +Em seguida, criamos uma subclasse personalizada de `fastapi.routing.APIRoute` que fará uso do `GzipRequest`. + +Dessa vez, ele irá sobrescrever o método `APIRoute.get_route_handler()`. + +Esse método retorna uma função. E essa função é o que irá receber uma requisição e retornar uma resposta. + +Aqui nós usamos para criar um `GzipRequest` a partir da requisição original. + +{* ../../docs_src/custom_request_and_route/tutorial001.py hl[18:26] *} + +/// note | Detalhes Técnicos + +Um `Request` também tem um `request.receive`, que é uma função para "receber" o corpo da requisição. + +Um `Request` também tem um `request.receive`, que é uma função para "receber" o corpo da requisição. + +O dicionário `scope` e a função `receive` são ambos parte da especificação ASGI. + +E essas duas coisas, `scope` e `receive`, são o que é necessário para criar uma nova instância de `Request`. + +Para aprender mais sobre o `Request` confira a documentação do Starlette sobre Requests. + +/// + +A única coisa que a função retornada por `GzipRequest.get_route_handler` faz de diferente é converter o `Request` para um `GzipRequest`. + +Fazendo isso, nosso `GzipRequest` irá cuidar de descomprimir os dados (se necessário) antes de passá-los para nossas *operações de rota*. + +Depois disso, toda a lógica de processamento é a mesma. + +Mas por causa das nossas mudanças em `GzipRequest.body`, o corpo da requisição será automaticamente descomprimido quando for carregado pelo **FastAPI** quando necessário. + +## Acessando o corpo da requisição em um manipulador de exceção + +/// tip | Dica + +Para resolver esse mesmo problema, é provavelmente muito mais fácil usar o `body` em um manipulador personalizado para `RequestValidationError` ([Tratando Erros](../tutorial/handling-errors.md#use-the-requestvalidationerror-body){.internal-link target=_blank}). + +Mas esse exemplo ainda é valido e mostra como interagir com os componentes internos. + +/// + +Também podemos usar essa mesma abordagem para acessar o corpo da requisição em um manipulador de exceção. + +Tudo que precisamos fazer é manipular a requisição dentro de um bloco `try`/`except`: + +{* ../../docs_src/custom_request_and_route/tutorial002.py hl[13,15] *} + +Se uma exceção ocorrer, a instância `Request` ainda estará em escopo, então podemos ler e fazer uso do corpo da requisição ao lidar com o erro: + +{* ../../docs_src/custom_request_and_route/tutorial002.py hl[16:18] *} + +## Classe `APIRoute` personalizada em um router + +você também pode definir o parametro `route_class` de uma `APIRouter`; + +{* ../../docs_src/custom_request_and_route/tutorial003.py hl[26] *} + +Nesse exemplo, as *operações de rota* sob o `router` irão usar a classe `TimedRoute` personalizada, e terão um cabeçalho extra `X-Response-Time` na resposta com o tempo que levou para gerar a resposta: + +{* ../../docs_src/custom_request_and_route/tutorial003.py hl[13:20] *} diff --git a/docs/pt/docs/how-to/extending-openapi.md b/docs/pt/docs/how-to/extending-openapi.md new file mode 100644 index 000000000..b4785edc1 --- /dev/null +++ b/docs/pt/docs/how-to/extending-openapi.md @@ -0,0 +1,80 @@ +# Extendendo o OpenAPI + +Existem alguns casos em que pode ser necessário modificar o esquema OpenAPI gerado. + +Nesta seção, você verá como fazer isso. + +## O processo normal + +O processo normal (padrão) é o seguinte: + +Uma aplicação (instância) do `FastAPI` possui um método `.openapi()` que deve retornar o esquema OpenAPI. + +Como parte da criação do objeto de aplicação, uma *operação de rota* para `/openapi.json` (ou para o que você definir como `openapi_url`) é registrada. + +Ela apenas retorna uma resposta JSON com o resultado do método `.openapi()` da aplicação. + +Por padrão, o que o método `.openapi()` faz é verificar se a propriedade `.openapi_schema` tem conteúdo e retorná-lo. + +Se não tiver, ele gera o conteúdo usando a função utilitária em `fastapi.openapi.utils.get_openapi`. + +E essa função `get_openapi()` recebe como parâmetros: + +* `title`: O título do OpenAPI, exibido na documentação. +* `version`: A versão da sua API, por exemplo, `2.5.0`. +* `openapi_version`: A versão da especificação OpenAPI utilizada. Por padrão, a mais recente: `3.1.0`. +* `summary`: Um resumo curto da API. +* `description`: A descrição da sua API, que pode incluir markdown e será exibida na documentação. +* `routes`: Uma lista de rotas, que são cada uma das *operações de rota* registradas. Elas são obtidas de `app.routes`. + +/// info | Informação + +O parâmetro `summary` está disponível no OpenAPI 3.1.0 e superior, suportado pelo FastAPI 0.99.0 e superior. + +/// + +## Sobrescrevendo os padrões + +Com as informações acima, você pode usar a mesma função utilitária para gerar o esquema OpenAPI e sobrescrever cada parte que precisar. + +Por exemplo, vamos adicionar Extensão OpenAPI do ReDoc para incluir um logo personalizado. + +### **FastAPI** Normal + +Primeiro, escreva toda a sua aplicação **FastAPI** normalmente: + +{* ../../docs_src/extending_openapi/tutorial001.py hl[1,4,7:9] *} + +### Gerar o esquema OpenAPI + +Em seguida, use a mesma função utilitária para gerar o esquema OpenAPI, dentro de uma função `custom_openapi()`: + +{* ../../docs_src/extending_openapi/tutorial001.py hl[2,15:21] *} + +### Modificar o esquema OpenAPI + +Agora, você pode adicionar a extensão do ReDoc, incluindo um `x-logo` personalizado ao "objeto" `info` no esquema OpenAPI: + +{* ../../docs_src/extending_openapi/tutorial001.py hl[22:24] *} + +### Armazenar em cache o esquema OpenAPI + +Você pode usar a propriedade `.openapi_schema` como um "cache" para armazenar o esquema gerado. + +Dessa forma, sua aplicação não precisará gerar o esquema toda vez que um usuário abrir a documentação da sua API. + +Ele será gerado apenas uma vez, e o mesmo esquema armazenado em cache será utilizado nas próximas requisições. + +{* ../../docs_src/extending_openapi/tutorial001.py hl[13:14,25:26] *} + +### Sobrescrever o método + +Agora, você pode substituir o método `.openapi()` pela sua nova função. + +{* ../../docs_src/extending_openapi/tutorial001.py hl[29] *} + +### Verificar + +Uma vez que você acessar http://127.0.0.1:8000/redoc, verá que está usando seu logo personalizado (neste exemplo, o logo do **FastAPI**): + + diff --git a/docs/pt/docs/how-to/general.md b/docs/pt/docs/how-to/general.md new file mode 100644 index 000000000..4f21463b2 --- /dev/null +++ b/docs/pt/docs/how-to/general.md @@ -0,0 +1,39 @@ +# Geral - Como Fazer - Receitas + +Aqui estão vários links para outros locais na documentação, para perguntas gerais ou frequentes + +## Filtro de dados- Segurança + +Para assegurar que você não vai retornar mais dados do que deveria, leia a seção [Tutorial - Response Model - Return Type](../tutorial/response-model.md){.internal-link target=_blank}. + +## Tags de Documentação - OpenAPI +Para adicionar tags às suas *rotas* e agrupá-las na UI da documentação, leia a seção [Tutorial - Path Operation Configurations - Tags](../tutorial/path-operation-configuration.md#tags){.internal-link target=_blank}. + +## Resumo e Descrição da documentação - OpenAPI + +Para adicionar um resumo e uma descrição às suas *rotas* e exibi-los na UI da documentação, leia a seção [Tutorial - Path Operation Configurations - Summary and Description](../tutorial/path-operation-configuration.md#summary-and-description){.internal-link target=_blank}. + +## Documentação das Descrições de Resposta - OpenAPI + +Para definir a descrição de uma resposta exibida na interface da documentação, leia a seção [Tutorial - Path Operation Configurations - Response description](../tutorial/path-operation-configuration.md#response-description){.internal-link target=_blank}. + +## Documentação para Depreciar uma *Operação de Rota* - OpenAPI + +Para depreciar uma *operação de rota* e exibi-la na interface da documentação, leia a seção [Tutorial - Path Operation Configurations - Deprecation](../tutorial/path-operation-configuration.md#deprecate-a-path-operation){.internal-link target=_blank}. + +## Converter qualquer dado para JSON + + +Para converter qualquer dado para um formato compatível com JSON, leia a seção [Tutorial - JSON Compatible Encoder](../tutorial/encoder.md){.internal-link target=_blank}. + +## OpenAPI Metadata - Docs + +Para adicionar metadados ao seu esquema OpenAPI, incluindo licensa, versão, contato, etc, leia a seção [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md){.internal-link target=_blank}. + +## OpenAPI com URL customizada + +Para customizar a URL do OpenAPI (ou removê-la), leia a seção [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md#openapi-url){.internal-link target=_blank}. + +## URLs de documentação do OpenAPI + +Para alterar as URLs usadas ​​para as interfaces de usuário da documentação gerada automaticamente, leia a seção [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md#docs-urls){.internal-link target=_blank}. diff --git a/docs/pt/docs/how-to/graphql.md b/docs/pt/docs/how-to/graphql.md new file mode 100644 index 000000000..ef0bad7f6 --- /dev/null +++ b/docs/pt/docs/how-to/graphql.md @@ -0,0 +1,60 @@ +# GraphQL + +Como o **FastAPI** é baseado no padrão **ASGI**, é muito fácil integrar qualquer biblioteca **GraphQL** também compatível com ASGI. + +Você pode combinar *operações de rota* normais do FastAPI com GraphQL na mesma aplicação. + +/// tip | Dica + +**GraphQL** resolve alguns casos de uso muito específicos. + +Ele tem **vantagens** e **desvantagens** quando comparado a **web APIs** comuns. + +Certifique-se de avaliar se os **benefícios** para o seu caso de uso compensam as **desvantagens**. 🤓 + +/// + +## Bibliotecas GraphQL + +Aqui estão algumas das bibliotecas **GraphQL** que têm suporte **ASGI**. Você pode usá-las com **FastAPI**: + +* Strawberry 🍓 + * Com docs para FastAPI +* Ariadne + * Com docs para FastAPI +* Tartiflette + * Com Tartiflette ASGI para fornecer integração ASGI +* Graphene + * Com starlette-graphene3 + +## GraphQL com Strawberry + +Se você precisar ou quiser trabalhar com **GraphQL**, **Strawberry** é a biblioteca **recomendada** pois tem o design mais próximo ao design do **FastAPI**, ela é toda baseada em **type annotations**. + +Dependendo do seu caso de uso, você pode preferir usar uma biblioteca diferente, mas se você me perguntasse, eu provavelmente sugeriria que você experimentasse o **Strawberry**. + +Aqui está uma pequena prévia de como você poderia integrar Strawberry com FastAPI: + +{* ../../docs_src/graphql/tutorial001.py hl[3,22,25:26] *} + +Você pode aprender mais sobre Strawberry na documentação do Strawberry. + +E também na documentação sobre Strawberry com FastAPI. + +## Antigo `GraphQLApp` do Starlette + +Versões anteriores do Starlette incluiam uma classe `GraphQLApp` para integrar com Graphene. + +Ela foi descontinuada do Starlette, mas se você tem código que a utilizava, você pode facilmente **migrar** para starlette-graphene3, que cobre o mesmo caso de uso e tem uma **interface quase idêntica**. + +/// tip | Dica + +Se você precisa de GraphQL, eu ainda recomendaria que você desse uma olhada no Strawberry, pois ele é baseado em type annotations em vez de classes e tipos personalizados. + +/// + +## Saiba Mais + +Você pode aprender mais sobre **GraphQL** na documentação oficial do GraphQL. + +Você também pode ler mais sobre cada uma das bibliotecas descritas acima em seus links. diff --git a/docs/pt/docs/how-to/index.md b/docs/pt/docs/how-to/index.md new file mode 100644 index 000000000..6747b01c7 --- /dev/null +++ b/docs/pt/docs/how-to/index.md @@ -0,0 +1,13 @@ +# Como Fazer - Exemplos Práticos + +Aqui você encontrará diferentes exemplos práticos ou tutoriais de "como fazer" para vários tópicos. + +A maioria dessas ideias será mais ou menos **independente**, e na maioria dos casos você só precisará estudá-las se elas se aplicarem diretamente ao **seu projeto**. + +Se algo parecer interessante e útil para o seu projeto, vá em frente e dê uma olhada. Caso contrário, você pode simplesmente ignorá-lo. + +/// tip + +Se você deseja **aprender FastAPI** de forma estruturada (recomendado), leia capítulo por capítulo [Tutorial - Guia de Usuário](../tutorial/index.md){.internal-link target=_blank} em vez disso. + +/// diff --git a/docs/pt/docs/how-to/separate-openapi-schemas.md b/docs/pt/docs/how-to/separate-openapi-schemas.md new file mode 100644 index 000000000..291b0e163 --- /dev/null +++ b/docs/pt/docs/how-to/separate-openapi-schemas.md @@ -0,0 +1,104 @@ +# Esquemas OpenAPI Separados para Entrada e Saída ou Não + +Ao usar **Pydantic v2**, o OpenAPI gerado é um pouco mais exato e **correto** do que antes. 😎 + +Inclusive, em alguns casos, ele terá até **dois JSON Schemas** no OpenAPI para o mesmo modelo Pydantic, para entrada e saída, dependendo se eles possuem **valores padrão**. + +Vamos ver como isso funciona e como alterar se for necessário. + +## Modelos Pydantic para Entrada e Saída + +Digamos que você tenha um modelo Pydantic com valores padrão, como este: + +{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:7] hl[7] *} + +### Modelo para Entrada + +Se você usar esse modelo como entrada, como aqui: + +{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py ln[1:15] hl[14] *} + +... então o campo `description` não será obrigatório. Porque ele tem um valor padrão de `None`. + +### Modelo de Entrada na Documentação + +Você pode confirmar que na documentação, o campo `description` não tem um **asterisco vermelho**, não é marcado como obrigatório: + +
+ +
+ +### Modelo para Saída + +Mas se você usar o mesmo modelo como saída, como aqui: + +{* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py hl[19] *} + +... então, como `description` tem um valor padrão, se você **não retornar nada** para esse campo, ele ainda terá o **valor padrão**. + +### Modelo para Dados de Resposta de Saída + +Se você interagir com a documentação e verificar a resposta, mesmo que o código não tenha adicionado nada em um dos campos `description`, a resposta JSON contém o valor padrão (`null`): + +
+ +
+ +Isso significa que ele **sempre terá um valor**, só que às vezes o valor pode ser `None` (ou `null` em termos de JSON). + +Isso quer dizer que, os clientes que usam sua API não precisam verificar se o valor existe ou não, eles podem **assumir que o campo sempre estará lá**, mas que em alguns casos terá o valor padrão de `None`. + +A maneira de descrever isso no OpenAPI é marcar esse campo como **obrigatório**, porque ele sempre estará lá. + +Por causa disso, o JSON Schema para um modelo pode ser diferente dependendo se ele é usado para **entrada ou saída**: + +* para **entrada**, o `description` **não será obrigatório** +* para **saída**, ele será **obrigatório** (e possivelmente `None`, ou em termos de JSON, `null`) + +### Modelo para Saída na Documentação + +Você pode verificar o modelo de saída na documentação também, ambos `name` e `description` são marcados como **obrigatórios** com um **asterisco vermelho**: + +
+ +
+ +### Modelo para Entrada e Saída na Documentação + +E se você verificar todos os Schemas disponíveis (JSON Schemas) no OpenAPI, verá que há dois, um `Item-Input` e um `Item-Output`. + +Para `Item-Input`, `description` **não é obrigatório**, não tem um asterisco vermelho. + +Mas para `Item-Output`, `description` **é obrigatório**, tem um asterisco vermelho. + +
+ +
+ +Com esse recurso do **Pydantic v2**, sua documentação da API fica mais **precisa**, e se você tiver clientes e SDKs gerados automaticamente, eles serão mais precisos também, proporcionando uma melhor **experiência para desenvolvedores** e consistência. 🎉 + +## Não Separe Schemas + +Agora, há alguns casos em que você pode querer ter o **mesmo esquema para entrada e saída**. + +Provavelmente, o principal caso de uso para isso é se você já tem algum código de cliente/SDK gerado automaticamente e não quer atualizar todo o código de cliente/SDK gerado ainda, você provavelmente vai querer fazer isso em algum momento, mas talvez não agora. + +Nesse caso, você pode desativar esse recurso no **FastAPI**, com o parâmetro `separate_input_output_schemas=False`. + +/// info | Informação + +O suporte para `separate_input_output_schemas` foi adicionado no FastAPI `0.102.0`. 🤓 + +/// + +{* ../../docs_src/separate_openapi_schemas/tutorial002_py310.py hl[10] *} + +### Mesmo Esquema para Modelos de Entrada e Saída na Documentação + +E agora haverá um único esquema para entrada e saída para o modelo, apenas `Item`, e `description` **não será obrigatório**: + +
+ +
+ +Esse é o mesmo comportamento do Pydantic v1. 🤓 diff --git a/docs/pt/docs/how-to/testing-database.md b/docs/pt/docs/how-to/testing-database.md new file mode 100644 index 000000000..02f909f24 --- /dev/null +++ b/docs/pt/docs/how-to/testing-database.md @@ -0,0 +1,7 @@ +# Testando a Base de Dados + +Você pode estudar sobre bases de dados, SQL e SQLModel na documentação de SQLModel. 🤓 + +Aqui tem um mini tutorial de como usar SQLModel com FastAPI. ✨ + +Esse tutorial inclui uma sessão sobre testar bases de dados SQL. 😎 diff --git a/docs/pt/docs/index.md b/docs/pt/docs/index.md index d1e64b3b9..9f08d5224 100644 --- a/docs/pt/docs/index.md +++ b/docs/pt/docs/index.md @@ -1,3 +1,9 @@ +# FastAPI + + +

FastAPI

@@ -5,26 +11,29 @@ Framework FastAPI, alta performance, fácil de aprender, fácil de codar, pronto para produção

- - Test + + Test - - Coverage + + Coverage Package version + + Supported Python versions +

--- **Documentação**: https://fastapi.tiangolo.com -**Código fonte**: https://github.com/tiangolo/fastapi +**Código fonte**: https://github.com/fastapi/fastapi --- -FastAPI é um moderno e rápido (alta performance) _framework web_ para construção de APIs com Python 3.8 ou superior, baseado nos _type hints_ padrões do Python. +FastAPI é um moderno e rápido (alta performance) _framework web_ para construção de APIs com Python, baseado nos _type hints_ padrões do Python. Os recursos chave são: @@ -54,13 +63,25 @@ Os recursos chave são: -Outros patrocinadores +Outros patrocinadores ## Opiniões "*[...] Estou usando **FastAPI** muito esses dias. [...] Estou na verdade planejando utilizar ele em todos os times de **serviços _Machine Learning_ na Microsoft**. Alguns deles estão sendo integrados no _core_ do produto **Windows** e alguns produtos **Office**.*" -
Kabir Khan - Microsoft (ref)
+
Kabir Khan - Microsoft (ref)
+ +--- + +"_Nós adotamos a biblioteca **FastAPI** para iniciar um servidor **REST** que pode ser consultado para obter **previsões**. [para o Ludwig]_" + +
Piero Molino, Yaroslav Dudin, e Sai Sumanth Miryala - Uber (ref)
+ +--- + +"_A **Netflix** tem o prazer de anunciar o lançamento open-source do nosso framework de orquestração de **gerenciamento de crises**: **Dispatch**! [criado com **FastAPI**]_" + +
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (ref)
--- @@ -72,7 +93,7 @@ Os recursos chave são: "*Honestamente, o que você construiu parece super sólido e rebuscado. De muitas formas, eu queria que o **Hug** fosse assim - é realmente inspirador ver alguém que construiu ele.*" -
Timothy Crosley - criador doHug (ref)
+
Timothy Crosley - criador doHug (ref)
--- @@ -84,9 +105,9 @@ Os recursos chave são: --- -"*Nós adotamos a biblioteca **FastAPI** para criar um servidor **REST** que possa ser chamado para obter **predições**. [para o Ludwig]*" +"_Se alguém estiver procurando construir uma API Python para produção, eu recomendaria fortemente o **FastAPI**. Ele é **lindamente projetado**, **simples de usar** e **altamente escalável**. Ele se tornou um **componente chave** para a nossa estratégia API first de desenvolvimento e está impulsionando diversas automações e serviços, como o nosso Virtual TAC Engineer._" -
Piero Molino, Yaroslav Dudin e Sai Sumanth Miryala - Uber (ref)
+
Deon Pillsbury - Cisco (ref)
--- @@ -100,37 +121,27 @@ Se você estiver construindo uma aplicação Starlette para as partes web. -* Pydantic para a parte de dados. +* Pydantic para a parte de dados. ## Instalação -
- -```console -$ pip install fastapi - ----> 100% -``` - -
- -Você também precisará de um servidor ASGI para produção, tal como Uvicorn ou Hypercorn. +Crie e ative um ambiente virtual, e então instale o FastAPI:
```console -$ pip install "uvicorn[standard]" +$ pip install "fastapi[standard]" ---> 100% ```
+**Nota**: Certifique-se de que você colocou `"fastapi[standard]"` com aspas, para garantir que funcione em todos os terminais. + ## Exemplo ### Crie @@ -180,7 +191,7 @@ async def read_item(item_id: int, q: Union[str, None] = None): **Nota**: -Se você não sabe, verifique a seção _"In a hurry?"_ sobre `async` e `await` nas docs. +Se você não sabe, verifique a seção _"Com pressa?"_ sobre `async` e `await` nas docs.
@@ -191,11 +202,24 @@ Rode o servidor com:
```console -$ uvicorn main:app --reload - +$ fastapi dev main.py + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + │ fastapi run │ + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -INFO: Started reloader process [28720] -INFO: Started server process [28722] +INFO: Started reloader process [2248755] using WatchFiles +INFO: Started server process [2248757] INFO: Waiting for application startup. INFO: Application startup complete. ``` @@ -203,13 +227,13 @@ INFO: Application startup complete.
-Sobre o comando uvicorn main:app --reload... +Sobre o comando fastapi dev main.py... + +O comando `fastapi dev` lê o seu arquivo `main.py`, identifica o aplicativo **FastAPI** nele, e inicia um servidor usando o Uvicorn. -O comando `uvicorn main:app` se refere a: +Por padrão, o `fastapi dev` iniciará com *auto-reload* habilitado para desenvolvimento local. -* `main`: o arquivo `main.py` (o "módulo" Python). -* `app`: o objeto criado dentro de `main.py` com a linha `app = FastAPI()`. -* `--reload`: faz o servidor recarregar após mudanças de código. Somente faça isso para desenvolvimento. +Você pode ler mais sobre isso na documentação do FastAPI CLI.
@@ -264,7 +288,7 @@ app = FastAPI() class Item(BaseModel): name: str price: float - is_offer: Union[bool] = None + is_offer: Union[bool, None] = None @app.get("/") @@ -282,7 +306,7 @@ def update_item(item_id: int, item: Item): return {"item_name": item.name, "item_id": item_id} ``` -O servidor deverá recarregar automaticamente (porquê você adicionou `--reload` ao comando `uvicorn` acima). +O servidor `fastapi dev` deverá recarregar automaticamente. ### Evoluindo a Documentação Interativa da API @@ -312,11 +336,11 @@ E agora, vá para Tutorial - Guia do Usuário. +Para um exemplo mais completo incluindo mais recursos, veja Tutorial - Guia do Usuário. **Alerta de Spoiler**: o tutorial - guia do usuário inclui: @@ -412,9 +436,9 @@ Para um exemplo mais completo incluindo mais recursos, veja Injeção de Dependência
**. * Segurança e autenticação, incluindo suporte para **OAuth2** com autenticação **JWT tokens** e **HTTP Basic**. * Técnicas mais avançadas (mas igualmente fáceis) para declaração de **modelos JSON profundamente aninhados** (graças ao Pydantic). +* Integrações **GraphQL** com o Strawberry e outras bibliotecas. * Muitos recursos extras (graças ao Starlette) como: * **WebSockets** - * **GraphQL** * testes extrememamente fáceis baseados em HTTPX e `pytest` * **CORS** * **Cookie Sessions** @@ -424,30 +448,49 @@ Para um exemplo mais completo incluindo mais recursos, veja um dos _frameworks_ Python mais rápidos disponíveis, somente atrás de Starlette e Uvicorn (utilizados internamente pelo FastAPI). (*) -Para entender mais sobre performance, veja a seção Benchmarks. +Para entender mais sobre performance, veja a seção Comparações. + +## Dependências + +O FastAPI depende do Pydantic e do Starlette. + + +### Dependências `standard` + +Quando você instala o FastAPI com `pip install "fastapi[standard]"`, ele vêm com o grupo `standard` (padrão) de dependências opcionais: + +Utilizado pelo Pydantic: + +* email-validator - para validação de email. + +Utilizado pelo Starlette: + +* httpx - Obrigatório caso você queira utilizar o `TestClient`. +* jinja2 - Obrigatório se você quer utilizar a configuração padrão de templates. +* python-multipart - Obrigatório se você deseja suporte a "parsing" de formulário, com `request.form()`. + +Utilizado pelo FastAPI / Starlette: + +* uvicorn - para o servidor que carrega e serve a sua aplicação. Isto inclui `uvicorn[standard]`, que inclui algumas dependências (e.g. `uvloop`) necessárias para servir em alta performance. +* `fastapi-cli` - que disponibiliza o comando `fastapi`. -## Dependências opcionais +### Sem as dependências `standard` -Usados por Pydantic: +Se você não deseja incluir as dependências opcionais `standard`, você pode instalar utilizando `pip install fastapi` ao invés de `pip install "fastapi[standard]"`. -* email_validator - para validação de email. +### Dpendências opcionais adicionais -Usados por Starlette: +Existem algumas dependências adicionais que você pode querer instalar. -* httpx - Necessário se você quiser utilizar o `TestClient`. -* jinja2 - Necessário se você quiser utilizar a configuração padrão de templates. -* python-multipart - Necessário se você quiser suporte com "parsing" de formulário, com `request.form()`. -* itsdangerous - Necessário para suporte a `SessionMiddleware`. -* pyyaml - Necessário para suporte a `SchemaGenerator` da Starlette (você provavelmente não precisará disso com o FastAPI). -* graphene - Necessário para suporte a `GraphQLApp`. -* ujson - Necessário se você quer utilizar `UJSONResponse`. +Dependências opcionais adicionais do Pydantic: -Usados por FastAPI / Starlette: +* pydantic-settings - para gerenciamento de configurações. +* pydantic-extra-types - tipos extras para serem utilizados com o Pydantic. -* uvicorn - para o servidor que carrega e serve sua aplicação. -* orjson - Necessário se você quer utilizar `ORJSONResponse`. +Dependências opcionais adicionais do FastAPI: -Você pode instalar todas essas dependências com `pip install fastapi[all]`. +* orjson - Obrigatório se você deseja utilizar o `ORJSONResponse`. +* ujson - Obrigatório se você deseja utilizar o `UJSONResponse`. ## Licença diff --git a/docs/pt/docs/learn/index.md b/docs/pt/docs/learn/index.md new file mode 100644 index 000000000..b9a7f5972 --- /dev/null +++ b/docs/pt/docs/learn/index.md @@ -0,0 +1,5 @@ +# Aprender + +Nesta parte da documentação encontramos as seções introdutórias e os tutoriais para aprendermos como usar o **FastAPI**. + +Nós poderíamos considerar isto um **livro**, **curso**, a maneira **oficial** e recomendada de aprender o FastAPI. 😎 diff --git a/docs/pt/docs/project-generation.md b/docs/pt/docs/project-generation.md index c98bd069d..e5c935fd2 100644 --- a/docs/pt/docs/project-generation.md +++ b/docs/pt/docs/project-generation.md @@ -14,7 +14,7 @@ GitHub: **FastAPI** Python: +* _Backend_ **FastAPI** Python: * **Rápido**: Alta performance, no nível de **NodeJS** e **Go** (graças ao Starlette e Pydantic). * **Intuitivo**: Ótimo suporte de editor. _Auto-Complete_ em todo lugar. Menos tempo _debugando_. * **Fácil**: Projetado para ser fácil de usar e aprender. Menos tempo lendo documentações. diff --git a/docs/pt/docs/python-types.md b/docs/pt/docs/python-types.md index 9f12211c7..90a361f40 100644 --- a/docs/pt/docs/python-types.md +++ b/docs/pt/docs/python-types.md @@ -1,28 +1,28 @@ # Introdução aos tipos Python -**Python 3.6 +** tem suporte para "type hints" opcionais. +O Python possui suporte para "dicas de tipo" ou "type hints" (também chamado de "anotações de tipo" ou "type annotations") -Esses **"type hints"** são uma nova sintaxe (desde Python 3.6+) que permite declarar o tipo de uma variável. +Esses **"type hints"** são uma sintaxe especial que permite declarar o tipo de uma variável. Ao declarar tipos para suas variáveis, editores e ferramentas podem oferecer um melhor suporte. -Este é apenas um **tutorial rápido / atualização** sobre type hints Python. Ele cobre apenas o mínimo necessário para usá-los com o **FastAPI** ... que é realmente muito pouco. +Este é apenas um **tutorial rápido / atualização** sobre type hints do Python. Ele cobre apenas o mínimo necessário para usá-los com o **FastAPI**... que é realmente muito pouco. O **FastAPI** é baseado nesses type hints, eles oferecem muitas vantagens e benefícios. Mas mesmo que você nunca use o **FastAPI**, você se beneficiaria de aprender um pouco sobre eles. -!!! note "Nota" - Se você é um especialista em Python e já sabe tudo sobre type hints, pule para o próximo capítulo. +/// note | Nota +Se você é um especialista em Python e já sabe tudo sobre type hints, pule para o próximo capítulo. + +/// ## Motivação Vamos começar com um exemplo simples: -```Python -{!../../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} A chamada deste programa gera: @@ -33,12 +33,10 @@ John Doe A função faz o seguinte: * Pega um `first_name` e `last_name`. -* Converte a primeira letra de cada uma em maiúsculas com `title ()`. -* Concatena com um espaço no meio. +* Converte a primeira letra de cada uma em maiúsculas com `title()`. +* Concatena com um espaço no meio. -```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} ### Edite-o @@ -46,7 +44,7 @@ A função faz o seguinte: Mas agora imagine que você estava escrevendo do zero. -Em algum momento você teria iniciado a definição da função, já tinha os parâmetros prontos ... +Em algum momento você teria iniciado a definição da função, já tinha os parâmetros prontos... Mas então você deve chamar "esse método que converte a primeira letra em maiúscula". @@ -80,9 +78,7 @@ para: Esses são os "type hints": -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} Isso não é o mesmo que declarar valores padrão como seria com: @@ -94,37 +90,33 @@ Isso não é o mesmo que declarar valores padrão como seria com: Estamos usando dois pontos (`:`), não é igual a (`=`). -E adicionar type hints normalmente não muda o que acontece do que aconteceria sem elas. +E adicionar type hints normalmente não muda o que acontece do que aconteceria sem eles. Mas agora, imagine que você está novamente no meio da criação dessa função, mas com type hints. -No mesmo ponto, você tenta acionar o preenchimento automático com o `Ctrl Space` e vê: +No mesmo ponto, você tenta acionar o preenchimento automático com o `Ctrl+Space` e vê: -Com isso, você pode rolar, vendo as opções, até encontrar o que "toca uma campainha": +Com isso, você pode rolar, vendo as opções, até encontrar o que "soa familiar": ## Mais motivação -Marque esta função, ela já possui type hints: +Verifique esta função, ela já possui type hints: -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} -Como o editor conhece os tipos de variáveis, você não apenas obtém a conclusão, mas também as verificações de erro: +Como o editor conhece os tipos de variáveis, você não obtém apenas o preenchimento automático, mas também as verificações de erro: -Agora você sabe que precisa corrigí-lo, converta `age` em uma string com `str (age)`: +Agora você sabe que precisa corrigí-lo, converta `age` em uma string com `str(age)`: -```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} -## Tipos de declaração +## Declarando Tipos Você acabou de ver o local principal para declarar type hints. Como parâmetros de função. @@ -141,44 +133,83 @@ Você pode usar, por exemplo: * `bool` * `bytes` -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} ### Tipos genéricos com parâmetros de tipo Existem algumas estruturas de dados que podem conter outros valores, como `dict`, `list`, `set` e `tuple`. E os valores internos também podem ter seu próprio tipo. -Para declarar esses tipos e os tipos internos, você pode usar o módulo Python padrão `typing`. +Estes tipos que possuem tipos internos são chamados de tipos "**genéricos**". E é possível declará-los mesmo com os seus tipos internos. + +Para declarar esses tipos e os tipos internos, você pode usar o módulo Python padrão `typing`. Ele existe especificamente para suportar esses type hints. + +#### Versões mais recentes do Python + +A sintaxe utilizando `typing` é **compatível** com todas as versões, desde o Python 3.6 até as últimas, incluindo o Python 3.9, 3.10, etc. + +Conforme o Python evolui, **novas versões** chegam com suporte melhorado para esses type annotations, e em muitos casos, você não precisará nem importar e utilizar o módulo `typing` para declarar os type annotations. + +Se você pode escolher uma versão mais recente do Python para o seu projeto, você poderá aproveitar isso ao seu favor. + +Em todos os documentos existem exemplos compatíveis com cada versão do Python (quando existem diferenças). + +Por exemplo, "**Python 3.6+**" significa que é compatível com o Python 3.6 ou superior (incluindo o 3.7, 3.8, 3.9, 3.10, etc). E "**Python 3.9+**" significa que é compatível com o Python 3.9 ou mais recente (incluindo o 3.10, etc). + +Se você pode utilizar a **versão mais recente do Python**, utilize os exemplos para as últimas versões. Eles terão as **melhores e mais simples sintaxes**, como por exemplo, "**Python 3.10+**". + +#### List -Ele existe especificamente para suportar esses type hints. +Por exemplo, vamos definir uma variável para ser uma `list` de `str`. -#### `List` +//// tab | Python 3.9+ -Por exemplo, vamos definir uma variável para ser uma `lista` de `str`. +Declare uma variável com a mesma sintaxe com dois pontos (`:`) -Em `typing`, importe `List` (com um `L` maiúsculo): +Como tipo, coloque `list`. + +Como a lista é o tipo que contém algum tipo interno, você coloca o tipo dentro de colchetes: + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial006_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +De `typing`, importe `List` (com o `L` maiúsculo): ```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` -Declare a variável com a mesma sintaxe de dois pontos (`:`). +Declare uma variável com a mesma sintaxe com dois pontos (`:`) -Como o tipo, coloque a `List`. +Como tipo, coloque o `List` que você importou de `typing`. -Como a lista é um tipo que contém alguns tipos internos, você os coloca entre colchetes: +Como a lista é o tipo que contém algum tipo interno, você coloca o tipo dentro de colchetes: ```Python hl_lines="4" -{!../../../docs_src/python_types/tutorial006.py!} +{!> ../../docs_src/python_types/tutorial006.py!} ``` -!!! tip "Dica" - Esses tipos internos entre colchetes são chamados de "parâmetros de tipo". +//// + +/// info | Informação + +Estes tipos internos dentro dos colchetes são chamados "parâmetros de tipo" (type parameters). + +Neste caso, `str` é o parâmetro de tipo passado para `List` (ou `list` no Python 3.9 ou superior). - Nesse caso, `str` é o parâmetro de tipo passado para `List`. +/// -Isso significa que: "a variável `items` é uma `list`, e cada um dos itens desta lista é uma `str`". +Isso significa: "a variável `items` é uma `list`, e cada um dos itens desta lista é uma `str`". + +/// tip | Dica + +Se você usa o Python 3.9 ou superior, você não precisa importar `List` de `typing`. Você pode utilizar o mesmo tipo `list` no lugar. + +/// Ao fazer isso, seu editor pode fornecer suporte mesmo durante o processamento de itens da lista: @@ -190,20 +221,32 @@ Observe que a variável `item` é um dos elementos da lista `items`. E, ainda assim, o editor sabe que é um `str` e fornece suporte para isso. -#### `Tuple` e `Set` +#### Tuple e Set Você faria o mesmo para declarar `tuple`s e `set`s: -```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial007.py!} +//// tab | Python 3.9+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial007_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial007.py!} ``` +//// + Isso significa que: * A variável `items_t` é uma `tuple` com 3 itens, um `int`, outro `int` e uma `str`. * A variável `items_s` é um `set`, e cada um de seus itens é do tipo `bytes`. -#### `Dict` +#### Dict Para definir um `dict`, você passa 2 parâmetros de tipo, separados por vírgulas. @@ -211,38 +254,181 @@ O primeiro parâmetro de tipo é para as chaves do `dict`. O segundo parâmetro de tipo é para os valores do `dict`: -```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial008.py!} +//// tab | Python 3.9+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial008_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial008.py!} ``` +//// + Isso significa que: * A variável `prices` é um dict`: * As chaves deste `dict` são do tipo `str` (digamos, o nome de cada item). * Os valores deste `dict` são do tipo `float` (digamos, o preço de cada item). -#### `Opcional` +#### Union + +Você pode declarar que uma variável pode ser de qualquer um dentre **diversos tipos**. Por exemplo, um `int` ou um `str`. + +No Python 3.6 e superior (incluindo o Python 3.10), você pode utilizar o tipo `Union` de `typing`, e colocar dentro dos colchetes os possíveis tipos aceitáveis. + +No Python 3.10 também existe uma **nova sintaxe** onde você pode colocar os possívels tipos separados por uma barra vertical (`|`). + +//// tab | Python 3.10+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial008b_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial008b.py!} +``` + +//// + +Em ambos os casos, isso significa que `item` poderia ser um `int` ou um `str`. + + +#### Possívelmente `None` + +Você pode declarar que um valor pode ter um tipo, como `str`, mas que ele também pode ser `None`. + +No Python 3.6 e superior (incluindo o Python 3.10) você pode declará-lo importando e utilizando `Optional` do módulo `typing`. + +```Python hl_lines="1 4" +{!../../docs_src/python_types/tutorial009.py!} +``` + +O uso de `Optional[str]` em vez de apenas `str` permitirá que o editor o ajude a detectar erros, onde você pode estar assumindo que um valor é sempre um `str`, quando na verdade também pode ser `None`. + +`Optional[Something]` é na verdade um atalho para `Union[Something, None]`, eles são equivalentes. + +Isso também significa que no Python 3.10, você pode utilizar `Something | None`: + +//// tab | Python 3.10+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial009_py310.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial009.py!} +``` + +//// + +//// tab | Python 3.8+ alternative -Você também pode usar o `Opcional` para declarar que uma variável tem um tipo, como `str`, mas que é "opcional", o que significa que também pode ser `None`: +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial009b.py!} +``` + +//// + +#### Utilizando `Union` ou `Optional` + +Se você está utilizando uma versão do Python abaixo da 3.10, aqui vai uma dica do meu ponto de vista bem **subjetivo**: + +* 🚨 Evite utilizar `Optional[SomeType]` +* No lugar, ✨ **use `Union[SomeType, None]`** ✨. + +Ambos são equivalentes, e no final das contas, eles são o mesmo. Mas eu recomendaria o `Union` ao invés de `Optional` porque a palavra **Optional** parece implicar que o valor é opcional, quando na verdade significa "isso pode ser `None`", mesmo que ele não seja opcional e ainda seja obrigatório. + +Eu penso que `Union[SomeType, None]` é mais explícito sobre o que ele significa. + +Isso é apenas sobre palavras e nomes. Mas estas palavras podem afetar como os seus colegas de trabalho pensam sobre o código. + +Por exemplo, vamos pegar esta função: + +{* ../../docs_src/python_types/tutorial009c.py hl[1,4] *} -```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +O paâmetro `name` é definido como `Optional[str]`, mas ele **não é opcional**, você não pode chamar a função sem o parâmetro: + +```Python +say_hi() # Oh, no, this throws an error! 😱 +``` + +O parâmetro `name` **ainda é obrigatório** (não *opicional*) porque ele não possui um valor padrão. Mesmo assim, `name` aceita `None` como valor: + +```Python +say_hi(name=None) # This works, None is valid 🎉 ``` -O uso de `Opcional [str]` em vez de apenas `str` permitirá que o editor o ajude a detectar erros, onde você pode estar assumindo que um valor é sempre um `str`, quando na verdade também pode ser `None`. +A boa notícia é, quando você estiver no Python 3.10 você não precisará se preocupar mais com isso, pois você poderá simplesmente utilizar o `|` para definir uniões de tipos: + +{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *} + +E então você não precisará mais se preocupar com nomes como `Optional` e `Union`. 😎 #### Tipos genéricos -Esses tipos que usam parâmetros de tipo entre colchetes, como: +Esses tipos que usam parâmetros de tipo entre colchetes são chamados **tipos genéricos** ou **genéricos**. Por exemplo: + +//// tab | Python 3.10+ + +Você pode utilizar os mesmos tipos internos como genéricos (com colchetes e tipos dentro): + +* `list` +* `tuple` +* `set` +* `dict` + +E o mesmo como no Python 3.8, do módulo `typing`: + +* `Union` +* `Optional` (o mesmo que com o 3.8) +* ...entro outros. + +No Python 3.10, como uma alternativa para a utilização dos genéricos `Union` e `Optional`, você pode usar a barra vertical (`|`) para declarar uniões de tipos. Isso é muito melhor e mais simples. + +//// + +//// tab | Python 3.9+ + +Você pode utilizar os mesmos tipos internos como genéricos (com colchetes e tipos dentro): + +* `list` +* `tuple` +* `set` +* `dict` + +E o mesmo como no Python 3.8, do módulo `typing`: + +* `Union` +* `Optional` +* ...entro outros. + +//// + +//// tab | Python 3.8+ * `List` * `Tuple` * `Set` * `Dict` -* `Opcional` -* ...e outros. +* `Union` +* `Optional` +* ...entro outros. -são chamados **tipos genéricos** ou **genéricos**. +//// ### Classes como tipos @@ -250,23 +436,23 @@ Você também pode declarar uma classe como o tipo de uma variável. Digamos que você tenha uma classe `Person`, com um nome: -```Python hl_lines="1 2 3" -{!../../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} Então você pode declarar que uma variável é do tipo `Person`: -```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} E então, novamente, você recebe todo o suporte do editor: +Perceba que isso significa que "`one_person` é uma **instância** da classe `Person`". + +Isso não significa que "`one_person` é a **classe** chamada `Person`". + ## Modelos Pydantic - Pydantic é uma biblioteca Python para executar a validação de dados. +O Pydantic é uma biblioteca Python para executar a validação de dados. Você declara a "forma" dos dados como classes com atributos. @@ -278,18 +464,93 @@ E você recebe todo o suporte do editor com esse objeto resultante. Retirado dos documentos oficiais dos Pydantic: +//// tab | Python 3.10+ + ```Python -{!../../../docs_src/python_types/tutorial011.py!} +{!> ../../docs_src/python_types/tutorial011_py310.py!} ``` -!!! info "Informação" - Para saber mais sobre o Pydantic, verifique seus documentos . +//// + +//// tab | Python 3.9+ -**FastAPI** é todo baseado em Pydantic. +```Python +{!> ../../docs_src/python_types/tutorial011_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python +{!> ../../docs_src/python_types/tutorial011.py!} +``` + +//// + +/// info | Informação + +Para saber mais sobre o Pydantic, verifique a sua documentação. + +/// + +O **FastAPI** é todo baseado em Pydantic. Você verá muito mais disso na prática no [Tutorial - Guia do usuário](tutorial/index.md){.internal-link target=_blank}. -## Type hints em **FastAPI** +/// tip | Dica + +O Pydantic tem um comportamento especial quando você usa `Optional` ou `Union[Something, None]` sem um valor padrão. Você pode ler mais sobre isso na documentação do Pydantic sobre campos Opcionais Obrigatórios. + +/// + + +## Type Hints com Metadados de Anotações + +O Python possui uma funcionalidade que nos permite incluir **metadados adicionais** nos type hints utilizando `Annotated`. + +//// tab | Python 3.9+ + +No Python 3.9, `Annotated` é parte da biblioteca padrão, então você pode importá-lo de `typing`. + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial013_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +Em versões abaixo do Python 3.9, você importa `Annotated` de `typing_extensions`. + +Ele já estará instalado com o **FastAPI**. + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial013.py!} +``` + +//// + +O Python em si não faz nada com este `Annotated`. E para editores e outras ferramentas, o tipo ainda é `str`. + +Mas você pode utilizar este espaço dentro do `Annotated` para fornecer ao **FastAPI** metadata adicional sobre como você deseja que a sua aplicação se comporte. + +O importante aqui de se lembrar é que **o primeiro *type parameter*** que você informar ao `Annotated` é o **tipo de fato**. O resto é apenas metadado para outras ferramentas. + +Por hora, você precisa apenas saber que o `Annotated` existe, e que ele é Python padrão. 😎 + +Mais tarde você verá o quão **poderoso** ele pode ser. + +/// tip | Dica + +O fato de que isso é **Python padrão** significa que você ainda obtém a **melhor experiência de desenvolvedor possível** no seu editor, com as ferramentas que você utiliza para analisar e refatorar o seu código, etc. ✨ + +E também que o seu código será muito compatível com diversas outras ferramentas e bibliotecas Python. 🚀 + +/// + + +## Type hints no **FastAPI** O **FastAPI** aproveita esses type hints para fazer várias coisas. @@ -298,18 +559,21 @@ Com o **FastAPI**, você declara parâmetros com type hints e obtém: * **Suporte ao editor**. * **Verificações de tipo**. -... e **FastAPI** usa as mesmas declarações para: +... e o **FastAPI** usa as mesmas declarações para: -* **Definir requisitos**: dos parâmetros do caminho da solicitação, parâmetros da consulta, cabeçalhos, corpos, dependências, etc. +* **Definir requisitos**: dos parâmetros de rota, parâmetros da consulta, cabeçalhos, corpos, dependências, etc. * **Converter dados**: da solicitação para o tipo necessário. * **Validar dados**: provenientes de cada solicitação: - * A geração de **erros automáticos** retornou ao cliente quando os dados são inválidos. -* **Documente** a API usando OpenAPI: + * Gerando **erros automáticos** retornados ao cliente quando os dados são inválidos. +* **Documentar** a API usando OpenAPI: * que é usado pelas interfaces de usuário da documentação interativa automática. Tudo isso pode parecer abstrato. Não se preocupe. Você verá tudo isso em ação no [Tutorial - Guia do usuário](tutorial/index.md){.internal-link target=_blank}. O importante é que, usando tipos padrão de Python, em um único local (em vez de adicionar mais classes, decoradores, etc.), o **FastAPI** fará muito trabalho para você. -!!! info "Informação" - Se você já passou por todo o tutorial e voltou para ver mais sobre os tipos, um bom recurso é a "cheat sheet" do `mypy` . +/// info | Informação + +Se você já passou por todo o tutorial e voltou para ver mais sobre os tipos, um bom recurso é a "cheat sheet" do `mypy` . + +/// diff --git a/docs/pt/docs/resources/index.md b/docs/pt/docs/resources/index.md new file mode 100644 index 000000000..6eff8f9e7 --- /dev/null +++ b/docs/pt/docs/resources/index.md @@ -0,0 +1,3 @@ +# Recursos + +Material complementar, links externos, artigos e muito mais. ✈️ diff --git a/docs/pt/docs/tutorial/background-tasks.md b/docs/pt/docs/tutorial/background-tasks.md index 625fa2b11..0f3796371 100644 --- a/docs/pt/docs/tutorial/background-tasks.md +++ b/docs/pt/docs/tutorial/background-tasks.md @@ -15,9 +15,7 @@ Isso inclui, por exemplo: Primeiro, importe `BackgroundTasks` e defina um parâmetro em sua _função de operação de caminho_ com uma declaração de tipo de `BackgroundTasks`: -```Python hl_lines="1 13" -{!../../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *} O **FastAPI** criará o objeto do tipo `BackgroundTasks` para você e o passará como esse parâmetro. @@ -33,17 +31,13 @@ Nesse caso, a função de tarefa gravará em um arquivo (simulando o envio de um E como a operação de gravação não usa `async` e `await`, definimos a função com `def` normal: -```Python hl_lines="6-9" -{!../../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *} ## Adicionar a tarefa em segundo plano Dentro de sua _função de operação de caminho_, passe sua função de tarefa para o objeto _tarefas em segundo plano_ com o método `.add_task()`: -```Python hl_lines="14" -{!../../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[14] *} `.add_task()` recebe como argumentos: @@ -57,9 +51,7 @@ Usar `BackgroundTasks` também funciona com o sistema de injeção de dependênc O **FastAPI** sabe o que fazer em cada caso e como reutilizar o mesmo objeto, de forma que todas as tarefas em segundo plano sejam mescladas e executadas em segundo plano posteriormente: -```Python hl_lines="13 15 22 25" -{!../../../docs_src/background_tasks/tutorial002.py!} -``` +{* ../../docs_src/background_tasks/tutorial002.py hl[13,15,22,25] *} Neste exemplo, as mensagens serão gravadas no arquivo `log.txt` _após_ o envio da resposta. @@ -85,8 +77,6 @@ Se você precisa realizar cálculos pesados ​​em segundo plano e não necess Eles tendem a exigir configurações mais complexas, um gerenciador de fila de mensagens/tarefas, como RabbitMQ ou Redis, mas permitem que você execute tarefas em segundo plano em vários processos e, especialmente, em vários servidores. -Para ver um exemplo, verifique os [Geradores de projeto](../project-generation.md){.internal-link target=\_blank}, todos incluem celery já configurado. - Mas se você precisa acessar variáveis ​​e objetos do mesmo aplicativo **FastAPI**, ou precisa realizar pequenas tarefas em segundo plano (como enviar uma notificação por e-mail), você pode simplesmente usar `BackgroundTasks`. ## Recapitulando diff --git a/docs/pt/docs/tutorial/bigger-applications.md b/docs/pt/docs/tutorial/bigger-applications.md new file mode 100644 index 000000000..a094005fd --- /dev/null +++ b/docs/pt/docs/tutorial/bigger-applications.md @@ -0,0 +1,556 @@ +# Aplicações Maiores - Múltiplos Arquivos + +Se você está construindo uma aplicação ou uma API web, é raro que você possa colocar tudo em um único arquivo. + +**FastAPI** oferece uma ferramenta conveniente para estruturar sua aplicação, mantendo toda a flexibilidade. + +/// info | Informação + +Se você vem do Flask, isso seria o equivalente aos Blueprints do Flask. + +/// + +## Um exemplo de estrutura de arquivos + +Digamos que você tenha uma estrutura de arquivos como esta: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   ├── dependencies.py +│   └── routers +│   │ ├── __init__.py +│   │ ├── items.py +│   │ └── users.py +│   └── internal +│   ├── __init__.py +│   └── admin.py +``` + +/// tip | Dica + +Existem vários arquivos `__init__.py` presentes em cada diretório ou subdiretório. + +Isso permite a importação de código de um arquivo para outro. + +Por exemplo, no arquivo `app/main.py`, você poderia ter uma linha como: + +``` +from app.routers import items +``` + +/// + +* O diretório `app` contém todo o código da aplicação. Ele possui um arquivo `app/__init__.py` vazio, o que o torna um "pacote Python" (uma coleção de "módulos Python"): `app`. +* Dentro dele, o arquivo `app/main.py` está localizado em um pacote Python (diretório com `__init__.py`). Portanto, ele é um "módulo" desse pacote: `app.main`. +* Existem também um arquivo `app/dependencies.py`, assim como o `app/main.py`, ele é um "módulo": `app.dependencies`. +* Há um subdiretório `app/routers/` com outro arquivo `__init__.py`, então ele é um "subpacote Python": `app.routers`. +* O arquivo `app/routers/items.py` está dentro de um pacote, `app/routers/`, portanto, é um "submódulo": `app.routers.items`. +* O mesmo com `app/routers/users.py`, ele é outro submódulo: `app.routers.users`. +* Há também um subdiretório `app/internal/` com outro arquivo `__init__.py`, então ele é outro "subpacote Python":`app.internal`. +* E o arquivo `app/internal/admin.py` é outro submódulo: `app.internal.admin`. + + + +A mesma estrutura de arquivos com comentários: + +``` +. +├── app # "app" é um pacote Python +│   ├── __init__.py # este arquivo torna "app" um "pacote Python" +│   ├── main.py # "main" módulo, e.g. import app.main +│   ├── dependencies.py # "dependencies" módulo, e.g. import app.dependencies +│   └── routers # "routers" é um "subpacote Python" +│   │ ├── __init__.py # torna "routers" um "subpacote Python" +│   │ ├── items.py # "items" submódulo, e.g. import app.routers.items +│   │ └── users.py # "users" submódulo, e.g. import app.routers.users +│   └── internal # "internal" é um "subpacote Python" +│   ├── __init__.py # torna "internal" um "subpacote Python" +│   └── admin.py # "admin" submódulo, e.g. import app.internal.admin +``` + +## `APIRouter` + +Vamos supor que o arquivo dedicado a lidar apenas com usuários seja o submódulo em `/app/routers/users.py`. + +Você quer manter as *operações de rota* relacionadas aos seus usuários separadas do restante do código, para mantê-lo organizado. + +Mas ele ainda faz parte da mesma aplicação/web API **FastAPI** (faz parte do mesmo "pacote Python"). + +Você pode criar as *operações de rotas* para esse módulo usando o `APIRouter`. + +### Importar `APIRouter` + +você o importa e cria uma "instância" da mesma maneira que faria com a classe `FastAPI`: + +```Python hl_lines="1 3" title="app/routers/users.py" +{!../../docs_src/bigger_applications/app/routers/users.py!} +``` + +### *Operações de Rota* com `APIRouter` + +E então você o utiliza para declarar suas *operações de rota*. + +Utilize-o da mesma maneira que utilizaria a classe `FastAPI`: + +```Python hl_lines="6 11 16" title="app/routers/users.py" +{!../../docs_src/bigger_applications/app/routers/users.py!} +``` + +Você pode pensar em `APIRouter` como uma classe "mini `FastAPI`". + +Todas as mesmas opções são suportadas. + +Todos os mesmos `parameters`, `responses`, `dependencies`, `tags`, etc. + +/// tip | Dica + +Neste exemplo, a variável é chamada de `router`, mas você pode nomeá-la como quiser. + +/// + +Vamos incluir este `APIRouter` na aplicação principal `FastAPI`, mas primeiro, vamos verificar as dependências e outro `APIRouter`. + +## Dependências + +Vemos que precisaremos de algumas dependências usadas em vários lugares da aplicação. + +Então, as colocamos em seu próprio módulo de `dependencies` (`app/dependencies.py`). + +Agora usaremos uma dependência simples para ler um cabeçalho `X-Token` personalizado: + +//// tab | Python 3.9+ + +```Python hl_lines="3 6-8" title="app/dependencies.py" +{!> ../../docs_src/bigger_applications/app_an_py39/dependencies.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 5-7" title="app/dependencies.py" +{!> ../../docs_src/bigger_applications/app_an/dependencies.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira usar a versão `Annotated` se possível. + +/// + +```Python hl_lines="1 4-6" title="app/dependencies.py" +{!> ../../docs_src/bigger_applications/app/dependencies.py!} +``` + +//// + +/// tip | Dica + +Estamos usando um cabeçalho inventado para simplificar este exemplo. + +Mas em casos reais, você obterá melhores resultados usando os [Utilitários de Segurança](security/index.md){.internal-link target=_blank} integrados. + +/// + +## Outro módulo com `APIRouter` + +Digamos que você também tenha os endpoints dedicados a manipular "itens" do seu aplicativo no módulo em `app/routers/items.py`. + +Você tem *operações de rota* para: + +* `/items/` +* `/items/{item_id}` + +É tudo a mesma estrutura de `app/routers/users.py`. + +Mas queremos ser mais inteligentes e simplificar um pouco o código. + +Sabemos que todas as *operações de rota* neste módulo têm o mesmo: + +* Path `prefix`: `/items`. +* `tags`: (apenas uma tag: `items`). +* Extra `responses`. +* `dependências`: todas elas precisam da dependência `X-Token` que criamos. + +Então, em vez de adicionar tudo isso a cada *operação de rota*, podemos adicioná-lo ao `APIRouter`. + +```Python hl_lines="5-10 16 21" title="app/routers/items.py" +{!../../docs_src/bigger_applications/app/routers/items.py!} +``` + +Como o caminho de cada *operação de rota* deve começar com `/`, como em: + +```Python hl_lines="1" +@router.get("/{item_id}") +async def read_item(item_id: str): + ... +``` + +...o prefixo não deve incluir um `/` final. + +Então, o prefixo neste caso é `/items`. + +Também podemos adicionar uma lista de `tags` e `responses` extras que serão aplicadas a todas as *operações de rota* incluídas neste roteador. + +E podemos adicionar uma lista de `dependencies` que serão adicionadas a todas as *operações de rota* no roteador e serão executadas/resolvidas para cada solicitação feita a elas. + +/// tip | Dica + +Observe que, assim como [dependências em *decoradores de operação de rota*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, nenhum valor será passado para sua *função de operação de rota*. + +/// + +O resultado final é que os caminhos dos itens agora são: + +* `/items/` +* `/items/{item_id}` + +...como pretendíamos. + +* Elas serão marcadas com uma lista de tags que contêm uma única string `"items"`. + * Essas "tags" são especialmente úteis para os sistemas de documentação interativa automática (usando OpenAPI). +* Todas elas incluirão as `responses` predefinidas. +* Todas essas *operações de rota* terão a lista de `dependencies` avaliada/executada antes delas. + * Se você também declarar dependências em uma *operação de rota* específica, **elas também serão executadas**. + * As dependências do roteador são executadas primeiro, depois as [`dependencies` no decorador](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank} e, em seguida, as dependências de parâmetros normais. + * Você também pode adicionar [dependências de `Segurança` com `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}. + +/// tip | Dica + +Ter `dependências` no `APIRouter` pode ser usado, por exemplo, para exigir autenticação para um grupo inteiro de *operações de rota*. Mesmo que as dependências não sejam adicionadas individualmente a cada uma delas. + +/// + +/// check + +Os parâmetros `prefix`, `tags`, `responses` e `dependencies` são (como em muitos outros casos) apenas um recurso do **FastAPI** para ajudar a evitar duplicação de código. + +/// + +### Importar as dependências + +Este código reside no módulo `app.routers.items`, o arquivo `app/routers/items.py`. + +E precisamos obter a função de dependência do módulo `app.dependencies`, o arquivo `app/dependencies.py`. + +Então usamos uma importação relativa com `..` para as dependências: + +```Python hl_lines="3" title="app/routers/items.py" +{!../../docs_src/bigger_applications/app/routers/items.py!} +``` + +#### Como funcionam as importações relativas + +/// tip | Dica + +Se você sabe perfeitamente como funcionam as importações, continue para a próxima seção abaixo. + +/// + +Um único ponto `.`, como em: + +```Python +from .dependencies import get_token_header +``` + +significaria: + +* Começando no mesmo pacote em que este módulo (o arquivo `app/routers/items.py`) vive (o diretório `app/routers/`)... +* encontre o módulo `dependencies` (um arquivo imaginário em `app/routers/dependencies.py`)... +* e dele, importe a função `get_token_header`. + +Mas esse arquivo não existe, nossas dependências estão em um arquivo em `app/dependencies.py`. + +Lembre-se de como nossa estrutura app/file se parece: + + + +--- + +Os dois pontos `..`, como em: + +```Python +from ..dependencies import get_token_header +``` + +significa: + +* Começando no mesmo pacote em que este módulo (o arquivo `app/routers/items.py`) reside (o diretório `app/routers/`)... +* vá para o pacote pai (o diretório `app/`)... +* e lá, encontre o módulo `dependencies` (o arquivo em `app/dependencies.py`)... +* e dele, importe a função `get_token_header`. + +Isso funciona corretamente! 🎉 + +--- + +Da mesma forma, se tivéssemos usado três pontos `...`, como em: + +```Python +from ...dependencies import get_token_header +``` + +isso significaria: + +* Começando no mesmo pacote em que este módulo (o arquivo `app/routers/items.py`) vive (o diretório `app/routers/`)... +* vá para o pacote pai (o diretório `app/`)... +* então vá para o pai daquele pacote (não há pacote pai, `app` é o nível superior 😱)... +* e lá, encontre o módulo `dependencies` (o arquivo em `app/dependencies.py`)... +* e dele, importe a função `get_token_header`. + +Isso se referiria a algum pacote acima de `app/`, com seu próprio arquivo `__init__.py`, etc. Mas não temos isso. Então, isso geraria um erro em nosso exemplo. 🚨 + +Mas agora você sabe como funciona, então você pode usar importações relativas em seus próprios aplicativos, não importa o quão complexos eles sejam. 🤓 + +### Adicione algumas `tags`, `respostas` e `dependências` personalizadas + +Não estamos adicionando o prefixo `/items` nem `tags=["items"]` a cada *operação de rota* porque os adicionamos ao `APIRouter`. + +Mas ainda podemos adicionar _mais_ `tags` que serão aplicadas a uma *operação de rota* específica, e também algumas `respostas` extras específicas para essa *operação de rota*: + +```Python hl_lines="30-31" title="app/routers/items.py" +{!../../docs_src/bigger_applications/app/routers/items.py!} +``` + +/// tip | Dica + +Esta última operação de caminho terá a combinação de tags: `["items", "custom"]`. + +E também terá ambas as respostas na documentação, uma para `404` e uma para `403`. + +/// + +## O principal `FastAPI` + +Agora, vamos ver o módulo em `app/main.py`. + +Aqui é onde você importa e usa a classe `FastAPI`. + +Este será o arquivo principal em seu aplicativo que une tudo. + +E como a maior parte de sua lógica agora viverá em seu próprio módulo específico, o arquivo principal será bem simples. + +### Importar `FastAPI` + +Você importa e cria uma classe `FastAPI` normalmente. + +E podemos até declarar [dependências globais](dependencies/global-dependencies.md){.internal-link target=_blank} que serão combinadas com as dependências para cada `APIRouter`: + +```Python hl_lines="1 3 7" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +### Importe o `APIRouter` + +Agora importamos os outros submódulos que possuem `APIRouter`s: + +```Python hl_lines="4-5" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +Como os arquivos `app/routers/users.py` e `app/routers/items.py` são submódulos que fazem parte do mesmo pacote Python `app`, podemos usar um único ponto `.` para importá-los usando "importações relativas". + +### Como funciona a importação + +A seção: + +```Python +from .routers import items, users +``` + +significa: + +* Começando no mesmo pacote em que este módulo (o arquivo `app/main.py`) reside (o diretório `app/`)... +* procure o subpacote `routers` (o diretório em `app/routers/`)... +* e dele, importe o submódulo `items` (o arquivo em `app/routers/items.py`) e `users` (o arquivo em `app/routers/users.py`)... + +O módulo `items` terá uma variável `router` (`items.router`). Esta é a mesma que criamos no arquivo `app/routers/items.py`, é um objeto `APIRouter`. + +E então fazemos o mesmo para o módulo `users`. + +Também poderíamos importá-los como: + +```Python +from app.routers import items, users +``` + +/// info | Informação + +A primeira versão é uma "importação relativa": + +```Python +from .routers import items, users +``` + +A segunda versão é uma "importação absoluta": + +```Python +from app.routers import items, users +``` + +Para saber mais sobre pacotes e módulos Python, leia a documentação oficial do Python sobre módulos. + +/// + +### Evite colisões de nomes + +Estamos importando o submódulo `items` diretamente, em vez de importar apenas sua variável `router`. + +Isso ocorre porque também temos outra variável chamada `router` no submódulo `users`. + +Se tivéssemos importado um após o outro, como: + +```Python +from .routers.items import router +from .routers.users import router +``` + +o `router` de `users` sobrescreveria o de `items` e não poderíamos usá-los ao mesmo tempo. + +Então, para poder usar ambos no mesmo arquivo, importamos os submódulos diretamente: + +```Python hl_lines="5" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +### Incluir o `APIRouter`s para `usuários` e `itens` + +Agora, vamos incluir os `roteadores` dos submódulos `usuários` e `itens`: + +```Python hl_lines="10-11" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +/// info | Informação + +`users.router` contém o `APIRouter` dentro do arquivo `app/routers/users.py`. + +E `items.router` contém o `APIRouter` dentro do arquivo `app/routers/items.py`. + +/// + +Com `app.include_router()` podemos adicionar cada `APIRouter` ao aplicativo principal `FastAPI`. + +Ele incluirá todas as rotas daquele roteador como parte dele. + +/// note | Detalhe Técnico + +Na verdade, ele criará internamente uma *operação de rota* para cada *operação de rota* que foi declarada no `APIRouter`. + +Então, nos bastidores, ele realmente funcionará como se tudo fosse o mesmo aplicativo único. + +/// + +/// check + +Você não precisa se preocupar com desempenho ao incluir roteadores. + +Isso levará microssegundos e só acontecerá na inicialização. + +Então não afetará o desempenho. ⚡ + +/// + +### Incluir um `APIRouter` com um `prefix` personalizado, `tags`, `responses` e `dependencies` + +Agora, vamos imaginar que sua organização lhe deu o arquivo `app/internal/admin.py`. + +Ele contém um `APIRouter` com algumas *operações de rota* de administração que sua organização compartilha entre vários projetos. + +Para este exemplo, será super simples. Mas digamos que, como ele é compartilhado com outros projetos na organização, não podemos modificá-lo e adicionar um `prefix`, `dependencies`, `tags`, etc. diretamente ao `APIRouter`: + +```Python hl_lines="3" title="app/internal/admin.py" +{!../../docs_src/bigger_applications/app/internal/admin.py!} +``` + +Mas ainda queremos definir um `prefixo` personalizado ao incluir o `APIRouter` para que todas as suas *operações de rota* comecem com `/admin`, queremos protegê-lo com as `dependências` que já temos para este projeto e queremos incluir `tags` e `responses`. + +Podemos declarar tudo isso sem precisar modificar o `APIRouter` original passando esses parâmetros para `app.include_router()`: + +```Python hl_lines="14-17" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +Dessa forma, o `APIRouter` original permanecerá inalterado, para que possamos compartilhar o mesmo arquivo `app/internal/admin.py` com outros projetos na organização. + +O resultado é que em nosso aplicativo, cada uma das *operações de rota* do módulo `admin` terá: + +* O prefixo `/admin`. +* A tag `admin`. +* A dependência `get_token_header`. +* A resposta `418`. 🍵 + +Mas isso afetará apenas o `APIRouter` em nosso aplicativo, e não em nenhum outro código que o utilize. + +Assim, por exemplo, outros projetos poderiam usar o mesmo `APIRouter` com um método de autenticação diferente. + +### Incluir uma *operação de rota* + +Também podemos adicionar *operações de rota* diretamente ao aplicativo `FastAPI`. + +Aqui fazemos isso... só para mostrar que podemos 🤷: + +```Python hl_lines="21-23" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +e funcionará corretamente, junto com todas as outras *operações de rota* adicionadas com `app.include_router()`. + +/// info | Detalhes Técnicos + +**Observação**: este é um detalhe muito técnico que você provavelmente pode **simplesmente pular**. + +--- + +Os `APIRouter`s não são "montados", eles não são isolados do resto do aplicativo. + +Isso ocorre porque queremos incluir suas *operações de rota* no esquema OpenAPI e nas interfaces de usuário. + +Como não podemos simplesmente isolá-los e "montá-los" independentemente do resto, as *operações de rota* são "clonadas" (recriadas), não incluídas diretamente. + +/// + +## Verifique a documentação automática da API + +Agora, execute `uvicorn`, usando o módulo `app.main` e a variável `app`: + +
+ +```console +$ uvicorn app.main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +E abra os documentos em http://127.0.0.1:8000/docs. + +Você verá a documentação automática da API, incluindo os caminhos de todos os submódulos, usando os caminhos (e prefixos) corretos e as tags corretas: + + + +## Incluir o mesmo roteador várias vezes com `prefixos` diferentes + +Você também pode usar `.include_router()` várias vezes com o *mesmo* roteador usando prefixos diferentes. + +Isso pode ser útil, por exemplo, para expor a mesma API sob prefixos diferentes, por exemplo, `/api/v1` e `/api/latest`. + +Esse é um uso avançado que você pode não precisar, mas está lá caso precise. + +## Incluir um `APIRouter` em outro + +Da mesma forma que você pode incluir um `APIRouter` em um aplicativo `FastAPI`, você pode incluir um `APIRouter` em outro `APIRouter` usando: + +```Python +router.include_router(other_router) +``` + +Certifique-se de fazer isso antes de incluir `router` no aplicativo `FastAPI`, para que as *operações de rota* de `other_router` também sejam incluídas. diff --git a/docs/pt/docs/tutorial/body-fields.md b/docs/pt/docs/tutorial/body-fields.md index 8f3313ae9..e7dfb07f2 100644 --- a/docs/pt/docs/tutorial/body-fields.md +++ b/docs/pt/docs/tutorial/body-fields.md @@ -6,34 +6,39 @@ Da mesma forma que você pode declarar validações adicionais e metadados nos p Primeiro, você tem que importá-lo: -```Python hl_lines="4" -{!../../../docs_src/body_fields/tutorial001.py!} -``` +{* ../../docs_src/body_fields/tutorial001.py hl[4] *} -!!! warning "Aviso" - Note que `Field` é importado diretamente do `pydantic`, não do `fastapi` como todo o resto (`Query`, `Path`, `Body`, etc). +/// warning | Aviso + +Note que `Field` é importado diretamente do `pydantic`, não do `fastapi` como todo o resto (`Query`, `Path`, `Body`, etc). + +/// ## Declare atributos do modelo Você pode então utilizar `Field` com atributos do modelo: -```Python hl_lines="11-14" -{!../../../docs_src/body_fields/tutorial001.py!} -``` +{* ../../docs_src/body_fields/tutorial001.py hl[11:14] *} `Field` funciona da mesma forma que `Query`, `Path` e `Body`, ele possui todos os mesmos parâmetros, etc. -!!! note "Detalhes técnicos" - Na realidade, `Query`, `Path` e outros que você verá em seguida, criam objetos de subclasses de uma classe `Param` comum, que é ela mesma uma subclasse da classe `FieldInfo` do Pydantic. +/// note | Detalhes técnicos + +Na realidade, `Query`, `Path` e outros que você verá em seguida, criam objetos de subclasses de uma classe `Param` comum, que é ela mesma uma subclasse da classe `FieldInfo` do Pydantic. + +E `Field` do Pydantic retorna uma instância de `FieldInfo` também. + +`Body` também retorna objetos de uma subclasse de `FieldInfo` diretamente. E tem outras que você verá mais tarde que são subclasses da classe `Body`. + +Lembre-se que quando você importa `Query`, `Path`, e outros de `fastapi`, esse são na realidade funções que retornam classes especiais. - E `Field` do Pydantic retorna uma instância de `FieldInfo` também. +/// - `Body` também retorna objetos de uma subclasse de `FieldInfo` diretamente. E tem outras que você verá mais tarde que são subclasses da classe `Body`. +/// tip | Dica - Lembre-se que quando você importa `Query`, `Path`, e outros de `fastapi`, esse são na realidade funções que retornam classes especiais. +Note como cada atributo do modelo com um tipo, valor padrão e `Field` possuem a mesma estrutura que parâmetros de *funções de operações de rota*, com `Field` ao invés de `Path`, `Query` e `Body`. -!!! tip "Dica" - Note como cada atributo do modelo com um tipo, valor padrão e `Field` possuem a mesma estrutura que parâmetros de *funções de operações de rota*, com `Field` ao invés de `Path`, `Query` e `Body`. +/// ## Adicione informações extras diff --git a/docs/pt/docs/tutorial/body-multiple-params.md b/docs/pt/docs/tutorial/body-multiple-params.md index 0eaa9664c..eda9b4dff 100644 --- a/docs/pt/docs/tutorial/body-multiple-params.md +++ b/docs/pt/docs/tutorial/body-multiple-params.md @@ -8,20 +8,13 @@ Primeiro, é claro, você pode misturar `Path`, `Query` e declarações de parâ E você também pode declarar parâmetros de corpo como opcionais, definindo o valor padrão com `None`: -=== "Python 3.10+" +{* ../../docs_src/body_multiple_params/tutorial001_py310.py hl[17:19] *} - ```Python hl_lines="17-19" - {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} - ``` +/// note | Nota -=== "Python 3.8+" +Repare que, neste caso, o `item` que seria capturado a partir do corpo é opcional. Visto que ele possui `None` como valor padrão. - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001.py!} - ``` - -!!! nota - Repare que, neste caso, o `item` que seria capturado a partir do corpo é opcional. Visto que ele possui `None` como valor padrão. +/// ## Múltiplos parâmetros de corpo @@ -38,17 +31,7 @@ No exemplo anterior, as *operações de rota* esperariam um JSON no corpo conten Mas você pode também declarar múltiplos parâmetros de corpo, por exemplo, `item` e `user`: -=== "Python 3.10+" - - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial002.py!} - ``` +{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *} Neste caso, o **FastAPI** perceberá que existe mais de um parâmetro de corpo na função (dois parâmetros que são modelos Pydantic). @@ -69,9 +52,11 @@ Então, ele usará o nome dos parâmetros como chaves (nome dos campos) no corpo } ``` -!!! nota - Repare que mesmo que o `item` esteja declarado da mesma maneira que antes, agora é esperado que ele esteja dentro do corpo com uma chave `item`. +/// note | Nota + +Repare que mesmo que o `item` esteja declarado da mesma maneira que antes, agora é esperado que ele esteja dentro do corpo com uma chave `item`. +/// O **FastAPI** fará a conversão automática a partir da requisição, assim esse parâmetro `item` receberá seu respectivo conteúdo e o mesmo ocorrerá com `user`. @@ -87,17 +72,7 @@ Se você declará-lo como é, porque é um valor singular, o **FastAPI** assumir Mas você pode instruir o **FastAPI** para tratá-lo como outra chave do corpo usando `Body`: -=== "Python 3.8+" - - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial003.py!} - ``` - -=== "Python 3.10+" - - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} - ``` +{* ../../docs_src/body_multiple_params/tutorial003.py hl[22] *} Neste caso, o **FastAPI** esperará um corpo como: @@ -137,20 +112,13 @@ q: str | None = None Por exemplo: -=== "Python 3.10+" - - ```Python hl_lines="26" - {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} - ``` +{* ../../docs_src/body_multiple_params/tutorial004_py310.py hl[26] *} -=== "Python 3.8+" +/// info | Informação - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004.py!} - ``` +`Body` também possui todas as validações adicionais e metadados de parâmetros como em `Query`,`Path` e outras que você verá depois. -!!! info "Informação" - `Body` também possui todas as validações adicionais e metadados de parâmetros como em `Query`,`Path` e outras que você verá depois. +/// ## Declare um único parâmetro de corpo indicando sua chave @@ -166,17 +134,7 @@ item: Item = Body(embed=True) como em: -=== "Python 3.10+" - - ```Python hl_lines="15" - {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005.py!} - ``` +{* ../../docs_src/body_multiple_params/tutorial005_py310.py hl[15] *} Neste caso o **FastAPI** esperará um corpo como: diff --git a/docs/pt/docs/tutorial/body-nested-models.md b/docs/pt/docs/tutorial/body-nested-models.md index 8ab77173e..2954ae3db 100644 --- a/docs/pt/docs/tutorial/body-nested-models.md +++ b/docs/pt/docs/tutorial/body-nested-models.md @@ -6,9 +6,7 @@ Com o **FastAPI**, você pode definir, validar, documentar e usar modelos profun Você pode definir um atributo como um subtipo. Por exemplo, uma `list` do Python: -```Python hl_lines="14" -{!../../../docs_src/body_nested_models/tutorial001.py!} -``` +{* ../../docs_src/body_nested_models/tutorial001.py hl[14] *} Isso fará com que tags seja uma lista de itens mesmo sem declarar o tipo dos elementos desta lista. @@ -20,9 +18,7 @@ Mas o Python tem uma maneira específica de declarar listas com tipos internos o Primeiramente, importe `List` do módulo `typing` que já vem por padrão no Python: -```Python hl_lines="1" -{!../../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *} ### Declare a `List` com um parâmetro de tipo @@ -44,9 +40,7 @@ Use a mesma sintaxe padrão para atributos de modelo com tipos internos. Portanto, em nosso exemplo, podemos fazer com que `tags` sejam especificamente uma "lista de strings": -```Python hl_lines="14" -{!../../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[14] *} ## Tipo "set" @@ -58,9 +52,7 @@ E que o Python tem um tipo de dados especial para conjuntos de itens únicos, o Então podemos importar `Set` e declarar `tags` como um `set` de `str`s: -```Python hl_lines="1 14" -{!../../../docs_src/body_nested_models/tutorial003.py!} -``` +{* ../../docs_src/body_nested_models/tutorial003.py hl[1,14] *} Com isso, mesmo que você receba uma requisição contendo dados duplicados, ela será convertida em um conjunto de itens exclusivos. @@ -82,17 +74,13 @@ Tudo isso, aninhado arbitrariamente. Por exemplo, nós podemos definir um modelo `Image`: -```Python hl_lines="9-11" -{!../../../docs_src/body_nested_models/tutorial004.py!} -``` +{* ../../docs_src/body_nested_models/tutorial004.py hl[9:11] *} ### Use o sub-modelo como um tipo E então podemos usa-lo como o tipo de um atributo: -```Python hl_lines="20" -{!../../../docs_src/body_nested_models/tutorial004.py!} -``` +{* ../../docs_src/body_nested_models/tutorial004.py hl[20] *} Isso significa que o **FastAPI** vai esperar um corpo similar à: @@ -121,13 +109,11 @@ Novamente, apenas fazendo essa declaração, com o **FastAPI**, você ganha: Além dos tipos singulares normais como `str`, `int`, `float`, etc. Você também pode usar tipos singulares mais complexos que herdam de `str`. -Para ver todas as opções possíveis, cheque a documentação para ostipos exoticos do Pydantic. Você verá alguns exemplos no próximo capitulo. +Para ver todas as opções possíveis, cheque a documentação para ostipos exoticos do Pydantic. Você verá alguns exemplos no próximo capitulo. Por exemplo, no modelo `Image` nós temos um campo `url`, nós podemos declara-lo como um `HttpUrl` do Pydantic invés de como uma `str`: -```Python hl_lines="4 10" -{!../../../docs_src/body_nested_models/tutorial005.py!} -``` +{* ../../docs_src/body_nested_models/tutorial005.py hl[4,10] *} A string será verificada para se tornar uma URL válida e documentada no esquema JSON/1OpenAPI como tal. @@ -135,9 +121,7 @@ A string será verificada para se tornar uma URL válida e documentada no esquem Você também pode usar modelos Pydantic como subtipos de `list`, `set`, etc: -```Python hl_lines="20" -{!../../../docs_src/body_nested_models/tutorial006.py!} -``` +{* ../../docs_src/body_nested_models/tutorial006.py hl[20] *} Isso vai esperar(converter, validar, documentar, etc) um corpo JSON tal qual: @@ -165,19 +149,23 @@ Isso vai esperar(converter, validar, documentar, etc) um corpo JSON tal qual: } ``` -!!! Informação - Note como o campo `images` agora tem uma lista de objetos de image. +/// info | informação + +Note como o campo `images` agora tem uma lista de objetos de image. + +/// ## Modelos profundamente aninhados Você pode definir modelos profundamente aninhados de forma arbitrária: -```Python hl_lines="9 14 20 23 27" -{!../../../docs_src/body_nested_models/tutorial007.py!} -``` +{* ../../docs_src/body_nested_models/tutorial007.py hl[9,14,20,23,27] *} + +/// info | informação + +Note como `Offer` tem uma lista de `Item`s, que por sua vez possui opcionalmente uma lista `Image`s -!!! Informação - Note como `Offer` tem uma lista de `Item`s, que por sua vez possui opcionalmente uma lista `Image`s +/// ## Corpos de listas puras @@ -190,9 +178,7 @@ images: List[Image] como em: -```Python hl_lines="15" -{!../../../docs_src/body_nested_models/tutorial008.py!} -``` +{* ../../docs_src/body_nested_models/tutorial008.py hl[15] *} ## Suporte de editor em todo canto @@ -222,18 +208,19 @@ Outro caso útil é quando você deseja ter chaves de outro tipo, por exemplo, ` Neste caso, você aceitaria qualquer `dict`, desde que tenha chaves` int` com valores `float`: -```Python hl_lines="9" -{!../../../docs_src/body_nested_models/tutorial009.py!} -``` +{* ../../docs_src/body_nested_models/tutorial009.py hl[9] *} + +/// tip | Dica + +Leve em condideração que o JSON só suporta `str` como chaves. -!!! Dica - Leve em condideração que o JSON só suporta `str` como chaves. +Mas o Pydantic tem conversão automática de dados. - Mas o Pydantic tem conversão automática de dados. +Isso significa que, embora os clientes da API só possam enviar strings como chaves, desde que essas strings contenham inteiros puros, o Pydantic irá convertê-los e validá-los. - Isso significa que, embora os clientes da API só possam enviar strings como chaves, desde que essas strings contenham inteiros puros, o Pydantic irá convertê-los e validá-los. +E o `dict` que você recebe como `weights` terá, na verdade, chaves `int` e valores` float`. - E o `dict` que você recebe como `weights` terá, na verdade, chaves `int` e valores` float`. +/// ## Recapitulação diff --git a/docs/pt/docs/tutorial/body-updates.md b/docs/pt/docs/tutorial/body-updates.md new file mode 100644 index 000000000..bf38aeb9e --- /dev/null +++ b/docs/pt/docs/tutorial/body-updates.md @@ -0,0 +1,116 @@ +# Corpo - Atualizações + +## Atualização de dados existentes com `PUT` + +Para atualizar um item, você pode usar a operação HTTP `PUT`. + +Você pode usar `jsonable_encoder` para converter os dados de entrada em dados que podem ser armazenados como JSON (por exemplo, com um banco de dados NoSQL). Por exemplo, convertendo `datetime` em `str`. + +{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *} + +`PUT` é usado para receber dados que devem substituir os dados existentes. + +### Aviso sobre a substituição + +Isso significa que, se você quiser atualizar o item `bar` usando `PUT` com um corpo contendo: + +```Python +{ + "name": "Barz", + "price": 3, + "description": None, +} +``` + +Como ele não inclui o atributo já armazenado `"tax": 20.2`, o modelo de entrada assumiria o valor padrão de `"tax": 10.5`. + +E os dados seriam salvos com esse "novo" `tax` de `10.5`. + +## Atualizações parciais com `PATCH` + +Você também pode usar a operação HTTP `PATCH` para *atualizar* parcialmente os dados. + +Isso significa que você pode enviar apenas os dados que deseja atualizar, deixando o restante intacto. + +/// note | Nota + +`PATCH` é menos comumente usado e conhecido do que `PUT`. + +E muitas equipes usam apenas `PUT`, mesmo para atualizações parciais. + +Você é **livre** para usá-los como preferir, **FastAPI** não impõe restrições. + +Mas este guia te dá uma ideia de como eles são destinados a serem usados. + +/// + +### Usando o parâmetro `exclude_unset` do Pydantic + +Se você quiser receber atualizações parciais, é muito útil usar o parâmetro `exclude_unset` no método `.model_dump()` do modelo do Pydantic. + +Como `item.model_dump(exclude_unset=True)`. + +/// info | Informação + +No Pydantic v1, o método que era chamado `.dict()` e foi depreciado (mas ainda suportado) no Pydantic v2. Agora, deve-se usar o método `.model_dump()`. + +Os exemplos aqui usam `.dict()` para compatibilidade com o Pydantic v1, mas você deve usar `.model_dump()` a partir do Pydantic v2. + +/// + +Isso gera um `dict` com apenas os dados definidos ao criar o modelo `item`, excluindo os valores padrão. + +Então, você pode usar isso para gerar um `dict` com apenas os dados definidos (enviados na solicitação), omitindo valores padrão: + +{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *} + +### Usando o parâmetro `update` do Pydantic + +Agora, você pode criar uma cópia do modelo existente usando `.model_copy()`, e passar o parâmetro `update` com um `dict` contendo os dados para atualizar. + +/// info | Informação + +No Pydantic v1, o método era chamado `.copy()`, ele foi depreciado (mas ainda suportado) no Pydantic v2, e renomeado para `.model_copy()`. + +Os exemplos aqui usam `.copy()` para compatibilidade com o Pydantic v1, mas você deve usar `.model_copy()` com o Pydantic v2. + +/// + +Como `stored_item_model.model_copy(update=update_data)`: + +{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *} + +### Recapitulando as atualizações parciais + +Resumindo, para aplicar atualizações parciais você pode: + +* (Opcionalmente) usar `PATCH` em vez de `PUT`. +* Recuperar os dados armazenados. +* Colocar esses dados em um modelo do Pydantic. +* Gerar um `dict` sem valores padrão a partir do modelo de entrada (usando `exclude_unset`). + * Dessa forma, você pode atualizar apenas os valores definidos pelo usuário, em vez de substituir os valores já armazenados com valores padrão em seu modelo. +* Criar uma cópia do modelo armazenado, atualizando seus atributos com as atualizações parciais recebidas (usando o parâmetro `update`). +* Converter o modelo copiado em algo que possa ser armazenado no seu banco de dados (por exemplo, usando o `jsonable_encoder`). + * Isso é comparável ao uso do método `.model_dump()`, mas garante (e converte) os valores para tipos de dados que possam ser convertidos em JSON, por exemplo, `datetime` para `str`. +* Salvar os dados no seu banco de dados. +* Retornar o modelo atualizado. + +{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *} + +/// tip | Dica + +Você pode realmente usar essa mesma técnica com uma operação HTTP `PUT`. + +Mas o exemplo aqui usa `PATCH` porque foi criado para esses casos de uso. + +/// + +/// note | Nota + +Observe que o modelo de entrada ainda é validado. + +Portanto, se você quiser receber atualizações parciais que possam omitir todos os atributos, precisará ter um modelo com todos os atributos marcados como opcionais (com valores padrão ou `None`). + +Para distinguir os modelos com todos os valores opcionais para **atualizações** e modelos com valores obrigatórios para **criação**, você pode usar as ideias descritas em [Modelos Adicionais](extra-models.md){.internal-link target=_blank}. + +/// diff --git a/docs/pt/docs/tutorial/body.md b/docs/pt/docs/tutorial/body.md index 99e05ab77..2508d7981 100644 --- a/docs/pt/docs/tutorial/body.md +++ b/docs/pt/docs/tutorial/body.md @@ -6,22 +6,23 @@ O corpo da **requisição** é a informação enviada pelo cliente para sua API. Sua API quase sempre irá enviar um corpo na **resposta**. Mas os clientes não necessariamente precisam enviar um corpo em toda **requisição**. -Para declarar um corpo da **requisição**, você utiliza os modelos do Pydantic com todos os seus poderes e benefícios. +Para declarar um corpo da **requisição**, você utiliza os modelos do Pydantic com todos os seus poderes e benefícios. -!!! info "Informação" - Para enviar dados, você deve usar utilizar um dos métodos: `POST` (Mais comum), `PUT`, `DELETE` ou `PATCH`. +/// info | Informação - Enviar um corpo em uma requisição `GET` não tem um comportamento definido nas especificações, porém é suportado pelo FastAPI, apenas para casos de uso bem complexos/extremos. +Para enviar dados, você deve usar utilizar um dos métodos: `POST` (Mais comum), `PUT`, `DELETE` ou `PATCH`. - Como é desencorajado, a documentação interativa com Swagger UI não irá mostrar a documentação para o corpo da requisição para um `GET`, e proxies que intermediarem podem não suportar o corpo da requisição. +Enviar um corpo em uma requisição `GET` não tem um comportamento definido nas especificações, porém é suportado pelo FastAPI, apenas para casos de uso bem complexos/extremos. + +Como é desencorajado, a documentação interativa com Swagger UI não irá mostrar a documentação para o corpo da requisição para um `GET`, e proxies que intermediarem podem não suportar o corpo da requisição. + +/// ## Importe o `BaseModel` do Pydantic Primeiro, você precisa importar `BaseModel` do `pydantic`: -```Python hl_lines="4" -{!../../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[4] *} ## Crie seu modelo de dados @@ -29,9 +30,7 @@ Então você declara seu modelo de dados como uma classe que herda `BaseModel`. Utilize os tipos Python padrão para todos os atributos: -```Python hl_lines="7-11" -{!../../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[7:11] *} Assim como quando declaramos parâmetros de consulta, quando um atributo do modelo possui um valor padrão, ele se torna opcional. Caso contrário, se torna obrigatório. Use `None` para torná-lo opcional. @@ -59,9 +58,7 @@ Por exemplo, o modelo acima declara um JSON "`object`" (ou `dict` no Python) com Para adicionar o corpo na *função de operação de rota*, declare-o da mesma maneira que você declarou parâmetros de rota e consulta: -```Python hl_lines="18" -{!../../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[18] *} ...E declare o tipo como o modelo que você criou, `Item`. @@ -110,24 +107,25 @@ Mas você terá o mesmo suporte do editor no -!!! tip "Dica" - Se você utiliza o PyCharm como editor, você pode utilizar o Plugin do Pydantic para o PyCharm . +/// tip | Dica + +Se você utiliza o PyCharm como editor, você pode utilizar o Plugin do Pydantic para o PyCharm . - Melhora o suporte do editor para seus modelos Pydantic com:: +Melhora o suporte do editor para seus modelos Pydantic com:: - * completação automática - * verificação de tipos - * refatoração - * buscas - * inspeções +* completação automática +* verificação de tipos +* refatoração +* buscas +* inspeções + +/// ## Use o modelo Dentro da função, você pode acessar todos os atributos do objeto do modelo diretamente: -```Python hl_lines="21" -{!../../../docs_src/body/tutorial002.py!} -``` +{* ../../docs_src/body/tutorial002.py hl[21] *} ## Corpo da requisição + parâmetros de rota @@ -135,9 +133,7 @@ Você pode declarar parâmetros de rota e corpo da requisição ao mesmo tempo. O **FastAPI** irá reconhecer que os parâmetros da função que combinam com parâmetros de rota devem ser **retirados da rota**, e parâmetros da função que são declarados como modelos Pydantic sejam **retirados do corpo da requisição**. -```Python hl_lines="17-18" -{!../../../docs_src/body/tutorial003.py!} -``` +{* ../../docs_src/body/tutorial003.py hl[17:18] *} ## Corpo da requisição + parâmetros de rota + parâmetros de consulta @@ -145,9 +141,7 @@ Você também pode declarar parâmetros de **corpo**, **rota** e **consulta**, a O **FastAPI** irá reconhecer cada um deles e retirar a informação do local correto. -```Python hl_lines="18" -{!../../../docs_src/body/tutorial004.py!} -``` +{* ../../docs_src/body/tutorial004.py hl[18] *} Os parâmetros da função serão reconhecidos conforme abaixo: @@ -155,11 +149,14 @@ Os parâmetros da função serão reconhecidos conforme abaixo: * Se o parâmetro é de um **tipo único** (como `int`, `float`, `str`, `bool`, etc) será interpretado como um parâmetro de **consulta**. * Se o parâmetro é declarado como um **modelo Pydantic**, será interpretado como o **corpo** da requisição. -!!! note "Observação" - O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`. +/// note | Observação + +O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`. + +O `Union` em `Union[str, None]` não é utilizado pelo FastAPI, mas permite ao seu editor de texto lhe dar um suporte melhor e detectar erros. - O `Union` em `Union[str, None]` não é utilizado pelo FastAPI, mas permite ao seu editor de texto lhe dar um suporte melhor e detectar erros. +/// ## Sem o Pydantic -Se você não quer utilizar os modelos Pydantic, você também pode utilizar o parâmetro **Body**. Veja a documentação para [Body - Parâmetros múltiplos: Valores singulares no body](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}. +Se você não quer utilizar os modelos Pydantic, você também pode utilizar o parâmetro **Body**. Veja a documentação para [Body - Parâmetros múltiplos: Valores singulares no body](body-multiple-params.md#valores-singulares-no-corpo){.internal-link target=_blank}. diff --git a/docs/pt/docs/tutorial/cookie-param-models.md b/docs/pt/docs/tutorial/cookie-param-models.md new file mode 100644 index 000000000..3d46ba44c --- /dev/null +++ b/docs/pt/docs/tutorial/cookie-param-models.md @@ -0,0 +1,78 @@ +# Modelos de Parâmetros de Cookie + +Se você possui um grupo de **cookies** que estão relacionados, você pode criar um **modelo Pydantic** para declará-los. 🍪 + +Isso lhe permitiria **reutilizar o modelo** em **diversos lugares** e também declarar validações e metadata para todos os parâmetros de uma vez. 😎 + +/// note | Nota + +Isso é suportado desde a versão `0.115.0` do FastAPI. 🤓 + +/// + +/// tip | Dica + +Essa mesma técnica se aplica para `Query`, `Cookie`, e `Header`. 😎 + +/// + +## Cookies com Modelos Pydantic + +Declare o parâmetro de **cookie** que você precisa em um **modelo Pydantic**, e depois declare o parâmetro como um `Cookie`: + +{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *} + +O **FastAPI** irá **extrair** os dados para **cada campo** dos **cookies** recebidos na requisição e lhe fornecer o modelo Pydantic que você definiu. + +## Verifique os Documentos + +Você pode ver os cookies definidos na IU dos documentos em `/docs`: + +
+ +
+ +/// info | Informação + +Tenha em mente que, como os **navegadores lidam com cookies** de maneira especial e por baixo dos panos, eles **não** permitem facilmente que o **JavaScript** lidem com eles. + +Se você for na **IU de documentos da API** em `/docs` você poderá ver a **documentação** para cookies das suas *operações de rotas*. + +Mas mesmo que você **adicionar os dados** e clicar em "Executar", pelo motivo da IU dos documentos trabalharem com **JavaScript**, os cookies não serão enviados, e você verá uma mensagem de **erro** como se você não tivesse escrito nenhum dado. + +/// + +## Proibir Cookies Adicionais + +Em alguns casos especiais (provavelmente não muito comuns), você pode querer **restringir** os cookies que você deseja receber. + +Agora a sua API possui o poder de contrar o seu próprio consentimento de cookie. 🤪🍪 + + + Você pode utilizar a configuração do modelo Pydantic para `proibir` qualquer campo `extra`. + + +{* ../../docs_src/cookie_param_models/tutorial002_an_py39.py hl[10] *} + +Se o cliente tentar enviar alguns **cookies extras**, eles receberão um retorno de **erro**. + +Coitados dos banners de cookies com todo o seu esforço para obter o seu consentimento para a API rejeitá-lo. 🍪 + +Por exemplo, se o cliente tentar enviar um cookie `santa_tracker` com o valor de `good-list-please`, o cliente receberá uma resposta de **erro** informando que o cookie `santa_tracker` is not allowed: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["cookie", "santa_tracker"], + "msg": "Extra inputs are not permitted", + "input": "good-list-please", + } + ] +} +``` + +## Resumo + +Você consegue utilizar **modelos Pydantic** para declarar **cookies** no **FastAPI**. 😎 diff --git a/docs/pt/docs/tutorial/cookie-params.md b/docs/pt/docs/tutorial/cookie-params.md index 1a60e3571..da85d796e 100644 --- a/docs/pt/docs/tutorial/cookie-params.md +++ b/docs/pt/docs/tutorial/cookie-params.md @@ -6,27 +6,30 @@ Você pode definir parâmetros de Cookie da mesma maneira que define paramêtros Primeiro importe `Cookie`: -```Python hl_lines="3" -{!../../../docs_src/cookie_params/tutorial001.py!} -``` +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[3] *} ## Declare parâmetros de `Cookie` Então declare os paramêtros de cookie usando a mesma estrutura que em `Path` e `Query`. -O primeiro valor é o valor padrão, você pode passar todas as validações adicionais ou parâmetros de anotação: +Você pode definir o valor padrão, assim como todas as validações extras ou parâmetros de anotação: -```Python hl_lines="9" -{!../../../docs_src/cookie_params/tutorial001.py!} -``` -!!! note "Detalhes Técnicos" - `Cookie` é uma classe "irmã" de `Path` e `Query`. Ela também herda da mesma classe em comum `Param`. +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9] *} - Mas lembre-se que quando você importa `Query`, `Path`, `Cookie` e outras de `fastapi`, elas são na verdade funções que retornam classes especiais. +/// note | Detalhes Técnicos -!!! info "Informação" - Para declarar cookies, você precisa usar `Cookie`, caso contrário, os parâmetros seriam interpretados como parâmetros de consulta. +`Cookie` é uma classe "irmã" de `Path` e `Query`. Ela também herda da mesma classe em comum `Param`. + +Mas lembre-se que quando você importa `Query`, `Path`, `Cookie` e outras de `fastapi`, elas são na verdade funções que retornam classes especiais. + +/// + +/// info | Informação + +Para declarar cookies, você precisa usar `Cookie`, pois caso contrário, os parâmetros seriam interpretados como parâmetros de consulta. + +/// ## Recapitulando diff --git a/docs/pt/docs/tutorial/cors.md b/docs/pt/docs/tutorial/cors.md new file mode 100644 index 000000000..0ab07a3c2 --- /dev/null +++ b/docs/pt/docs/tutorial/cors.md @@ -0,0 +1,85 @@ +# CORS (Cross-Origin Resource Sharing) + +CORS ou "Cross-Origin Resource Sharing" refere-se às situações em que um frontend rodando em um navegador possui um código JavaScript que se comunica com um backend, e o backend está em uma "origem" diferente do frontend. + +## Origem + +Uma origem é a combinação de protocolo (`http`, `https`), domínio (`myapp.com`, `localhost`, `localhost.tiangolo.com`), e porta (`80`, `443`, `8080`). + +Então, todos estes são origens diferentes: + +* `http://localhost` +* `https://localhost` +* `http://localhost:8080` + +Mesmo se todos estiverem em `localhost`, eles usam diferentes protocolos e portas, portanto, são "origens" diferentes. + +## Passos + +Então, digamos que você tenha um frontend rodando no seu navegador em `http://localhost:8080`, e seu JavaScript esteja tentando se comunicar com um backend rodando em http://localhost (como não especificamos uma porta, o navegador assumirá a porta padrão `80`). + +Portanto, o navegador irá enviar uma requisição HTTP `OPTIONS` ao backend, e se o backend enviar os cabeçalhos apropriados autorizando a comunicação a partir de uma origem diferente (`http://localhost:8080`) então o navegador deixará o JavaScript no frontend enviar sua requisição para o backend. + +Para conseguir isso, o backend deve ter uma lista de "origens permitidas". + +Neste caso, ele terá que incluir `http://localhost:8080` para o frontend funcionar corretamente. + +## Curingas + +É possível declarar uma lista com `"*"` (um "curinga") para dizer que tudo está permitido. + +Mas isso só permitirá certos tipos de comunicação, excluindo tudo que envolva credenciais: cookies, cabeçalhos de autorização como aqueles usados ​​com Bearer Tokens, etc. + +Então, para que tudo funcione corretamente, é melhor especificar explicitamente as origens permitidas. + +## Usar `CORSMiddleware` + +Você pode configurá-lo em sua aplicação **FastAPI** usando o `CORSMiddleware`. + +* Importe `CORSMiddleware`. +* Crie uma lista de origens permitidas (como strings). +* Adicione-a como um "middleware" à sua aplicação **FastAPI**. + +Você também pode especificar se o seu backend permite: + +* Credenciais (Cabeçalhos de autorização, Cookies, etc). +* Métodos HTTP específicos (`POST`, `PUT`) ou todos eles com o curinga `"*"`. +* Cabeçalhos HTTP específicos ou todos eles com o curinga `"*"`. + +{* ../../docs_src/cors/tutorial001.py hl[2,6:11,13:19] *} + +Os parâmetros padrão usados ​​pela implementação `CORSMiddleware` são restritivos por padrão, então você precisará habilitar explicitamente as origens, métodos ou cabeçalhos específicos para que os navegadores tenham permissão para usá-los em um contexto de domínios diferentes. + +Os seguintes argumentos são suportados: + +* `allow_origins` - Uma lista de origens que devem ter permissão para fazer requisições de origem cruzada. Por exemplo, `['https://example.org', 'https://www.example.org']`. Você pode usar `['*']` para permitir qualquer origem. +* `allow_origin_regex` - Uma string regex para corresponder às origens que devem ter permissão para fazer requisições de origem cruzada. Por exemplo, `'https://.*\.example\.org'`. +* `allow_methods` - Uma lista de métodos HTTP que devem ser permitidos para requisições de origem cruzada. O padrão é `['GET']`. Você pode usar `['*']` para permitir todos os métodos padrão. +* `allow_headers` - Uma lista de cabeçalhos de solicitação HTTP que devem ter suporte para requisições de origem cruzada. O padrão é `[]`. Você pode usar `['*']` para permitir todos os cabeçalhos. Os cabeçalhos `Accept`, `Accept-Language`, `Content-Language` e `Content-Type` são sempre permitidos para requisições CORS simples. +* `allow_credentials` - Indica que os cookies devem ser suportados para requisições de origem cruzada. O padrão é `False`. Além disso, `allow_origins` não pode ser definido como `['*']` para que as credenciais sejam permitidas, as origens devem ser especificadas. +* `expose_headers` - Indica quaisquer cabeçalhos de resposta que devem ser disponibilizados ao navegador. O padrão é `[]`. +* `max_age` - Define um tempo máximo em segundos para os navegadores armazenarem em cache as respostas CORS. O padrão é `600`. + +O middleware responde a dois tipos específicos de solicitação HTTP... + +### Requisições CORS pré-voo (preflight) + +Estas são quaisquer solicitações `OPTIONS` com cabeçalhos `Origin` e `Access-Control-Request-Method`. + +Nesse caso, o middleware interceptará a solicitação recebida e responderá com cabeçalhos CORS apropriados e uma resposta `200` ou `400` para fins informativos. + +### Requisições Simples + +Qualquer solicitação com um cabeçalho `Origin`. Neste caso, o middleware passará a solicitação normalmente, mas incluirá cabeçalhos CORS apropriados na resposta. + +## Mais informações + +Para mais informações CORS, acesse Mozilla CORS documentation. + +/// note | Detalhes técnicos + +Você também pode usar `from starlette.middleware.cors import CORSMiddleware`. + +**FastAPI** fornece vários middlewares em `fastapi.middleware` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria dos middlewares disponíveis vêm diretamente da Starlette. + +/// diff --git a/docs/pt/docs/tutorial/debugging.md b/docs/pt/docs/tutorial/debugging.md new file mode 100644 index 000000000..67b764457 --- /dev/null +++ b/docs/pt/docs/tutorial/debugging.md @@ -0,0 +1,113 @@ +# Depuração + +Você pode conectar o depurador no seu editor, por exemplo, com o Visual Studio Code ou PyCharm. + +## Chamar `uvicorn` + +Em seu aplicativo FastAPI, importe e execute `uvicorn` diretamente: + +{* ../../docs_src/debugging/tutorial001.py hl[1,15] *} + +### Sobre `__name__ == "__main__"` + +O objetivo principal de `__name__ == "__main__"` é ter algum código que seja executado quando seu arquivo for chamado com: + +
+ +```console +$ python myapp.py +``` + +
+ +mas não é chamado quando outro arquivo o importa, como em: + +```Python +from myapp import app +``` + +#### Mais detalhes + +Digamos que seu arquivo se chama `myapp.py`. + +Se você executá-lo com: + +
+ +```console +$ python myapp.py +``` + +
+ +então a variável interna `__name__` no seu arquivo, criada automaticamente pelo Python, terá como valor a string `"__main__"`. + +Então, a seção: + +```Python + uvicorn.run(app, host="0.0.0.0", port=8000) +``` + +vai executar. + +--- + +Isso não acontecerá se você importar esse módulo (arquivo). + +Então, se você tiver outro arquivo `importer.py` com: + +```Python +from myapp import app + +# Mais um pouco de código +``` + +nesse caso, a variável criada automaticamente dentro de `myapp.py` não terá a variável `__name__` com o valor `"__main__"`. + +Então, a linha: + +```Python + uvicorn.run(app, host="0.0.0.0", port=8000) +``` + +não será executada. + +/// info | Informação + +Para mais informações, consulte a documentação oficial do Python. + +/// + +## Execute seu código com seu depurador + +Como você está executando o servidor Uvicorn diretamente do seu código, você pode chamar seu programa Python (seu aplicativo FastAPI) diretamente do depurador. + +--- + +Por exemplo, no Visual Studio Code, você pode: + +* Ir para o painel "Debug". +* "Add configuration...". +* Selecionar "Python" +* Executar o depurador com a opção "`Python: Current File (Integrated Terminal)`". + +Em seguida, ele iniciará o servidor com seu código **FastAPI**, parará em seus pontos de interrupção, etc. + +Veja como pode parecer: + + + +--- + +Se você usar o Pycharm, você pode: + +* Abrir o menu "Executar". +* Selecionar a opção "Depurar...". +* Então um menu de contexto aparece. +* Selecionar o arquivo para depurar (neste caso, `main.py`). + +Em seguida, ele iniciará o servidor com seu código **FastAPI**, parará em seus pontos de interrupção, etc. + +Veja como pode parecer: + + diff --git a/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md new file mode 100644 index 000000000..ef67aa979 --- /dev/null +++ b/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md @@ -0,0 +1,288 @@ +# Classes como Dependências + +Antes de nos aprofundarmos no sistema de **Injeção de Dependência**, vamos melhorar o exemplo anterior. + +## `dict` do exemplo anterior + +No exemplo anterior, nós retornávamos um `dict` da nossa dependência ("injetável"): + +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[9] *} + +Mas assim obtemos um `dict` como valor do parâmetro `commons` na *função de operação de rota*. + +E sabemos que editores de texto não têm como oferecer muitas funcionalidades (como sugestões automáticas) para objetos do tipo `dict`, por que não há como eles saberem o tipo das chaves e dos valores. + +Podemos fazer melhor... + +## O que caracteriza uma dependência + +Até agora você apenas viu dependências declaradas como funções. + +Mas essa não é a única forma de declarar dependências (mesmo que provavelmente seja a mais comum). + +O fator principal para uma dependência é que ela deve ser "chamável" + +Um objeto "chamável" em Python é qualquer coisa que o Python possa "chamar" como uma função + +Então se você tiver um objeto `alguma_coisa` (que pode *não* ser uma função) que você possa "chamar" (executá-lo) dessa maneira: + +```Python +something() +``` + +ou + +```Python +something(some_argument, some_keyword_argument="foo") +``` + +Então esse objeto é um "chamável". + +## Classes como dependências + +Você deve ter percebido que para criar um instância de uma classe em Python, a mesma sintaxe é utilizada. + +Por exemplo: + +```Python +class Cat: + def __init__(self, name: str): + self.name = name + + +fluffy = Cat(name="Mr Fluffy") +``` + +Nesse caso, `fluffy` é uma instância da classe `Cat`. + +E para criar `fluffy`, você está "chamando" `Cat`. + +Então, uma classe Python também é "chamável". + +Então, no **FastAPI**, você pode utilizar uma classe Python como uma dependência. + +O que o FastAPI realmente verifica, é se a dependência é algo chamável (função, classe, ou outra coisa) e os parâmetros que foram definidos. + +Se você passar algo "chamável" como uma dependência do **FastAPI**, o framework irá analisar os parâmetros desse "chamável" e processá-los da mesma forma que os parâmetros de uma *função de operação de rota*. Incluindo as sub-dependências. + +Isso também se aplica a objetos chamáveis que não recebem nenhum parâmetro. Da mesma forma que uma *função de operação de rota* sem parâmetros. + +Então, podemos mudar o "injetável" na dependência `common_parameters` acima para a classe `CommonQueryParams`: + +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[11:15] *} + +Observe o método `__init__` usado para criar uma instância da classe: + +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[12] *} + +...ele possui os mesmos parâmetros que nosso `common_parameters` anterior: + +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8] *} + +Esses parâmetros são utilizados pelo **FastAPI** para "definir" a dependência. + +Em ambos os casos teremos: + +* Um parâmetro de consulta `q` opcional do tipo `str`. +* Um parâmetro de consulta `skip` do tipo `int`, com valor padrão `0`. +* Um parâmetro de consulta `limit` do tipo `int`, com valor padrão `100`. + +Os dados serão convertidos, validados, documentados no esquema da OpenAPI e etc nos dois casos. + +## Utilizando + +Agora você pode declarar sua dependência utilizando essa classe. + +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[19] *} + +O **FastAPI** chama a classe `CommonQueryParams`. Isso cria uma "instância" dessa classe e é a instância que será passada para o parâmetro `commons` na sua função. + +## Anotações de Tipo vs `Depends` + +Perceba como escrevemos `CommonQueryParams` duas vezes no código abaixo: + +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// + +O último `CommonQueryParams`, em: + +```Python +... Depends(CommonQueryParams) +``` + +...é o que o **FastAPI** irá realmente usar para saber qual é a dependência. + +É a partir dele que o FastAPI irá extrair os parâmetros passados e será o que o FastAPI irá realmente chamar. + +--- + +Nesse caso, o primeiro `CommonQueryParams`, em: + +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, ... +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python +commons: CommonQueryParams ... +``` + +//// + +...não tem nenhum signficado especial para o **FastAPI**. O FastAPI não irá utilizá-lo para conversão dos dados, validação, etc (já que ele utiliza `Depends(CommonQueryParams)` para isso). + +Na verdade você poderia escrever apenas: + +//// tab | Python 3.8+ + +```Python +commons: Annotated[Any, Depends(CommonQueryParams)] +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python +commons = Depends(CommonQueryParams) +``` + +//// + +...como em: + +{* ../../docs_src/dependencies/tutorial003_an_py310.py hl[19] *} + +Mas declarar o tipo é encorajado por que é a forma que o seu editor de texto sabe o que será passado como valor do parâmetro `commons`. + + + +## Pegando um Atalho + +Mas você pode ver que temos uma repetição do código neste exemplo, escrevendo `CommonQueryParams` duas vezes: + +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// + +O **FastAPI** nos fornece um atalho para esses casos, onde a dependência é *especificamente* uma classe que o **FastAPI** irá "chamar" para criar uma instância da própria classe. + +Para esses casos específicos, você pode fazer o seguinte: + +Em vez de escrever: + +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +//// + +...escreva: + +//// tab | Python 3.8+ + +```Python +commons: Annotated[CommonQueryParams, Depends()] +``` + +//// + +//// tab | Python 3.8 non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python +commons: CommonQueryParams = Depends() +``` + +//// + +Você declara a dependência como o tipo do parâmetro, e utiliza `Depends()` sem nenhum parâmetro, em vez de ter que escrever a classe *novamente* dentro de `Depends(CommonQueryParams)`. + +O mesmo exemplo ficaria então dessa forma: + +{* ../../docs_src/dependencies/tutorial004_an_py310.py hl[19] *} + +...e o **FastAPI** saberá o que fazer. + +/// tip | Dica + +Se isso parece mais confuso do que útil, não utilize, você não *precisa* disso. + +É apenas um atalho. Por que o **FastAPI** se preocupa em ajudar a minimizar a repetição de código. + +/// diff --git a/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md new file mode 100644 index 000000000..d7d31bb45 --- /dev/null +++ b/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -0,0 +1,69 @@ +# Dependências em decoradores de operações de rota + +Em alguns casos você não precisa necessariamente retornar o valor de uma dependência dentro de uma *função de operação de rota*. + +Ou a dependência não retorna nenhum valor. + +Mas você ainda precisa que ela seja executada/resolvida. + +Para esses casos, em vez de declarar um parâmetro em uma *função de operação de rota* com `Depends`, você pode adicionar um argumento `dependencies` do tipo `list` ao decorador da operação de rota. + +## Adicionando `dependencies` ao decorador da operação de rota + +O *decorador da operação de rota* recebe um argumento opcional `dependencies`. + +Ele deve ser uma lista de `Depends()`: + +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[19] *} + +Essas dependências serão executadas/resolvidas da mesma forma que dependências comuns. Mas o valor delas (se existir algum) não será passado para a sua *função de operação de rota*. + +/// tip | Dica + +Alguns editores de texto checam parâmetros de funções não utilizados, e os mostram como erros. + +Utilizando `dependencies` no *decorador da operação de rota* você pode garantir que elas serão executadas enquanto evita errors de editores/ferramentas. + +Isso também pode ser útil para evitar confundir novos desenvolvedores que ao ver um parâmetro não usado no seu código podem pensar que ele é desnecessário. + +/// + +/// info | Informação + +Neste exemplo utilizamos cabeçalhos personalizados inventados `X-Keys` e `X-Token`. + +Mas em situações reais, como implementações de segurança, você pode obter mais vantagens em usar as [Ferramentas de segurança integradas (o próximo capítulo)](../security/index.md){.internal-link target=_blank}. + +/// + +## Erros das dependências e valores de retorno + +Você pode utilizar as mesmas *funções* de dependências que você usaria normalmente. + +### Requisitos de Dependências + +Dependências podem declarar requisitos de requisições (como cabeçalhos) ou outras subdependências: + +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[8,13] *} + +### Levantando exceções + +Essas dependências podem levantar exceções, da mesma forma que dependências comuns: + +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[10,15] *} + +### Valores de retorno + +E elas também podem ou não retornar valores, eles não serão utilizados. + +Então, você pode reutilizar uma dependência comum (que retorna um valor) que já seja utilizada em outro lugar, e mesmo que o valor não seja utilizado, a dependência será executada: + +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[11,16] *} + +## Dependências para um grupo de *operações de rota* + +Mais a frente, quando você ler sobre como estruturar aplicações maiores ([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md){.internal-link target=_blank}), possivelmente com múltiplos arquivos, você aprenderá a declarar um único parâmetro `dependencies` para um grupo de *operações de rota*. + +## Dependências globais + +No próximo passo veremos como adicionar dependências para uma aplicação `FastAPI` inteira, para que ela seja aplicada em toda *operação de rota*. diff --git a/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md new file mode 100644 index 000000000..eaf711197 --- /dev/null +++ b/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md @@ -0,0 +1,373 @@ +# Dependências com yield + +O FastAPI possui suporte para dependências que realizam alguns passos extras ao finalizar. + +Para fazer isso, utilize `yield` em vez de `return`, e escreva os passos extras (código) depois. + +/// tip | Dica + +Garanta que `yield` é utilizado apenas uma vez. + +/// + +/// note | Detalhes Técnicos + +Qualquer função que possa ser utilizada com: + +* `@contextlib.contextmanager` ou +* `@contextlib.asynccontextmanager` + +pode ser utilizada como uma dependência do **FastAPI**. + +Na realidade, o FastAPI utiliza esses dois decoradores internamente. + +/// + +## Uma dependência de banco de dados com `yield` + +Por exemplo, você poderia utilizar isso para criar uma sessão do banco de dados, e fechá-la após terminar sua operação. + +Apenas o código anterior a declaração com `yield` e o código contendo essa declaração são executados antes de criar uma resposta. + +{* ../../docs_src/dependencies/tutorial007.py hl[2:4] *} + +O valor gerado (yielded) é o que é injetado nas *operações de rota* e outras dependências. + +{* ../../docs_src/dependencies/tutorial007.py hl[4] *} + +O código após o `yield` é executado após a resposta ser entregue: + +{* ../../docs_src/dependencies/tutorial007.py hl[5:6] *} + +/// tip | Dica + +Você pode usar funções assíncronas (`async`) ou funções comuns. + +O **FastAPI** saberá o que fazer com cada uma, da mesma forma que as dependências comuns. + +/// + +## Uma dependência com `yield` e `try` + +Se você utilizar um bloco `try` em uma dependência com `yield`, você irá capturar qualquer exceção que for lançada enquanto a dependência é utilizada. + +Por exemplo, se algum código em um certo momento no meio da operação, em outra dependência ou em uma *operação de rota*, fizer um "rollback" de uma transação de banco de dados ou causar qualquer outro erro, você irá capturar a exceção em sua dependência. + +Então, você pode procurar por essa exceção específica dentro da dependência com `except AlgumaExcecao`. + +Da mesma forma, você pode utilizar `finally` para garantir que os passos de saída são executados, com ou sem exceções. + +```python hl_lines="3 5" +{!../../docs_src/dependencies/tutorial007.py!} +``` + +## Subdependências com `yield` + +Você pode ter subdependências e "árvores" de subdependências de qualquer tamanho e forma, e qualquer uma ou todas elas podem utilizar `yield`. + +O **FastAPI** garantirá que o "código de saída" em cada dependência com `yield` é executado na ordem correta. + +Por exemplo, `dependency_c` pode depender de `dependency_b`, e `dependency_b` depender de `dependency_a`: + +//// tab | python 3.9+ + +```python hl_lines="6 14 22" +{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} +``` + +//// + +//// tab | python 3.8+ + +```python hl_lines="5 13 21" +{!> ../../docs_src/dependencies/tutorial008_an.py!} +``` + +//// + +//// tab | python 3.8+ non-annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```python hl_lines="4 12 20" +{!> ../../docs_src/dependencies/tutorial008.py!} +``` + +//// + +E todas elas podem utilizar `yield`. + +Neste caso, `dependency_c` precisa que o valor de `dependency_b` (nomeada de `dep_b` aqui) continue disponível para executar seu código de saída. + +E, por outro lado, `dependency_b` precisa que o valor de `dependency_a` (nomeada de `dep_a`) continue disponível para executar seu código de saída. + +//// tab | python 3.9+ + +```python hl_lines="18-19 26-27" +{!> ../../docs_src/dependencies/tutorial008_an_py39.py!} +``` + +//// + +//// tab | python 3.8+ + +```python hl_lines="17-18 25-26" +{!> ../../docs_src/dependencies/tutorial008_an.py!} +``` + +//// + +//// tab | python 3.8+ non-annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```python hl_lines="16-17 24-25" +{!> ../../docs_src/dependencies/tutorial008.py!} +``` + +//// + +Da mesma forma, você pode ter algumas dependências com `yield` e outras com `return` e ter uma relação de dependência entre algumas dos dois tipos. + +E você poderia ter uma única dependência que precisa de diversas outras dependências com `yield`, etc. + +Você pode ter qualquer combinação de dependências que você quiser. + +O **FastAPI** se encarrega de executá-las na ordem certa. + +/// note | Detalhes Técnicos + +Tudo isso funciona graças aos gerenciadores de contexto do Python. + +O **FastAPI** utiliza eles internamente para alcançar isso. + +/// + +## Dependências com `yield` e `httpexception` + +Você viu que dependências podem ser utilizadas com `yield` e podem incluir blocos `try` para capturar exceções. + +Da mesma forma, você pode lançar uma `httpexception` ou algo parecido no código de saída, após o `yield` + +/// tip | Dica + +Essa é uma técnica relativamente avançada, e na maioria dos casos você não precisa dela totalmente, já que você pode lançar exceções (incluindo `httpexception`) dentro do resto do código da sua aplicação, por exemplo, em uma *função de operação de rota*. + +Mas ela existe para ser utilizada caso você precise. 🤓 + +/// + +//// tab | python 3.9+ + +```python hl_lines="18-22 31" +{!> ../../docs_src/dependencies/tutorial008b_an_py39.py!} +``` + +//// + +//// tab | python 3.8+ + +```python hl_lines="17-21 30" +{!> ../../docs_src/dependencies/tutorial008b_an.py!} +``` + +//// + +//// tab | python 3.8+ non-annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```python hl_lines="16-20 29" +{!> ../../docs_src/dependencies/tutorial008b.py!} +``` + +//// + +Uma alternativa que você pode utilizar para capturar exceções (e possivelmente lançar outra HTTPException) é criar um [Manipulador de Exceções Customizado](../handling-errors.md#instalando-manipuladores-de-excecoes-customizados){.internal-link target=_blank}. + +## Dependências com `yield` e `except` + +Se você capturar uma exceção com `except` em uma dependência que utilize `yield` e ela não for levantada novamente (ou uma nova exceção for levantada), o FastAPI não será capaz de identifcar que houve uma exceção, da mesma forma que aconteceria com Python puro: + +{* ../../docs_src/dependencies/tutorial008c_an_py39.py hl[15:16] *} + +Neste caso, o cliente irá ver uma resposta *HTTP 500 Internal Server Error* como deveria acontecer, já que não estamos levantando nenhuma `HTTPException` ou coisa parecida, mas o servidor **não terá nenhum log** ou qualquer outra indicação de qual foi o erro. 😱 + +### Sempre levante (`raise`) exceções em Dependências com `yield` e `except` + +Se você capturar uma exceção em uma dependência com `yield`, a menos que você esteja levantando outra `HTTPException` ou coisa parecida, você deveria relançar a exceção original. + +Você pode relançar a mesma exceção utilizando `raise`: + +{* ../../docs_src/dependencies/tutorial008d_an_py39.py hl[17] *} + +//// tab | python 3.8+ non-annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +{* ../../docs_src/dependencies/tutorial008d.py hl[15] *} + +//// + +Agora o cliente irá receber a mesma resposta *HTTP 500 Internal Server Error*, mas o servidor terá nosso `InternalError` personalizado nos logs. 😎 + +## Execução de dependências com `yield` + +A sequência de execução é mais ou menos como esse diagrama. O tempo passa do topo para baixo. E cada coluna é uma das partes interagindo ou executando código. + +```mermaid +sequenceDiagram + +participant client as Cliente +participant handler as Manipulador de exceções +participant dep as Dep com yield +participant operation as Operação de Rota +participant tasks as Tarefas de Background + + Note over client,operation: pode lançar exceções, incluindo HTTPException + client ->> dep: Iniciar requisição + Note over dep: Executar código até o yield + opt lançar Exceção + dep -->> handler: lançar Exceção + handler -->> client: resposta de erro HTTP + end + dep ->> operation: Executar dependência, e.g. sessão de BD + opt raise + operation -->> dep: Lançar exceção (e.g. HTTPException) + opt handle + dep -->> dep: Pode capturar exceções, lançar uma nova HTTPException, lançar outras exceções + end + handler -->> client: resposta de erro HTTP + end + + operation ->> client: Retornar resposta ao cliente + Note over client,operation: Resposta já foi enviada, e não pode ser modificada + opt Tarefas + operation -->> tasks: Enviar tarefas de background + end + opt Lançar outra exceção + tasks -->> tasks: Manipula exceções no código da tarefa de background + end +``` + +/// info | Informação + +Apenas **uma resposta** será enviada para o cliente. Ela pode ser uma das respostas de erro, ou então a resposta da *operação de rota*. + +Após uma dessas respostas ser enviada, nenhuma outra resposta pode ser enviada + +/// + +/// tip | Dica + +Esse diagrama mostra `HttpException`, mas você pode levantar qualquer outra exceção que você capture em uma dependência com `yield` ou um [Manipulador de exceções personalizado](../handling-errors.md#instalando-manipuladores-de-excecoes-customizados){.internal-link target=_blank}. + +Se você lançar qualquer exceção, ela será passada para as dependências com yield, inlcuindo a `HTTPException`. Na maioria dos casos você vai querer relançar essa mesma exceção ou uma nova a partir da dependência com `yield` para garantir que ela seja tratada adequadamente. + +/// + +## Dependências com `yield`, `HTTPException`, `except` e Tarefas de Background + +/// warning | Aviso + +Você provavelmente não precisa desses detalhes técnicos, você pode pular essa seção e continuar na próxima seção abaixo. + +Esses detalhes são úteis principalmente se você estiver usando uma versão do FastAPI anterior à 0.106.0 e utilizando recursos de dependências com `yield` em tarefas de background. + +/// + +### Dependências com `yield` e `except`, Detalhes Técnicos + +Antes do FastAPI 0.110.0, se você utilizasse uma dependência com `yield`, e então capturasse uma dependência com `except` nessa dependência, caso a exceção não fosse relançada, ela era automaticamente lançada para qualquer manipulador de exceções ou o manipulador de erros interno do servidor. + +Isso foi modificado na versão 0.110.0 para consertar o consumo de memória não controlado das exceções relançadas automaticamente sem um manipulador (erros internos do servidor), e para manter o comportamento consistente com o código Python tradicional. + +### Tarefas de Background e Dependências com `yield`, Detalhes Técnicos + +Antes do FastAPI 0.106.0, levantar exceções após um `yield` não era possível, o código de saída nas dependências com `yield` era executado *após* a resposta ser enviada, então os [Manipuladores de Exceções](../handling-errors.md#instalando-manipuladores-de-excecoes-customizados){.internal-link target=_blank} já teriam executado. + +Isso foi implementado dessa forma principalmente para permitir que os mesmos objetos fornecidos ("yielded") pelas dependências dentro de tarefas de background fossem reutilizados, por que o código de saída era executado antes das tarefas de background serem finalizadas. + +Ainda assim, como isso exigiria esperar que a resposta navegasse pela rede enquanto mantia ativo um recurso desnecessário na dependência com yield (por exemplo, uma conexão com banco de dados), isso mudou na versão 0.106.0 do FastAPI. + +/// tip | Dica + +Adicionalmente, uma tarefa de background é, normalmente, um conjunto de lógicas independentes que devem ser manipuladas separadamente, com seus próprios recursos (e.g. sua própria conexão com banco de dados). + +Então, dessa forma você provavelmente terá um código mais limpo. + +/// + +Se você costumava depender desse comportamento, agora você precisa criar os recursos para uma tarefa de background dentro dela mesma, e usar internamente apenas dados que não dependam de recursos de dependências com `yield`. + +Por exemplo, em vez de utilizar a mesma sessão do banco de dados, você criaria uma nova sessão dentro da tarefa de background, e você obteria os objetos do banco de dados utilizando essa nova sessão. E então, em vez de passar o objeto obtido do banco de dados como um parâmetro para a função da tarefa de background, você passaria o ID desse objeto e buscaria ele novamente dentro da função da tarefa de background. + +## Gerenciadores de contexto + +### O que são gerenciadores de contexto + +"Gerenciadores de Contexto" são qualquer um dos objetos Python que podem ser utilizados com a declaração `with`. + +Por exemplo, você pode utilizar `with` para ler um arquivo: + +```Python +with open("./somefile.txt") as f: + contents = f.read() + print(contents) +``` + +Por baixo dos panos, o código `open("./somefile.txt")` cria um objeto que é chamado de "Gerenciador de Contexto". + +Quando o bloco `with` finaliza, ele se certifica de fechar o arquivo, mesmo que tenha ocorrido alguma exceção. + +Quando você cria uma dependência com `yield`, o **FastAPI** irá criar um gerenciador de contexto internamente para ela, e combiná-lo com algumas outras ferramentas relacionadas. + +### Utilizando gerenciadores de contexto em dependências com `yield` + +/// warning | Aviso + +Isso é uma ideia mais ou menos "avançada". + +Se você está apenas iniciando com o **FastAPI** você pode querer pular isso por enquanto. + +/// + +Em python, você pode criar Gerenciadores de Contexto ao criar uma classe com dois métodos: `__enter__()` e `__exit__()`. + +Você também pode usá-los dentro de dependências com `yield` do **FastAPI** ao utilizar `with` ou `async with` dentro da função da dependência: + +{* ../../docs_src/dependencies/tutorial010.py hl[1:9,13] *} + +/// tip | Dica + +Outra forma de criar um gerenciador de contexto é utilizando: + +* `@contextlib.contextmanager` ou + +* `@contextlib.asynccontextmanager` + +Para decorar uma função com um único `yield`. + +Isso é o que o **FastAPI** usa internamente para dependências com `yield`. + +Mas você não precisa usar esses decoradores para as dependências do FastAPI (e você não deveria). + +O FastAPI irá fazer isso para você internamente. + +/// diff --git a/docs/pt/docs/tutorial/dependencies/global-dependencies.md b/docs/pt/docs/tutorial/dependencies/global-dependencies.md new file mode 100644 index 000000000..a9a7e3b89 --- /dev/null +++ b/docs/pt/docs/tutorial/dependencies/global-dependencies.md @@ -0,0 +1,15 @@ +# Dependências Globais + +Para alguns tipos de aplicação específicos você pode querer adicionar dependências para toda a aplicação. + +De forma semelhante a [adicionar dependências (`dependencies`) em *decoradores de operação de rota*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, você pode adicioná-las à aplicação `FastAPI`. + +Nesse caso, elas serão aplicadas a todas as *operações de rota* da aplicação: + +{* ../../docs_src/dependencies/tutorial012_an_py39.py hl[16] *} + +E todos os conceitos apresentados na sessão sobre [adicionar dependências em *decoradores de operação de rota*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} ainda se aplicam, mas nesse caso, para todas as *operações de rota* da aplicação. + +## Dependências para conjuntos de *operações de rota* + +Mais para a frente, quando você ler sobre como estruturar aplicações maiores ([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md){.internal-link target=_blank}), possivelmente com múltiplos arquivos, você irá aprender a declarar um único parâmetro `dependencies` para um conjunto de *operações de rota*. diff --git a/docs/pt/docs/tutorial/dependencies/index.md b/docs/pt/docs/tutorial/dependencies/index.md new file mode 100644 index 000000000..1500b715a --- /dev/null +++ b/docs/pt/docs/tutorial/dependencies/index.md @@ -0,0 +1,250 @@ +# Dependências + +O **FastAPI** possui um poderoso, mas intuitivo sistema de **Injeção de Dependência**. + +Esse sistema foi pensado para ser fácil de usar, e permitir que qualquer desenvolvedor possa integrar facilmente outros componentes ao **FastAPI**. + +## O que é "Injeção de Dependência" + +**"Injeção de Dependência"** no mundo da programação significa, que existe uma maneira de declarar no seu código (nesse caso, suas *funções de operação de rota*) para declarar as coisas que ele precisa para funcionar e que serão utilizadas: "dependências". + +Então, esse sistema (nesse caso o **FastAPI**) se encarrega de fazer o que for preciso para fornecer essas dependências para o código ("injetando" as dependências). + +Isso é bastante útil quando você precisa: + +* Definir uma lógica compartilhada (mesmo formato de código repetidamente). +* Compartilhar conexões com banco de dados. +* Aplicar regras de segurança, autenticação, papéis de usuários, etc. +* E muitas outras coisas... + +Tudo isso, enquanto minimizamos a repetição de código. + +## Primeiros passos + +Vamos ver um exemplo simples. Tão simples que não será muito útil, por enquanto. + +Mas dessa forma podemos focar em como o sistema de **Injeção de Dependência** funciona. + +### Criando uma dependência, ou "injetável" + +Primeiro vamos focar na dependência. + +Ela é apenas uma função que pode receber os mesmos parâmetros de uma *função de operação de rota*: + +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *} + +E pronto. + +**2 linhas**. + +E com a mesma forma e estrutura de todas as suas *funções de operação de rota*. + +Você pode pensar nela como uma *função de operação de rota* sem o "decorador" (sem a linha `@app.get("/some-path")`). + +E com qualquer retorno que você desejar. + +Neste caso, a dependência espera por: + +* Um parâmetro de consulta opcional `q` do tipo `str`. +* Um parâmetro de consulta opcional `skip` do tipo `int`, e igual a `0` por padrão. +* Um parâmetro de consulta opcional `limit` do tipo `int`, e igual a `100` por padrão. + +E então retorna um `dict` contendo esses valores. + +/// info | Informação + +FastAPI passou a suportar a notação `Annotated` (e começou a recomendá-la) na versão 0.95.0. + +Se você utiliza uma versão anterior, ocorrerão erros ao tentar utilizar `Annotated`. + +Certifique-se de [Atualizar a versão do FastAPI](../../deployment/versions.md#atualizando-as-versoes-do-fastapi){.internal-link target=_blank} para pelo menos 0.95.1 antes de usar `Annotated`. + +/// + +### Importando `Depends` + +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *} + +### Declarando a dependência, no "dependente" + +Da mesma forma que você utiliza `Body`, `Query`, etc. Como parâmetros de sua *função de operação de rota*, utilize `Depends` com um novo parâmetro: + +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *} + +Ainda que `Depends` seja utilizado nos parâmetros da função da mesma forma que `Body`, `Query`, etc, `Depends` funciona de uma forma um pouco diferente. + +Você fornece um único parâmetro para `Depends`. + +Esse parâmetro deve ser algo como uma função. + +Você **não chama a função** diretamente (não adicione os parênteses no final), apenas a passe como parâmetro de `Depends()`. + +E essa função vai receber os parâmetros da mesma forma que uma *função de operação de rota*. + +/// tip | Dica + +Você verá quais outras "coisas", além de funções, podem ser usadas como dependências no próximo capítulo. + +/// + +Sempre que uma nova requisição for realizada, o **FastAPI** se encarrega de: + +* Chamar sua dependência ("injetável") com os parâmetros corretos. +* Obter o resultado da função. +* Atribuir esse resultado para o parâmetro em sua *função de operação de rota*. + +```mermaid +graph TB + +common_parameters(["common_parameters"]) +read_items["/items/"] +read_users["/users/"] + +common_parameters --> read_items +common_parameters --> read_users +``` + +Assim, você escreve um código compartilhado apenas uma vez e o **FastAPI** se encarrega de chamá-lo em suas *operações de rota*. + +/// check | Checando + +Perceba que você não precisa criar uma classe especial e enviar a dependência para algum outro lugar em que o **FastAPI** a "registre" ou realize qualquer operação similar. + +Você apenas envia para `Depends` e o **FastAPI** sabe como fazer o resto. + +/// + +## Compartilhando dependências `Annotated` + +Nos exemplos acima, você pode ver que existe uma pequena **duplicação de código**. + +Quando você precisa utilizar a dependência `common_parameters()`, você precisa escrever o parâmetro inteiro com uma anotação de tipo e `Depends()`: + +```Python +commons: Annotated[dict, Depends(common_parameters)] +``` + +Mas como estamos utilizando `Annotated`, podemos guardar esse valor `Annotated` em uma variável e utilizá-la em múltiplos locais: + +{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *} + +/// tip | Dica + +Isso é apenas Python padrão, essa funcionalidade é chamada de "type alias", e na verdade não é específica ao **FastAPI**. + +Mas como o **FastAPI** se baseia em convenções do Python, incluindo `Annotated`, você pode incluir esse truque no seu código. 😎 + +/// + +As dependências continuarão funcionando como esperado, e a **melhor parte** é que a **informação sobre o tipo é preservada**, o que signfica que seu editor de texto ainda irá incluir **preenchimento automático**, **visualização de erros**, etc. O mesmo vale para ferramentas como `mypy`. + +Isso é especialmente útil para uma **base de código grande** onde **as mesmas dependências** são utilizadas repetidamente em **muitas *operações de rota***. + +## `Async` ou não, eis a questão + +Como as dependências também serão chamadas pelo **FastAPI** (da mesma forma que *funções de operação de rota*), as mesmas regras se aplicam ao definir suas funções. + +Você pode utilizar `async def` ou apenas `def`. + +E você pode declarar dependências utilizando `async def` dentro de *funções de operação de rota* definidas com `def`, ou declarar dependências com `def` e utilizar dentro de *funções de operação de rota* definidas com `async def`, etc. + +Não faz diferença. O **FastAPI** sabe o que fazer. + +/// note | Nota + +Caso você não conheça, veja em [Async: *"Com Pressa?"*](../../async.md#com-pressa){.internal-link target=_blank} a sessão acerca de `async` e `await` na documentação. + +/// + +## Integrando com OpenAPI + +Todas as declarações de requisições, validações e requisitos para suas dependências (e sub-dependências) serão integradas em um mesmo esquema OpenAPI. + +Então, a documentação interativa também terá toda a informação sobre essas dependências: + + + +## Caso de Uso Simples + +Se você parar para ver, *funções de operação de rota* são declaradas para serem usadas sempre que uma *rota* e uma *operação* se encaixam, e então o **FastAPI** se encarrega de chamar a função correspondente com os argumentos corretos, extraindo os dados da requisição. + +Na verdade, todos (ou a maioria) dos frameworks web funcionam da mesma forma. + +Você nunca chama essas funções diretamente. Elas são chamadas pelo framework utilizado (nesse caso, **FastAPI**). + +Com o Sistema de Injeção de Dependência, você também pode informar ao **FastAPI** que sua *função de operação de rota* também "depende" em algo a mais que deve ser executado antes de sua *função de operação de rota*, e o **FastAPI** se encarrega de executar e "injetar" os resultados. + +Outros termos comuns para essa mesma ideia de "injeção de dependência" são: + +* recursos +* provedores +* serviços +* injetáveis +* componentes + +## Plug-ins em **FastAPI** + +Integrações e "plug-ins" podem ser construídos com o sistema de **Injeção de Dependência**. Mas na verdade, **não há necessidade de criar "plug-ins"**, já que utilizando dependências é possível declarar um número infinito de integrações e interações que se tornam disponíveis para as suas *funções de operação de rota*. + +E as dependências pode ser criadas de uma forma bastante simples e intuitiva que permite que você importe apenas os pacotes Python que forem necessários, e integrá-los com as funções de sua API em algumas linhas de código, *literalmente*. + +Você verá exemplos disso nos próximos capítulos, acerca de bancos de dados relacionais e NoSQL, segurança, etc. + +## Compatibilidade do **FastAPI** + +A simplicidade do sistema de injeção de dependência do **FastAPI** faz ele compatível com: + +* todos os bancos de dados relacionais +* bancos de dados NoSQL +* pacotes externos +* APIs externas +* sistemas de autenticação e autorização +* istemas de monitoramento de uso para APIs +* sistemas de injeção de dados de resposta +* etc. + +## Simples e Poderoso + +Mesmo que o sistema hierárquico de injeção de dependência seja simples de definir e utilizar, ele ainda é bastante poderoso. + +Você pode definir dependências que por sua vez definem suas próprias dependências. + +No fim, uma árvore hierárquica de dependências é criadas, e o sistema de **Injeção de Dependência** toma conta de resolver todas essas dependências (e as sub-dependências delas) para você, e provê (injeta) os resultados em cada passo. + +Por exemplo, vamos supor que você possua 4 endpoints na sua API (*operações de rota*): + +* `/items/public/` +* `/items/private/` +* `/users/{user_id}/activate` +* `/items/pro/` + +Você poderia adicionar diferentes requisitos de permissão para cada um deles utilizando apenas dependências e sub-dependências: + +```mermaid +graph TB + +current_user(["current_user"]) +active_user(["active_user"]) +admin_user(["admin_user"]) +paying_user(["paying_user"]) + +public["/items/public/"] +private["/items/private/"] +activate_user["/users/{user_id}/activate"] +pro_items["/items/pro/"] + +current_user --> active_user +active_user --> admin_user +active_user --> paying_user + +current_user --> public +active_user --> private +admin_user --> activate_user +paying_user --> pro_items +``` + +## Integração com **OpenAPI** + +Todas essas dependências, ao declarar os requisitos para suas *operações de rota*, também adicionam parâmetros, validações, etc. + +O **FastAPI** se encarrega de adicionar tudo isso ao esquema OpenAPI, para que seja mostrado nos sistemas de documentação interativa. diff --git a/docs/pt/docs/tutorial/dependencies/sub-dependencies.md b/docs/pt/docs/tutorial/dependencies/sub-dependencies.md new file mode 100644 index 000000000..3975ce182 --- /dev/null +++ b/docs/pt/docs/tutorial/dependencies/sub-dependencies.md @@ -0,0 +1,105 @@ +# Subdependências + +Você pode criar dependências que possuem **subdependências**. + +Elas podem ter o nível de **profundidade** que você achar necessário. + +O **FastAPI** se encarrega de resolver essas dependências. + +## Primeira dependência "injetável" + +Você pode criar uma primeira dependência (injetável) dessa forma: + +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *} + +Esse código declara um parâmetro de consulta opcional, `q`, com o tipo `str`, e então retorna esse parâmetro. + +Isso é bastante simples (e não muito útil), mas irá nos ajudar a focar em como as subdependências funcionam. + +## Segunda dependência, "injetável" e "dependente" + +Então, você pode criar uma outra função para uma dependência (um "injetável") que ao mesmo tempo declara sua própria dependência (o que faz dela um "dependente" também): + +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *} + +Vamos focar nos parâmetros declarados: + +* Mesmo que essa função seja uma dependência ("injetável") por si mesma, ela também declara uma outra dependência (ela "depende" de outra coisa). + * Ela depende do `query_extractor`, e atribui o valor retornado pela função ao parâmetro `q`. +* Ela também declara um cookie opcional `last_query`, do tipo `str`. + * Se o usuário não passou nenhuma consulta `q`, a última consulta é utilizada, que foi salva em um cookie anteriormente. + +## Utilizando a dependência + +Então podemos utilizar a dependência com: + +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *} + +/// info | Informação + +Perceba que nós estamos declarando apenas uma dependência na *função de operação de rota*, em `query_or_cookie_extractor`. + +Mas o **FastAPI** saberá que precisa solucionar `query_extractor` primeiro, para passar o resultado para `query_or_cookie_extractor` enquanto chama a função. + +/// + +```mermaid +graph TB + +query_extractor(["query_extractor"]) +query_or_cookie_extractor(["query_or_cookie_extractor"]) + +read_query["/items/"] + +query_extractor --> query_or_cookie_extractor --> read_query +``` + +## Utilizando a mesma dependência múltiplas vezes + +Se uma de suas dependências é declarada várias vezes para a mesma *operação de rota*, por exemplo, múltiplas dependências com uma mesma subdependência, o **FastAPI** irá chamar essa subdependência uma única vez para cada requisição. + +E o valor retornado é salvo em um "cache" e repassado para todos os "dependentes" que precisam dele em uma requisição específica, em vez de chamar a dependência múltiplas vezes para uma mesma requisição. + +Em um cenário avançado onde você precise que a dependência seja calculada em cada passo (possivelmente várias vezes) de uma requisição em vez de utilizar o valor em "cache", você pode definir o parâmetro `use_cache=False` em `Depends`: + +//// tab | Python 3.8+ + +```Python hl_lines="1" +async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]): + return {"fresh_value": fresh_value} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="1" +async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)): + return {"fresh_value": fresh_value} +``` + +//// + +## Recapitulando + +Com exceção de todas as palavras complicadas usadas aqui, o sistema de **Injeção de Dependência** é bastante simples. + +Consiste apenas de funções que parecem idênticas a *funções de operação de rota*. + +Mas ainda assim, é bastante poderoso, e permite que você declare grafos (árvores) de dependências com uma profundidade arbitrária. + +/// tip | Dica + +Tudo isso pode não parecer muito útil com esses exemplos. + +Mas você verá o quão útil isso é nos capítulos sobre **segurança**. + +E você também verá a quantidade de código que você não precisara escrever. + +/// diff --git a/docs/pt/docs/tutorial/encoder.md b/docs/pt/docs/tutorial/encoder.md index b9bfbf63b..87c6322e1 100644 --- a/docs/pt/docs/tutorial/encoder.md +++ b/docs/pt/docs/tutorial/encoder.md @@ -20,17 +20,7 @@ Você pode usar a função `jsonable_encoder` para resolver isso. A função recebe um objeto, como um modelo Pydantic e retorna uma versão compatível com JSON: -=== "Python 3.10+" - - ```Python hl_lines="4 21" - {!> ../../../docs_src/encoder/tutorial001_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="5 22" - {!> ../../../docs_src/encoder/tutorial001.py!} - ``` +{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *} Neste exemplo, ele converteria o modelo Pydantic em um `dict`, e o `datetime` em um `str`. @@ -38,5 +28,8 @@ O resultado de chamar a função é algo que pode ser codificado com o padrão d A função não retorna um grande `str` contendo os dados no formato JSON (como uma string). Mas sim, retorna uma estrutura de dados padrão do Python (por exemplo, um `dict`) com valores e subvalores compatíveis com JSON. -!!! nota - `jsonable_encoder` é realmente usado pelo **FastAPI** internamente para converter dados. Mas também é útil em muitos outros cenários. +/// note | Nota + +`jsonable_encoder` é realmente usado pelo **FastAPI** internamente para converter dados. Mas também é útil em muitos outros cenários. + +/// diff --git a/docs/pt/docs/tutorial/extra-data-types.md b/docs/pt/docs/tutorial/extra-data-types.md index e4b9913dc..09c838be0 100644 --- a/docs/pt/docs/tutorial/extra-data-types.md +++ b/docs/pt/docs/tutorial/extra-data-types.md @@ -36,7 +36,7 @@ Aqui estão alguns dos tipos de dados adicionais que você pode usar: * `datetime.timedelta`: * O `datetime.timedelta` do Python. * Em requisições e respostas será representado como um `float` de segundos totais. - * O Pydantic também permite representá-lo como uma "codificação ISO 8601 diferença de tempo", cheque a documentação para mais informações. + * O Pydantic também permite representá-lo como uma "codificação ISO 8601 diferença de tempo", cheque a documentação para mais informações. * `frozenset`: * Em requisições e respostas, será tratado da mesma forma que um `set`: * Nas requisições, uma lista será lida, eliminando duplicadas e convertendo-a em um `set`. @@ -49,18 +49,14 @@ Aqui estão alguns dos tipos de dados adicionais que você pode usar: * `Decimal`: * O `Decimal` padrão do Python. * Em requisições e respostas será representado como um `float`. -* Você pode checar todos os tipos de dados válidos do Pydantic aqui: Tipos de dados do Pydantic. +* Você pode checar todos os tipos de dados válidos do Pydantic aqui: Tipos de dados do Pydantic. ## Exemplo Aqui está um exemplo de *operação de rota* com parâmetros utilizando-se de alguns dos tipos acima. -```Python hl_lines="1 3 12-16" -{!../../../docs_src/extra_data_types/tutorial001.py!} -``` +{* ../../docs_src/extra_data_types/tutorial001.py hl[1,3,12:16] *} Note que os parâmetros dentro da função tem seu tipo de dados natural, e você pode, por exemplo, realizar manipulações normais de data, como: -```Python hl_lines="18-19" -{!../../../docs_src/extra_data_types/tutorial001.py!} -``` +{* ../../docs_src/extra_data_types/tutorial001.py hl[18:19] *} diff --git a/docs/pt/docs/tutorial/extra-models.md b/docs/pt/docs/tutorial/extra-models.md index 1343a3ae4..cccef16e3 100644 --- a/docs/pt/docs/tutorial/extra-models.md +++ b/docs/pt/docs/tutorial/extra-models.md @@ -8,26 +8,19 @@ Isso é especialmente o caso para modelos de usuários, porque: * O **modelo de saída** não deve ter uma senha. * O **modelo de banco de dados** provavelmente precisaria ter uma senha criptografada. -!!! danger - Nunca armazene senhas em texto simples dos usuários. Sempre armazene uma "hash segura" que você pode verificar depois. +/// danger - Se não souber, você aprenderá o que é uma "senha hash" nos [capítulos de segurança](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}. +Nunca armazene senhas em texto simples dos usuários. Sempre armazene uma "hash segura" que você pode verificar depois. -## Múltiplos modelos - -Aqui está uma ideia geral de como os modelos poderiam parecer com seus campos de senha e os lugares onde são usados: +Se não souber, você aprenderá o que é uma "senha hash" nos [capítulos de segurança](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}. -=== "Python 3.8 and above" +/// - ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" - {!> ../../../docs_src/extra_models/tutorial001.py!} - ``` +## Múltiplos modelos -=== "Python 3.10 and above" +Aqui está uma ideia geral de como os modelos poderiam parecer com seus campos de senha e os lugares onde são usados: - ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" - {!> ../../../docs_src/extra_models/tutorial001_py310.py!} - ``` +{* ../../docs_src/extra_models/tutorial001.py hl[9,11,16,22,24,29:30,33:35,40:41] *} ### Sobre `**user_in.dict()` @@ -139,8 +132,11 @@ UserInDB( ) ``` -!!! warning - As funções adicionais de suporte são apenas para demonstração de um fluxo possível dos dados, mas é claro que elas não fornecem segurança real. +/// warning + +As funções adicionais de suporte são apenas para demonstração de um fluxo possível dos dados, mas é claro que elas não fornecem segurança real. + +/// ## Reduzir duplicação @@ -158,17 +154,7 @@ Toda conversão de dados, validação, documentação, etc. ainda funcionará no Dessa forma, podemos declarar apenas as diferenças entre os modelos (com `password` em texto claro, com `hashed_password` e sem senha): -=== "Python 3.8 and above" - - ```Python hl_lines="9 15-16 19-20 23-24" - {!> ../../../docs_src/extra_models/tutorial002.py!} - ``` - -=== "Python 3.10 and above" - - ```Python hl_lines="7 13-14 17-18 21-22" - {!> ../../../docs_src/extra_models/tutorial002_py310.py!} - ``` +{* ../../docs_src/extra_models/tutorial002.py hl[9,15:16,19:20,23:24] *} ## `Union` ou `anyOf` @@ -178,20 +164,13 @@ Isso será definido no OpenAPI com `anyOf`. Para fazer isso, use a dica de tipo padrão do Python `typing.Union`: -!!! note - Ao definir um `Union`, inclua o tipo mais específico primeiro, seguido pelo tipo menos específico. No exemplo abaixo, o tipo mais específico `PlaneItem` vem antes de `CarItem` em `Union[PlaneItem, CarItem]`. - -=== "Python 3.8 and above" +/// note - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003.py!} - ``` +Ao definir um `Union`, inclua o tipo mais específico primeiro, seguido pelo tipo menos específico. No exemplo abaixo, o tipo mais específico `PlaneItem` vem antes de `CarItem` em `Union[PlaneItem, CarItem]`. -=== "Python 3.10 and above" +/// - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003_py310.py!} - ``` +{* ../../docs_src/extra_models/tutorial003.py hl[1,14:15,18:20,33] *} ### `Union` no Python 3.10 @@ -213,17 +192,7 @@ Da mesma forma, você pode declarar respostas de listas de objetos. Para isso, use o padrão Python `typing.List` (ou simplesmente `list` no Python 3.9 e superior): -=== "Python 3.8 and above" - - ```Python hl_lines="1 20" - {!> ../../../docs_src/extra_models/tutorial004.py!} - ``` - -=== "Python 3.9 and above" - - ```Python hl_lines="18" - {!> ../../../docs_src/extra_models/tutorial004_py39.py!} - ``` +{* ../../docs_src/extra_models/tutorial004.py hl[1,20] *} ## Resposta com `dict` arbitrário @@ -233,17 +202,7 @@ Isso é útil se você não souber os nomes de campo / atributo válidos (que se Neste caso, você pode usar `typing.Dict` (ou simplesmente dict no Python 3.9 e superior): -=== "Python 3.8 and above" - - ```Python hl_lines="1 8" - {!> ../../../docs_src/extra_models/tutorial005.py!} - ``` - -=== "Python 3.9 and above" - - ```Python hl_lines="6" - {!> ../../../docs_src/extra_models/tutorial005_py39.py!} - ``` +{* ../../docs_src/extra_models/tutorial005.py hl[1,8] *} ## Em resumo diff --git a/docs/pt/docs/tutorial/first-steps.md b/docs/pt/docs/tutorial/first-steps.md index 9fcdaf91f..5184d2d5f 100644 --- a/docs/pt/docs/tutorial/first-steps.md +++ b/docs/pt/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ O arquivo FastAPI mais simples pode se parecer com: -```Python -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} Copie o conteúdo para um arquivo `main.py`. @@ -13,23 +11,42 @@ Execute o servidor:
```console -$ uvicorn main:app --reload +$ fastapi dev main.py -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -INFO: Started reloader process [28720] -INFO: Started server process [28722] -INFO: Waiting for application startup. -INFO: Application startup complete. -``` + FastAPI Starting development server 🚀 -
+ Searching for package file structure from directories + with __init__.py files + Importing from /home/user/code/awesomeapp + + module 🐍 main.py + + code Importing the FastAPI app object from the module with + the following code: + + from main import app + + app Using import string: main:app -!!! nota - O comando `uvicorn main:app` se refere a: + server Server started at http://127.0.0.1:8000 + server Documentation at http://127.0.0.1:8000/docs - * `main`: o arquivo `main.py` (o "módulo" Python). - * `app`: o objeto criado no arquivo `main.py` com a linha `app = FastAPI()`. - * `--reload`: faz o servidor reiniciar após mudanças de código. Use apenas para desenvolvimento. + tip Running in development mode, for production use: + fastapi run + + Logs: + + INFO Will watch for changes in these directories: + ['/home/user/code/awesomeapp'] + INFO Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C + to quit) + INFO Started reloader process [383138] using WatchFiles + INFO Started server process [383153] + INFO Waiting for application startup. + INFO Application startup complete. +``` + + Na saída, temos: @@ -130,57 +147,26 @@ Você também pode usá-lo para gerar código automaticamente para clientes que ### Passo 1: importe `FastAPI` -```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI` é uma classe Python que fornece todas as funcionalidades para sua API. -!!! nota "Detalhes técnicos" - `FastAPI` é uma classe que herda diretamente de `Starlette`. +/// note | Detalhes técnicos - Você pode usar todas as funcionalidades do Starlette com `FastAPI` também. +`FastAPI` é uma classe que herda diretamente de `Starlette`. + +Você pode usar todas as funcionalidades do Starlette com `FastAPI` também. + +/// ### Passo 2: crie uma "instância" de `FastAPI` -```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[3] *} Aqui, a variável `app` será uma "instância" da classe `FastAPI`. Este será o principal ponto de interação para criar toda a sua API. -Este `app` é o mesmo referenciado por `uvicorn` no comando: - -
- -```console -$ uvicorn main:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -Se você criar a sua aplicação como: - -```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} -``` - -E colocar em um arquivo `main.py`, você iria chamar o `uvicorn` assim: - -
- -```console -$ uvicorn main:my_awesome_api --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- ### Passo 3: crie uma *rota* #### Rota @@ -199,8 +185,11 @@ https://example.com/items/foo /items/foo ``` -!!! info "Informação" - Uma "rota" também é comumente chamada de "endpoint". +/// info | Informação + +Uma "rota" também é comumente chamada de "endpoint". + +/// Ao construir uma API, a "rota" é a principal forma de separar "preocupações" e "recursos". @@ -241,25 +230,26 @@ Vamos chamá-los de "**operações**" também. #### Defina um *decorador de rota* -```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[6] *} O `@app.get("/")` diz ao **FastAPI** que a função logo abaixo é responsável por tratar as requisições que vão para: * a rota `/` * usando o operador get -!!! info "`@decorador`" - Essa sintaxe `@alguma_coisa` em Python é chamada de "decorador". +/// info | `@decorador` - Você o coloca em cima de uma função. Como um chapéu decorativo (acho que é daí que vem o termo). +Essa sintaxe `@alguma_coisa` em Python é chamada de "decorador". - Um "decorador" pega a função abaixo e faz algo com ela. +Você o coloca em cima de uma função. Como um chapéu decorativo (acho que é daí que vem o termo). - Em nosso caso, este decorador informa ao **FastAPI** que a função abaixo corresponde a **rota** `/` com uma **operação** `get`. +Um "decorador" pega a função abaixo e faz algo com ela. - É o "**decorador de rota**". +Em nosso caso, este decorador informa ao **FastAPI** que a função abaixo corresponde a **rota** `/` com uma **operação** `get`. + +É o "**decorador de rota**". + +/// Você também pode usar as outras operações: @@ -274,14 +264,17 @@ E os mais exóticos: * `@app.patch()` * `@app.trace()` -!!! tip "Dica" - Você está livre para usar cada operação (método HTTP) como desejar. +/// tip | Dica + +Você está livre para usar cada operação (método HTTP) como desejar. - O **FastAPI** não impõe nenhum significado específico. +O **FastAPI** não impõe nenhum significado específico. - As informações aqui são apresentadas como uma orientação, não uma exigência. +As informações aqui são apresentadas como uma orientação, não uma exigência. - Por exemplo, ao usar GraphQL, você normalmente executa todas as ações usando apenas operações `POST`. +Por exemplo, ao usar GraphQL, você normalmente executa todas as ações usando apenas operações `POST`. + +/// ### Passo 4: defina uma **função de rota** @@ -291,9 +284,7 @@ Esta é a nossa "**função de rota**": * **operação**: é `get`. * **função**: é a função abaixo do "decorador" (abaixo do `@app.get("/")`). -```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[7] *} Esta é uma função Python. @@ -305,18 +296,17 @@ Neste caso, é uma função `assíncrona`. Você também pode defini-la como uma função normal em vez de `async def`: -```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} -``` +{* ../../docs_src/first_steps/tutorial003.py hl[7] *} -!!! nota - Se você não sabe a diferença, verifique o [Async: *"Com pressa?"*](../async.md#com-pressa){.internal-link target=_blank}. +/// note | Nota + +Se você não sabe a diferença, verifique o [Async: *"Com pressa?"*](../async.md#com-pressa){.internal-link target=_blank}. + +/// ### Passo 5: retorne o conteúdo -```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[8] *} Você pode retornar um `dict`, `list` e valores singulares como `str`, `int`, etc. diff --git a/docs/pt/docs/tutorial/handling-errors.md b/docs/pt/docs/tutorial/handling-errors.md index 97a2e3eac..098195db7 100644 --- a/docs/pt/docs/tutorial/handling-errors.md +++ b/docs/pt/docs/tutorial/handling-errors.md @@ -26,9 +26,7 @@ Para retornar ao cliente *responses* HTTP com erros, use o `HTTPException`. ### Import `HTTPException` -```Python hl_lines="1" -{!../../../docs_src/handling_errors/tutorial001.py!} -``` +{* ../../docs_src/handling_errors/tutorial001.py hl[1] *} ### Lance o `HTTPException` no seu código. @@ -42,9 +40,7 @@ O benefício de lançar uma exceção em vez de retornar um valor ficará mais e Neste exemplo, quando o cliente pede, na requisição, por um item cujo ID não existe, a exceção com o status code `404` é lançada: -```Python hl_lines="11" -{!../../../docs_src/handling_errors/tutorial001.py!} -``` +{* ../../docs_src/handling_errors/tutorial001.py hl[11] *} ### A response resultante @@ -66,12 +62,14 @@ Mas se o cliente faz uma requisição para `http://example.com/items/bar` (ou se } ``` -!!! tip "Dica" - Quando você lançar um `HTTPException`, você pode passar qualquer valor convertível em JSON como parâmetro de `detail`, e não apenas `str`. +/// tip | Dica - Você pode passar um `dict` ou um `list`, etc. - Esses tipos de dados são manipulados automaticamente pelo **FastAPI** e convertidos em JSON. +Quando você lançar um `HTTPException`, você pode passar qualquer valor convertível em JSON como parâmetro de `detail`, e não apenas `str`. +Você pode passar um `dict` ou um `list`, etc. +Esses tipos de dados são manipulados automaticamente pelo **FastAPI** e convertidos em JSON. + +/// ## Adicione headers customizados @@ -81,9 +79,7 @@ Você provavelmente não precisará utilizar esses headers diretamente no seu c Mas caso você precise, para um cenário mais complexo, você pode adicionar headers customizados: -```Python hl_lines="14" -{!../../../docs_src/handling_errors/tutorial002.py!} -``` +{* ../../docs_src/handling_errors/tutorial002.py hl[14] *} ## Instalando manipuladores de exceções customizados @@ -93,9 +89,7 @@ Digamos que você tenha uma exceção customizada `UnicornException` que você ( Nesse cenário, se você precisa manipular essa exceção de modo global com o FastAPI, você pode adicionar um manipulador de exceção customizada com `@app.exception_handler()`. -```Python hl_lines="5-7 13-18 24" -{!../../../docs_src/handling_errors/tutorial003.py!} -``` +{* ../../docs_src/handling_errors/tutorial003.py hl[5:7,13:18,24] *} Nesse cenário, se você fizer uma requisição para `/unicorns/yolo`, a *operação de caminho* vai lançar (`raise`) o `UnicornException`. @@ -107,10 +101,13 @@ Dessa forma você receberá um erro "limpo", com o HTTP status code `418` e um J {"message": "Oops! yolo did something. There goes a rainbow..."} ``` -!!! note "Detalhes Técnicos" - Você também pode usar `from starlette.requests import Request` and `from starlette.responses import JSONResponse`. +/// note | Detalhes Técnicos + +Você também pode usar `from starlette.requests import Request` and `from starlette.responses import JSONResponse`. + +**FastAPI** disponibiliza o mesmo `starlette.responses` através do `fastapi.responses` por conveniência ao desenvolvedor. Contudo, a maior parte das respostas disponíveis vem diretamente do Starlette. O mesmo acontece com o `Request`. - **FastAPI** disponibiliza o mesmo `starlette.responses` através do `fastapi.responses` por conveniência ao desenvolvedor. Contudo, a maior parte das respostas disponíveis vem diretamente do Starlette. O mesmo acontece com o `Request`. +/// ## Sobrescreva o manipulador padrão de exceções @@ -126,9 +123,7 @@ Quando a requisição contém dados inválidos, **FastAPI** internamente lança Para sobrescrevê-lo, importe o `RequestValidationError` e use-o com o `@app.exception_handler(RequestValidationError)` para decorar o manipulador de exceções. -```Python hl_lines="2 14-16" -{!../../../docs_src/handling_errors/tutorial004.py!} -``` +{* ../../docs_src/handling_errors/tutorial004.py hl[2,14:16] *} Se você for ao `/items/foo`, em vez de receber o JSON padrão com o erro: @@ -157,10 +152,13 @@ path -> item_id ### `RequestValidationError` vs `ValidationError` -!!! warning "Aviso" - Você pode pular estes detalhes técnicos caso eles não sejam importantes para você neste momento. +/// warning | Aviso + +Você pode pular estes detalhes técnicos caso eles não sejam importantes para você neste momento. + +/// -`RequestValidationError` é uma subclasse do `ValidationError` existente no Pydantic. +`RequestValidationError` é uma subclasse do `ValidationError` existente no Pydantic. **FastAPI** faz uso dele para que você veja o erro no seu log, caso você utilize um modelo de Pydantic em `response_model`, e seus dados tenham erro. @@ -174,15 +172,15 @@ Do mesmo modo, você pode sobreescrever o `HTTPException`. Por exemplo, você pode querer retornar uma *response* em *plain text* ao invés de um JSON para os seguintes erros: -```Python hl_lines="3-4 9-11 22" -{!../../../docs_src/handling_errors/tutorial004.py!} -``` +{* ../../docs_src/handling_errors/tutorial004.py hl[3:4,9:11,22] *} + +/// note | Detalhes Técnicos -!!! note "Detalhes Técnicos" - Você pode usar `from starlette.responses import PlainTextResponse`. +Você pode usar `from starlette.responses import PlainTextResponse`. - **FastAPI** disponibiliza o mesmo `starlette.responses` como `fastapi.responses`, como conveniência a você, desenvolvedor. Contudo, a maior parte das respostas disponíveis vem diretamente do Starlette. +**FastAPI** disponibiliza o mesmo `starlette.responses` como `fastapi.responses`, como conveniência a você, desenvolvedor. Contudo, a maior parte das respostas disponíveis vem diretamente do Starlette. +/// ### Use o body do `RequestValidationError`. @@ -244,8 +242,6 @@ from starlette.exceptions import HTTPException as StarletteHTTPException Se você quer usar a exceção em conjunto com o mesmo manipulador de exceção *default* do **FastAPI**, você pode importar e re-usar esses manipuladores de exceção do `fastapi.exception_handlers`: -```Python hl_lines="2-5 15 21" -{!../../../docs_src/handling_errors/tutorial006.py!} -``` +{* ../../docs_src/handling_errors/tutorial006.py hl[2:5,15,21] *} Nesse exemplo você apenas imprime (`print`) o erro com uma mensagem expressiva. Mesmo assim, dá para pegar a ideia. Você pode usar a exceção e então apenas re-usar o manipulador de exceção *default*. diff --git a/docs/pt/docs/tutorial/header-param-models.md b/docs/pt/docs/tutorial/header-param-models.md new file mode 100644 index 000000000..9a88dbfec --- /dev/null +++ b/docs/pt/docs/tutorial/header-param-models.md @@ -0,0 +1,56 @@ +# Modelos de Parâmetros do Cabeçalho + +Se você possui um grupo de **parâmetros de cabeçalho** relacionados, você pode criar um **modelo do Pydantic** para declará-los. + +Isso vai lhe permitir **reusar o modelo** em **múltiplos lugares** e também declarar validações e metadadados para todos os parâmetros de uma vez. 😎 + +/// note | Nota + +Isso é possível desde a versão `0.115.0` do FastAPI. 🤓 + +/// + +## Parâmetros do Cabeçalho com um Modelo Pydantic + +Declare os **parâmetros de cabeçalho** que você precisa em um **modelo do Pydantic**, e então declare o parâmetro como `Header`: + +{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *} + +O **FastAPI** irá **extrair** os dados de **cada campo** a partir dos **cabeçalhos** da requisição e te retornará o modelo do Pydantic que você definiu. + +### Checando a documentação + +Você pode ver os headers necessários na interface gráfica da documentação em `/docs`: + +
+ +
+ +### Proibindo Cabeçalhos adicionais + +Em alguns casos de uso especiais (provavelmente não muito comuns), você pode querer **restringir** os cabeçalhos que você quer receber. + +Você pode usar a configuração dos modelos do Pydantic para proibir (`forbid`) quaisquer campos `extra`: + +{* ../../docs_src/header_param_models/tutorial002_an_py310.py hl[10] *} + +Se um cliente tentar enviar alguns **cabeçalhos extra**, eles irão receber uma resposta de **erro**. + +Por exemplo, se o cliente tentar enviar um cabeçalho `tool` com o valor `plumbus`, ele irá receber uma resposta de **erro** informando que o parâmetro do cabeçalho `tool` não é permitido: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["header", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus", + } + ] +} +``` + +## Resumo + +Você pode utilizar **modelos do Pydantic** para declarar **cabeçalhos** no **FastAPI**. 😎 diff --git a/docs/pt/docs/tutorial/header-params.md b/docs/pt/docs/tutorial/header-params.md index 4bdfb7e9c..d071bcc35 100644 --- a/docs/pt/docs/tutorial/header-params.md +++ b/docs/pt/docs/tutorial/header-params.md @@ -6,17 +6,7 @@ Você pode definir parâmetros de Cabeçalho da mesma maneira que define paramê Primeiro importe `Header`: -=== "Python 3.10+" - - ```Python hl_lines="1" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` +{* ../../docs_src/header_params/tutorial001_py310.py hl[1] *} ## Declare parâmetros de `Header` @@ -24,25 +14,21 @@ Então declare os paramêtros de cabeçalho usando a mesma estrutura que em `Pat O primeiro valor é o valor padrão, você pode passar todas as validações adicionais ou parâmetros de anotação: -=== "Python 3.10+" +{* ../../docs_src/header_params/tutorial001_py310.py hl[7] *} - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` +/// note | Detalhes Técnicos -=== "Python 3.8+" +`Header` é uma classe "irmã" de `Path`, `Query` e `Cookie`. Ela também herda da mesma classe em comum `Param`. - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` +Mas lembre-se que quando você importa `Query`, `Path`, `Header`, e outras de `fastapi`, elas são na verdade funções que retornam classes especiais. -!!! note "Detalhes Técnicos" - `Header` é uma classe "irmã" de `Path`, `Query` e `Cookie`. Ela também herda da mesma classe em comum `Param`. +/// - Mas lembre-se que quando você importa `Query`, `Path`, `Header`, e outras de `fastapi`, elas são na verdade funções que retornam classes especiais. +/// info -!!! info - Para declarar headers, você precisa usar `Header`, caso contrário, os parâmetros seriam interpretados como parâmetros de consulta. +Para declarar headers, você precisa usar `Header`, caso contrário, os parâmetros seriam interpretados como parâmetros de consulta. + +/// ## Conversão automática @@ -60,20 +46,13 @@ Portanto, você pode usar `user_agent` como faria normalmente no código Python, Se por algum motivo você precisar desabilitar a conversão automática de sublinhados para hífens, defina o parâmetro `convert_underscores` de `Header` para `False`: -=== "Python 3.10+" - - ```Python hl_lines="8" - {!> ../../../docs_src/header_params/tutorial002_py310.py!} - ``` +{* ../../docs_src/header_params/tutorial002_py310.py hl[8] *} -=== "Python 3.8+" +/// warning | Aviso - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial002.py!} - ``` +Antes de definir `convert_underscores` como `False`, lembre-se de que alguns proxies e servidores HTTP não permitem o uso de cabeçalhos com sublinhados. -!!! warning "Aviso" - Antes de definir `convert_underscores` como `False`, lembre-se de que alguns proxies e servidores HTTP não permitem o uso de cabeçalhos com sublinhados. +/// ## Cabeçalhos duplicados @@ -85,23 +64,7 @@ Você receberá todos os valores do cabeçalho duplicado como uma `list` Python. Por exemplo, para declarar um cabeçalho de `X-Token` que pode aparecer mais de uma vez, você pode escrever: -=== "Python 3.10+" - - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial003_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003.py!} - ``` +{* ../../docs_src/header_params/tutorial003_py310.py hl[7] *} Se você se comunicar com essa *operação de caminho* enviando dois cabeçalhos HTTP como: diff --git a/docs/pt/docs/tutorial/index.md b/docs/pt/docs/tutorial/index.md index 5fc0485a0..7c04b17f2 100644 --- a/docs/pt/docs/tutorial/index.md +++ b/docs/pt/docs/tutorial/index.md @@ -4,9 +4,7 @@ Esse tutorial mostra como usar o **FastAPI** com a maior parte de seus recursos, Cada seção constrói, gradualmente, sobre as anteriores, mas sua estrutura são tópicos separados, para que você possa ir a qualquer um específico e resolver suas necessidades específicas de API. -Ele também foi feito como referência futura. - -Então você poderá voltar e ver exatamente o que precisar. +Ele também foi construído para servir como uma referência futura, então você pode voltar e ver exatamente o que você precisa. ## Rode o código @@ -17,13 +15,39 @@ Para rodar qualquer um dos exemplos, copie o codigo para um arquivo `main.py`, e
```console -$ uvicorn main:app --reload +$ fastapi dev main.py + + FastAPI Starting development server 🚀 + + Searching for package file structure from directories + with __init__.py files + Importing from /home/user/code/awesomeapp + + module 🐍 main.py + + code Importing the FastAPI app object from the module with + the following code: + + from main import app + + app Using import string: main:app -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -INFO: Started reloader process [28720] -INFO: Started server process [28722] -INFO: Waiting for application startup. -INFO: Application startup complete. + server Server started at http://127.0.0.1:8000 + server Documentation at http://127.0.0.1:8000/docs + + tip Running in development mode, for production use: + fastapi run + + Logs: + + INFO Will watch for changes in these directories: + ['/home/user/code/awesomeapp'] + INFO Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C + to quit) + INFO Started reloader process [383138] using WatchFiles + INFO Started server process [383153] + INFO Waiting for application startup. + INFO Application startup complete. ```
@@ -43,31 +67,20 @@ Para o tutorial, você deve querer instalá-lo com todas as dependências e recu
```console -$ pip install "fastapi[all]" +$ pip install "fastapi[standard]" ---> 100% ```
-...isso também inclui o `uvicorn`, que você pode usar como o servidor que rodará seu código. - -!!! nota - Você também pode instalar parte por parte. - - Isso é provavelmente o que você faria quando você quisesse lançar sua aplicação em produção: - - ``` - pip install fastapi - ``` +/// note | Nota - Também instale o `uvicorn` para funcionar como servidor: +Quando você instala com pip install "fastapi[standard]", ele vem com algumas dependências opcionais padrão. - ``` - pip install "uvicorn[standard]" - ``` +Se você não quiser ter essas dependências opcionais, pode instalar pip install fastapi em vez disso. - E o mesmo para cada dependência opcional que você quiser usar. +/// ## Guia Avançado de Usuário diff --git a/docs/pt/docs/tutorial/metadata.md b/docs/pt/docs/tutorial/metadata.md new file mode 100644 index 000000000..57effb3ff --- /dev/null +++ b/docs/pt/docs/tutorial/metadata.md @@ -0,0 +1,120 @@ +# Metadados e Urls de Documentos + +Você pode personalizar várias configurações de metadados na sua aplicação **FastAPI**. + +## Metadados para API + +Você pode definir os seguintes campos que são usados na especificação OpenAPI e nas interfaces automáticas de documentação da API: + +| Parâmetro | Tipo | Descrição | +|------------|------|-------------| +| `title` | `str` | O título da API. | +| `summary` | `str` | Um breve resumo da API. Disponível desde OpenAPI 3.1.0, FastAPI 0.99.0. | +| `description` | `str` | Uma breve descrição da API. Pode usar Markdown. | +| `version` | `string` | A versão da API. Esta é a versão da sua aplicação, não do OpenAPI. Por exemplo, `2.5.0`. | +| `terms_of_service` | `str` | Uma URL para os Termos de Serviço da API. Se fornecido, deve ser uma URL. | +| `contact` | `dict` | As informações de contato da API exposta. Pode conter vários campos.
Campos de contact
ParâmetroTipoDescrição
namestrO nome identificador da pessoa/organização de contato.
urlstrA URL que aponta para as informações de contato. DEVE estar no formato de uma URL.
emailstrO endereço de e-mail da pessoa/organização de contato. DEVE estar no formato de um endereço de e-mail.
| +| `license_info` | `dict` | As informações de licença para a API exposta. Ela pode conter vários campos.
Campos de license_info
ParâmetroTipoDescrição
namestrOBRIGATÓRIO (se um license_info for definido). O nome da licença usada para a API.
identifierstrUma expressão de licença SPDX para a API. O campo identifier é mutuamente exclusivo do campo url. Disponível desde OpenAPI 3.1.0, FastAPI 0.99.0.
urlstrUma URL para a licença usada para a API. DEVE estar no formato de uma URL.
| + +Você pode defini-los da seguinte maneira: + +{* ../../docs_src/metadata/tutorial001.py hl[3:16,19:32] *} + +/// tip | Dica + +Você pode escrever Markdown no campo `description` e ele será renderizado na saída. + +/// + +Com essa configuração, a documentação automática da API se pareceria com: + + + +## Identificador de Licença + +Desde o OpenAPI 3.1.0 e FastAPI 0.99.0, você também pode definir o license_info com um identifier em vez de uma url. + +Por exemplo: + +{* ../../docs_src/metadata/tutorial001_1.py hl[31] *} + +## Metadados para tags + +Você também pode adicionar metadados adicionais para as diferentes tags usadas para agrupar suas operações de rota com o parâmetro `openapi_tags`. + +Ele recebe uma lista contendo um dicionário para cada tag. + +Cada dicionário pode conter: + +* `name` (**obrigatório**): uma `str` com o mesmo nome da tag que você usa no parâmetro `tags` nas suas *operações de rota* e `APIRouter`s. +* `description`: uma `str` com uma breve descrição da tag. Pode conter Markdown e será exibido na interface de documentação. +* `externalDocs`: um `dict` descrevendo a documentação externa com: + * `description`: uma `str` com uma breve descrição da documentação externa. + * `url` (**obrigatório**): uma `str` com a URL da documentação externa. + +### Criar Metadados para tags + +Vamos tentar isso em um exemplo com tags para `users` e `items`. + +Crie metadados para suas tags e passe-os para o parâmetro `openapi_tags`: + +{* ../../docs_src/metadata/tutorial004.py hl[3:16,18] *} + +Observe que você pode usar Markdown dentro das descrições. Por exemplo, "login" será exibido em negrito (**login**) e "fancy" será exibido em itálico (_fancy_). + +/// tip | Dica + +Você não precisa adicionar metadados para todas as tags que você usa. + +/// + +### Use suas tags + +Use o parâmetro `tags` com suas *operações de rota* (e `APIRouter`s) para atribuí-los a diferentes tags: + +{* ../../docs_src/metadata/tutorial004.py hl[21,26] *} + +/// info | Informação + +Leia mais sobre tags em [Configuração de Operação de Caminho](path-operation-configuration.md#tags){.internal-link target=_blank}. + +/// + +### Cheque os documentos + +Agora, se você verificar a documentação, ela exibirá todos os metadados adicionais: + + + +### Ordem das tags + +A ordem de cada dicionário de metadados de tag também define a ordem exibida na interface de documentação. + +Por exemplo, embora `users` apareça após `items` em ordem alfabética, ele é exibido antes deles, porque adicionamos seus metadados como o primeiro dicionário na lista. + +## URL da OpenAPI + +Por padrão, o esquema OpenAPI é servido em `/openapi.json`. + +Mas você pode configurá-lo com o parâmetro `openapi_url`. + +Por exemplo, para defini-lo para ser servido em `/api/v1/openapi.json`: + +{* ../../docs_src/metadata/tutorial002.py hl[3] *} + +Se você quiser desativar completamente o esquema OpenAPI, pode definir `openapi_url=None`, o que também desativará as interfaces de documentação que o utilizam. + +## URLs da Documentação + +Você pode configurar as duas interfaces de documentação incluídas: + +* **Swagger UI**: acessível em `/docs`. + * Você pode definir sua URL com o parâmetro `docs_url`. + * Você pode desativá-la definindo `docs_url=None`. +* **ReDoc**: acessível em `/redoc`. + * Você pode definir sua URL com o parâmetro `redoc_url`. + * Você pode desativá-la definindo `redoc_url=None`. + +Por exemplo, para definir o Swagger UI para ser servido em `/documentation` e desativar o ReDoc: + +{* ../../docs_src/metadata/tutorial003.py hl[3] *} diff --git a/docs/pt/docs/tutorial/middleware.md b/docs/pt/docs/tutorial/middleware.md new file mode 100644 index 000000000..32b81c646 --- /dev/null +++ b/docs/pt/docs/tutorial/middleware.md @@ -0,0 +1,66 @@ +# Middleware + +Você pode adicionar middleware à suas aplicações **FastAPI**. + +Um "middleware" é uma função que manipula cada **requisição** antes de ser processada por qualquer *operação de rota* específica. E também cada **resposta** antes de retorná-la. + +* Ele pega cada **requisição** que chega ao seu aplicativo. +* Ele pode então fazer algo com essa **requisição** ou executar qualquer código necessário. +* Então ele passa a **requisição** para ser processada pelo resto do aplicativo (por alguma *operação de rota*). +* Ele então pega a **resposta** gerada pelo aplicativo (por alguma *operação de rota*). +* Ele pode fazer algo com essa **resposta** ou executar qualquer código necessário. +* Então ele retorna a **resposta**. + +/// note | Detalhes técnicos + +Se você tiver dependências com `yield`, o código de saída será executado *depois* do middleware. + +Se houver alguma tarefa em segundo plano (documentada posteriormente), ela será executada *depois* de todo o middleware. + +/// + +## Criar um middleware + +Para criar um middleware, use o decorador `@app.middleware("http")` logo acima de uma função. + +A função middleware recebe: + +* A `request`. +* Uma função `call_next` que receberá o `request` como um parâmetro. + * Esta função passará a `request` para a *operação de rota* correspondente. + * Então ela retorna a `response` gerada pela *operação de rota* correspondente. +* Você pode então modificar ainda mais o `response` antes de retorná-lo. + +{* ../../docs_src/middleware/tutorial001.py hl[8:9,11,14] *} + +/// tip | Dica + +Tenha em mente que cabeçalhos proprietários personalizados podem ser adicionados usando o prefixo 'X-'. + +Mas se você tiver cabeçalhos personalizados desejando que um cliente em um navegador esteja apto a ver, você precisa adicioná-los às suas configurações CORS ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) usando o parâmetro `expose_headers` documentado em Documentos CORS da Starlette. + +/// + +/// note | Detalhes técnicos + +Você também pode usar `from starlette.requests import Request`. + +**FastAPI** fornece isso como uma conveniência para você, o desenvolvedor. Mas vem diretamente da Starlette. + +/// + +### Antes e depois da `response` + +Você pode adicionar código para ser executado com a `request`, antes que qualquer *operação de rota* o receba. + +E também depois que a `response` é gerada, antes de retorná-la. + +Por exemplo, você pode adicionar um cabeçalho personalizado `X-Process-Time` contendo o tempo em segundos que levou para processar a solicitação e gerar uma resposta: + +{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *} + +## Outros middlewares + +Mais tarde, você pode ler mais sobre outros middlewares no [Guia do usuário avançado: Middleware avançado](../advanced/middleware.md){.internal-link target=_blank}. + +Você lerá sobre como manipular CORS com um middleware na próxima seção. diff --git a/docs/pt/docs/tutorial/path-operation-configuration.md b/docs/pt/docs/tutorial/path-operation-configuration.md index 13a87240f..f183c9d23 100644 --- a/docs/pt/docs/tutorial/path-operation-configuration.md +++ b/docs/pt/docs/tutorial/path-operation-configuration.md @@ -2,8 +2,11 @@ Existem vários parâmetros que você pode passar para o seu *decorador de operação de rota* para configurá-lo. -!!! warning "Aviso" - Observe que esses parâmetros são passados diretamente para o *decorador de operação de rota*, não para a sua *função de operação de rota*. +/// warning | Aviso + +Observe que esses parâmetros são passados diretamente para o *decorador de operação de rota*, não para a sua *função de operação de rota*. + +/// ## Código de Status da Resposta @@ -13,52 +16,23 @@ Você pode passar diretamente o código `int`, como `404`. Mas se você não se lembrar o que cada código numérico significa, pode usar as constantes de atalho em `status`: -=== "Python 3.8 and above" - - ```Python hl_lines="3 17" - {!> ../../../docs_src/path_operation_configuration/tutorial001.py!} - ``` +{* ../../docs_src/path_operation_configuration/tutorial001.py hl[3,17] *} -=== "Python 3.9 and above" - - ```Python hl_lines="3 17" - {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} - ``` - -=== "Python 3.10 and above" +Esse código de status será usado na resposta e será adicionado ao esquema OpenAPI. - ```Python hl_lines="1 15" - {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} - ``` +/// note | Detalhes Técnicos -Esse código de status será usado na resposta e será adicionado ao esquema OpenAPI. +Você também poderia usar `from starlette import status`. -!!! note "Detalhes Técnicos" - Você também poderia usar `from starlette import status`. +**FastAPI** fornece o mesmo `starlette.status` como `fastapi.status` apenas como uma conveniência para você, o desenvolvedor. Mas vem diretamente do Starlette. - **FastAPI** fornece o mesmo `starlette.status` como `fastapi.status` apenas como uma conveniência para você, o desenvolvedor. Mas vem diretamente do Starlette. +/// ## Tags Você pode adicionar tags para sua *operação de rota*, passe o parâmetro `tags` com uma `list` de `str` (comumente apenas um `str`): -=== "Python 3.8 and above" - - ```Python hl_lines="17 22 27" - {!> ../../../docs_src/path_operation_configuration/tutorial002.py!} - ``` - -=== "Python 3.9 and above" - - ```Python hl_lines="17 22 27" - {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} - ``` - -=== "Python 3.10 and above" - - ```Python hl_lines="15 20 25" - {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} - ``` +{* ../../docs_src/path_operation_configuration/tutorial002.py hl[17,22,27] *} Eles serão adicionados ao esquema OpenAPI e usados pelas interfaces de documentação automática: @@ -72,31 +46,13 @@ Nestes casos, pode fazer sentido armazenar as tags em um `Enum`. **FastAPI** suporta isso da mesma maneira que com strings simples: -```Python hl_lines="1 8-10 13 18" -{!../../../docs_src/path_operation_configuration/tutorial002b.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial002b.py hl[1,8:10,13,18] *} ## Resumo e descrição Você pode adicionar um `summary` e uma `description`: -=== "Python 3.8 and above" - - ```Python hl_lines="20-21" - {!> ../../../docs_src/path_operation_configuration/tutorial003.py!} - ``` - -=== "Python 3.9 and above" - - ```Python hl_lines="20-21" - {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} - ``` - -=== "Python 3.10 and above" - - ```Python hl_lines="18-19" - {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} - ``` +{* ../../docs_src/path_operation_configuration/tutorial003.py hl[20:21] *} ## Descrição do docstring @@ -104,23 +60,7 @@ Como as descrições tendem a ser longas e cobrir várias linhas, você pode dec Você pode escrever Markdown na docstring, ele será interpretado e exibido corretamente (levando em conta a indentação da docstring). -=== "Python 3.8 and above" - - ```Python hl_lines="19-27" - {!> ../../../docs_src/path_operation_configuration/tutorial004.py!} - ``` - -=== "Python 3.9 and above" - - ```Python hl_lines="19-27" - {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} - ``` - -=== "Python 3.10 and above" - - ```Python hl_lines="17-25" - {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} - ``` +{* ../../docs_src/path_operation_configuration/tutorial004.py hl[19:27] *} Ela será usada nas documentações interativas: @@ -131,31 +71,21 @@ Ela será usada nas documentações interativas: Você pode especificar a descrição da resposta com o parâmetro `response_description`: -=== "Python 3.8 and above" - - ```Python hl_lines="21" - {!> ../../../docs_src/path_operation_configuration/tutorial005.py!} - ``` +{* ../../docs_src/path_operation_configuration/tutorial005.py hl[21] *} -=== "Python 3.9 and above" +/// info | Informação - ```Python hl_lines="21" - {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} - ``` +Note que `response_description` se refere especificamente à resposta, a `description` se refere à *operação de rota* em geral. -=== "Python 3.10 and above" +/// - ```Python hl_lines="19" - {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} - ``` +/// check -!!! info "Informação" - Note que `response_description` se refere especificamente à resposta, a `description` se refere à *operação de rota* em geral. +OpenAPI especifica que cada *operação de rota* requer uma descrição de resposta. -!!! check - OpenAPI especifica que cada *operação de rota* requer uma descrição de resposta. +Então, se você não fornecer uma, o **FastAPI** irá gerar automaticamente uma de "Resposta bem-sucedida". - Então, se você não fornecer uma, o **FastAPI** irá gerar automaticamente uma de "Resposta bem-sucedida". +/// @@ -163,9 +93,7 @@ Você pode especificar a descrição da resposta com o parâmetro `response_desc Se você precisar marcar uma *operação de rota* como descontinuada, mas sem removê-la, passe o parâmetro `deprecated`: -```Python hl_lines="16" -{!../../../docs_src/path_operation_configuration/tutorial006.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial006.py hl[16] *} Ela será claramente marcada como descontinuada nas documentações interativas: diff --git a/docs/pt/docs/tutorial/path-params-numeric-validations.md b/docs/pt/docs/tutorial/path-params-numeric-validations.md index eb0d31dc3..3aea1188d 100644 --- a/docs/pt/docs/tutorial/path-params-numeric-validations.md +++ b/docs/pt/docs/tutorial/path-params-numeric-validations.md @@ -6,17 +6,7 @@ Do mesmo modo que você pode declarar mais validações e metadados para parâme Primeiro, importe `Path` de `fastapi`: -=== "Python 3.10+" - - ```Python hl_lines="1" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +{* ../../docs_src/path_params_numeric_validations/tutorial001_py310.py hl[1] *} ## Declare metadados @@ -24,24 +14,17 @@ Você pode declarar todos os parâmetros da mesma maneira que na `Query`. Por exemplo para declarar um valor de metadado `title` para o parâmetro de rota `item_id` você pode digitar: -=== "Python 3.10+" - - ```Python hl_lines="8" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +{* ../../docs_src/path_params_numeric_validations/tutorial001_py310.py hl[8] *} -=== "Python 3.8+" +/// note | Nota - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +Um parâmetro de rota é sempre obrigatório, como se fizesse parte da rota. -!!! note "Nota" - Um parâmetro de rota é sempre obrigatório, como se fizesse parte da rota. +Então, você deve declará-lo com `...` para marcá-lo como obrigatório. - Então, você deve declará-lo com `...` para marcá-lo como obrigatório. +Mesmo que você declare-o como `None` ou defina um valor padrão, isso não teria efeito algum, o parâmetro ainda seria obrigatório. - Mesmo que você declare-o como `None` ou defina um valor padrão, isso não teria efeito algum, o parâmetro ainda seria obrigatório. +/// ## Ordene os parâmetros de acordo com sua necessidade @@ -59,9 +42,7 @@ Isso não faz diferença para o **FastAPI**. Ele vai detectar os parâmetros pel Então, você pode declarar sua função assim: -```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial002.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial002.py hl[7] *} ## Ordene os parâmetros de a acordo com sua necessidade, truques @@ -71,9 +52,7 @@ Passe `*`, como o primeiro parâmetro da função. O Python não vai fazer nada com esse `*`, mas ele vai saber que a partir dali os parâmetros seguintes deverão ser chamados argumentos nomeados (pares chave-valor), também conhecidos como kwargs. Mesmo que eles não possuam um valor padrão. -```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial003.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *} ## Validações numéricas: maior que ou igual @@ -81,9 +60,7 @@ Com `Query` e `Path` (e outras que você verá mais tarde) você pode declarar r Aqui, com `ge=1`, `item_id` precisará ser um número inteiro maior que ("`g`reater than") ou igual ("`e`qual") a 1. -```Python hl_lines="8" -{!../../../docs_src/path_params_numeric_validations/tutorial004.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial004.py hl[8] *} ## Validações numéricas: maior que e menor que ou igual @@ -92,9 +69,7 @@ O mesmo se aplica para: * `gt`: maior que (`g`reater `t`han) * `le`: menor que ou igual (`l`ess than or `e`qual) -```Python hl_lines="9" -{!../../../docs_src/path_params_numeric_validations/tutorial005.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial005.py hl[9] *} ## Validações numéricas: valores do tipo float, maior que e menor que @@ -106,9 +81,7 @@ Assim, `0.5` seria um valor válido. Mas `0.0` ou `0` não seria. E o mesmo para lt. -```Python hl_lines="11" -{!../../../docs_src/path_params_numeric_validations/tutorial006.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial006.py hl[11] *} ## Recapitulando @@ -121,18 +94,24 @@ E você também pode declarar validações numéricas: * `lt`: menor que (`l`ess `t`han) * `le`: menor que ou igual (`l`ess than or `e`qual) -!!! info "Informação" - `Query`, `Path` e outras classes que você verá a frente são subclasses de uma classe comum `Param`. +/// info | Informação + +`Query`, `Path` e outras classes que você verá a frente são subclasses de uma classe comum `Param`. + +Todas elas compartilham os mesmos parâmetros para validação adicional e metadados que você viu. + +/// + +/// note | Detalhes Técnicos - Todas elas compartilham os mesmos parâmetros para validação adicional e metadados que você viu. +Quando você importa `Query`, `Path` e outras de `fastapi`, elas são na verdade funções. -!!! note "Detalhes Técnicos" - Quando você importa `Query`, `Path` e outras de `fastapi`, elas são na verdade funções. +Que quando chamadas, retornam instâncias de classes de mesmo nome. - Que quando chamadas, retornam instâncias de classes de mesmo nome. +Então, você importa `Query`, que é uma função. E quando você a chama, ela retorna uma instância de uma classe também chamada `Query`. - Então, você importa `Query`, que é uma função. E quando você a chama, ela retorna uma instância de uma classe também chamada `Query`. +Estas funções são assim (ao invés de apenas usar as classes diretamente) para que seu editor não acuse erros sobre seus tipos. - Estas funções são assim (ao invés de apenas usar as classes diretamente) para que seu editor não acuse erros sobre seus tipos. +Dessa maneira você pode user seu editor e ferramentas de desenvolvimento sem precisar adicionar configurações customizadas para ignorar estes erros. - Dessa maneira você pode user seu editor e ferramentas de desenvolvimento sem precisar adicionar configurações customizadas para ignorar estes erros. +/// diff --git a/docs/pt/docs/tutorial/path-params.md b/docs/pt/docs/tutorial/path-params.md index cd8c18858..ecf77d676 100644 --- a/docs/pt/docs/tutorial/path-params.md +++ b/docs/pt/docs/tutorial/path-params.md @@ -2,9 +2,7 @@ Você pode declarar os "parâmetros" ou "variáveis" com a mesma sintaxe utilizada pelo formato de strings do Python: -```Python hl_lines="6-7" -{!../../../docs_src/path_params/tutorial001.py!} -``` +{* ../../docs_src/path_params/tutorial001.py hl[6:7] *} O valor do parâmetro que foi passado à `item_id` será passado para a sua função como o argumento `item_id`. @@ -18,13 +16,16 @@ Então, se você rodar este exemplo e for até dados @@ -35,7 +36,12 @@ Se você rodar esse exemplo e abrir o seu navegador em "parsing" automático no request . @@ -63,7 +69,12 @@ devido ao parâmetro da rota `item_id` ter um valor `"foo"`, que não é um `int O mesmo erro apareceria se você tivesse fornecido um `float` ao invés de um `int`, como em: http://127.0.0.1:8000/items/4.2 -!!! Verifique +/// check | Verifique + + + +/// + Então, com a mesma declaração de tipo do Python, o **FastAPI** dá pra você validação de dados. Observe que o erro também mostra claramente o ponto exato onde a validação não passou. @@ -76,7 +87,12 @@ Quando você abrir o seu navegador em -!!! check +/// check | Verifique + + + +/// + Novamente, apenas com a mesma declaração de tipo do Python, o **FastAPI** te dá de forma automática e interativa a documentação (integrada com o Swagger UI). Veja que o parâmetro de rota está declarado como sendo um inteiro (int). @@ -93,7 +109,7 @@ Da mesma forma, existem muitas ferramentas compatíveis. Incluindo ferramentas d ## Pydantic -Toda a validação de dados é feita por baixo dos panos pelo Pydantic, então você tem todos os benefícios disso. E assim você sabe que está em boas mãos. +Toda a validação de dados é feita por baixo dos panos pelo Pydantic, então você tem todos os benefícios disso. E assim você sabe que está em boas mãos. Você pode usar as mesmas declarações de tipo com `str`, `float`, `bool` e muitos outros tipos complexos de dados. @@ -109,9 +125,7 @@ E então você pode ter também uma rota `/users/{user_id}` para pegar dados sob Porque as operações de rota são avaliadas em ordem, você precisa ter certeza que a rota para `/users/me` está sendo declarado antes da rota `/users/{user_id}`: -```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003.py!} -``` +{* ../../docs_src/path_params/tutorial003.py hl[6,11] *} Caso contrário, a rota para `/users/{user_id}` coincidiria também para `/users/me`, "pensando" que estaria recebendo o parâmetro `user_id` com o valor de `"me"`. @@ -127,23 +141,27 @@ Por herdar de `str` a documentação da API vai ser capaz de saber que os valore Assim, crie atributos de classe com valores fixos, que serão os valores válidos disponíveis. -```Python hl_lines="1 6-9" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *} -!!! informação - Enumerations (ou enums) estão disponíveis no Python desde a versão 3.4. +/// info | informação + +Enumerations (ou enums) estão disponíveis no Python desde a versão 3.4. + +/// + +/// tip | Dica + + + +/// -!!! dica Se você está se perguntando, "AlexNet", "ResNet", e "LeNet" são apenas nomes de modelos de Machine Learning (aprendizado de máquina). ### Declare um *parâmetro de rota* Logo, crie um *parâmetro de rota* com anotações de tipo usando a classe enum que você criou (`ModelName`): -```Python hl_lines="16" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[16] *} ### Revise a documentação @@ -159,19 +177,20 @@ O valor do *parâmetro da rota* será um *membro de enumeration*. Você pode comparar eles com o *membro de enumeration* no enum `ModelName` que você criou: -```Python hl_lines="17" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[17] *} #### Obtenha o *valor de enumerate* Você pode ter o valor exato de enumerate (um `str` nesse caso) usando `model_name.value`, ou em geral, `your_enum_member.value`: -```Python hl_lines="20" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[20] *} + +/// tip | Dica + + + +/// -!!! conselho Você também poderia acessar o valor `"lenet"` com `ModelName.lenet.value` #### Retorne *membros de enumeration* @@ -180,9 +199,7 @@ Você pode retornar *membros de enum* da sua *rota de operação*, em um corpo J Eles serão convertidos para o seus valores correspondentes (strings nesse caso) antes de serem retornados ao cliente: -```Python hl_lines="18 21 23" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *} No seu cliente você vai obter uma resposta JSON como: @@ -221,11 +238,14 @@ Nesse caso, o nome do parâmetro é `file_path`, e a última parte, `:path`, diz Então, você poderia usar ele com: -```Python hl_lines="6" -{!../../../docs_src/path_params/tutorial004.py!} -``` +{* ../../docs_src/path_params/tutorial004.py hl[6] *} + +/// tip | Dica + + + +/// -!!! dica Você poderia precisar que o parâmetro contivesse `/home/johndoe/myfile.txt`, com uma barra no inicio (`/`). Neste caso, a URL deveria ser: `/files//home/johndoe/myfile.txt`, com barra dupla (`//`) entre `files` e `home`. diff --git a/docs/pt/docs/tutorial/query-param-models.md b/docs/pt/docs/tutorial/query-param-models.md new file mode 100644 index 000000000..01a6e462f --- /dev/null +++ b/docs/pt/docs/tutorial/query-param-models.md @@ -0,0 +1,69 @@ +# Modelos de Parâmetros de Consulta + +Se você possui um grupo de **parâmetros de consultas** que são relacionados, você pode criar um **modelo Pydantic** para declará-los. + +Isso permitiria que você **reutilizasse o modelo** em **diversos lugares**, e também declarasse validações e metadados de todos os parâmetros de uma única vez. 😎 + +/// note | Nota + +Isso é suportado desde o FastAPI versão `0.115.0`. 🤓 + +/// + +## Parâmetros de Consulta com um Modelo Pydantic + +Declare os **parâmetros de consulta** que você precisa em um **modelo Pydantic**, e então declare o parâmetro como `Query`: + +{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *} + +O **FastAPI** **extrairá** os dados para **cada campo** dos **parâmetros de consulta** presentes na requisição, e fornecerá o modelo Pydantic que você definiu. + + +## Verifique os Documentos + +Você pode ver os parâmetros de consulta nos documentos de IU em `/docs`: + +
+ +
+ +## Restrinja Parâmetros de Consulta Extras + +Em alguns casos especiais (provavelmente não muito comuns), você queira **restrinjir** os parâmetros de consulta que deseja receber. + +Você pode usar a configuração do modelo Pydantic para `forbid` (proibir) qualquer campo `extra`: + +{* ../../docs_src/query_param_models/tutorial002_an_py310.py hl[10] *} + +Caso um cliente tente enviar alguns dados **extras** nos **parâmetros de consulta**, eles receberão um retorno de **erro**. + +Por exemplo, se o cliente tentar enviar um parâmetro de consulta `tool` com o valor `plumbus`, como: + +```http +https://example.com/items/?limit=10&tool=plumbus +``` + +Eles receberão um retorno de **erro** informando-os que o parâmentro de consulta `tool` não é permitido: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["query", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus" + } + ] +} +``` + +## Resumo + +Você pode utilizar **modelos Pydantic** para declarar **parâmetros de consulta** no **FastAPI**. 😎 + +/// tip | Dica + +Alerta de spoiler: você também pode utilizar modelos Pydantic para declarar cookies e cabeçalhos, mas você irá ler sobre isso mais a frente no tutorial. 🤫 + +/// diff --git a/docs/pt/docs/tutorial/query-params-str-validations.md b/docs/pt/docs/tutorial/query-params-str-validations.md index 9a9e071db..8c4f2e655 100644 --- a/docs/pt/docs/tutorial/query-params-str-validations.md +++ b/docs/pt/docs/tutorial/query-params-str-validations.md @@ -4,16 +4,17 @@ O **FastAPI** permite que você declare informações adicionais e validações Vamos utilizar essa aplicação como exemplo: -```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial001.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial001.py hl[9] *} O parâmetro de consulta `q` é do tipo `Union[str, None]`, o que significa que é do tipo `str` mas que também pode ser `None`, e de fato, o valor padrão é `None`, então o FastAPI saberá que não é obrigatório. -!!! note "Observação" - O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`. +/// note | Observação + +O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`. - O `Union` em `Union[str, None]` não é usado pelo FastAPI, mas permitirá que seu editor lhe dê um melhor suporte e detecte erros. +O `Union` em `Union[str, None]` não é usado pelo FastAPI, mas permitirá que seu editor lhe dê um melhor suporte e detecte erros. + +/// ## Validação adicional @@ -23,17 +24,13 @@ Nós iremos forçar que mesmo o parâmetro `q` seja opcional, sempre que informa Para isso, primeiro importe `Query` de `fastapi`: -```Python hl_lines="3" -{!../../../docs_src/query_params_str_validations/tutorial002.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[3] *} ## Use `Query` como o valor padrão Agora utilize-o como valor padrão do seu parâmetro, definindo o parâmetro `max_length` para 50: -```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial002.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[9] *} Note que substituímos o valor padrão de `None` para `Query(default=None)`, o primeiro parâmetro de `Query` serve para o mesmo propósito: definir o valor padrão do parâmetro. @@ -51,22 +48,25 @@ q: Union[str, None] = None Mas o declara explicitamente como um parâmetro de consulta. -!!! info "Informação" - Tenha em mente que o FastAPI se preocupa com a parte: +/// info | Informação + +Tenha em mente que o FastAPI se preocupa com a parte: + +```Python += None +``` - ```Python - = None - ``` +Ou com: - Ou com: +```Python += Query(default=None) +``` - ```Python - = Query(default=None) - ``` +E irá utilizar o `None` para detectar que o parâmetro de consulta não é obrigatório. - E irá utilizar o `None` para detectar que o parâmetro de consulta não é obrigatório. +O `Union` é apenas para permitir que seu editor de texto lhe dê um melhor suporte. - O `Union` é apenas para permitir que seu editor de texto lhe dê um melhor suporte. +/// Então, podemos passar mais parâmetros para `Query`. Neste caso, o parâmetro `max_length` que se aplica a textos: @@ -80,17 +80,13 @@ Isso irá validar os dados, mostrar um erro claro quando os dados forem inválid Você também pode incluir um parâmetro `min_length`: -```Python hl_lines="10" -{!../../../docs_src/query_params_str_validations/tutorial003.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial003.py hl[10] *} ## Adicionando expressões regulares Você pode definir uma expressão regular que combine com um padrão esperado pelo parâmetro: -```Python hl_lines="11" -{!../../../docs_src/query_params_str_validations/tutorial004.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial004.py hl[11] *} Essa expressão regular específica verifica se o valor recebido no parâmetro: @@ -108,12 +104,13 @@ Da mesma maneira que você utiliza `None` como o primeiro argumento para ser uti Vamos dizer que você queira que o parâmetro de consulta `q` tenha um `min_length` de `3`, e um valor padrão de `"fixedquery"`, então declararíamos assim: -```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial005.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial005.py hl[7] *} + +/// note | Observação + +O parâmetro torna-se opcional quando possui um valor padrão. -!!! note "Observação" - O parâmetro torna-se opcional quando possui um valor padrão. +/// ## Torne-o obrigatório @@ -137,12 +134,13 @@ q: Union[str, None] = Query(default=None, min_length=3) Então, quando você precisa declarar um parâmetro obrigatório utilizando o `Query`, você pode utilizar `...` como o primeiro argumento: -```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial006.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial006.py hl[7] *} + +/// info | Informação -!!! info "Informação" - Se você nunca viu os `...` antes: é um valor único especial, faz parte do Python e é chamado "Ellipsis". +Se você nunca viu os `...` antes: é um valor único especial, faz parte do Python e é chamado "Ellipsis". + +/// Dessa forma o **FastAPI** saberá que o parâmetro é obrigatório. @@ -152,9 +150,7 @@ Quando você declara explicitamente um parâmetro com `Query` você pode declar Por exemplo, para declarar que o parâmetro `q` pode aparecer diversas vezes na URL, você escreveria: -```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial011.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial011.py hl[9] *} Então, com uma URL assim: @@ -175,8 +171,11 @@ Assim, a resposta para essa URL seria: } ``` -!!! tip "Dica" - Para declarar um parâmetro de consulta com o tipo `list`, como no exemplo acima, você precisa usar explicitamente o `Query`, caso contrário será interpretado como um corpo da requisição. +/// tip | Dica + +Para declarar um parâmetro de consulta com o tipo `list`, como no exemplo acima, você precisa usar explicitamente o `Query`, caso contrário será interpretado como um corpo da requisição. + +/// A documentação interativa da API irá atualizar de acordo, permitindo múltiplos valores: @@ -186,9 +185,7 @@ A documentação interativa da API irá atualizar de acordo, permitindo múltipl E você também pode definir uma lista (`list`) de valores padrão caso nenhum seja informado: -```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial012.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial012.py hl[9] *} Se você for até: @@ -211,14 +208,15 @@ O valor padrão de `q` será: `["foo", "bar"]` e sua resposta será: Você também pode utilizar o tipo `list` diretamente em vez de `List[str]`: -```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial013.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial013.py hl[7] *} -!!! note "Observação" - Tenha em mente que neste caso, o FastAPI não irá validar os conteúdos da lista. +/// note | Observação - Por exemplo, um `List[int]` iria validar (e documentar) que os contéudos da lista são números inteiros. Mas apenas `list` não. +Tenha em mente que neste caso, o FastAPI não irá validar os conteúdos da lista. + +Por exemplo, um `List[int]` iria validar (e documentar) que os contéudos da lista são números inteiros. Mas apenas `list` não. + +/// ## Declarando mais metadados @@ -226,22 +224,21 @@ Você pode adicionar mais informações sobre o parâmetro. Essa informações serão inclusas no esquema do OpenAPI e utilizado pela documentação interativa e ferramentas externas. -!!! note "Observação" - Tenha em mente que cada ferramenta oferece diferentes níveis de suporte ao OpenAPI. +/// note | Observação + +Tenha em mente que cada ferramenta oferece diferentes níveis de suporte ao OpenAPI. + +Algumas delas não exibem todas as informações extras que declaramos, ainda que na maioria dos casos, esses recursos estão planejados para desenvolvimento. - Algumas delas não exibem todas as informações extras que declaramos, ainda que na maioria dos casos, esses recursos estão planejados para desenvolvimento. +/// Você pode adicionar um `title`: -```Python hl_lines="10" -{!../../../docs_src/query_params_str_validations/tutorial007.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial007.py hl[10] *} E uma `description`: -```Python hl_lines="13" -{!../../../docs_src/query_params_str_validations/tutorial008.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial008.py hl[13] *} ## Apelidos (alias) de parâmetros @@ -261,9 +258,7 @@ Mas ainda você precisa que o nome seja exatamente `item-query`... Então você pode declarar um `alias`, e esse apelido (alias) que será utilizado para encontrar o valor do parâmetro: -```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial009.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial009.py hl[9] *} ## Parâmetros descontinuados @@ -273,9 +268,7 @@ Você tem que deixá-lo ativo por um tempo, já que existem clientes o utilizand Então você passa o parâmetro `deprecated=True` para `Query`: -```Python hl_lines="18" -{!../../../docs_src/query_params_str_validations/tutorial010.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial010.py hl[18] *} Na documentação aparecerá assim: diff --git a/docs/pt/docs/tutorial/query-params.md b/docs/pt/docs/tutorial/query-params.md index 08bb99dbc..8199de5af 100644 --- a/docs/pt/docs/tutorial/query-params.md +++ b/docs/pt/docs/tutorial/query-params.md @@ -2,9 +2,7 @@ Quando você declara outros parâmetros na função que não fazem parte dos parâmetros da rota, esses parâmetros são automaticamente interpretados como parâmetros de "consulta". -```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial001.py!} -``` +{* ../../docs_src/query_params/tutorial001.py hl[9] *} A consulta é o conjunto de pares chave-valor que vai depois de `?` na URL, separado pelo caractere `&`. @@ -63,39 +61,21 @@ Os valores dos parâmetros na sua função serão: Da mesma forma, você pode declarar parâmetros de consulta opcionais, definindo o valor padrão para `None`: -=== "Python 3.10+" - - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial002_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial002.py!} - ``` +{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *} Nesse caso, o parâmetro da função `q` será opcional, e `None` será o padrão. -!!! check "Verificar" - Você também pode notar que o **FastAPI** é esperto o suficiente para perceber que o parâmetro da rota `item_id` é um parâmetro da rota, e `q` não é, portanto, `q` é o parâmetro de consulta. +/// check | Verificar + +Você também pode notar que o **FastAPI** é esperto o suficiente para perceber que o parâmetro da rota `item_id` é um parâmetro da rota, e `q` não é, portanto, `q` é o parâmetro de consulta. +/// ## Conversão dos tipos de parâmetros de consulta Você também pode declarar tipos `bool`, e eles serão convertidos: -=== "Python 3.10+" - - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial003_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial003.py!} - ``` +{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *} Nesse caso, se você for para: @@ -137,17 +117,7 @@ E você não precisa declarar eles em nenhuma ordem específica. Eles serão detectados pelo nome: -=== "Python 3.10+" - - ```Python hl_lines="6 8" - {!> ../../../docs_src/query_params/tutorial004_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="8 10" - {!> ../../../docs_src/query_params/tutorial004.py!} - ``` +{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *} ## Parâmetros de consulta obrigatórios @@ -157,9 +127,7 @@ Caso você não queira adicionar um valor específico mas queira apenas torná-l Porém, quando você quiser fazer com que o parâmetro de consulta seja obrigatório, você pode simplesmente não declarar nenhum valor como padrão. -```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} -``` +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} Aqui o parâmetro de consulta `needy` é um valor obrigatório, do tipo `str`. @@ -203,17 +171,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy E claro, você pode definir alguns parâmetros como obrigatórios, alguns possuindo um valor padrão, e outros sendo totalmente opcionais: -=== "Python 3.10+" - - ```Python hl_lines="8" - {!> ../../../docs_src/query_params/tutorial006_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="10" - {!> ../../../docs_src/query_params/tutorial006.py!} - ``` +{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *} Nesse caso, existem 3 parâmetros de consulta: @@ -221,5 +179,8 @@ Nesse caso, existem 3 parâmetros de consulta: * `skip`, um `int` com o valor padrão `0`. * `limit`, um `int` opcional. -!!! tip "Dica" - Você também poderia usar `Enum` da mesma forma que com [Path Parameters](path-params.md#predefined-values){.internal-link target=_blank}. +/// tip | Dica + +Você também poderia usar `Enum` da mesma forma que com [Path Parameters](path-params.md#valores-predefinidos){.internal-link target=_blank}. + +/// diff --git a/docs/pt/docs/tutorial/request-files.md b/docs/pt/docs/tutorial/request-files.md new file mode 100644 index 000000000..c22c1c513 --- /dev/null +++ b/docs/pt/docs/tutorial/request-files.md @@ -0,0 +1,176 @@ +# Arquivos de Requisição + +Você pode definir arquivos para serem enviados pelo cliente usando `File`. + +/// info | Informação + +Para receber arquivos enviados, primeiro instale o `python-multipart`. + +Garanta que você criou um [ambiente virtual](../virtual-environments.md){.internal-link target=_blank}, o ativou e então o instalou, por exemplo: + +```console +$ pip install python-multipart +``` + +Isso é necessário, visto que os arquivos enviados são enviados como "dados de formulário". + +/// + +## Importe `File` + +Importe `File` e `UploadFile` de `fastapi`: + +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[3] *} + +## Definir Parâmetros `File` + +Crie parâmetros de arquivo da mesma forma que você faria para `Body` ou `Form`: + +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[9] *} + +/// info | Informação + +`File` é uma classe que herda diretamente de `Form`. + +Mas lembre-se que quando você importa `Query`, `Path`, `File` e outros de `fastapi`, eles são, na verdade, funções que retornam classes especiais. + +/// + +/// tip | Dica + +Para declarar corpos de arquivos, você precisa usar `File`, caso contrário, os parâmetros seriam interpretados como parâmetros de consulta ou parâmetros de corpo (JSON). + +/// + +Os arquivos serão enviados como "dados de formulário". + +Se você declarar o tipo do parâmetro da função da sua *operação de rota* como `bytes`, o **FastAPI** lerá o arquivo para você e você receberá o conteúdo como `bytes`. + +Mantenha em mente que isso significa que todo o conteúdo será armazenado na memória. Isso funcionará bem para arquivos pequenos. + +Mas há muitos casos em que você pode se beneficiar do uso de `UploadFile`. + +## Parâmetros de Arquivo com `UploadFile` + +Defina um parâmetro de arquivo com um tipo de `UploadFile`: + +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[14] *} + +Utilizar `UploadFile` tem várias vantagens sobre `bytes`: + +* Você não precisa utilizar o `File()` no valor padrão do parâmetro. +* Ele utiliza um arquivo "spooled": + * Um arquivo armazenado na memória até um limite máximo de tamanho, e após passar esse limite, ele será armazenado no disco. +* Isso significa que funcionará bem para arquivos grandes como imagens, vídeos, binários grandes, etc., sem consumir toda a memória. +* Você pode receber metadados do arquivo enviado. +* Ele tem uma file-like interface `assíncrona`. +* Ele expõe um objeto python `SpooledTemporaryFile` que você pode passar diretamente para outras bibliotecas que esperam um objeto semelhante a um arquivo("file-like"). + +### `UploadFile` + +`UploadFile` tem os seguintes atributos: + +* `filename`: Uma `str` com o nome do arquivo original que foi enviado (por exemplo, `myimage.jpg`). +* `content_type`: Uma `str` com o tipo de conteúdo (tipo MIME / tipo de mídia) (por exemplo, `image/jpeg`). +* `file`: Um `SpooledTemporaryFile` (um file-like objeto). Este é o objeto de arquivo Python que você pode passar diretamente para outras funções ou bibliotecas que esperam um objeto semelhante a um arquivo("file-like"). + +`UploadFile` tem os seguintes métodos `assíncronos`. Todos eles chamam os métodos de arquivo correspondentes por baixo dos panos (usando o `SpooledTemporaryFile` interno). + +* `write(data)`: Escreve `data` (`str` ou `bytes`) no arquivo. +* `read(size)`: Lê `size` (`int`) bytes/caracteres do arquivo. +* `seek(offset)`: Vai para o byte na posição `offset` (`int`) no arquivo. + * Por exemplo, `await myfile.seek(0)` irá para o início do arquivo. + * Isso é especialmente útil se você executar `await myfile.read()` uma vez e precisar ler o conteúdo novamente. +* `close()`: Fecha o arquivo. + +Como todos esses métodos são métodos `assíncronos`, você precisa "aguardar" por eles. + +Por exemplo, dentro de uma função de *operação de rota* `assíncrona`, você pode obter o conteúdo com: + +```Python +contents = await myfile.read() +``` + +Se você estiver dentro de uma função de *operação de rota* normal `def`, você pode acessar o `UploadFile.file` diretamente, por exemplo: + +```Python +contents = myfile.file.read() +``` + +/// note | Detalhes Técnicos do `async` + +Quando você usa os métodos `async`, o **FastAPI** executa os métodos de arquivo em um threadpool e aguarda por eles. + +/// + +/// note | Detalhes Técnicos do Starlette + +O `UploadFile` do ***FastAPI** herda diretamente do `UploadFile` do **Starlette** , mas adiciona algumas partes necessárias para torná-lo compatível com o **Pydantic** e as outras partes do FastAPI. + +/// + +## O que é "Form Data" + +O jeito que os formulários HTML (`
`) enviam os dados para o servidor normalmente usa uma codificação "especial" para esses dados, a qual é diferente do JSON. + +**FastAPI** se certificará de ler esses dados do lugar certo, ao invés de JSON. + +/// note | Detalhes Técnicos + +Dados de formulários normalmente são codificados usando o "media type" (tipo de mídia) `application/x-www-form-urlencoded` quando não incluem arquivos. + +Mas quando o formulário inclui arquivos, ele é codificado como `multipart/form-data`. Se você usar `File`, o **FastAPI** saberá que tem que pegar os arquivos da parte correta do corpo da requisição. + +Se você quiser ler mais sobre essas codificações e campos de formulário, vá para a MDN web docs para POST. + +/// + +/// warning | Aviso + +Você pode declarar múltiplos parâmetros `File` e `Form` em uma *operação de rota*, mas você não pode declarar campos `Body` que você espera receber como JSON, pois a requisição terá o corpo codificado usando `multipart/form-data` ao invés de `application/json`. + +Isso não é uma limitação do **FastAPI**, é parte do protocolo HTTP. + +/// + +## Upload de Arquivo Opcional + +Você pode tornar um arquivo opcional usando anotações de tipo padrão e definindo um valor padrão de `None`: + +{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *} + +## `UploadFile` com Metadados Adicionais + +Você também pode usar `File()` com `UploadFile`, por exemplo, para definir metadados adicionais: + +{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *} + +## Uploads de Múltiplos Arquivos + +É possível realizar o upload de vários arquivos ao mesmo tempo. + +Eles serão associados ao mesmo "campo de formulário" enviado usando "dados de formulário". + +Para usar isso, declare uma lista de `bytes` ou `UploadFile`: + +{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *} + +Você receberá, tal como declarado, uma `list` de `bytes` ou `UploadFile`. + +/// note | Detalhes Técnicos + +Você pode também pode usar `from starlette.responses import HTMLResponse`. + +**FastAPI** providencia o mesmo `starlette.responses` que `fastapi.responses` apenas como uma conveniência para você, o desenvolvedor. Mas a maioria das respostas disponíveis vem diretamente do Starlette. + +/// + +### Uploads de Múltiplos Arquivos com Metadados Adicionais + +Da mesma forma de antes, você pode usar `File()` para definir parâmetros adicionais, mesmo para `UploadFile`: + +{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *} + +## Recapitulando + +Utilize `File`, `bytes` e `UploadFile` para declarar arquivos a serem enviados na requisição, enviados como dados de formulário. diff --git a/docs/pt/docs/tutorial/request-form-models.md b/docs/pt/docs/tutorial/request-form-models.md new file mode 100644 index 000000000..ea0e63d38 --- /dev/null +++ b/docs/pt/docs/tutorial/request-form-models.md @@ -0,0 +1,78 @@ +# Modelos de Formulários + +Você pode utilizar **Modelos Pydantic** para declarar **campos de formulários** no FastAPI. + +/// info | Informação + +Para utilizar formulários, instale primeiramente o `python-multipart`. + +Certifique-se de criar um [ambiente virtual](../virtual-environments.md){.internal-link target=_blank}, ativá-lo, e então instalar. Por exemplo: + +```console +$ pip install python-multipart +``` + +/// + +/// note | Nota + +Isto é suportado desde a versão `0.113.0` do FastAPI. 🤓 + +/// + +## Modelos Pydantic para Formulários + +Você precisa apenas declarar um **modelo Pydantic** com os campos que deseja receber como **campos de formulários**, e então declarar o parâmetro como um `Form`: + +{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *} + +O **FastAPI** irá **extrair** as informações para **cada campo** dos **dados do formulário** na requisição e dar para você o modelo Pydantic que você definiu. + +## Confira os Documentos + +Você pode verificar na UI de documentação em `/docs`: + +
+ +
+ +## Proibir Campos Extras de Formulários + +Em alguns casos de uso especiais (provavelmente não muito comum), você pode desejar **restringir** os campos do formulário para aceitar apenas os declarados no modelo Pydantic. E **proibir** qualquer campo **extra**. + +/// note | Nota + +Isso é suportado deste a versão `0.114.0` do FastAPI. 🤓 + +/// + +Você pode utilizar a configuração de modelo do Pydantic para `proibir` qualquer campo `extra`: + +{* ../../docs_src/request_form_models/tutorial002_an_py39.py hl[12] *} + +Caso um cliente tente enviar informações adicionais, ele receberá um retorno de **erro**. + +Por exemplo, se o cliente tentar enviar os campos de formulário: + +* `username`: `Rick` +* `password`: `Portal Gun` +* `extra`: `Mr. Poopybutthole` + +Ele receberá um retorno de erro informando-o que o campo `extra` não é permitido: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["body", "extra"], + "msg": "Extra inputs are not permitted", + "input": "Mr. Poopybutthole" + } + ] +} +``` + +## Resumo + +Você pode utilizar modelos Pydantic para declarar campos de formulários no FastAPI. 😎 diff --git a/docs/pt/docs/tutorial/request-forms-and-files.md b/docs/pt/docs/tutorial/request-forms-and-files.md index 259f262f4..b08d87013 100644 --- a/docs/pt/docs/tutorial/request-forms-and-files.md +++ b/docs/pt/docs/tutorial/request-forms-and-files.md @@ -2,34 +2,35 @@ Você pode definir arquivos e campos de formulário ao mesmo tempo usando `File` e `Form`. -!!! info "Informação" - Para receber arquivos carregados e/ou dados de formulário, primeiro instale `python-multipart`. +/// info | Informação - Por exemplo: `pip install python-multipart`. +Para receber arquivos carregados e/ou dados de formulário, primeiro instale `python-multipart`. +Por exemplo: `pip install python-multipart`. + +/// ## Importe `File` e `Form` -```Python hl_lines="1" -{!../../../docs_src/request_forms_and_files/tutorial001.py!} -``` +{* ../../docs_src/request_forms_and_files/tutorial001.py hl[1] *} ## Defina parâmetros de `File` e `Form` Crie parâmetros de arquivo e formulário da mesma forma que você faria para `Body` ou `Query`: -```Python hl_lines="8" -{!../../../docs_src/request_forms_and_files/tutorial001.py!} -``` +{* ../../docs_src/request_forms_and_files/tutorial001.py hl[8] *} Os arquivos e campos de formulário serão carregados como dados de formulário e você receberá os arquivos e campos de formulário. E você pode declarar alguns dos arquivos como `bytes` e alguns como `UploadFile`. -!!! warning "Aviso" - Você pode declarar vários parâmetros `File` e `Form` em uma *operação de caminho*, mas não é possível declarar campos `Body` para receber como JSON, pois a requisição terá o corpo codificado usando `multipart/form-data` ao invés de `application/json`. +/// warning | Aviso + +Você pode declarar vários parâmetros `File` e `Form` em uma *operação de caminho*, mas não é possível declarar campos `Body` para receber como JSON, pois a requisição terá o corpo codificado usando `multipart/form-data` ao invés de `application/json`. + +Isso não é uma limitação do **FastAPI** , é parte do protocolo HTTP. - Isso não é uma limitação do **FastAPI** , é parte do protocolo HTTP. +/// ## Recapitulando diff --git a/docs/pt/docs/tutorial/request-forms.md b/docs/pt/docs/tutorial/request-forms.md index b6c1b0e75..572ddf003 100644 --- a/docs/pt/docs/tutorial/request-forms.md +++ b/docs/pt/docs/tutorial/request-forms.md @@ -2,26 +2,29 @@ Quando você precisar receber campos de formulário ao invés de JSON, você pode usar `Form`. -!!! info "Informação" - Para usar formulários, primeiro instale `python-multipart`. +/// info | Informação - Ex: `pip install python-multipart`. +Para usar formulários, primeiro instale `python-multipart`. + +Lembre-se de criar um [ambiente virtual](../virtual-environments.md){.internal-link target=_blank}, ativá-lo e então instalar a dependência, por exemplo: + +```console +$ pip install python-multipart +``` + +/// ## Importe `Form` Importe `Form` de `fastapi`: -```Python hl_lines="1" -{!../../../docs_src/request_forms/tutorial001.py!} -``` +{* ../../docs_src/request_forms/tutorial001.py hl[1] *} ## Declare parâmetros de `Form` Crie parâmetros de formulário da mesma forma que você faria para `Body` ou `Query`: -```Python hl_lines="7" -{!../../../docs_src/request_forms/tutorial001.py!} -``` +{* ../../docs_src/request_forms/tutorial001.py hl[7] *} Por exemplo, em uma das maneiras que a especificação OAuth2 pode ser usada (chamada "fluxo de senha"), é necessário enviar um `username` e uma `password` como campos do formulário. @@ -29,11 +32,17 @@ A spec exige que os campos sejam exatamente Com `Form` você pode declarar os mesmos metadados e validação que com `Body` (e `Query`, `Path`, `Cookie`). -!!! info "Informação" - `Form` é uma classe que herda diretamente de `Body`. +/// info | Informação + +`Form` é uma classe que herda diretamente de `Body`. -!!! tip "Dica" - Para declarar corpos de formulário, você precisa usar `Form` explicitamente, porque sem ele os parâmetros seriam interpretados como parâmetros de consulta ou parâmetros de corpo (JSON). +/// + +/// tip | Dica + +Para declarar corpos de formulário, você precisa usar `Form` explicitamente, porque sem ele os parâmetros seriam interpretados como parâmetros de consulta ou parâmetros de corpo (JSON). + +/// ## Sobre "Campos de formulário" @@ -41,17 +50,23 @@ A forma como os formulários HTML (`
`) enviam os dados para o servi O **FastAPI** fará a leitura desses dados no lugar certo em vez de JSON. -!!! note "Detalhes técnicos" - Os dados dos formulários são normalmente codificados usando o "tipo de mídia" `application/x-www-form-urlencoded`. +/// note | Detalhes técnicos + +Os dados dos formulários são normalmente codificados usando o "tipo de mídia" `application/x-www-form-urlencoded`. + + Mas quando o formulário inclui arquivos, ele é codificado como `multipart/form-data`. Você lerá sobre como lidar com arquivos no próximo capítulo. + +Se você quiser ler mais sobre essas codificações e campos de formulário, vá para o MDN web docs para POST. + +/// - Mas quando o formulário inclui arquivos, ele é codificado como `multipart/form-data`. Você lerá sobre como lidar com arquivos no próximo capítulo. +/// warning | Aviso - Se você quiser ler mais sobre essas codificações e campos de formulário, vá para o MDN web docs para POST. +Você pode declarar vários parâmetros `Form` em uma *operação de caminho*, mas não pode declarar campos `Body` que espera receber como JSON, pois a solicitação terá o corpo codificado usando `application/x-www- form-urlencoded` em vez de `application/json`. -!!! warning "Aviso" - Você pode declarar vários parâmetros `Form` em uma *operação de caminho*, mas não pode declarar campos `Body` que espera receber como JSON, pois a solicitação terá o corpo codificado usando `application/x-www- form-urlencoded` em vez de `application/json`. +Esta não é uma limitação do **FastAPI**, é parte do protocolo HTTP. - Esta não é uma limitação do **FastAPI**, é parte do protocolo HTTP. +/// ## Recapitulando diff --git a/docs/pt/docs/tutorial/request_files.md b/docs/pt/docs/tutorial/request_files.md new file mode 100644 index 000000000..15c1ad825 --- /dev/null +++ b/docs/pt/docs/tutorial/request_files.md @@ -0,0 +1,172 @@ +# Arquivos de Requisição + +Você pode definir arquivos para serem enviados para o cliente utilizando `File`. + +/// info + +Para receber arquivos compartilhados, primeiro instale `python-multipart`. + +E.g. `pip install python-multipart`. + +Isso se deve por que arquivos enviados são enviados como "dados de formulário". + +/// + +## Importe `File` + +Importe `File` e `UploadFile` do `fastapi`: + +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[3] *} + +## Defina os parâmetros de `File` + +Cria os parâmetros do arquivo da mesma forma que você faria para `Body` ou `Form`: + +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[9] *} + +/// info | Informação + +`File` é uma classe que herda diretamente de `Form`. + +Mas lembre-se que quando você importa `Query`,`Path`, `File`, entre outros, do `fastapi`, essas são na verdade funções que retornam classes especiais. + +/// + +/// tip | Dica + +Para declarar o corpo de arquivos, você precisa utilizar `File`, do contrário os parâmetros seriam interpretados como parâmetros de consulta ou corpo (JSON) da requisição. + +/// + +Os arquivos serão enviados como "form data". + +Se você declarar o tipo do seu parâmetro na sua *função de operação de rota* como `bytes`, o **FastAPI** irá ler o arquivo para você e você receberá o conteúdo como `bytes`. + +Lembre-se que isso significa que o conteúdo inteiro será armazenado em memória. Isso funciona bem para arquivos pequenos. + +Mas existem vários casos em que você pode se beneficiar ao usar `UploadFile`. + +## Parâmetros de arquivo com `UploadFile` + +Defina um parâmetro de arquivo com o tipo `UploadFile` + +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[14] *} + +Utilizando `UploadFile` tem várias vantagens sobre `bytes`: + +* Você não precisa utilizar `File()` como o valor padrão do parâmetro. +* A classe utiliza um arquivo em "spool": + * Um arquivo guardado em memória até um tamanho máximo, depois desse limite ele é guardado em disco. +* Isso significa que a classe funciona bem com arquivos grandes como imagens, vídeos, binários extensos, etc. Sem consumir toda a memória. +* Você pode obter metadados do arquivo enviado. +* Ela possui uma interface semelhante a arquivos `async`. +* Ela expõe um objeto python `SpooledTemporaryFile` que você pode repassar para bibliotecas que esperam um objeto com comportamento de arquivo. + +### `UploadFile` + +`UploadFile` tem os seguintes atributos: + +* `filename`: Uma string (`str`) com o nome original do arquivo enviado (e.g. `myimage.jpg`). +* `content-type`: Uma `str` com o tipo do conteúdo (tipo MIME / media) (e.g. `image/jpeg`). +* `file`: Um objeto do tipo `SpooledTemporaryFile` (um objeto file-like). O arquivo propriamente dito que você pode passar diretamente para outras funções ou bibliotecas que esperam um objeto "file-like". + +`UploadFile` tem os seguintes métodos `async`. Todos eles chamam os métodos de arquivos por baixo dos panos (usando o objeto `SpooledTemporaryFile` interno). + +* `write(data)`: escreve dados (`data`) em `str` ou `bytes` no arquivo. +* `read(size)`: Lê um número de bytes/caracteres de acordo com a quantidade `size` (`int`). +* `seek(offset)`: Navega para o byte na posição `offset` (`int`) do arquivo. + * E.g., `await myfile.seek(0)` navegaria para o ínicio do arquivo. + * Isso é especialmente útil se você executar `await myfile.read()` uma vez e depois precisar ler os conteúdos do arquivo de novo. +* `close()`: Fecha o arquivo. + +Como todos esses métodos são assíncronos (`async`) você precisa esperar ("await") por eles. + +Por exemplo, dentro de uma *função de operação de rota* assíncrona você pode obter os conteúdos com: + +```Python +contents = await myfile.read() +``` + +Se você estiver dentro de uma *função de operação de rota* definida normalmente com `def`, você pode acessar `UploadFile.file` diretamente, por exemplo: + +```Python +contents = myfile.file.read() +``` + +/// note | Detalhes técnicos do `async` + +Quando você utiliza métodos assíncronos, o **FastAPI** executa os métodos do arquivo em uma threadpool e espera por eles. + +/// + +/// note | Detalhes técnicos do Starlette + +O `UploadFile` do **FastAPI** herda diretamente do `UploadFile` do **Starlette**, mas adiciona algumas funcionalidades necessárias para ser compatível com o **Pydantic** + +/// + +## O que é "Form Data" + +A forma como formulários HTML(`
`) enviam dados para o servidor normalmente utilizam uma codificação "especial" para esses dados, que é diferente do JSON. + +O **FastAPI** garante que os dados serão lidos da forma correta, em vez do JSON. + +/// note | Detalhes Técnicos + +Dados vindos de formulários geralmente tem a codificação com o "media type" `application/x-www-form-urlencoded` quando estes não incluem arquivos. + +Mas quando os dados incluem arquivos, eles são codificados como `multipart/form-data`. Se você utilizar `File`, **FastAPI** saberá que deve receber os arquivos da parte correta do corpo da requisição. + +Se você quer ler mais sobre essas codificações e campos de formulário, veja a documentação online da MDN sobre POST . + +/// + +/// warning | Aviso + +Você pode declarar múltiplos parâmetros `File` e `Form` em uma *operação de rota*, mas você não pode declarar campos `Body`que seriam recebidos como JSON junto desses parâmetros, por que a codificação do corpo da requisição será `multipart/form-data` em vez de `application/json`. + +Isso não é uma limitação do **FastAPI**, é uma parte do protocolo HTTP. + +/// + +## Arquivo de upload opcional + +Você pode definir um arquivo como opcional utilizando as anotações de tipo padrão e definindo o valor padrão como `None`: + +{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *} + +## `UploadFile` com Metadados Adicionais + +Você também pode utilizar `File()` com `UploadFile`, por exemplo, para definir metadados adicionais: + +{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *} + +## Envio de Múltiplos Arquivos + +É possível enviar múltiplos arquivos ao mesmo tmepo. + +Ele ficam associados ao mesmo "campo do formulário" enviado com "form data". + +Para usar isso, declare uma lista de `bytes` ou `UploadFile`: + +{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *} + +Você irá receber, como delcarado uma lista (`list`) de `bytes` ou `UploadFile`s, + +/// note | Detalhes Técnicos + +Você também poderia utilizar `from starlette.responses import HTMLResponse`. + +O **FastAPI** fornece as mesmas `starlette.responses` como `fastapi.responses` apenas como um facilitador para você, desenvolvedor. Mas a maior parte das respostas vem diretamente do Starlette. + +/// + +### Enviando Múltiplos Arquivos com Metadados Adicionais + +E da mesma forma que antes, você pode utilizar `File()` para definir parâmetros adicionais, até mesmo para `UploadFile`: + +{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *} + +## Recapitulando + +Use `File`, `bytes` e `UploadFile` para declarar arquivos que serão enviados na requisição, enviados como dados do formulário. diff --git a/docs/pt/docs/tutorial/response-model.md b/docs/pt/docs/tutorial/response-model.md new file mode 100644 index 000000000..6726a20a7 --- /dev/null +++ b/docs/pt/docs/tutorial/response-model.md @@ -0,0 +1,357 @@ +# Modelo de resposta - Tipo de retorno + +Você pode declarar o tipo usado para a resposta anotando o **tipo de retorno** *da função de operação de rota*. + +Você pode usar **anotações de tipo** da mesma forma que usaria para dados de entrada em **parâmetros** de função, você pode usar modelos Pydantic, listas, dicionários, valores escalares como inteiros, booleanos, etc. + +{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *} + +O FastAPI usará este tipo de retorno para: + +* **Validar** os dados retornados. + * Se os dados forem inválidos (por exemplo, se estiver faltando um campo), significa que o código do *seu* aplicativo está quebrado, não retornando o que deveria, e retornará um erro de servidor em vez de retornar dados incorretos. Dessa forma, você e seus clientes podem ter certeza de que receberão os dados e o formato de dados esperados. +* Adicionar um **Esquema JSON** para a resposta, na *operação de rota* do OpenAPI. + * Isso será usado pela **documentação automática**. + * Também será usado por ferramentas de geração automática de código do cliente. + +Mas o mais importante: + +* Ele **limitará e filtrará** os dados de saída para o que está definido no tipo de retorno. + * Isso é particularmente importante para a **segurança**, veremos mais sobre isso abaixo. + +## Parâmetro `response_model` + +Existem alguns casos em que você precisa ou deseja retornar alguns dados que não são exatamente o que o tipo declara. + +Por exemplo, você pode querer **retornar um dicionário** ou um objeto de banco de dados, mas **declará-lo como um modelo Pydantic**. Dessa forma, o modelo Pydantic faria toda a documentação de dados, validação, etc. para o objeto que você retornou (por exemplo, um dicionário ou objeto de banco de dados). + +Se você adicionasse a anotação do tipo de retorno, ferramentas e editores reclamariam com um erro (correto) informando que sua função está retornando um tipo (por exemplo, um dict) diferente do que você declarou (por exemplo, um modelo Pydantic). + +Nesses casos, você pode usar o parâmetro `response_model` do *decorador de operação de rota* em vez do tipo de retorno. + +Você pode usar o parâmetro `response_model` em qualquer uma das *operações de rota*: + +* `@app.get()` +* `@app.post()` +* `@app.put()` +* `@app.delete()` +* etc. + +{* ../../docs_src/response_model/tutorial001_py310.py hl[17,22,24:27] *} + +/// note | Nota + +Observe que `response_model` é um parâmetro do método "decorator" (`get`, `post`, etc). Não da sua *função de operação de rota*, como todos os parâmetros e corpo. + +/// + +`response_model` recebe o mesmo tipo que você declararia para um campo de modelo Pydantic, então, pode ser um modelo Pydantic, mas também pode ser, por exemplo, uma `lista` de modelos Pydantic, como `List[Item]`. + +O FastAPI usará este `response_model` para fazer toda a documentação de dados, validação, etc. e também para **converter e filtrar os dados de saída** para sua declaração de tipo. + +/// tip | Dica + +Se você tiver verificações de tipo rigorosas em seu editor, mypy, etc, você pode declarar o tipo de retorno da função como `Any`. + +Dessa forma, você diz ao editor que está retornando qualquer coisa intencionalmente. Mas o FastAPI ainda fará a documentação de dados, validação, filtragem, etc. com o `response_model`. + +/// + +### Prioridade `response_model` + +Se você declarar tanto um tipo de retorno quanto um `response_model`, o `response_model` terá prioridade e será usado pelo FastAPI. + +Dessa forma, você pode adicionar anotações de tipo corretas às suas funções, mesmo quando estiver retornando um tipo diferente do modelo de resposta, para ser usado pelo editor e ferramentas como mypy. E ainda assim você pode fazer com que o FastAPI faça a validação de dados, documentação, etc. usando o `response_model`. + +Você também pode usar `response_model=None` para desabilitar a criação de um modelo de resposta para essa *operação de rota*, você pode precisar fazer isso se estiver adicionando anotações de tipo para coisas que não são campos Pydantic válidos, você verá um exemplo disso em uma das seções abaixo. + +## Retorna os mesmos dados de entrada + +Aqui estamos declarando um modelo `UserIn`, ele conterá uma senha em texto simples: + +{* ../../docs_src/response_model/tutorial002_py310.py hl[7,9] *} + +/// info | Informação + +Para usar `EmailStr`, primeiro instale `email-validator`. + +Certifique-se de criar um [ambiente virtual](../virtual-environments.md){.internal-link target=_blank}, ative-o e instale-o, por exemplo: + +```console +$ pip install email-validator +``` + +ou com: + +```console +$ pip install "pydantic[email]" +``` + +/// + +E estamos usando este modelo para declarar nossa entrada e o mesmo modelo para declarar nossa saída: + +{* ../../docs_src/response_model/tutorial002_py310.py hl[16] *} + +Agora, sempre que um navegador estiver criando um usuário com uma senha, a API retornará a mesma senha na resposta. + +Neste caso, pode não ser um problema, porque é o mesmo usuário enviando a senha. + +Mas se usarmos o mesmo modelo para outra *operação de rota*, poderíamos estar enviando as senhas dos nossos usuários para todos os clientes. + +/// danger | Perigo + +Nunca armazene a senha simples de um usuário ou envie-a em uma resposta como esta, a menos que você saiba todas as ressalvas e saiba o que está fazendo. + +/// + +## Adicionar um modelo de saída + +Podemos, em vez disso, criar um modelo de entrada com a senha em texto simples e um modelo de saída sem ela: + +{* ../../docs_src/response_model/tutorial003_py310.py hl[9,11,16] *} + +Aqui, embora nossa *função de operação de rota* esteja retornando o mesmo usuário de entrada que contém a senha: + +{* ../../docs_src/response_model/tutorial003_py310.py hl[24] *} + +...declaramos o `response_model` como nosso modelo `UserOut`, que não inclui a senha: + +{* ../../docs_src/response_model/tutorial003_py310.py hl[22] *} + +Então, **FastAPI** cuidará de filtrar todos os dados que não são declarados no modelo de saída (usando Pydantic). + +### `response_model` ou Tipo de Retorno + +Neste caso, como os dois modelos são diferentes, se anotássemos o tipo de retorno da função como `UserOut`, o editor e as ferramentas reclamariam que estamos retornando um tipo inválido, pois são classes diferentes. + +É por isso que neste exemplo temos que declará-lo no parâmetro `response_model`. + +...mas continue lendo abaixo para ver como superar isso. + +## Tipo de Retorno e Filtragem de Dados + +Vamos continuar do exemplo anterior. Queríamos **anotar a função com um tipo**, mas queríamos poder retornar da função algo que realmente incluísse **mais dados**. + +Queremos que o FastAPI continue **filtrando** os dados usando o modelo de resposta. Para que, embora a função retorne mais dados, a resposta inclua apenas os campos declarados no modelo de resposta. + +No exemplo anterior, como as classes eram diferentes, tivemos que usar o parâmetro `response_model`. Mas isso também significa que não temos suporte do editor e das ferramentas verificando o tipo de retorno da função. + +Mas na maioria dos casos em que precisamos fazer algo assim, queremos que o modelo apenas **filtre/remova** alguns dados como neste exemplo. + +E nesses casos, podemos usar classes e herança para aproveitar as **anotações de tipo** de função para obter melhor suporte no editor e nas ferramentas, e ainda obter a **filtragem de dados** FastAPI. + +{* ../../docs_src/response_model/tutorial003_01_py310.py hl[7:10,13:14,18] *} + +Com isso, temos suporte de ferramentas, de editores e mypy, pois este código está correto em termos de tipos, mas também obtemos a filtragem de dados do FastAPI. + +Como isso funciona? Vamos verificar. 🤓 + +### Anotações de tipo e ferramentas + +Primeiro, vamos ver como editores, mypy e outras ferramentas veriam isso. + +`BaseUser` tem os campos base. Então `UserIn` herda de `BaseUser` e adiciona o campo `password`, então, ele incluirá todos os campos de ambos os modelos. + +Anotamos o tipo de retorno da função como `BaseUser`, mas na verdade estamos retornando uma instância `UserIn`. + +O editor, mypy e outras ferramentas não reclamarão disso porque, em termos de digitação, `UserIn` é uma subclasse de `BaseUser`, o que significa que é um tipo *válido* quando o que é esperado é qualquer coisa que seja um `BaseUser`. + +### Filtragem de dados FastAPI + +Agora, para FastAPI, ele verá o tipo de retorno e garantirá que o que você retornar inclua **apenas** os campos que são declarados no tipo. + +O FastAPI faz várias coisas internamente com o Pydantic para garantir que essas mesmas regras de herança de classe não sejam usadas para a filtragem de dados retornados, caso contrário, você pode acabar retornando muito mais dados do que o esperado. + +Dessa forma, você pode obter o melhor dos dois mundos: anotações de tipo com **suporte a ferramentas** e **filtragem de dados**. + +## Veja na documentação + +Quando você vê a documentação automática, pode verificar se o modelo de entrada e o modelo de saída terão seus próprios esquemas JSON: + + + +E ambos os modelos serão usados ​​para a documentação interativa da API: + + + +## Outras anotações de tipo de retorno + +Pode haver casos em que você retorna algo que não é um campo Pydantic válido e anota na função, apenas para obter o suporte fornecido pelas ferramentas (o editor, mypy, etc). + +### Retornar uma resposta diretamente + +O caso mais comum seria [retornar uma resposta diretamente, conforme explicado posteriormente na documentação avançada](../advanced/response-directly.md){.internal-link target=_blank}. + +{* ../../docs_src/response_model/tutorial003_02.py hl[8,10:11] *} + +Este caso simples é tratado automaticamente pelo FastAPI porque a anotação do tipo de retorno é a classe (ou uma subclasse de) `Response`. + +E as ferramentas também ficarão felizes porque `RedirectResponse` e ​​`JSONResponse` são subclasses de `Response`, então a anotação de tipo está correta. + +### Anotar uma subclasse de resposta + +Você também pode usar uma subclasse de `Response` na anotação de tipo: + +{* ../../docs_src/response_model/tutorial003_03.py hl[8:9] *} + +Isso também funcionará porque `RedirectResponse` é uma subclasse de `Response`, e o FastAPI tratará automaticamente este caso simples. + +### Anotações de Tipo de Retorno Inválido + +Mas quando você retorna algum outro objeto arbitrário que não é um tipo Pydantic válido (por exemplo, um objeto de banco de dados) e você o anota dessa forma na função, o FastAPI tentará criar um modelo de resposta Pydantic a partir dessa anotação de tipo e falhará. + +O mesmo aconteceria se você tivesse algo como uma união entre tipos diferentes onde um ou mais deles não são tipos Pydantic válidos, por exemplo, isso falharia 💥: + +{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *} + +... isso falha porque a anotação de tipo não é um tipo Pydantic e não é apenas uma única classe ou subclasse `Response`, é uma união (qualquer uma das duas) entre um `Response` e ​​um `dict`. + +### Desabilitar modelo de resposta + +Continuando com o exemplo acima, você pode não querer ter a validação de dados padrão, documentação, filtragem, etc. que é realizada pelo FastAPI. + +Mas você pode querer manter a anotação do tipo de retorno na função para obter o suporte de ferramentas como editores e verificadores de tipo (por exemplo, mypy). + +Neste caso, você pode desabilitar a geração do modelo de resposta definindo `response_model=None`: + +{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *} + +Isso fará com que o FastAPI pule a geração do modelo de resposta e, dessa forma, você pode ter quaisquer anotações de tipo de retorno que precisar sem afetar seu aplicativo FastAPI. 🤓 + +## Parâmetros de codificação do modelo de resposta + +Seu modelo de resposta pode ter valores padrão, como: + +{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *} + +* `description: Union[str, None] = None` (ou `str | None = None` no Python 3.10) tem um padrão de `None`. +* `tax: float = 10.5` tem um padrão de `10.5`. +* `tags: List[str] = []` tem um padrão de uma lista vazia: `[]`. + +mas você pode querer omiti-los do resultado se eles não foram realmente armazenados. + +Por exemplo, se você tem modelos com muitos atributos opcionais em um banco de dados NoSQL, mas não quer enviar respostas JSON muito longas cheias de valores padrão. + +### Usar o parâmetro `response_model_exclude_unset` + +Você pode definir o parâmetro `response_model_exclude_unset=True` do *decorador de operação de rota* : + +{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *} + +e esses valores padrão não serão incluídos na resposta, apenas os valores realmente definidos. + +Então, se você enviar uma solicitação para essa *operação de rota* para o item com ID `foo`, a resposta (sem incluir valores padrão) será: + +```JSON +{ +"name": "Foo", +"price": 50.2 +} +``` + +/// info | Informação + +No Pydantic v1, o método era chamado `.dict()`, ele foi descontinuado (mas ainda suportado) no Pydantic v2 e renomeado para `.model_dump()`. + +Os exemplos aqui usam `.dict()` para compatibilidade com Pydantic v1, mas você deve usar `.model_dump()` em vez disso se puder usar Pydantic v2. + +/// + +/// info | Informação + +O FastAPI usa `.dict()` do modelo Pydantic com seu parâmetro `exclude_unset` para chegar a isso. + +/// + +/// info | Informação + +Você também pode usar: + +* `response_model_exclude_defaults=True` +* `response_model_exclude_none=True` + +conforme descrito na documentação do Pydantic para `exclude_defaults` e `exclude_none`. + +/// + +#### Dados com valores para campos com padrões + +Mas se seus dados tiverem valores para os campos do modelo com valores padrões, como o item com ID `bar`: + +```Python hl_lines="3 5" +{ +"name": "Bar", +"description": "The bartenders", +"price": 62, +"tax": 20.2 +} +``` + +eles serão incluídos na resposta. + +#### Dados com os mesmos valores que os padrões + +Se os dados tiverem os mesmos valores que os padrões, como o item com ID `baz`: + +```Python hl_lines="3 5-6" +{ +"name": "Baz", +"description": None, +"price": 50.2, +"tax": 10.5, +"tags": [] +} +``` + +O FastAPI é inteligente o suficiente (na verdade, o Pydantic é inteligente o suficiente) para perceber que, embora `description`, `tax` e `tags` tenham os mesmos valores que os padrões, eles foram definidos explicitamente (em vez de retirados dos padrões). + +Portanto, eles serão incluídos na resposta JSON. + +/// tip | Dica + +Observe que os valores padrão podem ser qualquer coisa, não apenas `None`. + +Eles podem ser uma lista (`[]`), um `float` de `10.5`, etc. + +/// + +### `response_model_include` e `response_model_exclude` + +Você também pode usar os parâmetros `response_model_include` e `response_model_exclude` do *decorador de operação de rota*. + +Eles pegam um `set` de `str` com o nome dos atributos para incluir (omitindo o resto) ou para excluir (incluindo o resto). + +Isso pode ser usado como um atalho rápido se você tiver apenas um modelo Pydantic e quiser remover alguns dados da saída. + +/// tip | Dica + +Mas ainda é recomendado usar as ideias acima, usando várias classes, em vez desses parâmetros. + +Isso ocorre porque o Schema JSON gerado no OpenAPI do seu aplicativo (e a documentação) ainda será o único para o modelo completo, mesmo que você use `response_model_include` ou `response_model_exclude` para omitir alguns atributos. + +Isso também se aplica ao `response_model_by_alias` que funciona de forma semelhante. + +/// + +{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *} + +/// tip | Dica + +A sintaxe `{"nome", "descrição"}` cria um `conjunto` com esses dois valores. + +É equivalente a `set(["nome", "descrição"])`. + +/// + +#### Usando `list`s em vez de `set`s + +Se você esquecer de usar um `set` e usar uma `lista` ou `tupla` em vez disso, o FastAPI ainda o converterá em um `set` e funcionará corretamente: + +{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *} + +## Recapitulação + +Use o parâmetro `response_model` do *decorador de operação de rota* para definir modelos de resposta e, especialmente, para garantir que dados privados sejam filtrados. + +Use `response_model_exclude_unset` para retornar apenas os valores definidos explicitamente. diff --git a/docs/pt/docs/tutorial/response-status-code.md b/docs/pt/docs/tutorial/response-status-code.md index 2df17d4ea..48957f67a 100644 --- a/docs/pt/docs/tutorial/response-status-code.md +++ b/docs/pt/docs/tutorial/response-status-code.md @@ -8,17 +8,21 @@ Da mesma forma que você pode especificar um modelo de resposta, você também p * `@app.delete()` * etc. -```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} -!!! note "Nota" - Observe que `status_code` é um parâmetro do método "decorador" (get, post, etc). Não da sua função de *operação de caminho*, como todos os parâmetros e corpo. +/// note | Nota + +Observe que `status_code` é um parâmetro do método "decorador" (get, post, etc). Não da sua função de *operação de caminho*, como todos os parâmetros e corpo. + +/// O parâmetro `status_code` recebe um número com o código de status HTTP. -!!! info "Informação" - `status_code` também pode receber um `IntEnum`, como o do Python `http.HTTPStatus`. +/// info | Informação + +`status_code` também pode receber um `IntEnum`, como o do Python `http.HTTPStatus`. + +/// Dessa forma: @@ -27,15 +31,21 @@ Dessa forma: -!!! note "Nota" - Alguns códigos de resposta (consulte a próxima seção) indicam que a resposta não possui um corpo. +/// note | Nota + +Alguns códigos de resposta (consulte a próxima seção) indicam que a resposta não possui um corpo. + +O FastAPI sabe disso e produzirá documentos OpenAPI informando que não há corpo de resposta. - O FastAPI sabe disso e produzirá documentos OpenAPI informando que não há corpo de resposta. +/// ## Sobre os códigos de status HTTP -!!! note "Nota" - Se você já sabe o que são códigos de status HTTP, pule para a próxima seção. +/// note | Nota + +Se você já sabe o que são códigos de status HTTP, pule para a próxima seção. + +/// Em HTTP, você envia um código de status numérico de 3 dígitos como parte da resposta. @@ -55,16 +65,17 @@ Resumidamente: * Para erros genéricos do cliente, você pode usar apenas `400`. * `500` e acima são para erros do servidor. Você quase nunca os usa diretamente. Quando algo der errado em alguma parte do código do seu aplicativo ou servidor, ele retornará automaticamente um desses códigos de status. -!!! tip "Dica" - Para saber mais sobre cada código de status e qual código serve para quê, verifique o MDN documentação sobre códigos de status HTTP. +/// tip | Dica + +Para saber mais sobre cada código de status e qual código serve para quê, verifique o MDN documentação sobre códigos de status HTTP. + +/// ## Atalho para lembrar os nomes Vamos ver o exemplo anterior novamente: -```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} `201` é o código de status para "Criado". @@ -72,19 +83,19 @@ Mas você não precisa memorizar o que cada um desses códigos significa. Você pode usar as variáveis de conveniência de `fastapi.status`. -```Python hl_lines="1 6" -{!../../../docs_src/response_status_code/tutorial002.py!} -``` +{* ../../docs_src/response_status_code/tutorial002.py hl[1,6] *} Eles são apenas uma conveniência, eles possuem o mesmo número, mas dessa forma você pode usar o autocomplete do editor para encontrá-los: -!!! note "Detalhes técnicos" - Você também pode usar `from starlette import status`. +/// note | Detalhes técnicos + +Você também pode usar `from starlette import status`. - **FastAPI** fornece o mesmo `starlette.status` como `fastapi.status` apenas como uma conveniência para você, o desenvolvedor. Mas vem diretamente da Starlette. +**FastAPI** fornece o mesmo `starlette.status` como `fastapi.status` apenas como uma conveniência para você, o desenvolvedor. Mas vem diretamente da Starlette. +/// ## Alterando o padrão diff --git a/docs/pt/docs/tutorial/schema-extra-example.md b/docs/pt/docs/tutorial/schema-extra-example.md new file mode 100644 index 000000000..5d3498d7d --- /dev/null +++ b/docs/pt/docs/tutorial/schema-extra-example.md @@ -0,0 +1,110 @@ +# Declare um exemplo dos dados da requisição + +Você pode declarar exemplos dos dados que a sua aplicação pode receber. + +Aqui estão várias formas de se fazer isso. + +## `schema_extra` do Pydantic + +Você pode declarar um `example` para um modelo Pydantic usando `Config` e `schema_extra`, conforme descrito em Documentação do Pydantic: Schema customization: + +{* ../../docs_src/schema_extra_example/tutorial001.py hl[15:23] *} + +Essas informações extras serão adicionadas como se encontram no **JSON Schema** de resposta desse modelo e serão usadas na documentação da API. + +/// tip | Dica + +Você pode usar a mesma técnica para estender o JSON Schema e adicionar suas próprias informações extras de forma personalizada. + +Por exemplo, você pode usar isso para adicionar metadados para uma interface de usuário de front-end, etc. + +/// + +## `Field` de argumentos adicionais + +Ao usar `Field ()` com modelos Pydantic, você também pode declarar informações extras para o **JSON Schema** passando quaisquer outros argumentos arbitrários para a função. + +Você pode usar isso para adicionar um `example` para cada campo: + +{* ../../docs_src/schema_extra_example/tutorial002.py hl[4,10:13] *} + +/// warning | Atenção + +Lembre-se de que esses argumentos extras passados ​​não adicionarão nenhuma validação, apenas informações extras, para fins de documentação. + +/// + +## `example` e `examples` no OpenAPI + +Ao usar quaisquer dos: + +* `Path()` +* `Query()` +* `Header()` +* `Cookie()` +* `Body()` +* `Form()` +* `File()` + +você também pode declarar um dado `example` ou um grupo de `examples` com informações adicionais que serão adicionadas ao **OpenAPI**. + +### `Body` com `example` + +Aqui nós passamos um `example` dos dados esperados por `Body()`: + +{* ../../docs_src/schema_extra_example/tutorial003.py hl[21:26] *} + +### Exemplo na UI da documentação + +Com qualquer um dos métodos acima, os `/docs` vão ficar assim: + + + +### `Body` com vários `examples` + +Alternativamente ao único `example`, você pode passar `examples` usando um `dict` com **vários examples**, cada um com informações extras que serão adicionadas no **OpenAPI** também. + +As chaves do `dict` identificam cada exemplo, e cada valor é outro `dict`. + +Cada `dict` de exemplo específico em `examples` pode conter: + +* `summary`: Pequena descrição do exemplo. +* `description`: Uma descrição longa que pode conter texto em Markdown. +* `value`: O próprio exemplo mostrado, ex: um `dict`. +* `externalValue`: alternativa ao `value`, uma URL apontando para o exemplo. Embora isso possa não ser suportado por tantas ferramentas quanto `value`. + +{* ../../docs_src/schema_extra_example/tutorial004.py hl[22:48] *} + +### Exemplos na UI da documentação + +Com `examples` adicionado a `Body()`, os `/docs` vão ficar assim: + + + +## Detalhes técnicos + +/// warning | Atenção + +Esses são detalhes muito técnicos sobre os padrões **JSON Schema** e **OpenAPI**. + +Se as ideias explicadas acima já funcionam para você, isso pode ser o suficiente, e você provavelmente não precisa desses detalhes, fique à vontade para pular. + +/// + +Quando você adiciona um exemplo dentro de um modelo Pydantic, usando `schema_extra` ou` Field(example="something") `esse exemplo é adicionado ao **JSON Schema** para esse modelo Pydantic. + +E esse **JSON Schema** do modelo Pydantic está incluído no **OpenAPI** da sua API e, em seguida, é usado na UI da documentação. + +O **JSON Schema** na verdade não tem um campo `example` nos padrões. Versões recentes do JSON Schema definem um campo `examples`, mas o OpenAPI 3.0.3 é baseado numa versão mais antiga do JSON Schema que não tinha `examples`. + +Por isso, o OpenAPI 3.0.3 definiu o seu próprio `example` para a versão modificada do **JSON Schema** que é usada, para o mesmo próposito (mas é apenas `example` no singular, não `examples`), e é isso que é usado pela UI da documentação da API(usando o Swagger UI). + +Portanto, embora `example` não seja parte do JSON Schema, é parte da versão customizada do JSON Schema usada pelo OpenAPI, e é isso que vai ser usado dentro da UI de documentação. + +Mas quando você usa `example` ou `examples` com qualquer um dos outros utilitários (`Query()`, `Body()`, etc.) esses exemplos não são adicionados ao JSON Schema que descreve esses dados (nem mesmo para versão própria do OpenAPI do JSON Schema), eles são adicionados diretamente à declaração da *operação de rota* no OpenAPI (fora das partes do OpenAPI que usam o JSON Schema). + +Para `Path()`, `Query()`, `Header()`, e `Cookie()`, o `example` e `examples` são adicionados a definição do OpenAPI, dentro do `Parameter Object` (na especificação). + +E para `Body()`, `File()`, e `Form()`, o `example` e `examples` são de maneira equivalente adicionados para a definição do OpenAPI, dentro do `Request Body Object`, no campo `content`, no `Media Type Object` (na especificação). + +Por outro lado, há uma versão mais recente do OpenAPI: **3.1.0**, lançada recentemente. Baseado no JSON Schema mais recente e a maioria das modificações da versão customizada do OpenAPI do JSON Schema são removidas, em troca dos recursos das versões recentes do JSON Schema, portanto, todas essas pequenas diferenças são reduzidas. No entanto, a UI do Swagger atualmente não oferece suporte a OpenAPI 3.1.0, então, por enquanto, é melhor continuar usando as opções acima. diff --git a/docs/pt/docs/tutorial/security/first-steps.md b/docs/pt/docs/tutorial/security/first-steps.md index ed07d1c96..f4dea8e14 100644 --- a/docs/pt/docs/tutorial/security/first-steps.md +++ b/docs/pt/docs/tutorial/security/first-steps.md @@ -19,14 +19,17 @@ Vamos primeiro usar o código e ver como funciona, e depois voltaremos para ente ## Crie um `main.py` Copie o exemplo em um arquivo `main.py`: -```Python -{!../../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py *} ## Execute-o -!!! informação - Primeiro, instale `python-multipart`. +/// info | informação + + + +/// + + Primeiro, instale `python-multipart`. Ex: `pip install python-multipart`. @@ -52,7 +55,12 @@ Você verá algo deste tipo: -!!! marque o "botão de Autorizar!" +/// check | 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. @@ -61,7 +69,12 @@ E se você clicar, você terá um pequeno formulário de autorização para digi -!!! nota +/// note | 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. @@ -104,7 +117,12 @@ Então, vamos rever de um ponto de vista simplificado: 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 +/// info | informação + + + +/// + Um token "bearer" não é a única opção. Mas é a melhor no nosso caso. @@ -115,11 +133,14 @@ Neste exemplo, nós vamos usar o **OAuth2** com o fluxo de **Senha**, usando um Quando nós criamos uma instância da classe `OAuth2PasswordBearer`, nós passamos pelo parâmetro `tokenUrl` Esse parâmetro contém a URL que o client (o frontend rodando no browser do usuário) vai usar para mandar o `username` e `senha` para obter um token. -```Python hl_lines="6" -{!../../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[6] *} + +/// tip | Dica + + + +/// -!!! 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`. @@ -130,7 +151,12 @@ Esse parâmetro não cria um endpoint / *path operation*, mas declara que a URL Em breve também criaremos o atual path operation. -!!! informação +/// info | 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. @@ -149,15 +175,18 @@ Então, pode ser usado com `Depends`. Agora você pode passar aquele `oauth2_scheme` em uma dependência com `Depends`. -```Python hl_lines="10" -{!../../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[10] *} Esse dependência vai fornecer uma `str` que é atribuído ao parâmetro `token da *função do path operation* 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" +/// info | 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. diff --git a/docs/pt/docs/tutorial/security/get-current-user.md b/docs/pt/docs/tutorial/security/get-current-user.md new file mode 100644 index 000000000..1a2badb83 --- /dev/null +++ b/docs/pt/docs/tutorial/security/get-current-user.md @@ -0,0 +1,105 @@ +# Obter Usuário Atual + +No capítulo anterior, o sistema de segurança (que é baseado no sistema de injeção de dependências) estava fornecendo à *função de operação de rota* um `token` como uma `str`: + +{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *} + +Mas isso ainda não é tão útil. + +Vamos fazer com que ele nos forneça o usuário atual. + +## Criar um modelo de usuário + +Primeiro, vamos criar um modelo de usuário com Pydantic. + +Da mesma forma que usamos o Pydantic para declarar corpos, podemos usá-lo em qualquer outro lugar: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:6] *} + +## Criar uma dependência `get_current_user` + +Vamos criar uma dependência chamada `get_current_user`. + +Lembra que as dependências podem ter subdependências? + +`get_current_user` terá uma dependência com o mesmo `oauth2_scheme` que criamos antes. + +Da mesma forma que estávamos fazendo antes diretamente na *operação de rota*, a nossa nova dependência `get_current_user` receberá um `token` como uma `str` da subdependência `oauth2_scheme`: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[25] *} + +## Obter o usuário + +`get_current_user` usará uma função utilitária (falsa) que criamos, que recebe um token como uma `str` e retorna nosso modelo Pydantic `User`: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[19:22,26:27] *} + +## Injetar o usuário atual + +Então agora nós podemos usar o mesmo `Depends` com nosso `get_current_user` na *operação de rota*: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[31] *} + +Observe que nós declaramos o tipo de `current_user` como o modelo Pydantic `User`. + +Isso nos ajudará dentro da função com todo o preenchimento automático e verificações de tipo. + +/// tip | Dica + +Você pode se lembrar que corpos de requisição também são declarados com modelos Pydantic. + +Aqui, o **FastAPI** não ficará confuso porque você está usando `Depends`. + +/// + +/// check | Verifique + +A forma como esse sistema de dependências foi projetado nos permite ter diferentes dependências (diferentes "dependables") que retornam um modelo `User`. + +Não estamos restritos a ter apenas uma dependência que possa retornar esse tipo de dado. + +/// + +## Outros modelos + +Agora você pode obter o usuário atual diretamente nas *funções de operação de rota* e lidar com os mecanismos de segurança no nível da **Injeção de Dependências**, usando `Depends`. + +E você pode usar qualquer modelo ou dado para os requisitos de segurança (neste caso, um modelo Pydantic `User`). + +Mas você não está restrito a usar um modelo de dados, classe ou tipo específico. + +Você quer ter apenas um `id` e `email`, sem incluir nenhum `username` no modelo? Claro. Você pode usar essas mesmas ferramentas. + +Você quer ter apenas uma `str`? Ou apenas um `dict`? Ou uma instância de modelo de classe de banco de dados diretamente? Tudo funciona da mesma forma. + +Na verdade, você não tem usuários que fazem login no seu aplicativo, mas sim robôs, bots ou outros sistemas, que possuem apenas um token de acesso? Novamente, tudo funciona da mesma forma. + +Apenas use qualquer tipo de modelo, qualquer tipo de classe, qualquer tipo de banco de dados que você precise para a sua aplicação. O **FastAPI** cobre tudo com o sistema de injeção de dependências. + +## Tamanho do código + +Este exemplo pode parecer verboso. Lembre-se de que estamos misturando segurança, modelos de dados, funções utilitárias e *operações de rota* no mesmo arquivo. + +Mas aqui está o ponto principal. + +O código relacionado à segurança e à injeção de dependências é escrito apenas uma vez. + +E você pode torná-lo tão complexo quanto quiser. E ainda assim, tê-lo escrito apenas uma vez, em um único lugar. Com toda a flexibilidade. + +Mas você pode ter milhares de endpoints (*operações de rota*) usando o mesmo sistema de segurança. + +E todos eles (ou qualquer parte deles que você desejar) podem aproveitar o reuso dessas dependências ou de quaisquer outras dependências que você criar. + +E todos esses milhares de *operações de rota* podem ter apenas 3 linhas: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[30:32] *} + +## Recapitulação + +Agora você pode obter o usuário atual diretamente na sua *função de operação de rota*. + +Já estamos na metade do caminho. + +Só precisamos adicionar uma *operação de rota* para que o usuário/cliente realmente envie o `username` e `password`. + +Isso vem a seguir. diff --git a/docs/pt/docs/tutorial/security/index.md b/docs/pt/docs/tutorial/security/index.md index f94a8ab62..b4440ec04 100644 --- a/docs/pt/docs/tutorial/security/index.md +++ b/docs/pt/docs/tutorial/security/index.md @@ -32,9 +32,11 @@ Não é muito popular ou usado nos dias atuais. OAuth2 não especifica como criptografar a comunicação, ele espera que você tenha sua aplicação em um servidor HTTPS. -!!! tip "Dica" - Na seção sobre **deployment** você irá ver como configurar HTTPS de modo gratuito, usando Traefik e Let’s Encrypt. +/// tip | Dica +Na seção sobre **deployment** você irá ver como configurar HTTPS de modo gratuito, usando Traefik e Let’s Encrypt. + +/// ## OpenID Connect @@ -87,10 +89,13 @@ OpenAPI define os seguintes esquemas de segurança: * Essa descoberta automática é o que é definido na especificação OpenID Connect. -!!! tip "Dica" - Integração com outros provedores de autenticação/autorização como Google, Facebook, Twitter, GitHub, etc. é bem possível e relativamente fácil. +/// tip | Dica + +Integração com outros provedores de autenticação/autorização como Google, Facebook, Twitter, GitHub, etc. é bem possível e relativamente fácil. + +O problema mais complexo é criar um provedor de autenticação/autorização como eles, mas o FastAPI dá a você ferramentas para fazer isso facilmente, enquanto faz o trabalho pesado para você. - O problema mais complexo é criar um provedor de autenticação/autorização como eles, mas o FastAPI dá a você ferramentas para fazer isso facilmente, enquanto faz o trabalho pesado para você. +/// ## **FastAPI** utilitários diff --git a/docs/pt/docs/tutorial/security/oauth2-jwt.md b/docs/pt/docs/tutorial/security/oauth2-jwt.md new file mode 100644 index 000000000..4b99c4c59 --- /dev/null +++ b/docs/pt/docs/tutorial/security/oauth2-jwt.md @@ -0,0 +1,274 @@ +# OAuth2 com Senha (e hashing), Bearer com tokens JWT + +Agora que temos todo o fluxo de segurança, vamos tornar a aplicação realmente segura, usando tokens JWT e hashing de senhas seguras. + +Este código é algo que você pode realmente usar na sua aplicação, salvar os hashes das senhas no seu banco de dados, etc. + +Vamos começar de onde paramos no capítulo anterior e incrementá-lo. + +## Sobre o JWT + +JWT significa "JSON Web Tokens". + +É um padrão para codificar um objeto JSON em uma string longa e densa sem espaços. Ele se parece com isso: + +``` +eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c +``` + +Ele não é criptografado, então qualquer pessoa pode recuperar as informações do seu conteúdo. + +Mas ele é assinado. Assim, quando você recebe um token que você emitiu, você pode verificar que foi realmente você quem o emitiu. + +Dessa forma, você pode criar um token com um prazo de expiração, digamos, de 1 semana. E então, quando o usuário voltar no dia seguinte com o token, você sabe que ele ainda está logado no seu sistema. + +Depois de uma semana, o token expirará e o usuário não estará autorizado, precisando fazer login novamente para obter um novo token. E se o usuário (ou uma terceira parte) tentar modificar o token para alterar a expiração, você seria capaz de descobrir isso, pois as assinaturas não iriam corresponder. + +Se você quiser brincar com tokens JWT e ver como eles funcionam, visite https://jwt.io. + +## Instalar `PyJWT` + +Nós precisamos instalar o `PyJWT` para criar e verificar os tokens JWT em Python. + +Certifique-se de criar um [ambiente virtual](../../virtual-environments.md){.internal-link target=_blank}, ativá-lo e então instalar o `pyjwt`: + +
+ +```console +$ pip install pyjwt + +---> 100% +``` + +
+ +/// info | Informação + +Se você pretente utilizar algoritmos de assinatura digital como o RSA ou o ECDSA, você deve instalar a dependência da biblioteca de criptografia `pyjwt[crypto]`. + +Você pode ler mais sobre isso na documentação de instalação do PyJWT. + +/// + +## Hashing de senhas + +"Hashing" significa converter algum conteúdo (uma senha neste caso) em uma sequência de bytes (apenas uma string) que parece um monte de caracteres sem sentido. + +Sempre que você passar exatamente o mesmo conteúdo (exatamente a mesma senha), você obterá exatamente o mesmo resultado. + +Mas não é possível converter os caracteres sem sentido de volta para a senha original. + +### Por que usar hashing de senhas + +Se o seu banco de dados for roubado, o invasor não terá as senhas em texto puro dos seus usuários, apenas os hashes. + +Então, o invasor não poderá tentar usar essas senhas em outro sistema (como muitos usuários utilizam a mesma senha em vários lugares, isso seria perigoso). + +## Instalar o `passlib` + +O PassLib é uma excelente biblioteca Python para lidar com hashes de senhas. + +Ele suporta muitos algoritmos de hashing seguros e utilitários para trabalhar com eles. + +O algoritmo recomendado é o "Bcrypt". + +Certifique-se de criar um [ambiente virtual](../../virtual-environments.md){.internal-link target=_blank}, ativá-lo e então instalar o PassLib com Bcrypt: + +
+ +```console +$ pip install "passlib[bcrypt]" + +---> 100% +``` + +
+ +/// tip | Dica + +Com o `passlib`, você poderia até configurá-lo para ser capaz de ler senhas criadas pelo **Django**, um plug-in de segurança do **Flask** ou muitos outros. + +Assim, você poderia, por exemplo, compartilhar os mesmos dados de um aplicativo Django em um banco de dados com um aplicativo FastAPI. Ou migrar gradualmente uma aplicação Django usando o mesmo banco de dados. + +E seus usuários poderiam fazer login tanto pela sua aplicação Django quanto pela sua aplicação **FastAPI**, ao mesmo tempo. + +/// + +## Criar o hash e verificar as senhas + +Importe as ferramentas que nós precisamos de `passlib`. + +Crie um "contexto" do PassLib. Este será usado para criar o hash e verificar as senhas. + +/// tip | Dica + +O contexto do PassLib também possui funcionalidades para usar diferentes algoritmos de hashing, incluindo algoritmos antigos que estão obsoletos, apenas para permitir verificá-los, etc. + +Por exemplo, você poderia usá-lo para ler e verificar senhas geradas por outro sistema (como Django), mas criar o hash de novas senhas com um algoritmo diferente, como o Bcrypt. + +E ser compatível com todos eles ao mesmo tempo. + +/// + +Crie uma função utilitária para criar o hash de uma senha fornecida pelo usuário. + +E outra função utilitária para verificar se uma senha recebida corresponde ao hash armazenado. + +E outra para autenticar e retornar um usuário. + +{* ../../docs_src/security/tutorial004_an_py310.py hl[8,49,56:57,60:61,70:76] *} + +/// note | Nota + +Se você verificar o novo banco de dados (falso) `fake_users_db`, você verá como o hash da senha se parece agora: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`. + +/// + +## Manipular tokens JWT + +Importe os módulos instalados. + +Crie uma chave secreta aleatória que será usada para assinar os tokens JWT. + +Para gerar uma chave secreta aleatória e segura, use o comando: + +
+ +```console +$ openssl rand -hex 32 + +09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7 +``` + +
+ +E copie a saída para a variável `SECRET_KEY` (não use a do exemplo). + +Crie uma variável `ALGORITHM` com o algoritmo usado para assinar o token JWT e defina como `"HS256"`. + +Crie uma variável para a expiração do token. + +Defina um modelo Pydantic que será usado no endpoint de token para a resposta. + +Crie uma função utilitária para gerar um novo token de acesso. + +{* ../../docs_src/security/tutorial004_an_py310.py hl[4,7,13:15,29:31,79:87] *} + +## Atualize as dependências + +Atualize `get_current_user` para receber o mesmo token de antes, mas desta vez, usando tokens JWT. + +Decodifique o token recebido, verifique-o e retorne o usuário atual. + +Se o token for inválido, retorne um erro HTTP imediatamente. + +{* ../../docs_src/security/tutorial004_an_py310.py hl[90:107] *} + +## Atualize a *operação de rota* `/token` + +Crie um `timedelta` com o tempo de expiração do token. + +Crie um token de acesso JWT real e o retorne. + +{* ../../docs_src/security/tutorial004_an_py310.py hl[118:133] *} + +### Detalhes técnicos sobre o "sujeito" `sub` do JWT + +A especificação JWT diz que existe uma chave `sub`, com o sujeito do token. + +É opcional usá-la, mas é onde você colocaria a identificação do usuário, então nós estamos usando aqui. + +O JWT pode ser usado para outras coisas além de identificar um usuário e permitir que ele execute operações diretamente na sua API. + +Por exemplo, você poderia identificar um "carro" ou uma "postagem de blog". + +Depois, você poderia adicionar permissões sobre essa entidade, como "dirigir" (para o carro) ou "editar" (para o blog). + +E então, poderia dar esse token JWT para um usuário (ou bot), e ele poderia usá-lo para realizar essas ações (dirigir o carro ou editar o blog) sem sequer precisar ter uma conta, apenas com o token JWT que sua API gerou para isso. + +Usando essas ideias, o JWT pode ser usado para cenários muito mais sofisticados. + +Nesses casos, várias dessas entidades poderiam ter o mesmo ID, digamos `foo` (um usuário `foo`, um carro `foo` e uma postagem de blog `foo`). + +Então, para evitar colisões de ID, ao criar o token JWT para o usuário, você poderia prefixar o valor da chave `sub`, por exemplo, com `username:`. Assim, neste exemplo, o valor de `sub` poderia ser: `username:johndoe`. + +O importante a se lembrar é que a chave `sub` deve ter um identificador único em toda a aplicação e deve ser uma string. + +## Testando + +Execute o servidor e vá para a documentação: http://127.0.0.1:8000/docs. + +Você verá a interface de usuário assim: + + + +Autorize a aplicação da mesma maneira que antes. + +Usando as credenciais: + +Username: `johndoe` +Password: `secret` + +/// check | Verifique + +Observe que em nenhuma parte do código está a senha em texto puro "`secret`", nós temos apenas o hash. + +/// + + + +Chame o endpoint `/users/me/`, você receberá o retorno como: + +```JSON +{ + "username": "johndoe", + "email": "johndoe@example.com", + "full_name": "John Doe", + "disabled": false +} +``` + + + +Se você abrir as ferramentas de desenvolvedor, poderá ver que os dados enviados incluem apenas o token. A senha é enviada apenas na primeira requisição para autenticar o usuário e obter o token de acesso, mas não é enviada nas próximas requisições: + + + +/// note | Nota + +Perceba que o cabeçalho `Authorization`, com o valor que começa com `Bearer `. + +/// + +## Uso avançado com `scopes` + +O OAuth2 tem a noção de "scopes" (escopos). + +Você pode usá-los para adicionar um conjunto específico de permissões a um token JWT. + +Então, você pode dar este token diretamente a um usuário ou a uma terceira parte para interagir com sua API com um conjunto de restrições. + +Você pode aprender como usá-los e como eles são integrados ao **FastAPI** mais adiante no **Guia Avançado do Usuário**. + + +## Recapitulação + +Com o que você viu até agora, você pode configurar uma aplicação **FastAPI** segura usando padrões como OAuth2 e JWT. + +Em quase qualquer framework, lidar com a segurança se torna rapidamente um assunto bastante complexo. + +Muitos pacotes que simplificam bastante isso precisam fazer muitas concessões com o modelo de dados, o banco de dados e os recursos disponíveis. E alguns desses pacotes que simplificam demais na verdade têm falhas de segurança subjacentes. + +--- + +O **FastAPI** não faz nenhuma concessão com nenhum banco de dados, modelo de dados ou ferramenta. + +Ele oferece toda a flexibilidade para você escolher as opções que melhor se ajustam ao seu projeto. + +E você pode usar diretamente muitos pacotes bem mantidos e amplamente utilizados, como `passlib` e `PyJWT`, porque o **FastAPI** não exige mecanismos complexos para integrar pacotes externos. + +Mas ele fornece as ferramentas para simplificar o processo o máximo possível, sem comprometer a flexibilidade, robustez ou segurança. + +E você pode usar e implementar protocolos padrão seguros, como o OAuth2, de uma maneira relativamente simples. + +Você pode aprender mais no **Guia Avançado do Usuário** sobre como usar os "scopes" do OAuth2 para um sistema de permissões mais refinado, seguindo esses mesmos padrões. O OAuth2 com scopes é o mecanismo usado por muitos provedores grandes de autenticação, como o Facebook, Google, GitHub, Microsoft, Twitter, etc. para autorizar aplicativos de terceiros a interagir com suas APIs em nome de seus usuários. diff --git a/docs/pt/docs/tutorial/security/simple-oauth2.md b/docs/pt/docs/tutorial/security/simple-oauth2.md new file mode 100644 index 000000000..1cf05785e --- /dev/null +++ b/docs/pt/docs/tutorial/security/simple-oauth2.md @@ -0,0 +1,289 @@ +# Simples OAuth2 com senha e Bearer + +Agora vamos construir a partir do capítulo anterior e adicionar as partes que faltam para ter um fluxo de segurança completo. + +## Pegue o `username` (nome de usuário) e `password` (senha) + +É utilizado o utils de segurança da **FastAPI** para obter o `username` e a `password`. + +OAuth2 especifica que ao usar o "password flow" (fluxo de senha), que estamos usando, o cliente/usuário deve enviar os campos `username` e `password` como dados do formulário. + +E a especificação diz que os campos devem ser nomeados assim. Portanto, `user-name` ou `email` não funcionariam. + +Mas não se preocupe, você pode mostrá-lo como quiser aos usuários finais no frontend. + +E seus modelos de banco de dados podem usar qualquer outro nome que você desejar. + +Mas para a *operação de rota* de login, precisamos usar esses nomes para serem compatíveis com a especificação (e poder, por exemplo, usar o sistema integrado de documentação da API). + +A especificação também afirma que o `username` e a `password` devem ser enviados como dados de formulário (portanto, não há JSON aqui). + +### `scope` + +A especificação também diz que o cliente pode enviar outro campo de formulário "`scope`" (Escopo). + +O nome do campo do formulário é `scope` (no singular), mas na verdade é uma longa string com "escopos" separados por espaços. + +Cada “scope” é apenas uma string (sem espaços). + +Normalmente são usados para declarar permissões de segurança específicas, por exemplo: + +* `users:read` ou `users:write` são exemplos comuns. +* `instagram_basic` é usado pelo Facebook e Instagram. +* `https://www.googleapis.com/auth/drive` é usado pelo Google. + +/// info | Informação + +No OAuth2, um "scope" é apenas uma string que declara uma permissão específica necessária. + +Não importa se tem outros caracteres como `:` ou se é uma URL. + +Esses detalhes são específicos da implementação. + +Para OAuth2 são apenas strings. + +/// + +## Código para conseguir o `username` e a `password` + +Agora vamos usar os utilitários fornecidos pelo **FastAPI** para lidar com isso. + +### `OAuth2PasswordRequestForm` + +Primeiro, importe `OAuth2PasswordRequestForm` e use-o como uma dependência com `Depends` na *operação de rota* para `/token`: + +{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *} + +`OAuth2PasswordRequestForm` é uma dependência de classe que declara um corpo de formulário com: + +* O `username`. +* A `password`. +* Um campo `scope` opcional como uma string grande, composta de strings separadas por espaços. +* Um `grant_type` (tipo de concessão) opcional. + +/// tip | Dica + +A especificação OAuth2 na verdade *requer* um campo `grant_type` com um valor fixo de `password`, mas `OAuth2PasswordRequestForm` não o impõe. + +Se você precisar aplicá-lo, use `OAuth2PasswordRequestFormStrict` em vez de `OAuth2PasswordRequestForm`. + +/// + +* Um `client_id` opcional (não precisamos dele em nosso exemplo). +* Um `client_secret` opcional (não precisamos dele em nosso exemplo). + +/// info | Informação + +O `OAuth2PasswordRequestForm` não é uma classe especial para **FastAPI** como é `OAuth2PasswordBearer`. + +`OAuth2PasswordBearer` faz com que **FastAPI** saiba que é um esquema de segurança. Portanto, é adicionado dessa forma ao OpenAPI. + +Mas `OAuth2PasswordRequestForm` é apenas uma dependência de classe que você mesmo poderia ter escrito ou poderia ter declarado os parâmetros do `Form` (formulário) diretamente. + +Mas como é um caso de uso comum, ele é fornecido diretamente pelo **FastAPI**, apenas para facilitar. + +/// + +### Use os dados do formulário + +/// tip | Dica + +A instância da classe de dependência `OAuth2PasswordRequestForm` não terá um atributo `scope` com a string longa separada por espaços, em vez disso, terá um atributo `scopes` com a lista real de strings para cada escopo enviado. + +Não estamos usando `scopes` neste exemplo, mas a funcionalidade está disponível se você precisar. + +/// + +Agora, obtenha os dados do usuário do banco de dados (falso), usando o `username` do campo do formulário. + +Se não existir tal usuário, retornaremos um erro dizendo "Incorrect username or password" (Nome de usuário ou senha incorretos). + +Para o erro, usamos a exceção `HTTPException`: + +{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *} + +### Confira a password (senha) + +Neste ponto temos os dados do usuário do nosso banco de dados, mas não verificamos a senha. + +Vamos colocar esses dados primeiro no modelo `UserInDB` do Pydantic. + +Você nunca deve salvar senhas em texto simples, portanto, usaremos o sistema de hashing de senhas (falsas). + +Se as senhas não corresponderem, retornaremos o mesmo erro. + +#### Hashing de senha + +"Hashing" significa: converter algum conteúdo (uma senha neste caso) em uma sequência de bytes (apenas uma string) que parece algo sem sentido. + +Sempre que você passa exatamente o mesmo conteúdo (exatamente a mesma senha), você obtém exatamente a mesma sequência aleatória de caracteres. + +Mas você não pode converter a sequência aleatória de caracteres de volta para a senha. + +##### Porque usar hashing de senha + +Se o seu banco de dados for roubado, o ladrão não terá as senhas em texto simples dos seus usuários, apenas os hashes. + +Assim, o ladrão não poderá tentar usar essas mesmas senhas em outro sistema (como muitos usuários usam a mesma senha em todos os lugares, isso seria perigoso). + +{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *} + +#### Sobre `**user_dict` + +`UserInDB(**user_dict)` significa: + +*Passe as keys (chaves) e values (valores) de `user_dict` diretamente como argumentos de valor-chave, equivalente a:* + +```Python +UserInDB( + username = user_dict["username"], + email = user_dict["email"], + full_name = user_dict["full_name"], + disabled = user_dict["disabled"], + hashed_password = user_dict["hashed_password"], +) +``` + +/// info | Informação + +Para uma explicação mais completa de `**user_dict`, verifique [a documentação para **Extra Models**](../extra-models.md#about-user_indict){.internal-link target=_blank}. + +/// + +## Retorne o token + +A resposta do endpoint `token` deve ser um objeto JSON. + +Deve ter um `token_type`. No nosso caso, como estamos usando tokens "Bearer", o tipo de token deve ser "`bearer`". + +E deve ter um `access_token`, com uma string contendo nosso token de acesso. + +Para este exemplo simples, seremos completamente inseguros e retornaremos o mesmo `username` do token. + +/// tip | Dica + +No próximo capítulo, você verá uma implementação realmente segura, com hash de senha e tokens JWT. + +Mas, por enquanto, vamos nos concentrar nos detalhes específicos de que precisamos. + +/// + +{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *} + +/// tip | Dica + +Pela especificação, você deve retornar um JSON com um `access_token` e um `token_type`, o mesmo que neste exemplo. + +Isso é algo que você mesmo deve fazer em seu código e certifique-se de usar essas chaves JSON. + +É quase a única coisa que você deve se lembrar de fazer corretamente, para estar em conformidade com as especificações. + +De resto, **FastAPI** cuida disso para você. + +/// + +## Atualize as dependências + +Agora vamos atualizar nossas dependências. + +Queremos obter o `user_user` *somente* se este usuário estiver ativo. + +Portanto, criamos uma dependência adicional `get_current_active_user` que por sua vez usa `get_current_user` como dependência. + +Ambas as dependências retornarão apenas um erro HTTP se o usuário não existir ou se estiver inativo. + +Portanto, em nosso endpoint, só obteremos um usuário se o usuário existir, tiver sido autenticado corretamente e estiver ativo: + +{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *} + +/// info | Informação + +O cabeçalho adicional `WWW-Authenticate` com valor `Bearer` que estamos retornando aqui também faz parte da especificação. + +Qualquer código de status HTTP (erro) 401 "UNAUTHORIZED" também deve retornar um cabeçalho `WWW-Authenticate`. + +No caso de tokens ao portador (nosso caso), o valor desse cabeçalho deve ser `Bearer`. + +Na verdade, você pode pular esse cabeçalho extra e ainda funcionaria. + +Mas é fornecido aqui para estar em conformidade com as especificações. + +Além disso, pode haver ferramentas que esperam e usam isso (agora ou no futuro) e que podem ser úteis para você ou seus usuários, agora ou no futuro. + +Esse é o benefício dos padrões... + +/// + +## Veja em ação + +Abra o docs interativo: http://127.0.0.1:8000/docs. + +### Autenticação + +Clique no botão "Authorize". + +Use as credenciais: + +User: `johndoe` + +Password: `secret` + + + +Após autenticar no sistema, você verá assim: + + + +### Obtenha seus próprios dados de usuário + +Agora use a operação `GET` com o caminho `/users/me`. + +Você obterá os dados do seu usuário, como: + +```JSON +{ + "username": "johndoe", + "email": "johndoe@example.com", + "full_name": "John Doe", + "disabled": false, + "hashed_password": "fakehashedsecret" +} +``` + + + +Se você clicar no ícone de cadeado, sair e tentar a mesma operação novamente, receberá um erro HTTP 401 de: + +```JSON +{ + "detail": "Not authenticated" +} +``` + +### Usuário inativo + +Agora tente com um usuário inativo, autentique-se com: + +User: `alice` + +Password: `secret2` + +E tente usar a operação `GET` com o caminho `/users/me`. + +Você receberá um erro "Usuário inativo", como: + +```JSON +{ + "detail": "Inactive user" +} +``` + +## Recaptulando + +Agora você tem as ferramentas para implementar um sistema de segurança completo baseado em `username` e `password` para sua API. + +Usando essas ferramentas, você pode tornar o sistema de segurança compatível com qualquer banco de dados e com qualquer usuário ou modelo de dados. + +O único detalhe que falta é que ainda não é realmente "seguro". + +No próximo capítulo você verá como usar uma biblioteca de hashing de senha segura e tokens JWT. diff --git a/docs/pt/docs/tutorial/sql-databases.md b/docs/pt/docs/tutorial/sql-databases.md new file mode 100644 index 000000000..3d76a532c --- /dev/null +++ b/docs/pt/docs/tutorial/sql-databases.md @@ -0,0 +1,359 @@ +# Bancos de Dados SQL (Relacionais) + +**FastAPI** não exige que você use um banco de dados SQL (relacional). Mas você pode usar **qualquer banco de dados** que quiser. + +Aqui veremos um exemplo usando SQLModel. + +**SQLModel** é construído sobre SQLAlchemy e Pydantic. Ele foi criado pelo mesmo autor do **FastAPI** para ser o par perfeito para aplicações **FastAPI** que precisam usar **bancos de dados SQL**. + +/// tip | Dica + +Você pode usar qualquer outra biblioteca de banco de dados SQL ou NoSQL que quiser (em alguns casos chamadas de "ORMs"), o FastAPI não obriga você a usar nada. 😎 + +/// + +Como o SQLModel é baseado no SQLAlchemy, você pode facilmente usar **qualquer banco de dados suportado** pelo SQLAlchemy (o que também os torna suportados pelo SQLModel), como: + +* PostgreSQL +* MySQL +* SQLite +* Oracle +* Microsoft SQL Server, etc. + +Neste exemplo, usaremos **SQLite**, porque ele usa um único arquivo e o Python tem suporte integrado. Assim, você pode copiar este exemplo e executá-lo como está. + +Mais tarde, para sua aplicação em produção, você pode querer usar um servidor de banco de dados como o **PostgreSQL**. + +/// tip | Dica + +Existe um gerador de projetos oficial com **FastAPI** e **PostgreSQL** incluindo um frontend e mais ferramentas: https://github.com/fastapi/full-stack-fastapi-template + +/// + +Este é um tutorial muito simples e curto, se você quiser aprender sobre bancos de dados em geral, sobre SQL ou recursos mais avançados, acesse a documentação do SQLModel. + +## Instalar o `SQLModel` + +Primeiro, certifique-se de criar seu [ambiente virtual](../virtual-environments.md){.internal-link target=_blank}, ativá-lo e, em seguida, instalar o `sqlmodel`: + +
+ +```console +$ pip install sqlmodel +---> 100% +``` + +
+ +## Criar o App com um Único Modelo + +Vamos criar a primeira versão mais simples do app com um único modelo **SQLModel**. + +Depois, vamos melhorá-lo aumentando a segurança e versatilidade com **múltiplos modelos** abaixo. 🤓 + +### Criar Modelos + +Importe o `SQLModel` e crie um modelo de banco de dados: + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[1:11] hl[7:11] *} + +A classe `Hero` é muito semelhante a um modelo Pydantic (na verdade, por baixo dos panos, ela *é um modelo Pydantic*). + +Existem algumas diferenças: + +* `table=True` informa ao SQLModel que este é um *modelo de tabela*, ele deve representar uma **tabela** no banco de dados SQL, não é apenas um *modelo de dados* (como seria qualquer outra classe Pydantic comum). + +* `Field(primary_key=True)` informa ao SQLModel que o `id` é a **chave primária** no banco de dados SQL (você pode aprender mais sobre chaves primárias SQL na documentação do SQLModel). + + Ao ter o tipo como `int | None`, o SQLModel saberá que essa coluna deve ser um `INTEGER` no banco de dados SQL e que ela deve ser `NULLABLE`. + +* `Field(index=True)` informa ao SQLModel que ele deve criar um **índice SQL** para essa coluna, o que permitirá buscas mais rápidas no banco de dados ao ler dados filtrados por essa coluna. + + O SQLModel saberá que algo declarado como `str` será uma coluna SQL do tipo `TEXT` (ou `VARCHAR`, dependendo do banco de dados). + +### Criar um Engine +Um `engine` SQLModel (por baixo dos panos, ele é na verdade um `engine` do SQLAlchemy) é o que **mantém as conexões** com o banco de dados. + +Você teria **um único objeto `engine`** para todo o seu código se conectar ao mesmo banco de dados. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[14:18] hl[14:15,17:18] *} + +Usar `check_same_thread=False` permite que o FastAPI use o mesmo banco de dados SQLite em diferentes threads. Isso é necessário, pois **uma única requisição** pode usar **mais de uma thread** (por exemplo, em dependências). + +Não se preocupe, com a forma como o código está estruturado, garantiremos que usamos **uma única *sessão* SQLModel por requisição** mais tarde, isso é realmente o que o `check_same_thread` está tentando conseguir. + +### Criar as Tabelas + +Em seguida, adicionamos uma função que usa `SQLModel.metadata.create_all(engine)` para **criar as tabelas** para todos os *modelos de tabela*. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[21:22] hl[21:22] *} + +### Criar uma Dependência de Sessão + +Uma **`Session`** é o que armazena os **objetos na memória** e acompanha as alterações necessárias nos dados, para então **usar o `engine`** para se comunicar com o banco de dados. + +Vamos criar uma **dependência** do FastAPI com `yield` que fornecerá uma nova `Session` para cada requisição. Isso é o que garante que usamos uma única sessão por requisição. 🤓 + +Então, criamos uma dependência `Annotated` chamada `SessionDep` para simplificar o restante do código que usará essa dependência. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[25:30] hl[25:27,30] *} + +### Criar Tabelas de Banco de Dados na Inicialização + +Vamos criar as tabelas do banco de dados quando o aplicativo for iniciado. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[32:37] hl[35:37] *} + +Aqui, criamos as tabelas em um evento de inicialização do aplicativo. + +Para produção, você provavelmente usaria um script de migração que é executado antes de iniciar seu app. 🤓 + +/// tip | Dica + +O SQLModel terá utilitários de migração envolvendo o Alembic, mas por enquanto, você pode usar o Alembic diretamente. + +/// + +### Criar um Hero + +Como cada modelo SQLModel também é um modelo Pydantic, você pode usá-lo nas mesmas **anotações de tipo** que usaria para modelos Pydantic. + +Por exemplo, se você declarar um parâmetro do tipo `Hero`, ele será lido do **corpo JSON**. + +Da mesma forma, você pode declará-lo como o **tipo de retorno** da função, e então o formato dos dados aparecerá na interface de documentação automática da API. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[40:45] hl[40:45] *} + + + +Aqui, usamos a dependência `SessionDep` (uma `Session`) para adicionar o novo `Hero` à instância `Session`, fazer commit das alterações no banco de dados, atualizar os dados no `hero` e então retorná-lo. + +### Ler Heroes + +Podemos **ler** `Hero`s do banco de dados usando um `select()`. Podemos incluir um `limit` e `offset` para paginar os resultados. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[48:55] hl[51:52,54] *} + +### Ler um Único Hero + +Podemos **ler** um único `Hero`. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[58:63] hl[60] *} + +### Deletar um Hero + +Também podemos **deletar** um `Hero`. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[66:73] hl[71] *} + +### Executar o App + +Você pode executar o app: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Então, vá para a interface `/docs`, você verá que o **FastAPI** está usando esses **modelos** para **documentar** a API, e ele também os usará para **serializar** e **validar** os dados. + +
+ +
+ +## Atualizar o App com Múltiplos Modelos + +Agora vamos **refatorar** este app um pouco para aumentar a **segurança** e **versatilidade**. + +Se você verificar o app anterior, na interface você pode ver que, até agora, ele permite que o cliente decida o `id` do `Hero` a ser criado. 😱 + +Não deveríamos deixar isso acontecer, eles poderiam sobrescrever um `id` que já atribuimos na base de dados. Decidir o `id` deve ser feito pelo **backend** ou pelo **banco de dados**, **não pelo cliente**. + +Além disso, criamos um `secret_name` para o hero, mas até agora estamos retornando ele em todos os lugares, isso não é muito **secreto**... 😅 + +Vamos corrigir essas coisas adicionando alguns **modelos extras**. Aqui é onde o SQLModel vai brilhar. ✨ + +### Criar Múltiplos Modelos + +No **SQLModel**, qualquer classe de modelo que tenha `table=True` é um **modelo de tabela**. + +E qualquer classe de modelo que não tenha `table=True` é um **modelo de dados**, esses são na verdade apenas modelos Pydantic (com alguns recursos extras pequenos). 🤓 + +Com o SQLModel, podemos usar a **herança** para **evitar duplicação** de todos os campos em todos os casos. + +#### `HeroBase` - a classe base + +Vamos começar com um modelo `HeroBase` que tem todos os **campos compartilhados** por todos os modelos: + +* `name` +* `age` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:9] hl[7:9] *} + +#### `Hero` - o *modelo de tabela* + +Em seguida, vamos criar `Hero`, o verdadeiro *modelo de tabela*, com os **campos extras** que nem sempre estão nos outros modelos: + +* `id` +* `secret_name` + +Como `Hero` herda de `HeroBase`, ele **também** tem os **campos** declarados em `HeroBase`, então todos os campos para `Hero` são: + +* `id` +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:14] hl[12:14] *} + +#### `HeroPublic` - o *modelo de dados* público + +Em seguida, criamos um modelo `HeroPublic`, que será **retornado** para os clientes da API. + +Ele tem os mesmos campos que `HeroBase`, então não incluirá `secret_name`. + +Finalmente, a identidade dos nossos heróis está protegida! 🥷 + +Ele também declara novamente `id: int`. Ao fazer isso, estamos fazendo um **contrato** com os clientes da API, para que eles possam sempre esperar que o `id` estará lá e será um `int` (nunca será `None`). + +/// tip | Dica + +Fazer com que o modelo de retorno garanta que um valor esteja sempre disponível e sempre seja um `int` (não `None`) é muito útil para os clientes da API, eles podem escrever código muito mais simples com essa certeza. + +Além disso, **clientes gerados automaticamente** terão interfaces mais simples, para que os desenvolvedores que se comunicam com sua API possam ter uma experiência muito melhor trabalhando com sua API. 😎 + +/// + +Todos os campos em `HeroPublic` são os mesmos que em `HeroBase`, com `id` declarado como `int` (não `None`): + +* `id` +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:18] hl[17:18] *} + +#### `HeroCreate` - o *modelo de dados* para criar um hero + +Agora criamos um modelo `HeroCreate`, este é o que **validará** os dados dos clientes. + +Ele tem os mesmos campos que `HeroBase`, e também tem `secret_name`. + +Agora, quando os clientes **criarem um novo hero**, eles enviarão o `secret_name`, ele será armazenado no banco de dados, mas esses nomes secretos não serão retornados na API para os clientes. + +/// tip | Dica + +É assim que você trataria **senhas**. Receba-as, mas não as retorne na API. + +Você também faria um **hash** com os valores das senhas antes de armazená-los, **nunca os armazene em texto simples**. + +/// + +Os campos de `HeroCreate` são: + +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:22] hl[21:22] *} + +#### `HeroUpdate` - o *modelo de dados* para atualizar um hero + +Não tínhamos uma maneira de **atualizar um hero** na versão anterior do app, mas agora com **múltiplos modelos**, podemos fazer isso. 🎉 + +O *modelo de dados* `HeroUpdate` é um pouco especial, ele tem **todos os mesmos campos** que seriam necessários para criar um novo hero, mas todos os campos são **opcionais** (todos têm um valor padrão). Dessa forma, quando você atualizar um hero, poderá enviar apenas os campos que deseja atualizar. + +Como todos os **campos realmente mudam** (o tipo agora inclui `None` e eles agora têm um valor padrão de `None`), precisamos **declarar novamente** todos eles. + +Não precisamos herdar de `HeroBase`, pois estamos redeclarando todos os campos. Vou deixá-lo herdando apenas por consistência, mas isso não é necessário. É mais uma questão de gosto pessoal. 🤷 + +Os campos de `HeroUpdate` são: + +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:28] hl[25:28] *} + +### Criar com `HeroCreate` e retornar um `HeroPublic` + +Agora que temos **múltiplos modelos**, podemos atualizar as partes do app que os utilizam. + +Recebemos na requisição um *modelo de dados* `HeroCreate`, e a partir dele, criamos um *modelo de tabela* `Hero`. + +Esse novo *modelo de tabela* `Hero` terá os campos enviados pelo cliente, e também terá um `id` gerado pelo banco de dados. + +Em seguida, retornamos o mesmo *modelo de tabela* `Hero` como está na função. Mas como declaramos o `response_model` com o *modelo de dados* `HeroPublic`, o **FastAPI** usará `HeroPublic` para validar e serializar os dados. + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[56:62] hl[56:58] *} + +/// tip | Dica + +Agora usamos `response_model=HeroPublic` em vez da **anotação de tipo de retorno** `-> HeroPublic` porque o valor que estamos retornando na verdade *não* é um `HeroPublic`. + +Se tivéssemos declarado `-> HeroPublic`, seu editor e o linter reclamariam (com razão) que você está retornando um `Hero` em vez de um `HeroPublic`. + +Ao declará-lo no `response_model`, estamos dizendo ao **FastAPI** para fazer o seu trabalho, sem interferir nas anotações de tipo e na ajuda do seu editor e de outras ferramentas. + +/// + +### Ler Heroes com `HeroPublic` + +Podemos fazer o mesmo que antes para **ler** `Hero`s, novamente, usamos `response_model=list[HeroPublic]` para garantir que os dados sejam validados e serializados corretamente. + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[65:72] hl[65] *} + +### Ler Um Hero com `HeroPublic` + +Podemos **ler** um único herói: + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[75:80] hl[77] *} + +### Atualizar um Hero com `HeroUpdate` + +Podemos **atualizar um hero**. Para isso, usamos uma operação HTTP `PATCH`. + +E no código, obtemos um `dict` com todos os dados enviados pelo cliente, **apenas os dados enviados pelo cliente**, excluindo quaisquer valores que estariam lá apenas por serem os valores padrão. Para fazer isso, usamos `exclude_unset=True`. Este é o truque principal. 🪄 + +Em seguida, usamos `hero_db.sqlmodel_update(hero_data)` para atualizar o `hero_db` com os dados de `hero_data`. + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[83:93] hl[83:84,88:89] *} + +### Deletar um Hero Novamente + +**Deletar** um hero permanece praticamente o mesmo. + +Não vamos satisfazer o desejo de refatorar tudo neste aqui. 😅 + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[96:103] hl[101] *} + +### Executar o App Novamente + +Você pode executar o app novamente: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +If you go to the `/docs` API UI, you will see that it is now updated, and it won't expect to receive the `id` from the client when creating a hero, etc. + +
+ +
+ +## Recapitulando + +Você pode usar **SQLModel** para interagir com um banco de dados SQL e simplificar o código com *modelos de dados* e *modelos de tabela*. + +Você pode aprender muito mais na documentação do **SQLModel**, há um mini tutorial sobre como usar SQLModel com **FastAPI** mais longo. 🚀 diff --git a/docs/pt/docs/tutorial/static-files.md b/docs/pt/docs/tutorial/static-files.md index 009158fc6..0660078f4 100644 --- a/docs/pt/docs/tutorial/static-files.md +++ b/docs/pt/docs/tutorial/static-files.md @@ -7,14 +7,15 @@ Você pode servir arquivos estáticos automaticamente de um diretório usando `S * Importe `StaticFiles`. * "Monte" uma instância de `StaticFiles()` em um caminho específico. -```Python hl_lines="2 6" -{!../../../docs_src/static_files/tutorial001.py!} -``` +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} -!!! note "Detalhes técnicos" - Você também pode usar `from starlette.staticfiles import StaticFiles`. +/// note | Detalhes técnicos - O **FastAPI** fornece o mesmo que `starlette.staticfiles` como `fastapi.staticfiles` apenas como uma conveniência para você, o desenvolvedor. Mas na verdade vem diretamente da Starlette. +Você também pode usar `from starlette.staticfiles import StaticFiles`. + +O **FastAPI** fornece o mesmo que `starlette.staticfiles` como `fastapi.staticfiles` apenas como uma conveniência para você, o desenvolvedor. Mas na verdade vem diretamente da Starlette. + +/// ### O que é "Montagem" diff --git a/docs/pt/docs/tutorial/testing.md b/docs/pt/docs/tutorial/testing.md new file mode 100644 index 000000000..8eb2f29b7 --- /dev/null +++ b/docs/pt/docs/tutorial/testing.md @@ -0,0 +1,241 @@ +# Testando + +Graças ao Starlette, testar aplicativos **FastAPI** é fácil e agradável. + +Ele é baseado no HTTPX, que por sua vez é projetado com base em Requests, por isso é muito familiar e intuitivo. + +Com ele, você pode usar o pytest diretamente com **FastAPI**. + +## Usando `TestClient` + +/// info | Informação + +Para usar o `TestClient`, primeiro instale o `httpx`. + +Certifique-se de criar um [ambiente virtual](../virtual-environments.md){.internal-link target=_blank}, ativá-lo e instalá-lo, por exemplo: + +```console +$ pip install httpx +``` + +/// + +Importe `TestClient`. + +Crie um `TestClient` passando seu aplicativo **FastAPI** para ele. + +Crie funções com um nome que comece com `test_` (essa é a convenção padrão do `pytest`). + +Use o objeto `TestClient` da mesma forma que você faz com `httpx`. + +Escreva instruções `assert` simples com as expressões Python padrão que você precisa verificar (novamente, `pytest` padrão). + +{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *} + +/// tip | Dica + +Observe que as funções de teste são `def` normais, não `async def`. + +E as chamadas para o cliente também são chamadas normais, não usando `await`. + +Isso permite que você use `pytest` diretamente sem complicações. + +/// + +/// note | Detalhes técnicos + +Você também pode usar `from starlette.testclient import TestClient`. + +**FastAPI** fornece o mesmo `starlette.testclient` que `fastapi.testclient` apenas como uma conveniência para você, o desenvolvedor. Mas ele vem diretamente da Starlette. + +/// + +/// tip | Dica + +Se você quiser chamar funções `async` em seus testes além de enviar solicitações ao seu aplicativo FastAPI (por exemplo, funções de banco de dados assíncronas), dê uma olhada em [Testes assíncronos](../advanced/async-tests.md){.internal-link target=_blank} no tutorial avançado. + +/// + +## Separando testes + +Em uma aplicação real, você provavelmente teria seus testes em um arquivo diferente. + +E seu aplicativo **FastAPI** também pode ser composto de vários arquivos/módulos, etc. + +### Arquivo do aplicativo **FastAPI** + +Digamos que você tenha uma estrutura de arquivo conforme descrito em [Aplicativos maiores](bigger-applications.md){.internal-link target=_blank}: + +``` +. +├── app +│   ├── __init__.py +│   └── main.py +``` + +No arquivo `main.py` você tem seu aplicativo **FastAPI**: + + +{* ../../docs_src/app_testing/main.py *} + +### Arquivo de teste + +Então você poderia ter um arquivo `test_main.py` com seus testes. Ele poderia estar no mesmo pacote Python (o mesmo diretório com um arquivo `__init__.py`): + +``` hl_lines="5" +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +Como esse arquivo está no mesmo pacote, você pode usar importações relativas para importar o objeto `app` do módulo `main` (`main.py`): + +{* ../../docs_src/app_testing/test_main.py hl[3] *} + +...e ter o código para os testes como antes. + +## Testando: exemplo estendido + +Agora vamos estender este exemplo e adicionar mais detalhes para ver como testar diferentes partes. + +### Arquivo de aplicativo **FastAPI** estendido + +Vamos continuar com a mesma estrutura de arquivo de antes: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +Digamos que agora o arquivo `main.py` com seu aplicativo **FastAPI** tenha algumas outras **operações de rotas**. + +Ele tem uma operação `GET` que pode retornar um erro. + +Ele tem uma operação `POST` que pode retornar vários erros. + +Ambas as *operações de rotas* requerem um cabeçalho `X-Token`. + +//// tab | Python 3.10+ + +```Python +{!> ../../docs_src/app_testing/app_b_an_py310/main.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python +{!> ../../docs_src/app_testing/app_b_an_py39/main.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python +{!> ../../docs_src/app_testing/app_b_an/main.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Prefira usar a versão `Annotated` se possível. + +/// + +```Python +{!> ../../docs_src/app_testing/app_b_py310/main.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Prefira usar a versão `Annotated` se possível. + +/// + +```Python +{!> ../../docs_src/app_testing/app_b/main.py!} +``` + +//// + +### Arquivo de teste estendido + +Você pode então atualizar `test_main.py` com os testes estendidos: + +{* ../../docs_src/app_testing/app_b/test_main.py *} + +Sempre que você precisar que o cliente passe informações na requisição e não souber como, você pode pesquisar (no Google) como fazer isso no `httpx`, ou até mesmo como fazer isso com `requests`, já que o design do HTTPX é baseado no design do Requests. + +Depois é só fazer o mesmo nos seus testes. + +Por exemplo: + +* Para passar um parâmetro *path* ou *query*, adicione-o à própria URL. +* Para passar um corpo JSON, passe um objeto Python (por exemplo, um `dict`) para o parâmetro `json`. +* Se você precisar enviar *Dados de Formulário* em vez de JSON, use o parâmetro `data`. +* Para passar *headers*, use um `dict` no parâmetro `headers`. +* Para *cookies*, um `dict` no parâmetro `cookies`. + +Para mais informações sobre como passar dados para o backend (usando `httpx` ou `TestClient`), consulte a documentação do HTTPX. + +/// info | Informação + +Observe que o `TestClient` recebe dados que podem ser convertidos para JSON, não para modelos Pydantic. + +Se você tiver um modelo Pydantic em seu teste e quiser enviar seus dados para o aplicativo durante o teste, poderá usar o `jsonable_encoder` descrito em [Codificador compatível com JSON](encoder.md){.internal-link target=_blank}. + +/// + +## Execute-o + +Depois disso, você só precisa instalar o `pytest`. + +Certifique-se de criar um [ambiente virtual](../virtual-environments.md){.internal-link target=_blank}, ativá-lo e instalá-lo, por exemplo: + +
+ +```console +$ pip install pytest + +---> 100% +``` + +
+ +Ele detectará os arquivos e os testes automaticamente, os executará e informará os resultados para você. + +Execute os testes com: + +
+ +```console +$ pytest + +================ test session starts ================ +platform linux -- Python 3.6.9, pytest-5.3.5, py-1.8.1, pluggy-0.13.1 +rootdir: /home/user/code/superawesome-cli/app +plugins: forked-1.1.3, xdist-1.31.0, cov-2.8.1 +collected 6 items + +---> 100% + +test_main.py ...... [100%] + +================= 1 passed in 0.03s ================= +``` + +
diff --git a/docs/pt/docs/virtual-environments.md b/docs/pt/docs/virtual-environments.md new file mode 100644 index 000000000..5fc1a8866 --- /dev/null +++ b/docs/pt/docs/virtual-environments.md @@ -0,0 +1,844 @@ +# Ambientes Virtuais + +Ao trabalhar em projetos Python, você provavelmente deve usar um **ambiente virtual** (ou um mecanismo similar) para isolar os pacotes que você instala para cada projeto. + +/// info | Informação + +Se você já sabe sobre ambientes virtuais, como criá-los e usá-los, talvez seja melhor pular esta seção. 🤓 + +/// + +/// tip | Dica + +Um **ambiente virtual** é diferente de uma **variável de ambiente**. + +Uma **variável de ambiente** é uma variável no sistema que pode ser usada por programas. + +Um **ambiente virtual** é um diretório com alguns arquivos. + +/// + +/// info | Informação + +Esta página lhe ensinará como usar **ambientes virtuais** e como eles funcionam. + +Se você estiver pronto para adotar uma **ferramenta que gerencia tudo** para você (incluindo a instalação do Python), experimente uv. + +/// + +## Criar um Projeto + +Primeiro, crie um diretório para seu projeto. + +O que normalmente faço é criar um diretório chamado `code` dentro do meu diretório home/user. + +E dentro disso eu crio um diretório por projeto. + +
+ +```console +// Vá para o diretório inicial +$ cd +// Crie um diretório para todos os seus projetos de código +$ mkdir code +// Entre nesse diretório de código +$ cd code +// Crie um diretório para este projeto +$ mkdir awesome-project +// Entre no diretório do projeto +$ cd awesome-project +``` + +
+ +## Crie um ambiente virtual + +Ao começar a trabalhar em um projeto Python **pela primeira vez**, crie um ambiente virtual **dentro do seu projeto**. + +/// tip | Dica + +Você só precisa fazer isso **uma vez por projeto**, não toda vez que trabalhar. + +/// + +//// tab | `venv` + +Para criar um ambiente virtual, você pode usar o módulo `venv` que vem com o Python. + +
+ +```console +$ python -m venv .venv +``` + +
+ +/// details | O que esse comando significa + +* `python`: usa o programa chamado `python` +* `-m`: chama um módulo como um script, nós diremos a ele qual módulo vem em seguida +* `venv`: usa o módulo chamado `venv` que normalmente vem instalado com o Python +* `.venv`: cria o ambiente virtual no novo diretório `.venv` + +/// + +//// + +//// tab | `uv` + +Se você tiver o `uv` instalado, poderá usá-lo para criar um ambiente virtual. + +
+ +```console +$ uv venv +``` + +
+ +/// tip | Dica + +Por padrão, `uv` criará um ambiente virtual em um diretório chamado `.venv`. + +Mas você pode personalizá-lo passando um argumento adicional com o nome do diretório. + +/// + +//// + +Esse comando cria um novo ambiente virtual em um diretório chamado `.venv`. + +/// details | `.venv` ou outro nome + +Você pode criar o ambiente virtual em um diretório diferente, mas há uma convenção para chamá-lo de `.venv`. + +/// + +## Ative o ambiente virtual + +Ative o novo ambiente virtual para que qualquer comando Python que você executar ou pacote que você instalar o utilize. + +/// tip | Dica + +Faça isso **toda vez** que iniciar uma **nova sessão de terminal** para trabalhar no projeto. + +/// + +//// tab | Linux, macOS + +
+ +```console +$ source .venv/bin/activate +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ .venv\Scripts\Activate.ps1 +``` + +
+ +//// + +//// tab | Windows Bash + +Ou se você usa o Bash para Windows (por exemplo, Git Bash): + +
+ +```console +$ source .venv/Scripts/activate +``` + +
+ +//// + +/// tip | Dica + +Toda vez que você instalar um **novo pacote** naquele ambiente, **ative** o ambiente novamente. + +Isso garante que, se você usar um **programa de terminal (CLI)** instalado por esse pacote, você usará aquele do seu ambiente virtual e não qualquer outro que possa ser instalado globalmente, provavelmente com uma versão diferente do que você precisa. + +/// + +## Verifique se o ambiente virtual está ativo + +Verifique se o ambiente virtual está ativo (o comando anterior funcionou). + +/// tip | Dica + +Isso é **opcional**, mas é uma boa maneira de **verificar** se tudo está funcionando conforme o esperado e se você está usando o ambiente virtual pretendido. + +/// + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
+ +Se ele mostrar o binário `python` em `.venv/bin/python`, dentro do seu projeto (neste caso `awesome-project`), então funcionou. 🎉 + +//// + +//// tab | Windows PowerShell + +
+ +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
+ +Se ele mostrar o binário `python` em `.venv\Scripts\python`, dentro do seu projeto (neste caso `awesome-project`), então funcionou. 🎉 + +//// + +## Atualizar `pip` + +/// tip | Dica + +Se você usar `uv`, você o usará para instalar coisas em vez do `pip`, então não precisará atualizar o `pip`. 😎 + +/// + +Se você estiver usando `pip` para instalar pacotes (ele vem por padrão com o Python), você deve **atualizá-lo** para a versão mais recente. + +Muitos erros exóticos durante a instalação de um pacote são resolvidos apenas atualizando o `pip` primeiro. + +/// tip | Dica + +Normalmente, você faria isso **uma vez**, logo após criar o ambiente virtual. + +/// + +Certifique-se de que o ambiente virtual esteja ativo (com o comando acima) e execute: + +
+ +```console +$ python -m pip install --upgrade pip + +---> 100% +``` + +
+ +## Adicionar `.gitignore` + +Se você estiver usando **Git** (você deveria), adicione um arquivo `.gitignore` para excluir tudo em seu `.venv` do Git. + +/// tip | Dica + +Se você usou `uv` para criar o ambiente virtual, ele já fez isso para você, você pode pular esta etapa. 😎 + +/// + +/// tip | Dica + +Faça isso **uma vez**, logo após criar o ambiente virtual. + +/// + +
+ +```console +$ echo "*" > .venv/.gitignore +``` + +
+ +/// details | O que esse comando significa + +* `echo "*"`: irá "imprimir" o texto `*` no terminal (a próxima parte muda isso um pouco) +* `>`: qualquer coisa impressa no terminal pelo comando à esquerda de `>` não deve ser impressa, mas sim escrita no arquivo que vai à direita de `>` +* `.gitignore`: o nome do arquivo onde o texto deve ser escrito + +E `*` para Git significa "tudo". Então, ele ignorará tudo no diretório `.venv`. + +Esse comando criará um arquivo `.gitignore` com o conteúdo: + +```gitignore +* +``` + +/// + +## Instalar Pacotes + +Após ativar o ambiente, você pode instalar pacotes nele. + +/// tip | Dica + +Faça isso **uma vez** ao instalar ou atualizar os pacotes que seu projeto precisa. + +Se precisar atualizar uma versão ou adicionar um novo pacote, você **fará isso novamente**. + +/// + +### Instalar pacotes diretamente + +Se estiver com pressa e não quiser usar um arquivo para declarar os requisitos de pacote do seu projeto, você pode instalá-los diretamente. + +/// tip | Dica + +É uma (muito) boa ideia colocar os pacotes e versões que seu programa precisa em um arquivo (por exemplo `requirements.txt` ou `pyproject.toml`). + +/// + +//// tab | `pip` + +
+ +```console +$ pip install "fastapi[standard]" + +---> 100% +``` + +
+ +//// + +//// tab | `uv` + +Se você tem o `uv`: + +
+ +```console +$ uv pip install "fastapi[standard]" +---> 100% +``` + +
+ +//// + +### Instalar a partir de `requirements.txt` + +Se você tiver um `requirements.txt`, agora poderá usá-lo para instalar seus pacotes. + +//// tab | `pip` + +
+ +```console +$ pip install -r requirements.txt +---> 100% +``` + +
+ +//// + +//// tab | `uv` + +Se você tem o `uv`: + +
+ +```console +$ uv pip install -r requirements.txt +---> 100% +``` + +
+ +//// + +/// details | `requirements.txt` + +Um `requirements.txt` com alguns pacotes poderia se parecer com: + +```requirements.txt +fastapi[standard]==0.113.0 +pydantic==2.8.0 +``` + +/// + +## Execute seu programa + +Depois de ativar o ambiente virtual, você pode executar seu programa, e ele usará o Python dentro do seu ambiente virtual com os pacotes que você instalou lá. + +
+ +```console +$ python main.py + +Hello World +``` + +
+ +## Configure seu editor + +Você provavelmente usaria um editor. Certifique-se de configurá-lo para usar o mesmo ambiente virtual que você criou (ele provavelmente o detectará automaticamente) para que você possa obter erros de preenchimento automático e em linha. + +Por exemplo: + +* VS Code +* PyCharm + +/// tip | Dica + +Normalmente, você só precisa fazer isso **uma vez**, ao criar o ambiente virtual. + +/// + +## Desativar o ambiente virtual + +Quando terminar de trabalhar no seu projeto, você pode **desativar** o ambiente virtual. + +
+ +```console +$ deactivate +``` + +
+ +Dessa forma, quando você executar `python`, ele não tentará executá-lo naquele ambiente virtual com os pacotes instalados nele. + +## Pronto para trabalhar + +Agora você está pronto para começar a trabalhar no seu projeto. + + + +/// tip | Dica + +Você quer entender o que é tudo isso acima? + +Continue lendo. 👇🤓 + +/// + +## Por que ambientes virtuais + +Para trabalhar com o FastAPI, você precisa instalar o Python. + +Depois disso, você precisará **instalar** o FastAPI e quaisquer outros **pacotes** que queira usar. + +Para instalar pacotes, você normalmente usaria o comando `pip` que vem com o Python (ou alternativas semelhantes). + +No entanto, se você usar `pip` diretamente, os pacotes serão instalados no seu **ambiente Python global** (a instalação global do Python). + +### O Problema + +Então, qual é o problema em instalar pacotes no ambiente global do Python? + +Em algum momento, você provavelmente acabará escrevendo muitos programas diferentes que dependem de **pacotes diferentes**. E alguns desses projetos em que você trabalha dependerão de **versões diferentes** do mesmo pacote. 😱 + +Por exemplo, você pode criar um projeto chamado `philosophers-stone`, este programa depende de outro pacote chamado **`harry`, usando a versão `1`**. Então, você precisa instalar `harry`. + +```mermaid +flowchart LR + stone(philosophers-stone) -->|requires| harry-1[harry v1] +``` + +Então, em algum momento depois, você cria outro projeto chamado `prisoner-of-azkaban`, e esse projeto também depende de `harry`, mas esse projeto precisa do **`harry` versão `3`**. + +```mermaid +flowchart LR + azkaban(prisoner-of-azkaban) --> |requires| harry-3[harry v3] +``` + +Mas agora o problema é que, se você instalar os pacotes globalmente (no ambiente global) em vez de em um **ambiente virtual** local, você terá que escolher qual versão do `harry` instalar. + +Se você quiser executar `philosophers-stone`, precisará primeiro instalar `harry` versão `1`, por exemplo com: + +
+ +```console +$ pip install "harry==1" +``` + +
+ +E então você acabaria com `harry` versão `1` instalado em seu ambiente Python global. + +```mermaid +flowchart LR + subgraph global[global env] + harry-1[harry v1] + end + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) -->|requires| harry-1 + end +``` + +Mas se você quiser executar `prisoner-of-azkaban`, você precisará desinstalar `harry` versão `1` e instalar `harry` versão `3` (ou apenas instalar a versão `3` desinstalaria automaticamente a versão `1`). + +
+ +```console +$ pip install "harry==3" +``` + +
+ +E então você acabaria com `harry` versão `3` instalado em seu ambiente Python global. + +E se você tentar executar `philosophers-stone` novamente, há uma chance de que **não funcione** porque ele precisa de `harry` versão `1`. + +```mermaid +flowchart LR + subgraph global[global env] + harry-1[harry v1] + style harry-1 fill:#ccc,stroke-dasharray: 5 5 + harry-3[harry v3] + end + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) -.-x|⛔️| harry-1 + end + subgraph azkaban-project[prisoner-of-azkaban project] + azkaban(prisoner-of-azkaban) --> |requires| harry-3 + end +``` + +/// tip | Dica + +É muito comum em pacotes Python tentar ao máximo **evitar alterações drásticas** em **novas versões**, mas é melhor prevenir do que remediar e instalar versões mais recentes intencionalmente e, quando possível, executar os testes para verificar se tudo está funcionando corretamente. + +/// + +Agora, imagine isso com **muitos** outros **pacotes** dos quais todos os seus **projetos dependem**. Isso é muito difícil de gerenciar. E você provavelmente acabaria executando alguns projetos com algumas **versões incompatíveis** dos pacotes, e não saberia por que algo não está funcionando. + +Além disso, dependendo do seu sistema operacional (por exemplo, Linux, Windows, macOS), ele pode ter vindo com o Python já instalado. E, nesse caso, provavelmente tinha alguns pacotes pré-instalados com algumas versões específicas **necessárias para o seu sistema**. Se você instalar pacotes no ambiente global do Python, poderá acabar **quebrando** alguns dos programas que vieram com seu sistema operacional. + +## Onde os pacotes são instalados + +Quando você instala o Python, ele cria alguns diretórios com alguns arquivos no seu computador. + +Alguns desses diretórios são os responsáveis ​​por ter todos os pacotes que você instala. + +Quando você executa: + +
+ +```console +// Não execute isso agora, é apenas um exemplo 🤓 +$ pip install "fastapi[standard]" +---> 100% +``` + +
+ +Isso fará o download de um arquivo compactado com o código FastAPI, normalmente do PyPI. + +Ele também fará o **download** de arquivos para outros pacotes dos quais o FastAPI depende. + +Em seguida, ele **extrairá** todos esses arquivos e os colocará em um diretório no seu computador. + +Por padrão, ele colocará os arquivos baixados e extraídos no diretório que vem com a instalação do Python, que é o **ambiente global**. + +## O que são ambientes virtuais + +A solução para os problemas de ter todos os pacotes no ambiente global é usar um **ambiente virtual para cada projeto** em que você trabalha. + +Um ambiente virtual é um **diretório**, muito semelhante ao global, onde você pode instalar os pacotes para um projeto. + +Dessa forma, cada projeto terá seu próprio ambiente virtual (diretório `.venv`) com seus próprios pacotes. + +```mermaid +flowchart TB + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) --->|requires| harry-1 + subgraph venv1[.venv] + harry-1[harry v1] + end + end + subgraph azkaban-project[prisoner-of-azkaban project] + azkaban(prisoner-of-azkaban) --->|requires| harry-3 + subgraph venv2[.venv] + harry-3[harry v3] + end + end + stone-project ~~~ azkaban-project +``` + +## O que significa ativar um ambiente virtual + +Quando você ativa um ambiente virtual, por exemplo com: + +//// tab | Linux, macOS + +
+ +```console +$ source .venv/bin/activate +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ .venv\Scripts\Activate.ps1 +``` + +
+ +//// + +//// tab | Windows Bash + +Ou se você usa o Bash para Windows (por exemplo, Git Bash): + +
+ +```console +$ source .venv/Scripts/activate +``` + +
+ +//// + +Esse comando criará ou modificará algumas [variáveis ​​de ambiente](environment-variables.md){.internal-link target=_blank} que estarão disponíveis para os próximos comandos. + +Uma dessas variáveis ​​é a variável `PATH`. + +/// tip | Dica + +Você pode aprender mais sobre a variável de ambiente `PATH` na seção [Variáveis ​​de ambiente](environment-variables.md#path-environment-variable){.internal-link target=_blank}. + +/// + +A ativação de um ambiente virtual adiciona seu caminho `.venv/bin` (no Linux e macOS) ou `.venv\Scripts` (no Windows) à variável de ambiente `PATH`. + +Digamos que antes de ativar o ambiente, a variável `PATH` estava assim: + +//// tab | Linux, macOS + +```plaintext +/usr/bin:/bin:/usr/sbin:/sbin +``` + +Isso significa que o sistema procuraria programas em: + +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Windows\System32 +``` + +Isso significa que o sistema procuraria programas em: + +* `C:\Windows\System32` + +//// + +Após ativar o ambiente virtual, a variável `PATH` ficaria mais ou menos assim: + +//// tab | Linux, macOS + +```plaintext +/home/user/code/awesome-project/.venv/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +Isso significa que o sistema agora começará a procurar primeiro por programas em: + +```plaintext +/home/user/code/awesome-project/.venv/bin +``` + +antes de procurar nos outros diretórios. + +Então, quando você digita `python` no terminal, o sistema encontrará o programa Python em + +```plaintext +/home/user/code/awesome-project/.venv/bin/python +``` + +e usa esse. + +//// + +//// tab | Windows + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts;C:\Windows\System32 +``` + +Isso significa que o sistema agora começará a procurar primeiro por programas em: + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts +``` + +antes de procurar nos outros diretórios. + +Então, quando você digita `python` no terminal, o sistema encontrará o programa Python em + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +e usa esse. + +//// + +Um detalhe importante é que ele colocará o caminho do ambiente virtual no **início** da variável `PATH`. O sistema o encontrará **antes** de encontrar qualquer outro Python disponível. Dessa forma, quando você executar `python`, ele usará o Python **do ambiente virtual** em vez de qualquer outro `python` (por exemplo, um `python` de um ambiente global). + +Ativar um ambiente virtual também muda algumas outras coisas, mas esta é uma das mais importantes. + +## Verificando um ambiente virtual + +Ao verificar se um ambiente virtual está ativo, por exemplo com: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
+ +//// + +Isso significa que o programa `python` que será usado é aquele **no ambiente virtual**. + +você usa `which` no Linux e macOS e `Get-Command` no Windows PowerShell. + +A maneira como esse comando funciona é que ele vai e verifica na variável de ambiente `PATH`, passando por **cada caminho em ordem**, procurando pelo programa chamado `python`. Uma vez que ele o encontre, ele **mostrará o caminho** para esse programa. + +A parte mais importante é que quando você chama ``python`, esse é exatamente o "`python`" que será executado. + +Assim, você pode confirmar se está no ambiente virtual correto. + +/// tip | Dica + +É fácil ativar um ambiente virtual, obter um Python e então **ir para outro projeto**. + +E o segundo projeto **não funcionaria** porque você está usando o **Python incorreto**, de um ambiente virtual para outro projeto. + +É útil poder verificar qual `python` está sendo usado. 🤓 + +/// + +## Por que desativar um ambiente virtual + +Por exemplo, você pode estar trabalhando em um projeto `philosophers-stone`, **ativar esse ambiente virtual**, instalar pacotes e trabalhar com esse ambiente. + +E então você quer trabalhar em **outro projeto** `prisoner-of-azkaban`. + +Você vai para aquele projeto: + +
+ +```console +$ cd ~/code/prisoner-of-azkaban +``` + +
+ +Se você não desativar o ambiente virtual para `philosophers-stone`, quando você executar `python` no terminal, ele tentará usar o Python de `philosophers-stone`. + +
+ +```console +$ cd ~/code/prisoner-of-azkaban + +$ python main.py + +// Erro ao importar o Sirius, ele não está instalado 😱 +Traceback (most recent call last): + File "main.py", line 1, in + import sirius +``` + +
+ +Mas se você desativar o ambiente virtual e ativar o novo para `prisoner-of-askaban`, quando você executar `python`, ele usará o Python do ambiente virtual em `prisoner-of-azkaban`. + +
+ +```console +$ cd ~/code/prisoner-of-azkaban + +// Você não precisa estar no diretório antigo para desativar, você pode fazer isso de onde estiver, mesmo depois de ir para o outro projeto 😎 +$ deactivate + +// Ative o ambiente virtual em prisoner-of-azkaban/.venv 🚀 +$ source .venv/bin/activate + +// Agora, quando você executar o python, ele encontrará o pacote sirius instalado neste ambiente virtual ✨ +$ python main.py + +Eu juro solenemente 🐺 +``` + +
+ +## Alternativas + +Este é um guia simples para você começar e lhe ensinar como tudo funciona **por baixo**. + +Existem muitas **alternativas** para gerenciar ambientes virtuais, dependências de pacotes (requisitos) e projetos. + +Quando estiver pronto e quiser usar uma ferramenta para **gerenciar todo o projeto**, dependências de pacotes, ambientes virtuais, etc., sugiro que você experimente o uv. + +`uv` pode fazer muitas coisas, ele pode: + +* **Instalar o Python** para você, incluindo versões diferentes +* Gerenciar o **ambiente virtual** para seus projetos +* Instalar **pacotes** +* Gerenciar **dependências e versões** de pacotes para seu projeto +* Certifique-se de ter um conjunto **exato** de pacotes e versões para instalar, incluindo suas dependências, para que você possa ter certeza de que pode executar seu projeto em produção exatamente da mesma forma que em seu computador durante o desenvolvimento, isso é chamado de **bloqueio** +* E muitas outras coisas + +## Conclusão + +Se você leu e entendeu tudo isso, agora **você sabe muito mais** sobre ambientes virtuais do que muitos desenvolvedores por aí. 🤓 + +Saber esses detalhes provavelmente será útil no futuro, quando você estiver depurando algo que parece complexo, mas você saberá **como tudo funciona**. 😎 diff --git a/docs/ru/docs/about/index.md b/docs/ru/docs/about/index.md new file mode 100644 index 000000000..1015b667a --- /dev/null +++ b/docs/ru/docs/about/index.md @@ -0,0 +1,3 @@ +# О проекте + +FastAPI: внутреннее устройство, повлиявшие технологии и всё такое прочее. 🤓 diff --git a/docs/ru/docs/advanced/async-tests.md b/docs/ru/docs/advanced/async-tests.md new file mode 100644 index 000000000..7849ad109 --- /dev/null +++ b/docs/ru/docs/advanced/async-tests.md @@ -0,0 +1,99 @@ +# Асинхронное тестирование + +Вы уже видели как тестировать **FastAPI** приложение, используя имеющийся класс `TestClient`. К этому моменту вы видели только как писать тесты в синхронном стиле без использования `async` функций. + +Возможность использования асинхронных функций в ваших тестах может быть полезнa, когда, например, вы асинхронно обращаетесь к вашей базе данных. Представьте, что вы хотите отправить запросы в ваше FastAPI приложение, а затем при помощи асинхронной библиотеки для работы с базой данных удостовериться, что ваш бекэнд корректно записал данные в базу данных. + +Давайте рассмотрим, как мы можем это реализовать. + +## pytest.mark.anyio + +Если мы хотим вызывать асинхронные функции в наших тестах, то наши тестовые функции должны быть асинхронными. AnyIO предоставляет для этого отличный плагин, который позволяет нам указывать, какие тестовые функции должны вызываться асинхронно. + +## HTTPX + +Даже если **FastAPI** приложение использует обычные функции `def` вместо `async def`, это все равно `async` приложение 'под капотом'. + +Чтобы работать с асинхронным FastAPI приложением в ваших обычных тестовых функциях `def`, используя стандартный pytest, `TestClient` внутри себя делает некоторую магию. Но эта магия перестает работать, когда мы используем его внутри асинхронных функций. Запуская наши тесты асинхронно, мы больше не можем использовать `TestClient` внутри наших тестовых функций. + +`TestClient` основан на HTTPX, и, к счастью, мы можем использовать его (`HTTPX`) напрямую для тестирования API. + +## Пример + +В качестве простого примера, давайте рассмотрим файловую структуру, схожую с описанной в [Большие приложения](../tutorial/bigger-applications.md){.internal-link target=_blank} и [Тестирование](../tutorial/testing.md){.internal-link target=_blank}: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +Файл `main.py`: + +{* ../../docs_src/async_tests/main.py *} + +Файл `test_main.py` содержит тесты для `main.py`, теперь он может выглядеть так: + +{* ../../docs_src/async_tests/test_main.py *} + +## Запуск тестов + +Вы можете запустить свои тесты как обычно: + +
+ +```console +$ pytest + +---> 100% +``` + +
+ +## Подробнее + +Маркер `@pytest.mark.anyio` говорит pytest, что тестовая функция должна быть вызвана асинхронно: + +{* ../../docs_src/async_tests/test_main.py hl[7] *} + +/// tip | Подсказка + +Обратите внимание, что тестовая функция теперь `async def` вместо простого `def`, как это было при использовании `TestClient`. + +/// + +Затем мы можем создать `AsyncClient` со ссылкой на приложение и посылать асинхронные запросы, используя `await`. + +{* ../../docs_src/async_tests/test_main.py hl[9:12] *} + +Это эквивалентно следующему: + +```Python +response = client.get('/') +``` + +...которое мы использовали для отправки наших запросов с `TestClient`. + +/// tip | Подсказка + +Обратите внимание, что мы используем async/await с `AsyncClient` - запрос асинхронный. + +/// + +/// warning | Внимание + +Если ваше приложение полагается на lifespan события, то `AsyncClient` не запустит эти события. Чтобы обеспечить их срабатывание используйте `LifespanManager` из florimondmanca/asgi-lifespan. + +/// + +## Вызов других асинхронных функций + +Теперь тестовая функция стала асинхронной, поэтому внутри нее вы можете вызывать также и другие `async` функции, не связанные с отправлением запросов в ваше FastAPI приложение. Как если бы вы вызывали их в любом другом месте вашего кода. + +/// tip | Подсказка + +Если вы столкнулись с `RuntimeError: Task attached to a different loop` при вызове асинхронных функций в ваших тестах (например, при использовании MongoDB's MotorClient), то не забывайте инициализировать объекты, которым нужен цикл событий (event loop), только внутри асинхронных функций, например, в `'@app.on_event("startup")` callback. + +/// diff --git a/docs/ru/docs/advanced/response-cookies.md b/docs/ru/docs/advanced/response-cookies.md new file mode 100644 index 000000000..e04ff577c --- /dev/null +++ b/docs/ru/docs/advanced/response-cookies.md @@ -0,0 +1,48 @@ + +# Cookies в ответе + +## Использование параметра `Response` + +Вы можете объявить параметр типа `Response` в вашей функции эндпоинта. + +Затем установить cookies в этом временном объекте ответа. + +{* ../../docs_src/response_cookies/tutorial002.py hl[1, 8:9] *} + +После этого можно вернуть любой объект, как и раньше (например, `dict`, объект модели базы данных и так далее). + +Если вы указали `response_model`, он всё равно будет использоваться для фильтрации и преобразования возвращаемого объекта. + +**FastAPI** извлечет cookies (а также заголовки и коды состояния) из временного ответа и включит их в окончательный ответ, содержащий ваше возвращаемое значение, отфильтрованное через `response_model`. + +Вы также можете объявить параметр типа Response в зависимостях и устанавливать cookies (и заголовки) там. + +## Возвращение `Response` напрямую + +Вы также можете установить cookies, если возвращаете `Response` напрямую в вашем коде. + +Для этого создайте объект `Response`, как описано в разделе [Возвращение ответа напрямую](response-directly.md){.target=_blank}. + +Затем установите cookies и верните этот объект: + +{* ../../docs_src/response_cookies/tutorial001.py hl[10:12] *} + +/// tip | Примечание +Имейте в виду, что если вы возвращаете ответ напрямую, вместо использования параметра `Response`, **FastAPI** отправит его без дополнительной обработки. + +Убедитесь, что ваши данные имеют корректный тип. Например, они должны быть совместимы с JSON, если вы используете `JSONResponse`. + +Также убедитесь, что вы не отправляете данные, которые должны были быть отфильтрованы через `response_model`. +/// + +### Дополнительная информация + +/// note | Технические детали +Вы также можете использовать `from starlette.responses import Response` или `from starlette.responses import JSONResponse`. + +**FastAPI** предоставляет `fastapi.responses`, которые являются теми же объектами, что и `starlette.responses`, просто для удобства. Однако большинство доступных типов ответов поступает непосредственно из **Starlette**. + +Для установки заголовков и cookies `Response` используется часто, поэтому **FastAPI** также предоставляет его через `fastapi.responses`. +/// + +Чтобы увидеть все доступные параметры и настройки, ознакомьтесь с документацией Starlette. diff --git a/docs/ru/docs/advanced/websockets.md b/docs/ru/docs/advanced/websockets.md new file mode 100644 index 000000000..bc9dfcbff --- /dev/null +++ b/docs/ru/docs/advanced/websockets.md @@ -0,0 +1,186 @@ +# Веб-сокеты + +Вы можете использовать веб-сокеты в **FastAPI**. + +## Установка `WebSockets` + +Убедитесь, что [виртуальная среда](../virtual-environments.md){.internal-link target=_blank} создана, активируйте её и установите `websockets`: + +
+ +```console +$ pip install websockets + +---> 100% +``` + +
+ +## Клиент WebSockets + +### Рабочее приложение + +Скорее всего, в вашей реальной продуктовой системе есть фронтенд, реализованный при помощи современных фреймворков React, Vue.js или Angular. + +И наверняка для взаимодействия с бекендом через веб-сокеты вы будете использовать средства фронтенда. + +Также у вас может быть нативное мобильное приложение, коммуницирующее непосредственно с веб-сокетами на бекенд-сервере. + +Либо вы можете сделать какой-либо другой способ взаимодействия с веб-сокетами. + +--- + +Но для этого примера мы воспользуемся очень простым HTML документом с небольшими вставками JavaScript кода. + +Конечно же это неоптимально, и на практике так делать не стоит. + +В реальных приложениях стоит воспользоваться одним из вышеупомянутых способов. + +Для примера нам нужен наиболее простой способ, который позволит сосредоточиться на серверной части веб-сокетов и получить рабочий код: + +{* ../../docs_src/websockets/tutorial001.py hl[2,6:38,41:43] *} + +## Создание `websocket` + +Создайте `websocket` в своем **FastAPI** приложении: + +{* ../../docs_src/websockets/tutorial001.py hl[1,46:47] *} + +/// note | Технические детали + +Вы также можете использовать `from starlette.websockets import WebSocket`. + +**FastAPI** напрямую предоставляет тот же самый `WebSocket` просто для удобства. На самом деле это `WebSocket` из Starlette. + +/// + +## Ожидание и отправка сообщений + +Через эндпоинт веб-сокета вы можете получать и отправлять сообщения. + +{* ../../docs_src/websockets/tutorial001.py hl[48:52] *} + +Вы можете получать и отправлять двоичные, текстовые и JSON данные. + +## Проверка в действии + +Если ваш файл называется `main.py`, то запустите приложение командой: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Откройте браузер по адресу http://127.0.0.1:8000. + +Вы увидите следующую простенькую страницу: + + + +Вы можете набирать сообщения в поле ввода и отправлять их: + + + +И ваше **FastAPI** приложение с веб-сокетами ответит: + + + +Вы можете отправлять и получать множество сообщений: + + + +И все они будут использовать одно и то же веб-сокет соединение. + +## Использование `Depends` и не только + +Вы можете импортировать из `fastapi` и использовать в эндпоинте вебсокета: + +* `Depends` +* `Security` +* `Cookie` +* `Header` +* `Path` +* `Query` + +Они работают так же, как и в других FastAPI эндпоинтах/*операциях пути*: + +{* ../../docs_src/websockets/tutorial002_an_py310.py hl[68:69,82] *} + +/// info | Примечание + +В веб-сокете вызывать `HTTPException` не имеет смысла. Вместо этого нужно использовать `WebSocketException`. + +Закрывающий статус код можно использовать из valid codes defined in the specification. + +/// + +### Веб-сокеты с зависимостями: проверка в действии + +Если ваш файл называется `main.py`, то запустите приложение командой: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Откройте браузер по адресу http://127.0.0.1:8000. + +Там вы можете задать: + +* "Item ID", используемый в пути. +* "Token", используемый как query-параметр. + +/// tip | Подсказка + +Обратите внимание, что query-параметр `token` будет обработан в зависимости. + +/// + +Теперь вы можете подключиться к веб-сокету и начинать отправку и получение сообщений: + + + +## Обработка отключений и работа с несколькими клиентами + +Если веб-сокет соединение закрыто, то `await websocket.receive_text()` вызовет исключение `WebSocketDisconnect`, которое можно поймать и обработать как в этом примере: + +{* ../../docs_src/websockets/tutorial003_py39.py hl[79:81] *} + +Чтобы воспроизвести пример: + +* Откройте приложение в нескольких вкладках браузера. +* Отправьте из них сообщения. +* Затем закройте одну из вкладок. + +Это вызовет исключение `WebSocketDisconnect`, и все остальные клиенты получат следующее сообщение: + +``` +Client #1596980209979 left the chat +``` + +/// tip | Примечание + +Приложение выше - это всего лишь простой минимальный пример, демонстрирующий обработку и передачу сообщений нескольким веб-сокет соединениям. + +Но имейте в виду, что это будет работать только в одном процессе и только пока он активен, так как всё обрабатывается в простом списке в оперативной памяти. + +Если нужно что-то легко интегрируемое с FastAPI, но более надежное и с поддержкой Redis, PostgreSQL или другого, то можно воспользоваться encode/broadcaster. + +/// + +## Дополнительная информация + +Для более глубокого изучения темы воспользуйтесь документацией Starlette: + +* The `WebSocket` class. +* Class-based WebSocket handling. diff --git a/docs/ru/docs/alternatives.md b/docs/ru/docs/alternatives.md index 9e3c497d1..3c5147e79 100644 --- a/docs/ru/docs/alternatives.md +++ b/docs/ru/docs/alternatives.md @@ -33,12 +33,18 @@ DRF использовался многими компаниями, включа Это был один из первых примеров **автоматического документирования API** и это была одна из первых идей, вдохновивших на создание **FastAPI**. -!!! note "Заметка" - Django REST Framework был создан Tom Christie. - Он же создал Starlette и Uvicorn, на которых основан **FastAPI**. +/// note | Заметка -!!! check "Идея для **FastAPI**" - Должно быть автоматическое создание документации API с пользовательским веб-интерфейсом. +Django REST Framework был создан Tom Christie. +Он же создал Starlette и Uvicorn, на которых основан **FastAPI**. + +/// + +/// check | Идея для **FastAPI** + +Должно быть автоматическое создание документации API с пользовательским веб-интерфейсом. + +/// ### Flask @@ -56,11 +62,13 @@ Flask часто используется и для приложений, кот Простота Flask, показалась мне подходящей для создания API. Но ещё нужно было найти "Django REST Framework" для Flask. -!!! check "Идеи для **FastAPI**" - Это будет микрофреймворк. К нему легко будет добавить необходимые инструменты и части. +/// check | Идеи для **FastAPI** + +Это будет микрофреймворк. К нему легко будет добавить необходимые инструменты и части. - Должна быть простая и лёгкая в использовании система маршрутизации запросов. +Должна быть простая и лёгкая в использовании система маршрутизации запросов. +/// ### Requests @@ -100,11 +108,13 @@ def read_url(): Глядите, как похоже `requests.get(...)` и `@app.get(...)`. -!!! check "Идеи для **FastAPI**" - * Должен быть простой и понятный API. - * Нужно использовать названия HTTP-методов (операций) для упрощения понимания происходящего. - * Должны быть разумные настройки по умолчанию и широкие возможности их кастомизации. +/// check | Идеи для **FastAPI** + +* Должен быть простой и понятный API. +* Нужно использовать названия HTTP-методов (операций) для упрощения понимания происходящего. +* Должны быть разумные настройки по умолчанию и широкие возможности их кастомизации. +/// ### Swagger / OpenAPI @@ -119,16 +129,19 @@ def read_url(): Вот почему, когда говорят о версии 2.0, обычно говорят "Swagger", а для версии 3+ "OpenAPI". -!!! check "Идеи для **FastAPI**" - Использовать открытые стандарты для спецификаций API вместо самодельных схем. +/// check | Идеи для **FastAPI** - Совместимость с основанными на стандартах пользовательскими интерфейсами: +Использовать открытые стандарты для спецификаций API вместо самодельных схем. - * Swagger UI - * ReDoc +Совместимость с основанными на стандартах пользовательскими интерфейсами: - Они были выбраны за популярность и стабильность. - Но сделав беглый поиск, Вы можете найти десятки альтернативных пользовательских интерфейсов для OpenAPI, которые Вы можете использовать с **FastAPI**. +* Swagger UI +* ReDoc + +Они были выбраны за популярность и стабильность. +Но сделав беглый поиск, Вы можете найти десятки альтернативных пользовательских интерфейсов для OpenAPI, которые Вы можете использовать с **FastAPI**. + +/// ### REST фреймворки для Flask @@ -152,8 +165,11 @@ def read_url(): Итак, чтобы определить каждую схему, Вам нужно использовать определенные утилиты и классы, предоставляемые Marshmallow. -!!! check "Идея для **FastAPI**" - Использовать код программы для автоматического создания "схем", определяющих типы данных и их проверку. +/// check | Идея для **FastAPI** + +Использовать код программы для автоматического создания "схем", определяющих типы данных и их проверку. + +/// ### Webargs @@ -165,11 +181,17 @@ Webargs - это инструмент, который был создан для Это превосходный инструмент и я тоже часто пользовался им до **FastAPI**. -!!! info "Информация" - Webargs бы создан разработчиками Marshmallow. +/// info | Информация + +Webargs бы создан разработчиками Marshmallow. + +/// -!!! check "Идея для **FastAPI**" - Должна быть автоматическая проверка входных данных. +/// check | Идея для **FastAPI** + +Должна быть автоматическая проверка входных данных. + +/// ### APISpec @@ -190,11 +212,17 @@ Marshmallow и Webargs осуществляют проверку, анализ Редактор кода не особо может помочь в такой парадигме. А изменив какие-то параметры или схемы для Marshmallow можно забыть отредактировать докстринг с YAML и сгенерированная схема становится недействительной. -!!! info "Информация" - APISpec тоже был создан авторами Marshmallow. +/// info | Информация + +APISpec тоже был создан авторами Marshmallow. + +/// + +/// check | Идея для **FastAPI** + +Необходима поддержка открытого стандарта для API - OpenAPI. -!!! check "Идея для **FastAPI**" - Необходима поддержка открытого стандарта для API - OpenAPI. +/// ### Flask-apispec @@ -218,11 +246,17 @@ Marshmallow и Webargs осуществляют проверку, анализ Эти генераторы проектов также стали основой для [Генераторов проектов с **FastAPI**](project-generation.md){.internal-link target=_blank}. -!!! info "Информация" - Как ни странно, но Flask-apispec тоже создан авторами Marshmallow. +/// info | Информация -!!! check "Идея для **FastAPI**" - Схема OpenAPI должна создаваться автоматически и использовать тот же код, который осуществляет сериализацию и проверку данных. +Как ни странно, но Flask-apispec тоже создан авторами Marshmallow. + +/// + +/// check | Идея для **FastAPI** + +Схема OpenAPI должна создаваться автоматически и использовать тот же код, который осуществляет сериализацию и проверку данных. + +/// ### NestJSAngular) @@ -242,25 +276,34 @@ Marshmallow и Webargs осуществляют проверку, анализ Кроме того, он не очень хорошо справляется с вложенными моделями. Если в запросе имеется объект JSON, внутренние поля которого, в свою очередь, являются вложенными объектами JSON, это не может быть должным образом задокументировано и проверено. -!!! check "Идеи для **FastAPI** " - Нужно использовать подсказки типов, чтоб воспользоваться поддержкой редактора кода. +/// check | Идеи для **FastAPI** + +Нужно использовать подсказки типов, чтоб воспользоваться поддержкой редактора кода. + +Нужна мощная система внедрения зависимостей. Необходим способ для уменьшения повторов кода. - Нужна мощная система внедрения зависимостей. Необходим способ для уменьшения повторов кода. +/// ### Sanic Sanic был одним из первых чрезвычайно быстрых Python-фреймворков основанных на `asyncio`. Он был сделан очень похожим на Flask. -!!! note "Технические детали" - В нём использован `uvloop` вместо стандартного цикла событий `asyncio`, что и сделало его таким быстрым. +/// note | Технические детали - Он явно вдохновил создателей Uvicorn и Starlette, которые в настоящее время быстрее Sanic в открытых бенчмарках. +В нём использован `uvloop` вместо стандартного цикла событий `asyncio`, что и сделало его таким быстрым. -!!! check "Идеи для **FastAPI**" - Должна быть сумасшедшая производительность. +Он явно вдохновил создателей Uvicorn и Starlette, которые в настоящее время быстрее Sanic в открытых бенчмарках. - Для этого **FastAPI** основан на Starlette, самом быстром из доступных фреймворков (по замерам незаинтересованных лиц). +/// + +/// check | Идеи для **FastAPI** + +Должна быть сумасшедшая производительность. + +Для этого **FastAPI** основан на Starlette, самом быстром из доступных фреймворков (по замерам незаинтересованных лиц). + +/// ### Falcon @@ -275,12 +318,15 @@ Falcon - ещё один высокопроизводительный Python-ф Либо эти функции должны быть встроены во фреймворк, сконструированный поверх Falcon, как в Hug. Такая же особенность присутствует и в других фреймворках, вдохновлённых идеей Falcon, использовать только один объект запроса и один объект ответа. -!!! check "Идея для **FastAPI**" - Найдите способы добиться отличной производительности. +/// check | Идея для **FastAPI** + +Найдите способы добиться отличной производительности. + +Объявлять параметры `ответа сервера` в функциях, как в Hug. - Объявлять параметры `ответа сервера` в функциях, как в Hug. +Хотя в FastAPI это необязательно и используется в основном для установки заголовков, куки и альтернативных кодов состояния. - Хотя в FastAPI это необязательно и используется в основном для установки заголовков, куки и альтернативных кодов состояния. +/// ### Molten @@ -302,13 +348,16 @@ Molten мне попался на начальной стадии написан Это больше похоже на Django, чем на Flask и Starlette. Он разделяет в коде вещи, которые довольно тесно связаны. -!!! check "Идея для **FastAPI**" - Определить дополнительные проверки типов данных, используя значения атрибутов модели "по умолчанию". - Это улучшает помощь редактора и раньше это не было доступно в Pydantic. +/// check | Идея для **FastAPI** - Фактически это подтолкнуло на обновление Pydantic для поддержки одинакового стиля проверок (теперь этот функционал уже доступен в Pydantic). +Определить дополнительные проверки типов данных, используя значения атрибутов модели "по умолчанию". +Это улучшает помощь редактора и раньше это не было доступно в Pydantic. -### Hug +Фактически это подтолкнуло на обновление Pydantic для поддержки одинакового стиля проверок (теперь этот функционал уже доступен в Pydantic). + +/// + +### Hug Hug был одним из первых фреймворков, реализовавших объявление параметров API с использованием подсказок типов Python. Эта отличная идея была использована и другими инструментами. @@ -325,15 +374,21 @@ Hug был одним из первых фреймворков, реализов Поскольку он основан на WSGI, старом стандарте для синхронных веб-фреймворков, он не может работать с веб-сокетами и другими модными штуками, но всё равно обладает высокой производительностью. -!!! info "Информация" - Hug создан Timothy Crosley, автором `isort`, отличного инструмента для автоматической сортировки импортов в Python-файлах. +/// info | Информация + +Hug создан Timothy Crosley, автором `isort`, отличного инструмента для автоматической сортировки импортов в Python-файлах. + +/// + +/// check | Идеи для **FastAPI** + +Hug повлиял на создание некоторых частей APIStar и был одним из инструментов, которые я счел наиболее многообещающими, наряду с APIStar. -!!! check "Идеи для **FastAPI**" - Hug повлиял на создание некоторых частей APIStar и был одним из инструментов, которые я счел наиболее многообещающими, наряду с APIStar. +Hug натолкнул на мысли использовать в **FastAPI** подсказки типов Python для автоматического создания схемы, определяющей API и его параметры. - Hug натолкнул на мысли использовать в **FastAPI** подсказки типов Python для автоматического создания схемы, определяющей API и его параметры. +Hug вдохновил **FastAPI** объявить параметр `ответа` в функциях для установки заголовков и куки. - Hug вдохновил **FastAPI** объявить параметр `ответа` в функциях для установки заголовков и куки. +/// ### APIStar (<= 0.5) @@ -363,38 +418,47 @@ Hug был одним из первых фреймворков, реализов Ныне APIStar - это набор инструментов для проверки спецификаций OpenAPI. -!!! info "Информация" - APIStar был создан Tom Christie. Тот самый парень, который создал: +/// info | Информация - * Django REST Framework - * Starlette (на котором основан **FastAPI**) - * Uvicorn (используемый в Starlette и **FastAPI**) +APIStar был создан Tom Christie. Тот самый парень, который создал: -!!! check "Идеи для **FastAPI**" - Воплощение. +* Django REST Framework +* Starlette (на котором основан **FastAPI**) +* Uvicorn (используемый в Starlette и **FastAPI**) - Мне казалось блестящей идеей объявлять множество функций (проверка данных, сериализация, документация) с помощью одних и тех же типов Python, которые при этом обеспечивают ещё и помощь редактора кода. +/// - После долгих поисков среди похожих друг на друга фреймворков и сравнения их различий, APIStar стал самым лучшим выбором. +/// check | Идеи для **FastAPI** - Но APIStar перестал быть фреймворком для создания веб-сервера, зато появился Starlette, новая и лучшая основа для построения подобных систем. - Это была последняя капля, сподвигнувшая на создание **FastAPI**. +Воплощение. - Я считаю **FastAPI** "духовным преемником" APIStar, улучившим его возможности благодаря урокам, извлечённым из всех упомянутых выше инструментов. +Мне казалось блестящей идеей объявлять множество функций (проверка данных, сериализация, документация) с помощью одних и тех же типов Python, которые при этом обеспечивают ещё и помощь редактора кода. + +После долгих поисков среди похожих друг на друга фреймворков и сравнения их различий, APIStar стал самым лучшим выбором. + +Но APIStar перестал быть фреймворком для создания веб-сервера, зато появился Starlette, новая и лучшая основа для построения подобных систем. +Это была последняя капля, сподвигнувшая на создание **FastAPI**. + +Я считаю **FastAPI** "духовным преемником" APIStar, улучившим его возможности благодаря урокам, извлечённым из всех упомянутых выше инструментов. + +/// ## Что используется в **FastAPI** -### Pydantic +### Pydantic Pydantic - это библиотека для валидации данных, сериализации и документирования (используя JSON Schema), основываясь на подсказках типов Python, что делает его чрезвычайно интуитивным. Его можно сравнить с Marshmallow, хотя в бенчмарках Pydantic быстрее, чем Marshmallow. И он основан на тех же подсказках типов, которые отлично поддерживаются редакторами кода. -!!! check "**FastAPI** использует Pydantic" - Для проверки данных, сериализации данных и автоматической документации моделей (на основе JSON Schema). +/// check | **FastAPI** использует Pydantic + +Для проверки данных, сериализации данных и автоматической документации моделей (на основе JSON Schema). + +Затем **FastAPI** берёт эти схемы JSON и помещает их в схему OpenAPI, не касаясь других вещей, которые он делает. - Затем **FastAPI** берёт эти схемы JSON и помещает их в схему OpenAPI, не касаясь других вещей, которые он делает. +/// ### Starlette @@ -424,19 +488,25 @@ Starlette обеспечивает весь функционал микрофр **FastAPI** добавляет эти функции используя подсказки типов Python и Pydantic. Ещё **FastAPI** добавляет систему внедрения зависимостей, утилиты безопасности, генерацию схемы OpenAPI и т.д. -!!! note "Технические детали" - ASGI - это новый "стандарт" разработанный участниками команды Django. - Он пока что не является "стандартом в Python" (то есть принятым PEP), но процесс принятия запущен. +/// note | Технические детали - Тем не менее он уже используется в качестве "стандарта" несколькими инструментами. - Это значительно улучшает совместимость, поскольку Вы можете переключиться с Uvicorn на любой другой ASGI-сервер (например, Daphne или Hypercorn) или Вы можете добавить ASGI-совместимые инструменты, такие как `python-socketio`. +ASGI - это новый "стандарт" разработанный участниками команды Django. +Он пока что не является "стандартом в Python" (то есть принятым PEP), но процесс принятия запущен. -!!! check "**FastAPI** использует Starlette" - В качестве ядра веб-сервиса для обработки запросов, добавив некоторые функции сверху. +Тем не менее он уже используется в качестве "стандарта" несколькими инструментами. +Это значительно улучшает совместимость, поскольку Вы можете переключиться с Uvicorn на любой другой ASGI-сервер (например, Daphne или Hypercorn) или Вы можете добавить ASGI-совместимые инструменты, такие как `python-socketio`. - Класс `FastAPI` наследуется напрямую от класса `Starlette`. +/// - Таким образом, всё что Вы могли делать со Starlette, Вы можете делать с **FastAPI**, по сути это прокачанный Starlette. +/// check | **FastAPI** использует Starlette + +В качестве ядра веб-сервиса для обработки запросов, добавив некоторые функции сверху. + +Класс `FastAPI` наследуется напрямую от класса `Starlette`. + +Таким образом, всё что Вы могли делать со Starlette, Вы можете делать с **FastAPI**, по сути это прокачанный Starlette. + +/// ### Uvicorn @@ -448,12 +518,15 @@ Uvicorn является сервером, а не фреймворком. Он рекомендуется в качестве сервера для Starlette и **FastAPI**. -!!! check "**FastAPI** рекомендует его" - Как основной сервер для запуска приложения **FastAPI**. +/// check | **FastAPI** рекомендует его + +Как основной сервер для запуска приложения **FastAPI**. + +Вы можете объединить его с Gunicorn, чтобы иметь асинхронный многопроцессный сервер. - Вы можете объединить его с Gunicorn, чтобы иметь асинхронный многопроцессный сервер. +Узнать больше деталей можно в разделе [Развёртывание](deployment/index.md){.internal-link target=_blank}. - Узнать больше деталей можно в разделе [Развёртывание](deployment/index.md){.internal-link target=_blank}. +/// ## Тестовые замеры и скорость diff --git a/docs/ru/docs/async.md b/docs/ru/docs/async.md index 4c44fc22d..6c5d982df 100644 --- a/docs/ru/docs/async.md +++ b/docs/ru/docs/async.md @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! note - `await` можно использовать только внутри функций, объявленных с использованием `async def`. +/// note + +`await` можно использовать только внутри функций, объявленных с использованием `async def`. + +/// --- @@ -444,14 +447,17 @@ Starlette (и **FastAPI**) основаны на -Но в любом случае велика вероятность, что **FastAPI** [окажется быстрее](/#performance){.internal-link target=_blank} +Но в любом случае велика вероятность, что **FastAPI** [окажется быстрее](index.md#_11){.internal-link target=_blank} другого фреймворка (или хотя бы на уровне с ним). ### Зависимости @@ -502,4 +508,4 @@ Starlette (и **FastAPI**) основаны на Нет времени?. +В противном случае просто ознакомьтесь с основными принципами в разделе выше: Нет времени?. diff --git a/docs/ru/docs/contributing.md b/docs/ru/docs/contributing.md deleted file mode 100644 index f9b8912e5..000000000 --- a/docs/ru/docs/contributing.md +++ /dev/null @@ -1,469 +0,0 @@ -# Участие в разработке фреймворка - -Возможно, для начала Вам стоит ознакомиться с основными способами [помочь FastAPI или получить помощь](help-fastapi.md){.internal-link target=_blank}. - -## Разработка - -Если Вы уже склонировали репозиторий и знаете, что Вам нужно более глубокое погружение в код фреймворка, то здесь представлены некоторые инструкции по настройке виртуального окружения. - -### Виртуальное окружение с помощью `venv` - -Находясь в нужной директории, Вы можете создать виртуальное окружение при помощи Python модуля `venv`. - -
- -```console -$ python -m venv env -``` - -
- -Эта команда создаст директорию `./env/` с бинарными (двоичными) файлами Python, а затем Вы сможете скачивать и устанавливать необходимые библиотеки в изолированное виртуальное окружение. - -### Активация виртуального окружения - -Активируйте виртуально окружение командой: - -=== "Linux, macOS" - -
- - ```console - $ source ./env/bin/activate - ``` - -
- -=== "Windows PowerShell" - -
- - ```console - $ .\env\Scripts\Activate.ps1 - ``` - -
- -=== "Windows Bash" - - Если Вы пользуетесь Bash для Windows (например: Git Bash): - -
- - ```console - $ source ./env/Scripts/activate - ``` - -
- -Проверьте, что всё сработало: - -=== "Linux, macOS, Windows Bash" - -
- - ```console - $ which pip - - some/directory/fastapi/env/bin/pip - ``` - -
- -=== "Windows PowerShell" - -
- - ```console - $ Get-Command pip - - some/directory/fastapi/env/bin/pip - ``` - -
- -Если в терминале появится ответ, что бинарник `pip` расположен по пути `.../env/bin/pip`, значит всё в порядке. 🎉 - -Во избежание ошибок в дальнейших шагах, удостоверьтесь, что в Вашем виртуальном окружении установлена последняя версия `pip`: - -
- -```console -$ python -m pip install --upgrade pip - ----> 100% -``` - -
- -!!! tip "Подсказка" - Каждый раз, перед установкой новой библиотеки в виртуальное окружение при помощи `pip`, не забудьте активировать это виртуальное окружение. - - Это гарантирует, что если Вы используете библиотеку, установленную этим пакетом, то Вы используете библиотеку из Вашего локального окружения, а не любую другую, которая может быть установлена глобально. - -### pip - -После активации виртуального окружения, как было указано ранее, введите следующую команду: - -
- -```console -$ pip install -r requirements.txt - ----> 100% -``` - -
- -Это установит все необходимые зависимости в локальное окружение для Вашего локального FastAPI. - -#### Использование локального FastAPI - -Если Вы создаёте Python файл, который импортирует и использует FastAPI,а затем запускаете его интерпретатором Python из Вашего локального окружения, то он будет использовать код из локального FastAPI. - -И, так как при вводе вышеупомянутой команды был указан флаг `-e`, если Вы измените код локального FastAPI, то при следующем запуске этого файла, он будет использовать свежую версию локального FastAPI, который Вы только что изменили. - -Таким образом, Вам не нужно "переустанавливать" Вашу локальную версию, чтобы протестировать каждое изменение. - -### Форматировние - -Скачанный репозиторий содержит скрипт, который может отформатировать и подчистить Ваш код: - -
- -```console -$ bash scripts/format.sh -``` - -
- -Заодно он упорядочит Ваши импорты. - -Чтобы он сортировал их правильно, необходимо, чтобы FastAPI был установлен локально в Вашей среде, с помощью команды из раздела выше, использующей флаг `-e`. - -## Документация - -Прежде всего, убедитесь, что Вы настроили своё окружение, как описано выше, для установки всех зависимостей. - -Документация использует MkDocs. - -Также существуют дополнительные инструменты/скрипты для работы с переводами в `./scripts/docs.py`. - -!!! tip "Подсказка" - - Нет необходимости заглядывать в `./scripts/docs.py`, просто используйте это в командной строке. - -Вся документация имеет формат Markdown и расположена в директории `./docs/en/`. - -Многие руководства содержат блоки кода. - -В большинстве случаев эти блоки кода представляют собой вполне законченные приложения, которые можно запускать как есть. - -На самом деле, эти блоки кода не написаны внутри Markdown, это Python файлы в директории `./docs_src/`. - -И эти Python файлы включаются/вводятся в документацию при создании сайта. - -### Тестирование документации - - -Фактически, большинство тестов запускаются с примерами исходных файлов в документации. - -Это помогает убедиться, что: - -* Документация находится в актуальном состоянии. -* Примеры из документации могут быть запущены как есть. -* Большинство функций описаны в документации и покрыты тестами. - -Существует скрипт, который во время локальной разработки создаёт сайт и проверяет наличие любых изменений, перезагружая его в реальном времени: - -
- -```console -$ python ./scripts/docs.py live - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -Он запустит сайт документации по адресу: `http://127.0.0.1:8008`. - - -Таким образом, Вы сможете редактировать файлы с документацией или кодом и наблюдать изменения вживую. - -#### Typer CLI (опционально) - - -Приведенная ранее инструкция показала Вам, как запускать скрипт `./scripts/docs.py` непосредственно через интерпретатор `python` . - -Но также можно использовать Typer CLI, что позволит Вам воспользоваться автозаполнением команд в Вашем терминале. - -Если Вы установили Typer CLI, то для включения функции автозаполнения, введите эту команду: - -
- -```console -$ typer --install-completion - -zsh completion installed in /home/user/.bashrc. -Completion will take effect once you restart the terminal. -``` - -
- -### Приложения и документация одновременно - -Если Вы запускаете приложение, например так: - -
- -```console -$ uvicorn tutorial001:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -По умолчанию Uvicorn будет использовать порт `8000` и не будет конфликтовать с сайтом документации, использующим порт `8008`. - -### Переводы на другие языки - -Помощь с переводами ценится КРАЙНЕ ВЫСОКО! И переводы не могут быть сделаны без помощи сообщества. 🌎 🚀 - -Ниже приведены шаги, как помочь с переводами. - -#### Подсказки и инструкции - -* Проверьте существующие пул-реквесты для Вашего языка. Добавьте отзывы с просьбой внести изменения, если они необходимы, или одобрите их. - -!!! tip "Подсказка" - Вы можете добавлять комментарии с предложениями по изменению в существующие пул-реквесты. - - Ознакомьтесь с документацией о добавлении отзыва к пул-реквесту, чтобы утвердить его или запросить изменения. - -* Проверьте проблемы и вопросы, чтобы узнать, есть ли кто-то, координирующий переводы для Вашего языка. - -* Добавляйте один пул-реквест для каждой отдельной переведённой страницы. Это значительно облегчит другим его просмотр. - -Для языков, которые я не знаю, прежде чем добавить перевод в основную ветку, я подожду пока несколько других участников сообщества проверят его. - -* Вы также можете проверить, есть ли переводы для Вашего языка и добавить к ним отзыв, который поможет мне убедиться в правильности перевода. Тогда я смогу объединить его с основной веткой. - -* Используйте те же самые примеры кода Python. Переводите только текст документации. Вам не нужно ничего менять, чтобы эти примеры работали. - -* Используйте те же самые изображения, имена файлов и ссылки. Вы не должны менять ничего для сохранения работоспособности. - -* Чтобы узнать 2-буквенный код языка, на который Вы хотите сделать перевод, Вы можете воспользоваться таблицей Список кодов языков ISO 639-1. - -#### Существующий язык - -Допустим, Вы хотите перевести страницу на язык, на котором уже есть какие-то переводы, например, на испанский. - -Кодом испанского языка является `es`. А значит директория для переводов на испанский язык: `docs/es/`. - -!!! tip "Подсказка" - Главный ("официальный") язык - английский, директория для него `docs/en/`. - -Вы можете запустить сервер документации на испанском: - -
- -```console -// Используйте команду "live" и передайте код языка в качестве аргумента командной строки -$ python ./scripts/docs.py live es - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -Теперь Вы можете перейти по адресу: http://127.0.0.1:8008 и наблюдать вносимые Вами изменения вживую. - - -Если Вы посмотрите на сайт документации FastAPI, то увидите, что все страницы есть на каждом языке. Но некоторые страницы не переведены и имеют уведомление об отсутствующем переводе. - -Но когда Вы запускаете сайт локально, Вы видите только те страницы, которые уже переведены. - - -Предположим, что Вы хотите добавить перевод страницы [Основные свойства](features.md){.internal-link target=_blank}. - -* Скопируйте файл: - -``` -docs/en/docs/features.md -``` - -* Вставьте его точно в то же место, но в директорию языка, на который Вы хотите сделать перевод, например: - -``` -docs/es/docs/features.md -``` - -!!! tip "Подсказка" - Заметьте, что в пути файла мы изменили только код языка с `en` на `es`. - -* Теперь откройте файл конфигурации MkDocs для английского языка, расположенный тут: - -``` -docs/en/mkdocs.yml -``` - -* Найдите в файле конфигурации место, где расположена строка `docs/features.md`. Похожее на это: - -```YAML hl_lines="8" -site_name: FastAPI -# More stuff -nav: -- FastAPI: index.md -- Languages: - - en: / - - es: /es/ -- features.md -``` - -* Откройте файл конфигурации MkDocs для языка, на который Вы переводите, например: - -``` -docs/es/mkdocs.yml -``` - -* Добавьте строку `docs/features.md` точно в то же место, как и в случае для английского, как-то так: - -```YAML hl_lines="8" -site_name: FastAPI -# More stuff -nav: -- FastAPI: index.md -- Languages: - - en: / - - es: /es/ -- features.md -``` - -Убедитесь, что при наличии других записей, новая запись с Вашим переводом находится точно в том же порядке, что и в английской версии. - -Если Вы зайдёте в свой браузер, то увидите, что в документации стал отображаться Ваш новый раздел.🎉 - -Теперь Вы можете переводить эту страницу и смотреть, как она выглядит при сохранении файла. - -#### Новый язык - -Допустим, Вы хотите добавить перевод для языка, на который пока что не переведена ни одна страница. - -Скажем, Вы решили сделать перевод для креольского языка, но его еще нет в документации. - -Перейдите в таблицу кодов языков по ссылке указанной выше, где найдёте, что кодом креольского языка является `ht`. - -Затем запустите скрипт, генерирующий директорию для переводов на новые языки: - -
- -```console -// Используйте команду new-lang и передайте код языка в качестве аргумента командной строки -$ python ./scripts/docs.py new-lang ht - -Successfully initialized: docs/ht -Updating ht -Updating en -``` - -
- -После чего Вы можете проверить в своем редакторе кода, что появился новый каталог `docs/ht/`. - -!!! tip "Подсказка" - Создайте первый пул-реквест, который будет содержать только пустую директорию для нового языка, прежде чем добавлять переводы. - - Таким образом, другие участники могут переводить другие страницы, пока Вы работаете над одной. 🚀 - -Начните перевод с главной страницы `docs/ht/index.md`. - -В дальнейшем можно действовать, как указано в предыдущих инструкциях для "существующего языка". - -##### Новый язык не поддерживается - -Если при запуске скрипта `./scripts/docs.py live` Вы получаете сообщение об ошибке, что язык не поддерживается, что-то вроде: - -``` - raise TemplateNotFound(template) -jinja2.exceptions.TemplateNotFound: partials/language/xx.html -``` - -Сие означает, что тема не поддерживает этот язык (в данном случае с поддельным 2-буквенным кодом `xx`). - -Но не стоит переживать. Вы можете установить языком темы английский, а затем перевести текст документации. - -Если возникла такая необходимость, отредактируйте `mkdocs.yml` для Вашего нового языка. Это будет выглядеть как-то так: - -```YAML hl_lines="5" -site_name: FastAPI -# More stuff -theme: - # More stuff - language: xx -``` - -Измените `xx` (код Вашего языка) на `en` и перезапустите сервер. - -#### Предпросмотр результата - -Когда Вы запускаете скрипт `./scripts/docs.py` с командой `live`, то будут показаны файлы и переводы для указанного языка. - -Но когда Вы закончите, то можете посмотреть, как это будет выглядеть по-настоящему. - -Для этого сначала создайте всю документацию: - -
- -```console -// Используйте команду "build-all", это займёт немного времени -$ python ./scripts/docs.py build-all - -Updating es -Updating en -Building docs for: en -Building docs for: es -Successfully built docs for: es -Copying en index.md to README.md -``` - -
- -Скрипт сгенерирует `./docs_build/` для каждого языка. Он добавит все файлы с отсутствующими переводами с пометкой о том, что "у этого файла еще нет перевода". Но Вам не нужно ничего делать с этим каталогом. - -Затем он создаст независимые сайты MkDocs для каждого языка, объединит их и сгенерирует конечный результат на `./site/`. - -После чего Вы сможете запустить сервер со всеми языками командой `serve`: - -
- -```console -// Используйте команду "serve" после того, как отработает команда "build-all" -$ python ./scripts/docs.py serve - -Warning: this is a very simple server. For development, use mkdocs serve instead. -This is here only to preview a site with translations already built. -Make sure you run the build-all command first. -Serving at: http://127.0.0.1:8008 -``` - -
- -## Тесты - -Также в репозитории есть скрипт, который Вы можете запустить локально, чтобы протестировать весь код и сгенерировать отчеты о покрытии тестами в HTML: - -
- -```console -$ bash scripts/test-cov-html.sh -``` - -
- -Эта команда создаст директорию `./htmlcov/`, в которой будет файл `./htmlcov/index.html`. Открыв его в Вашем браузере, Вы можете в интерактивном режиме изучить, все ли части кода охвачены тестами. diff --git a/docs/ru/docs/deployment/concepts.md b/docs/ru/docs/deployment/concepts.md index 681acf15e..7cdc29526 100644 --- a/docs/ru/docs/deployment/concepts.md +++ b/docs/ru/docs/deployment/concepts.md @@ -1,6 +1,6 @@ # Концепции развёртывания -Существует несколько концепций, применяемых для развёртывания приложений **FastAPI**, равно как и для любых других типов веб-приложений, среди которых Вы можете выбрать **наиболее подходящий** способ. +Существует несколько концепций, применяемых для развёртывания приложений **FastAPI**, равно как и для любых других типов веб-приложений, среди которых вы можете выбрать **наиболее подходящий** способ. Самые важные из них: @@ -13,11 +13,11 @@ Рассмотрим ниже влияние каждого из них на процесс **развёртывания**. -Наша конечная цель - **обслуживать клиентов Вашего API безопасно** и **бесперебойно**, с максимально эффективным использованием **вычислительных ресурсов** (например, удалённых серверов/виртуальных машин). 🚀 +Наша конечная цель - **обслуживать клиентов вашего API безопасно** и **бесперебойно**, с максимально эффективным использованием **вычислительных ресурсов** (например, удалённых серверов/виртуальных машин). 🚀 -Здесь я немного расскажу Вам об этих **концепциях** и надеюсь, что у Вас сложится **интуитивное понимание**, какой способ выбрать при развертывании Вашего API в различных окружениях, возможно, даже **ещё не существующих**. +Здесь я немного расскажу Вам об этих **концепциях** и надеюсь, что у вас сложится **интуитивное понимание**, какой способ выбрать при развертывании вашего API в различных окружениях, возможно, даже **ещё не существующих**. -Ознакомившись с этими концепциями, Вы сможете **оценить и выбрать** лучший способ развёртывании **Вашего API**. +Ознакомившись с этими концепциями, вы сможете **оценить и выбрать** лучший способ развёртывании **Вашего API**. В последующих главах я предоставлю Вам **конкретные рецепты** развёртывания приложения FastAPI. @@ -25,15 +25,15 @@ ## Использование более безопасного протокола HTTPS -В [предыдущей главе об HTTPS](./https.md){.internal-link target=_blank} мы рассмотрели, как HTTPS обеспечивает шифрование для Вашего API. +В [предыдущей главе об HTTPS](https.md){.internal-link target=_blank} мы рассмотрели, как HTTPS обеспечивает шифрование для вашего API. -Также мы заметили, что обычно для работы с HTTPS Вашему приложению нужен **дополнительный** компонент - **прокси-сервер завершения работы TLS**. +Также мы заметили, что обычно для работы с HTTPS вашему приложению нужен **дополнительный** компонент - **прокси-сервер завершения работы TLS**. И если прокси-сервер не умеет сам **обновлять сертификаты HTTPS**, то нужен ещё один компонент для этого действия. ### Примеры инструментов для работы с HTTPS -Вот некоторые инструменты, которые Вы можете применять как прокси-серверы: +Вот некоторые инструменты, которые вы можете применять как прокси-серверы: * Traefik * С автоматическим обновлением сертификатов ✨ @@ -47,7 +47,7 @@ * С дополнительным компонентом типа cert-manager для обновления сертификатов * Использование услуг облачного провайдера (читайте ниже 👇) -В последнем варианте Вы можете воспользоваться услугами **облачного сервиса**, который сделает большую часть работы, включая настройку HTTPS. Это может наложить дополнительные ограничения или потребовать дополнительную плату и т.п. Зато Вам не понадобится самостоятельно заниматься настройками прокси-сервера. +В последнем варианте вы можете воспользоваться услугами **облачного сервиса**, который сделает большую часть работы, включая настройку HTTPS. Это может наложить дополнительные ограничения или потребовать дополнительную плату и т.п. Зато Вам не понадобится самостоятельно заниматься настройками прокси-сервера. В дальнейшем я покажу Вам некоторые конкретные примеры их применения. @@ -63,7 +63,7 @@ Термином **программа** обычно описывают множество вещей: -* **Код**, который Вы написали, в нашем случае **Python-файлы**. +* **Код**, который вы написали, в нашем случае **Python-файлы**. * **Файл**, который может быть **исполнен** операционной системой, например `python`, `python.exe` или `uvicorn`. * Конкретная программа, **запущенная** операционной системой и использующая центральный процессор и память. В таком случае это также называется **процесс**. @@ -74,13 +74,13 @@ * Конкретная программа, **запущенная** операционной системой. * Это не имеет отношения к какому-либо файлу или коду, но нечто **определённое**, управляемое и **выполняемое** операционной системой. * Любая программа, любой код, **могут делать что-то** только когда они **выполняются**. То есть, когда являются **работающим процессом**. -* Процесс может быть **прерван** (или "убит") Вами или Вашей операционной системой. В результате чего он перестанет исполняться и **не будет продолжать делать что-либо**. -* Каждое приложение, которое Вы запустили на своём компьютере, каждая программа, каждое "окно" запускает какой-то процесс. И обычно на включенном компьютере **одновременно** запущено множество процессов. +* Процесс может быть **прерван** (или "убит") Вами или вашей операционной системой. В результате чего он перестанет исполняться и **не будет продолжать делать что-либо**. +* Каждое приложение, которое вы запустили на своём компьютере, каждая программа, каждое "окно" запускает какой-то процесс. И обычно на включенном компьютере **одновременно** запущено множество процессов. * И **одна программа** может запустить **несколько параллельных процессов**. -Если Вы заглянете в "диспетчер задач" или "системный монитор" (или аналогичные инструменты) Вашей операционной системы, то увидите множество работающих процессов. +Если вы заглянете в "диспетчер задач" или "системный монитор" (или аналогичные инструменты) вашей операционной системы, то увидите множество работающих процессов. -Вполне вероятно, что Вы увидите несколько процессов с одним и тем же названием браузерной программы (Firefox, Chrome, Edge и т. Д.). Обычно браузеры запускают один процесс на вкладку и вдобавок некоторые дополнительные процессы. +Вполне вероятно, что вы увидите несколько процессов с одним и тем же названием браузерной программы (Firefox, Chrome, Edge и т. Д.). Обычно браузеры запускают один процесс на вкладку и вдобавок некоторые дополнительные процессы. @@ -90,21 +90,21 @@ ## Настройки запуска приложения -В большинстве случаев когда Вы создаёте веб-приложение, то желаете, чтоб оно **работало постоянно** и непрерывно, предоставляя клиентам доступ в любое время. Хотя иногда у Вас могут быть причины, чтоб оно запускалось только при определённых условиях. +В большинстве случаев когда вы создаёте веб-приложение, то желаете, чтоб оно **работало постоянно** и непрерывно, предоставляя клиентам доступ в любое время. Хотя иногда у вас могут быть причины, чтоб оно запускалось только при определённых условиях. ### Удалённый сервер -Когда Вы настраиваете удалённый сервер (облачный сервер, виртуальную машину и т.п.), самое простое, что можно сделать, запустить Uvicorn (или его аналог) вручную, как Вы делаете при локальной разработке. +Когда вы настраиваете удалённый сервер (облачный сервер, виртуальную машину и т.п.), самое простое, что можно сделать, запустить Uvicorn (или его аналог) вручную, как вы делаете при локальной разработке. Это рабочий способ и он полезен **во время разработки**. -Но если Вы потеряете соединение с сервером, то не сможете отслеживать - работает ли всё ещё **запущенный Вами процесс**. +Но если вы потеряете соединение с сервером, то не сможете отслеживать - работает ли всё ещё **запущенный Вами процесс**. -И если сервер перезагрузится (например, после обновления или каких-то действий облачного провайдера), Вы скорее всего **этого не заметите**, чтобы снова запустить процесс вручную. Вследствие этого Ваш API останется мёртвым. 😱 +И если сервер перезагрузится (например, после обновления или каких-то действий облачного провайдера), вы скорее всего **этого не заметите**, чтобы снова запустить процесс вручную. Вследствие этого Ваш API останется мёртвым. 😱 ### Автоматический запуск программ -Вероятно Вы пожелаете, чтоб Ваша серверная программа (такая как Uvicorn) стартовала автоматически при включении сервера, без **человеческого вмешательства** и всегда могла управлять Вашим API (так как Uvicorn запускает приложение FastAPI). +Вероятно вы захотите, чтоб Ваша серверная программа (такая, как Uvicorn) стартовала автоматически при включении сервера, без **человеческого вмешательства** и всегда могла управлять Вашим API (так как Uvicorn запускает приложение FastAPI). ### Отдельная программа @@ -127,7 +127,7 @@ ## Перезапуск -Вы, вероятно, также пожелаете, чтоб Ваше приложение **перезапускалось**, если в нём произошёл сбой. +Вы, вероятно, также захотите, чтоб ваше приложение **перезапускалось**, если в нём произошёл сбой. ### Мы ошибаемся @@ -137,7 +137,7 @@ ### Небольшие ошибки обрабатываются автоматически -Когда Вы создаёте свои API на основе FastAPI и допускаете в коде ошибку, то FastAPI обычно остановит её распространение внутри одного запроса, при обработке которого она возникла. 🛡 +Когда вы создаёте свои API на основе FastAPI и допускаете в коде ошибку, то FastAPI обычно остановит её распространение внутри одного запроса, при обработке которого она возникла. 🛡 Клиент получит ошибку **500 Internal Server Error** в ответ на свой запрос, но приложение не сломается и будет продолжать работать с последующими запросами. @@ -151,12 +151,15 @@ Для случаев, когда ошибки приводят к сбою в запущенном **процессе**, Вам понадобится добавить компонент, который **перезапустит** процесс хотя бы пару раз... -!!! tip "Заметка" - ... Если приложение падает сразу же после запуска, вероятно бесполезно его бесконечно перезапускать. Но полагаю, Вы заметите такое поведение во время разработки или, по крайней мере, сразу после развёртывания. +/// tip | Заметка - Так что давайте сосредоточимся на конкретных случаях, когда приложение может полностью выйти из строя, но всё ещё есть смысл его запустить заново. +... Если приложение падает сразу же после запуска, вероятно бесполезно его бесконечно перезапускать. Но полагаю, вы заметите такое поведение во время разработки или, по крайней мере, сразу после развёртывания. -Возможно Вы захотите, чтоб был некий **внешний компонент**, ответственный за перезапуск Вашего приложения даже если уже не работает Uvicorn или Python. То есть ничего из того, что написано в Вашем коде внутри приложения, не может быть выполнено в принципе. +Так что давайте сосредоточимся на конкретных случаях, когда приложение может полностью выйти из строя, но всё ещё есть смысл его запустить заново. + +/// + +Возможно вы захотите, чтоб был некий **внешний компонент**, ответственный за перезапуск вашего приложения даже если уже не работает Uvicorn или Python. То есть ничего из того, что написано в вашем коде внутри приложения, не может быть выполнено в принципе. ### Примеры инструментов для автоматического перезапуска @@ -181,13 +184,13 @@ ### Множество процессов - Воркеры (Workers) -Если количество Ваших клиентов больше, чем может обслужить один процесс (допустим, что виртуальная машина не слишком мощная), но при этом Вам доступно **несколько ядер процессора**, то Вы можете запустить **несколько процессов** одного и того же приложения параллельно и распределить запросы между этими процессами. +Если количество Ваших клиентов больше, чем может обслужить один процесс (допустим, что виртуальная машина не слишком мощная), но при этом Вам доступно **несколько ядер процессора**, то вы можете запустить **несколько процессов** одного и того же приложения параллельно и распределить запросы между этими процессами. **Несколько запущенных процессов** одной и той же API-программы часто называют **воркерами**. ### Процессы и порты́ -Помните ли Вы, как на странице [Об HTTPS](./https.md){.internal-link target=_blank} мы обсуждали, что на сервере только один процесс может слушать одну комбинацию IP-адреса и порта? +Помните ли Вы, как на странице [Об HTTPS](https.md){.internal-link target=_blank} мы обсуждали, что на сервере только один процесс может слушать одну комбинацию IP-адреса и порта? С тех пор ничего не изменилось. @@ -197,11 +200,11 @@ Работающая программа загружает в память данные, необходимые для её работы, например, переменные содержащие модели машинного обучения или большие файлы. Каждая переменная **потребляет некоторое количество оперативной памяти (RAM)** сервера. -Обычно процессы **не делятся памятью друг с другом**. Сие означает, что каждый работающий процесс имеет свои данные, переменные и свой кусок памяти. И если для выполнения Вашего кода процессу нужно много памяти, то **каждый такой же процесс** запущенный дополнительно, потребует такого же количества памяти. +Обычно процессы **не делятся памятью друг с другом**. Сие означает, что каждый работающий процесс имеет свои данные, переменные и свой кусок памяти. И если для выполнения вашего кода процессу нужно много памяти, то **каждый такой же процесс** запущенный дополнительно, потребует такого же количества памяти. ### Память сервера -Допустим, что Ваш код загружает модель машинного обучения **размером 1 ГБ**. Когда Вы запустите своё API как один процесс, он займёт в оперативной памяти не менее 1 ГБ. А если Вы запустите **4 таких же процесса** (4 воркера), то каждый из них займёт 1 ГБ оперативной памяти. В результате Вашему API потребуется **4 ГБ оперативной памяти (RAM)**. +Допустим, что Ваш код загружает модель машинного обучения **размером 1 ГБ**. Когда вы запустите своё API как один процесс, он займёт в оперативной памяти не менее 1 ГБ. А если вы запустите **4 таких же процесса** (4 воркера), то каждый из них займёт 1 ГБ оперативной памяти. В результате вашему API потребуется **4 ГБ оперативной памяти (RAM)**. И если Ваш удалённый сервер или виртуальная машина располагает только 3 ГБ памяти, то попытка загрузить в неё 4 ГБ данных вызовет проблемы. 🚨 @@ -211,15 +214,15 @@ Менеджер процессов будет слушать определённый **сокет** (IP:порт) и передавать данные работающим процессам. -Каждый из этих процессов будет запускать Ваше приложение для обработки полученного **запроса** и возвращения вычисленного **ответа** и они будут использовать оперативную память. +Каждый из этих процессов будет запускать ваше приложение для обработки полученного **запроса** и возвращения вычисленного **ответа** и они будут использовать оперативную память. -Безусловно, на этом же сервере будут работать и **другие процессы**, которые не относятся к Вашему приложению. +Безусловно, на этом же сервере будут работать и **другие процессы**, которые не относятся к вашему приложению. -Интересная деталь - обычно в течение времени процент **использования центрального процессора (CPU)** каждым процессом может очень сильно **изменяться**, но объём занимаемой **оперативной памяти (RAM)** остаётся относительно **стабильным**. +Интересная деталь заключается в том, что процент **использования центрального процессора (CPU)** каждым процессом может сильно меняться с течением времени, но объём занимаемой **оперативной памяти (RAM)** остаётся относительно **стабильным**. -Если у Вас есть API, который каждый раз выполняет сопоставимый объем вычислений, и у Вас много клиентов, то **загрузка процессора**, вероятно, *также будет стабильной* (вместо того, чтобы постоянно быстро увеличиваться и уменьшаться). +Если у вас есть API, который каждый раз выполняет сопоставимый объем вычислений, и у вас много клиентов, то **загрузка процессора**, вероятно, *также будет стабильной* (вместо того, чтобы постоянно быстро увеличиваться и уменьшаться). ### Примеры стратегий и инструментов для запуска нескольких экземпляров приложения @@ -236,12 +239,15 @@ * **Kubernetes** и аналогичные **контейнерные системы** * Какой-то компонент в **Kubernetes** будет слушать **IP:port**. Необходимое количество запущенных экземпляров приложения будет осуществляться посредством запуска **нескольких контейнеров**, в каждом из которых работает **один процесс Uvicorn**. * **Облачные сервисы**, которые позаботятся обо всём за Вас - * Возможно, что облачный сервис умеет **управлять запуском дополнительных экземпляров приложения**. Вероятно, он потребует, чтоб Вы указали - какой **процесс** или **образ** следует клонировать. Скорее всего, Вы укажете **один процесс Uvicorn** и облачный сервис будет запускать его копии при необходимости. + * Возможно, что облачный сервис умеет **управлять запуском дополнительных экземпляров приложения**. Вероятно, он потребует, чтоб вы указали - какой **процесс** или **образ** следует клонировать. Скорее всего, вы укажете **один процесс Uvicorn** и облачный сервис будет запускать его копии при необходимости. + +/// tip | Заметка + +Если вы не знаете, что такое **контейнеры**, Docker или Kubernetes, не переживайте. -!!! tip "Заметка" - Если Вы не знаете, что такое **контейнеры**, Docker или Kubernetes, не переживайте. +Я поведаю Вам о контейнерах, образах, Docker, Kubernetes и т.п. в главе: [FastAPI внутри контейнеров - Docker](docker.md){.internal-link target=_blank}. - Я поведаю Вам о контейнерах, образах, Docker, Kubernetes и т.п. в главе: [FastAPI внутри контейнеров - Docker](./docker.md){.internal-link target=_blank}. +/// ## Шаги, предшествующие запуску @@ -253,18 +259,21 @@ Поэтому Вам нужен будет **один процесс**, выполняющий эти **подготовительные шаги** до запуска приложения. -Также Вам нужно будет убедиться, что этот процесс выполнил подготовительные шаги *даже* если впоследствии Вы запустите **несколько процессов** (несколько воркеров) самого приложения. Если бы эти шаги выполнялись в каждом **клонированном процессе**, они бы **дублировали** работу, пытаясь выполнить её **параллельно**. И если бы эта работа была бы чем-то деликатным, вроде миграции базы данных, то это может вызвать конфликты между ними. +Также Вам нужно будет убедиться, что этот процесс выполнил подготовительные шаги *даже* если впоследствии вы запустите **несколько процессов** (несколько воркеров) самого приложения. Если бы эти шаги выполнялись в каждом **клонированном процессе**, они бы **дублировали** работу, пытаясь выполнить её **параллельно**. И если бы эта работа была бы чем-то деликатным, вроде миграции базы данных, то это может вызвать конфликты между ними. Безусловно, возможны случаи, когда нет проблем при выполнении предварительной подготовки параллельно или несколько раз. Тогда Вам повезло, работать с ними намного проще. -!!! tip "Заметка" - Имейте в виду, что в некоторых случаях запуск Вашего приложения **может не требовать каких-либо предварительных шагов вовсе**. +/// tip | Заметка - Что ж, тогда Вам не нужно беспокоиться об этом. 🤷 +Имейте в виду, что в некоторых случаях запуск вашего приложения **может не требовать каких-либо предварительных шагов вовсе**. + +Что ж, тогда Вам не нужно беспокоиться об этом. 🤷 + +/// ### Примеры стратегий запуска предварительных шагов -Существует **сильная зависимость** от того, как Вы **развёртываете свою систему**, запускаете программы, обрабатываете перезапуски и т.д. +Существует **сильная зависимость** от того, как вы **развёртываете свою систему**, запускаете программы, обрабатываете перезапуски и т.д. Вот некоторые возможные идеи: @@ -272,26 +281,29 @@ * Bash-скрипт, выполняющий предварительные шаги, а затем запускающий приложение. * При этом Вам всё ещё нужно найти способ - как запускать/перезапускать *такой* bash-скрипт, обнаруживать ошибки и т.п. -!!! tip "Заметка" - Я приведу Вам больше конкретных примеров работы с контейнерами в главе: [FastAPI внутри контейнеров - Docker](./docker.md){.internal-link target=_blank}. +/// tip | Заметка + +Я приведу Вам больше конкретных примеров работы с контейнерами в главе: [FastAPI внутри контейнеров - Docker](docker.md){.internal-link target=_blank}. + +/// ## Утилизация ресурсов Ваш сервер располагает ресурсами, которые Ваши программы могут потреблять или **утилизировать**, а именно - время работы центрального процессора и объём оперативной памяти. -Как много системных ресурсов Вы предполагаете потребить/утилизировать? Если не задумываться, то можно ответить - "немного", но на самом деле Вы, вероятно, пожелаете использовать **максимально возможное количество**. +Как много системных ресурсов вы предполагаете потребить/утилизировать? Если не задумываться, то можно ответить - "немного", но на самом деле Вы, вероятно, захотите использовать **максимально возможное количество**. -Если Вы платите за содержание трёх серверов, но используете лишь малую часть системных ресурсов каждого из них, то Вы **выбрасываете деньги на ветер**, а также **впустую тратите электроэнергию** и т.п. +Если вы платите за содержание трёх серверов, но используете лишь малую часть системных ресурсов каждого из них, то вы **выбрасываете деньги на ветер**, а также **впустую тратите электроэнергию** и т.п. В таком случае было бы лучше обойтись двумя серверами, но более полно утилизировать их ресурсы (центральный процессор, оперативную память, жёсткий диск, сети передачи данных и т.д). -С другой стороны, если Вы располагаете только двумя серверами и используете **на 100% их процессоры и память**, но какой-либо процесс запросит дополнительную память, то операционная система сервера будет использовать жёсткий диск для расширения оперативной памяти (а диск работает в тысячи раз медленнее), а то вовсе **упадёт**. Или если какому-то процессу понадобится произвести вычисления, то ему придётся подождать, пока процессор освободится. +С другой стороны, если вы располагаете только двумя серверами и используете **на 100% их процессоры и память**, но какой-либо процесс запросит дополнительную память, то операционная система сервера будет использовать жёсткий диск для расширения оперативной памяти (а диск работает в тысячи раз медленнее), а то вовсе **упадёт**. Или если какому-то процессу понадобится произвести вычисления, то ему придётся подождать, пока процессор освободится. В такой ситуации лучше подключить **ещё один сервер** и перераспределить процессы между серверами, чтоб всем **хватало памяти и процессорного времени**. -Также есть вероятность, что по какой-то причине возник **всплеск** запросов к Вашему API. Возможно, это был вирус, боты или другие сервисы начали пользоваться им. И для таких происшествий Вы можете захотеть иметь дополнительные ресурсы. +Также есть вероятность, что по какой-то причине возник **всплеск** запросов к вашему API. Возможно, это был вирус, боты или другие сервисы начали пользоваться им. И для таких происшествий вы можете захотеть иметь дополнительные ресурсы. -При настройке логики развёртываний, Вы можете указать **целевое значение** утилизации ресурсов, допустим, **от 50% до 90%**. Обычно эти метрики и используют. +При настройке логики развёртываний, вы можете указать **целевое значение** утилизации ресурсов, допустим, **от 50% до 90%**. Обычно эти метрики и используют. Вы можете использовать простые инструменты, такие как `htop`, для отслеживания загрузки центрального процессора и оперативной памяти сервера, в том числе каждым процессом. Или более сложные системы мониторинга нескольких серверов. @@ -308,4 +320,4 @@ Осознание этих идей и того, как их применять, должно дать Вам интуитивное понимание, необходимое для принятия решений при настройке развертываний. 🤓 -В следующих разделах я приведу более конкретные примеры возможных стратегий, которым Вы можете следовать. 🚀 +В следующих разделах я приведу более конкретные примеры возможных стратегий, которым вы можете следовать. 🚀 diff --git a/docs/ru/docs/deployment/docker.md b/docs/ru/docs/deployment/docker.md index f045ca944..c72f67172 100644 --- a/docs/ru/docs/deployment/docker.md +++ b/docs/ru/docs/deployment/docker.md @@ -4,8 +4,11 @@ Использование контейнеров на основе Linux имеет ряд преимуществ, включая **безопасность**, **воспроизводимость**, **простоту** и прочие. -!!! tip "Подсказка" - Торопитесь или уже знакомы с этой технологией? Перепрыгните на раздел [Создать Docker-образ для FastAPI 👇](#docker-fastapi) +/// tip | Подсказка + +Торопитесь или уже знакомы с этой технологией? Перепрыгните на раздел [Создать Docker-образ для FastAPI 👇](#docker-fastapi) + +///
Развернуть Dockerfile 👀 @@ -55,7 +58,7 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] ## Образы контейнеров -Docker является одним оз основных инструментов для создания **образов** и **контейнеров** и управления ими. +Docker является одним из основных инструментов для создания **образов** и **контейнеров** и управления ими. Существует общедоступный Docker Hub с подготовленными **официальными образами** многих инструментов, окружений, баз данных и приложений. @@ -70,21 +73,21 @@ Docker является одним оз основных инструменто и т.п. -Использование подготовленных образов значительно упрощает **комбинирование** и использование разных инструментов. Например, Вы можете попытаться использовать новую базу данных. В большинстве случаев можно использовать **официальный образ** и всего лишь указать переменные окружения. +Использование подготовленных образов значительно упрощает **комбинирование** и использование разных инструментов. Например, вы можете попытаться использовать новую базу данных. В большинстве случаев можно использовать **официальный образ** и всего лишь указать переменные окружения. -Таким образом, Вы можете изучить, что такое контейнеризация и Docker, и использовать полученные знания с разными инструментами и компонентами. +Таким образом, вы можете изучить, что такое контейнеризация и Docker, и использовать полученные знания с разными инструментами и компонентами. -Так, Вы можете запустить одновременно **множество контейнеров** с базой данных, Python-приложением, веб-сервером, React-приложением и соединить их вместе через внутреннюю сеть. +Так, вы можете запустить одновременно **множество контейнеров** с базой данных, Python-приложением, веб-сервером, React-приложением и соединить их вместе через внутреннюю сеть. Все системы управления контейнерами (такие, как Docker или Kubernetes) имеют встроенные возможности для организации такого сетевого взаимодействия. ## Контейнеры и процессы -Обычно **образ контейнера** содержит метаданные предустановленной программы или команду, которую следует выполнить при запуске **контейнера**. Также он может содержать параметры, передаваемые предустановленной программе. Похоже на то, как если бы Вы запускали такую программу через терминал. +Обычно **образ контейнера** содержит метаданные предустановленной программы или команду, которую следует выполнить при запуске **контейнера**. Также он может содержать параметры, передаваемые предустановленной программе. Похоже на то, как если бы вы запускали такую программу через терминал. -Когда **контейнер** запущен, он будет выполнять прописанные в нём команды и программы. Но Вы можете изменить его так, чтоб он выполнял другие команды и программы. +Когда **контейнер** запущен, он будет выполнять прописанные в нём команды и программы. Но вы можете изменить его так, чтоб он выполнял другие команды и программы. -Контейнер буде работать до тех пор, пока выполняется его **главный процесс** (команда или программа). +Контейнер будет работать до тех пор, пока выполняется его **главный процесс** (команда или программа). В контейнере обычно выполняется **только один процесс**, но от его имени можно запустить другие процессы, тогда в этом же в контейнере будет выполняться **множество процессов**. @@ -100,17 +103,17 @@ Docker является одним оз основных инструменто * Использование с **Kubernetes** или аналогичным инструментом * Запуск в **Raspberry Pi** -* Использование в облачных сервисах, запускающих образы контейнеров для Вас и т.п. +* Использование в облачных сервисах, запускающих образы контейнеров для вас и т.п. ### Установить зависимости -Обычно Вашему приложению необходимы **дополнительные библиотеки**, список которых находится в отдельном файле. +Обычно вашему приложению необходимы **дополнительные библиотеки**, список которых находится в отдельном файле. На название и содержание такого файла влияет выбранный Вами инструмент **установки** этих библиотек (зависимостей). Чаще всего это простой файл `requirements.txt` с построчным перечислением библиотек и их версий. -При этом Вы, для выбора версий, будете использовать те же идеи, что упомянуты на странице [О версиях FastAPI](./versions.md){.internal-link target=_blank}. +При этом Вы, для выбора версий, будете использовать те же идеи, что упомянуты на странице [О версиях FastAPI](versions.md){.internal-link target=_blank}. Ваш файл `requirements.txt` может выглядеть как-то так: @@ -132,10 +135,13 @@ Successfully installed fastapi pydantic uvicorn -!!! info "Информация" - Существуют и другие инструменты управления зависимостями. +/// info | Информация + +Существуют и другие инструменты управления зависимостями. - В этом же разделе, но позже, я покажу Вам пример использования Poetry. 👇 +В этом же разделе, но позже, я покажу вам пример использования Poetry. 👇 + +/// ### Создать приложение **FastAPI** @@ -195,20 +201,23 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] Сначала копируйте **только** файл с зависимостями. - Этот файл **изменяется довольно редко**, Docker ищет изменения при постройке образа и если не находит, то использует **кэш**, в котором хранятся предыдущии версии сборки образа. + Этот файл **изменяется довольно редко**, Docker ищет изменения при постройке образа и если не находит, то использует **кэш**, в котором хранятся предыдущие версии сборки образа. 4. Установите библиотеки перечисленные в файле с зависимостями. Опция `--no-cache-dir` указывает `pip` не сохранять загружаемые библиотеки на локальной машине для использования их в случае повторной загрузки. В контейнере, в случае пересборки этого шага, они всё равно будут удалены. - !!! note "Заметка" - Опция `--no-cache-dir` нужна только для `pip`, она никак не влияет на Docker или контейнеры. + /// note | Заметка + + Опция `--no-cache-dir` нужна только для `pip`, она никак не влияет на Docker или контейнеры. + + /// Опция `--upgrade` указывает `pip` обновить библиотеки, емли они уже установлены. - Ка и в предыдущем шаге с копированием файла, этот шаг также будет использовать **кэш Docker** в случае отсутствия изменений. + Как и в предыдущем шаге с копированием файла, этот шаг также будет использовать **кэш Docker** в случае отсутствия изменений. - Использрвание кэша, особенно на этом шаге, позволит Вам **сэкономить** кучу времени при повторной сборке образа, так как зависимости будут сохранены в кеше, а не **загружаться и устанавливаться каждый раз**. + Использование кэша, особенно на этом шаге, позволит вам **сэкономить** кучу времени при повторной сборке образа, так как зависимости будут сохранены в кеше, а не **загружаться и устанавливаться каждый раз**. 5. Скопируйте директорию `./app` внутрь директории `/code` (в контейнере). @@ -216,14 +225,17 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 6. Укажите **команду**, запускающую сервер `uvicorn`. - `CMD` принимает список строк, разделённых запятыми, но при выполнении объединит их через пробел, собрав из них одну команду, которую Вы могли бы написать в терминале. + `CMD` принимает список строк, разделённых запятыми, но при выполнении объединит их через пробел, собрав из них одну команду, которую вы могли бы написать в терминале. - Эта команда будет выполнена в **текущей рабочей директории**, а именно в директории `/code`, котоая указана командой `WORKDIR /code`. + Эта команда будет выполнена в **текущей рабочей директории**, а именно в директории `/code`, которая указана в команде `WORKDIR /code`. - Так как команда выполняется внутрии директории `/code`, в которую мы поместили папку `./app` с приложением, то **Uvicorn** сможет найти и **импортировать** объект `app` из файла `app.main`. + Так как команда выполняется внутри директории `/code`, в которую мы поместили папку `./app` с приложением, то **Uvicorn** сможет найти и **импортировать** объект `app` из файла `app.main`. -!!! tip "Подсказка" - Если ткнёте на кружок с плюсом, то увидите пояснения. 👆 +/// tip | Подсказка + +Если ткнёте на кружок с плюсом, то увидите пояснения. 👆 + +/// На данном этапе структура проекта должны выглядеть так: @@ -238,7 +250,7 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] #### Использование прокси-сервера -Если Вы запускаете контейнер за прокси-сервером завершения TLS (балансирующего нагрузку), таким как Nginx или Traefik, добавьте опцию `--proxy-headers`, которая укажет Uvicorn, что он работает позади прокси-сервера и может доверять заголовкам отправляемым им. +Если вы запускаете контейнер за прокси-сервером завершения TLS (балансирующего нагрузку), таким как Nginx или Traefik, добавьте опцию `--proxy-headers`, которая укажет Uvicorn, что он работает позади прокси-сервера и может доверять заголовкам отправляемым им. ```Dockerfile CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"] @@ -269,7 +281,7 @@ RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt Для загрузки и установки необходимых библиотек **может понадобиться несколько минут**, но использование **кэша** занимает несколько **секунд** максимум. -И так как во время разработки Вы будете часто пересобирать контейнер для проверки работоспособности внесённых изменений, то сэкономленные минуты сложатся в часы, а то и дни. +И так как во время разработки вы будете часто пересобирать контейнер для проверки работоспособности внесённых изменений, то сэкономленные минуты сложатся в часы, а то и дни. Так как папка с кодом приложения **изменяется чаще всего**, то мы расположили её в конце `Dockerfile`, ведь после внесённых в код изменений кэш не будет использован на этом и следующих шагах. @@ -294,14 +306,17 @@ $ docker build -t myimage . -!!! tip "Подсказка" - Обратите внимание, что в конце написана точка - `.`, это то же самое что и `./`, тем самым мы указываем Docker директорию, из которой нужно выполнять сборку образа контейнера. +/// tip | Подсказка + +Обратите внимание, что в конце написана точка - `.`, это то же самое что и `./`, тем самым мы указываем Docker директорию, из которой нужно выполнять сборку образа контейнера. - В данном случае это та же самая директория (`.`). +В данном случае это та же самая директория (`.`). + +/// ### Запуск Docker-контейнера -* Запустите контейнер, основанный на Вашем образе: +* Запустите контейнер, основанный на вашем образе:
@@ -315,7 +330,7 @@ $ docker run -d --name mycontainer -p 80:80 myimage Вы можете проверить, что Ваш Docker-контейнер работает перейдя по ссылке: http://192.168.99.100/items/5?q=somequery или http://127.0.0.1/items/5?q=somequery (или похожей, которую использует Ваш Docker-хост). -Там Вы увидите: +Там вы увидите: ```JSON {"item_id": 5, "q": "somequery"} @@ -325,21 +340,21 @@ $ docker run -d --name mycontainer -p 80:80 myimage Теперь перейдите по ссылке http://192.168.99.100/docs или http://127.0.0.1/docs (или похожей, которую использует Ваш Docker-хост). -Здесь Вы увидите автоматическую интерактивную документацию API (предоставляемую Swagger UI): +Здесь вы увидите автоматическую интерактивную документацию API (предоставляемую Swagger UI): ![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) ## Альтернативная документация API -Также Вы можете перейти по ссылке http://192.168.99.100/redoc or http://127.0.0.1/redoc (или похожей, которую использует Ваш Docker-хост). +Также вы можете перейти по ссылке http://192.168.99.100/redoc or http://127.0.0.1/redoc (или похожей, которую использует Ваш Docker-хост). -Здесь Вы увидите альтернативную автоматическую документацию API (предоставляемую ReDoc): +Здесь вы увидите альтернативную автоматическую документацию API (предоставляемую ReDoc): ![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) ## Создание Docker-образа на основе однофайлового приложения FastAPI -Если Ваше приложение FastAPI помещено в один файл, например, `main.py` и структура Ваших файлов похожа на эту: +Если ваше приложение FastAPI помещено в один файл, например, `main.py` и структура Ваших файлов похожа на эту: ``` . @@ -374,9 +389,9 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ## Концепции развёртывания -Давайте вспомним о [Концепциях развёртывания](./concepts.md){.internal-link target=_blank} и применим их к контейнерам. +Давайте вспомним о [Концепциях развёртывания](concepts.md){.internal-link target=_blank} и применим их к контейнерам. -Контейнеры - это, в основном, инструмент упрощающий **сборку и развёртывание** приложения и они не обязыают к применению какой-то определённой **концепции развёртывания**, а значит мы можем выбирать нужную стратегию. +Контейнеры - это, в основном, инструмент упрощающий **сборку и развёртывание** приложения и они не обязывают к применению какой-то определённой **концепции развёртывания**, а значит мы можем выбирать нужную стратегию. **Хорошая новость** в том, что независимо от выбранной стратегии, мы всё равно можем покрыть все концепции развёртывания. 🎉 @@ -395,8 +410,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] Это может быть другой контейнер, в котором есть, например, Traefik, работающий с **HTTPS** и **самостоятельно** обновляющий **сертификаты**. -!!! tip "Подсказка" - Traefik совместим с Docker, Kubernetes и им подобными инструментами. Он очень прост в установке и настройке использования HTTPS для Ваших контейнеров. +/// tip | Подсказка + +Traefik совместим с Docker, Kubernetes и им подобными инструментами. Он очень прост в установке и настройке использования HTTPS для Ваших контейнеров. + +/// В качестве альтернативы, работу с HTTPS можно доверить облачному провайдеру, если он предоставляет такую услугу. @@ -412,7 +430,7 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ## Запуск нескольких экземпляров приложения - Указание количества процессов -Если у Вас есть кластер машин под управлением **Kubernetes**, Docker Swarm Mode, Nomad или аналогичной сложной системой оркестрации контейнеров, скорее всего, вместо использования менеджера процессов (типа Gunicorn и его воркеры) в каждом контейнере, Вы захотите **управлять количеством запущенных экземпляров приложения** на **уровне кластера**. +Если у вас есть кластер машин под управлением **Kubernetes**, Docker Swarm Mode, Nomad или аналогичной сложной системой оркестрации контейнеров, скорее всего, вместо использования менеджера процессов (типа Gunicorn и его воркеры) в каждом контейнере, вы захотите **управлять количеством запущенных экземпляров приложения** на **уровне кластера**. В любую из этих систем управления контейнерами обычно встроен способ управления **количеством запущенных контейнеров** для распределения **нагрузки** от входящих запросов на **уровне кластера**. @@ -424,20 +442,23 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] Поскольку этот компонент **принимает запросы** и равномерно **распределяет** их между компонентами, его также называют **балансировщиком нагрузки**. -!!! tip "Подсказка" - **Прокси-сервер завершения работы TLS** одновременно может быть **балансировщиком нагрузки**. +/// tip | Подсказка + +**Прокси-сервер завершения работы TLS** одновременно может быть **балансировщиком нагрузки**. + +/// -Система оркестрации, которую Вы используете для запуска и управления контейнерами, имеет встроенный инструмент **сетевого взаимодействия** (например, для передачи HTTP-запросов) между контейнерами с Вашими приложениями и **балансировщиком нагрузки** (который также может быть **прокси-сервером**). +Система оркестрации, которую вы используете для запуска и управления контейнерами, имеет встроенный инструмент **сетевого взаимодействия** (например, для передачи HTTP-запросов) между контейнерами с Вашими приложениями и **балансировщиком нагрузки** (который также может быть **прокси-сервером**). ### Один балансировщик - Множество контейнеров -При работе с **Kubernetes** или аналогичными системами оркестрации использование их внутреннней сети позволяет иметь один **балансировщик нагрузки**, который прослушивает **главный** порт и передаёт запросы **множеству запущенных контейнеров** с Вашими приложениями. +При работе с **Kubernetes** или аналогичными системами оркестрации использование их внутренней сети позволяет иметь один **балансировщик нагрузки**, который прослушивает **главный** порт и передаёт запросы **множеству запущенных контейнеров** с Вашими приложениями. В каждом из контейнеров обычно работает **только один процесс** (например, процесс Uvicorn управляющий Вашим приложением FastAPI). Контейнеры могут быть **идентичными**, запущенными на основе одного и того же образа, но у каждого будут свои отдельные процесс, память и т.п. Таким образом мы получаем преимущества **распараллеливания** работы по **разным ядрам** процессора или даже **разным машинам**. Система управления контейнерами с **балансировщиком нагрузки** будет **распределять запросы** к контейнерам с приложениями **по очереди**. То есть каждый запрос будет обработан одним из множества **одинаковых контейнеров** с одним и тем же приложением. -**Балансировщик нагрузки** может обрабатывать запросы к *разным* приложениям, расположенным в Вашем кластере (например, если у них разные домены или префиксы пути) и передавать запросы нужному контейнеру с требуемым приложением. +**Балансировщик нагрузки** может обрабатывать запросы к *разным* приложениям, расположенным в вашем кластере (например, если у них разные домены или префиксы пути) и передавать запросы нужному контейнеру с требуемым приложением. ### Один процесс на контейнер @@ -447,37 +468,37 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] Использование менеджера процессов (Gunicorn или Uvicorn) внутри контейнера только добавляет **излишнее усложнение**, так как управление следует осуществлять системой оркестрации. -### Множество процессов внутри контейнера для особых случаев +### Множество процессов внутри контейнера для особых случаев -Безусловно, бывают **особые случаи**, когда может понадобится внутри контейнера запускать **менеджер процессов Gunicorn**, управляющий несколькими **процессами Uvicorn**. +Безусловно, бывают **особые случаи**, когда может понадобиться внутри контейнера запускать **менеджер процессов Gunicorn**, управляющий несколькими **процессами Uvicorn**. -Для таких случаев Вы можете использовать **официальный Docker-образ** (прим. пер: - *здесь и далее на этой странице, если Вы встретите сочетание "официальный Docker-образ" без уточнений, то автор имеет в виду именно предоставляемый им образ*), где в качестве менеджера процессов используется **Gunicorn**, запускающий несколько **процессов Uvicorn** и некоторые настройки по умолчанию, автоматически устанавливающие количество запущенных процессов в зависимости от количества ядер Вашего процессора. Я расскажу Вам об этом подробнее тут: [Официальный Docker-образ со встроенными Gunicorn и Uvicorn](#docker-gunicorn-uvicorn). +Для таких случаев вы можете использовать **официальный Docker-образ** (прим. пер: - *здесь и далее на этой странице, если вы встретите сочетание "официальный Docker-образ" без уточнений, то автор имеет в виду именно предоставляемый им образ*), где в качестве менеджера процессов используется **Gunicorn**, запускающий несколько **процессов Uvicorn** и некоторые настройки по умолчанию, автоматически устанавливающие количество запущенных процессов в зависимости от количества ядер вашего процессора. Я расскажу вам об этом подробнее тут: [Официальный Docker-образ со встроенными Gunicorn и Uvicorn](#docker-gunicorn-uvicorn). Некоторые примеры подобных случаев: #### Простое приложение -Вы можете использовать менеджер процессов внутри контейнера, если Ваше приложение **настолько простое**, что у Вас нет необходимости (по крайней мере, пока нет) в тщательных настройках количества процессов и Вам достаточно имеющихся настроек по умолчанию (если используется официальный Docker-образ) для запуска приложения **только на одном сервере**, а не в кластере. +Вы можете использовать менеджер процессов внутри контейнера, если ваше приложение **настолько простое**, что у вас нет необходимости (по крайней мере, пока нет) в тщательных настройках количества процессов и вам достаточно имеющихся настроек по умолчанию (если используется официальный Docker-образ) для запуска приложения **только на одном сервере**, а не в кластере. #### Docker Compose -С помощью **Docker Compose** можно разворачивать несколько контейнеров на **одном сервере** (не кластере), но при это у Вас не будет простого способа управления количеством запущенных контейнеров с одновременным сохранением общей сети и **балансировки нагрузки**. +С помощью **Docker Compose** можно разворачивать несколько контейнеров на **одном сервере** (не кластере), но при это у вас не будет простого способа управления количеством запущенных контейнеров с одновременным сохранением общей сети и **балансировки нагрузки**. В этом случае можно использовать **менеджер процессов**, управляющий **несколькими процессами**, внутри **одного контейнера**. #### Prometheus и прочие причины -У Вас могут быть и **другие причины**, когда использование **множества процессов** внутри **одного контейнера** будет проще, нежели запуск **нескольких контейнеров** с **единственным процессом** в каждом из них. +У вас могут быть и **другие причины**, когда использование **множества процессов** внутри **одного контейнера** будет проще, нежели запуск **нескольких контейнеров** с **единственным процессом** в каждом из них. -Например (в зависимости от конфигурации), у Вас могут быть инструменты подобные экспортёру Prometheus, которые должны иметь доступ к **каждому запросу** приходящему в контейнер. +Например (в зависимости от конфигурации), у вас могут быть инструменты подобные экспортёру Prometheus, которые должны иметь доступ к **каждому запросу** приходящему в контейнер. -Если у Вас будет **несколько контейнеров**, то Prometheus, по умолчанию, **при сборе метрик** получит их **только с одного контейнера**, который обрабатывает конкретный запрос, вместо **сбора метрик** со всех работающих контейнеров. +Если у вас будет **несколько контейнеров**, то Prometheus, по умолчанию, **при сборе метрик** получит их **только с одного контейнера**, который обрабатывает конкретный запрос, вместо **сбора метрик** со всех работающих контейнеров. В таком случае может быть проще иметь **один контейнер** со **множеством процессов**, с нужным инструментом (таким как экспортёр Prometheus) в этом же контейнере и собирающем метрики со всех внутренних процессов этого контейнера. --- -Самое главное - **ни одно** из перечисленных правил не является **высеченным в камне** и Вы не обязаны слепо их повторять. Вы можете использовать эти идеи при **рассмотрении Вашего конкретного случая** и самостоятельно решать, какая из концепции подходит лучше: +Самое главное - **ни одно** из перечисленных правил не является **высеченным на камне** и вы не обязаны слепо их повторять. вы можете использовать эти идеи при **рассмотрении вашего конкретного случая** и самостоятельно решать, какая из концепции подходит лучше: * Использование более безопасного протокола HTTPS * Настройки запуска приложения @@ -488,41 +509,47 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] ## Управление памятью -При **запуске одного процесса на контейнер** Вы получаете относительно понятный, стабильный и ограниченный объём памяти, потребляемый одним контейнером. +При **запуске одного процесса на контейнер** вы получаете относительно понятный, стабильный и ограниченный объём памяти, потребляемый одним контейнером. Вы можете установить аналогичные ограничения по памяти при конфигурировании своей системы управления контейнерами (например, **Kubernetes**). Таким образом система сможет **изменять количество контейнеров** на **доступных ей машинах** приводя в соответствие количество памяти нужной контейнерам с количеством памяти доступной в кластере (наборе доступных машин). -Если у Вас **простенькое** приложение, вероятно у Вас не будет **необходимости** устанавливать жёсткие ограничения на выделяемую ему память. Но если приложение **использует много памяти** (например, оно использует модели **машинного обучения**), Вам следует проверить, как много памяти ему требуется и отрегулировать **количество контейнеров** запущенных на **каждой машине** (может быть даже добавить машин в кластер). +Если у вас **простенькое** приложение, вероятно у вас не будет **необходимости** устанавливать жёсткие ограничения на выделяемую ему память. Но если приложение **использует много памяти** (например, оно использует модели **машинного обучения**), вам следует проверить, как много памяти ему требуется и отрегулировать **количество контейнеров** запущенных на **каждой машине** (может быть даже добавить машин в кластер). -Если Вы запускаете **несколько процессов в контейнере**, то должны быть уверены, что эти процессы не **займут памяти больше**, чем доступно для контейнера. +Если вы запускаете **несколько процессов в контейнере**, то должны быть уверены, что эти процессы не **займут памяти больше**, чем доступно для контейнера. ## Подготовительные шаги при запуске контейнеров -Есть два основных подхода, которые Вы можете использовать при запуске контейнеров (Docker, Kubernetes и т.п.). +Есть два основных подхода, которые вы можете использовать при запуске контейнеров (Docker, Kubernetes и т.п.). ### Множество контейнеров -Когда Вы запускаете **множество контейнеров**, в каждом из которых работает **только один процесс** (например, в кластере **Kubernetes**), может возникнуть необходимость иметь **отдельный контейнер**, который осуществит **предварительные шаги перед запуском** остальных контейнеров (например, применяет миграции к базе данных). +Когда вы запускаете **множество контейнеров**, в каждом из которых работает **только один процесс** (например, в кластере **Kubernetes**), может возникнуть необходимость иметь **отдельный контейнер**, который осуществит **предварительные шаги перед запуском** остальных контейнеров (например, применяет миграции к базе данных). -!!! info "Информация" - При использовании Kubernetes, это может быть Инициализирующий контейнер. +/// info | Информация -При отсутствии такой необходимости (допустим, не нужно применять миграции к базе данных, а только проверить, что она готова принимать соединения), Вы можете проводить такую проверку в каждом контейнере перед запуском его основного процесса и запускать все контейнеры **одновременно**. +При использовании Kubernetes, это может быть Инициализирующий контейнер. + +/// + +При отсутствии такой необходимости (допустим, не нужно применять миграции к базе данных, а только проверить, что она готова принимать соединения), вы можете проводить такую проверку в каждом контейнере перед запуском его основного процесса и запускать все контейнеры **одновременно**. ### Только один контейнер -Если у Вас несложное приложение для работы которого достаточно **одного контейнера**, но в котором работает **несколько процессов** (или один процесс), то прохождение предварительных шагов можно осуществить в этом же контейнере до запуска основного процесса. Официальный Docker-образ поддерживает такие действия. +Если у вас несложное приложение для работы которого достаточно **одного контейнера**, но в котором работает **несколько процессов** (или один процесс), то прохождение предварительных шагов можно осуществить в этом же контейнере до запуска основного процесса. Официальный Docker-образ поддерживает такие действия. ## Официальный Docker-образ с Gunicorn и Uvicorn -Я подготовил для Вас Docker-образ, в который включён Gunicorn управляющий процессами (воркерами) Uvicorn, в соответствии с концепциями рассмотренными в предыдущей главе: [Рабочие процессы сервера (воркеры) - Gunicorn совместно с Uvicorn](./server-workers.md){.internal-link target=_blank}. +Я подготовил для вас Docker-образ, в который включён Gunicorn управляющий процессами (воркерами) Uvicorn, в соответствии с концепциями рассмотренными в предыдущей главе: [Рабочие процессы сервера (воркеры) - Gunicorn совместно с Uvicorn](server-workers.md){.internal-link target=_blank}. -Этот образ может быть полезен для ситуаций описанных тут: [Множество процессов внутри контейнера для особых случаев](#special-cases). +Этот образ может быть полезен для ситуаций описанных тут: [Множество процессов внутри контейнера для особых случаев](#_11). * tiangolo/uvicorn-gunicorn-fastapi. -!!! warning "Предупреждение" - Скорее всего у Вас **нет необходимости** в использовании этого образа или подобного ему и лучше создать свой образ с нуля как описано тут: [Создать Docker-образ для FastAPI](#docker-fastapi). +/// warning | Предупреждение + +Скорее всего у вас **нет необходимости** в использовании этого образа или подобного ему и лучше создать свой образ с нуля как описано тут: [Создать Docker-образ для FastAPI](#docker-fastapi). + +/// В этом образе есть **автоматический** механизм подстройки для запуска **необходимого количества процессов** в соответствии с доступным количеством ядер процессора. @@ -530,8 +557,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] Он также поддерживает прохождение **Подготовительных шагов при запуске контейнеров** при помощи скрипта. -!!! tip "Подсказка" - Для просмотра всех возможных настроек перейдите на страницу этого Docker-образа: tiangolo/uvicorn-gunicorn-fastapi. +/// tip | Подсказка + +Для просмотра всех возможных настроек перейдите на страницу этого Docker-образа: tiangolo/uvicorn-gunicorn-fastapi. + +/// ### Количество процессов в официальном Docker-образе @@ -539,11 +569,11 @@ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] Это означает, что он будет пытаться **выжать** из процессора как можно больше **производительности**. -Но Вы можете изменять и обновлять конфигурацию с помощью **переменных окружения** и т.п. +Но вы можете изменять и обновлять конфигурацию с помощью **переменных окружения** и т.п. Поскольку количество процессов зависит от процессора, на котором работает контейнер, **объём потребляемой памяти** также будет зависеть от этого. -А значит, если Вашему приложению требуется много оперативной памяти (например, оно использует модели машинного обучения) и Ваш сервер имеет центральный процессор с большим количеством ядер, но **не слишком большим объёмом оперативной памяти**, то может дойти до того, что контейнер попытается занять памяти больше, чем доступно, из-за чего будет падение производительности (или сервер вовсе упадёт). 🚨 +А значит, если вашему приложению требуется много оперативной памяти (например, оно использует модели машинного обучения) и Ваш сервер имеет центральный процессор с большим количеством ядер, но **не слишком большим объёмом оперативной памяти**, то может дойти до того, что контейнер попытается занять памяти больше, чем доступно, из-за чего будет падение производительности (или сервер вовсе упадёт). 🚨 ### Написание `Dockerfile` @@ -562,7 +592,7 @@ COPY ./app /app ### Большие приложения -Если Вы успели ознакомиться с разделом [Приложения содержащие много файлов](../tutorial/bigger-applications.md){.internal-link target=_blank}, состоящие из множества файлов, Ваш Dockerfile может выглядеть так: +Если вы успели ознакомиться с разделом [Приложения содержащие много файлов](../tutorial/bigger-applications.md){.internal-link target=_blank}, состоящие из множества файлов, Ваш Dockerfile может выглядеть так: ```Dockerfile hl_lines="7" FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9 @@ -576,9 +606,9 @@ COPY ./app /app/app ### Как им пользоваться -Если Вы используете **Kubernetes** (или что-то вроде того), скорее всего Вам **не нужно** использовать официальный Docker-образ (или другой похожий) в качестве основы, так как управление **количеством запущенных контейнеров** должно быть настроено на уровне кластера. В таком случае лучше **создать образ с нуля**, как описано в разделе Создать [Docker-образ для FastAPI](#docker-fastapi). +Если вы используете **Kubernetes** (или что-то вроде того), скорее всего вам **не нужно** использовать официальный Docker-образ (или другой похожий) в качестве основы, так как управление **количеством запущенных контейнеров** должно быть настроено на уровне кластера. В таком случае лучше **создать образ с нуля**, как описано в разделе Создать [Docker-образ для FastAPI](#docker-fastapi). -Официальный образ может быть полезен в отдельных случаях, описанных выше в разделе [Множество процессов внутри контейнера для особых случаев](#special-cases). Например, если Ваше приложение **достаточно простое**, не требует запуска в кластере и способно уместиться в один контейнер, то его настройки по умолчанию будут работать довольно хорошо. Или же Вы развертываете его с помощью **Docker Compose**, работаете на одном сервере и т. д +Официальный образ может быть полезен в отдельных случаях, описанных выше в разделе [Множество процессов внутри контейнера для особых случаев](#_11). Например, если ваше приложение **достаточно простое**, не требует запуска в кластере и способно уместиться в один контейнер, то его настройки по умолчанию будут работать довольно хорошо. Или же вы развертываете его с помощью **Docker Compose**, работаете на одном сервере и т. д ## Развёртывание образа контейнера @@ -590,11 +620,11 @@ COPY ./app /app/app * С использованием **Kubernetes** в кластере * С использованием режима Docker Swarm в кластере * С использованием других инструментов, таких как Nomad -* С использованием облачного сервиса, который будет управлять разворачиванием Вашего контейнера +* С использованием облачного сервиса, который будет управлять разворачиванием вашего контейнера ## Docker-образ и Poetry -Если Вы пользуетесь Poetry для управления зависимостями Вашего проекта, то можете использовать многоэтапную сборку образа: +Если вы пользуетесь Poetry для управления зависимостями вашего проекта, то можете использовать многоэтапную сборку образа: ```{ .dockerfile .annotate } # (1) @@ -659,24 +689,27 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 11. Запустите `uvicorn`, указав ему использовать объект `app`, расположенный в `app.main`. -!!! tip "Подсказка" - Если ткнёте на кружок с плюсом, то увидите объяснения, что происходит в этой строке. +/// tip | Подсказка + +Если ткнёте на кружок с плюсом, то увидите объяснения, что происходит в этой строке. + +/// **Этапы сборки Docker-образа** являются частью `Dockerfile` и работают как **временные образы контейнеров**. Они нужны только для создания файлов, используемых в дальнейших этапах. -Первый этап был нужен только для **установки Poetry** и **создания файла `requirements.txt`**, в которым прописаны зависимости Вашего проекта, взятые из файла `pyproject.toml`. +Первый этап был нужен только для **установки Poetry** и **создания файла `requirements.txt`**, в которым прописаны зависимости вашего проекта, взятые из файла `pyproject.toml`. На **следующем этапе** `pip` будет использовать файл `requirements.txt`. В итоговом образе будет содержаться **только последний этап сборки**, предыдущие этапы будут отброшены. -При использовании Poetry, имеет смысл использовать **многоэтапную сборку Docker-образа**, потому что на самом деле Вам не нужен Poetry и его зависимости в окончательном образе контейнера, Вам **нужен только** сгенерированный файл `requirements.txt` для установки зависимостей Вашего проекта. +При использовании Poetry, имеет смысл использовать **многоэтапную сборку Docker-образа**, потому что на самом деле вам не нужен Poetry и его зависимости в окончательном образе контейнера, вам **нужен только** сгенерированный файл `requirements.txt` для установки зависимостей вашего проекта. А на последнем этапе, придерживаясь описанных ранее правил, создаётся итоговый образ ### Использование прокси-сервера завершения TLS и Poetry -И снова повторюсь, если используете прокси-сервер (балансировщик нагрузки), такой, как Nginx или Traefik, добавьте в команду запуска опцию `--proxy-headers`: +И снова повторюсь, если используете прокси-сервер (балансировщик нагрузки), такой как Nginx или Traefik, добавьте в команду запуска опцию `--proxy-headers`: ```Dockerfile CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"] @@ -695,6 +728,6 @@ CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port" В большинстве случаев Вам, вероятно, не нужно использовать какой-либо базовый образ, **лучше создать образ контейнера с нуля** на основе официального Docker-образа Python. -Позаботившись о **порядке написания** инструкций в `Dockerfile`, Вы сможете использовать **кэш Docker'а**, **минимизировав время сборки**, максимально повысив свою производительность (и избежать скуки). 😎 +Позаботившись о **порядке написания** инструкций в `Dockerfile`, вы сможете использовать **кэш Docker'а**, **минимизировав время сборки**, максимально повысив свою производительность (и не заскучать). 😎 В некоторых особых случаях вы можете использовать официальный образ Docker для FastAPI. 🤓 diff --git a/docs/ru/docs/deployment/https.md b/docs/ru/docs/deployment/https.md index a53ab6927..85c4cce60 100644 --- a/docs/ru/docs/deployment/https.md +++ b/docs/ru/docs/deployment/https.md @@ -1,11 +1,14 @@ # Об HTTPS -Обычно представляется, что HTTPS это некая опция, которая либо "включена", либо нет. +Обычно представляется, что HTTPS это некая опция, которая либо "включена", либо нет. Но всё несколько сложнее. -!!! tip "Заметка" - Если Вы торопитесь или Вам не интересно, можете перейти на следующую страницу этого пошагового руководства по размещению приложений на серверах с использованием различных технологий. +/// tip | Заметка + +Если вы торопитесь или вам не интересно, можете перейти на следующую страницу этого пошагового руководства по размещению приложений на серверах с использованием различных технологий. + +/// Чтобы **изучить основы HTTPS** для клиента, перейдите по ссылке https://howhttps.works/. @@ -22,8 +25,8 @@ * **TCP не знает о "доменах"**, но знает об IP-адресах. * Информация о **запрашиваемом домене** извлекается из запроса **на уровне HTTP**. * **Сертификаты HTTPS** "сертифицируют" **конкретный домен**, но проверка сертификатов и шифрование данных происходит на уровне протокола TCP, то есть **до того**, как станет известен домен-получатель данных. -* **По умолчанию** это означает, что у Вас может быть **только один сертификат HTTPS на один IP-адрес**. - * Не важно, насколько большой у Вас сервер и насколько маленькие приложения на нём могут быть. +* **По умолчанию** это означает, что у вас может быть **только один сертификат HTTPS на один IP-адрес**. + * Не важно, насколько большой у вас сервер и насколько маленькие приложения на нём могут быть. * Однако, у этой проблемы есть **решение**. * Существует **расширение** протокола **TLS** (который работает на уровне TCP, то есть до HTTP) называемое **SNI**. * Расширение SNI позволяет одному серверу (с **одним IP-адресом**) иметь **несколько сертификатов HTTPS** и обслуживать **множество HTTPS-доменов/приложений**. @@ -35,12 +38,12 @@ * получение **зашифрованных HTTPS-запросов** * отправка **расшифрованных HTTP запросов** в соответствующее HTTP-приложение, работающее на том же сервере (в нашем случае, это приложение **FastAPI**) -* получние **HTTP-ответа** от приложения +* получение **HTTP-ответа** от приложения * **шифрование ответа** используя подходящий **сертификат HTTPS** * отправка зашифрованного **HTTPS-ответа клиенту**. Такой сервер часто называют **Прокси-сервер завершения работы TLS** или просто "прокси-сервер". -Вот некоторые варианты, которые Вы можете использовать в качестве такого прокси-сервера: +Вот некоторые варианты, которые вы можете использовать в качестве такого прокси-сервера: * Traefik (может обновлять сертификаты) * Caddy (может обновлять сертификаты) @@ -67,24 +70,27 @@ ### Имя домена -Чаще всего, всё начинается с **приобретения имени домена**. Затем нужно настроить DNS-сервер (вероятно у того же провайдера, который выдал Вам домен). +Чаще всего, всё начинается с **приобретения имени домена**. Затем нужно настроить DNS-сервер (вероятно у того же провайдера, который выдал вам домен). -Далее, возможно, Вы получаете "облачный" сервер (виртуальную машину) или что-то типа этого, у которого есть постоянный **публичный IP-адрес**. +Далее, возможно, вы получаете "облачный" сервер (виртуальную машину) или что-то типа этого, у которого есть постоянный **публичный IP-адрес**. -На DNS-сервере (серверах) Вам следует настроить соответствующую ресурсную запись ("`запись A`"), указав, что **Ваш домен** связан с публичным **IP-адресом Вашего сервера**. +На DNS-сервере (серверах) вам следует настроить соответствующую ресурсную запись ("`запись A`"), указав, что **Ваш домен** связан с публичным **IP-адресом вашего сервера**. Обычно эту запись достаточно указать один раз, при первоначальной настройке всего сервера. -!!! tip "Заметка" - Уровни протоколов, работающих с именами доменов, намного ниже HTTPS, но об этом следует упомянуть здесь, так как всё зависит от доменов и IP-адресов. +/// tip | Заметка + +Уровни протоколов, работающих с именами доменов, намного ниже HTTPS, но об этом следует упомянуть здесь, так как всё зависит от доменов и IP-адресов. + +/// ### DNS Теперь давайте сфокусируемся на работе с HTTPS. -Всё начинается с того, что браузер спрашивает у **DNS-серверов**, какой **IP-адрес связан с доменом**, для примера возьмём домен `someapp.example.com`. +Всё начинается с того, что браузер спрашивает у **DNS-серверов**, какой **IP-адрес связан с доменом**, для примера возьмём домен `someapp.example.com`. -DNS-сервера присылают браузеру определённый **IP-адрес**, тот самый публичный IP-адрес Вашего сервера, который Вы указали в ресурсной "записи А" при настройке. +DNS-сервера присылают браузеру определённый **IP-адрес**, тот самый публичный IP-адрес вашего сервера, который вы указали в ресурсной "записи А" при настройке. @@ -96,7 +102,7 @@ DNS-сервера присылают браузеру определённый -Эта часть клиент-серверного взаимодействия устанавливает TLS-соединение и называется **TLS-рукопожатием**. +Эта часть клиент-серверного взаимодействия устанавливает TLS-соединение и называется **TLS-рукопожатием**. ### TLS с расширением SNI @@ -122,8 +128,11 @@ DNS-сервера присылают браузеру определённый Таким образом, **HTTPS** это тот же **HTTP**, но внутри **безопасного TLS-соединения** вместо чистого (незашифрованного) TCP-соединения. -!!! tip "Заметка" - Обратите внимание, что шифрование происходит на **уровне TCP**, а не на более высоком уровне HTTP. +/// tip | Заметка + +Обратите внимание, что шифрование происходит на **уровне TCP**, а не на более высоком уровне HTTP. + +/// ### HTTPS-запрос @@ -185,7 +194,7 @@ DNS-сервера присылают браузеру определённый * **Запуск в качестве программы-сервера** (как минимум, на время обновления сертификатов) на публичном IP-адресе домена. * Как уже не раз упоминалось, только один процесс может прослушивать определённый порт определённого IP-адреса. * Это одна из причин использования прокси-сервера ещё и в качестве программы обновления сертификатов. - * В случае, если обновлением сертификатов занимается другая программа, Вам понадобится остановить прокси-сервер, запустить программу обновления сертификатов на сокете, предназначенном для прокси-сервера, настроить прокси-сервер на работу с новыми сертификатами и перезапустить его. Эта схема далека от идеальной, так как Ваши приложения будут недоступны на время отключения прокси-сервера. + * В случае, если обновлением сертификатов занимается другая программа, вам понадобится остановить прокси-сервер, запустить программу обновления сертификатов на сокете, предназначенном для прокси-сервера, настроить прокси-сервер на работу с новыми сертификатами и перезапустить его. Эта схема далека от идеальной, так как Ваши приложения будут недоступны на время отключения прокси-сервера. Весь этот процесс обновления, одновременный с обслуживанием запросов, является одной из основных причин, по которой желательно иметь **отдельную систему для работы с HTTPS** в виде прокси-сервера завершения TLS, а не просто использовать сертификаты TLS непосредственно с сервером приложений (например, Uvicorn). @@ -193,6 +202,6 @@ DNS-сервера присылают браузеру определённый Наличие **HTTPS** очень важно и довольно **критично** в большинстве случаев. Однако, Вам, как разработчику, не нужно тратить много сил на это, достаточно **понимать эти концепции** и принципы их работы. -Но узнав базовые основы **HTTPS** Вы можете легко совмещать разные инструменты, которые помогут Вам в дальнейшей разработке. +Но узнав базовые основы **HTTPS** вы можете легко совмещать разные инструменты, которые помогут вам в дальнейшей разработке. -В следующих главах я покажу Вам несколько примеров, как настраивать **HTTPS** для приложений **FastAPI**. 🔒 +В следующих главах я покажу вам несколько примеров, как настраивать **HTTPS** для приложений **FastAPI**. 🔒 diff --git a/docs/ru/docs/deployment/index.md b/docs/ru/docs/deployment/index.md index d214a9d62..e88ddc3e2 100644 --- a/docs/ru/docs/deployment/index.md +++ b/docs/ru/docs/deployment/index.md @@ -8,7 +8,7 @@ Обычно **веб-приложения** размещают на удалённом компьютере с серверной программой, которая обеспечивает хорошую производительность, стабильность и т. д., Чтобы ваши пользователи могли эффективно, беспрерывно и беспроблемно обращаться к приложению. -Это отличется от **разработки**, когда вы постоянно меняете код, делаете в нём намеренные ошибки и исправляете их, останавливаете и перезапускаете сервер разработки и т. д. +Это отличается от **разработки**, когда вы постоянно меняете код, делаете в нём намеренные ошибки и исправляете их, останавливаете и перезапускаете сервер разработки и т. д. ## Стратегии развёртывания diff --git a/docs/ru/docs/deployment/manually.md b/docs/ru/docs/deployment/manually.md index 1d00b3086..9b1d32be8 100644 --- a/docs/ru/docs/deployment/manually.md +++ b/docs/ru/docs/deployment/manually.md @@ -1,100 +1,113 @@ # Запуск сервера вручную - Uvicorn -Для запуска приложения **FastAPI** на удалённой серверной машине Вам необходим программный сервер, поддерживающий протокол ASGI, такой как **Uvicorn**. +Для запуска приложения **FastAPI** на удалённой серверной машине вам необходим программный сервер, поддерживающий протокол ASGI, такой как **Uvicorn**. Существует три наиболее распространённые альтернативы: * Uvicorn: высокопроизводительный ASGI сервер. -* Hypercorn: ASGI сервер, помимо прочего поддерживающий HTTP/2 и Trio. +* Hypercorn: ASGI сервер, помимо прочего поддерживающий HTTP/2 и Trio. * Daphne: ASGI сервер, созданный для Django Channels. ## Сервер как машина и сервер как программа -В этих терминах есть некоторые различия и Вам следует запомнить их. 💡 +В этих терминах есть некоторые различия и вам следует запомнить их. 💡 Слово "**сервер**" чаще всего используется в двух контекстах: - удалённый или расположенный в "облаке" компьютер (физическая или виртуальная машина). - программа, запущенная на таком компьютере (например, Uvicorn). -Просто запомните, если Вам встретился термин "сервер", то обычно он подразумевает что-то из этих двух смыслов. +Просто запомните, если вам встретился термин "сервер", то обычно он подразумевает что-то из этих двух смыслов. -Когда имеют в виду именно удалённый компьютер, часто говорят просто **сервер**, но ещё его называют **машина**, **ВМ** (виртуальная машина), **нода**. Все эти термины обозначают одно и то же - удалённый компьютер, обычно под управлением Linux, на котором Вы запускаете программы. +Когда имеют в виду именно удалённый компьютер, часто говорят просто **сервер**, но ещё его называют **машина**, **ВМ** (виртуальная машина), **нода**. Все эти термины обозначают одно и то же - удалённый компьютер, обычно под управлением Linux, на котором вы запускаете программы. ## Установка программного сервера Вы можете установить сервер, совместимый с протоколом ASGI, так: -=== "Uvicorn" +//// tab | Uvicorn - * Uvicorn, молниесный ASGI сервер, основанный на библиотеках uvloop и httptools. +* Uvicorn, очень быстрый ASGI сервер, основанный на библиотеках uvloop и httptools. -
+
- ```console - $ pip install "uvicorn[standard]" +```console +$ pip install "uvicorn[standard]" - ---> 100% - ``` +---> 100% +``` -
+
+ +/// tip | Подсказка - !!! tip "Подсказка" - С опцией `standard`, Uvicorn будет установливаться и использоваться с некоторыми дополнительными рекомендованными зависимостями. +С опцией `standard`, Uvicorn будет устанавливаться и использоваться с некоторыми дополнительными рекомендованными зависимостями. - В них входит `uvloop`, высокопроизводительная замена `asyncio`, которая значительно ускоряет работу асинхронных программ. +В них входит `uvloop`, высокопроизводительная замена `asyncio`, которая значительно ускоряет работу асинхронных программ. -=== "Hypercorn" +/// - * Hypercorn, ASGI сервер, поддерживающий протокол HTTP/2. +//// -
+//// tab | Hypercorn - ```console - $ pip install hypercorn +* Hypercorn, ASGI сервер, поддерживающий протокол HTTP/2. - ---> 100% - ``` +
-
+```console +$ pip install hypercorn + +---> 100% +``` + +
- ...или какой-либо другой ASGI сервер. +...или какой-либо другой ASGI сервер. + +//// ## Запуск серверной программы -Затем запустите Ваше приложение так же, как было указано в руководстве ранее, но без опции `--reload`: +Затем запустите ваше приложение так же, как было указано в руководстве ранее, но без опции `--reload`: + +//// tab | Uvicorn + +
+ +```console +$ uvicorn main:app --host 0.0.0.0 --port 80 -=== "Uvicorn" +INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) +``` -
+
- ```console - $ uvicorn main:app --host 0.0.0.0 --port 80 +//// - INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) - ``` +//// tab | Hypercorn -
+
-=== "Hypercorn" +```console +$ hypercorn main:app --bind 0.0.0.0:80 -
+Running on 0.0.0.0:8080 over http (CTRL + C to quit) +``` - ```console - $ hypercorn main:app --bind 0.0.0.0:80 +
- Running on 0.0.0.0:8080 over http (CTRL + C to quit) - ``` +//// -
+/// warning | Предупреждение -!!! warning "Предупреждение" +Не забудьте удалить опцию `--reload`, если ранее пользовались ею. - Не забудьте удалить опцию `--reload`, если ранее пользовались ею. +Включение опции `--reload` требует дополнительных ресурсов, влияет на стабильность работы приложения и может повлечь прочие неприятности. - Включение опции `--reload` требует дополнительных ресурсов, влияет на стабильность работы приложения и может повлечь прочие неприятности. +Она сильно помогает во время **разработки**, но **не следует** использовать её при **реальной работе** приложения. - Она сильно помогает во время **разработки**, но **не следует** использовать её при **реальной работе** приложения. +/// ## Hypercorn с Trio @@ -103,11 +116,11 @@ Starlette и **FastAPI** основаны на `uvloop`, высокопроизводительной заменой `asyncio`. -Но если Вы хотите использовать **Trio** напрямую, то можете воспользоваться **Hypercorn**, так как они совместимы. ✨ +Но если вы хотите использовать **Trio** напрямую, то можете воспользоваться **Hypercorn**, так как они совместимы. ✨ ### Установка Hypercorn с Trio -Для начала, Вам нужно установить Hypercorn с поддержкой Trio: +Для начала, вам нужно установить Hypercorn с поддержкой Trio:
@@ -130,15 +143,15 @@ $ hypercorn main:app --worker-class trio
-Hypercorn, в свою очередь, запустит Ваше приложение использующее Trio. +Hypercorn, в свою очередь, запустит ваше приложение использующее Trio. -Таким образом, Вы сможете использовать Trio в своём приложении. Но лучше использовать AnyIO, для сохранения совместимости и с Trio, и с asyncio. 🎉 +Таким образом, вы сможете использовать Trio в своём приложении. Но лучше использовать AnyIO, для сохранения совместимости и с Trio, и с asyncio. 🎉 ## Концепции развёртывания В вышеприведённых примерах серверные программы (например Uvicorn) запускали только **один процесс**, принимающий входящие запросы с любого IP (на это указывал аргумент `0.0.0.0`) на определённый порт (в примерах мы указывали порт `80`). -Это основная идея. Но возможно, Вы озаботитесь добавлением дополнительных возможностей, таких как: +Это основная идея. Но возможно, вы озаботитесь добавлением дополнительных возможностей, таких как: * Использование более безопасного протокола HTTPS * Настройки запуска приложения @@ -147,4 +160,4 @@ Hypercorn, в свою очередь, запустит Ваше приложе * Управление памятью * Использование перечисленных функций перед запуском приложения. -Я поведаю Вам больше о каждой из этих концепций в следующих главах, с конкретными примерами стратегий работы с ними. 🚀 +Я расскажу вам больше о каждой из этих концепций в следующих главах, с конкретными примерами стратегий работы с ними. 🚀 diff --git a/docs/ru/docs/deployment/versions.md b/docs/ru/docs/deployment/versions.md index 91b9038e9..e8db30ce8 100644 --- a/docs/ru/docs/deployment/versions.md +++ b/docs/ru/docs/deployment/versions.md @@ -42,8 +42,11 @@ fastapi>=0.45.0,<0.46.0 FastAPI следует соглашению в том, что любые изменения "ПАТЧ"-версии предназначены для исправления багов и внесения обратно совместимых изменений. -!!! Подсказка - "ПАТЧ" - это последнее число. Например, в `0.2.3`, ПАТЧ-версия - это `3`. +/// tip | Подсказка + +"ПАТЧ" - это последнее число. Например, в `0.2.3`, ПАТЧ-версия - это `3`. + +/// Итак, вы можете закрепить версию следующим образом: @@ -53,8 +56,11 @@ fastapi>=0.45.0,<0.46.0 Обратно несовместимые изменения и новые функции добавляются в "МИНОРНЫЕ" версии. -!!! Подсказка - "МИНОРНАЯ" версия - это число в середине. Например, в `0.2.3` МИНОРНАЯ версия - это `2`. +/// tip | Подсказка + +"МИНОРНАЯ" версия - это число в середине. Например, в `0.2.3` МИНОРНАЯ версия - это `2`. + +/// ## Обновление версий FastAPI diff --git a/docs/ru/docs/environment-variables.md b/docs/ru/docs/environment-variables.md new file mode 100644 index 000000000..a6c7b0c77 --- /dev/null +++ b/docs/ru/docs/environment-variables.md @@ -0,0 +1,297 @@ +# Переменные окружения + +/// tip + +Если вы уже знаете, что такое «переменные окружения» и как их использовать, можете пропустить это. + +/// + +Переменная окружения (также известная как «**env var**») - это переменная, которая живет **вне** кода Python, в **операционной системе**, и может быть прочитана вашим кодом Python (или другими программами). + +Переменные окружения могут быть полезны для работы с **настройками** приложений, как часть **установки** Python и т.д. + +## Создание и использование переменных окружения + +Можно **создавать** и использовать переменные окружения в **оболочке (терминале)**, не прибегая к помощи Python: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// Вы можете создать переменную окружения MY_NAME с помощью +$ export MY_NAME="Wade Wilson" + +// Затем её можно использовать в других программах, например +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// Создайте переменную окружения MY_NAME +$ $Env:MY_NAME = "Wade Wilson" + +// Используйте её с другими программами, например +$ echo "Hello $Env:MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +## Чтение переменных окружения в python + +Так же существует возможность создания переменных окружения **вне** Python, в терминале (или любым другим способом), а затем **чтения их в Python**. + +Например, у вас есть файл `main.py`: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// tip + +Второй аргумент `os.getenv()` - это возвращаемое по умолчанию значение. + +Если значение не указано, то по умолчанию оно равно `None`. В данном случае мы указываем `«World»` в качестве значения по умолчанию. +/// + +Затем можно запустить эту программу на Python: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// Здесь мы еще не устанавливаем переменную окружения +$ python main.py + +// Поскольку мы не задали переменную окружения, мы получим значение по умолчанию + +Hello World from Python + +// Но если мы сначала создадим переменную окружения +$ export MY_NAME="Wade Wilson" + +// А затем снова запустим программу +$ python main.py + +// Теперь она прочитает переменную окружения + +Hello Wade Wilson from Python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// Здесь мы еще не устанавливаем переменную окружения +$ python main.py + +// Поскольку мы не задали переменную окружения, мы получим значение по умолчанию + +Hello World from Python + +// Но если мы сначала создадим переменную окружения +$ $Env:MY_NAME = "Wade Wilson" + +// А затем снова запустим программу +$ python main.py + +// Теперь она может прочитать переменную окружения + +Hello Wade Wilson from Python +``` + +
+ +//// + +Поскольку переменные окружения могут быть установлены вне кода, но могут быть прочитаны кодом, и их не нужно хранить (фиксировать в `git`) вместе с остальными файлами, их принято использовать для конфигураций или **настроек**. + +Вы также можете создать переменную окружения только для **конкретного вызова программы**, которая будет доступна только для этой программы и только на время ее выполнения. + +Для этого создайте её непосредственно перед самой программой, в той же строке: + +
+ +```console +// Создайте переменную окружения MY_NAME в строке для этого вызова программы +$ MY_NAME="Wade Wilson" python main.py + +// Теперь она может прочитать переменную окружения + +Hello Wade Wilson from Python + +// После этого переменная окружения больше не существует +$ python main.py + +Hello World from Python +``` + +
+ +/// tip + +Подробнее об этом можно прочитать на сайте The Twelve-Factor App: Config. + +/// + +## Типизация и Валидация + +Эти переменные окружения могут работать только с **текстовыми строками**, поскольку они являются внешними по отношению к Python и должны быть совместимы с другими программами и остальной системой (и даже с различными операционными системами, такими как Linux, Windows, macOS). + +Это означает, что **любое значение**, считанное в Python из переменной окружения, **будет `str`**, и любое преобразование к другому типу или любая проверка должны быть выполнены в коде. + +Подробнее об использовании переменных окружения для работы с **настройками приложения** вы узнаете в [Расширенное руководство пользователя - Настройки и переменные среды](./advanced/settings.md){.internal-link target=_blank}. + +## Переменная окружения `PATH` + +Существует **специальная** переменная окружения **`PATH`**, которая используется операционными системами (Linux, macOS, Windows) для поиска программ для запуска. + +Значение переменной `PATH` - это длинная строка, состоящая из каталогов, разделенных двоеточием `:` в Linux и macOS, и точкой с запятой `;` в Windows. + +Например, переменная окружения `PATH` может выглядеть следующим образом: + +//// tab | Linux, macOS + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +Это означает, что система должна искать программы в каталогах: + +* `/usr/local/bin` +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32 +``` + +Это означает, что система должна искать программы в каталогах: + +* `C:\Program Files\Python312\Scripts` +* `C:\Program Files\Python312` +* `C:\Windows\System32` + +//// + +Когда вы вводите **команду** в терминале, операционная система **ищет** программу в **каждой из тех директорий**, которые перечислены в переменной окружения `PATH`. + +Например, когда вы вводите `python` в терминале, операционная система ищет программу под названием `python` в **первой директории** в этом списке. + +Если она ее находит, то **использует ее**. В противном случае она продолжает искать в **других каталогах**. + +### Установка Python и обновление `PATH` + +При установке Python вас могут спросить, нужно ли обновить переменную окружения `PATH`. + +//// tab | Linux, macOS + +Допустим, вы устанавливаете Python, и он оказывается в каталоге `/opt/custompython/bin`. + +Если вы скажете «да», чтобы обновить переменную окружения `PATH`, то программа установки добавит `/opt/custompython/bin` в переменную окружения `PATH`. + +Это может выглядеть следующим образом: + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin +``` + +Таким образом, когда вы набираете `python` в терминале, система найдет программу Python в `/opt/custompython/bin` (последний каталог) и использует ее. + +//// + +//// tab | Windows + +Допустим, вы устанавливаете Python, и он оказывается в каталоге `C:\opt\custompython\bin`. + +Если вы согласитесь обновить переменную окружения `PATH`, то программа установки добавит `C:\opt\custompython\bin` в переменную окружения `PATH`. + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin +``` + +Таким образом, когда вы набираете `python` в терминале, система найдет программу Python в `C:\opt\custompython\bin` (последний каталог) и использует ее. + +//// + +Итак, если вы напечатаете: + +
+ +```console +$ python +``` + +
+ +//// tab | Linux, macOS + +Система **найдет** программу `python` в `/opt/custompython/bin` и запустит ее. + +Это примерно эквивалентно набору текста: + +
+ +```console +$ /opt/custompython/bin/python +``` + +
+ +//// + +//// tab | Windows + +Система **найдет** программу `python` в каталоге `C:\opt\custompython\bin\python` и запустит ее. + +Это примерно эквивалентно набору текста: + +
+ +```console +$ C:\opt\custompython\bin\python +``` + +
+ +//// + +Эта информация будет полезна при изучении [Виртуальных окружений](virtual-environments.md){.internal-link target=_blank}. + +## Вывод + +Благодаря этому вы должны иметь базовое представление о том, что такое **переменные окружения** и как использовать их в Python. + +Подробнее о них вы также можете прочитать в статье о переменных окружения на википедии. + +Во многих случаях не всегда очевидно, как переменные окружения могут быть полезны и применимы. Но они постоянно появляются в различных сценариях разработки, поэтому знать о них полезно. + +Например, эта информация понадобится вам в следующем разделе, посвященном [Виртуальным окружениям](virtual-environments.md). diff --git a/docs/ru/docs/external-links.md b/docs/ru/docs/external-links.md deleted file mode 100644 index 2448ef82e..000000000 --- a/docs/ru/docs/external-links.md +++ /dev/null @@ -1,33 +0,0 @@ -# Внешние ссылки и статьи - -**FastAPI** имеет отличное и постоянно растущее сообщество. - -Существует множество сообщений, статей, инструментов и проектов, связанных с **FastAPI**. - -Вот неполный список некоторых из них. - -!!! tip - Если у вас есть статья, проект, инструмент или что-либо, связанное с **FastAPI**, что еще не перечислено здесь, создайте Pull Request. - -{% for section_name, section_content in external_links.items() %} - -## {{ section_name }} - -{% for lang_name, lang_content in section_content.items() %} - -### {{ lang_name }} - -{% for item in lang_content %} - -* {{ item.title }} by {{ item.author }}. - -{% endfor %} -{% endfor %} -{% endfor %} - -## Проекты - -Последние GitHub-проекты с пометкой `fastapi`: - -
-
diff --git a/docs/ru/docs/fastapi-cli.md b/docs/ru/docs/fastapi-cli.md new file mode 100644 index 000000000..c0be4a5df --- /dev/null +++ b/docs/ru/docs/fastapi-cli.md @@ -0,0 +1,75 @@ +# FastAPI CLI + +**FastAPI CLI** это программа командной строки, которую вы можете использовать для запуска вашего FastAPI приложения, для управления FastAPI-проектом, а также для многих других вещей. + +`fastapi-cli` устанавливается вместе со стандартным пакетом FastAPI (при запуске команды `pip install "fastapi[standard]"`). Данный пакет предоставляет доступ к программе `fastapi` через терминал. + +Чтобы запустить приложение FastAPI в режиме разработки, вы можете использовать команду `fastapi dev`: + +
+ +```console +$ fastapi dev main.py + + FastAPI Starting development server 🚀 + + Searching for package file structure from directories with + __init__.py files + Importing from /home/user/code/awesomeapp + + module 🐍 main.py + + code Importing the FastAPI app object from the module with the + following code: + + from main import app + + app Using import string: main:app + + server Server started at http://127.0.0.1:8000 + server Documentation at http://127.0.0.1:8000/docs + + tip Running in development mode, for production use: + fastapi run + + Logs: + + INFO Will watch for changes in these directories: + ['/home/user/code/awesomeapp'] + INFO Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to + quit) + INFO Started reloader process [383138] using WatchFiles + INFO Started server process [383153] + INFO Waiting for application startup. + INFO Application startup complete. +``` + +
+ +Приложение командной строки `fastapi` это и есть **FastAPI CLI**. + +FastAPI CLI берет путь к вашей Python-программе (напр. `main.py`) и автоматически находит объект `FastAPI` (обычно это `app`), затем определяет правильный процесс импорта и запускает сервер приложения. + +Для работы в production окружении вместо `fastapi dev` нужно использовать `fastapi run`. 🚀 + +Внутри **FastAPI CLI** используется Uvicorn, высокопроизводительный, готовый к работе в production сервер ASGI. 😎 + +## `fastapi dev` + +Вызов `fastapi dev` запускает режим разработки. + +По умолчанию включена автоматическая перезагрузка (**auto-reload**), благодаря этому при изменении кода происходит перезагрузка сервера приложения. Эта установка требует значительных ресурсов и делает систему менее стабильной. Используйте её только при разработке. Приложение слушает входящие подключения на IP `127.0.0.1`. Это IP адрес вашей машины, предназначенный для внутренних коммуникаций (`localhost`). + +## `fastapi run` + +Вызов `fastapi run` по умолчанию запускает FastAPI в режиме production. + +По умолчанию функция перезагрузки **auto-reload** отключена. Приложение слушает входящие подключения на IP `0.0.0.0`, т.е. на всех доступных адресах компьютера. Таким образом, приложение будет находиться в публичном доступе для любого, кто может подсоединиться к вашей машине. Продуктовые приложения запускаются именно так, например, с помощью контейнеров. + +В большинстве случаев вы будете (и должны) использовать прокси-сервер ("termination proxy"), который будет поддерживать HTTPS поверх вашего приложения. Всё будет зависеть от того, как вы развертываете приложение: за вас это либо сделает ваш провайдер, либо вам придется сделать настройки самостоятельно. + +/// tip | Подсказка + +Вы можете больше узнать об этом в документации по развертыванию приложений [deployment documentation](deployment/index.md){.internal-link target=_blank}. + +/// diff --git a/docs/ru/docs/fastapi-people.md b/docs/ru/docs/fastapi-people.md deleted file mode 100644 index 64ae66a03..000000000 --- a/docs/ru/docs/fastapi-people.md +++ /dev/null @@ -1,180 +0,0 @@ - -# Люди, поддерживающие FastAPI - -У FastAPI замечательное сообщество, которое доброжелательно к людям с любым уровнем знаний. - -## Создатель и хранитель - -Ку! 👋 - -Это я: - -{% if people %} -
-{% for user in people.maintainers %} - -
@{{ user.login }}
Answers: {{ user.answers }}
Pull Requests: {{ user.prs }}
-{% endfor %} - -
-{% endif %} - -Я создал и продолжаю поддерживать **FastAPI**. Узнать обо мне больше можно тут [Помочь FastAPI - Получить помощь - Связаться с автором](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. - -... но на этой странице я хочу показать вам наше сообщество. - ---- - -**FastAPI** получает огромную поддержку от своего сообщества. И я хочу отметить вклад его участников. - -Это люди, которые: - -* [Помогают другим с их проблемами (вопросами) на GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}. -* [Создают пул-реквесты](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. -* Делают ревью пул-реквестов, [что особенно важно для переводов на другие языки](contributing.md#translations){.internal-link target=_blank}. - -Поаплодируем им! 👏 🙇 - -## Самые активные участники за прошедший месяц - -Эти участники [оказали наибольшую помощь другим с решением их проблем (вопросов) на GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank} в течение последнего месяца. ☕ - -{% if people %} -
-{% for user in people.last_month_active %} - -
@{{ user.login }}
Issues replied: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Эксперты - -Здесь представлены **Эксперты FastAPI**. 🤓 - -Эти участники [оказали наибольшую помощь другим с решением их проблем (вопросов) на GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank} за *всё время*. - -Оказывая помощь многим другим, они подтвердили свой уровень знаний. ✨ - -{% if people %} -
-{% for user in people.experts %} - -
@{{ user.login }}
Issues replied: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Рейтинг участников, внёсших вклад в код - -Здесь представлен **Рейтинг участников, внёсших вклад в код**. 👷 - -Эти люди [сделали наибольшее количество пул-реквестов](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}, *включённых в основной код*. - -Они сделали наибольший вклад в исходный код, документацию, переводы и т.п. 📦 - -{% if people %} -
-{% for user in people.top_contributors %} - -
@{{ user.login }}
Pull Requests: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -На самом деле таких людей довольно много (более сотни), вы можете увидеть всех на этой странице FastAPI GitHub Contributors page. 👷 - -## Рейтинг ревьюеров - -Здесь представлен **Рейтинг ревьюеров**. 🕵️ - -### Проверки переводов на другие языки - -Я знаю не очень много языков (и не очень хорошо 😅). -Итак, ревьюеры - это люди, которые могут [**подтвердить предложенный вами перевод** документации](contributing.md#translations){.internal-link target=_blank}. Без них не было бы документации на многих языках. - ---- - -В **Рейтинге ревьюеров** 🕵️ представлены те, кто проверил наибольшее количество пул-реквестов других участников, обеспечивая качество кода, документации и, особенно, **переводов на другие языки**. - -{% if people %} -
-{% for user in people.top_reviewers %} - -
@{{ user.login }}
Reviews: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Спонсоры - -Здесь представлены **Спонсоры**. 😎 - -Спонсоры поддерживают мою работу над **FastAPI** (и другими проектами) главным образом через GitHub Sponsors. - -{% if sponsors %} - -{% if sponsors.gold %} - -### Золотые спонсоры - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Серебрянные спонсоры - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Бронзовые спонсоры - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -{% endif %} - -### Индивидуальные спонсоры - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
- -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
- -{% endfor %} -{% endif %} - -## О данных - технические детали - -Основная цель этой страницы - подчеркнуть усилия сообщества по оказанию помощи другим. - -Особенно это касается усилий, которые обычно менее заметны и во многих случаях более трудоемки, таких как помощь другим в решении проблем и проверка пул-реквестов с переводами. - -Данные рейтинги подсчитываются каждый месяц, ознакомиться с тем, как это работает можно тут. - -Кроме того, я также подчеркиваю вклад спонсоров. - -И я оставляю за собой право обновлять алгоритмы подсчёта, виды рейтингов, пороговые значения и т.д. (так, на всякий случай 🤷). diff --git a/docs/ru/docs/features.md b/docs/ru/docs/features.md index 97841cc83..77d6b936a 100644 --- a/docs/ru/docs/features.md +++ b/docs/ru/docs/features.md @@ -66,10 +66,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! Информация - `**second_user_data` означает: +/// info | Информация - Передать ключи и значения словаря `second_user_data`, в качестве аргументов типа "ключ-значение", это эквивалентно: `User(id=4, name="Mary", joined="2018-11-30")` . +`**second_user_data` означает: + +Передать ключи и значения словаря `second_user_data`, в качестве аргументов типа "ключ-значение", это эквивалентно: `User(id=4, name="Mary", joined="2018-11-30")` . + +/// ### Поддержка редакторов (IDE) @@ -177,7 +180,7 @@ FastAPI включает в себя чрезвычайно простую в и ## Особенности и возможности Pydantic -**FastAPI** основан на Pydantic и полностью совместим с ним. Так что, любой дополнительный код Pydantic, который у вас есть, будет также работать. +**FastAPI** основан на Pydantic и полностью совместим с ним. Так что, любой дополнительный код Pydantic, который у вас есть, будет также работать. Включая внешние библиотеки, также основанные на Pydantic, такие как: ORM'ы, ODM'ы для баз данных. @@ -192,8 +195,6 @@ FastAPI включает в себя чрезвычайно простую в и * Если вы знаете аннотации типов в Python, вы знаете, как использовать Pydantic. * Прекрасно сочетается с вашими **IDE/linter/мозгом**: * Потому что структуры данных pydantic - это всего лишь экземпляры классов, определённых вами. Автодополнение, проверка кода, mypy и ваша интуиция - всё будет работать с вашими проверенными данными. -* **Быстродействие**: - * В тестовых замерах Pydantic быстрее, чем все другие проверенные библиотеки. * Проверка **сложных структур**: * Использование иерархических моделей Pydantic; `List`, `Dict` и т.п. из модуля `typing` (входит в стандартную библиотеку Python). * Валидаторы позволяют четко и легко определять, проверять и документировать сложные схемы данных в виде JSON Schema. diff --git a/docs/ru/docs/help-fastapi.md b/docs/ru/docs/help-fastapi.md index 65ff768d1..474b3d689 100644 --- a/docs/ru/docs/help-fastapi.md +++ b/docs/ru/docs/help-fastapi.md @@ -12,7 +12,7 @@ ## Подписаться на новостную рассылку -Вы можете подписаться на редкую [новостную рассылку **FastAPI и его друзья**](/newsletter/){.internal-link target=_blank} и быть в курсе о: +Вы можете подписаться на редкую [новостную рассылку **FastAPI и его друзья**](newsletter.md){.internal-link target=_blank} и быть в курсе о: * Новостях о FastAPI и его друзьях 🚀 * Руководствах 📝 @@ -26,13 +26,13 @@ ## Добавить **FastAPI** звезду на GitHub -Вы можете добавить FastAPI "звезду" на GitHub (кликнуть на кнопку звезды в верхнем правом углу экрана): https://github.com/tiangolo/fastapi. ⭐️ +Вы можете добавить FastAPI "звезду" на GitHub (кликнуть на кнопку звезды в верхнем правом углу экрана): https://github.com/fastapi/fastapi. ⭐️ Чем больше звёзд, тем легче другим пользователям найти нас и увидеть, что проект уже стал полезным для многих. ## Отслеживать свежие выпуски в репозитории на GitHub -Вы можете "отслеживать" FastAPI на GitHub (кликните по кнопке "watch" наверху справа): https://github.com/tiangolo/fastapi. 👀 +Вы можете "отслеживать" FastAPI на GitHub (кликните по кнопке "watch" наверху справа): https://github.com/fastapi/fastapi. 👀 Там же Вы можете указать в настройках - "Releases only". @@ -59,7 +59,7 @@ ## Оставить сообщение в Twitter о **FastAPI** -Оставьте сообщение в Twitter о **FastAPI** и позвольте мне и другим узнать - почему он Вам нравится. 🎉 +Оставьте сообщение в Twitter о **FastAPI** и позвольте мне и другим узнать - почему он Вам нравится. 🎉 Я люблю узнавать о том, как **FastAPI** используется, что Вам понравилось в нём, в каких проектах/компаниях Вы используете его и т.п. @@ -71,9 +71,9 @@ ## Помочь другим с их проблемами на GitHub -Вы можете посмотреть, какие проблемы испытывают другие люди и попытаться помочь им. Чаще всего это вопросы, на которые, весьма вероятно, Вы уже знаете ответ. 🤓 +Вы можете посмотреть, какие проблемы испытывают другие люди и попытаться помочь им. Чаще всего это вопросы, на которые, весьма вероятно, Вы уже знаете ответ. 🤓 -Если Вы будете много помогать людям с решением их проблем, Вы можете стать официальным [Экспертом FastAPI](fastapi-people.md#experts){.internal-link target=_blank}. 🎉 +Если Вы будете много помогать людям с решением их проблем, Вы можете стать официальным [Экспертом FastAPI](fastapi-people.md#_3){.internal-link target=_blank}. 🎉 Только помните, самое важное при этом - доброта. Столкнувшись с проблемой, люди расстраиваются и часто задают вопросы не лучшим образом, но постарайтесь быть максимально доброжелательным. 🤗 @@ -117,7 +117,7 @@ ## Отслеживать репозиторий на GitHub -Вы можете "отслеживать" FastAPI на GitHub (кликните по кнопке "watch" наверху справа): https://github.com/tiangolo/fastapi. 👀 +Вы можете "отслеживать" FastAPI на GitHub (кликните по кнопке "watch" наверху справа): https://github.com/fastapi/fastapi. 👀 Если Вы выберете "Watching" вместо "Releases only", то будете получать уведомления когда кто-либо попросит о помощи с решением его проблемы. @@ -125,7 +125,7 @@ ## Запросить помощь с решением проблемы -Вы можете создать новый запрос с просьбой о помощи в репозитории на GitHub, например: +Вы можете создать новый запрос с просьбой о помощи в репозитории на GitHub, например: * Задать **вопрос** или попросить помощи в решении **проблемы**. * Предложить новое **улучшение**. @@ -162,12 +162,15 @@ * Затем, используя **комментарий**, сообщите, что Вы сделали проверку, тогда я буду знать, что Вы действительно проверили код. -!!! Информация - К сожалению, я не могу так просто доверять пул-реквестам, у которых уже есть несколько одобрений. +/// info | Информация - Бывали случаи, что пул-реквесты имели 3, 5 или больше одобрений, вероятно из-за привлекательного описания, но когда я проверял эти пул-реквесты, они оказывались сломаны, содержали ошибки или вовсе не решали проблему, которую, как они утверждали, должны были решить. 😅 +К сожалению, я не могу так просто доверять пул-реквестам, у которых уже есть несколько одобрений. - Потому это действительно важно - проверять и запускать код, и комментарием уведомлять меня, что Вы проделали эти действия. 🤓 +Бывали случаи, что пул-реквесты имели 3, 5 или больше одобрений, вероятно из-за привлекательного описания, но когда я проверял эти пул-реквесты, они оказывались сломаны, содержали ошибки или вовсе не решали проблему, которую, как они утверждали, должны были решить. 😅 + +Потому это действительно важно - проверять и запускать код, и комментарием уведомлять меня, что Вы проделали эти действия. 🤓 + +/// * Если Вы считаете, что пул-реквест можно упростить, то можете попросить об этом, но не нужно быть слишком придирчивым, может быть много субъективных точек зрения (и у меня тоже будет своя 🙈), поэтому будет лучше, если Вы сосредоточитесь на фундаментальных вещах. @@ -188,9 +191,9 @@ Вы можете [сделать вклад](contributing.md){.internal-link target=_blank} в код фреймворка используя пул-реквесты, например: * Исправить опечатку, которую Вы нашли в документации. -* Поделиться статьёй, видео или подкастом о FastAPI, которые Вы создали или нашли изменив этот файл. +* Поделиться статьёй, видео или подкастом о FastAPI, которые Вы создали или нашли изменив этот файл. * Убедитесь, что Вы добавили свою ссылку в начало соответствующего раздела. -* Помочь с [переводом документации](contributing.md#translations){.internal-link target=_blank} на Ваш язык. +* Помочь с [переводом документации](contributing.md#_8){.internal-link target=_blank} на Ваш язык. * Вы также можете проверять переводы сделанные другими. * Предложить новые разделы документации. * Исправить существующуе проблемы/баги. @@ -207,8 +210,8 @@ Основные задачи, которые Вы можете выполнить прямо сейчас: -* [Помочь другим с их проблемами на GitHub](#help-others-with-issues-in-github){.internal-link target=_blank} (смотрите вышестоящую секцию). -* [Проверить пул-реквесты](#review-pull-requests){.internal-link target=_blank} (смотрите вышестоящую секцию). +* [Помочь другим с их проблемами на GitHub](#github_1){.internal-link target=_blank} (смотрите вышестоящую секцию). +* [Проверить пул-реквесты](#-){.internal-link target=_blank} (смотрите вышестоящую секцию). Эти две задачи **отнимают больше всего времени**. Это основная работа по поддержке FastAPI. @@ -218,10 +221,13 @@ Подключайтесь к 👥 чату в Discord 👥 и общайтесь с другими участниками сообщества FastAPI. -!!! Подсказка - Вопросы по проблемам с фреймворком лучше задавать в GitHub issues, так больше шансов, что Вы получите помощь от [Экспертов FastAPI](fastapi-people.md#experts){.internal-link target=_blank}. +/// tip | Подсказка + +Вопросы по проблемам с фреймворком лучше задавать в GitHub issues, так больше шансов, что Вы получите помощь от [Экспертов FastAPI](fastapi-people.md#_3){.internal-link target=_blank}. + +Используйте этот чат только для бесед на отвлечённые темы. - Используйте этот чат только для бесед на отвлечённые темы. +/// ### Не использовать чаты для вопросов @@ -229,7 +235,7 @@ В разделе "проблемы" на GitHub, есть шаблон, который поможет Вам написать вопрос правильно, чтобы Вам было легче получить хороший ответ или даже решить проблему самостоятельно, прежде чем Вы зададите вопрос. В GitHub я могу быть уверен, что всегда отвечаю на всё, даже если это займет какое-то время. И я не могу сделать то же самое в чатах. 😅 -Кроме того, общение в чатах не так легкодоступно для поиска, как в GitHub, потому вопросы и ответы могут потеряться среди другого общения. И только проблемы решаемые на GitHub учитываются в получении лычки [Эксперт FastAPI](fastapi-people.md#experts){.internal-link target=_blank}, так что весьма вероятно, что Вы получите больше внимания на GitHub. +Кроме того, общение в чатах не так легкодоступно для поиска, как в GitHub, потому вопросы и ответы могут потеряться среди другого общения. И только проблемы решаемые на GitHub учитываются в получении лычки [Эксперт FastAPI](fastapi-people.md#_3){.internal-link target=_blank}, так что весьма вероятно, что Вы получите больше внимания на GitHub. С другой стороны, в чатах тысячи пользователей, а значит есть большие шансы в любое время найти там кого-то, с кем можно поговорить. 😄 diff --git a/docs/ru/docs/history-design-future.md b/docs/ru/docs/history-design-future.md index 2a5e428b1..96604e3a4 100644 --- a/docs/ru/docs/history-design-future.md +++ b/docs/ru/docs/history-design-future.md @@ -1,6 +1,6 @@ # История создания и дальнейшее развитие -Однажды, один из пользователей **FastAPI** задал вопрос: +Однажды, один из пользователей **FastAPI** задал вопрос: > Какова история этого проекта? Создаётся впечатление, что он явился из ниоткуда и завоевал мир за несколько недель [...] @@ -52,7 +52,7 @@ ## Зависимости -Протестировав несколько вариантов, я решил, что в качестве основы буду использовать **Pydantic** и его преимущества. +Протестировав несколько вариантов, я решил, что в качестве основы буду использовать **Pydantic** и его преимущества. По моим предложениям был изменён код этого фреймворка, чтобы сделать его полностью совместимым с JSON Schema, поддержать различные способы определения ограничений и улучшить помощь редакторов (проверки типов, автозаполнение). diff --git a/docs/ru/docs/index.md b/docs/ru/docs/index.md index 6c99f623d..a9546cf1e 100644 --- a/docs/ru/docs/index.md +++ b/docs/ru/docs/index.md @@ -1,3 +1,9 @@ +# FastAPI + + +

FastAPI

@@ -5,11 +11,11 @@ Готовый к внедрению высокопроизводительный фреймворк, простой в изучении и разработке.

- - Test + + Test - - Coverage + + Coverage Package version @@ -23,11 +29,11 @@ **Документация**: https://fastapi.tiangolo.com -**Исходный код**: https://github.com/tiangolo/fastapi +**Исходный код**: https://github.com/fastapi/fastapi --- -FastAPI — это современный, быстрый (высокопроизводительный) веб-фреймворк для создания API используя Python 3.8+, в основе которого лежит стандартная аннотация типов Python. +FastAPI — это современный, быстрый (высокопроизводительный) веб-фреймворк для создания API используя Python, в основе которого лежит стандартная аннотация типов Python. Ключевые особенности: @@ -63,7 +69,7 @@ FastAPI — это современный, быстрый (высокопрои "_В последнее время я много где использую **FastAPI**. [...] На самом деле я планирую использовать его для всех **сервисов машинного обучения моей команды в Microsoft**. Некоторые из них интегрируются в основной продукт **Windows**, а некоторые — в продукты **Office**._" -

Kabir Khan - Microsoft (ref)
+
Kabir Khan - Microsoft (ref)
--- @@ -87,7 +93,7 @@ FastAPI — это современный, быстрый (высокопрои "_Честно говоря, то, что вы создали, выглядит очень солидно и отполировано. Во многих смыслах я хотел, чтобы **Hug** был именно таким — это действительно вдохновляет, когда кто-то создаёт такое._" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- @@ -109,12 +115,10 @@ FastAPI — это современный, быстрый (высокопрои ## Зависимости -Python 3.8+ - FastAPI стоит на плечах гигантов: * Starlette для части связанной с вебом. -* Pydantic для части связанной с данными. +* Pydantic для части связанной с данными. ## Установка @@ -128,7 +132,7 @@ $ pip install fastapi
-Вам также понадобится сервер ASGI для производства, такой как Uvicorn или Hypercorn. +Вам также понадобится сервер ASGI для производства, такой как Uvicorn или Hypercorn.
@@ -325,7 +329,7 @@ def update_item(item_id: int, item: Item): Вам не нужно изучать новый синтаксис, методы или классы конкретной библиотеки и т. д. -Только стандартный **Python 3.8+**. +Только стандартный **Python**. Например, для `int`: @@ -439,21 +443,21 @@ item: Item Используется Pydantic: -* email_validator - для проверки электронной почты. +* email-validator - для проверки электронной почты. Используется Starlette: * HTTPX - Обязательно, если вы хотите использовать `TestClient`. * jinja2 - Обязательно, если вы хотите использовать конфигурацию шаблона по умолчанию. -* python-multipart - Обязательно, если вы хотите поддерживать форму "парсинга" с помощью `request.form()`. +* python-multipart - Обязательно, если вы хотите поддерживать форму "парсинга" с помощью `request.form()`. * itsdangerous - Обязательно, для поддержки `SessionMiddleware`. * pyyaml - Обязательно, для поддержки `SchemaGenerator` Starlette (возможно, вам это не нужно с FastAPI). -* ujson - Обязательно, если вы хотите использовать `UJSONResponse`. Используется FastAPI / Starlette: * uvicorn - сервер, который загружает и обслуживает ваше приложение. * orjson - Обязательно, если вы хотите использовать `ORJSONResponse`. +* ujson - Обязательно, если вы хотите использовать `UJSONResponse`. Вы можете установить все это с помощью `pip install "fastapi[all]"`. diff --git a/docs/ru/docs/project-generation.md b/docs/ru/docs/project-generation.md index 76253d6f2..efd6794ad 100644 --- a/docs/ru/docs/project-generation.md +++ b/docs/ru/docs/project-generation.md @@ -14,7 +14,7 @@ GitHub: **FastAPI**: +* Бэкенд построен на фреймворке **FastAPI**: * **Быстрый**: Высокопроизводительный, на уровне **NodeJS** и **Go** (благодаря Starlette и Pydantic). * **Интуитивно понятный**: Отличная поддержка редактора. Автодополнение кода везде. Меньше времени на отладку. * **Простой**: Разработан так, чтоб быть простым в использовании и изучении. Меньше времени на чтение документации. diff --git a/docs/ru/docs/python-types.md b/docs/ru/docs/python-types.md index 7523083c8..b1d4715fd 100644 --- a/docs/ru/docs/python-types.md +++ b/docs/ru/docs/python-types.md @@ -12,16 +12,18 @@ Python имеет поддержку необязательных аннотац Но даже если вы никогда не используете **FastAPI**, вам будет полезно немного узнать о них. -!!! note - Если вы являетесь экспертом в Python и уже знаете всё об аннотациях типов, переходите к следующему разделу. +/// note + +Если вы являетесь экспертом в Python и уже знаете всё об аннотациях типов, переходите к следующему разделу. + +/// ## Мотивация Давайте начнем с простого примера: -```Python -{!../../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} + Вызов этой программы выводит: @@ -35,9 +37,8 @@ John Doe * Преобразует первую букву содержимого каждой переменной в верхний регистр с `title()`. * Соединяет их через пробел. -```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### Отредактируем пример @@ -79,9 +80,8 @@ John Doe Это аннотации типов: -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + Это не то же самое, что объявление значений по умолчанию, например: @@ -109,9 +109,8 @@ John Doe Проверьте эту функцию, она уже имеет аннотации типов: -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + Поскольку редактор знает типы переменных, вы получаете не только дополнение, но и проверки ошибок: @@ -119,9 +118,8 @@ John Doe Теперь вы знаете, что вам нужно исправить, преобразовав `age` в строку с `str(age)`: -```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## Объявление типов @@ -140,9 +138,8 @@ John Doe * `bool` * `bytes` -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### Generic-типы с параметрами типов @@ -158,9 +155,8 @@ John Doe Импортируйте `List` из `typing` (с заглавной `L`): -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[1] *} + Объявите переменную с тем же синтаксисом двоеточия (`:`). @@ -168,14 +164,16 @@ John Doe Поскольку список является типом, содержащим некоторые внутренние типы, вы помещаете их в квадратные скобки: -```Python hl_lines="4" -{!../../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[4] *} + -!!! tip - Эти внутренние типы в квадратных скобках называются «параметрами типов». +/// tip - В этом случае `str` является параметром типа, передаваемым в `List`. +Эти внутренние типы в квадратных скобках называются «параметрами типов». + +В этом случае `str` является параметром типа, передаваемым в `List`. + +/// Это означает: "переменная `items` является `list`, и каждый из элементов этого списка является `str`". @@ -193,9 +191,8 @@ John Doe Вы бы сделали то же самое, чтобы объявить `tuple` и `set`: -```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial007.py!} -``` +{* ../../docs_src/python_types/tutorial007.py hl[1,4] *} + Это означает: @@ -210,9 +207,8 @@ John Doe Второй параметр типа предназначен для значений `dict`: -```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial008.py!} -``` +{* ../../docs_src/python_types/tutorial008.py hl[1,4] *} + Это означает: @@ -225,7 +221,7 @@ John Doe Вы также можете использовать `Optional`, чтобы объявить, что переменная имеет тип, например, `str`, но это является «необязательным», что означает, что она также может быть `None`: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` Использование `Optional[str]` вместо просто `str` позволит редактору помочь вам в обнаружении ошибок, в которых вы могли бы предположить, что значение всегда является `str`, хотя на самом деле это может быть и `None`. @@ -249,15 +245,13 @@ John Doe Допустим, у вас есть класс `Person` с полем `name`: -```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + Тогда вы можете объявить переменную типа `Person`: -```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + И снова вы получаете полную поддержку редактора: @@ -265,7 +259,7 @@ John Doe ## Pydantic-модели -Pydantic является Python-библиотекой для выполнения валидации данных. +Pydantic является Python-библиотекой для выполнения валидации данных. Вы объявляете «форму» данных как классы с атрибутами. @@ -277,12 +271,14 @@ John Doe Взято из официальной документации Pydantic: -```Python -{!../../../docs_src/python_types/tutorial011.py!} -``` +{* ../../docs_src/python_types/tutorial011.py *} + -!!! info - Чтобы узнать больше о Pydantic, читайте его документацию. +/// info + +Чтобы узнать больше о Pydantic, читайте его документацию. + +/// **FastAPI** целиком основан на Pydantic. @@ -310,5 +306,8 @@ John Doe Важно то, что при использовании стандартных типов Python в одном месте (вместо добавления дополнительных классов, декораторов и т.д.) **FastAPI** сделает за вас большую часть работы. -!!! info - Если вы уже прошли всё руководство и вернулись, чтобы узнать больше о типах, хорошим ресурсом является «шпаргалка» от `mypy`. +/// info + +Если вы уже прошли всё руководство и вернулись, чтобы узнать больше о типах, хорошим ресурсом является «шпаргалка» от `mypy`. + +/// diff --git a/docs/ru/docs/tutorial/background-tasks.md b/docs/ru/docs/tutorial/background-tasks.md index 73ba860bc..bf2e9dec3 100644 --- a/docs/ru/docs/tutorial/background-tasks.md +++ b/docs/ru/docs/tutorial/background-tasks.md @@ -15,9 +15,7 @@ Сначала импортируйте `BackgroundTasks`, потом добавьте в функцию параметр с типом `BackgroundTasks`: -```Python hl_lines="1 13" -{!../../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *} **FastAPI** создаст объект класса `BackgroundTasks` для вас и запишет его в параметр. @@ -33,17 +31,13 @@ Так как операция записи не использует `async` и `await`, мы определим ее как обычную `def`: -```Python hl_lines="6-9" -{!../../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *} ## Добавление фоновой задачи Внутри функции вызовите метод `.add_task()` у объекта *background tasks* и передайте ему функцию, которую хотите выполнить в фоне: -```Python hl_lines="14" -{!../../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[14] *} `.add_task()` принимает следующие аргументы: @@ -57,17 +51,7 @@ **FastAPI** знает, что нужно сделать в каждом случае и как переиспользовать тот же объект `BackgroundTasks`, так чтобы все фоновые задачи собрались и запустились вместе в фоне: -=== "Python 3.10+" - - ```Python hl_lines="11 13 20 23" - {!> ../../../docs_src/background_tasks/tutorial002_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002.py!} - ``` +{* ../../docs_src/background_tasks/tutorial002_py310.py hl[11,13,20,23] *} В этом примере сообщения будут записаны в `log.txt` *после* того, как ответ сервера был отправлен. @@ -93,8 +77,6 @@ Их тяжелее настраивать, также им нужен брокер сообщений наподобие RabbitMQ или Redis, но зато они позволяют вам запускать фоновые задачи в нескольких процессах и даже на нескольких серверах. -Для примера, посмотрите [Project Generators](../project-generation.md){.internal-link target=_blank}, там есть проект с уже настроенным Celery. - Но если вам нужен доступ к общим переменным и объектам вашего **FastAPI** приложения или вам нужно выполнять простые фоновые задачи (наподобие отправки письма из примера) вы можете просто использовать `BackgroundTasks`. ## Резюме diff --git a/docs/ru/docs/tutorial/bigger-applications.md b/docs/ru/docs/tutorial/bigger-applications.md new file mode 100644 index 000000000..7c3dc288f --- /dev/null +++ b/docs/ru/docs/tutorial/bigger-applications.md @@ -0,0 +1,556 @@ +# Большие приложения, в которых много файлов + +При построении приложения или веб-API нам редко удается поместить всё в один файл. + +**FastAPI** предоставляет удобный инструментарий, который позволяет нам структурировать приложение, сохраняя при этом всю необходимую гибкость. + +/// info | Примечание + +Если вы раньше использовали Flask, то это аналог шаблонов Flask (Flask's Blueprints). + +/// + +## Пример структуры приложения + +Давайте предположим, что наше приложение имеет следующую структуру: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   ├── dependencies.py +│   └── routers +│   │ ├── __init__.py +│   │ ├── items.py +│   │ └── users.py +│   └── internal +│   ├── __init__.py +│   └── admin.py +``` + +/// tip | Подсказка + +Обратите внимание, что в каждом каталоге и подкаталоге имеется файл `__init__.py` + +Это как раз то, что позволяет импортировать код из одного файла в другой. + +Например, в файле `app/main.py` может быть следующая строка: + +``` +from app.routers import items +``` + +/// + +* Всё помещается в каталоге `app`. В нём также находится пустой файл `app/__init__.py`. Таким образом, `app` является "Python-пакетом" (коллекцией модулей Python). +* Он содержит файл `app/main.py`. Данный файл является частью пакета (т.е. находится внутри каталога, содержащего файл `__init__.py`), и, соответственно, он является модулем пакета: `app.main`. +* Он также содержит файл `app/dependencies.py`, который также, как и `app/main.py`, является модулем: `app.dependencies`. +* Здесь также находится подкаталог `app/routers/`, содержащий `__init__.py`. Он является суб-пакетом: `app.routers`. +* Файл `app/routers/items.py` находится внутри пакета `app/routers/`. Таким образом, он является суб-модулем: `app.routers.items`. +* Точно также `app/routers/users.py` является ещё одним суб-модулем: `app.routers.users`. +* Подкаталог `app/internal/`, содержащий файл `__init__.py`, является ещё одним суб-пакетом: `app.internal`. +* А файл `app/internal/admin.py` является ещё одним суб-модулем: `app.internal.admin`. + + + +Та же самая файловая структура приложения, но с комментариями: + +``` +. +├── app # "app" пакет +│   ├── __init__.py # этот файл превращает "app" в "Python-пакет" +│   ├── main.py # модуль "main", напр.: import app.main +│   ├── dependencies.py # модуль "dependencies", напр.: import app.dependencies +│   └── routers # суб-пакет "routers" +│   │ ├── __init__.py # превращает "routers" в суб-пакет +│   │ ├── items.py # суб-модуль "items", напр.: import app.routers.items +│   │ └── users.py # суб-модуль "users", напр.: import app.routers.users +│   └── internal # суб-пакет "internal" +│   ├── __init__.py # превращает "internal" в суб-пакет +│   └── admin.py # суб-модуль "admin", напр.: import app.internal.admin +``` + +## `APIRouter` + +Давайте предположим, что для работы с пользователями используется отдельный файл (суб-модуль) `/app/routers/users.py`. + +Для лучшей организации приложения, вы хотите отделить операции пути, связанные с пользователями, от остального кода. + +Но так, чтобы эти операции по-прежнему оставались частью **FastAPI** приложения/веб-API (частью одного пакета) + +С помощью `APIRouter` вы можете создать *операции пути* (*эндпоинты*) для данного модуля. + + +### Импорт `APIRouter` + +Точно также, как и в случае с классом `FastAPI`, вам нужно импортировать и создать объект класса `APIRouter`. + +```Python hl_lines="1 3" title="app/routers/users.py" +{!../../docs_src/bigger_applications/app/routers/users.py!} +``` + +### Создание *эндпоинтов* с помощью `APIRouter` + +В дальнейшем используйте `APIRouter` для объявления *эндпоинтов*, точно также, как вы используете класс `FastAPI`: + +```Python hl_lines="6 11 16" title="app/routers/users.py" +{!../../docs_src/bigger_applications/app/routers/users.py!} +``` + +Вы можете думать об `APIRouter` как об "уменьшенной версии" класса FastAPI`. + +`APIRouter` поддерживает все те же самые опции. + +`APIRouter` поддерживает все те же самые параметры, такие как `parameters`, `responses`, `dependencies`, `tags`, и т. д. + +/// tip | Подсказка + +В данном примере, в качестве названия переменной используется `router`, но вы можете использовать любое другое имя. + +/// + +Мы собираемся подключить данный `APIRouter` к нашему основному приложению на `FastAPI`, но сначала давайте проверим зависимости и создадим ещё один модуль с `APIRouter`. + +## Зависимости + +Нам понадобятся некоторые зависимости, которые мы будем использовать в разных местах нашего приложения. + +Мы поместим их в отдельный модуль `dependencies` (`app/dependencies.py`). + +Теперь мы воспользуемся простой зависимостью, чтобы прочитать кастомизированный `X-Token` из заголовка: + +//// tab | Python 3.9+ + +```Python hl_lines="3 6-8" title="app/dependencies.py" +{!> ../../docs_src/bigger_applications/app_an_py39/dependencies.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1 5-7" title="app/dependencies.py" +{!> ../../docs_src/bigger_applications/app_an/dependencies.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Подсказка + +Мы рекомендуем использовать версию `Annotated`, когда это возможно. + +/// + +```Python hl_lines="1 4-6" title="app/dependencies.py" +{!> ../../docs_src/bigger_applications/app/dependencies.py!} +``` + +//// + +/// tip | Подсказка + +Для простоты мы воспользовались неким воображаемым заголовоком. + +В реальных случаях для получения наилучших результатов используйте интегрированные утилиты обеспечения безопасности [Security utilities](security/index.md){.internal-link target=_blank}. + +/// + +## Ещё один модуль с `APIRouter` + +Давайте также предположим, что у вас есть *эндпоинты*, отвечающие за обработку "items", и они находятся в модуле `app/routers/items.py`. + +У вас определены следующие *операции пути* (*эндпоинты*): + +* `/items/` +* `/items/{item_id}` + +Тут всё точно также, как и в ситуации с `app/routers/users.py`. + +Но теперь мы хотим поступить немного умнее и слегка упростить код. + +Мы знаем, что все *эндпоинты* данного модуля имеют некоторые общие свойства: + +* Префикс пути: `/items`. +* Теги: (один единственный тег: `items`). +* Дополнительные ответы (responses) +* Зависимости: использование созданной нами зависимости `X-token` + +Таким образом, вместо того чтобы добавлять все эти свойства в функцию каждого отдельного *эндпоинта*, +мы добавим их в `APIRouter`. + +```Python hl_lines="5-10 16 21" title="app/routers/items.py" +{!../../docs_src/bigger_applications/app/routers/items.py!} +``` + +Так как каждый *эндпоинт* начинается с символа `/`: + +```Python hl_lines="1" +@router.get("/{item_id}") +async def read_item(item_id: str): + ... +``` + +...то префикс не должен заканчиваться символом `/`. + +В нашем случае префиксом является `/items`. + +Мы также можем добавить в наш маршрутизатор (router) список `тегов` (`tags`) и дополнительных `ответов` (`responses`), которые являются общими для каждого *эндпоинта*. + +И ещё мы можем добавить в наш маршрутизатор список `зависимостей`, которые должны вызываться при каждом обращении к *эндпоинтам*. + +/// tip | Подсказка + +Обратите внимание, что также, как и в случае с зависимостями в декораторах *эндпоинтов* ([dependencies in *path operation decorators*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}), никакого значения в *функцию эндпоинта* передано не будет. + +/// + +В результате мы получим следующие эндпоинты: + +* `/items/` +* `/items/{item_id}` + +...как мы и планировали. + +* Они будут помечены тегами из заданного списка, в нашем случае это `"items"`. + * Эти теги особенно полезны для системы автоматической интерактивной документации (с использованием OpenAPI). +* Каждый из них будет включать предопределенные ответы `responses`. +* Каждый *эндпоинт* будет иметь список зависимостей (`dependencies`), исполняемых перед вызовом *эндпоинта*. + * Если вы определили зависимости в самой операции пути, **то она также будет выполнена**. + * Сначала выполняются зависимости маршрутизатора, затем вызываются зависимости, определенные в декораторе *эндпоинта* ([`dependencies` in the decorator](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}), и, наконец, обычные параметрические зависимости. + * Вы также можете добавить зависимости безопасности с областями видимости (`scopes`) [`Security` dependencies with `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}. + +/// tip | Подсказка + +Например, с помощью зависимостей в `APIRouter` мы можем потребовать аутентификации для доступа ко всей группе *эндпоинтов*, не указывая зависимости для каждой отдельной функции *эндпоинта*. + +/// + +/// check | Заметка + +Параметры `prefix`, `tags`, `responses` и `dependencies` относятся к функционалу **FastAPI**, помогающему избежать дублирования кода. + +/// + +### Импорт зависимостей + +Наш код находится в модуле `app.routers.items` (файл `app/routers/items.py`). + +И нам нужно вызвать функцию зависимости из модуля `app.dependencies` (файл `app/dependencies.py`). + +Мы используем операцию относительного импорта `..` для импорта зависимости: + +```Python hl_lines="3" title="app/routers/items.py" +{!../../docs_src/bigger_applications/app/routers/items.py!} +``` + +#### Как работает относительный импорт? + +/// tip | Подсказка + +Если вы прекрасно знаете, как работает импорт в Python, то переходите к следующему разделу. + +/// + +Одна точка `.`, как в данном примере: + +```Python +from .dependencies import get_token_header +``` +означает: + +* Начните с пакета, в котором находится данный модуль (файл `app/routers/items.py` расположен в каталоге `app/routers/`)... +* ... найдите модуль `dependencies` (файл `app/routers/dependencies.py`)... +* ... и импортируйте из него функцию `get_token_header`. + +К сожалению, такого файла не существует, и наши зависимости находятся в файле `app/dependencies.py`. + +Вспомните, как выглядит файловая структура нашего приложения: + + + +--- + +Две точки `..`, как в данном примере: + +```Python +from ..dependencies import get_token_header +``` + +означают: + +* Начните с пакета, в котором находится данный модуль (файл `app/routers/items.py` находится в каталоге `app/routers/`)... +* ... перейдите в родительский пакет (каталог `app/`)... +* ... найдите в нём модуль `dependencies` (файл `app/dependencies.py`)... +* ... и импортируйте из него функцию `get_token_header`. + +Это работает верно! 🎉 + +--- + +Аналогично, если бы мы использовали три точки `...`, как здесь: + +```Python +from ...dependencies import get_token_header +``` + +то это бы означало: + +* Начните с пакета, в котором находится данный модуль (файл `app/routers/items.py` находится в каталоге `app/routers/`)... +* ... перейдите в родительский пакет (каталог `app/`)... +* ... затем перейдите в родительский пакет текущего пакета (такого пакета не существует, `app` находится на самом верхнем уровне 😱)... +* ... найдите в нём модуль `dependencies` (файл `app/dependencies.py`)... +* ... и импортируйте из него функцию `get_token_header`. + +Это будет относиться к некоторому пакету, находящемуся на один уровень выше чем `app/` и содержащему свой собственный файл `__init__.py`. Но ничего такого у нас нет. Поэтому это приведет к ошибке в нашем примере. 🚨 + +Теперь вы знаете, как работает импорт в Python, и сможете использовать относительное импортирование в своих собственных приложениях любого уровня сложности. 🤓 + +### Добавление пользовательских тегов (`tags`), ответов (`responses`) и зависимостей (`dependencies`) + +Мы не будем добавлять префикс `/items` и список тегов `tags=["items"]` для каждого *эндпоинта*, т.к. мы уже их добавили с помощью `APIRouter`. + +Но помимо этого мы можем добавить новые теги для каждого отдельного *эндпоинта*, а также некоторые дополнительные ответы (`responses`), характерные для данного *эндпоинта*: + +```Python hl_lines="30-31" title="app/routers/items.py" +{!../../docs_src/bigger_applications/app/routers/items.py!} +``` + +/// tip | Подсказка + +Последний *эндпоинт* будет иметь следующую комбинацию тегов: `["items", "custom"]`. + +А также в его документации будут содержаться оба ответа: один для `404` и другой для `403`. + +/// + +## Модуль main в `FastAPI` + +Теперь давайте посмотрим на модуль `app/main.py`. + +Именно сюда вы импортируете и именно здесь вы используете класс `FastAPI`. + +Это основной файл вашего приложения, который объединяет всё в одно целое. + +И теперь, когда большая часть логики приложения разделена на отдельные модули, основной файл `app/main.py` будет достаточно простым. + +### Импорт `FastAPI` + +Вы импортируете и создаете класс `FastAPI` как обычно. + +Мы даже можем объявить глобальные зависимости [global dependencies](dependencies/global-dependencies.md){.internal-link target=_blank}, которые будут объединены с зависимостями для каждого отдельного маршрутизатора: + +```Python hl_lines="1 3 7" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +### Импорт `APIRouter` + +Теперь мы импортируем другие суб-модули, содержащие `APIRouter`: + +```Python hl_lines="4-5" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +Так как файлы `app/routers/users.py` и `app/routers/items.py` являются суб-модулями одного и того же Python-пакета `app`, то мы сможем их импортировать, воспользовавшись операцией относительного импорта `.`. + +### Как работает импорт? + +Данная строка кода: + +```Python +from .routers import items, users +``` + +означает: + +* Начните с пакета, в котором содержится данный модуль (файл `app/main.py` содержится в каталоге `app/`)... +* ... найдите суб-пакет `routers` (каталог `app/routers/`)... +* ... и из него импортируйте суб-модули `items` (файл `app/routers/items.py`) и `users` (файл `app/routers/users.py`)... + +В модуле `items` содержится переменная `router` (`items.router`), та самая, которую мы создали в файле `app/routers/items.py`, она является объектом класса `APIRouter`. + +И затем мы сделаем то же самое для модуля `users`. + +Мы также могли бы импортировать и другим методом: + +```Python +from app.routers import items, users +``` + +/// info | Примечание + +Первая версия является примером относительного импорта: + +```Python +from .routers import items, users +``` + +Вторая версия является примером абсолютного импорта: + +```Python +from app.routers import items, users +``` + +Узнать больше о пакетах и модулях в Python вы можете из официальной документации Python о модулях + +/// + +### Избегайте конфликтов имен + +Вместо того чтобы импортировать только переменную `router`, мы импортируем непосредственно суб-модуль `items`. + +Мы делаем это потому, что у нас есть ещё одна переменная `router` в суб-модуле `users`. + +Если бы мы импортировали их одну за другой, как показано в примере: + +```Python +from .routers.items import router +from .routers.users import router +``` + +то переменная `router` из `users` переписал бы переменную `router` из `items`, и у нас не было бы возможности использовать их одновременно. + +Поэтому, для того чтобы использовать обе эти переменные в одном файле, мы импортировали соответствующие суб-модули: + +```Python hl_lines="5" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +### Подключение маршрутизаторов (`APIRouter`) для `users` и для `items` + +Давайте подключим маршрутизаторы (`router`) из суб-модулей `users` и `items`: + +```Python hl_lines="10-11" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +/// info | Примечание + +`users.router` содержит `APIRouter` из файла `app/routers/users.py`. + +А `items.router` содержит `APIRouter` из файла `app/routers/items.py`. + +/// + +С помощью `app.include_router()` мы можем добавить каждый из маршрутизаторов (`APIRouter`) в основное приложение `FastAPI`. + +Он подключит все маршруты заданного маршрутизатора к нашему приложению. + +/// note | Технические детали + +Фактически, внутри он создаст все *операции пути* для каждой операции пути объявленной в `APIRouter`. + +И под капотом всё будет работать так, как будто бы мы имеем дело с одним файлом приложения. + +/// + +/// check | Заметка + +При подключении маршрутизаторов не стоит беспокоиться о производительности. + +Операция подключения займёт микросекунды и понадобится только при запуске приложения. + +Таким образом, это не повлияет на производительность. ⚡ + +/// + +### Подключение `APIRouter` с пользовательскими префиксом (`prefix`), тегами (`tags`), ответами (`responses`), и зависимостями (`dependencies`) + +Теперь давайте представим, что ваша организация передала вам файл `app/internal/admin.py`. + +Он содержит `APIRouter` с некоторыми *эндпоитами* администрирования, которые ваша организация использует для нескольких проектов. + +В данном примере это сделать очень просто. Но давайте предположим, что поскольку файл используется для нескольких проектов, +то мы не можем модифицировать его, добавляя префиксы (`prefix`), зависимости (`dependencies`), теги (`tags`), и т.д. непосредственно в `APIRouter`: + +```Python hl_lines="3" title="app/internal/admin.py" +{!../../docs_src/bigger_applications/app/internal/admin.py!} +``` + +Но, несмотря на это, мы хотим использовать кастомный префикс (`prefix`) для подключенного маршрутизатора (`APIRouter`), в результате чего, каждая *операция пути* будет начинаться с `/admin`. Также мы хотим защитить наш маршрутизатор с помощью зависимостей, созданных для нашего проекта. И ещё мы хотим включить теги (`tags`) и ответы (`responses`). + +Мы можем применить все вышеперечисленные настройки, не изменяя начальный `APIRouter`. Нам всего лишь нужно передать нужные параметры в `app.include_router()`. + +```Python hl_lines="14-17" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +Таким образом, оригинальный `APIRouter` не будет модифицирован, и мы сможем использовать файл `app/internal/admin.py` сразу в нескольких проектах организации. + +В результате, в нашем приложении каждый *эндпоинт* модуля `admin` будет иметь: + +* Префикс `/admin`. +* Тег `admin`. +* Зависимость `get_token_header`. +* Ответ `418`. 🍵 + +Это будет иметь место исключительно для `APIRouter` в нашем приложении, и не затронет любой другой код, использующий его. + +Например, другие проекты, могут использовать тот же самый `APIRouter` с другими методами аутентификации. + +### Подключение отдельного *эндпоинта* + +Мы также можем добавить *эндпоинт* непосредственно в основное приложение `FastAPI`. + +Здесь мы это делаем ... просто, чтобы показать, что это возможно 🤷: + +```Python hl_lines="21-23" title="app/main.py" +{!../../docs_src/bigger_applications/app/main.py!} +``` + +и это будет работать корректно вместе с другими *эндпоинтами*, добавленными с помощью `app.include_router()`. + +/// info | Сложные технические детали + +**Примечание**: это сложная техническая деталь, которую, скорее всего, **вы можете пропустить**. + +--- + +Маршрутизаторы (`APIRouter`) не "монтируются" по-отдельности и не изолируются от остального приложения. + +Это происходит потому, что нужно включить их *эндпоинты* в OpenAPI схему и в интерфейс пользователя. + +В силу того, что мы не можем их изолировать и "примонтировать" независимо от остальных, *эндпоинты* клонируются (пересоздаются) и не подключаются напрямую. + +/// + +## Проверка автоматической документации API + +Теперь запустите приложение: + +
+ +```console +$ fastapi dev app/main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Откройте документацию по адресу http://127.0.0.1:8000/docs. + +Вы увидите автоматическую API документацию. Она включает в себя маршруты из суб-модулей, используя верные маршруты, префиксы и теги: + + + +## Подключение существующего маршрута через новый префикс (`prefix`) + +Вы можете использовать `.include_router()` несколько раз с одним и тем же маршрутом, применив различные префиксы. + +Это может быть полезным, если нужно предоставить доступ к одному и тому же API через различные префиксы, например, `/api/v1` и `/api/latest`. + +Это продвинутый способ, который вам может и не пригодится. Мы приводим его на случай, если вдруг вам это понадобится. + +## Включение одного маршрутизатора (`APIRouter`) в другой + +Точно так же, как вы включаете `APIRouter` в приложение `FastAPI`, вы можете включить `APIRouter` в другой `APIRouter`: + +```Python +router.include_router(other_router) +``` + +Удостоверьтесь, что вы сделали это до того, как подключить маршрутизатор (`router`) к вашему `FastAPI` приложению, и *эндпоинты* маршрутизатора `other_router` были также подключены. diff --git a/docs/ru/docs/tutorial/body-fields.md b/docs/ru/docs/tutorial/body-fields.md index 02a598004..5ed5f59fc 100644 --- a/docs/ru/docs/tutorial/body-fields.md +++ b/docs/ru/docs/tutorial/body-fields.md @@ -6,50 +6,39 @@ Сначала вы должны импортировать его: -=== "Python 3.10+" +{* ../../docs_src/body_fields/tutorial001_py310.py hl[2] *} - ```Python hl_lines="2" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +/// warning | Внимание -=== "Python 3.8+" +Обратите внимание, что функция `Field` импортируется непосредственно из `pydantic`, а не из `fastapi`, как все остальные функции (`Query`, `Path`, `Body` и т.д.). - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` - -!!! warning "Внимание" - Обратите внимание, что функция `Field` импортируется непосредственно из `pydantic`, а не из `fastapi`, как все остальные функции (`Query`, `Path`, `Body` и т.д.). +/// ## Объявление атрибутов модели Вы можете использовать функцию `Field` с атрибутами модели: -=== "Python 3.10+" +{* ../../docs_src/body_fields/tutorial001_py310.py hl[9:12] *} - ```Python hl_lines="9-12" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +Функция `Field` работает так же, как `Query`, `Path` и `Body`, у неё такие же параметры и т.д. -=== "Python 3.8+" +/// note | Технические детали - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +На самом деле, `Query`, `Path` и другие функции, которые вы увидите в дальнейшем, создают объекты подклассов общего класса `Param`, который сам по себе является подклассом `FieldInfo` из Pydantic. -Функция `Field` работает так же, как `Query`, `Path` и `Body`, у неё такие же параметры и т.д. +И `Field` (из Pydantic), и `Body`, оба возвращают объекты подкласса `FieldInfo`. -!!! note "Технические детали" - На самом деле, `Query`, `Path` и другие функции, которые вы увидите в дальнейшем, создают объекты подклассов общего класса `Param`, который сам по себе является подклассом `FieldInfo` из Pydantic. +У класса `Body` есть и другие подклассы, с которыми вы ознакомитесь позже. - И `Field` (из Pydantic), и `Body`, оба возвращают объекты подкласса `FieldInfo`. +Помните, что когда вы импортируете `Query`, `Path` и другое из `fastapi`, это фактически функции, которые возвращают специальные классы. - У класса `Body` есть и другие подклассы, с которыми вы ознакомитесь позже. +/// - Помните, что когда вы импортируете `Query`, `Path` и другое из `fastapi`, это фактически функции, которые возвращают специальные классы. +/// tip | Подсказка -!!! tip "Подсказка" - Обратите внимание, что каждый атрибут модели с типом, значением по умолчанию и `Field` имеет ту же структуру, что и параметр *функции обработки пути* с `Field` вместо `Path`, `Query` и `Body`. +Обратите внимание, что каждый атрибут модели с типом, значением по умолчанию и `Field` имеет ту же структуру, что и параметр *функции обработки пути* с `Field` вместо `Path`, `Query` и `Body`. + +/// ## Добавление дополнительной информации @@ -58,9 +47,12 @@ Вы узнаете больше о добавлении дополнительной информации позже в документации, когда будете изучать, как задавать примеры принимаемых данных. -!!! warning "Внимание" - Дополнительные ключи, переданные в функцию `Field`, также будут присутствовать в сгенерированной OpenAPI схеме вашего приложения. - Поскольку эти ключи не являются обязательной частью спецификации OpenAPI, некоторые инструменты OpenAPI, например, [валидатор OpenAPI](https://validator.swagger.io/), могут не работать с вашей сгенерированной схемой. +/// warning | Внимание + +Дополнительные ключи, переданные в функцию `Field`, также будут присутствовать в сгенерированной OpenAPI схеме вашего приложения. +Поскольку эти ключи не являются обязательной частью спецификации OpenAPI, некоторые инструменты OpenAPI, например, [валидатор OpenAPI](https://validator.swagger.io/), могут не работать с вашей сгенерированной схемой. + +/// ## Резюме diff --git a/docs/ru/docs/tutorial/body-multiple-params.md b/docs/ru/docs/tutorial/body-multiple-params.md index e52ef6f6f..9300aa1bd 100644 --- a/docs/ru/docs/tutorial/body-multiple-params.md +++ b/docs/ru/docs/tutorial/body-multiple-params.md @@ -8,44 +8,13 @@ Вы также можете объявить параметры тела запроса как необязательные, установив значение по умолчанию, равное `None`: -=== "Python 3.10+" +{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *} - ```Python hl_lines="18-20" - {!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} - ``` +/// note | Заметка -=== "Python 3.9+" +Заметьте, что в данном случае параметр `item`, который будет взят из тела запроса, необязателен. Так как было установлено значение `None` по умолчанию. - ```Python hl_lines="18-20" - {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! Заметка - Рекомендуется использовать `Annotated` версию, если это возможно. - - ```Python hl_lines="17-19" - {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! Заметка - Рекомендуется использовать версию с `Annotated`, если это возможно. - - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001.py!} - ``` - -!!! Заметка - Заметьте, что в данном случае параметр `item`, который будет взят из тела запроса, необязателен. Так как было установлено значение `None` по умолчанию. +/// ## Несколько параметров тела запроса @@ -62,17 +31,7 @@ Но вы также можете объявить множество параметров тела запроса, например `item` и `user`: -=== "Python 3.10+" - - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial002.py!} - ``` +{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *} В этом случае **FastAPI** заметит, что в функции есть более одного параметра тела (два параметра, которые являются моделями Pydantic). @@ -93,9 +52,11 @@ } ``` -!!! Внимание - Обратите внимание, что хотя параметр `item` был объявлен таким же способом, как и раньше, теперь предпологается, что он находится внутри тела с ключом `item`. +/// note | Внимание + +Обратите внимание, что хотя параметр `item` был объявлен таким же способом, как и раньше, теперь предпологается, что он находится внутри тела с ключом `item`. +/// **FastAPI** сделает автоматические преобразование из запроса, так что параметр `item` получит своё конкретное содержимое, и то же самое происходит с пользователем `user`. @@ -111,41 +72,7 @@ Но вы можете указать **FastAPI** обрабатывать его, как ещё один ключ тела запроса, используя `Body`: -=== "Python 3.10+" - - ```Python hl_lines="23" - {!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="23" - {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="24" - {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! Заметка - Рекомендуется использовать `Annotated` версию, если это возможно. - - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! Заметка - Рекомендуется использовать `Annotated` версию, если это возможно. - - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial003.py!} - ``` +{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *} В этом случае, **FastAPI** будет ожидать тело запроса в формате: @@ -185,44 +112,13 @@ q: str | None = None Например: -=== "Python 3.10+" - - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="28" - {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! Заметка - Рекомендуется использовать `Annotated` версию, если это возможно. - - ```Python hl_lines="25" - {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} - ``` - -=== "Python 3.8+ non-Annotated" +{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[27] *} - !!! Заметка - Рекомендуется использовать `Annotated` версию, если это возможно. +/// info | Информация - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004.py!} - ``` +`Body` также имеет все те же дополнительные параметры валидации и метаданных, как у `Query`,`Path` и других, которые вы увидите позже. -!!! Информация - `Body` также имеет все те же дополнительные параметры валидации и метаданных, как у `Query`,`Path` и других, которые вы увидите позже. +/// ## Добавление одного body-параметра @@ -238,41 +134,7 @@ item: Item = Body(embed=True) так же, как в этом примере: -=== "Python 3.10+" - - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="18" - {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! Заметка - Рекомендуется использовать `Annotated` версию, если это возможно. - - ```Python hl_lines="15" - {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! Заметка - Рекомендуется использовать `Annotated` версию, если это возможно. - - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005.py!} - ``` +{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *} В этом случае **FastAPI** будет ожидать тело запроса в формате: diff --git a/docs/ru/docs/tutorial/body-nested-models.md b/docs/ru/docs/tutorial/body-nested-models.md index bbf9b7685..430092892 100644 --- a/docs/ru/docs/tutorial/body-nested-models.md +++ b/docs/ru/docs/tutorial/body-nested-models.md @@ -6,17 +6,7 @@ Вы можете определять атрибут как подтип. Например, тип `list` в Python: -=== "Python 3.10+" - - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial001.py!} - ``` +{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *} Это приведёт к тому, что обьект `tags` преобразуется в список, несмотря на то что тип его элементов не объявлен. @@ -30,9 +20,7 @@ Но в версиях Python до 3.9 (начиная с 3.6) сначала вам необходимо импортировать `List` из стандартного модуля `typing` в Python: -```Python hl_lines="1" -{!> ../../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *} ### Объявление `list` с указанием типов для вложенных элементов @@ -61,23 +49,7 @@ my_list: List[str] Таким образом, в нашем примере мы можем явно указать тип данных для поля `tags` как "список строк": -=== "Python 3.10+" - - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial002.py!} - ``` +{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *} ## Типы множеств @@ -87,23 +59,7 @@ my_list: List[str] Тогда мы можем обьявить поле `tags` как множество строк: -=== "Python 3.10+" - - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="1 14" - {!> ../../../docs_src/body_nested_models/tutorial003.py!} - ``` +{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *} С помощью этого, даже если вы получите запрос с повторяющимися данными, они будут преобразованы в множество уникальных элементов. @@ -125,45 +81,13 @@ my_list: List[str] Например, мы можем определить модель `Image`: -=== "Python 3.10+" - - ```Python hl_lines="7-9" - {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="9-11" - {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="9-11" - {!> ../../../docs_src/body_nested_models/tutorial004.py!} - ``` +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *} ### Использование вложенной модели в качестве типа Также мы можем использовать эту модель как тип атрибута: -=== "Python 3.10+" - - ```Python hl_lines="18" - {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial004.py!} - ``` +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *} Это означает, что **FastAPI** будет ожидать тело запроса, аналогичное этому: @@ -192,27 +116,11 @@ my_list: List[str] Помимо обычных простых типов, таких как `str`, `int`, `float`, и т.д. Вы можете использовать более сложные базовые типы, которые наследуются от типа `str`. -Чтобы увидеть все варианты, которые у вас есть, ознакомьтесь с документацией по необычным типам Pydantic. Вы увидите некоторые примеры в следующей главе. +Чтобы увидеть все варианты, которые у вас есть, ознакомьтесь с документацией по необычным типам Pydantic. Вы увидите некоторые примеры в следующей главе. Например, так как в модели `Image` у нас есть поле `url`, то мы можем объявить его как тип `HttpUrl` из модуля Pydantic вместо типа `str`: -=== "Python 3.10+" - - ```Python hl_lines="2 8" - {!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="4 10" - {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="4 10" - {!> ../../../docs_src/body_nested_models/tutorial005.py!} - ``` +{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *} Строка будет проверена на соответствие допустимому URL-адресу и задокументирована в JSON схему / OpenAPI. @@ -220,23 +128,7 @@ my_list: List[str] Вы также можете использовать модели Pydantic в качестве типов вложенных в `list`, `set` и т.д: -=== "Python 3.10+" - - ```Python hl_lines="18" - {!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial006.py!} - ``` +{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *} Такая реализация будет ожидать (конвертировать, валидировать, документировать и т.д) JSON-содержимое в следующем формате: @@ -264,33 +156,23 @@ my_list: List[str] } ``` -!!! info "Информация" - Заметьте, что теперь у ключа `images` есть список объектов изображений. +/// info | Информация -## Глубоко вложенные модели +Заметьте, что теперь у ключа `images` есть список объектов изображений. -Вы можете определять модели с произвольным уровнем вложенности: +/// -=== "Python 3.10+" - - ```Python hl_lines="7 12 18 21 25" - {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} - ``` +## Глубоко вложенные модели -=== "Python 3.9+" +Вы можете определять модели с произвольным уровнем вложенности: - ```Python hl_lines="9 14 20 23 27" - {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} - ``` +{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *} -=== "Python 3.8+" +/// info | Информация - ```Python hl_lines="9 14 20 23 27" - {!> ../../../docs_src/body_nested_models/tutorial007.py!} - ``` +Заметьте, что у объекта `Offer` есть список объектов `Item`, которые, в свою очередь, могут содержать необязательный список объектов `Image` -!!! info "Информация" - Заметьте, что у объекта `Offer` есть список объектов `Item`, которые, в свою очередь, могут содержать необязательный список объектов `Image` +/// ## Тела с чистыми списками элементов @@ -308,17 +190,7 @@ images: list[Image] например так: -=== "Python 3.9+" - - ```Python hl_lines="13" - {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="15" - {!> ../../../docs_src/body_nested_models/tutorial008.py!} - ``` +{* ../../docs_src/body_nested_models/tutorial008_py39.py hl[13] *} ## Универсальная поддержка редактора @@ -348,26 +220,19 @@ images: list[Image] В этом случае вы принимаете `dict`, пока у него есть ключи типа `int` со значениями типа `float`: -=== "Python 3.9+" - - ```Python hl_lines="7" - {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} - ``` +{* ../../docs_src/body_nested_models/tutorial009_py39.py hl[7] *} -=== "Python 3.8+" +/// tip | Совет - ```Python hl_lines="9" - {!> ../../../docs_src/body_nested_models/tutorial009.py!} - ``` +Имейте в виду, что JSON поддерживает только ключи типа `str`. -!!! tip "Совет" - Имейте в виду, что JSON поддерживает только ключи типа `str`. +Но Pydantic обеспечивает автоматическое преобразование данных. - Но Pydantic обеспечивает автоматическое преобразование данных. +Это значит, что даже если пользователи вашего API могут отправлять только строки в качестве ключей, при условии, что эти строки содержат целые числа, Pydantic автоматический преобразует и валидирует эти данные. - Это значит, что даже если пользователи вашего API могут отправлять только строки в качестве ключей, при условии, что эти строки содержат целые числа, Pydantic автоматический преобразует и валидирует эти данные. +А `dict`, с именем `weights`, который вы получите в качестве ответа Pydantic, действительно будет иметь ключи типа `int` и значения типа `float`. - А `dict`, с именем `weights`, который вы получите в качестве ответа Pydantic, действительно будет иметь ключи типа `int` и значения типа `float`. +/// ## Резюме diff --git a/docs/ru/docs/tutorial/body-updates.md b/docs/ru/docs/tutorial/body-updates.md new file mode 100644 index 000000000..99f475a41 --- /dev/null +++ b/docs/ru/docs/tutorial/body-updates.md @@ -0,0 +1,98 @@ +# Body - Обновления + +## Полное обновление с помощью `PUT` + +Для полного обновления элемента можно воспользоваться операцией HTTP `PUT`. + +Вы можете использовать функцию `jsonable_encoder` для преобразования входных данных в JSON, так как нередки случаи, когда работать можно только с простыми типами данных (например, для хранения в NoSQL-базе данных). + +{* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *} + +`PUT` используется для получения данных, которые должны полностью заменить существующие данные. + +### Предупреждение о замене + +Это означает, что если вы хотите обновить элемент `bar`, используя `PUT` с телом, содержащим: + +```Python +{ + "name": "Barz", + "price": 3, + "description": None, +} +``` + +поскольку оно не включает уже сохраненный атрибут `"tax": 20.2`, входная модель примет значение по умолчанию `"tax": 10.5`. + +И данные будут сохранены с этим "новым" `tax`, равным `10,5`. + +## Частичное обновление с помощью `PATCH` + +Также можно использовать HTTP `PATCH` операцию для *частичного* обновления данных. + +Это означает, что можно передавать только те данные, которые необходимо обновить, оставляя остальные нетронутыми. + +/// note | Технические детали + +`PATCH` менее распространен и известен, чем `PUT`. + +А многие команды используют только `PUT`, даже для частичного обновления. + +Вы можете **свободно** использовать их как угодно, **FastAPI** не накладывает никаких ограничений. + +Но в данном руководстве более или менее понятно, как они должны использоваться. + +/// + +### Использование параметра `exclude_unset` в Pydantic + +Если необходимо выполнить частичное обновление, то очень полезно использовать параметр `exclude_unset` в методе `.dict()` модели Pydantic. + +Например, `item.dict(exclude_unset=True)`. + +В результате будет сгенерирован словарь, содержащий только те данные, которые были заданы при создании модели `item`, без учета значений по умолчанию. Затем вы можете использовать это для создания словаря только с теми данными, которые были установлены (отправлены в запросе), опуская значения по умолчанию: + +{* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *} + +### Использование параметра `update` в Pydantic + +Теперь можно создать копию существующей модели, используя `.copy()`, и передать параметр `update` с `dict`, содержащим данные для обновления. + +Например, `stored_item_model.copy(update=update_data)`: + +{* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *} + +### Кратко о частичном обновлении + +В целом, для применения частичных обновлений необходимо: + +* (Опционально) использовать `PATCH` вместо `PUT`. +* Извлечь сохранённые данные. +* Поместить эти данные в Pydantic модель. +* Сгенерировать `dict` без значений по умолчанию из входной модели (с использованием `exclude_unset`). + * Таким образом, можно обновлять только те значения, которые действительно установлены пользователем, вместо того чтобы переопределять значения, уже сохраненные в модели по умолчанию. +* Создать копию хранимой модели, обновив ее атрибуты полученными частичными обновлениями (с помощью параметра `update`). +* Преобразовать скопированную модель в то, что может быть сохранено в вашей БД (например, с помощью `jsonable_encoder`). + * Это сравнимо с повторным использованием метода модели `.dict()`, но при этом происходит проверка (и преобразование) значений в типы данных, которые могут быть преобразованы в JSON, например, `datetime` в `str`. +* Сохранить данные в своей БД. +* Вернуть обновленную модель. + +{* ../../docs_src/body_updates/tutorial002_py310.py hl[28:35] *} + +/// tip | Подсказка + +Эту же технику можно использовать и для операции HTTP `PUT`. + +Но в приведенном примере используется `PATCH`, поскольку он был создан именно для таких случаев использования. + +/// + +/// note | Технические детали + +Обратите внимание, что входная модель по-прежнему валидируется. + +Таким образом, если вы хотите получать частичные обновления, в которых могут быть опущены все атрибуты, вам необходимо иметь модель, в которой все атрибуты помечены как необязательные (со значениями по умолчанию или `None`). + +Чтобы отличить модели со всеми необязательными значениями для **обновления** от моделей с обязательными значениями для **создания**, можно воспользоваться идеями, описанными в [Дополнительные модели](extra-models.md){.internal-link target=_blank}. + +/// diff --git a/docs/ru/docs/tutorial/body.md b/docs/ru/docs/tutorial/body.md index c03d40c3f..2c9110226 100644 --- a/docs/ru/docs/tutorial/body.md +++ b/docs/ru/docs/tutorial/body.md @@ -6,22 +6,23 @@ Ваш API почти всегда отправляет тело **ответа**. Но клиентам не обязательно всегда отправлять тело **запроса**. -Чтобы объявить тело **запроса**, необходимо использовать модели Pydantic, со всей их мощью и преимуществами. +Чтобы объявить тело **запроса**, необходимо использовать модели Pydantic, со всей их мощью и преимуществами. -!!! info "Информация" - Чтобы отправить данные, необходимо использовать один из методов: `POST` (обычно), `PUT`, `DELETE` или `PATCH`. +/// info | Информация - Отправка тела с запросом `GET` имеет неопределенное поведение в спецификациях, тем не менее, оно поддерживается FastAPI только для очень сложных/экстремальных случаев использования. +Чтобы отправить данные, необходимо использовать один из методов: `POST` (обычно), `PUT`, `DELETE` или `PATCH`. - Поскольку это не рекомендуется, интерактивная документация со Swagger UI не будет отображать информацию для тела при использовании метода GET, а промежуточные прокси-серверы могут не поддерживать такой вариант запроса. +Отправка тела с запросом `GET` имеет неопределенное поведение в спецификациях, тем не менее, оно поддерживается FastAPI только для очень сложных/экстремальных случаев использования. + +Поскольку это не рекомендуется, интерактивная документация со Swagger UI не будет отображать информацию для тела при использовании метода GET, а промежуточные прокси-серверы могут не поддерживать такой вариант запроса. + +/// ## Импортирование `BaseModel` из Pydantic Первое, что вам необходимо сделать, это импортировать `BaseModel` из пакета `pydantic`: -```Python hl_lines="4" -{!../../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[4] *} ## Создание вашей собственной модели @@ -29,9 +30,7 @@ Используйте аннотации типов Python для всех атрибутов: -```Python hl_lines="7-11" -{!../../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[7:11] *} Также как и при описании параметров запроса, когда атрибут модели имеет значение по умолчанию, он является необязательным. Иначе он обязателен. Используйте `None`, чтобы сделать его необязательным без использования конкретных значений по умолчанию. @@ -59,9 +58,7 @@ Чтобы добавить параметр к вашему *обработчику*, объявите его также, как вы объявляли параметры пути или параметры запроса: -```Python hl_lines="18" -{!../../../docs_src/body/tutorial001.py!} -``` +{* ../../docs_src/body/tutorial001.py hl[18] *} ...и укажите созданную модель в качестве типа параметра, `Item`. @@ -110,24 +107,25 @@ -!!! tip "Подсказка" - Если вы используете PyCharm в качестве редактора, то вам стоит попробовать плагин Pydantic PyCharm Plugin. +/// tip | Подсказка + +Если вы используете PyCharm в качестве редактора, то вам стоит попробовать плагин Pydantic PyCharm Plugin. - Он улучшает поддержку редактором моделей Pydantic в части: +Он улучшает поддержку редактором моделей Pydantic в части: - * автодополнения, - * проверки типов, - * рефакторинга, - * поиска, - * инспектирования. +* автодополнения, +* проверки типов, +* рефакторинга, +* поиска, +* инспектирования. + +/// ## Использование модели Внутри функции вам доступны все атрибуты объекта модели напрямую: -```Python hl_lines="21" -{!../../../docs_src/body/tutorial002.py!} -``` +{* ../../docs_src/body/tutorial002.py hl[21] *} ## Тело запроса + параметры пути @@ -135,9 +133,7 @@ **FastAPI** распознает, какие параметры функции соответствуют параметрам пути и должны быть **получены из пути**, а какие параметры функции, объявленные как модели Pydantic, должны быть **получены из тела запроса**. -```Python hl_lines="17-18" -{!../../../docs_src/body/tutorial003.py!} -``` +{* ../../docs_src/body/tutorial003.py hl[17:18] *} ## Тело запроса + параметры пути + параметры запроса @@ -145,9 +141,7 @@ **FastAPI** распознает каждый из них и возьмет данные из правильного источника. -```Python hl_lines="18" -{!../../../docs_src/body/tutorial004.py!} -``` +{* ../../docs_src/body/tutorial004.py hl[18] *} Параметры функции распознаются следующим образом: @@ -155,11 +149,14 @@ * Если аннотация типа параметра содержит **примитивный тип** (`int`, `float`, `str`, `bool` и т.п.), он будет интерпретирован как параметр **запроса**. * Если аннотация типа параметра представляет собой **модель Pydantic**, он будет интерпретирован как параметр **тела запроса**. -!!! note "Заметка" - FastAPI понимает, что значение параметра `q` не является обязательным, потому что имеет значение по умолчанию `= None`. +/// note | Заметка + +FastAPI понимает, что значение параметра `q` не является обязательным, потому что имеет значение по умолчанию `= None`. + +Аннотация `Optional` в `Optional[str]` не используется FastAPI, но помогает вашему редактору лучше понимать ваш код и обнаруживать ошибки. - Аннотация `Optional` в `Optional[str]` не используется FastAPI, но помогает вашему редактору лучше понимать ваш код и обнаруживать ошибки. +/// ## Без Pydantic -Если вы не хотите использовать модели Pydantic, вы все еще можете использовать параметры **тела запроса**. Читайте в документации раздел [Тело - Несколько параметров: Единичные значения в теле](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}. +Если вы не хотите использовать модели Pydantic, вы все еще можете использовать параметры **тела запроса**. Читайте в документации раздел [Тело - Несколько параметров: Единичные значения в теле](body-multiple-params.md#_2){.internal-link target=_blank}. diff --git a/docs/ru/docs/tutorial/cookie-params.md b/docs/ru/docs/tutorial/cookie-params.md index 5f99458b6..d1ed943d7 100644 --- a/docs/ru/docs/tutorial/cookie-params.md +++ b/docs/ru/docs/tutorial/cookie-params.md @@ -6,17 +6,7 @@ Сначала импортируйте `Cookie`: -=== "Python 3.10+" - - ```Python hl_lines="1" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +{* ../../docs_src/cookie_params/tutorial001_py310.py hl[1] *} ## Объявление параметров `Cookie` @@ -24,25 +14,21 @@ Первое значение - это значение по умолчанию, вы можете передать все дополнительные параметры проверки или аннотации: -=== "Python 3.10+" +{* ../../docs_src/cookie_params/tutorial001_py310.py hl[7] *} + +/// note | Технические детали - ```Python hl_lines="7" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +`Cookie` - это класс, родственный `Path` и `Query`. Он также наследуется от общего класса `Param`. -=== "Python 3.8+" +Но помните, что когда вы импортируете `Query`, `Path`, `Cookie` и другое из `fastapi`, это фактически функции, которые возвращают специальные классы. - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +/// -!!! note "Технические детали" - `Cookie` - это класс, родственный `Path` и `Query`. Он также наследуется от общего класса `Param`. +/// info | Дополнительная информация - Но помните, что когда вы импортируете `Query`, `Path`, `Cookie` и другое из `fastapi`, это фактически функции, которые возвращают специальные классы. +Для объявления cookies, вам нужно использовать `Cookie`, иначе параметры будут интерпретированы как параметры запроса. -!!! info "Дополнительная информация" - Для объявления cookies, вам нужно использовать `Cookie`, иначе параметры будут интерпретированы как параметры запроса. +/// ## Резюме diff --git a/docs/ru/docs/tutorial/cors.md b/docs/ru/docs/tutorial/cors.md index 8c7fbc046..e8bf04576 100644 --- a/docs/ru/docs/tutorial/cors.md +++ b/docs/ru/docs/tutorial/cors.md @@ -46,9 +46,7 @@ * Отдельных HTTP-методов (`POST`, `PUT`) или всех вместе, используя `"*"`. * Отдельных HTTP-заголовков или всех вместе, используя `"*"`. -```Python hl_lines="2 6-11 13-19" -{!../../../docs_src/cors/tutorial001.py!} -``` +{* ../../docs_src/cors/tutorial001.py hl[2,6:11,13:19] *} `CORSMiddleware` использует для параметров "запрещающие" значения по умолчанию, поэтому вам нужно явным образом разрешить использование отдельных источников, методов или заголовков, чтобы браузеры могли использовать их в кросс-доменном контексте. @@ -78,7 +76,10 @@ Для получения более подробной информации о CORS, обратитесь к Документации CORS от Mozilla. -!!! note "Технические детали" - Вы также можете использовать `from starlette.middleware.cors import CORSMiddleware`. +/// note | Технические детали - **FastAPI** предоставляет несколько middleware в `fastapi.middleware` только для вашего удобства как разработчика. Но большинство доступных middleware взяты напрямую из Starlette. +Вы также можете использовать `from starlette.middleware.cors import CORSMiddleware`. + +**FastAPI** предоставляет несколько middleware в `fastapi.middleware` только для вашего удобства как разработчика. Но большинство доступных middleware взяты напрямую из Starlette. + +/// diff --git a/docs/ru/docs/tutorial/debugging.md b/docs/ru/docs/tutorial/debugging.md index 38709e56d..05806f087 100644 --- a/docs/ru/docs/tutorial/debugging.md +++ b/docs/ru/docs/tutorial/debugging.md @@ -6,9 +6,7 @@ В вашем FastAPI приложении, импортируйте и вызовите `uvicorn` напрямую: -```Python hl_lines="1 15" -{!../../../docs_src/debugging/tutorial001.py!} -``` +{* ../../docs_src/debugging/tutorial001.py hl[1,15] *} ### Описание `__name__ == "__main__"` @@ -74,8 +72,11 @@ from myapp import app не будет выполнена. -!!! Информация - Для получения дополнительной информации, ознакомьтесь с официальной документацией Python. +/// info | Информация + +Для получения дополнительной информации, ознакомьтесь с официальной документацией Python. + +/// ## Запуск вашего кода с помощью отладчика diff --git a/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md index b6ad25daf..8037872b9 100644 --- a/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,41 +6,7 @@ В предыдущем примере мы возвращали `словарь` из нашей зависимости: -=== "Python 3.10+" - - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` - -=== "Python 3.6+" - - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` - -=== "Python 3.10+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python hl_lines="7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` - -=== "Python 3.6+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python hl_lines="11" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[9] *} Но затем мы получаем `словарь` в параметре `commons` *функции операции пути*. И мы знаем, что редакторы не могут обеспечить достаточную поддержку для `словаря`, поскольку они не могут знать их ключи и типы значений. @@ -101,117 +67,15 @@ fluffy = Cat(name="Mr Fluffy") Теперь мы можем изменить зависимость `common_parameters`, указанную выше, на класс `CommonQueryParams`: -=== "Python 3.10+" - - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} - ``` - -=== "Python 3.6+" - - ```Python hl_lines="12-16" - {!> ../../../docs_src/dependencies/tutorial002_an.py!} - ``` - -=== "Python 3.10+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python hl_lines="9-13" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` - -=== "Python 3.6+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[11:15] *} Обратите внимание на метод `__init__`, используемый для создания экземпляра класса: -=== "Python 3.10+" - - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} - ``` - -=== "Python 3.6+" - - ```Python hl_lines="13" - {!> ../../../docs_src/dependencies/tutorial002_an.py!} - ``` - -=== "Python 3.10+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` - -=== "Python 3.6+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[12] *} ...имеет те же параметры, что и ранее используемая функция `common_parameters`: -=== "Python 3.10+" - - ```Python hl_lines="8" - {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} - ``` - -=== "Python 3.6+" - - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial001_an.py!} - ``` - -=== "Python 3.10+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python hl_lines="6" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` - -=== "Python 3.6+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8] *} Эти параметры и будут использоваться **FastAPI** для "решения" зависимости. @@ -227,62 +91,35 @@ fluffy = Cat(name="Mr Fluffy") Теперь вы можете объявить свою зависимость, используя этот класс. -=== "Python 3.10+" - - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} - ``` - -=== "Python 3.9+" +{* ../../docs_src/dependencies/tutorial002_an_py310.py hl[19] *} - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} - ``` - -=== "Python 3.6+" - - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial002_an.py!} - ``` - -=== "Python 3.10+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` +**FastAPI** вызывает класс `CommonQueryParams`. При этом создается "экземпляр" этого класса, который будет передан в качестве параметра `commons` в вашу функцию. -=== "Python 3.6+ без Annotated" +## Аннотация типа или `Depends` - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Обратите внимание, что в приведенном выше коде мы два раза пишем `CommonQueryParams`: - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +//// tab | Python 3.6+ без Annotated -**FastAPI** вызывает класс `CommonQueryParams`. При этом создается "экземпляр" этого класса, который будет передан в качестве параметра `commons` в вашу функцию. +/// tip | Подсказка -## Аннотация типа или `Depends` +Рекомендуется использовать версию с `Annotated` если возможно. -Обратите внимание, что в приведенном выше коде мы два раза пишем `CommonQueryParams`: +/// -=== "Python 3.6+ без Annotated" +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// - ```Python - commons: CommonQueryParams = Depends(CommonQueryParams) - ``` +//// tab | Python 3.6+ -=== "Python 3.6+" +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` - ```Python - commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] - ``` +//// Последний параметр `CommonQueryParams`, в: @@ -298,77 +135,57 @@ fluffy = Cat(name="Mr Fluffy") В этом случае первый `CommonQueryParams`, в: -=== "Python 3.6+" - - ```Python - commons: Annotated[CommonQueryParams, ... - ``` +//// tab | Python 3.6+ -=== "Python 3.6+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python - commons: CommonQueryParams ... - ``` +```Python +commons: Annotated[CommonQueryParams, ... +``` -...не имеет никакого специального значения для **FastAPI**. FastAPI не будет использовать его для преобразования данных, валидации и т.д. (поскольку для этого используется `Depends(CommonQueryParams)`). +//// -На самом деле можно написать просто: +//// tab | Python 3.6+ без Annotated -=== "Python 3.6+" +/// tip | Подсказка - ```Python - commons: Annotated[Any, Depends(CommonQueryParams)] - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.6+ без Annotated" +/// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +```Python +commons: CommonQueryParams ... +``` - ```Python - commons = Depends(CommonQueryParams) - ``` +//// -...как тут: +...не имеет никакого специального значения для **FastAPI**. FastAPI не будет использовать его для преобразования данных, валидации и т.д. (поскольку для этого используется `Depends(CommonQueryParams)`). -=== "Python 3.10+" +На самом деле можно написать просто: - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003_an_py310.py!} - ``` +//// tab | Python 3.6+ -=== "Python 3.9+" +```Python +commons: Annotated[Any, Depends(CommonQueryParams)] +``` - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003_an_py39.py!} - ``` +//// -=== "Python 3.6+" +//// tab | Python 3.6+ без Annotated - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial003_an.py!} - ``` +/// tip | Подсказка -=== "Python 3.10+ без Annotated" +Рекомендуется использовать версию с `Annotated` если возможно. - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial003_py310.py!} - ``` +```Python +commons = Depends(CommonQueryParams) +``` -=== "Python 3.6+ без Annotated" +//// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +...как тут: - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003.py!} - ``` +{* ../../docs_src/dependencies/tutorial003_an_py310.py hl[19] *} Но объявление типа приветствуется, так как в этом случае ваш редактор будет знать, что будет передано в качестве параметра `commons`, и тогда он сможет помочь вам с автодополнением, проверкой типов и т.д: @@ -378,101 +195,91 @@ fluffy = Cat(name="Mr Fluffy") Но вы видите, что здесь мы имеем некоторое повторение кода, дважды написав `CommonQueryParams`: -=== "Python 3.6+ без Annotated" +//// tab | Python 3.6+ без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | Подсказка - ```Python - commons: CommonQueryParams = Depends(CommonQueryParams) - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.6+" +/// - ```Python - commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] - ``` +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` -Для случаев, когда зависимостью является *конкретный* класс, который **FastAPI** "вызовет" для создания экземпляра этого класса, можно использовать укороченную запись. +//// +//// tab | Python 3.6+ -Вместо того чтобы писать: +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` -=== "Python 3.6+" +//// - ```Python - commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] - ``` +Для случаев, когда зависимостью является *конкретный* класс, который **FastAPI** "вызовет" для создания экземпляра этого класса, можно использовать укороченную запись. -=== "Python 3.6+ без Annotated" - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Вместо того чтобы писать: - ```Python - commons: CommonQueryParams = Depends(CommonQueryParams) - ``` +//// tab | Python 3.6+ -...следует написать: +```Python +commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] +``` -=== "Python 3.6+" +//// - ```Python - commons: Annotated[CommonQueryParams, Depends()] - ``` +//// tab | Python 3.6+ без Annotated -=== "Python 3.6 без Annotated" +/// tip | Подсказка - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Рекомендуется использовать версию с `Annotated` если возможно. - ```Python - commons: CommonQueryParams = Depends() - ``` +/// -Вы объявляете зависимость как тип параметра и используете `Depends()` без какого-либо параметра, вместо того чтобы *снова* писать полный класс внутри `Depends(CommonQueryParams)`. +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` -Аналогичный пример будет выглядеть следующим образом: +//// + +...следует написать: -=== "Python 3.10+" +//// tab | Python 3.6+ - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004_an_py310.py!} - ``` +```Python +commons: Annotated[CommonQueryParams, Depends()] +``` -=== "Python 3.9+" +//// - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004_an_py39.py!} - ``` +//// tab | Python 3.6 без Annotated -=== "Python 3.6+" +/// tip | Подсказка - ```Python hl_lines="20" - {!> ../../../docs_src/dependencies/tutorial004_an.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -=== "Python 3.10+ без Annotated" +/// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +```Python +commons: CommonQueryParams = Depends() +``` - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial004_py310.py!} - ``` +//// -=== "Python 3.6+ без Annotated" +Вы объявляете зависимость как тип параметра и используете `Depends()` без какого-либо параметра, вместо того чтобы *снова* писать полный класс внутри `Depends(CommonQueryParams)`. - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Аналогичный пример будет выглядеть следующим образом: - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004.py!} - ``` +{* ../../docs_src/dependencies/tutorial004_an_py310.py hl[19] *} ...и **FastAPI** будет знать, что делать. -!!! tip "Подсказка" - Если это покажется вам более запутанным, чем полезным, не обращайте внимания, это вам не *нужно*. +/// tip | Подсказка + +Если это покажется вам более запутанным, чем полезным, не обращайте внимания, это вам не *нужно*. + +Это просто сокращение. Потому что **FastAPI** заботится о том, чтобы помочь вам свести к минимуму повторение кода. - Это просто сокращение. Потому что **FastAPI** заботится о том, чтобы помочь вам свести к минимуму повторение кода. +/// diff --git a/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md new file mode 100644 index 000000000..0e4eb95be --- /dev/null +++ b/docs/ru/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -0,0 +1,69 @@ +# Зависимости в декораторах операции пути + +В некоторых случаях, возвращаемое значение зависимости не используется внутри *функции операции пути*. + +Или же зависимость не возвращает никакого значения. + +Но вам всё-таки нужно, чтобы она выполнилась. + +Для таких ситуаций, вместо объявления *функции операции пути* с параметром `Depends`, вы можете добавить список зависимостей `dependencies` в *декоратор операции пути*. + +## Добавление `dependencies` в *декоратор операции пути* + +*Декоратор операции пути* получает необязательный аргумент `dependencies`. + +Это должен быть `list` состоящий из `Depends()`: + +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[19] *} + +Зависимости из dependencies выполнятся так же, как и обычные зависимости. Но их значения (если они были) не будут переданы в *функцию операции пути*. + +/// tip | Подсказка + +Некоторые редакторы кода определяют неиспользуемые параметры функций и подсвечивают их как ошибку. + +Использование `dependencies` в *декораторе операции пути* гарантирует выполнение зависимостей, избегая при этом предупреждений редактора кода и других инструментов. + +Это также должно помочь предотвратить путаницу у начинающих разработчиков, которые видят неиспользуемые параметры в коде и могут подумать что в них нет необходимости. + +/// + +/// info | Примечание + +В этом примере мы используем выдуманные пользовательские заголовки `X-Key` и `X-Token`. + +Но в реальных проектах, при внедрении системы безопасности, вы получите больше пользы используя интегрированные [средства защиты (следующая глава)](../security/index.md){.internal-link target=_blank}. + +/// + +## Исключения в dependencies и возвращаемые значения + +Вы можете использовать те же *функции* зависимостей, что и обычно. + +### Требования к зависимостям + +Они могут объявлять требования к запросу (например заголовки) или другие подзависимости: + +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[8,13] *} + +### Вызов исключений + +Зависимости из dependencies могут вызывать исключения с помощью `raise`, как и обычные зависимости: + +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[10,15] *} + +### Возвращаемые значения + +И они могут возвращать значения или нет, эти значения использоваться не будут. + +Таким образом, вы можете переиспользовать обычную зависимость (возвращающую значение), которую вы уже используете где-то в другом месте, и хотя значение не будет использоваться, зависимость будет выполнена: + +{* ../../docs_src/dependencies/tutorial006_an_py39.py hl[11,16] *} + +## Dependencies для группы *операций путей* + +Позже, читая о том как структурировать большие приложения ([Bigger Applications - Multiple Files](../../tutorial/bigger-applications.md){.internal-link target=_blank}), возможно, многофайловые, вы узнаете как объявить единый параметр `dependencies` для всей группы *операций путей*. + +## Глобальный Dependencies + +Далее мы увидим, как можно добавить dependencies для всего `FastAPI` приложения, так чтобы они применялись к каждой *операции пути*. diff --git a/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md new file mode 100644 index 000000000..e64f6777c --- /dev/null +++ b/docs/ru/docs/tutorial/dependencies/dependencies-with-yield.md @@ -0,0 +1,259 @@ +# Зависимости с yield + +FastAPI поддерживает зависимости, которые выполняют некоторые дополнительные действия после завершения работы. + +Для этого используйте `yield` вместо `return`, а дополнительный код напишите после него. + +/// tip | Подсказка + +Обязательно используйте `yield` один-единственный раз. + +/// + +/// note | Технические детали + +Любая функция, с которой может работать: + +* `@contextlib.contextmanager` или +* `@contextlib.asynccontextmanager` + +будет корректно использоваться в качестве **FastAPI**-зависимости. + +На самом деле, FastAPI использует эту пару декораторов "под капотом". + +/// + +## Зависимость базы данных с помощью `yield` + +Например, с его помощью можно создать сессию работы с базой данных и закрыть его после завершения. + +Перед созданием ответа будет выполнен только код до и включая `yield`. + +{* ../../docs_src/dependencies/tutorial007.py hl[2:4] *} + +Полученное значение и есть то, что будет внедрено в функцию операции пути и другие зависимости: + +{* ../../docs_src/dependencies/tutorial007.py hl[4] *} + +Код, следующий за оператором `yield`, выполняется после доставки ответа: + +{* ../../docs_src/dependencies/tutorial007.py hl[5:6] *} + +/// tip | Подсказка + +Можно использовать как `async` так и обычные функции. + +**FastAPI** это корректно обработает, и в обоих случаях будет делать то же самое, что и с обычными зависимостями. + +/// + +## Зависимость с `yield` и `try` одновременно + +Если использовать блок `try` в зависимости с `yield`, то будет получено всякое исключение, которое было выброшено при использовании зависимости. + +Например, если какой-то код в какой-то момент в середине, в другой зависимости или в *функции операции пути*, сделал "откат" транзакции базы данных или создал любую другую ошибку, то вы получите исключение в своей зависимости. + +Таким образом, можно искать конкретное исключение внутри зависимости с помощью `except SomeException`. + +Таким же образом можно использовать `finally`, чтобы убедиться, что обязательные шаги при выходе выполнены, независимо от того, было ли исключение или нет. + +{* ../../docs_src/dependencies/tutorial007.py hl[3,5] *} + +## Подзависимости с `yield` + +Вы можете иметь подзависимости и "деревья" подзависимостей любого размера и формы, и любая из них или все они могут использовать `yield`. + +**FastAPI** будет следить за тем, чтобы "код по выходу" в каждой зависимости с `yield` выполнялся в правильном порядке. + +Например, `dependency_c` может иметь зависимость от `dependency_b`, а `dependency_b` от `dependency_a`: + +{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[6,14,22] *} + +И все они могут использовать `yield`. + +В этом случае `dependency_c` для выполнения своего кода выхода нуждается в том, чтобы значение из `dependency_b` (здесь `dep_b`) было еще доступно. + +И, в свою очередь, `dependency_b` нуждается в том, чтобы значение из `dependency_a` (здесь `dep_a`) было доступно для ее завершающего кода. + +{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[18:19,26:27] *} + +Точно так же можно иметь часть зависимостей с `yield`, часть с `return`, и какие-то из них могут зависеть друг от друга. + +Либо у вас может быть одна зависимость, которая требует несколько других зависимостей с `yield` и т.д. + +Комбинации зависимостей могут быть какими вам угодно. + +**FastAPI** проследит за тем, чтобы все выполнялось в правильном порядке. + +/// note | Технические детали + +Это работает благодаря Контекстным менеджерам в Python. + +/// + + **FastAPI** использует их "под капотом" с этой целью. + +## Зависимости с `yield` и `HTTPException` + +Вы видели, что можно использовать зависимости с `yield` совместно с блоком `try`, отлавливающие исключения. + +Таким же образом вы можете поднять исключение `HTTPException` или что-то подобное в завершающем коде, после `yield`. + +Код выхода в зависимостях с `yield` выполняется *после* отправки ответа, поэтому [Обработчик исключений](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} уже будет запущен. В коде выхода (после `yield`) нет ничего, перехватывающего исключения, брошенные вашими зависимостями. + +Таким образом, если после `yield` возникает `HTTPException`, то стандартный (или любой пользовательский) обработчик исключений, который перехватывает `HTTPException` и возвращает ответ HTTP 400, уже не сможет перехватить это исключение. + +Благодаря этому все, что установлено в зависимости (например, сеанс работы с БД), может быть использовано, например, фоновыми задачами. + +Фоновые задачи выполняются *после* отправки ответа. Поэтому нет возможности поднять `HTTPException`, так как нет даже возможности изменить уже отправленный ответ. + +Но если фоновая задача создает ошибку в БД, то, по крайней мере, можно сделать откат или чисто закрыть сессию в зависимости с помощью `yield`, а также, возможно, занести ошибку в журнал или сообщить о ней в удаленную систему отслеживания. + +Если у вас есть код, который, как вы знаете, может вызвать исключение, сделайте самую обычную/"питонячью" вещь и добавьте блок `try` в этот участок кода. + +Если у вас есть пользовательские исключения, которые вы хотите обрабатывать *до* возврата ответа и, возможно, модифицировать ответ, даже вызывая `HTTPException`, создайте [Cобственный обработчик исключений](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. + +/// tip | Подсказка + +Вы все еще можете вызывать исключения, включая `HTTPException`, *до* `yield`. Но не после. + +/// + +Последовательность выполнения примерно такая, как на этой схеме. Время течет сверху вниз. А каждый столбец - это одна из частей, взаимодействующих с кодом или выполняющих код. + +```mermaid +sequenceDiagram + +participant client as Client +participant handler as Exception handler +participant dep as Dep with yield +participant operation as Path Operation +participant tasks as Background tasks + + Note over client,tasks: Can raise exception for dependency, handled after response is sent + Note over client,operation: Can raise HTTPException and can change the response + client ->> dep: Start request + Note over dep: Run code up to yield + opt raise + dep -->> handler: Raise HTTPException + handler -->> client: HTTP error response + dep -->> dep: Raise other exception + end + dep ->> operation: Run dependency, e.g. DB session + opt raise + operation -->> dep: Raise HTTPException + dep -->> handler: Auto forward exception + handler -->> client: HTTP error response + operation -->> dep: Raise other exception + dep -->> handler: Auto forward exception + end + operation ->> client: Return response to client + Note over client,operation: Response is already sent, can't change it anymore + opt Tasks + operation -->> tasks: Send background tasks + end + opt Raise other exception + tasks -->> dep: Raise other exception + end + Note over dep: After yield + opt Handle other exception + dep -->> dep: Handle exception, can't change response. E.g. close DB session. + end +``` + +/// info | Дополнительная информация + +Клиенту будет отправлен только **один ответ**. Это может быть один из ответов об ошибке или это будет ответ от *операции пути*. + +После отправки одного из этих ответов никакой другой ответ не может быть отправлен. + +/// + +/// tip | Подсказка + +На этой диаграмме показано "HttpException", но вы также можете вызвать любое другое исключение, для которого вы создаете [Пользовательский обработчик исключений](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. + +Если вы создадите какое-либо исключение, оно будет передано зависимостям с yield, включая `HttpException`, а затем **снова** обработчикам исключений. Если для этого исключения нет обработчика исключений, то оно будет обработано внутренним "ServerErrorMiddleware" по умолчанию, возвращающим код состояния HTTP 500, чтобы уведомить клиента, что на сервере произошла ошибка. + +/// + +## Зависимости с `yield`, `HTTPException` и фоновыми задачами + +/// warning | Внимание + +Скорее всего, вам не нужны эти технические подробности, вы можете пропустить этот раздел и продолжить ниже. + +Эти подробности полезны, главным образом, если вы использовали версию FastAPI до 0.106.0 и использовали ресурсы из зависимостей с `yield` в фоновых задачах. + +/// + +До версии FastAPI 0.106.0 вызывать исключения после `yield` было невозможно, код выхода в зависимостях с `yield` выполнялся *после* отправки ответа, поэтому [Обработчик Ошибок](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} уже был бы запущен. + +Это было сделано главным образом для того, чтобы позволить использовать те же объекты, "отданные" зависимостями, внутри фоновых задач, поскольку код выхода будет выполняться после завершения фоновых задач. + +Тем не менее, поскольку это означало бы ожидание ответа в сети, а также ненужное удержание ресурса в зависимости от доходности (например, соединение с базой данных), это было изменено в FastAPI 0.106.0. + +/// tip | Подсказка + +Кроме того, фоновая задача обычно представляет собой независимый набор логики, который должен обрабатываться отдельно, со своими собственными ресурсами (например, собственным подключением к базе данных). +Таким образом, вы, вероятно, получите более чистый код. + +/// + +Если вы полагались на это поведение, то теперь вам следует создавать ресурсы для фоновых задач внутри самой фоновой задачи, а внутри использовать только те данные, которые не зависят от ресурсов зависимостей с `yield`. + +Например, вместо того чтобы использовать ту же сессию базы данных, вы создадите новую сессию базы данных внутри фоновой задачи и будете получать объекты из базы данных с помощью этой новой сессии. А затем, вместо того чтобы передавать объект из базы данных в качестве параметра в функцию фоновой задачи, вы передадите идентификатор этого объекта, а затем снова получите объект в функции фоновой задачи. + +## Контекстные менеджеры + +### Что такое "контекстные менеджеры" + +"Контекстные менеджеры" - это любые объекты Python, которые можно использовать в операторе `with`. + +Например, можно использовать `with` для чтения файла: + +```Python +with open("./somefile.txt") as f: + contents = f.read() + print(contents) +``` + +Под капотом" open("./somefile.txt") создаёт объект называемый "контекстным менеджером". + +Когда блок `with` завершается, он обязательно закрывает файл, даже если были исключения. + +Когда вы создаете зависимость с помощью `yield`, **FastAPI** внутренне преобразует ее в контекстный менеджер и объединяет с некоторыми другими связанными инструментами. + +### Использование менеджеров контекста в зависимостях с помощью `yield` + +/// warning | Внимание + +Это более или менее "продвинутая" идея. + +Если вы только начинаете работать с **FastAPI**, то лучше пока пропустить этот пункт. + +/// + +В Python для создания менеджеров контекста можно создать класс с двумя методами: `__enter__()` и `__exit__()`. + +Вы также можете использовать их внутри зависимостей **FastAPI** с `yield`, используя операторы +`with` или `async with` внутри функции зависимости: + +{* ../../docs_src/dependencies/tutorial010.py hl[1:9,13] *} + +/// tip | Подсказка + +Другой способ создания контекстного менеджера - с помощью: + +* `@contextlib.contextmanager` или +* `@contextlib.asynccontextmanager` + +используйте их для оформления функции с одним `yield`. + +Это то, что **FastAPI** использует внутри себя для зависимостей с `yield`. + +Но использовать декораторы для зависимостей FastAPI не обязательно (да и не стоит). + +FastAPI сделает это за вас на внутреннем уровне. + +/// diff --git a/docs/ru/docs/tutorial/dependencies/global-dependencies.md b/docs/ru/docs/tutorial/dependencies/global-dependencies.md index eb1b4d7c1..5d2e70f6e 100644 --- a/docs/ru/docs/tutorial/dependencies/global-dependencies.md +++ b/docs/ru/docs/tutorial/dependencies/global-dependencies.md @@ -6,26 +6,7 @@ В этом случае они будут применяться ко всем *операциям пути* в приложении: -=== "Python 3.9+" - - ```Python hl_lines="16" - {!> ../../../docs_src/dependencies/tutorial012_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="16" - {!> ../../../docs_src/dependencies/tutorial012_an.py!} - ``` - -=== "Python 3.8 non-Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать 'Annotated' версию, если это возможно. - - ```Python hl_lines="15" - {!> ../../../docs_src/dependencies/tutorial012.py!} - ``` +{* ../../docs_src/dependencies/tutorial012_an_py39.py hl[16] *} Все способы [добавления зависимостей в *декораторах операций пути*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} по-прежнему применимы, но в данном случае зависимости применяются ко всем *операциям пути* приложения. diff --git a/docs/ru/docs/tutorial/dependencies/index.md b/docs/ru/docs/tutorial/dependencies/index.md new file mode 100644 index 000000000..28790bd5a --- /dev/null +++ b/docs/ru/docs/tutorial/dependencies/index.md @@ -0,0 +1,244 @@ +# Зависимости + +**FastAPI** имеет очень мощную и интуитивную систему **Dependency Injection**. + +Она проектировалась таким образом, чтобы быть простой в использовании и облегчить любому разработчику интеграцию других компонентов с **FastAPI**. + +## Что такое "Dependency Injection" (инъекция зависимости) + +**"Dependency Injection"** в программировании означает, что у вашего кода (в данном случае, вашей *функции обработки пути*) есть способы объявить вещи, которые запрашиваются для работы и использования: "зависимости". + +И потом эта система (в нашем случае **FastAPI**) организует всё, что требуется, чтобы обеспечить ваш код этой зависимостью (сделать "инъекцию" зависимости). + +Это очень полезно, когда вам нужно: + +* Обеспечить общую логику (один и тот же алгоритм снова и снова). +* Общее соединение с базой данных. +* Обеспечение безопасности, аутентификации, запроса роли и т.п. +* И многое другое. + +Всё это минимизирует повторение кода. + +## Первые шаги + +Давайте рассмотрим очень простой пример. Он настолько простой, что на данный момент почти бесполезный. + +Но таким способом мы можем сфокусироваться на том, как же всё таки работает система **Dependency Injection**. + +### Создание зависимости или "зависимого" +Давайте для начала сфокусируемся на зависимостях. + +Это просто функция, которая может принимать все те же параметры, что и *функции обработки пути*: +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[8:9] *} + +**И всё.** + +**2 строки.** + +И теперь она той же формы и структуры, что и все ваши *функции обработки пути*. + +Вы можете думать об *функции обработки пути* как о функции без "декоратора" (без `@app.get("/some-path")`). + +И она может возвращать всё, что требуется. + +В этом случае, эта зависимость ожидает: + +* Необязательный query-параметр `q` с типом `str` +* Необязательный query-параметр `skip` с типом `int`, и значением по умолчанию `0` +* Необязательный query-параметр `limit` с типом `int`, и значением по умолчанию `100` + +И в конце она возвращает `dict`, содержащий эти значения. + +/// info | Информация + +**FastAPI** добавил поддержку для `Annotated` (и начал её рекомендовать) в версии 0.95.0. + + Если у вас более старая версия, будут ошибки при попытке использовать `Annotated`. + +Убедитесь, что вы [Обновили FastAPI версию](../../deployment/versions.md#fastapi_2){.internal-link target=_blank} до, как минимум 0.95.1, перед тем как использовать `Annotated`. + +/// + +### Import `Depends` + +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[3] *} + +### Объявите зависимость в "зависимом" + +Точно так же, как вы использовали `Body`, `Query` и т.д. с вашей *функцией обработки пути* для параметров, используйте `Depends` с новым параметром: + +{* ../../docs_src/dependencies/tutorial001_an_py310.py hl[13,18] *} + +`Depends` работает немного иначе. Вы передаёте в `Depends` одиночный параметр, который будет похож на функцию. + +Вы **не вызываете его** на месте (не добавляете скобочки в конце: 👎 *your_best_func()*👎), просто передаёте как параметр в `Depends()`. + +И потом функция берёт параметры так же, как *функция обработки пути*. + +/// tip | Подсказка + +В следующей главе вы увидите, какие другие вещи, помимо функций, можно использовать в качестве зависимостей. + +/// + +Каждый раз, когда новый запрос приходит, **FastAPI** позаботится о: + +* Вызове вашей зависимости ("зависимого") функции с корректными параметрами. +* Получении результата из вашей функции. +* Назначении результата в параметр в вашей *функции обработки пути*. + +```mermaid +graph TB + +common_parameters(["common_parameters"]) +read_items["/items/"] +read_users["/users/"] + +common_parameters --> read_items +common_parameters --> read_users +``` + +Таким образом, вы пишете общий код один раз, и **FastAPI** позаботится о его вызове для ваших *операций с путями*. + +/// check | Проверка + +Обратите внимание, что вы не создаёте специальный класс и не передаёте его куда-то в **FastAPI** для регистрации, или что-то в этом роде. + +Вы просто передаёте это в `Depends`, и **FastAPI** знает, что делать дальше. + +/// + +## Объединяем с `Annotated` зависимостями + +В приведенном выше примере есть небольшое **повторение кода**. + +Когда вам нужно использовать `common_parameters()` зависимость, вы должны написать весь параметр с аннотацией типов и `Depends()`: + +```Python +commons: Annotated[dict, Depends(common_parameters)] +``` + +Но потому что мы используем `Annotated`, мы можем хранить `Annotated` значение в переменной и использовать его в нескольких местах: + +{* ../../docs_src/dependencies/tutorial001_02_an_py310.py hl[12,16,21] *} + +/// tip | Подсказка + +Это стандартный синтаксис python и называется "type alias", это не особенность **FastAPI**. + +Но потому что **FastAPI** базируется на стандартах Python, включая `Annotated`, вы можете использовать этот трюк в вашем коде. 😎 + +/// + +Зависимости продолжат работу как ожидалось, и **лучшая часть** в том, что **информация о типе будет сохранена**. Это означает, что ваш редактор кода будет корректно обрабатывать **автодополнения**, **встроенные ошибки** и так далее. То же самое относится и к инструментам, таким как `mypy`. + +Это очень полезно, когда вы интегрируете это в **большую кодовую базу**, используя **одинаковые зависимости** снова и снова во **многих** ***операциях пути***. + +## Использовать `async` или не `async` + +Для зависимостей, вызванных **FastAPI** (то же самое, что и ваши *функции обработки пути*), те же правила, что приняты для определения ваших функций. + +Вы можете использовать `async def` или обычное `def`. + +Вы также можете объявить зависимости с `async def` внутри обычной `def` *функции обработки пути*, или `def` зависимости внутри `async def` *функции обработки пути*, и так далее. + +Это всё не важно. **FastAPI** знает, что нужно сделать. 😎 + +/// note | Информация + +Если вам эта тема не знакома, прочтите [Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank} раздел о `async` и `await` в документации. + +/// + +## Интеграция с OpenAPI + +Все заявления о запросах, валидаторы, требования ваших зависимостей (и подзависимостей) будут интегрированы в соответствующую OpenAPI-схему. + +В интерактивной документации будет вся информация по этим зависимостям тоже: + + + +## Простое использование + +Если вы посмотрите на фото, *функция обработки пути* объявляется каждый раз, когда вычисляется путь, и тогда **FastAPI** позаботится о вызове функции с корректными параметрами, извлекая информацию из запроса. + +На самом деле, все (или большинство) веб-фреймворков работают по схожему сценарию. + +Вы никогда не вызываете эти функции на месте. Их вызовет ваш фреймворк (в нашем случае, **FastAPI**). + +С системой Dependency Injection, вы можете сообщить **FastAPI**, что ваша *функция обработки пути* "зависит" от чего-то ещё, что должно быть извлечено перед вашей *функцией обработки пути*, и **FastAPI** позаботится об извлечении и инъекции результата. + +Другие распространённые термины для описания схожей идеи "dependency injection" являются: + +- ресурсность +- доставка +- сервисность +- инъекция +- компонентность + +## **FastAPI** подключаемые модули + +Инъекции и модули могут быть построены с использованием системы **Dependency Injection**. Но на самом деле, **нет необходимости создавать новые модули**, просто используя зависимости, можно объявить бесконечное количество интеграций и взаимодействий, которые доступны вашей *функции обработки пути*. + +И зависимости могут быть созданы очень простым и интуитивным способом, что позволяет вам просто импортировать нужные пакеты Python и интегрировать их в API функции за пару строк. + +Вы увидите примеры этого в следующих главах о реляционных и NoSQL базах данных, безопасности и т.д. + +## Совместимость с **FastAPI** + +Простота Dependency Injection делает **FastAPI** совместимым с: + +- всеми реляционными базами данных +- NoSQL базами данных +- внешними пакетами +- внешними API +- системами авторизации, аутентификации +- системами мониторинга использования API +- системами ввода данных ответов +- и так далее. + +## Просто и сильно + +Хотя иерархическая система Dependency Injection очень проста для описания и использования, она по-прежнему очень мощная. + +Вы можете описывать зависимости в очередь, и они уже будут вызываться друг за другом. + +Когда иерархическое дерево построено, система **Dependency Injection** берет на себя решение всех зависимостей для вас (и их подзависимостей) и обеспечивает (инъектирует) результат на каждом шаге. + +Например, у вас есть 4 API-эндпоинта (*операции пути*): + +- `/items/public/` +- `/items/private/` +- `/users/{user_id}/activate` +- `/items/pro/` + +Тогда вы можете требовать разные права для каждого из них, используя зависимости и подзависимости: + +```mermaid +graph TB + +current_user(["current_user"]) +active_user(["active_user"]) +admin_user(["admin_user"]) +paying_user(["paying_user"]) + +public["/items/public/"] +private["/items/private/"] +activate_user["/users/{user_id}/activate"] +pro_items["/items/pro/"] + +current_user --> active_user +active_user --> admin_user +active_user --> paying_user + +current_user --> public +active_user --> private +admin_user --> activate_user +paying_user --> pro_items +``` + +## Интегрировано с **OpenAPI** + +Все эти зависимости, объявляя свои требования, также добавляют параметры, проверки и т.д. к вашим операциям *path*. + +**FastAPI** позаботится о добавлении всего этого в схему открытого API, чтобы это отображалось в системах интерактивной документации. diff --git a/docs/ru/docs/tutorial/dependencies/sub-dependencies.md b/docs/ru/docs/tutorial/dependencies/sub-dependencies.md new file mode 100644 index 000000000..5e8de0c4a --- /dev/null +++ b/docs/ru/docs/tutorial/dependencies/sub-dependencies.md @@ -0,0 +1,105 @@ +# Подзависимости + +Вы можете создавать зависимости, которые имеют **подзависимости**. + +Их **вложенность** может быть любой глубины. + +**FastAPI** сам займётся их управлением. + +## Провайдер зависимости + +Можно создать первую зависимость следующим образом: + +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[8:9] *} + +Она объявляет необязательный параметр запроса `q` как строку, а затем возвращает его. + +Это довольно просто (хотя и не очень полезно), но поможет нам сосредоточиться на том, как работают подзависимости. + +## Вторая зависимость + +Затем можно создать еще одну функцию зависимости, которая в то же время содержит внутри себя первую зависимость (таким образом, она тоже является "зависимой"): + +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[13] *} + +Остановимся на объявленных параметрах: + +* Несмотря на то, что эта функция сама является зависимостью, она также является зависимой от чего-то другого. + * Она зависит от `query_extractor` и присваивает возвращаемое ей значение параметру `q`. +* Она также объявляет необязательный куки-параметр `last_query` в виде строки. + * Если пользователь не указал параметр `q` в запросе, то мы используем последний использованный запрос, который мы ранее сохранили в куки-параметре `last_query`. + +## Использование зависимости + +Затем мы можем использовать зависимость вместе с: + +{* ../../docs_src/dependencies/tutorial005_an_py310.py hl[23] *} + +/// info | Дополнительная информация + +Обратите внимание, что мы объявляем только одну зависимость в *функции операции пути* - `query_or_cookie_extractor`. + +Но **FastAPI** будет знать, что сначала он должен выполнить `query_extractor`, чтобы передать результаты этого в `query_or_cookie_extractor` при его вызове. + +/// + +```mermaid +graph TB + +query_extractor(["query_extractor"]) +query_or_cookie_extractor(["query_or_cookie_extractor"]) + +read_query["/items/"] + +query_extractor --> query_or_cookie_extractor --> read_query +``` + +## Использование одной и той же зависимости несколько раз + +Если одна из ваших зависимостей объявлена несколько раз для одной и той же *функции операции пути*, например, несколько зависимостей имеют общую подзависимость, **FastAPI** будет знать, что вызывать эту подзависимость нужно только один раз за запрос. + +При этом возвращаемое значение будет сохранено в "кэш" и будет передано всем "зависимым" функциям, которые нуждаются в нем внутри этого конкретного запроса, вместо того, чтобы вызывать зависимость несколько раз для одного и того же запроса. + +В расширенном сценарии, когда вы знаете, что вам нужно, чтобы зависимость вызывалась на каждом шаге (возможно, несколько раз) в одном и том же запросе, вместо использования "кэшированного" значения, вы можете установить параметр `use_cache=False` при использовании `Depends`: + +//// tab | Python 3.6+ + +```Python hl_lines="1" +async def needy_dependency(fresh_value: Annotated[str, Depends(get_value, use_cache=False)]): + return {"fresh_value": fresh_value} +``` + +//// + +//// tab | Python 3.6+ без Annotated + +/// tip | Подсказка + +Предпочтительнее использовать версию с аннотацией, если это возможно. + +/// + +```Python hl_lines="1" +async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False)): + return {"fresh_value": fresh_value} +``` + +//// + +## Резюме + +Помимо всех этих умных слов, используемых здесь, система внедрения зависимостей довольно проста. + +Это просто функции, которые выглядят так же, как *функции операций путей*. + +Но, тем не менее, эта система очень мощная и позволяет вам объявлять вложенные графы (деревья) зависимостей сколь угодно глубоко. + +/// tip | Подсказка + +Все это может показаться не столь полезным на этих простых примерах. + +Но вы увидите как это пригодится в главах посвященных безопасности. + +И вы также увидите, сколько кода это вам сэкономит. + +/// diff --git a/docs/ru/docs/tutorial/encoder.md b/docs/ru/docs/tutorial/encoder.md new file mode 100644 index 000000000..4ed5039b3 --- /dev/null +++ b/docs/ru/docs/tutorial/encoder.md @@ -0,0 +1,35 @@ +# JSON кодировщик + +В некоторых случаях может потребоваться преобразование типа данных (например, Pydantic-модели) в тип, совместимый с JSON (например, `dict`, `list` и т.д.). + +Например, если необходимо хранить его в базе данных. + +Для этого **FastAPI** предоставляет функцию `jsonable_encoder()`. + +## Использование `jsonable_encoder` + +Представим, что у вас есть база данных `fake_db`, которая принимает только JSON-совместимые данные. + +Например, он не принимает объекты `datetime`, так как они не совместимы с JSON. + +В таком случае объект `datetime` следует преобразовать в строку соответствующую формату ISO. + +Точно так же эта база данных не может принять Pydantic модель (объект с атрибутами), а только `dict`. + +Для этого можно использовать функцию `jsonable_encoder`. + +Она принимает объект, например, модель Pydantic, и возвращает его версию, совместимую с JSON: + +{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *} + +В данном примере она преобразует Pydantic модель в `dict`, а `datetime` - в `str`. + +Результатом её вызова является объект, который может быть закодирован с помощью функции из стандартной библиотеки Python – `json.dumps()`. + +Функция не возвращает большой `str`, содержащий данные в формате JSON (в виде строки). Она возвращает стандартную структуру данных Python (например, `dict`) со значениями и подзначениями, которые совместимы с JSON. + +/// note | Технические детали + +`jsonable_encoder` фактически используется **FastAPI** внутри системы для преобразования данных. Однако он полезен и во многих других сценариях. + +/// diff --git a/docs/ru/docs/tutorial/extra-data-types.md b/docs/ru/docs/tutorial/extra-data-types.md index 0f613a6b2..6d6d4aa9f 100644 --- a/docs/ru/docs/tutorial/extra-data-types.md +++ b/docs/ru/docs/tutorial/extra-data-types.md @@ -36,7 +36,7 @@ * `datetime.timedelta`: * Встроенный в Python `datetime.timedelta`. * В запросах и ответах будет представлен в виде общего количества секунд типа `float`. - * Pydantic также позволяет представить его как "Кодировку разницы во времени ISO 8601", см. документацию для получения дополнительной информации. + * Pydantic также позволяет представить его как "Кодировку разницы во времени ISO 8601", см. документацию для получения дополнительной информации. * `frozenset`: * В запросах и ответах обрабатывается так же, как и `set`: * В запросах будет прочитан список, исключены дубликаты и преобразован в `set`. @@ -49,34 +49,14 @@ * `Decimal`: * Встроенный в Python `Decimal`. * В запросах и ответах обрабатывается так же, как и `float`. -* Вы можете проверить все допустимые типы данных pydantic здесь: Типы данных Pydantic. +* Вы можете проверить все допустимые типы данных pydantic здесь: Типы данных Pydantic. ## Пример Вот пример *операции пути* с параметрами, который демонстрирует некоторые из вышеперечисленных типов. -=== "Python 3.8 и выше" - - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` - -=== "Python 3.10 и выше" - - ```Python hl_lines="1 2 11-15" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +{* ../../docs_src/extra_data_types/tutorial001.py hl[1,3,12:16] *} Обратите внимание, что параметры внутри функции имеют свой естественный тип данных, и вы, например, можете выполнять обычные манипуляции с датами, такие как: -=== "Python 3.8 и выше" - - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` - -=== "Python 3.10 и выше" - - ```Python hl_lines="17-18" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` +{* ../../docs_src/extra_data_types/tutorial001.py hl[18:19] *} diff --git a/docs/ru/docs/tutorial/extra-models.md b/docs/ru/docs/tutorial/extra-models.md index 30176b4e3..5b51aa402 100644 --- a/docs/ru/docs/tutorial/extra-models.md +++ b/docs/ru/docs/tutorial/extra-models.md @@ -8,26 +8,19 @@ * **Модель для вывода** не должна содержать пароль. * **Модель для базы данных**, возможно, должна содержать хэшированный пароль. -!!! danger "Внимание" - Никогда не храните пароли пользователей в чистом виде. Всегда храните "безопасный хэш", который вы затем сможете проверить. +/// danger | Внимание - Если вам это не знакомо, вы можете узнать про "хэш пароля" в [главах о безопасности](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}. +Никогда не храните пароли пользователей в чистом виде. Всегда храните "безопасный хэш", который вы затем сможете проверить. -## Множественные модели - -Ниже изложена основная идея того, как могут выглядеть эти модели с полями для паролей, а также описаны места, где они используются: +Если вам это не знакомо, вы можете узнать про "хэш пароля" в [главах о безопасности](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}. -=== "Python 3.10+" +/// - ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" - {!> ../../../docs_src/extra_models/tutorial001_py310.py!} - ``` +## Множественные модели -=== "Python 3.8+" +Ниже изложена основная идея того, как могут выглядеть эти модели с полями для паролей, а также описаны места, где они используются: - ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" - {!> ../../../docs_src/extra_models/tutorial001.py!} - ``` +{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *} ### Про `**user_in.dict()` @@ -139,8 +132,11 @@ UserInDB( ) ``` -!!! warning "Предупреждение" - Цель использованных в примере вспомогательных функций - не более чем демонстрация возможных операций с данными, но, конечно, они не обеспечивают настоящую безопасность. +/// warning | Предупреждение + +Цель использованных в примере вспомогательных функций - не более чем демонстрация возможных операций с данными, но, конечно, они не обеспечивают настоящую безопасность. + +/// ## Сократите дублирование @@ -158,17 +154,7 @@ UserInDB( В этом случае мы можем определить только различия между моделями (с `password` в чистом виде, с `hashed_password` и без пароля): -=== "Python 3.10+" - - ```Python hl_lines="7 13-14 17-18 21-22" - {!> ../../../docs_src/extra_models/tutorial002_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="9 15-16 19-20 23-24" - {!> ../../../docs_src/extra_models/tutorial002.py!} - ``` +{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *} ## `Union` или `anyOf` @@ -178,20 +164,13 @@ UserInDB( Для этого используйте стандартные аннотации типов в Python `typing.Union`: -!!! note "Примечание" - При объявлении `Union`, сначала указывайте наиболее детальные типы, затем менее детальные. В примере ниже более детальный `PlaneItem` стоит перед `CarItem` в `Union[PlaneItem, CarItem]`. - -=== "Python 3.10+" +/// note | Примечание - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003_py310.py!} - ``` +При объявлении `Union`, сначала указывайте наиболее детальные типы, затем менее детальные. В примере ниже более детальный `PlaneItem` стоит перед `CarItem` в `Union[PlaneItem, CarItem]`. -=== "Python 3.8+" +/// - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003.py!} - ``` +{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *} ### `Union` в Python 3.10 @@ -213,17 +192,7 @@ some_variable: PlaneItem | CarItem Для этого используйте `typing.List` из стандартной библиотеки Python (или просто `list` в Python 3.9 и выше): -=== "Python 3.9+" - - ```Python hl_lines="18" - {!> ../../../docs_src/extra_models/tutorial004_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="1 20" - {!> ../../../docs_src/extra_models/tutorial004.py!} - ``` +{* ../../docs_src/extra_models/tutorial004_py39.py hl[18] *} ## Ответ с произвольным `dict` @@ -233,17 +202,7 @@ some_variable: PlaneItem | CarItem В этом случае вы можете использовать `typing.Dict` (или просто `dict` в Python 3.9 и выше): -=== "Python 3.9+" - - ```Python hl_lines="6" - {!> ../../../docs_src/extra_models/tutorial005_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="1 8" - {!> ../../../docs_src/extra_models/tutorial005.py!} - ``` +{* ../../docs_src/extra_models/tutorial005_py39.py hl[6] *} ## Резюме diff --git a/docs/ru/docs/tutorial/first-steps.md b/docs/ru/docs/tutorial/first-steps.md index b46f235bc..cb3d19a71 100644 --- a/docs/ru/docs/tutorial/first-steps.md +++ b/docs/ru/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ Самый простой FastAPI файл может выглядеть так: -```Python -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} Скопируйте в файл `main.py`. @@ -24,12 +22,15 @@ $ uvicorn main:app --reload
-!!! note "Технические детали" - Команда `uvicorn main:app` обращается к: +/// note | Технические детали + +Команда `uvicorn main:app` обращается к: + +* `main`: файл `main.py` (модуль Python). +* `app`: объект, созданный внутри файла `main.py` в строке `app = FastAPI()`. +* `--reload`: перезапускает сервер после изменения кода. Используйте только для разработки. - * `main`: файл `main.py` (модуль Python). - * `app`: объект, созданный внутри файла `main.py` в строке `app = FastAPI()`. - * `--reload`: перезапускает сервер после изменения кода. Используйте только для разработки. +/// В окне вывода появится следующая строка: @@ -130,22 +131,21 @@ OpenAPI описывает схему API. Эта схема содержит о ### Шаг 1: импортируйте `FastAPI` -```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI` это класс в Python, который предоставляет всю функциональность для API. -!!! note "Технические детали" - `FastAPI` это класс, который наследуется непосредственно от `Starlette`. +/// note | Технические детали + +`FastAPI` это класс, который наследуется непосредственно от `Starlette`. - Вы можете использовать всю функциональность Starlette в `FastAPI`. +Вы можете использовать всю функциональность Starlette в `FastAPI`. + +/// ### Шаг 2: создайте экземпляр `FastAPI` -```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[3] *} Переменная `app` является экземпляром класса `FastAPI`. @@ -165,9 +165,7 @@ $ uvicorn main:app --reload Если создать такое приложение: -```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} -``` +{* ../../docs_src/first_steps/tutorial002.py hl[3] *} И поместить его в `main.py`, тогда вызов `uvicorn` будет таким: @@ -199,8 +197,11 @@ https://example.com/items/foo /items/foo ``` -!!! info "Дополнительная иформация" - Термин "path" также часто называется "endpoint" или "route". +/// info | Дополнительная иформация + +Термин "path" также часто называется "endpoint" или "route". + +/// При создании API, "путь" является основным способом разделения "задач" и "ресурсов". @@ -241,25 +242,26 @@ https://example.com/items/foo #### Определите *декоратор операции пути (path operation decorator)* -```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[6] *} Декоратор `@app.get("/")` указывает **FastAPI**, что функция, прямо под ним, отвечает за обработку запросов, поступающих по адресу: * путь `/` * использующих get операцию -!!! info "`@decorator` Дополнительная информация" - Синтаксис `@something` в Python называется "декоратор". +/// info | `@decorator` Дополнительная информация + +Синтаксис `@something` в Python называется "декоратор". + +Вы помещаете его над функцией. Как красивую декоративную шляпу (думаю, что оттуда и происходит этот термин). - Вы помещаете его над функцией. Как красивую декоративную шляпу (думаю, что оттуда и происходит этот термин). +"Декоратор" принимает функцию ниже и выполняет с ней какое-то действие. - "Декоратор" принимает функцию ниже и выполняет с ней какое-то действие. +В нашем случае, этот декоратор сообщает **FastAPI**, что функция ниже соответствует **пути** `/` и **операции** `get`. - В нашем случае, этот декоратор сообщает **FastAPI**, что функция ниже соответствует **пути** `/` и **операции** `get`. +Это и есть "**декоратор операции пути**". - Это и есть "**декоратор операции пути**". +/// Можно также использовать операции: @@ -274,14 +276,17 @@ https://example.com/items/foo * `@app.patch()` * `@app.trace()` -!!! tip "Подсказка" - Вы можете использовать каждую операцию (HTTP-метод) по своему усмотрению. +/// tip | Подсказка + +Вы можете использовать каждую операцию (HTTP-метод) по своему усмотрению. + +**FastAPI** не навязывает определенного значения для каждого метода. - **FastAPI** не навязывает определенного значения для каждого метода. +Информация здесь представлена как рекомендация, а не требование. - Информация здесь представлена как рекомендация, а не требование. +Например, при использовании GraphQL обычно все действия выполняются только с помощью POST операций. - Например, при использовании GraphQL обычно все действия выполняются только с помощью POST операций. +/// ### Шаг 4: определите **функцию операции пути** @@ -291,9 +296,7 @@ https://example.com/items/foo * **операция**: `get`. * **функция**: функция ниже "декоратора" (ниже `@app.get("/")`). -```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[7] *} Это обычная Python функция. @@ -305,18 +308,17 @@ https://example.com/items/foo Вы также можете определить ее как обычную функцию вместо `async def`: -```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} -``` +{* ../../docs_src/first_steps/tutorial003.py hl[7] *} + +/// note | Технические детали -!!! note "Технические детали" - Если не знаете в чём разница, посмотрите [Конкурентность: *"Нет времени?"*](../async.md#in-a-hurry){.internal-link target=_blank}. +Если не знаете в чём разница, посмотрите [Конкурентность: *"Нет времени?"*](../async.md#_1){.internal-link target=_blank}. + +/// ### Шаг 5: верните результат -```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[8] *} Вы можете вернуть `dict`, `list`, отдельные значения `str`, `int` и т.д. diff --git a/docs/ru/docs/tutorial/handling-errors.md b/docs/ru/docs/tutorial/handling-errors.md new file mode 100644 index 000000000..c596abe1f --- /dev/null +++ b/docs/ru/docs/tutorial/handling-errors.md @@ -0,0 +1,257 @@ +# Обработка ошибок + +Существует множество ситуаций, когда необходимо сообщить об ошибке клиенту, использующему ваш API. + +Таким клиентом может быть браузер с фронтендом, чужой код, IoT-устройство и т.д. + +Возможно, вам придется сообщить клиенту о следующем: + +* Клиент не имеет достаточных привилегий для выполнения данной операции. +* Клиент не имеет доступа к данному ресурсу. +* Элемент, к которому клиент пытался получить доступ, не существует. +* и т.д. + +В таких случаях обычно возвращается **HTTP-код статуса ответа** в диапазоне **400** (от 400 до 499). + +Они похожи на двухсотые HTTP статус-коды (от 200 до 299), которые означают, что запрос обработан успешно. + +Четырёхсотые статус-коды означают, что ошибка произошла по вине клиента. + +Помните ли ошибки **"404 Not Found "** (и шутки) ? + +## Использование `HTTPException` + +Для возврата клиенту HTTP-ответов с ошибками используется `HTTPException`. + +### Импортируйте `HTTPException` + +{* ../../docs_src/handling_errors/tutorial001.py hl[1] *} + +### Вызовите `HTTPException` в своем коде + +`HTTPException` - это обычное исключение Python с дополнительными данными, актуальными для API. + +Поскольку это исключение Python, то его не `возвращают`, а `вызывают`. + +Это также означает, что если вы находитесь внутри функции, которая вызывается внутри вашей *функции операции пути*, и вы поднимаете `HTTPException` внутри этой функции, то она не будет выполнять остальной код в *функции операции пути*, а сразу завершит запрос и отправит HTTP-ошибку из `HTTPException` клиенту. + +О том, насколько выгоднее `вызывать` исключение, чем `возвращать` значение, будет рассказано в разделе, посвященном зависимостям и безопасности. + +В данном примере, когда клиент запрашивает элемент по несуществующему ID, возникает исключение со статус-кодом `404`: + +{* ../../docs_src/handling_errors/tutorial001.py hl[11] *} + +### Возвращаемый ответ + +Если клиент запросит `http://example.com/items/foo` (`item_id` `"foo"`), то он получит статус-код 200 и ответ в формате JSON: + +```JSON +{ + "item": "The Foo Wrestlers" +} +``` + +Но если клиент запросит `http://example.com/items/bar` (несуществующий `item_id` `"bar"`), то он получит статус-код 404 (ошибка "не найдено") и JSON-ответ в виде: + +```JSON +{ + "detail": "Item not found" +} +``` + +/// tip | Подсказка + +При вызове `HTTPException` в качестве параметра `detail` можно передавать любое значение, которое может быть преобразовано в JSON, а не только `str`. + +Вы можете передать `dict`, `list` и т.д. + +Они автоматически обрабатываются **FastAPI** и преобразуются в JSON. + +/// + +## Добавление пользовательских заголовков + +В некоторых ситуациях полезно иметь возможность добавлять пользовательские заголовки к ошибке HTTP. Например, для некоторых типов безопасности. + +Скорее всего, вам не потребуется использовать его непосредственно в коде. + +Но в случае, если это необходимо для продвинутого сценария, можно добавить пользовательские заголовки: + +{* ../../docs_src/handling_errors/tutorial002.py hl[14] *} + +## Установка пользовательских обработчиков исключений + +Вы можете добавить пользовательские обработчики исключений с помощью то же самое исключение - утилиты от Starlette. + +Допустим, у вас есть пользовательское исключение `UnicornException`, которое вы (или используемая вами библиотека) можете `вызвать`. + +И вы хотите обрабатывать это исключение глобально с помощью FastAPI. + +Можно добавить собственный обработчик исключений с помощью `@app.exception_handler()`: + +{* ../../docs_src/handling_errors/tutorial003.py hl[5:7,13:18,24] *} + +Здесь, если запросить `/unicorns/yolo`, то *операция пути* вызовет `UnicornException`. + +Но оно будет обработано `unicorn_exception_handler`. + +Таким образом, вы получите чистую ошибку с кодом состояния HTTP `418` и содержимым JSON: + +```JSON +{"message": "Oops! yolo did something. There goes a rainbow..."} +``` + +/// note | Технические детали + +Также можно использовать `from starlette.requests import Request` и `from starlette.responses import JSONResponse`. + +**FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. То же самое касается и `Request`. + +/// + +## Переопределение стандартных обработчиков исключений + +**FastAPI** имеет некоторые обработчики исключений по умолчанию. + +Эти обработчики отвечают за возврат стандартных JSON-ответов при `вызове` `HTTPException` и при наличии в запросе недопустимых данных. + +Вы можете переопределить эти обработчики исключений на свои собственные. + +### Переопределение исключений проверки запроса + +Когда запрос содержит недопустимые данные, **FastAPI** внутренне вызывает ошибку `RequestValidationError`. + +А также включает в себя обработчик исключений по умолчанию. + +Чтобы переопределить его, импортируйте `RequestValidationError` и используйте его с `@app.exception_handler(RequestValidationError)` для создания обработчика исключений. + +Обработчик исключения получит объект `Request` и исключение. + +{* ../../docs_src/handling_errors/tutorial004.py hl[2,14:16] *} + +Теперь, если перейти к `/items/foo`, то вместо стандартной JSON-ошибки с: + +```JSON +{ + "detail": [ + { + "loc": [ + "path", + "item_id" + ], + "msg": "value is not a valid integer", + "type": "type_error.integer" + } + ] +} +``` + +вы получите текстовую версию: + +``` +1 validation error +path -> item_id + value is not a valid integer (type=type_error.integer) +``` + +#### `RequestValidationError` или `ValidationError` + +/// warning | Внимание + +Это технические детали, которые можно пропустить, если они не важны для вас сейчас. + +/// + +`RequestValidationError` является подклассом Pydantic `ValidationError`. + +**FastAPI** использует его для того, чтобы, если вы используете Pydantic-модель в `response_model`, и ваши данные содержат ошибку, вы увидели ошибку в журнале. + +Но клиент/пользователь этого не увидит. Вместо этого клиент получит сообщение "Internal Server Error" с кодом состояния HTTP `500`. + +Так и должно быть, потому что если в вашем *ответе* или где-либо в вашем коде (не в *запросе* клиента) возникает Pydantic `ValidationError`, то это действительно ошибка в вашем коде. + +И пока вы не устраните ошибку, ваши клиенты/пользователи не должны иметь доступа к внутренней информации о ней, так как это может привести к уязвимости в системе безопасности. + +### Переопределите обработчик ошибок `HTTPException` + +Аналогичным образом можно переопределить обработчик `HTTPException`. + +Например, для этих ошибок можно вернуть обычный текстовый ответ вместо JSON: + +{* ../../docs_src/handling_errors/tutorial004.py hl[3:4,9:11,22] *} + +/// note | Технические детали + +Можно также использовать `from starlette.responses import PlainTextResponse`. + +**FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. + +/// + +### Используйте тело `RequestValidationError` + +Ошибка `RequestValidationError` содержит полученное `тело` с недопустимыми данными. + +Вы можете использовать его при разработке приложения для регистрации тела и его отладки, возврата пользователю и т.д. + +{* ../../docs_src/handling_errors/tutorial005.py hl[14] *} + +Теперь попробуйте отправить недействительный элемент, например: + +```JSON +{ + "title": "towel", + "size": "XL" +} +``` + +Вы получите ответ о том, что данные недействительны, содержащий следующее тело: + +```JSON hl_lines="12-15" +{ + "detail": [ + { + "loc": [ + "body", + "size" + ], + "msg": "value is not a valid integer", + "type": "type_error.integer" + } + ], + "body": { + "title": "towel", + "size": "XL" + } +} +``` + +#### `HTTPException` в FastAPI или в Starlette + +**FastAPI** имеет собственный `HTTPException`. + +Класс ошибок **FastAPI** `HTTPException` наследует от класса ошибок Starlette `HTTPException`. + +Единственное отличие заключается в том, что `HTTPException` от **FastAPI** позволяет добавлять заголовки, которые будут включены в ответ. + +Он необходим/используется внутри системы для OAuth 2.0 и некоторых утилит безопасности. + +Таким образом, вы можете продолжать вызывать `HTTPException` от **FastAPI** как обычно в своем коде. + +Но когда вы регистрируете обработчик исключений, вы должны зарегистрировать его для `HTTPException` от Starlette. + +Таким образом, если какая-либо часть внутреннего кода Starlette, расширение или плагин Starlette вызовет исключение Starlette `HTTPException`, ваш обработчик сможет перехватить и обработать его. + +В данном примере, чтобы иметь возможность использовать оба `HTTPException` в одном коде, исключения Starlette переименованы в `StarletteHTTPException`: + +```Python +from starlette.exceptions import HTTPException as StarletteHTTPException +``` + +### Переиспользование обработчиков исключений **FastAPI** + +Если вы хотите использовать исключение вместе с теми же обработчиками исключений по умолчанию из **FastAPI**, вы можете импортировать и повторно использовать обработчики исключений по умолчанию из `fastapi.exception_handlers`: + +{* ../../docs_src/handling_errors/tutorial006.py hl[2:5,15,21] *} + +В этом примере вы просто `выводите в терминал` ошибку с очень выразительным сообщением, но идея вам понятна. Вы можете использовать исключение, а затем просто повторно использовать стандартные обработчики исключений. diff --git a/docs/ru/docs/tutorial/header-params.md b/docs/ru/docs/tutorial/header-params.md index 1be4ac707..e892cfc07 100644 --- a/docs/ru/docs/tutorial/header-params.md +++ b/docs/ru/docs/tutorial/header-params.md @@ -6,41 +6,7 @@ Сперва импортируйте `Header`: -=== "Python 3.10+" - - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001_an.py!} - ``` - -=== "Python 3.10+ без Annotated" - - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. - - ```Python hl_lines="1" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` - -=== "Python 3.8+ без Annotated" - - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. - - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` +{* ../../docs_src/header_params/tutorial001_an_py310.py hl[3] *} ## Объявление параметров `Header` @@ -48,49 +14,21 @@ Первое значение является значением по умолчанию, вы можете передать все дополнительные параметры валидации или аннотации: -=== "Python 3.10+" +{* ../../docs_src/header_params/tutorial001_an_py310.py hl[9] *} - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001_an_py310.py!} - ``` +/// note | Технические детали -=== "Python 3.9+" +`Header` - это "родственный" класс `Path`, `Query` и `Cookie`. Он также наследуется от того же общего класса `Param`. - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001_an_py39.py!} - ``` +Но помните, что когда вы импортируете `Query`, `Path`, `Header` и другие из `fastapi`, на самом деле это функции, которые возвращают специальные классы. -=== "Python 3.8+" +/// - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial001_an.py!} - ``` +/// info | Дополнительная информация -=== "Python 3.10+ без Annotated" +Чтобы объявить заголовки, важно использовать `Header`, иначе параметры интерпретируются как query-параметры. - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. - - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` - -=== "Python 3.8+ без Annotated" - - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. - - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` - -!!! note "Технические детали" - `Header` - это "родственный" класс `Path`, `Query` и `Cookie`. Он также наследуется от того же общего класса `Param`. - - Но помните, что когда вы импортируете `Query`, `Path`, `Header` и другие из `fastapi`, на самом деле это функции, которые возвращают специальные классы. - -!!! info "Дополнительная информация" - Чтобы объявить заголовки, важно использовать `Header`, иначе параметры интерпретируются как query-параметры. +/// ## Автоматическое преобразование @@ -108,44 +46,13 @@ Если по какой-либо причине вам необходимо отключить автоматическое преобразование подчеркиваний в дефисы, установите для параметра `convert_underscores` в `Header` значение `False`: -=== "Python 3.10+" - - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial002_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="11" - {!> ../../../docs_src/header_params/tutorial002_an_py39.py!} - ``` +{* ../../docs_src/header_params/tutorial002_an_py310.py hl[10] *} -=== "Python 3.8+" +/// warning | Внимание - ```Python hl_lines="12" - {!> ../../../docs_src/header_params/tutorial002_an.py!} - ``` +Прежде чем установить для `convert_underscores` значение `False`, имейте в виду, что некоторые HTTP-прокси и серверы запрещают использование заголовков с подчеркиванием. -=== "Python 3.10+ без Annotated" - - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. - - ```Python hl_lines="8" - {!> ../../../docs_src/header_params/tutorial002_py310.py!} - ``` - -=== "Python 3.8+ без Annotated" - - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. - - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial002.py!} - ``` - -!!! warning "Внимание" - Прежде чем установить для `convert_underscores` значение `False`, имейте в виду, что некоторые HTTP-прокси и серверы запрещают использование заголовков с подчеркиванием. +/// ## Повторяющиеся заголовки @@ -157,50 +64,7 @@ Например, чтобы объявить заголовок `X-Token`, который может появляться более одного раза, вы можете написать: -=== "Python 3.10+" - - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial003_an.py!} - ``` - -=== "Python 3.10+ без Annotated" - - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. - - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial003_py310.py!} - ``` - -=== "Python 3.9+ без Annotated" - - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. - - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_py39.py!} - ``` - -=== "Python 3.8+ без Annotated" - - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. - - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003.py!} - ``` +{* ../../docs_src/header_params/tutorial003_an_py310.py hl[9] *} Если вы взаимодействуете с этой *операцией пути*, отправляя два HTTP-заголовка, таких как: diff --git a/docs/ru/docs/tutorial/index.md b/docs/ru/docs/tutorial/index.md index ea3a1c37a..ddca2fbb1 100644 --- a/docs/ru/docs/tutorial/index.md +++ b/docs/ru/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ...это также включает `uvicorn`, который вы можете использовать в качестве сервера, который запускает ваш код. -!!! note "Технические детали" - Вы также можете установить его по частям. +/// note | Технические детали - Это то, что вы, вероятно, сделаете, когда захотите развернуть свое приложение в рабочей среде: +Вы также можете установить его по частям. - ``` - pip install fastapi - ``` +Это то, что вы, вероятно, сделаете, когда захотите развернуть свое приложение в рабочей среде: - Также установите `uvicorn` для работы в качестве сервера: +``` +pip install fastapi +``` + +Также установите `uvicorn` для работы в качестве сервера: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +И то же самое для каждой из необязательных зависимостей, которые вы хотите использовать. - И то же самое для каждой из необязательных зависимостей, которые вы хотите использовать. +/// ## Продвинутое руководство пользователя diff --git a/docs/ru/docs/tutorial/metadata.md b/docs/ru/docs/tutorial/metadata.md index 331c96734..f07073508 100644 --- a/docs/ru/docs/tutorial/metadata.md +++ b/docs/ru/docs/tutorial/metadata.md @@ -17,12 +17,13 @@ Вы можете задать их следующим образом: -```Python hl_lines="3-16 19-31" -{!../../../docs_src/metadata/tutorial001.py!} -``` +{* ../../docs_src/metadata/tutorial001.py hl[3:16,19:31] *} -!!! tip "Подсказка" - Вы можете использовать Markdown в поле `description`, и оно будет отображено в выводе. +/// tip | Подсказка + +Вы можете использовать Markdown в поле `description`, и оно будет отображено в выводе. + +/// С этой конфигурацией автоматическая документация API будут выглядеть так: @@ -48,24 +49,26 @@ Создайте метаданные для ваших тегов и передайте их в параметре `openapi_tags`: -```Python hl_lines="3-16 18" -{!../../../docs_src/metadata/tutorial004.py!} -``` +{* ../../docs_src/metadata/tutorial004.py hl[3:16,18] *} Помните, что вы можете использовать Markdown внутри описания, к примеру "login" будет отображен жирным шрифтом (**login**) и "fancy" будет отображаться курсивом (_fancy_). -!!! tip "Подсказка" - Вам необязательно добавлять метаданные для всех используемых тегов +/// tip | Подсказка + +Вам необязательно добавлять метаданные для всех используемых тегов + +/// ### Используйте собственные теги Используйте параметр `tags` с вашими *операциями пути* (и `APIRouter`ами), чтобы присвоить им различные теги: -```Python hl_lines="21 26" -{!../../../docs_src/metadata/tutorial004.py!} -``` +{* ../../docs_src/metadata/tutorial004.py hl[21,26] *} + +/// info | Дополнительная информация + +Узнайте больше о тегах в [Конфигурации операции пути](path-operation-configuration.md#_3){.internal-link target=_blank}. -!!! info "Дополнительная информация" - Узнайте больше о тегах в [Конфигурации операции пути](../path-operation-configuration/#tags){.internal-link target=_blank}. +/// ### Проверьте документацию @@ -87,9 +90,7 @@ К примеру, чтобы задать её отображение по адресу `/api/v1/openapi.json`: -```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial002.py!} -``` +{* ../../docs_src/metadata/tutorial002.py hl[3] *} Если вы хотите отключить схему OpenAPI полностью, вы можете задать `openapi_url=None`, это также отключит пользовательские интерфейсы документации, которые его использует. @@ -106,6 +107,4 @@ К примеру, чтобы задать отображение Swagger UI по адресу `/documentation` и отключить ReDoc: -```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial003.py!} -``` +{* ../../docs_src/metadata/tutorial003.py hl[3] *} diff --git a/docs/ru/docs/tutorial/middleware.md b/docs/ru/docs/tutorial/middleware.md new file mode 100644 index 000000000..845e881e1 --- /dev/null +++ b/docs/ru/docs/tutorial/middleware.md @@ -0,0 +1,74 @@ +# Middleware (Промежуточный слой) + +Вы можете добавить промежуточный слой (middleware) в **FastAPI** приложение. + +"Middleware" это функция, которая выполняется с каждым запросом до его обработки какой-либо конкретной *операцией пути*. +А также с каждым ответом перед его возвращением. + + +* Она принимает каждый поступающий **запрос**. +* Может что-то сделать с этим **запросом** или выполнить любой нужный код. +* Затем передает **запрос** для последующей обработки (какой-либо *операцией пути*). +* Получает **ответ** (от *операции пути*). +* Может что-то сделать с этим **ответом** или выполнить любой нужный код. +* И возвращает **ответ**. + +/// note | Технические детали + +Если у вас есть зависимости с `yield`, то код выхода (код после `yield`) будет выполняться *после* middleware. + +Если у вас имеются некие фоновые задачи (см. документацию), то они будут запущены после middleware. + +/// + +## Создание middleware + +Для создания middleware используйте декоратор `@app.middleware("http")`. + +Функция middleware получает: + +* `request` (объект запроса). +* Функцию `call_next`, которая получает `request` в качестве параметра. + * Эта функция передаёт `request` соответствующей *операции пути*. + * Затем она возвращает ответ `response`, сгенерированный *операцией пути*. +* Также имеется возможность видоизменить `response`, перед тем как его вернуть. + +{* ../../docs_src/middleware/tutorial001.py hl[8:9,11,14] *} + +/// tip | Примечание + +Имейте в виду, что можно добавлять свои собственные заголовки при помощи префикса 'X-'. + +Если же вы хотите добавить собственные заголовки, которые клиент сможет увидеть в браузере, то вам потребуется добавить их в настройки CORS ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}), используя параметр `expose_headers`, см. документацию Starlette's CORS docs. + +/// + +/// note | Технические детали + +Вы также можете использовать `from starlette.requests import Request`. + +**FastAPI** предоставляет такой доступ для удобства разработчиков. Но, на самом деле, это `Request` из Starlette. + +/// + +### До и после `response` + +Вы можете добавить код, использующий `request` до передачи его какой-либо *операции пути*. + +А также после формирования `response`, до того, как вы его вернёте. + +Например, вы можете добавить собственный заголовок `X-Process-Time`, содержащий время в секундах, необходимое для обработки запроса и генерации ответа: + +{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *} + +/// tip | Примечание + +Мы используем `time.perf_counter()` вместо `time.time()` для обеспечения большей точности наших примеров. 🤓 + +/// + +## Другие middleware + +О других middleware вы можете узнать больше в разделе [Advanced User Guide: Advanced Middleware](../advanced/middleware.md){.internal-link target=_blank}. + +В следующем разделе вы можете прочитать, как настроить CORS с помощью middleware. diff --git a/docs/ru/docs/tutorial/path-operation-configuration.md b/docs/ru/docs/tutorial/path-operation-configuration.md index db99409f4..af471ca69 100644 --- a/docs/ru/docs/tutorial/path-operation-configuration.md +++ b/docs/ru/docs/tutorial/path-operation-configuration.md @@ -2,8 +2,11 @@ Существует несколько параметров, которые вы можете передать вашему *декоратору операций пути* для его настройки. -!!! warning "Внимание" - Помните, что эти параметры передаются непосредственно *декоратору операций пути*, а не вашей *функции-обработчику операций пути*. +/// warning | Внимание + +Помните, что эти параметры передаются непосредственно *декоратору операций пути*, а не вашей *функции-обработчику операций пути*. + +/// ## Коды состояния @@ -13,52 +16,23 @@ Но если вы не помните, для чего нужен каждый числовой код, вы можете использовать сокращенные константы в параметре `status`: -=== "Python 3.10+" - - ```Python hl_lines="1 15" - {!> ../../../docs_src/path_operation_configuration/tutorial001_py310.py!} - ``` +{* ../../docs_src/path_operation_configuration/tutorial001_py310.py hl[1,15] *} -=== "Python 3.9+" - - ```Python hl_lines="3 17" - {!> ../../../docs_src/path_operation_configuration/tutorial001_py39.py!} - ``` - -=== "Python 3.8+" +Этот код состояния будет использован в ответе и будет добавлен в схему OpenAPI. - ```Python hl_lines="3 17" - {!> ../../../docs_src/path_operation_configuration/tutorial001.py!} - ``` +/// note | Технические детали -Этот код состояния будет использован в ответе и будет добавлен в схему OpenAPI. +Вы также можете использовать `from starlette import status`. -!!! note "Технические детали" - Вы также можете использовать `from starlette import status`. +**FastAPI** предоставляет тот же `starlette.status` под псевдонимом `fastapi.status` для удобства разработчика. Но его источник - это непосредственно Starlette. - **FastAPI** предоставляет тот же `starlette.status` под псевдонимом `fastapi.status` для удобства разработчика. Но его источник - это непосредственно Starlette. +/// ## Теги Вы можете добавлять теги к вашим *операциям пути*, добавив параметр `tags` с `list` заполненным `str`-значениями (обычно в нём только одна строка): -=== "Python 3.10+" - - ```Python hl_lines="15 20 25" - {!> ../../../docs_src/path_operation_configuration/tutorial002_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="17 22 27" - {!> ../../../docs_src/path_operation_configuration/tutorial002_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="17 22 27" - {!> ../../../docs_src/path_operation_configuration/tutorial002.py!} - ``` +{* ../../docs_src/path_operation_configuration/tutorial002_py310.py hl[15,20,25] *} Они будут добавлены в схему OpenAPI и будут использованы в автоматической документации интерфейса: @@ -72,31 +46,13 @@ **FastAPI** поддерживает это так же, как и в случае с обычными строками: -```Python hl_lines="1 8-10 13 18" -{!../../../docs_src/path_operation_configuration/tutorial002b.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial002b.py hl[1,8:10,13,18] *} ## Краткое и развёрнутое содержание Вы можете добавить параметры `summary` и `description`: -=== "Python 3.10+" - - ```Python hl_lines="18-19" - {!> ../../../docs_src/path_operation_configuration/tutorial003_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="20-21" - {!> ../../../docs_src/path_operation_configuration/tutorial003_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="20-21" - {!> ../../../docs_src/path_operation_configuration/tutorial003.py!} - ``` +{* ../../docs_src/path_operation_configuration/tutorial003_py310.py hl[18:19] *} ## Описание из строк документации @@ -104,23 +60,7 @@ Вы можете использовать Markdown в строке документации, и он будет интерпретирован и отображён корректно (с учетом отступа в строке документации). -=== "Python 3.10+" - - ```Python hl_lines="17-25" - {!> ../../../docs_src/path_operation_configuration/tutorial004_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="19-27" - {!> ../../../docs_src/path_operation_configuration/tutorial004_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="19-27" - {!> ../../../docs_src/path_operation_configuration/tutorial004.py!} - ``` +{* ../../docs_src/path_operation_configuration/tutorial004_py310.py hl[17:25] *} Он будет использован в интерактивной документации: @@ -130,31 +70,21 @@ Вы можете указать описание ответа с помощью параметра `response_description`: -=== "Python 3.10+" - - ```Python hl_lines="19" - {!> ../../../docs_src/path_operation_configuration/tutorial005_py310.py!} - ``` +{* ../../docs_src/path_operation_configuration/tutorial005_py310.py hl[19] *} -=== "Python 3.9+" +/// info | Дополнительная информация - ```Python hl_lines="21" - {!> ../../../docs_src/path_operation_configuration/tutorial005_py39.py!} - ``` +Помните, что `response_description` относится конкретно к ответу, а `description` относится к *операции пути* в целом. -=== "Python 3.8+" +/// - ```Python hl_lines="21" - {!> ../../../docs_src/path_operation_configuration/tutorial005.py!} - ``` +/// check | Технические детали -!!! info "Дополнительная информация" - Помните, что `response_description` относится конкретно к ответу, а `description` относится к *операции пути* в целом. +OpenAPI указывает, что каждой *операции пути* необходимо описание ответа. -!!! check "Технические детали" - OpenAPI указывает, что каждой *операции пути* необходимо описание ответа. +Если вдруг вы не укажете его, то **FastAPI** автоматически сгенерирует это описание с текстом "Successful response". - Если вдруг вы не укажете его, то **FastAPI** автоматически сгенерирует это описание с текстом "Successful response". +/// @@ -162,9 +92,7 @@ Если вам необходимо пометить *операцию пути* как устаревшую, при этом не удаляя её, передайте параметр `deprecated`: -```Python hl_lines="16" -{!../../../docs_src/path_operation_configuration/tutorial006.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial006.py hl[16] *} Он будет четко помечен как устаревший в интерактивной документации: diff --git a/docs/ru/docs/tutorial/path-params-numeric-validations.md b/docs/ru/docs/tutorial/path-params-numeric-validations.md index bd2c29d0a..dca267f78 100644 --- a/docs/ru/docs/tutorial/path-params-numeric-validations.md +++ b/docs/ru/docs/tutorial/path-params-numeric-validations.md @@ -6,48 +6,17 @@ Сначала импортируйте `Path` из `fastapi`, а также импортируйте `Annotated`: -=== "Python 3.10+" +{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *} - ```Python hl_lines="1 3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} - ``` +/// info | Информация -=== "Python 3.9+" +Поддержка `Annotated` была добавлена в FastAPI начиная с версии 0.95.0 (и с этой версии рекомендуется использовать этот подход). - ```Python hl_lines="1 3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} - ``` +Если вы используете более старую версию, вы столкнётесь с ошибками при попытке использовать `Annotated`. -=== "Python 3.8+" +Убедитесь, что вы [обновили версию FastAPI](../deployment/versions.md#fastapi_2){.internal-link target=_blank} как минимум до 0.95.1 перед тем, как использовать `Annotated`. - ```Python hl_lines="3-4" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} - ``` - -=== "Python 3.10+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python hl_lines="1" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` - -=== "Python 3.8+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python hl_lines="3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` - -!!! info "Информация" - Поддержка `Annotated` была добавлена в FastAPI начиная с версии 0.95.0 (и с этой версии рекомендуется использовать этот подход). - - Если вы используете более старую версию, вы столкнётесь с ошибками при попытке использовать `Annotated`. - - Убедитесь, что вы [обновили версию FastAPI](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} как минимум до 0.95.1 перед тем, как использовать `Annotated`. +/// ## Определите метаданные @@ -55,53 +24,25 @@ Например, чтобы указать значение метаданных `title` для path-параметра `item_id`, вы можете написать: -=== "Python 3.10+" - - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} - ``` - -=== "Python 3.8+" +{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *} - ```Python hl_lines="11" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} - ``` +/// note | Примечание -=== "Python 3.10+ без Annotated" +Path-параметр всегда является обязательным, поскольку он составляет часть пути. - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Поэтому следует объявить его с помощью `...`, чтобы обозначить, что этот параметр обязательный. - ```Python hl_lines="8" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` +Тем не менее, даже если вы объявите его как `None` или установите для него значение по умолчанию, это ни на что не повлияет и параметр останется обязательным. -=== "Python 3.8+ без Annotated" +/// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` - -!!! note "Примечание" - Path-параметр всегда является обязательным, поскольку он составляет часть пути. +## Задайте нужный вам порядок параметров - Поэтому следует объявить его с помощью `...`, чтобы обозначить, что этот параметр обязательный. +/// tip | Подсказка - Тем не менее, даже если вы объявите его как `None` или установите для него значение по умолчанию, это ни на что не повлияет и параметр останется обязательным. +Это не имеет большого значения, если вы используете `Annotated`. -## Задайте нужный вам порядок параметров - -!!! tip "Подсказка" - Это не имеет большого значения, если вы используете `Annotated`. +/// Допустим, вы хотите объявить query-параметр `q` как обязательный параметр типа `str`. @@ -117,33 +58,31 @@ Поэтому вы можете определить функцию так: -=== "Python 3.8 без Annotated" +//// tab | Python 3.8 без Annotated - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// tip | Подсказка - ```Python hl_lines="7" - {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} - ``` +Рекомендуется использовать версию с `Annotated` если возможно. -Но имейте в виду, что если вы используете `Annotated`, вы не столкнётесь с этой проблемой, так как вы не используете `Query()` или `Path()` в качестве значения по умолчанию для параметра функции. +/// -=== "Python 3.9+" +```Python hl_lines="7" +{!> ../../docs_src/path_params_numeric_validations/tutorial002.py!} +``` - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py!} - ``` +//// -=== "Python 3.8+" +Но имейте в виду, что если вы используете `Annotated`, вы не столкнётесь с этой проблемой, так как вы не используете `Query()` или `Path()` в качестве значения по умолчанию для параметра функции. - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial002_an.py!} - ``` +{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py hl[10] *} ## Задайте нужный вам порядок параметров, полезные приёмы -!!! tip "Подсказка" - Это не имеет большого значения, если вы используете `Annotated`. +/// tip | Подсказка + +Это не имеет большого значения, если вы используете `Annotated`. + +/// Здесь описан **небольшой приём**, который может оказаться удобным, хотя часто он вам не понадобится. @@ -160,25 +99,13 @@ Python не будет ничего делать с `*`, но он будет знать, что все следующие параметры являются именованными аргументами (парами ключ-значение), также известными как kwargs, даже если у них нет значений по умолчанию. -```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial003.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *} ### Лучше с `Annotated` Имейте в виду, что если вы используете `Annotated`, то, поскольку вы не используете значений по умолчанию для параметров функции, то у вас не возникнет подобной проблемы и вам не придётся использовать `*`. -=== "Python 3.9+" - - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial003_an.py!} - ``` +{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *} ## Валидация числовых данных: больше или равно @@ -186,26 +113,7 @@ Python не будет ничего делать с `*`, но он будет з В этом примере при указании `ge=1`, параметр `item_id` должен быть больше или равен `1` ("`g`reater than or `e`qual"). -=== "Python 3.9+" - - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004_an.py!} - ``` - -=== "Python 3.8+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python hl_lines="8" - {!> ../../../docs_src/path_params_numeric_validations/tutorial004.py!} - ``` +{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *} ## Валидация числовых данных: больше и меньше или равно @@ -214,26 +122,7 @@ Python не будет ничего делать с `*`, но он будет з * `gt`: больше (`g`reater `t`han) * `le`: меньше или равно (`l`ess than or `e`qual) -=== "Python 3.9+" - - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial005_an.py!} - ``` - -=== "Python 3.8+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python hl_lines="9" - {!> ../../../docs_src/path_params_numeric_validations/tutorial005.py!} - ``` +{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *} ## Валидация числовых данных: числа с плавающей точкой, больше и меньше @@ -245,26 +134,7 @@ Python не будет ничего делать с `*`, но он будет з То же самое справедливо и для lt. -=== "Python 3.9+" - - ```Python hl_lines="13" - {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="12" - {!> ../../../docs_src/path_params_numeric_validations/tutorial006_an.py!} - ``` - -=== "Python 3.8+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python hl_lines="11" - {!> ../../../docs_src/path_params_numeric_validations/tutorial006.py!} - ``` +{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *} ## Резюме @@ -277,16 +147,22 @@ Python не будет ничего делать с `*`, но он будет з * `lt`: меньше (`l`ess `t`han) * `le`: меньше или равно (`l`ess than or `e`qual) -!!! info "Информация" - `Query`, `Path` и другие классы, которые мы разберём позже, являются наследниками общего класса `Param`. +/// info | Информация + +`Query`, `Path` и другие классы, которые мы разберём позже, являются наследниками общего класса `Param`. + +Все они используют те же параметры для дополнительной валидации и метаданных, которые вы видели ранее. + +/// + +/// note | Технические детали - Все они используют те же параметры для дополнительной валидации и метаданных, которые вы видели ранее. +`Query`, `Path` и другие "классы", которые вы импортируете из `fastapi`, на самом деле являются функциями, которые при вызове возвращают экземпляры одноимённых классов. -!!! note "Технические детали" - `Query`, `Path` и другие "классы", которые вы импортируете из `fastapi`, на самом деле являются функциями, которые при вызове возвращают экземпляры одноимённых классов. +Объект `Query`, который вы импортируете, является функцией. И при вызове она возвращает экземпляр одноимённого класса `Query`. - Объект `Query`, который вы импортируете, является функцией. И при вызове она возвращает экземпляр одноимённого класса `Query`. +Использование функций (вместо использования классов напрямую) нужно для того, чтобы ваш редактор не подсвечивал ошибки, связанные с их типами. - Использование функций (вместо использования классов напрямую) нужно для того, чтобы ваш редактор не подсвечивал ошибки, связанные с их типами. +Таким образом вы можете использовать привычный вам редактор и инструменты разработки, не добавляя дополнительных конфигураций для игнорирования подобных ошибок. - Таким образом вы можете использовать привычный вам редактор и инструменты разработки, не добавляя дополнительных конфигураций для игнорирования подобных ошибок. +/// diff --git a/docs/ru/docs/tutorial/path-params.md b/docs/ru/docs/tutorial/path-params.md index 55b498ef0..5c2d82a65 100644 --- a/docs/ru/docs/tutorial/path-params.md +++ b/docs/ru/docs/tutorial/path-params.md @@ -2,9 +2,7 @@ Вы можете определить "параметры" или "переменные" пути, используя синтаксис форматированных строк Python: -```Python hl_lines="6-7" -{!../../../docs_src/path_params/tutorial001.py!} -``` +{* ../../docs_src/path_params/tutorial001.py hl[6:7] *} Значение параметра пути `item_id` будет передано в функцию в качестве аргумента `item_id`. @@ -18,14 +16,15 @@ Вы можете объявить тип параметра пути в функции, используя стандартные аннотации типов Python. -```Python hl_lines="7" -{!../../../docs_src/path_params/tutorial002.py!} -``` +{* ../../docs_src/path_params/tutorial002.py hl[7] *} Здесь, `item_id` объявлен типом `int`. -!!! check "Заметка" - Это обеспечит поддержку редактора внутри функции (проверка ошибок, автодополнение и т.п.). +/// check | Заметка + +Это обеспечит поддержку редактора внутри функции (проверка ошибок, автодополнение и т.п.). + +/// ## Преобразование данных @@ -35,10 +34,13 @@ {"item_id":3} ``` -!!! check "Заметка" - Обратите внимание на значение `3`, которое получила (и вернула) функция. Это целочисленный Python `int`, а не строка `"3"`. +/// check | Заметка - Используя определения типов, **FastAPI** выполняет автоматический "парсинг" запросов. +Обратите внимание на значение `3`, которое получила (и вернула) функция. Это целочисленный Python `int`, а не строка `"3"`. + +Используя определения типов, **FastAPI** выполняет автоматический "парсинг" запросов. + +/// ## Проверка данных @@ -63,12 +65,15 @@ Та же ошибка возникнет, если вместо `int` передать `float` , например: http://127.0.0.1:8000/items/4.2 -!!! check "Заметка" - **FastAPI** обеспечивает проверку типов, используя всё те же определения типов. +/// check | Заметка + +**FastAPI** обеспечивает проверку типов, используя всё те же определения типов. - Обратите внимание, что в тексте ошибки явно указано место не прошедшее проверку. +Обратите внимание, что в тексте ошибки явно указано место не прошедшее проверку. - Это очень полезно при разработке и отладке кода, который взаимодействует с API. +Это очень полезно при разработке и отладке кода, который взаимодействует с API. + +/// ## Документация @@ -76,10 +81,13 @@ -!!! check "Заметка" - Ещё раз, просто используя определения типов, **FastAPI** обеспечивает автоматическую интерактивную документацию (с интеграцией Swagger UI). +/// check | Заметка + +Ещё раз, просто используя определения типов, **FastAPI** обеспечивает автоматическую интерактивную документацию (с интеграцией Swagger UI). + +Обратите внимание, что параметр пути объявлен целочисленным. - Обратите внимание, что параметр пути объявлен целочисленным. +/// ## Преимущества стандартизации, альтернативная документация @@ -93,7 +101,7 @@ ## Pydantic -Вся проверка данных выполняется под капотом с помощью Pydantic. Поэтому вы можете быть уверены в качестве обработки данных. +Вся проверка данных выполняется под капотом с помощью Pydantic. Поэтому вы можете быть уверены в качестве обработки данных. Вы можете использовать в аннотациях как простые типы данных, вроде `str`, `float`, `bool`, так и более сложные типы. @@ -110,17 +118,13 @@ Поскольку *операции пути* выполняются в порядке их объявления, необходимо, чтобы путь для `/users/me` был объявлен раньше, чем путь для `/users/{user_id}`: -```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003.py!} -``` +{* ../../docs_src/path_params/tutorial003.py hl[6,11] *} Иначе путь для `/users/{user_id}` также будет соответствовать `/users/me`, "подразумевая", что он получает параметр `user_id` со значением `"me"`. Аналогично, вы не можете переопределить операцию с путем: -```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003b.py!} -``` +{* ../../docs_src/path_params/tutorial003b.py hl[6,11] *} Первый будет выполняться всегда, так как путь совпадает первым. @@ -136,23 +140,25 @@ Затем создайте атрибуты класса с фиксированными допустимыми значениями: -```Python hl_lines="1 6-9" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *} -!!! info "Дополнительная информация" - Перечисления (enum) доступны в Python начиная с версии 3.4. +/// info | Дополнительная информация -!!! tip "Подсказка" - Если интересно, то "AlexNet", "ResNet" и "LeNet" - это названия моделей машинного обучения. +Перечисления (enum) доступны в Python начиная с версии 3.4. + +/// + +/// tip | Подсказка + +Если интересно, то "AlexNet", "ResNet" и "LeNet" - это названия моделей машинного обучения. + +/// ### Определение *параметра пути* Определите *параметр пути*, используя в аннотации типа класс перечисления (`ModelName`), созданный ранее: -```Python hl_lines="16" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[16] *} ### Проверьте документацию @@ -168,20 +174,19 @@ Вы можете сравнить это значение с *элементом перечисления* класса `ModelName`: -```Python hl_lines="17" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[17] *} #### Получение *значения перечисления* Можно получить фактическое значение (в данном случае - `str`) с помощью `model_name.value` или в общем случае `your_enum_member.value`: -```Python hl_lines="20" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[20] *} -!!! tip "Подсказка" - Значение `"lenet"` также можно получить с помощью `ModelName.lenet.value`. +/// tip | Подсказка + +Значение `"lenet"` также можно получить с помощью `ModelName.lenet.value`. + +/// #### Возврат *элементов перечисления* @@ -189,9 +194,7 @@ Они будут преобразованы в соответствующие значения (в данном случае - строки) перед их возвратом клиенту: -```Python hl_lines="18 21 23" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *} Вы отправите клиенту такой JSON-ответ: ```JSON @@ -229,14 +232,15 @@ OpenAPI не поддерживает способов объявления *п Можете использовать так: -```Python hl_lines="6" -{!../../../docs_src/path_params/tutorial004.py!} -``` +{* ../../docs_src/path_params/tutorial004.py hl[6] *} + +/// tip | Подсказка + +Возможно, вам понадобится, чтобы параметр содержал `/home/johndoe/myfile.txt` с ведущим слэшем (`/`). -!!! tip "Подсказка" - Возможно, вам понадобится, чтобы параметр содержал `/home/johndoe/myfile.txt` с ведущим слэшем (`/`). +В этом случае URL будет таким: `/files//home/johndoe/myfile.txt`, с двойным слэшем (`//`) между `files` и `home`. - В этом случае URL будет таким: `/files//home/johndoe/myfile.txt`, с двойным слэшем (`//`) между `files` и `home`. +/// ## Резюме Используя **FastAPI** вместе со стандартными объявлениями типов Python (короткими и интуитивно понятными), вы получаете: diff --git a/docs/ru/docs/tutorial/query-param-models.md b/docs/ru/docs/tutorial/query-param-models.md new file mode 100644 index 000000000..4d76d09e8 --- /dev/null +++ b/docs/ru/docs/tutorial/query-param-models.md @@ -0,0 +1,68 @@ +# Модели Query-Параметров + +Если у вас есть группа связанных **query-параметров**, то вы можете объединить их в одну **Pydantic-модель**. + +Это позволит вам **переиспользовать модель** в **разных местах**, устанавливать валидаторы и метаданные, в том числе для сразу всех параметров, в одном месте. 😎 + +/// note | Заметка + +Этот функционал доступен с версии `0.115.0`. 🤓 + +/// + +## Pydantic-Модель для Query-Параметров + +Объявите нужные **query-параметры** в **Pydantic-модели**, а после аннотируйте параметр как `Query`: + +{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *} + +**FastAPI извлечёт** данные соответствующие **каждому полю модели** из **query-параметров** запроса и выдаст вам объявленную Pydantic-модель заполненную ими. + +## Проверьте Сгенерированную Документацию + +Вы можете посмотреть query-параметры в графическом интерфейсе сгенерированной документации по пути `/docs`: + +
+ +
+ +## Запретить Дополнительные Query-Параметры + +В некоторых случаях (не особо часто встречающихся) вам может понадобиться **ограничить** query-параметры, которые вы хотите получить. + +Вы можете сконфигурировать Pydantic-модель так, чтобы запретить (`forbid`) все дополнительные (`extra`) поля. + +{* ../../docs_src/query_param_models/tutorial002_an_py310.py hl[10] *} + +Если клиент попробует отправить **дополнительные** данные в **query-параметрах**, то в ответ он получит **ошибку**. + +Например, если клиент попытается отправить query-параметр `tool` с значением `plumbus`, в виде: + +```http +https://example.com/items/?limit=10&tool=plumbus +``` + +То в ответ он получит **ошибку**, сообщающую ему, что query-параметр `tool` не разрешен: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["query", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus" + } + ] +} +``` + +## Заключение + +Вы можете использовать **Pydantic-модели** для объявления **query-параметров** в **FastAPI**. 😎 + +/// tip | Совет + +Спойлер: вы также можете использовать Pydantic-модели для группировки кук (cookies) и заголовков (headers), но об этом вы прочитаете позже. 🤫 + +/// diff --git a/docs/ru/docs/tutorial/query-params-str-validations.md b/docs/ru/docs/tutorial/query-params-str-validations.md index cc826b871..13b7015db 100644 --- a/docs/ru/docs/tutorial/query-params-str-validations.md +++ b/docs/ru/docs/tutorial/query-params-str-validations.md @@ -4,24 +4,17 @@ Давайте рассмотрим следующий пример: -=== "Python 3.10+" +{* ../../docs_src/query_params_str_validations/tutorial001_py310.py hl[7] *} - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} - ``` - -=== "Python 3.8+" +Query-параметр `q` имеет тип `Union[str, None]` (или `str | None` в Python 3.10). Это означает, что входной параметр будет типа `str`, но может быть и `None`. Ещё параметр имеет значение по умолчанию `None`, из-за чего FastAPI определит параметр как необязательный. - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial001.py!} - ``` +/// note | Технические детали -Query-параметр `q` имеет тип `Union[str, None]` (или `str | None` в Python 3.10). Это означает, что входной параметр будет типа `str`, но может быть и `None`. Ещё параметр имеет значение по умолчанию `None`, из-за чего FastAPI определит параметр как необязательный. +FastAPI определит параметр `q` как необязательный, потому что его значение по умолчанию `= None`. -!!! note "Технические детали" - FastAPI определит параметр `q` как необязательный, потому что его значение по умолчанию `= None`. +`Union` в `Union[str, None]` позволит редактору кода оказать вам лучшую поддержку и найти ошибки. - `Union` в `Union[str, None]` позволит редактору кода оказать вам лучшую поддержку и найти ошибки. +/// ## Расширенная валидация @@ -34,23 +27,27 @@ Query-параметр `q` имеет тип `Union[str, None]` (или `str | N * `Query` из пакета `fastapi`: * `Annotated` из пакета `typing` (или из `typing_extensions` для Python ниже 3.9) -=== "Python 3.10+" +//// tab | Python 3.10+ + +В Python 3.9 или выше, `Annotated` является частью стандартной библиотеки, таким образом вы можете импортировать его из `typing`. + +```Python hl_lines="1 3" +{!> ../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} +``` - В Python 3.9 или выше, `Annotated` является частью стандартной библиотеки, таким образом вы можете импортировать его из `typing`. +//// - ```Python hl_lines="1 3" - {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +В версиях Python ниже Python 3.9 `Annotation` импортируется из `typing_extensions`. - В версиях Python ниже Python 3.9 `Annotation` импортируется из `typing_extensions`. +Эта библиотека будет установлена вместе с FastAPI. - Эта библиотека будет установлена вместе с FastAPI. +```Python hl_lines="3-4" +{!> ../../docs_src/query_params_str_validations/tutorial002_an.py!} +``` - ```Python hl_lines="3-4" - {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} - ``` +//// ## `Annotated` как тип для query-параметра `q` @@ -60,31 +57,39 @@ Query-параметр `q` имеет тип `Union[str, None]` (или `str | N У нас была аннотация следующего типа: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python +q: str | None = None +``` + +//// - ```Python - q: str | None = None - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python +q: Union[str, None] = None +``` - ```Python - q: Union[str, None] = None - ``` +//// Вот что мы получим, если обернём это в `Annotated`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python +q: Annotated[str | None] = None +``` + +//// - ```Python - q: Annotated[str | None] = None - ``` +//// tab | Python 3.8+ -=== "Python 3.8+" +```Python +q: Annotated[Union[str, None]] = None +``` - ```Python - q: Annotated[Union[str, None]] = None - ``` +//// Обе эти версии означают одно и тоже. `q` - это параметр, который может быть `str` или `None`, и по умолчанию он будет принимать `None`. @@ -94,17 +99,7 @@ Query-параметр `q` имеет тип `Union[str, None]` (или `str | N Теперь, когда у нас есть `Annotated`, где мы можем добавить больше метаданных, добавим `Query` со значением параметра `max_length` равным 50: -=== "Python 3.10+" - - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial002_an.py!} - ``` +{* ../../docs_src/query_params_str_validations/tutorial002_an_py310.py hl[9] *} Обратите внимание, что значение по умолчанию всё ещё `None`, так что параметр остаётся необязательным. @@ -120,22 +115,15 @@ Query-параметр `q` имеет тип `Union[str, None]` (или `str | N В предыдущих версиях FastAPI (ниже 0.95.0) необходимо было использовать `Query` как значение по умолчанию для query-параметра. Так было вместо размещения его в `Annotated`, так что велика вероятность, что вам встретится такой код. Сейчас объясню. -!!! tip "Подсказка" - При написании нового кода и везде где это возможно, используйте `Annotated`, как было описано ранее. У этого способа есть несколько преимуществ (о них дальше) и никаких недостатков. 🍰 +/// tip | Подсказка -Вот как вы могли бы использовать `Query()` в качестве значения по умолчанию параметра вашей функции, установив для параметра `max_length` значение 50: - -=== "Python 3.10+" +При написании нового кода и везде где это возможно, используйте `Annotated`, как было описано ранее. У этого способа есть несколько преимуществ (о них дальше) и никаких недостатков. 🍰 - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial002_py310.py!} - ``` +/// -=== "Python 3.8+" +Вот как вы могли бы использовать `Query()` в качестве значения по умолчанию параметра вашей функции, установив для параметра `max_length` значение 50: - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial002.py!} - ``` +{* ../../docs_src/query_params_str_validations/tutorial002_py310.py hl[7] *} В таком случае (без использования `Annotated`), мы заменили значение по умолчанию с `None` на `Query()` в функции. Теперь нам нужно установить значение по умолчанию для query-параметра `Query(default=None)`, что необходимо для тех же целей, как когда ранее просто указывалось значение по умолчанию (по крайней мере, для FastAPI). @@ -165,22 +153,25 @@ q: str | None = None Но он явно объявляет его как query-параметр. -!!! info "Дополнительная информация" - Запомните, важной частью объявления параметра как необязательного является: +/// info | Дополнительная информация + +Запомните, важной частью объявления параметра как необязательного является: + +```Python += None +``` - ```Python - = None - ``` +или: - или: +```Python += Query(default=None) +``` - ```Python - = Query(default=None) - ``` +так как `None` указан в качестве значения по умолчанию, параметр будет **необязательным**. - так как `None` указан в качестве значения по умолчанию, параметр будет **необязательным**. +`Union[str, None]` позволит редактору кода оказать вам лучшую поддержку. Но это не то, на что обращает внимание FastAPI для определения необязательности параметра. - `Union[str, None]` позволит редактору кода оказать вам лучшую поддержку. Но это не то, на что обращает внимание FastAPI для определения необязательности параметра. +/// Теперь, мы можем указать больше параметров для `Query`. В данном случае, параметр `max_length` применяется к строкам: @@ -232,81 +223,13 @@ q: str = Query(default="rick") Вы также можете добавить параметр `min_length`: -=== "Python 3.10+" - - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial003_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial003_an.py!} - ``` - -=== "Python 3.10+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial003_py310.py!} - ``` - -=== "Python 3.8+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial003.py!} - ``` +{* ../../docs_src/query_params_str_validations/tutorial003_an_py310.py hl[10] *} ## Регулярные выражения Вы можете определить регулярное выражение, которому должен соответствовать параметр: -=== "Python 3.10+" - - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial004_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="12" - {!> ../../../docs_src/query_params_str_validations/tutorial004_an.py!} - ``` - -=== "Python 3.10+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial004_py310.py!} - ``` - -=== "Python 3.8+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial004.py!} - ``` +{* ../../docs_src/query_params_str_validations/tutorial004_an_py310.py hl[11] *} Данное регулярное выражение проверяет, что полученное значение параметра: @@ -324,29 +247,13 @@ q: str = Query(default="rick") Например, вы хотите для параметра запроса `q` указать, что он должен состоять минимум из 3 символов (`min_length=3`) и иметь значение по умолчанию `"fixedquery"`: -=== "Python 3.9+" - - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial005_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial005_an.py!} - ``` - -=== "Python 3.8+ без Annotated" +{* ../../docs_src/query_params_str_validations/tutorial005_an_py39.py hl[9] *} - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +/// note | Технические детали - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial005.py!} - ``` +Наличие значения по умолчанию делает параметр необязательным. -!!! note "Технические детали" - Наличие значения по умолчанию делает параметр необязательным. +/// ## Обязательный параметр @@ -364,77 +271,25 @@ q: Union[str, None] = None Но у нас query-параметр определён как `Query`. Например: -=== "Annotated" - - ```Python - q: Annotated[Union[str, None], Query(min_length=3)] = None - ``` - -=== "без Annotated" - - ```Python - q: Union[str, None] = Query(default=None, min_length=3) - ``` - -В таком случае, чтобы сделать query-параметр `Query` обязательным, вы можете просто не указывать значение по умолчанию: - -=== "Python 3.9+" - - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial006_an.py!} - ``` - -=== "Python 3.8+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// tab | Annotated - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial006.py!} - ``` - - !!! tip "Подсказка" - Обратите внимание, что даже когда `Query()` используется как значение по умолчанию для параметра функции, мы не передаём `default=None` в `Query()`. - - Лучше будет использовать версию с `Annotated`. 😉 - -### Обязательный параметр с Ellipsis (`...`) - -Альтернативный способ указать обязательность параметра запроса - это указать параметр `default` через многоточие `...`: - -=== "Python 3.9+" - - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006b_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial006b_an.py!} - ``` +```Python +q: Annotated[Union[str, None], Query(min_length=3)] = None +``` -=== "Python 3.8+ без Annotated" +//// - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +//// tab | без Annotated - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial006b.py!} - ``` +```Python +q: Union[str, None] = Query(default=None, min_length=3) +``` -!!! info "Дополнительная информация" - Если вы ранее не сталкивались с `...`: это специальное значение, часть языка Python и называется "Ellipsis". +//// - Используется в Pydantic и FastAPI для определения, что значение требуется обязательно. +В таком случае, чтобы сделать query-параметр `Query` обязательным, вы можете просто не указывать значение по умолчанию: -Таким образом, **FastAPI** определяет, что параметр является обязательным. +{* ../../docs_src/query_params_str_validations/tutorial006_an_py39.py hl[9] *} ### Обязательный параметр с `None` @@ -442,72 +297,13 @@ q: Union[str, None] = None Чтобы этого добиться, вам нужно определить `None` как валидный тип для параметра запроса, но также указать `default=...`: -=== "Python 3.10+" - - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_an.py!} - ``` - -=== "Python 3.10+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial006c_py310.py!} - ``` - -=== "Python 3.8+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +{* ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py hl[9] *} - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial006c.py!} - ``` +/// tip | Подсказка -!!! tip "Подсказка" - Pydantic, мощь которого используется в FastAPI для валидации и сериализации, имеет специальное поведение для `Optional` или `Union[Something, None]` без значения по умолчанию. Вы можете узнать об этом больше в документации Pydantic, раздел Обязательные Опциональные поля. +Pydantic, мощь которого используется в FastAPI для валидации и сериализации, имеет специальное поведение для `Optional` или `Union[Something, None]` без значения по умолчанию. Вы можете узнать об этом больше в документации Pydantic, раздел Обязательные Опциональные поля. -### Использование Pydantic's `Required` вместо Ellipsis (`...`) - -Если вас смущает `...`, вы можете использовать `Required` из Pydantic: - -=== "Python 3.9+" - - ```Python hl_lines="4 10" - {!> ../../../docs_src/query_params_str_validations/tutorial006d_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="2 9" - {!> ../../../docs_src/query_params_str_validations/tutorial006d_an.py!} - ``` - -=== "Python 3.8+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python hl_lines="2 8" - {!> ../../../docs_src/query_params_str_validations/tutorial006d.py!} - ``` - -!!! tip "Подсказка" - Запомните, когда вам необходимо объявить query-параметр обязательным, вы можете просто не указывать параметр `default`. Таким образом, вам редко придётся использовать `...` или `Required`. +/// ## Множество значений для query-параметра @@ -515,50 +311,7 @@ q: Union[str, None] = None Например, query-параметр `q` может быть указан в URL несколько раз. И если вы ожидаете такой формат запроса, то можете указать это следующим образом: -=== "Python 3.10+" - - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial011_an.py!} - ``` - -=== "Python 3.10+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial011_py310.py!} - ``` - -=== "Python 3.9+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011_py39.py!} - ``` - -=== "Python 3.8+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial011.py!} - ``` +{* ../../docs_src/query_params_str_validations/tutorial011_an_py310.py hl[9] *} Затем, получив такой URL: @@ -579,8 +332,11 @@ http://localhost:8000/items/?q=foo&q=bar } ``` -!!! tip "Подсказка" - Чтобы объявить query-параметр типом `list`, как в примере выше, вам нужно явно использовать `Query`, иначе он будет интерпретирован как тело запроса. +/// tip | Подсказка + +Чтобы объявить query-параметр типом `list`, как в примере выше, вам нужно явно использовать `Query`, иначе он будет интерпретирован как тело запроса. + +/// Интерактивная документация API будет обновлена соответствующим образом, где будет разрешено множество значений: @@ -590,35 +346,7 @@ http://localhost:8000/items/?q=foo&q=bar Вы также можете указать тип `list` со списком значений по умолчанию на случай, если вам их не предоставят: -=== "Python 3.9+" - - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial012_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial012_an.py!} - ``` - -=== "Python 3.9+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial012_py39.py!} - ``` - -=== "Python 3.8+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial012.py!} - ``` +{* ../../docs_src/query_params_str_validations/tutorial012_an_py39.py hl[9] *} Если вы перейдёте по ссылке: @@ -641,31 +369,15 @@ http://localhost:8000/items/ Вы также можете использовать `list` напрямую вместо `List[str]` (или `list[str]` в Python 3.9+): -=== "Python 3.9+" - - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial013_an_py39.py!} - ``` - -=== "Python 3.8+" +{* ../../docs_src/query_params_str_validations/tutorial013_an_py39.py hl[9] *} - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial013_an.py!} - ``` +/// note | Технические детали -=== "Python 3.8+ без Annotated" +Запомните, что в таком случае, FastAPI не будет проверять содержимое списка. - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Например, для List[int] список будет провалидирован (и задокументирован) на содержание только целочисленных элементов. Но для простого `list` такой проверки не будет. - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial013.py!} - ``` - -!!! note "Технические детали" - Запомните, что в таком случае, FastAPI не будет проверять содержимое списка. - - Например, для List[int] список будет провалидирован (и задокументирован) на содержание только целочисленных элементов. Но для простого `list` такой проверки не будет. +/// ## Больше метаданных @@ -673,86 +385,21 @@ http://localhost:8000/items/ Указанная информация будет включена в генерируемую OpenAPI документацию и использована в пользовательском интерфейсе и внешних инструментах. -!!! note "Технические детали" - Имейте в виду, что разные инструменты могут иметь разные уровни поддержки OpenAPI. - - Некоторые из них могут не отображать (на данный момент) всю заявленную дополнительную информацию, хотя в большинстве случаев отсутствующая функция уже запланирована к разработке. - -Вы можете указать название query-параметра, используя параметр `title`: - -=== "Python 3.10+" - - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial007_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial007_an.py!} - ``` +/// note | Технические детали -=== "Python 3.10+ без Annotated" +Имейте в виду, что разные инструменты могут иметь разные уровни поддержки OpenAPI. - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Некоторые из них могут не отображать (на данный момент) всю заявленную дополнительную информацию, хотя в большинстве случаев отсутствующая функция уже запланирована к разработке. - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial007_py310.py!} - ``` +/// -=== "Python 3.8+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. +Вы можете указать название query-параметра, используя параметр `title`: - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial007.py!} - ``` +{* ../../docs_src/query_params_str_validations/tutorial007_an_py310.py hl[10] *} Добавить описание, используя параметр `description`: -=== "Python 3.10+" - - ```Python hl_lines="14" - {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="14" - {!> ../../../docs_src/query_params_str_validations/tutorial008_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="15" - {!> ../../../docs_src/query_params_str_validations/tutorial008_an.py!} - ``` - -=== "Python 3.10+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial008_py310.py!} - ``` - -=== "Python 3.8+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python hl_lines="13" - {!> ../../../docs_src/query_params_str_validations/tutorial008.py!} - ``` +{* ../../docs_src/query_params_str_validations/tutorial008_an_py310.py hl[14] *} ## Псевдонимы параметров @@ -772,41 +419,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems Тогда вы можете объявить `псевдоним`, и этот псевдоним будет использоваться для поиска значения параметра запроса: -=== "Python 3.10+" - - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial009_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial009_an.py!} - ``` - -=== "Python 3.10+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial009_py310.py!} - ``` - -=== "Python 3.8+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial009.py!} - ``` +{* ../../docs_src/query_params_str_validations/tutorial009_an_py310.py hl[9] *} ## Устаревшие параметры @@ -816,41 +429,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems Тогда для `Query` укажите параметр `deprecated=True`: -=== "Python 3.10+" - - ```Python hl_lines="19" - {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="19" - {!> ../../../docs_src/query_params_str_validations/tutorial010_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="20" - {!> ../../../docs_src/query_params_str_validations/tutorial010_an.py!} - ``` - -=== "Python 3.10+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python hl_lines="16" - {!> ../../../docs_src/query_params_str_validations/tutorial010_py310.py!} - ``` - -=== "Python 3.8+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python hl_lines="18" - {!> ../../../docs_src/query_params_str_validations/tutorial010.py!} - ``` +{* ../../docs_src/query_params_str_validations/tutorial010_an_py310.py hl[19] *} В документации это будет отображено следующим образом: @@ -860,41 +439,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems Чтобы исключить query-параметр из генерируемой OpenAPI схемы (а также из системы автоматической генерации документации), укажите в `Query` параметр `include_in_schema=False`: -=== "Python 3.10+" - - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial014_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="11" - {!> ../../../docs_src/query_params_str_validations/tutorial014_an.py!} - ``` - -=== "Python 3.10+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python hl_lines="8" - {!> ../../../docs_src/query_params_str_validations/tutorial014_py310.py!} - ``` - -=== "Python 3.8+ без Annotated" - - !!! tip "Подсказка" - Рекомендуется использовать версию с `Annotated` если возможно. - - ```Python hl_lines="10" - {!> ../../../docs_src/query_params_str_validations/tutorial014.py!} - ``` +{* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *} ## Резюме diff --git a/docs/ru/docs/tutorial/query-params.md b/docs/ru/docs/tutorial/query-params.md index 6e885cb65..547d9831d 100644 --- a/docs/ru/docs/tutorial/query-params.md +++ b/docs/ru/docs/tutorial/query-params.md @@ -2,9 +2,7 @@ Когда вы объявляете параметры функции, которые не являются параметрами пути, они автоматически интерпретируются как "query"-параметры. -```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial001.py!} -``` +{* ../../docs_src/query_params/tutorial001.py hl[9] *} Query-параметры представляют из себя набор пар ключ-значение, которые идут после знака `?` в URL-адресе, разделенные символами `&`. @@ -63,38 +61,21 @@ http://127.0.0.1:8000/items/?skip=20 Аналогично, вы можете объявлять необязательные query-параметры, установив их значение по умолчанию, равное `None`: -=== "Python 3.10+" - - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial002_py310.py!} - ``` +{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *} -=== "Python 3.8+" +В этом случае, параметр `q` будет не обязательным и будет иметь значение `None` по умолчанию. - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial002.py!} - ``` +/// check | Важно -В этом случае, параметр `q` будет не обязательным и будет иметь значение `None` по умолчанию. +Также обратите внимание, что **FastAPI** достаточно умён чтобы заметить, что параметр `item_id` является path-параметром, а `q` нет, поэтому, это параметр запроса. -!!! Важно - Также обратите внимание, что **FastAPI** достаточно умён чтобы заметить, что параметр `item_id` является path-параметром, а `q` нет, поэтому, это параметр запроса. +/// ## Преобразование типа параметра запроса Вы также можете объявлять параметры с типом `bool`, которые будут преобразованы соответственно: -=== "Python 3.10+" - - ```Python hl_lines="7" - {!> ../../../docs_src/query_params/tutorial003_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="9" - {!> ../../../docs_src/query_params/tutorial003.py!} - ``` +{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *} В этом случае, если вы сделаете запрос: @@ -137,17 +118,7 @@ http://127.0.0.1:8000/items/foo?short=yes Они будут обнаружены по именам: -=== "Python 3.10+" - - ```Python hl_lines="6 8" - {!> ../../../docs_src/query_params/tutorial004_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="8 10" - {!> ../../../docs_src/query_params/tutorial004.py!} - ``` +{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *} ## Обязательные query-параметры @@ -157,9 +128,7 @@ http://127.0.0.1:8000/items/foo?short=yes Но если вы хотите сделать query-параметр обязательным, вы можете просто не указывать значение по умолчанию: -```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} -``` +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} Здесь параметр запроса `needy` является обязательным параметром с типом данных `str`. @@ -203,17 +172,7 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy Конечно, вы можете определить некоторые параметры как обязательные, некоторые - со значением по умполчанию, а некоторые - полностью необязательные: -=== "Python 3.10+" - - ```Python hl_lines="8" - {!> ../../../docs_src/query_params/tutorial006_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="10" - {!> ../../../docs_src/query_params/tutorial006.py!} - ``` +{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *} В этом примере, у нас есть 3 параметра запроса: @@ -221,5 +180,8 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy * `skip`, типа `int` и со значением по умолчанию `0`. * `limit`, необязательный `int`. -!!! подсказка - Вы можете использовать класс `Enum` также, как ранее применяли его с [Path-параметрами](path-params.md#predefined-values){.internal-link target=_blank}. +/// tip | Подсказка + +Вы можете использовать класс `Enum` также, как ранее применяли его с [Path-параметрами](path-params.md#_7){.internal-link target=_blank}. + +/// diff --git a/docs/ru/docs/tutorial/request-files.md b/docs/ru/docs/tutorial/request-files.md index 00f8c8377..2cfa4e1dc 100644 --- a/docs/ru/docs/tutorial/request-files.md +++ b/docs/ru/docs/tutorial/request-files.md @@ -2,70 +2,41 @@ Используя класс `File`, мы можем позволить клиентам загружать файлы. -!!! info "Дополнительная информация" - Чтобы получать загруженные файлы, сначала установите `python-multipart`. +/// info | Дополнительная информация - Например: `pip install python-multipart`. +Чтобы получать загруженные файлы, сначала установите `python-multipart`. - Это связано с тем, что загружаемые файлы передаются как данные формы. +Например: `pip install python-multipart`. -## Импорт `File` - -Импортируйте `File` и `UploadFile` из модуля `fastapi`: - -=== "Python 3.9+" +Это связано с тем, что загружаемые файлы передаются как данные формы. - ```Python hl_lines="3" - {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} - ``` +/// -=== "Python 3.6+" - - ```Python hl_lines="1" - {!> ../../../docs_src/request_files/tutorial001_an.py!} - ``` - -=== "Python 3.6+ без Annotated" +## Импорт `File` - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +Импортируйте `File` и `UploadFile` из модуля `fastapi`: - ```Python hl_lines="1" - {!> ../../../docs_src/request_files/tutorial001.py!} - ``` +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[3] *} ## Определите параметры `File` Создайте параметры `File` так же, как вы это делаете для `Body` или `Form`: -=== "Python 3.9+" - - ```Python hl_lines="9" - {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} - ``` +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[9] *} -=== "Python 3.6+" +/// info | Дополнительная информация - ```Python hl_lines="8" - {!> ../../../docs_src/request_files/tutorial001_an.py!} - ``` +`File` - это класс, который наследуется непосредственно от `Form`. -=== "Python 3.6+ без Annotated" +Но помните, что когда вы импортируете `Query`, `Path`, `File` и другие из `fastapi`, на самом деле это функции, которые возвращают специальные классы. - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +/// - ```Python hl_lines="7" - {!> ../../../docs_src/request_files/tutorial001.py!} - ``` +/// tip | Подсказка -!!! info "Дополнительная информация" - `File` - это класс, который наследуется непосредственно от `Form`. +Для объявления тела файла необходимо использовать `File`, поскольку в противном случае параметры будут интерпретироваться как параметры запроса или параметры тела (JSON). - Но помните, что когда вы импортируете `Query`, `Path`, `File` и другие из `fastapi`, на самом деле это функции, которые возвращают специальные классы. - -!!! tip "Подсказка" - Для объявления тела файла необходимо использовать `File`, поскольку в противном случае параметры будут интерпретироваться как параметры запроса или параметры тела (JSON). +/// Файлы будут загружены как данные формы. @@ -79,26 +50,7 @@ Определите параметр файла с типом `UploadFile`: -=== "Python 3.9+" - - ```Python hl_lines="14" - {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} - ``` - -=== "Python 3.6+" - - ```Python hl_lines="13" - {!> ../../../docs_src/request_files/tutorial001_an.py!} - ``` - -=== "Python 3.6+ без Annotated" - - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. - - ```Python hl_lines="12" - {!> ../../../docs_src/request_files/tutorial001.py!} - ``` +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[14] *} Использование `UploadFile` имеет ряд преимуществ перед `bytes`: @@ -141,94 +93,53 @@ contents = await myfile.read() contents = myfile.file.read() ``` -!!! note "Технические детали `async`" - При использовании методов `async` **FastAPI** запускает файловые методы в пуле потоков и ожидает их. +/// note | Технические детали `async` -!!! note "Технические детали Starlette" - **FastAPI** наследует `UploadFile` непосредственно из **Starlette**, но добавляет некоторые детали для совместимости с **Pydantic** и другими частями FastAPI. - -## Про данные формы ("Form Data") +При использовании методов `async` **FastAPI** запускает файловые методы в пуле потоков и ожидает их. -Способ, которым HTML-формы (`
`) отправляют данные на сервер, обычно использует "специальную" кодировку для этих данных, отличную от JSON. - -**FastAPI** позаботится о том, чтобы считать эти данные из нужного места, а не из JSON. +/// -!!! note "Технические детали" - Данные из форм обычно кодируются с использованием "media type" `application/x-www-form-urlencoded` когда он не включает файлы. +/// note | Технические детали Starlette - Но когда форма включает файлы, она кодируется как multipart/form-data. Если вы используете `File`, **FastAPI** будет знать, что ему нужно получить файлы из нужной части тела. +**FastAPI** наследует `UploadFile` непосредственно из **Starlette**, но добавляет некоторые детали для совместимости с **Pydantic** и другими частями FastAPI. - Если вы хотите узнать больше об этих кодировках и полях форм, перейдите по ссылке MDN web docs for POST. +/// -!!! warning "Внимание" - В операции *функции операции пути* можно объявить несколько параметров `File` и `Form`, но нельзя также объявлять поля `Body`, которые предполагается получить в виде JSON, поскольку тело запроса будет закодировано с помощью `multipart/form-data`, а не `application/json`. - - Это не является ограничением **FastAPI**, это часть протокола HTTP. +## Про данные формы ("Form Data") -## Необязательная загрузка файлов +Способ, которым HTML-формы (`
`) отправляют данные на сервер, обычно использует "специальную" кодировку для этих данных, отличную от JSON. -Вы можете сделать загрузку файла необязательной, используя стандартные аннотации типов и установив значение по умолчанию `None`: +**FastAPI** позаботится о том, чтобы считать эти данные из нужного места, а не из JSON. -=== "Python 3.10+" +/// note | Технические детали - ```Python hl_lines="9 17" - {!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!} - ``` +Данные из форм обычно кодируются с использованием "media type" `application/x-www-form-urlencoded` когда он не включает файлы. -=== "Python 3.9+" +Но когда форма включает файлы, она кодируется как multipart/form-data. Если вы используете `File`, **FastAPI** будет знать, что ему нужно получить файлы из нужной части тела. - ```Python hl_lines="9 17" - {!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!} - ``` +Если вы хотите узнать больше об этих кодировках и полях форм, перейдите по ссылке MDN web docs for POST. -=== "Python 3.6+" +/// - ```Python hl_lines="10 18" - {!> ../../../docs_src/request_files/tutorial001_02_an.py!} - ``` +/// warning | Внимание -=== "Python 3.10+ без Annotated" +В операции *функции операции пути* можно объявить несколько параметров `File` и `Form`, но нельзя также объявлять поля `Body`, которые предполагается получить в виде JSON, поскольку тело запроса будет закодировано с помощью `multipart/form-data`, а не `application/json`. - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +Это не является ограничением **FastAPI**, это часть протокола HTTP. - ```Python hl_lines="7 15" - {!> ../../../docs_src/request_files/tutorial001_02_py310.py!} - ``` +/// -=== "Python 3.6+ без Annotated" +## Необязательная загрузка файлов - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +Вы можете сделать загрузку файла необязательной, используя стандартные аннотации типов и установив значение по умолчанию `None`: - ```Python hl_lines="9 17" - {!> ../../../docs_src/request_files/tutorial001_02.py!} - ``` +{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *} ## `UploadFile` с дополнительными метаданными Вы также можете использовать `File()` вместе с `UploadFile`, например, для установки дополнительных метаданных: -=== "Python 3.9+" - - ```Python hl_lines="9 15" - {!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!} - ``` - -=== "Python 3.6+" - - ```Python hl_lines="8 14" - {!> ../../../docs_src/request_files/tutorial001_03_an.py!} - ``` - -=== "Python 3.6+ без Annotated" - - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. - - ```Python hl_lines="7 13" - {!> ../../../docs_src/request_files/tutorial001_03.py!} - ``` +{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *} ## Загрузка нескольких файлов @@ -238,76 +149,23 @@ contents = myfile.file.read() Для этого необходимо объявить список `bytes` или `UploadFile`: -=== "Python 3.9+" - - ```Python hl_lines="10 15" - {!> ../../../docs_src/request_files/tutorial002_an_py39.py!} - ``` - -=== "Python 3.6+" - - ```Python hl_lines="11 16" - {!> ../../../docs_src/request_files/tutorial002_an.py!} - ``` - -=== "Python 3.9+ без Annotated" - - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *} - ```Python hl_lines="8 13" - {!> ../../../docs_src/request_files/tutorial002_py39.py!} - ``` - -=== "Python 3.6+ без Annotated" - - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +Вы получите, как и было объявлено, список `list` из `bytes` или `UploadFile`. - ```Python hl_lines="10 15" - {!> ../../../docs_src/request_files/tutorial002.py!} - ``` +/// note | Technical Details -Вы получите, как и было объявлено, список `list` из `bytes` или `UploadFile`. +Можно также использовать `from starlette.responses import HTMLResponse`. -!!! note "Technical Details" - Можно также использовать `from starlette.responses import HTMLResponse`. +**FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. - **FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. +/// ### Загрузка нескольких файлов с дополнительными метаданными Так же, как и раньше, вы можете использовать `File()` для задания дополнительных параметров, даже для `UploadFile`: -=== "Python 3.9+" - - ```Python hl_lines="11 18-20" - {!> ../../../docs_src/request_files/tutorial003_an_py39.py!} - ``` - -=== "Python 3.6+" - - ```Python hl_lines="12 19-21" - {!> ../../../docs_src/request_files/tutorial003_an.py!} - ``` - -=== "Python 3.9+ без Annotated" - - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. - - ```Python hl_lines="9 16" - {!> ../../../docs_src/request_files/tutorial003_py39.py!} - ``` - -=== "Python 3.6+ без Annotated" - - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. - - ```Python hl_lines="11 18" - {!> ../../../docs_src/request_files/tutorial003.py!} - ``` +{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *} ## Резюме diff --git a/docs/ru/docs/tutorial/request-forms-and-files.md b/docs/ru/docs/tutorial/request-forms-and-files.md index 3f587c38a..116c0cdb1 100644 --- a/docs/ru/docs/tutorial/request-forms-and-files.md +++ b/docs/ru/docs/tutorial/request-forms-and-files.md @@ -2,67 +2,35 @@ Вы можете определять файлы и поля формы одновременно, используя `File` и `Form`. -!!! info "Дополнительная информация" - Чтобы получать загруженные файлы и/или данные форм, сначала установите `python-multipart`. +/// info | Дополнительная информация - Например: `pip install python-multipart`. +Чтобы получать загруженные файлы и/или данные форм, сначала установите `python-multipart`. -## Импортируйте `File` и `Form` - -=== "Python 3.9+" - - ```Python hl_lines="3" - {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} - ``` - -=== "Python 3.6+" +Например: `pip install python-multipart`. - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} - ``` +/// -=== "Python 3.6+ без Annotated" - - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. +## Импортируйте `File` и `Form` - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms_and_files/tutorial001.py!} - ``` +{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[3] *} ## Определите параметры `File` и `Form` Создайте параметры файла и формы таким же образом, как для `Body` или `Query`: -=== "Python 3.9+" - - ```Python hl_lines="10-12" - {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} - ``` - -=== "Python 3.6+" - - ```Python hl_lines="9-11" - {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} - ``` - -=== "Python 3.6+ без Annotated" - - !!! tip "Подсказка" - Предпочтительнее использовать версию с аннотацией, если это возможно. - - ```Python hl_lines="8" - {!> ../../../docs_src/request_forms_and_files/tutorial001.py!} - ``` +{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[10:12] *} Файлы и поля формы будут загружены в виде данных формы, и вы получите файлы и поля формы. Вы можете объявить некоторые файлы как `bytes`, а некоторые - как `UploadFile`. -!!! warning "Внимание" - Вы можете объявить несколько параметров `File` и `Form` в операции *path*, но вы не можете также объявить поля `Body`, которые вы ожидаете получить в виде JSON, так как запрос будет иметь тело, закодированное с помощью `multipart/form-data` вместо `application/json`. +/// warning | Внимание + +Вы можете объявить несколько параметров `File` и `Form` в операции *path*, но вы не можете также объявить поля `Body`, которые вы ожидаете получить в виде JSON, так как запрос будет иметь тело, закодированное с помощью `multipart/form-data` вместо `application/json`. + +Это не ограничение **Fast API**, это часть протокола HTTP. - Это не ограничение **Fast API**, это часть протокола HTTP. +/// ## Резюме diff --git a/docs/ru/docs/tutorial/request-forms.md b/docs/ru/docs/tutorial/request-forms.md index 0fc9e4eda..b33ea044b 100644 --- a/docs/ru/docs/tutorial/request-forms.md +++ b/docs/ru/docs/tutorial/request-forms.md @@ -2,72 +2,43 @@ Когда вам нужно получить поля формы вместо JSON, вы можете использовать `Form`. -!!! info "Дополнительная информация" - Чтобы использовать формы, сначала установите `python-multipart`. +/// info | Дополнительная информация - Например, выполните команду `pip install python-multipart`. +Чтобы использовать формы, сначала установите `python-multipart`. -## Импорт `Form` - -Импортируйте `Form` из `fastapi`: - -=== "Python 3.9+" - - ```Python hl_lines="3" - {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} - ``` +Например, выполните команду `pip install python-multipart`. -=== "Python 3.8+" +/// - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms/tutorial001_an.py!} - ``` - -=== "Python 3.8+ без Annotated" +## Импорт `Form` - !!! tip "Подсказка" - Рекомендуется использовать 'Annotated' версию, если это возможно. +Импортируйте `Form` из `fastapi`: - ```Python hl_lines="1" - {!> ../../../docs_src/request_forms/tutorial001.py!} - ``` +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[3] *} ## Определение параметров `Form` Создайте параметры формы так же, как это делается для `Body` или `Query`: -=== "Python 3.9+" - - ```Python hl_lines="9" - {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} - ``` - -=== "Python 3.8+" +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[9] *} - ```Python hl_lines="8" - {!> ../../../docs_src/request_forms/tutorial001_an.py!} - ``` +Например, в одном из способов использования спецификации OAuth2 (называемом "потоком пароля") требуется отправить `username` и `password` в виде полей формы. -=== "Python 3.8+ без Annotated" +Данный способ требует отправку данных для авторизации посредством формы (а не JSON) и обязательного наличия в форме строго именованных полей `username` и `password`. - !!! tip "Подсказка" - Рекомендуется использовать 'Annotated' версию, если это возможно. +Вы можете настроить `Form` точно так же, как настраиваете и `Body` ( `Query`, `Path`, `Cookie`), включая валидации, примеры, псевдонимы (например, `user-name` вместо `username`) и т.д. - ```Python hl_lines="7" - {!> ../../../docs_src/request_forms/tutorial001.py!} - ``` +/// info | Дополнительная информация -Например, в одном из способов использования спецификации OAuth2 (называемом "потоком пароля") требуется отправить `username` и `password` в виде полей формы. +`Form` - это класс, который наследуется непосредственно от `Body`. -Данный способ требует отправку данных для авторизации посредством формы (а не JSON) и обязательного наличия в форме строго именованных полей `username` и `password`. +/// -Вы можете настроить `Form` точно так же, как настраиваете и `Body` ( `Query`, `Path`, `Cookie`), включая валидации, примеры, псевдонимы (например, `user-name` вместо `username`) и т.д. +/// tip | Подсказка -!!! info "Дополнительная информация" - `Form` - это класс, который наследуется непосредственно от `Body`. +Вам необходимо явно указывать параметр `Form` при объявлении каждого поля, иначе поля будут интерпретироваться как параметры запроса или параметры тела (JSON). -!!! tip "Подсказка" - Вам необходимо явно указывать параметр `Form` при объявлении каждого поля, иначе поля будут интерпретироваться как параметры запроса или параметры тела (JSON). +/// ## О "полях формы" @@ -75,17 +46,23 @@ **FastAPI** гарантирует правильное чтение этих данных из соответствующего места, а не из JSON. -!!! note "Технические детали" - Данные из форм обычно кодируются с использованием "типа медиа" `application/x-www-form-urlencoded`. +/// note | Технические детали + +Данные из форм обычно кодируются с использованием "типа медиа" `application/x-www-form-urlencoded`. + +Но когда форма содержит файлы, она кодируется как `multipart/form-data`. Вы узнаете о работе с файлами в следующей главе. + +Если вы хотите узнать больше про кодировки и поля формы, ознакомьтесь с документацией MDN для `POST` на веб-сайте. + +/// - Но когда форма содержит файлы, она кодируется как `multipart/form-data`. Вы узнаете о работе с файлами в следующей главе. +/// warning | Предупреждение - Если вы хотите узнать больше про кодировки и поля формы, ознакомьтесь с документацией MDN для `POST` на веб-сайте. +Вы можете объявлять несколько параметров `Form` в *операции пути*, но вы не можете одновременно с этим объявлять поля `Body`, которые вы ожидаете получить в виде JSON, так как запрос будет иметь тело, закодированное с использованием `application/x-www-form-urlencoded`, а не `application/json`. -!!! warning "Предупреждение" - Вы можете объявлять несколько параметров `Form` в *операции пути*, но вы не можете одновременно с этим объявлять поля `Body`, которые вы ожидаете получить в виде JSON, так как запрос будет иметь тело, закодированное с использованием `application/x-www-form-urlencoded`, а не `application/json`. +Это не ограничение **FastAPI**, это часть протокола HTTP. - Это не ограничение **FastAPI**, это часть протокола HTTP. +/// ## Резюме diff --git a/docs/ru/docs/tutorial/response-model.md b/docs/ru/docs/tutorial/response-model.md index 38b45e2a5..b3c29281c 100644 --- a/docs/ru/docs/tutorial/response-model.md +++ b/docs/ru/docs/tutorial/response-model.md @@ -4,23 +4,7 @@ FastAPI позволяет использовать **аннотации типов** таким же способом, как и для ввода данных в **параметры** функции, вы можете использовать модели Pydantic, списки, словари, скалярные типы (такие, как int, bool и т.д.). -=== "Python 3.10+" - - ```Python hl_lines="16 21" - {!> ../../../docs_src/response_model/tutorial001_01_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="18 23" - {!> ../../../docs_src/response_model/tutorial001_01_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="18 23" - {!> ../../../docs_src/response_model/tutorial001_01.py!} - ``` +{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *} FastAPI будет использовать этот возвращаемый тип для: @@ -53,35 +37,25 @@ FastAPI будет использовать этот возвращаемый т * `@app.delete()` * и др. -=== "Python 3.10+" - - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001_py310.py!} - ``` - -=== "Python 3.9+" +{* ../../docs_src/response_model/tutorial001_py310.py hl[17,22,24:27] *} - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001_py39.py!} - ``` +/// note | Технические детали -=== "Python 3.8+" +Помните, что параметр `response_model` является параметром именно декоратора http-методов (`get`, `post`, и т.п.). Не следует его указывать для *функций операций пути*, как вы бы поступили с другими параметрами или с телом запроса. - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001.py!} - ``` - -!!! note "Технические детали" - Помните, что параметр `response_model` является параметром именно декоратора http-методов (`get`, `post`, и т.п.). Не следует его указывать для *функций операций пути*, как вы бы поступили с другими параметрами или с телом запроса. +/// `response_model` принимает те же типы, которые можно указать для какого-либо поля в модели Pydantic. Таким образом, это может быть как одиночная модель Pydantic, так и `список (list)` моделей Pydantic. Например, `List[Item]`. FastAPI будет использовать значение `response_model` для того, чтобы автоматически генерировать документацию, производить валидацию и т.п. А также для **конвертации и фильтрации выходных данных** в объявленный тип. -!!! tip "Подсказка" - Если вы используете анализаторы типов со строгой проверкой (например, mypy), можно указать `Any` в качестве типа возвращаемого значения функции. +/// tip | Подсказка + +Если вы используете анализаторы типов со строгой проверкой (например, mypy), можно указать `Any` в качестве типа возвращаемого значения функции. - Таким образом вы информируете ваш редактор кода, что намеренно возвращаете данные неопределенного типа. Но возможности FastAPI, такие как автоматическая генерация документации, валидация, фильтрация и т.д. все так же будут работать, просто используя параметр `response_model`. +Таким образом вы информируете ваш редактор кода, что намеренно возвращаете данные неопределенного типа. Но возможности FastAPI, такие как автоматическая генерация документации, валидация, фильтрация и т.д. все так же будут работать, просто используя параметр `response_model`. + +/// ### Приоритет `response_model` @@ -95,36 +69,19 @@ FastAPI будет использовать значение `response_model` д Здесь мы объявили модель `UserIn`, которая хранит пользовательский пароль в открытом виде: -=== "Python 3.10+" - - ```Python hl_lines="7 9" - {!> ../../../docs_src/response_model/tutorial002_py310.py!} - ``` +{* ../../docs_src/response_model/tutorial002_py310.py hl[7,9] *} -=== "Python 3.8+" +/// info | Информация - ```Python hl_lines="9 11" - {!> ../../../docs_src/response_model/tutorial002.py!} - ``` +Чтобы использовать `EmailStr`, прежде необходимо установить `email-validator`. +Используйте `pip install email-validator` +или `pip install pydantic[email]`. -!!! info "Информация" - Чтобы использовать `EmailStr`, прежде необходимо установить `email_validator`. - Используйте `pip install email-validator` - или `pip install pydantic[email]`. +/// Далее мы используем нашу модель в аннотациях типа как для аргумента функции, так и для выходного значения: -=== "Python 3.10+" - - ```Python hl_lines="16" - {!> ../../../docs_src/response_model/tutorial002_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="18" - {!> ../../../docs_src/response_model/tutorial002.py!} - ``` +{* ../../docs_src/response_model/tutorial002_py310.py hl[16] *} Теперь всякий раз, когда клиент создает пользователя с паролем, API будет возвращать его пароль в ответе. @@ -132,52 +89,25 @@ FastAPI будет использовать значение `response_model` д Но что если мы захотим использовать эту модель для какой-либо другой *операции пути*? Мы можем, сами того не желая, отправить пароль любому другому пользователю. -!!! danger "Осторожно" - Никогда не храните пароли пользователей в открытом виде, а также никогда не возвращайте их в ответе, как в примере выше. В противном случае - убедитесь, что вы хорошо продумали и учли все возможные риски такого подхода и вам известно, что вы делаете. +/// danger | Осторожно -## Создание модели для ответа - -Вместо этого мы можем создать входную модель, хранящую пароль в открытом виде и выходную модель без пароля: +Никогда не храните пароли пользователей в открытом виде, а также никогда не возвращайте их в ответе, как в примере выше. В противном случае - убедитесь, что вы хорошо продумали и учли все возможные риски такого подхода и вам известно, что вы делаете. -=== "Python 3.10+" +/// - ```Python hl_lines="9 11 16" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +## Создание модели для ответа -=== "Python 3.8+" +Вместо этого мы можем создать входную модель, хранящую пароль в открытом виде и выходную модель без пароля: - ```Python hl_lines="9 11 16" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +{* ../../docs_src/response_model/tutorial003_py310.py hl[9,11,16] *} В таком случае, даже несмотря на то, что наша *функция операции пути* возвращает тот же самый объект пользователя с паролем, полученным на вход: -=== "Python 3.10+" - - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +{* ../../docs_src/response_model/tutorial003_py310.py hl[24] *} ...мы указали в `response_model` модель `UserOut`, в которой отсутствует поле, содержащее пароль - и он будет исключен из ответа: -=== "Python 3.10+" - - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +{* ../../docs_src/response_model/tutorial003_py310.py hl[22] *} Таким образом **FastAPI** позаботится о фильтрации ответа и исключит из него всё, что не указано в выходной модели (при помощи Pydantic). @@ -201,17 +131,7 @@ FastAPI будет использовать значение `response_model` д И в таких случаях мы можем использовать классы и наследование, чтобы пользоваться преимуществами **аннотаций типов** и получать более полную статическую проверку типов. Но при этом все так же получать **фильтрацию ответа** от FastAPI. -=== "Python 3.10+" - - ```Python hl_lines="7-10 13-14 18" - {!> ../../../docs_src/response_model/tutorial003_01_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="9-13 15-16 20" - {!> ../../../docs_src/response_model/tutorial003_01.py!} - ``` +{* ../../docs_src/response_model/tutorial003_01_py310.py hl[7:10,13:14,18] *} Таким образом, мы получаем поддержку редактора кода и mypy в части типов, сохраняя при этом фильтрацию данных от FastAPI. @@ -253,9 +173,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма Самый частый сценарий использования - это [возвращать Response напрямую, как описано в расширенной документации](../advanced/response-directly.md){.internal-link target=_blank}. -```Python hl_lines="8 10-11" -{!> ../../../docs_src/response_model/tutorial003_02.py!} -``` +{* ../../docs_src/response_model/tutorial003_02.py hl[8,10:11] *} Это поддерживается FastAPI по-умолчанию, т.к. аннотация проставлена в классе (или подклассе) `Response`. @@ -265,9 +183,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма Вы также можете указать подкласс `Response` в аннотации типа: -```Python hl_lines="8-9" -{!> ../../../docs_src/response_model/tutorial003_03.py!} -``` +{* ../../docs_src/response_model/tutorial003_03.py hl[8:9] *} Это сработает, потому что `RedirectResponse` является подклассом `Response` и FastAPI автоматически обработает этот простейший случай. @@ -277,17 +193,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма То же самое произошло бы, если бы у вас было что-то вроде Union различных типов и один или несколько из них не являлись бы допустимыми типами для Pydantic. Например, такой вариант приведет к ошибке 💥: -=== "Python 3.10+" - - ```Python hl_lines="8" - {!> ../../../docs_src/response_model/tutorial003_04_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="10" - {!> ../../../docs_src/response_model/tutorial003_04.py!} - ``` +{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *} ...такой код вызовет ошибку, потому что в аннотации указан неподдерживаемый Pydantic тип. А также этот тип не является классом или подклассом `Response`. @@ -299,17 +205,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма В таком случае, вы можете отключить генерацию модели ответа, указав `response_model=None`: -=== "Python 3.10+" - - ```Python hl_lines="7" - {!> ../../../docs_src/response_model/tutorial003_05_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="9" - {!> ../../../docs_src/response_model/tutorial003_05.py!} - ``` +{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *} Тогда FastAPI не станет генерировать модель ответа и вы сможете сохранить такую аннотацию типа, которая вам требуется, никак не влияя на работу FastAPI. 🤓 @@ -317,23 +213,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма Модель ответа может иметь значения по умолчанию, например: -=== "Python 3.10+" - - ```Python hl_lines="9 11-12" - {!> ../../../docs_src/response_model/tutorial004_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="11 13-14" - {!> ../../../docs_src/response_model/tutorial004_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="11 13-14" - {!> ../../../docs_src/response_model/tutorial004.py!} - ``` +{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *} * `description: Union[str, None] = None` (или `str | None = None` в Python 3.10), где `None` является значением по умолчанию. * `tax: float = 10.5`, где `10.5` является значением по умолчанию. @@ -347,23 +227,7 @@ FastAPI совместно с Pydantic выполнит некоторую ма Установите для *декоратора операции пути* параметр `response_model_exclude_unset=True`: -=== "Python 3.10+" - - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial004_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial004_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial004.py!} - ``` +{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *} и тогда значения по умолчанию не будут включены в ответ. В нем будут только те поля, значения которых фактически были установлены. @@ -376,16 +240,22 @@ FastAPI совместно с Pydantic выполнит некоторую ма } ``` -!!! info "Информация" - "Под капотом" FastAPI использует метод `.dict()` у объектов моделей Pydantic с параметром `exclude_unset`, чтобы достичь такого эффекта. +/// info | Информация + +"Под капотом" FastAPI использует метод `.dict()` у объектов моделей Pydantic с параметром `exclude_unset`, чтобы достичь такого эффекта. + +/// + +/// info | Информация -!!! info "Информация" - Вы также можете использовать: +Вы также можете использовать: - * `response_model_exclude_defaults=True` - * `response_model_exclude_none=True` +* `response_model_exclude_defaults=True` +* `response_model_exclude_none=True` - как описано в документации Pydantic для параметров `exclude_defaults` и `exclude_none`. +как описано в документации Pydantic для параметров `exclude_defaults` и `exclude_none`. + +/// #### Если значение поля отличается от значения по-умолчанию @@ -420,10 +290,13 @@ FastAPI достаточно умен (на самом деле, это засл И поэтому, они также будут включены в JSON ответа. -!!! tip "Подсказка" - Значением по умолчанию может быть что угодно, не только `None`. +/// tip | Подсказка + +Значением по умолчанию может быть что угодно, не только `None`. - Им может быть и список (`[]`), значение 10.5 типа `float`, и т.п. +Им может быть и список (`[]`), значение 10.5 типа `float`, и т.п. + +/// ### `response_model_include` и `response_model_exclude` @@ -433,45 +306,31 @@ FastAPI достаточно умен (на самом деле, это засл Это можно использовать как быстрый способ исключить данные из ответа, не создавая отдельную модель Pydantic. -!!! tip "Подсказка" - Но по-прежнему рекомендуется следовать изложенным выше советам и использовать несколько моделей вместо данных параметров. +/// tip | Подсказка + +Но по-прежнему рекомендуется следовать изложенным выше советам и использовать несколько моделей вместо данных параметров. - Потому как JSON схема OpenAPI, генерируемая вашим приложением (а также документация) все еще будет содержать все поля, даже если вы использовали `response_model_include` или `response_model_exclude` и исключили некоторые атрибуты. +Потому как JSON схема OpenAPI, генерируемая вашим приложением (а также документация) все еще будет содержать все поля, даже если вы использовали `response_model_include` или `response_model_exclude` и исключили некоторые атрибуты. - То же самое применимо к параметру `response_model_by_alias`. +То же самое применимо к параметру `response_model_by_alias`. -=== "Python 3.10+" +/// - ```Python hl_lines="29 35" - {!> ../../../docs_src/response_model/tutorial005_py310.py!} - ``` +{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *} -=== "Python 3.8+" +/// tip | Подсказка - ```Python hl_lines="31 37" - {!> ../../../docs_src/response_model/tutorial005.py!} - ``` +При помощи кода `{"name","description"}` создается объект множества (`set`) с двумя строковыми значениями. -!!! tip "Подсказка" - При помощи кода `{"name","description"}` создается объект множества (`set`) с двумя строковыми значениями. +Того же самого можно достичь используя `set(["name", "description"])`. - Того же самого можно достичь используя `set(["name", "description"])`. +/// #### Что если использовать `list` вместо `set`? Если вы забыли про `set` и использовали структуру `list` или `tuple`, FastAPI автоматически преобразует этот объект в `set`, чтобы обеспечить корректную работу: -=== "Python 3.10+" - - ```Python hl_lines="29 35" - {!> ../../../docs_src/response_model/tutorial006_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="31 37" - {!> ../../../docs_src/response_model/tutorial006.py!} - ``` +{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *} ## Резюме diff --git a/docs/ru/docs/tutorial/response-status-code.md b/docs/ru/docs/tutorial/response-status-code.md index b2f9b7704..b46f656f3 100644 --- a/docs/ru/docs/tutorial/response-status-code.md +++ b/docs/ru/docs/tutorial/response-status-code.md @@ -8,17 +8,21 @@ * `@app.delete()` * и других. -```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} -!!! note "Примечание" - Обратите внимание, что `status_code` является атрибутом метода-декоратора (`get`, `post` и т.д.), а не *функции-обработчика пути* в отличие от всех остальных параметров и тела запроса. +/// note | Примечание + +Обратите внимание, что `status_code` является атрибутом метода-декоратора (`get`, `post` и т.д.), а не *функции-обработчика пути* в отличие от всех остальных параметров и тела запроса. + +/// Параметр `status_code` принимает число, обозначающее HTTP код статуса ответа. -!!! info "Информация" - В качестве значения параметра `status_code` также может использоваться `IntEnum`, например, из библиотеки `http.HTTPStatus` в Python. +/// info | Информация + +В качестве значения параметра `status_code` также может использоваться `IntEnum`, например, из библиотеки `http.HTTPStatus` в Python. + +/// Это позволит: @@ -27,15 +31,21 @@ -!!! note "Примечание" - Некоторые коды статуса ответа (см. следующий раздел) указывают на то, что ответ не имеет тела. +/// note | Примечание + +Некоторые коды статуса ответа (см. следующий раздел) указывают на то, что ответ не имеет тела. + +FastAPI знает об этом и создаст документацию OpenAPI, в которой будет указано, что тело ответа отсутствует. - FastAPI знает об этом и создаст документацию OpenAPI, в которой будет указано, что тело ответа отсутствует. +/// ## Об HTTP кодах статуса ответа -!!! note "Примечание" - Если вы уже знаете, что представляют собой HTTP коды статуса ответа, можете перейти к следующему разделу. +/// note | Примечание + +Если вы уже знаете, что представляют собой HTTP коды статуса ответа, можете перейти к следующему разделу. + +/// В протоколе HTTP числовой код состояния из 3 цифр отправляется как часть ответа. @@ -54,16 +64,17 @@ * Для общих ошибок со стороны клиента можно просто использовать код `400`. * `5XX` – статус-коды, сообщающие о серверной ошибке. Они почти никогда не используются разработчиками напрямую. Когда что-то идет не так в какой-то части кода вашего приложения или на сервере, он автоматически вернёт один из 5XX кодов. -!!! tip "Подсказка" - Чтобы узнать больше о HTTP кодах статуса и о том, для чего каждый из них предназначен, ознакомьтесь с документацией MDN об HTTP кодах статуса ответа. +/// tip | Подсказка + +Чтобы узнать больше о HTTP кодах статуса и о том, для чего каждый из них предназначен, ознакомьтесь с документацией MDN об HTTP кодах статуса ответа. + +/// ## Краткие обозначения для запоминания названий кодов Рассмотрим предыдущий пример еще раз: -```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} `201` – это код статуса "Создано". @@ -71,18 +82,19 @@ Для удобства вы можете использовать переменные из `fastapi.status`. -```Python hl_lines="1 6" -{!../../../docs_src/response_status_code/tutorial002.py!} -``` +{* ../../docs_src/response_status_code/tutorial002.py hl[1,6] *} Они содержат те же числовые значения, но позволяют использовать подсказки редактора для выбора кода статуса: -!!! note "Технические детали" - Вы также можете использовать `from starlette import status` вместо `from fastapi import status`. +/// note | Технические детали + +Вы также можете использовать `from starlette import status` вместо `from fastapi import status`. + +**FastAPI** позволяет использовать как `starlette.status`, так и `fastapi.status` исключительно для удобства разработчиков. Но поставляется fastapi.status непосредственно из Starlette. - **FastAPI** позволяет использовать как `starlette.status`, так и `fastapi.status` исключительно для удобства разработчиков. Но поставляется fastapi.status непосредственно из Starlette. +/// ## Изменение кода статуса по умолчанию diff --git a/docs/ru/docs/tutorial/schema-extra-example.md b/docs/ru/docs/tutorial/schema-extra-example.md index a13ab5935..f17b24349 100644 --- a/docs/ru/docs/tutorial/schema-extra-example.md +++ b/docs/ru/docs/tutorial/schema-extra-example.md @@ -6,26 +6,19 @@ ## Pydantic `schema_extra` -Вы можете объявить ключ `example` для модели Pydantic, используя класс `Config` и переменную `schema_extra`, как описано в Pydantic документации: Настройка схемы: +Вы можете объявить ключ `example` для модели Pydantic, используя класс `Config` и переменную `schema_extra`, как описано в Pydantic документации: Настройка схемы: -=== "Python 3.10+" +{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:21] *} - ```Python hl_lines="13-21" - {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} - ``` - -=== "Python 3.8+" +Эта дополнительная информация будет включена в **JSON Schema** выходных данных для этой модели, и она будет использоваться в документации к API. - ```Python hl_lines="15-23" - {!> ../../../docs_src/schema_extra_example/tutorial001.py!} - ``` +/// tip | Подсказка -Эта дополнительная информация будет включена в **JSON Schema** выходных данных для этой модели, и она будет использоваться в документации к API. +Вы можете использовать тот же метод для расширения JSON-схемы и добавления своей собственной дополнительной информации. -!!! tip Подсказка - Вы можете использовать тот же метод для расширения JSON-схемы и добавления своей собственной дополнительной информации. +Например, вы можете использовать это для добавления дополнительной информации для пользовательского интерфейса в вашем веб-приложении и т.д. - Например, вы можете использовать это для добавления дополнительной информации для пользовательского интерфейса в вашем веб-приложении и т.д. +/// ## Дополнительные аргументы поля `Field` @@ -33,20 +26,13 @@ Вы можете использовать это, чтобы добавить аргумент `example` для каждого поля: -=== "Python 3.10+" - - ```Python hl_lines="2 8-11" - {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} - ``` +{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *} -=== "Python 3.8+" +/// warning | Внимание - ```Python hl_lines="4 10-13" - {!> ../../../docs_src/schema_extra_example/tutorial002.py!} - ``` +Имейте в виду, что эти дополнительные переданные аргументы не добавляют никакой валидации, только дополнительную информацию для документации. -!!! warning Внимание - Имейте в виду, что эти дополнительные переданные аргументы не добавляют никакой валидации, только дополнительную информацию для документации. +/// ## Использование `example` и `examples` в OpenAPI @@ -66,41 +52,7 @@ Здесь мы передаём аргумент `example`, как пример данных ожидаемых в параметре `Body()`: -=== "Python 3.10+" - - ```Python hl_lines="22-27" - {!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="22-27" - {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="23-28" - {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! tip Заметка - Рекомендуется использовать версию с `Annotated`, если это возможно. - - ```Python hl_lines="18-23" - {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip Заметка - Рекомендуется использовать версию с `Annotated`, если это возможно. - - ```Python hl_lines="20-25" - {!> ../../../docs_src/schema_extra_example/tutorial003.py!} - ``` +{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:27] *} ### Аргумент "example" в UI документации @@ -121,41 +73,7 @@ * `value`: Это конкретный пример, который отображается, например, в виде типа `dict`. * `externalValue`: альтернатива параметру `value`, URL-адрес, указывающий на пример. Хотя это может не поддерживаться таким же количеством инструментов разработки и тестирования API, как параметр `value`. -=== "Python 3.10+" - - ```Python hl_lines="23-49" - {!> ../../../docs_src/schema_extra_example/tutorial004_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="23-49" - {!> ../../../docs_src/schema_extra_example/tutorial004_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="24-50" - {!> ../../../docs_src/schema_extra_example/tutorial004_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! tip Заметка - Рекомендуется использовать версию с `Annotated`, если это возможно. - - ```Python hl_lines="19-45" - {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip Заметка - Рекомендуется использовать версию с `Annotated`, если это возможно. - - ```Python hl_lines="21-47" - {!> ../../../docs_src/schema_extra_example/tutorial004.py!} - ``` +{* ../../docs_src/schema_extra_example/tutorial004_an_py310.py hl[23:49] *} ### Аргумент "examples" в UI документации @@ -165,10 +83,13 @@ ## Технические Детали -!!! warning Внимание - Эти технические детали относятся к стандартам **JSON Schema** и **OpenAPI**. +/// warning | Внимание + +Эти технические детали относятся к стандартам **JSON Schema** и **OpenAPI**. + +Если предложенные выше идеи уже работают для вас, возможно этого будет достаточно и эти детали вам не потребуются, можете спокойно их пропустить. - Если предложенные выше идеи уже работают для вас, возможно этого будет достаточно и эти детали вам не потребуются, можете спокойно их пропустить. +/// Когда вы добавляете пример внутрь модели Pydantic, используя `schema_extra` или `Field(example="something")`, этот пример добавляется в **JSON Schema** для данной модели Pydantic. diff --git a/docs/ru/docs/tutorial/security/first-steps.md b/docs/ru/docs/tutorial/security/first-steps.md new file mode 100644 index 000000000..375c2d7f6 --- /dev/null +++ b/docs/ru/docs/tutorial/security/first-steps.md @@ -0,0 +1,195 @@ +# Безопасность - первые шаги + +Представим, что у вас есть свой **бэкенд** API на некотором домене. + +И у вас есть **фронтенд** на другом домене или на другом пути того же домена (или в мобильном приложении). + +И вы хотите иметь возможность аутентификации фронтенда с бэкендом, используя **имя пользователя** и **пароль**. + +Мы можем использовать **OAuth2** для создания такой системы с помощью **FastAPI**. + +Но давайте избавим вас от необходимости читать всю длинную спецификацию, чтобы найти те небольшие кусочки информации, которые вам нужны. + +Для работы с безопасностью воспользуемся средствами, предоставленными **FastAPI**. + +## Как это выглядит + +Давайте сначала просто воспользуемся кодом и посмотрим, как он работает, а затем детально разберём, что происходит. + +## Создание `main.py` + +Скопируйте пример в файл `main.py`: + +{* ../../docs_src/security/tutorial001_an_py39.py *} + +## Запуск + +/// info | Дополнительная информация + +Вначале, установите библиотеку `python-multipart`. + +А именно: `pip install python-multipart`. + +Это связано с тем, что **OAuth2** использует "данные формы" для передачи `имени пользователя` и `пароля`. + +/// + +Запустите ваш сервер: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +## Проверка + +Перейдите к интерактивной документации по адресу: http://127.0.0.1:8000/docs. + +Вы увидите примерно следующее: + + + +/// check | Кнопка авторизации! + +У вас уже появилась новая кнопка "Authorize". + +А у *операции пути* теперь появился маленький замочек в правом верхнем углу, на который можно нажать. + +/// + +При нажатии на нее появляется небольшая форма авторизации, в которую нужно ввести `имя пользователя` и `пароль` (и другие необязательные поля): + + + +/// note | Технические детали + +Неважно, что вы введете в форму, она пока не будет работать. Но мы к этому еще придем. + +/// + +Конечно, это не фронтенд для конечных пользователей, но это отличный автоматический инструмент для интерактивного документирования всех ваших API. + +Он может использоваться командой фронтенда (которой можете быть и вы сами). + +Он может быть использован сторонними приложениями и системами. + +Кроме того, его можно использовать самостоятельно для отладки, проверки и тестирования одного и того же приложения. + +## Аутентификация по паролю + +Теперь давайте вернемся немного назад и разберемся, что же это такое. + +Аутентификация по паролю является одним из способов, определенных в OAuth2, для обеспечения безопасности и аутентификации. + +OAuth2 был разработан для того, чтобы бэкэнд или API были независимы от сервера, который аутентифицирует пользователя. + +Но в нашем случае одно и то же приложение **FastAPI** будет работать с API и аутентификацией. + +Итак, рассмотрим его с этой упрощенной точки зрения: + +* Пользователь вводит на фронтенде `имя пользователя` и `пароль` и нажимает `Enter`. +* Фронтенд (работающий в браузере пользователя) отправляет эти `имя пользователя` и `пароль` на определенный URL в нашем API (объявленный с помощью параметра `tokenUrl="token"`). +* API проверяет эти `имя пользователя` и `пароль` и выдает в ответ "токен" (мы еще не реализовали ничего из этого). + * "Токен" - это просто строка с некоторым содержимым, которое мы можем использовать позже для верификации пользователя. + * Обычно срок действия токена истекает через некоторое время. + * Таким образом, пользователю придется снова войти в систему в какой-то момент времени. + * И если токен будет украден, то риск будет меньше, так как он не похож на постоянный ключ, который будет работать вечно (в большинстве случаев). +* Фронтенд временно хранит этот токен в каком-то месте. +* Пользователь щелкает мышью на фронтенде, чтобы перейти в другой раздел на фронтенде. +* Фронтенду необходимо получить дополнительные данные из API. + * Но для этого необходима аутентификация для конкретной конечной точки. + * Поэтому для аутентификации в нашем API он посылает заголовок `Authorization` со значением `Bearer` плюс сам токен. + * Если токен содержит `foobar`, то содержание заголовка `Authorization` будет таким: `Bearer foobar`. + +## Класс `OAuth2PasswordBearer` в **FastAPI** + +**FastAPI** предоставляет несколько средств на разных уровнях абстракции для реализации этих функций безопасности. + +В данном примере мы будем использовать **OAuth2**, с аутентификацией по паролю, используя токен **Bearer**. Для этого мы используем класс `OAuth2PasswordBearer`. + +/// info | Дополнительная информация + +Токен "bearer" - не единственный вариант, но для нашего случая он является наилучшим. + +И это может быть лучшим вариантом для большинства случаев использования, если только вы не являетесь экспертом в области OAuth2 и точно знаете, почему вам лучше подходит какой-то другой вариант. + +В этом случае **FastAPI** также предоставляет инструменты для его реализации. + +/// + +При создании экземпляра класса `OAuth2PasswordBearer` мы передаем в него параметр `tokenUrl`. Этот параметр содержит URL, который клиент (фронтенд, работающий в браузере пользователя) будет использовать для отправки `имени пользователя` и `пароля` с целью получения токена. + +{* ../../docs_src/security/tutorial001_an_py39.py hl[8] *} + +/// 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 | Дополнительная информация + +Если вы очень строгий "питонист", то вам может не понравиться стиль названия параметра `tokenUrl` вместо `token_url`. + +Это связано с тем, что тут используется то же имя, что и в спецификации OpenAPI. Таким образом, если вам необходимо более подробно изучить какую-либо из этих схем безопасности, вы можете просто использовать копирование/вставку, чтобы найти дополнительную информацию о ней. + +/// + +Переменная `oauth2_scheme` является экземпляром `OAuth2PasswordBearer`, но она также является "вызываемой". + +Ее можно вызвать следующим образом: + +```Python +oauth2_scheme(some, parameters) +``` + +Поэтому ее можно использовать вместе с `Depends`. + +### Использование + +Теперь вы можете передать ваш `oauth2_scheme` в зависимость с помощью `Depends`. + +{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *} + +Эта зависимость будет предоставлять `строку`, которая присваивается параметру `token` в *функции операции пути*. + +**FastAPI** будет знать, что он может использовать эту зависимость для определения "схемы безопасности" в схеме OpenAPI (и автоматической документации по API). + +/// info | Технические детали + +**FastAPI** будет знать, что он может использовать класс `OAuth2PasswordBearer` (объявленный в зависимости) для определения схемы безопасности в OpenAPI, поскольку он наследуется от `fastapi.security.oauth2.OAuth2`, который, в свою очередь, наследуется от `fastapi.security.base.SecurityBase`. + +Все утилиты безопасности, интегрируемые в OpenAPI (и автоматическая документация по API), наследуются от `SecurityBase`, поэтому **FastAPI** может знать, как интегрировать их в OpenAPI. + +/// + +## Что он делает + +Он будет искать в запросе заголовок `Authorization` и проверять, содержит ли он значение `Bearer` с некоторым токеном, и возвращать токен в виде `строки`. + +Если он не видит заголовка `Authorization` или значение не имеет токена `Bearer`, то в ответ будет выдана ошибка с кодом состояния 401 (`UNAUTHORIZED`). + +Для возврата ошибки даже не нужно проверять, существует ли токен. Вы можете быть уверены, что если ваша функция была выполнена, то в этом токене есть `строка`. + +Проверить это можно уже сейчас в интерактивной документации: + + + +Мы пока не проверяем валидность токена, но для начала неплохо. + +## Резюме + +Таким образом, всего за 3-4 дополнительные строки вы получаете некую примитивную форму защиты. diff --git a/docs/ru/docs/tutorial/security/get-current-user.md b/docs/ru/docs/tutorial/security/get-current-user.md new file mode 100644 index 000000000..05eb290d7 --- /dev/null +++ b/docs/ru/docs/tutorial/security/get-current-user.md @@ -0,0 +1,99 @@ +# Данные текущего пользователя + +В предыдущей главе система безопасности (основанная на системе внедрения зависимостей) передавала *функции, обрабатывающей эндпоинт,* `токен` в виде `строки`: + +{* ../../docs_src/security/tutorial001_an_py39.py hl[12] *} + +Это пока что не слишком нам полезно. Давайте изменим код так, чтобы он возвращал нам данные пользователя, отправившего запрос. + +## Создание модели пользователя + +Сначала создадим Pydantic-модель пользователя. + +Точно так же, как мы использовали Pydantic для объявления тел запросов, мы можем использовать его где угодно: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[5,12:6] *} + +## Создание зависимости `get_current_user` + +Давайте создадим зависимость `get_current_user`. + +Помните, что у зависимостей могут быть подзависимости? + +`get_current_user` как раз будет иметь подзависимость `oauth2_scheme`, которую мы создали ранее. + +Аналогично тому, как мы делали это ранее в *обработчике эндпоинта* наша новая зависимость `get_current_user` будет получать `token` в виде `строки` от подзависимости `oauth2_scheme`: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[25] *} + +## Получение данных пользователя + +`get_current_user` будет использовать созданную нами (ненастоящую) служебную функцию, которая принимает токен в виде `строки` и возвращает нашу Pydantic-модель `User`: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[19:22,26:27] *} + +## Внедрение зависимости текущего пользователя + +Теперь мы можем использовать тот же `Depends` с нашей зависимостью `get_current_user` в *функции обрабатывающей эндпоинт*: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[31] *} + +Обратите внимание, что мы объявляем тип переменной `current_user` как Pydantic-модель `User`. + +Это поможет выполнить внутри функции все проверки автозаполнения и типа. + +/// tip | Подсказка +Возможно, вы помните, что тело запроса также объявляется с помощью Pydantic-моделей. + +В этом месте у **FastAPI** не возникнет проблем, потому что вы используете `Depends`. +/// + +/// check | Заметка +То, как устроена эта система зависимостей, позволяет нам иметь различные зависимости, которые возвращают модель `User`. + +Мы не ограничены наличием только одной зависимости, которая может возвращать данные такого типа. +/// + +## Другие модели + +Теперь вы можете получать информацию о текущем пользователе непосредственно в *функции обрабатывающей эндпоинт* и работать с механизмами безопасности на уровне **Внедрения Зависимостей**, используя `Depends`. + +Причем для обеспечения требований безопасности можно использовать любую модель или данные (в данном случае - Pydantic-модель `User`). + +Но вы не ограничены использованием какой-то конкретной моделью данных, классом или типом. + +Вы хотите использовать в модели `id` и `email`, а `username` вам не нужен? Ну разумеется. Воспользуйтесь тем же инструментарием. + +Вам нужны только `строки`? Или только `словари`? Или непосредственно экземпляр модели класса базы данных? Все это работает точно также. + +У вас нет пользователей, которые входят в ваше приложение, а только роботы, боты или другие системы, у которых есть только токен доступа? Опять же, все работает одинаково. + +Просто используйте любую модель, любой класс, любую базу данных, которые нужны для вашего приложения. Система внедрения зависимостей **FastAPI** поможет вам в этом. + +## Размер кода + +Этот пример может показаться многословным. Следует иметь в виду, что в одном файле мы смешиваем безопасность, модели данных, служебные функции и *эндпоинты*. + +Но вот ключевой момент: + +Все, что касается безопасности и внедрения зависимостей, пишется один раз. + +И вы можете сделать его настолько сложным, насколько захотите. И все это будет написано только один раз, в одном месте, со всей своей гибкостью. + +И у вас могут быть тысячи конечных точек (*эндпоинтов*), использующих одну и ту же систему безопасности. + +И все они (или любая их часть по вашему желанию) могут воспользоваться преимуществами повторного использования этих зависимостей или любых других зависимостей, которые вы создадите. + +И все эти тысячи *эндпоинтов* могут составлять всего 3 строки: + +{* ../../docs_src/security/tutorial002_an_py310.py hl[30:32] *} + +## Резюме + +Теперь вы можете получать данные о текущем пользователе непосредственно в своей *функции обработчике эндпоинта*. + +Мы уже на полпути к этому. + +Осталось лишь добавить *эндпоинт* для отправки пользователем/клиентом своих `имени пользователя` и `пароля`. + +Это будет рассмотрено в следующем разделе. diff --git a/docs/ru/docs/tutorial/security/index.md b/docs/ru/docs/tutorial/security/index.md index d5fe4e76f..e4969c4cf 100644 --- a/docs/ru/docs/tutorial/security/index.md +++ b/docs/ru/docs/tutorial/security/index.md @@ -32,9 +32,11 @@ OAuth2 включает в себя способы аутентификации OAuth2 не указывает, как шифровать сообщение, он ожидает, что ваше приложение будет обслуживаться по протоколу HTTPS. -!!! tip "Подсказка" - В разделе **Развертывание** вы увидите [как настроить протокол HTTPS бесплатно, используя Traefik и Let's Encrypt.](https://fastapi.tiangolo.com/ru/deployment/https/) +/// tip | Подсказка +В разделе **Развертывание** вы увидите [как настроить протокол HTTPS бесплатно, используя Traefik и Let's Encrypt.](https://fastapi.tiangolo.com/ru/deployment/https/) + +/// ## OpenID Connect @@ -87,10 +89,13 @@ OpenAPI может использовать следующие схемы авт * Это автоматическое обнаружение определено в спецификации OpenID Connect. -!!! tip "Подсказка" - Интеграция сторонних сервисов для аутентификации/авторизации таких как Google, Facebook, Twitter, GitHub и т.д. осуществляется достаточно легко. +/// tip | Подсказка + +Интеграция сторонних сервисов для аутентификации/авторизации таких как Google, Facebook, Twitter, GitHub и т.д. осуществляется достаточно легко. + +Самой сложной проблемой является создание такого провайдера аутентификации/авторизации, но **FastAPI** предоставляет вам инструменты, позволяющие легко это сделать, выполняя при этом всю тяжелую работу за вас. - Самой сложной проблемой является создание такого провайдера аутентификации/авторизации, но **FastAPI** предоставляет вам инструменты, позволяющие легко это сделать, выполняя при этом всю тяжелую работу за вас. +/// ## Преимущества **FastAPI** diff --git a/docs/ru/docs/tutorial/security/oauth2-jwt.md b/docs/ru/docs/tutorial/security/oauth2-jwt.md new file mode 100644 index 000000000..1195fad21 --- /dev/null +++ b/docs/ru/docs/tutorial/security/oauth2-jwt.md @@ -0,0 +1,261 @@ +# OAuth2 с паролем (и хешированием), Bearer с JWT-токенами + +Теперь, когда у нас определен процесс обеспечения безопасности, давайте сделаем приложение действительно безопасным, используя токены JWT и безопасное хеширование паролей. + +Этот код можно реально использовать в своем приложении, сохранять хэши паролей в базе данных и т.д. + +Мы продолжим разбираться, начиная с того места, на котором остановились в предыдущей главе. + +## Про JWT + +JWT означает "JSON Web Tokens". + +Это стандарт для кодирования JSON-объекта в виде длинной строки без пробелов. Выглядит это следующим образом: + +``` +eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c +``` + +Он не зашифрован, поэтому любой человек может восстановить информацию из его содержимого. + +Но он подписан. Следовательно, когда вы получаете токен, который вы эмитировали (выдавали), вы можете убедиться, что это именно вы его эмитировали. + +Таким образом, можно создать токен со сроком действия, скажем, 1 неделя. А когда пользователь вернется на следующий день с тем же токеном, вы будете знать, что он все еще авторизирован в вашей системе. + +Через неделю срок действия токена истечет, пользователь не будет авторизован и ему придется заново входить в систему, чтобы получить новый токен. А если пользователь (или третье лицо) попытается модифицировать токен, чтобы изменить срок действия, вы сможете это обнаружить, поскольку подписи не будут совпадать. + +Если вы хотите поиграть с JWT-токенами и посмотреть, как они работают, посмотрите https://jwt.io. + +## Установка `PyJWT` + +Нам необходимо установить `pyjwt` для генерации и проверки JWT-токенов на языке Python. + +Убедитесь, что вы создали [виртуальное окружение](../../virtual-environments.md){.internal-link target=_blank}, активируйте его, а затем установите `pyjwt`: + +
+ +```console +$ pip install pyjwt + +---> 100% +``` + +
+ +/// info | Дополнительная информация +Если вы планируете использовать алгоритмы цифровой подписи, такие как RSA или ECDSA, вам следует установить зависимость библиотеки криптографии `pyjwt[crypto]`. + +Подробнее об этом можно прочитать в документации по установке PyJWT. +/// + +## Хеширование паролей + +"Хеширование" означает преобразование некоторого содержимого (в данном случае пароля) в последовательность байтов (просто строку), которая выглядит как тарабарщина. + +Каждый раз, когда вы передаете точно такое же содержимое (точно такой же пароль), вы получаете точно такую же тарабарщину. + +Но преобразовать тарабарщину обратно в пароль невозможно. + +### Для чего нужно хеширование паролей + +Если ваша база данных будет украдена, то вор не получит пароли пользователей в открытом виде, а только их хэши. + +Таким образом, вор не сможет использовать этот пароль в другой системе (поскольку многие пользователи везде используют один и тот же пароль, это было бы опасно). + +## Установка `passlib` + +PassLib - это отличный пакет Python для работы с хэшами паролей. + +Он поддерживает множество безопасных алгоритмов хеширования и утилит для работы с ними. + +Рекомендуемый алгоритм - "Bcrypt". + +Убедитесь, что вы создали и активировали виртуальное окружение, и затем установите PassLib вместе с Bcrypt: + +
+ +```console +$ pip install "passlib[bcrypt]" + +---> 100% +``` + +
+ +/// tip | Подсказка +С помощью `passlib` можно даже настроить его на чтение паролей, созданных **Django**, плагином безопасности **Flask** или многими другими библиотеками. + +Таким образом, вы сможете, например, совместно использовать одни и те же данные из приложения Django в базе данных с приложением FastAPI. Или постепенно мигрировать Django-приложение, используя ту же базу данных. + +При этом пользователи смогут одновременно входить в систему как из приложения Django, так и из приложения **FastAPI**. +/// + +## Хеширование и проверка паролей + +Импортируйте необходимые инструменты из `passlib`. + +Создайте "контекст" PassLib. Именно он будет использоваться для хэширования и проверки паролей. + +/// tip | Подсказка +Контекст PassLib также имеет функциональность для использования различных алгоритмов хеширования, в том числе и устаревших, только для возможности их проверки и т.д. + +Например, вы можете использовать его для чтения и проверки паролей, сгенерированных другой системой (например, Django), но хэшировать все новые пароли другим алгоритмом, например Bcrypt. + +И при этом быть совместимым со всеми этими системами. +/// + +Создайте служебную функцию для хэширования пароля, поступающего от пользователя. + +А затем создайте другую - для проверки соответствия полученного пароля и хранимого хэша. + +И еще одну - для аутентификации и возврата пользователя. + +{* ../../docs_src/security/tutorial004_an_py310.py hl[8,49,56:57,60:61,70:76] *} + +/// note | Технические детали +Если проверить новую (фальшивую) базу данных `fake_users_db`, то можно увидеть, как теперь выглядит хэшированный пароль: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`. +/// + +## Работа с JWT токенами + +Импортируйте установленные модули. + +Создайте случайный секретный ключ, который будет использоваться для подписи JWT-токенов. + +Для генерации безопасного случайного секретного ключа используйте команду: + +
+ +```console +$ openssl rand -hex 32 + +09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7 +``` + +
+ +И скопируйте полученный результат в переменную `SECRET_KEY` (не используйте тот, что в примере). + +Создайте переменную `ALGORITHM` с алгоритмом, используемым для подписи JWT-токена, и установите для нее значение `"HS256"`. + +Создайте переменную для срока действия токена. + +Определите Pydantic Model, которая будет использоваться для формирования ответа на запрос на получение токена. + +Создайте служебную функцию для генерации нового токена доступа. + +{* ../../docs_src/security/tutorial004_an_py310.py hl[4,7,13:15,29:31,79:87] *} + +## Обновление зависимостей + +Обновите `get_current_user` для получения того же токена, что и раньше, но на этот раз с использованием JWT-токенов. + +Декодируйте полученный токен, проверьте его и верните текущего пользователя. + +Если токен недействителен, то сразу же верните HTTP-ошибку. + +{* ../../docs_src/security/tutorial004_an_py310.py hl[90:107] *} + +## Обновление *операции пути* `/token` + +Создайте `timedelta` со временем истечения срока действия токена. + +Создайте реальный токен доступа JWT и верните его + +{* ../../docs_src/security/tutorial004_an_py310.py hl[118:133] *} + +### Технические подробности о JWT ключе `sub` + +В спецификации JWT говорится, что существует ключ `sub`, содержащий субъект токена. + +Его использование необязательно, но это именно то место, куда вы должны поместить идентификатор пользователя, и поэтому мы здесь его и используем. + +JWT может использоваться и для других целей, помимо идентификации пользователя и предоставления ему возможности выполнять операции непосредственно в вашем API. + +Например, вы могли бы определить "автомобиль" или "запись в блоге". + +Затем вы могли бы добавить права доступа к этой сущности, например "управлять" (для автомобиля) или "редактировать" (для блога). + +Затем вы могли бы передать этот JWT-токен пользователю (или боту), и они использовали бы его для выполнения определенных действий (управление автомобилем или редактирование запись в блоге), даже не имея учетной записи, просто используя JWT-токен, сгенерированный вашим API. + +Используя эти идеи, JWT можно применять для гораздо более сложных сценариев. + +В отдельных случаях несколько сущностей могут иметь один и тот же идентификатор, скажем, `foo` (пользователь `foo`, автомобиль `foo` и запись в блоге `foo`). + +Поэтому, чтобы избежать коллизий идентификаторов, при создании JWT-токена для пользователя можно добавить префикс `username` к значению ключа `sub`. Таким образом, в данном примере значение `sub` было бы `username:johndoe`. + +Важно помнить, что ключ `sub` должен иметь уникальный идентификатор для всего приложения и представлять собой строку. + +## Проверка в действии + +Запустите сервер и перейдите к документации: http://127.0.0.1:8000/docs. + +Вы увидите пользовательский интерфейс вида: + + + +Пройдите авторизацию так же, как делали раньше. + +Используя учетные данные пользователя: + +Username: `johndoe` +Password: `secret` + +/// check | Заметка +Обратите внимание, что нигде в коде не используется открытый текст пароля "`secret`", мы используем только его хэшированную версию. +/// + + + +Вызвав эндпоинт `/users/me/`, вы получите ответ в виде: + +```JSON +{ + "username": "johndoe", + "email": "johndoe@example.com", + "full_name": "John Doe", + "disabled": false +} +``` + + + +Если открыть инструменты разработчика, то можно увидеть, что передаваемые данные включают только токен, пароль передается только в первом запросе для аутентификации пользователя и получения токена доступа, но не в последующих: + + + +/// note | Техническая информация +Обратите внимание на заголовок `Authorization`, значение которого начинается с `Bearer`. +/// + +## Продвинутое использование `scopes` + +В OAuth2 существует понятие "диапазоны" ("`scopes`"). + +С их помощью можно добавить определенный набор разрешений к JWT-токену. + +Затем вы можете передать этот токен непосредственно пользователю или третьей стороне для взаимодействия с вашим API с определенным набором ограничений. + +О том, как их использовать и как они интегрированы в **FastAPI**, читайте далее в **Руководстве пользователя**. + +## Резюме + +С учетом того, что вы видели до сих пор, вы можете создать безопасное приложение **FastAPI**, используя такие стандарты, как OAuth2 и JWT. + +Практически в любом фреймворке работа с безопасностью довольно быстро превращается в сложную тему. + +Многие пакеты, сильно упрощающие эту задачу, вынуждены идти на многочисленные компромиссы с моделью данных, с базой данных и с доступным функционалом. Некоторые из этих пакетов, которые пытаются уж слишком все упростить, имеют даже "дыры" в системе безопасности. + +--- + +**FastAPI** не делает уступок ни одной базе данных, модели данных или инструментарию. + +Он предоставляет вам полную свободу действий, позволяя выбирать то, что лучше всего подходит для вашего проекта. + +Вы можете напрямую использовать многие хорошо поддерживаемые и широко распространенные пакеты, такие как `passlib` и `PyJWT`, поскольку **FastAPI** не требует сложных механизмов для интеграции внешних пакетов. + +Напротив, он предоставляет инструменты, позволяющие максимально упростить этот процесс без ущерба для гибкости, надежности и безопасности. + +При этом вы можете использовать и реализовывать безопасные стандартные протоколы, такие как OAuth2, относительно простым способом. + +В **Руководстве пользователя** вы можете узнать больше о том, как использовать "диапазоны" ("`scopes`") OAuth2 для создания более точно настроенной системы разрешений в соответствии с теми же стандартами. OAuth2 с диапазонами - это механизм, используемый многими крупными провайдерами сервиса аутентификации, такими как Facebook, Google, GitHub, Microsoft, Twitter и др., для авторизации сторонних приложений на взаимодействие с их API от имени их пользователей. diff --git a/docs/ru/docs/tutorial/security/simple-oauth2.md b/docs/ru/docs/tutorial/security/simple-oauth2.md new file mode 100644 index 000000000..9732265cc --- /dev/null +++ b/docs/ru/docs/tutorial/security/simple-oauth2.md @@ -0,0 +1,272 @@ +# Простая авторизация по протоколу OAuth2 с токеном типа Bearer + +Теперь, отталкиваясь от предыдущей главы, добавим недостающие части, чтобы получить безопасную систему. + +## Получение `имени пользователя` и `пароля` + +Для получения `имени пользователя` и `пароля` мы будем использовать утилиты безопасности **FastAPI**. + +Протокол OAuth2 определяет, что при использовании "аутентификации по паролю" (которую мы и используем) клиент/пользователь должен передавать поля `username` и `password` в полях формы. + +В спецификации сказано, что поля должны быть названы именно так. Поэтому `user-name` или `email` работать не будут. + +Но не волнуйтесь, вы можете показать его конечным пользователям во фронтенде в том виде, в котором хотите. + +А ваши модели баз данных могут использовать любые другие имена. + +Но при авторизации согласно спецификации, требуется использовать именно эти имена, что даст нам возможность воспользоваться встроенной системой документации API. + +В спецификации также указано, что `username` и `password` должны передаваться в виде данных формы (так что никакого JSON здесь нет). + +### Oбласть видимости (scope) + +В спецификации также говорится, что клиент может передать еще одно поле формы "`scope`". + +Имя поля формы - `scope` (в единственном числе), но на самом деле это длинная строка, состоящая из отдельных областей видимости (scopes), разделенных пробелами. + +Каждая "область видимости" (scope) - это просто строка (без пробелов). + +Обычно они используются для указания уровней доступа, например: + +* `users:read` или `users:write` являются распространенными примерами. +* `instagram_basic` используется Facebook / Instagram. +* `https://www.googleapis.com/auth/drive` используется компанией Google. + +/// info | Дополнительнаяя информация +В OAuth2 "scope" - это просто строка, которая уточняет уровень доступа. + +Не имеет значения, содержит ли он другие символы, например `:`, или является ли он URL. + +Эти детали зависят от конкретной реализации. + +Для OAuth2 это просто строки. +/// + +## Код получения `имени пользователя` и `пароля` + +Для решения задачи давайте воспользуемся утилитами, предоставляемыми **FastAPI**. + +### `OAuth2PasswordRequestForm` + +Сначала импортируйте `OAuth2PasswordRequestForm` и затем используйте ее как зависимость с `Depends` в *эндпоинте* `/token`: + + +{* ../../docs_src/security/tutorial003_an_py310.py hl[4,78] *} + +`OAuth2PasswordRequestForm` - это класс для использования в качестве зависимости для *функции обрабатывающей эндпоинт*, который определяет тело формы со следующими полями: + +* `username`. +* `password`. +* Необязательное поле `scope` в виде большой строки, состоящей из строк, разделенных пробелами. +* Необязательное поле `grant_type`. + +/// tip | Подсказка +По спецификации OAuth2 поле `grant_type` является обязательным и содержит фиксированное значение `password`, но `OAuth2PasswordRequestForm` не обеспечивает этого. + +Если вам необходимо использовать `grant_type`, воспользуйтесь `OAuth2PasswordRequestFormStrict` вместо `OAuth2PasswordRequestForm`. +/// + +* Необязательное поле `client_id` (в нашем примере он не нужен). +* Необязательное поле `client_secret` (в нашем примере он не нужен). + +/// info | Дополнительная информация +Форма `OAuth2PasswordRequestForm` не является специальным классом для **FastAPI**, как `OAuth2PasswordBearer`. + +`OAuth2PasswordBearer` указывает **FastAPI**, что это схема безопасности. Следовательно, она будет добавлена в OpenAPI. + +Но `OAuth2PasswordRequestForm` - это всего лишь класс зависимости, который вы могли бы написать самостоятельно или вы могли бы объявить параметры `Form` напрямую. + +Но, поскольку это распространённый вариант использования, он предоставляется **FastAPI** напрямую, просто чтобы облегчить задачу. +/// + +### Использование данных формы + +/// tip | Подсказка +В экземпляре зависимого класса `OAuth2PasswordRequestForm` атрибут `scope`, состоящий из одной длинной строки, разделенной пробелами, заменен на атрибут `scopes`, состоящий из списка отдельных строк, каждая из которых соответствует определенному уровню доступа. + +В данном примере мы не используем `scopes`, но если вам это необходимо, то такая функциональность имеется. +/// + +Теперь получим данные о пользователе из (ненастоящей) базы данных, используя `username` из поля формы. + +Если такого пользователя нет, то мы возвращаем ошибку "неверное имя пользователя или пароль". + +Для ошибки мы используем исключение `HTTPException`: + +{* ../../docs_src/security/tutorial003_an_py310.py hl[3,79:81] *} + +### Проверка пароля + +На данный момент у нас есть данные о пользователе из нашей базы данных, но мы еще не проверили пароль. + +Давайте сначала поместим эти данные в модель Pydantic `UserInDB`. + +Ни в коем случае нельзя сохранять пароли в открытом виде, поэтому мы будем использовать (пока что ненастоящую) систему хеширования паролей. + +Если пароли не совпадают, мы возвращаем ту же ошибку. + +#### Хеширование паролей + +"Хеширование" означает: преобразование некоторого содержимого (в данном случае пароля) в последовательность байтов (просто строку), которая выглядит как тарабарщина. + +Каждый раз, когда вы передаете точно такое же содержимое (точно такой же пароль), вы получаете точно такую же тарабарщину. + +Но преобразовать тарабарщину обратно в пароль невозможно. + +##### Зачем использовать хеширование паролей + +Если ваша база данных будет украдена, то у вора не будет паролей пользователей в открытом виде, только хэши. + +Таким образом, вор не сможет использовать эти же пароли в другой системе (поскольку многие пользователи используют одни и те же пароли повсеместно, это было бы опасно). + +{* ../../docs_src/security/tutorial003_an_py310.py hl[82:85] *} + +#### Про `**user_dict` + +`UserInDB(**user_dict)` означает: + +*Передавать ключи и значения `user_dict` непосредственно в качестве аргументов ключ-значение, что эквивалентно:* + +```Python +UserInDB( + username = user_dict["username"], + email = user_dict["email"], + full_name = user_dict["full_name"], + disabled = user_dict["disabled"], + hashed_password = user_dict["hashed_password"], +) +``` + +/// info | Дополнительная информация +Более полное объяснение `**user_dict` можно найти в [документации к **Дополнительным моделям**](../extra-models.md#about-user_indict){.internal-link target=_blank}. +/// + +## Возврат токена + +Ответ эндпоинта `token` должен представлять собой объект в формате JSON. + +Он должен иметь `token_type`. В нашем случае, поскольку мы используем токены типа "Bearer", тип токена должен быть "`bearer`". + +И в нем должна быть строка `access_token`, содержащая наш токен доступа. + +В этом простом примере мы нарушим все правила безопасности, и будем считать, что имя пользователя (username) полностью соответствует токену (token) + +/// tip | Подсказка +В следующей главе мы рассмотрим реальную защищенную реализацию с хешированием паролей и токенами JWT. + +Но пока давайте остановимся на необходимых нам деталях. +/// + +{* ../../docs_src/security/tutorial003_an_py310.py hl[87] *} + +/// tip | Подсказка +Согласно спецификации, вы должны возвращать JSON с `access_token` и `token_type`, как в данном примере. + +Это то, что вы должны сделать сами в своем коде и убедиться, что вы используете эти JSON-ключи. + +Это практически единственное, что нужно не забывать делать самостоятельно, чтобы следовать требованиям спецификации. + +Все остальное за вас сделает **FastAPI**. +/// + +## Обновление зависимостей + +Теперь мы обновим наши зависимости. + +Мы хотим получить значение `current_user` *только* если этот пользователь активен. + +Поэтому мы создаем дополнительную зависимость `get_current_active_user`, которая, в свою очередь, использует в качестве зависимости `get_current_user`. + +Обе эти зависимости просто вернут HTTP-ошибку, если пользователь не существует или неактивен. + +Таким образом, в нашем эндпоинте мы получим пользователя только в том случае, если он существует, правильно аутентифицирован и активен: + +{* ../../docs_src/security/tutorial003_an_py310.py hl[58:66,69:74,94] *} + +/// info | Дополнительная информация +Дополнительный заголовок `WWW-Authenticate` со значением `Bearer`, который мы здесь возвращаем, также является частью спецификации. + +Ответ сервера с HTTP-кодом 401 "UNAUTHORIZED" должен также возвращать заголовок `WWW-Authenticate`. + +В случае с bearer-токенами (наш случай) значение этого заголовка должно быть `Bearer`. + +На самом деле этот дополнительный заголовок можно пропустить и все будет работать. + +Но он приведён здесь для соответствия спецификации. + +Кроме того, могут существовать инструменты, которые ожидают его и могут использовать, и это может быть полезно для вас или ваших пользователей сейчас или в будущем. + +В этом и заключается преимущество стандартов... +/// + +## Посмотим как это работает + +Откроем интерактивную документацию: http://127.0.0.1:8000/docs. + +### Аутентификация + +Нажмите кнопку "Авторизация". + +Используйте учётные данные: + +Пользователь: `johndoe` + +Пароль: `secret` + + + +После авторизации в системе вы увидите следующее: + + + +### Получение собственных пользовательских данных + +Теперь, используя операцию `GET` с путем `/users/me`, вы получите данные пользователя, например: + +```JSON +{ + "username": "johndoe", + "email": "johndoe@example.com", + "full_name": "John Doe", + "disabled": false, + "hashed_password": "fakehashedsecret" +} +``` + + + +Если щелкнуть на значке замка и выйти из системы, а затем попытаться выполнить ту же операцию ещё раз, то будет выдана ошибка HTTP 401: + +```JSON +{ + "detail": "Not authenticated" +} +``` + +### Неактивный пользователь + +Теперь попробуйте пройти аутентификацию с неактивным пользователем: + +Пользователь: `alice` + +Пароль: `secret2` + +И попробуйте использовать операцию `GET` с путем `/users/me`. + +Вы получите ошибку "Inactive user", как тут: + +```JSON +{ + "detail": "Inactive user" +} +``` + +## Резюме + +Теперь у вас есть инструменты для реализации полноценной системы безопасности на основе `имени пользователя` и `пароля` для вашего API. + +Используя эти средства, можно сделать систему безопасности совместимой с любой базой данных, с любым пользователем или моделью данных. + + Единственным недостатком нашей системы является то, что она всё ещё не защищена. + +В следующей главе вы увидите, как использовать библиотеку безопасного хеширования паролей и токены JWT. diff --git a/docs/ru/docs/tutorial/sql-databases.md b/docs/ru/docs/tutorial/sql-databases.md new file mode 100644 index 000000000..b127e44d5 --- /dev/null +++ b/docs/ru/docs/tutorial/sql-databases.md @@ -0,0 +1,358 @@ +# SQL (реляционные) базы данных + +**FastAPI** не требует использования реляционной базы данных. Вы можете воспользоваться любой базой данных, которой хотите. + +В этом разделе мы продемонстрируем, как работать с SQLModel. + +Библиотека **SQLModel** построена на основе SQLAlchemy и Pydantic. Она была разработана автором **FastAPI** специально для приложений на основе FastAPI, которые используют **реляционные базы данных**. + +/// tip | Подсказка + +Вы можете воспользоваться любой библиотекой для работы с реляционными (SQL) или нереляционными (NoSQL) базами данных. (Их ещё называют **ORM** библиотеками). FastAPI не принуждает вас к использованию чего-либо конкретного. 😎 + +/// + +В основе SQLModel лежит SQLAlchemy, поэтому вы спокойно можете использовать любую базу данных, поддерживаемую SQLAlchemy (и, соответственно, поддерживаемую SQLModel), например: + +* PostgreSQL +* MySQL +* SQLite +* Oracle +* Microsoft SQL Server, и т.д. + +В данном примере мы будем использовать базу данных **SQLite**, т.к. она состоит из единственного файла и поддерживается встроенными библиотеками Python. Таким образом, вы сможете скопировать данный пример и запустить его как он есть. + +В дальнейшем, для продакшн-версии вашего приложения, возможно, вам стоит использовать серверную базу данных, например, **PostgreSQL**. + +/// tip | Подсказка + +Существует официальный генератор проектов на **FastAPI** и **PostgreSQL**, который также включает frontend и дополнительные инструменты https://github.com/fastapi/full-stack-fastapi-template + +/// + +Это очень простое и короткое руководство, поэтому, если вы хотите узнать о базах данных в целом, об SQL, разобраться с более продвинутым функционалом, то воспользуйтесь документацией SQLModel. + +## Установка `SQLModel` + +Создайте виртуальное окружение [virtual environment](../virtual-environments.md){.internal-link target=_blank}, активируйте его и установите `sqlmodel`: + +
+ +```console +$ pip install sqlmodel +---> 100% +``` + +
+ +## Создание приложения с единственной моделью + +Мы начнем с создания наиболее простой первой версии нашего приложения с одной единственной моделью **SQLModel**. + +В дальнейшем с помощью **дополнительных моделей** мы его улучшим и сделаем более безопасным и универсальным. 🤓 + +### Создание моделей + +Импортируйте `SQLModel` и создайте модель базы данных: + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[1:11] hl[7:11] *} + +Класс `Hero` очень напоминает модель Pydantic (фактически, под капотом, *это и есть модель Pydantic*). + +Но есть и некоторые различия + +* `table=True` для SQLModel означает, что это *модель-таблица*, которая должна представлять **таблицу** в реляционной базе данных. Это не просто *модель данных* (в отличие от обычного класса в Pydantic). + +* `Field(primary_key=True)` для SQLModel означает, что поле `id` является первичным ключом в таблице базы данных (вы можете подробнее узнать о первичных ключах баз данных в документации по SQLModel). + + Тип `int | None` сигнализирует для SQLModel, что столбец таблицы базы данных должен иметь тип `INTEGER`, или иметь пустое значение `NULL`. + +* `Field(index=True)` для SQLModel означает, что нужно создать **SQL индекс** для данного столбца. Это обеспечит более быстрый поиск при чтении данных, отфильтрованных по данному столбцу. + + SQLModel будет знать, что данные типа `str`, будут представлены в базе данных как `TEXT` (или `VARCHAR`, в зависимости от типа базы данных). + +### Создание соединения с базой данных (Engine) + +В SQLModel объект соединения `engine` (по сути это `Engine` из SQLAlchemy) **содержит пул соединений** к базе данных. + +Для обеспечения всех подключений приложения к одной базе данных нужен только один объект соединения `engine`. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[14:18] hl[14:15,17:18] *} + +Использование настройки `check_same_thread=False` позволяет FastAPI использовать одну и ту же SQLite базу данных в различных потоках (threads). Это необходимо, когда **один запрос** использует **более одного потока** (например, в зависимостях). + +Не беспокойтесь, учитывая структуру кода, мы позже позаботимся о том, чтобы использовать **отдельную SQLModel-сессию на каждый отдельный запрос**, это как раз то, что пытается обеспечить `check_same_thread`. + +### Создание таблиц + +Далее мы добавляем функцию, использующую `SQLModel.metadata.create_all(engine)`, для того, чтобы создать **таблицы** для каждой из **моделей таблицы**. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[21:22] hl[21:22] *} + +### Создание зависимости Session + +Сессия базы данных (**`Session`**) хранит **объекты в памяти** и отслеживает любые необходимые изменения в данных, а затем **использует `engine`** для коммуникации с базой данных. + +Мы создадим FastAPI-**зависимость** с помощью `yield`, которая будет создавать новую сессию (Session) для каждого запроса. Это как раз и обеспечит использование отдельной сессии на каждый отдельный запрос. 🤓 + +Затем мы создадим объявленную (`Annotated`) зависимость `SessionDep`. Мы сделаем это для того, чтобы упростить остальной код, который будет использовать эту зависимость. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[25:30] hl[25:27,30] *} + +### Создание таблиц базы данных при запуске приложения + +Мы будем создавать таблицы базы данных при запуске приложения. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[32:37] hl[35:37] *} + +В данном примере мы создаем таблицы при наступлении события запуска приложения. + +В продуктовом приложении вы, скорее всего, будете использовать скрипт для миграции базы данных, который выполняется перед запуском приложения. 🤓 + +/// tip | Подсказка + +В SQLModel будут включены утилиты миграции, входящие в состав Alembic, но на данный момент вы просто можете использовать +Alembic напрямую. + +/// + +### Создание героя (Hero) + +Каждая модель в SQLModel является также моделью Pydantic, поэтому вы можете использовать её при **объявлении типов**, точно также, как и модели Pydantic. + +Например, при объявлении параметра типа `Hero`, она будет считана из **тела JSON**. + +Точно также, вы можете использовать её при объявлении типа значения, возвращаемого функцией, и тогда структурированные данные будут отображены через пользовательский интерфейс автоматически сгенерированной документации FastAPI. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[40:45] hl[40:45] *} + +Мы используем зависимость `SessionDep` (сессию базы данных) для того, чтобы добавить нового героя `Hero` в объект сессии (`Session`), сохранить изменения в базе данных, обновить данные героя и затем вернуть их. + +### Чтение данных о героях + +Мы можем **читать** данные героев из базы данных с помощью `select()`. Мы можем включить `limit` и `offset` для постраничного считывания результатов. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[48:55] hl[51:52,54] *} + +### Чтение данных отдельного героя + +Мы можем прочитать данные отдельного героя (`Hero`). + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[58:63] hl[60] *} + +### Удаление данных героя + +Мы также можем удалить героя `Hero` из базы данных. + +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[66:73] hl[71] *} + +### Запуск приложения + +Вы можете запустить приложение следующим образом: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Далее перейдите в пользовательский интерфейс API `/docs`. Вы увидите, что **FastAPI** использует модели для создания документации API. Эти же модели используются для сериализации и проверки данных. + +
+ +
+ +## Добавление в приложение дополнительных (вспомогательных) моделей + +Теперь давайте проведём **рефакторинг** нашего приложения, чтобы сделать его более безопасным и более универсальным. + +Обратите внимание, что на данном этапе наше приложение позволяет на уровне клиента определять `id` создаваемого героя (`Hero`). 😱 + +Мы не можем этого допустить, т.к. существует риск переписать уже присвоенные `id` в базе данных. Присвоение `id` должно происходить **на уровне бэкэнда (backend)** или **на уровне базы данных**, но никак **не на уровне клиента**. + +Кроме того, мы создаем секретное имя `secret_name` для героя, но пока что, мы возвращаем его повсеместно, и это слабо напоминает **секретность**... 😅 + +Мы поправим это с помощью нескольких дополнительных (вспомогательных) моделей. Вот где SQLModel по-настоящему покажет себя. ✨ + +### Создание дополнительных моделей + +В **SQLModel**, любая модель с параметром `table=True` является **моделью таблицы**. + +Любая модель, не содержащая `table=True` является **моделью данных**, это по сути обычные модели Pydantic (с несколько расширенным функционалом). 🤓 + +С помощью SQLModel мы можем использовать **наследование**, что поможет нам **избежать дублирования** всех полей. + +#### Базовый класс `HeroBase` + +Давайте начнём с модели `HeroBase`, которая содержит поля, общие для всех моделей: + +* `name` +* `age` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:9] hl[7:9] *} + +#### Модель таблицы `Hero` + +Далее давайте создадим **модель таблицы** `Hero` с дополнительными полями, которых может не быть в других моделях: + +* `id` +* `secret_name` + +Модель `Hero` наследует от `HeroBase`, и поэтому включает также поля из `HeroBase`. Таким образом, все поля, содержащиеся в `Hero`, будут следующими: + +* `id` +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:14] hl[12:14] *} + +#### Публичная модель данных `HeroPublic` + +Далее мы создадим модель `HeroPublic`. Мы будем возвращать её клиентам API. + +Она включает в себя те же поля, что и `HeroBase`, и, соответственно, поле `secret_name` в ней отсутствует. + +Наконец-то личность наших героев защищена! 🥷 + +В модели `HeroPublic` также объявляется поле `id: int`. Мы как бы заключаем договоренность с API клиентом, на то, что передаваемые данные всегда должны содержать поле `id`, и это поле должно содержать целое число (и никогда не содержать `None`). + +/// tip | Подсказка + +Модель ответа, гарантирующая наличие поля со значением типа `int` (не `None`), очень полезна при разработке API клиентов. Определенность в передаваемых данных может обеспечить написание более простого кода. + +Также **автоматически генерируемые клиенты** будут иметь более простой интерфейс. И в результате жизнь разработчиков, использующих ваш API, станет значительно легче. 😎 + +/// + +`HeroPublic` содержит все поля `HeroBase`, а также поле `id`, объявленное как `int` (не `None`): + +* `id` +* `name` +* `age` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:18] hl[17:18] *} + +#### Модель для создания героя `HeroCreate` + +Сейчас мы создадим модель `HeroCreate`. Эта модель будет использоваться для проверки данных, переданных клиентом. + +Она содержит те же поля, что и `HeroBase`, а также поле `secret_name`. + +Теперь, при создании нового героя, клиенты будут передавать секретное имя `secret_name`, которое будет сохранено в базе данных, но не будет возвращено в ответе API клиентам. + +/// tip | Подсказка + +Вот как нужно работать с **паролями**: получайте их, но не возвращайте их через API. + +Также хэшируйте значения паролей перед тем, как их сохранить. Ни в коем случае не храните пароли в открытом виде, как обычный текст. + +/// + +Поля модели `HeroCreate`: + +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:22] hl[21:22] *} + +#### Модель для обновления данных героя `HeroUpdate` + +В предыдущих версиях нашей программы мы не могли обновить данные героя, теперь, воспользовавшись дополнительными моделями, мы сможем это сделать. 🎉 + +Модель данных `HeroUpdate` в некотором смысле особенная. Она содержит все те же поля, что и модель создания героя, но все поля модели являются **необязательными**. (Все они имеют значение по умолчанию.) Таким образом, при обновлении данных героя, вам достаточно передать только те поля, которые требуют изменения. + +Поскольку **все поля по сути меняются** (теперь тип каждого поля допускает значение `None` и значение по умолчанию `None`), мы должны их **объявить заново**. + +Фактически, нам не нужно наследоваться от `HeroBase`, потому что мы будем заново объявлять все поля. Я оставлю наследование просто для поддержания общего стиля, но оно (наследование) здесь необязательно. 🤷 + +Поля `HeroUpdate`: + +* `name` +* `age` +* `secret_name` + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:28] hl[25:28] *} + +### Создание героя с помощью `HeroCreate` и возвращение результатов с помощью `HeroPublic` + +Теперь, когда у нас есть дополнительные модели, мы можем обновить те части приложения, которые их используют. + +Вместе c запросом на создание героя мы получаем объект данных `HeroCreate`, и создаем на его основе объект модели таблицы `Hero`. + +Созданный объект *модели таблицы* `Hero` будет иметь все поля, переданные клиентом, а также поле `id`, сгенерированное базой данных. + +Далее функция вернёт объект *модели таблицы* `Hero`. Но поскольку, мы объявили `HeroPublic` как модель ответа, то **FastAPI** будет использовать именно её для проверки и сериализации данных. + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[56:62] hl[56:58] *} + +/// tip | Подсказка + +Теперь мы используем модель ответа `response_model=HeroPublic`, вместо того, чтобы объявить тип возвращаемого значения как `-> HeroPublic`. Мы это делаем потому, что тип возвращаемого значения не относится к `HeroPublic`. + +Если бы мы объявили тип возвращаемого значения как `-> HeroPublic`, то редактор и линтер начали бы ругаться (и вполне справедливо), что возвращаемое значение принадлежит типу `Hero`, а совсем не `HeroPublic`. + +Объявляя модель ответа в `response_model`, мы как бы говорим **FastAPI**: делай свое дело, не вмешиваясь в аннотацию типов и не полагаясь на помощь редактора или других инструментов. + +/// + +### Чтение данных героев с помощью `HeroPublic` + +Мы можем проделать то же самое **для чтения данных** героев. Мы применим модель ответа `response_model=list[HeroPublic]`, и тем самым обеспечим правильную проверку и сериализацию данных. + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[65:72] hl[65] *} + +### Чтение данных отдельного героя с помощью `HeroPublic` + +Мы можем **прочитать** данные отдельного героя: + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[75:80] hl[77] *} + +### Обновление данных героя с помощью `HeroUpdate` + +Мы можем **обновить данные героя**. Для этого мы воспользуемся HTTP методом `PATCH`. + +В коде мы получаем объект словаря `dict` с данными, переданными клиентом (т.е. **только c данными, переданными клиентом**, исключая любые значения, которые могли бы быть там только потому, что они являются значениями по умолчанию). Для того чтобы сделать это, мы воспользуемся опцией `exclude_unset=True`. В этом главная хитрость. 🪄 + +Затем мы применим `hero_db.sqlmodel_update(hero_data)`, и обновим `hero_db`, использовав данные `hero_data`. + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[83:93] hl[83:84,88:89] *} + +### Удалим героя ещё раз + +Операция **удаления** героя практически не меняется. + +В данном случае желание *`отрефакторить всё`* остаётся неудовлетворенным. 😅 + +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[96:103] hl[101] *} + +### Снова запустим приложение + +Вы можете снова запустить приложение: + +
+ +```console +$ fastapi dev main.py + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Если вы перейдете в пользовательский интерфейс API `/docs`, то вы увидите, что он был обновлен, и больше не принимает параметра `id` от клиента при создании нового героя, и т.д. + +
+ +
+ +## Резюме + +Вы можете использовать **SQLModel** для взаимодействия с реляционными базами данных, а также для упрощения работы с **моделями данных** и **моделями таблиц**. + +Вы можете узнать гораздо больше информации в документации по **SQLModel**. Там вы найдете более подробное мини-руководство по использованию SQLModel с **FastAPI**. 🚀 diff --git a/docs/ru/docs/tutorial/static-files.md b/docs/ru/docs/tutorial/static-files.md index ec09eb5a3..c06eb858b 100644 --- a/docs/ru/docs/tutorial/static-files.md +++ b/docs/ru/docs/tutorial/static-files.md @@ -7,14 +7,15 @@ * Импортируйте `StaticFiles`. * "Примонтируйте" экземпляр `StaticFiles()` с указанием определенной директории. -```Python hl_lines="2 6" -{!../../../docs_src/static_files/tutorial001.py!} -``` +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} -!!! заметка "Технические детали" - Вы также можете использовать `from starlette.staticfiles import StaticFiles`. +/// note | Технические детали - **FastAPI** предоставляет `starlette.staticfiles` под псевдонимом `fastapi.staticfiles`, просто для вашего удобства, как разработчика. Но на самом деле это берётся напрямую из библиотеки Starlette. +Вы также можете использовать `from starlette.staticfiles import StaticFiles`. + +**FastAPI** предоставляет `starlette.staticfiles` под псевдонимом `fastapi.staticfiles`, просто для вашего удобства, как разработчика. Но на самом деле это берётся напрямую из библиотеки Starlette. + +/// ### Что такое "Монтирование" diff --git a/docs/ru/docs/tutorial/testing.md b/docs/ru/docs/tutorial/testing.md index ca47a6f51..2c0f93d48 100644 --- a/docs/ru/docs/tutorial/testing.md +++ b/docs/ru/docs/tutorial/testing.md @@ -8,10 +8,13 @@ ## Использование класса `TestClient` -!!! info "Информация" - Для использования класса `TestClient` необходимо установить библиотеку `httpx`. +/// info | Информация - Например, так: `pip install httpx`. +Для использования класса `TestClient` необходимо установить библиотеку `httpx`. + +Например, так: `pip install httpx`. + +/// Импортируйте `TestClient`. @@ -23,24 +26,31 @@ Напишите простое утверждение с `assert` дабы проверить истинность Python-выражения (это тоже стандарт `pytest`). -```Python hl_lines="2 12 15-18" -{!../../../docs_src/app_testing/tutorial001.py!} -``` +{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *} + +/// tip | Подсказка + +Обратите внимание, что тестирующая функция является обычной `def`, а не асинхронной `async def`. -!!! tip "Подсказка" - Обратите внимание, что тестирующая функция является обычной `def`, а не асинхронной `async def`. +И вызов клиента также осуществляется без `await`. - И вызов клиента также осуществляется без `await`. +Это позволяет вам использовать `pytest` без лишних усложнений. - Это позволяет вам использовать `pytest` без лишних усложнений. +/// -!!! note "Технические детали" - Также можно написать `from starlette.testclient import TestClient`. +/// note | Технические детали - **FastAPI** предоставляет тот же самый `starlette.testclient` как `fastapi.testclient`. Это всего лишь небольшое удобство для Вас, как разработчика. +Также можно написать `from starlette.testclient import TestClient`. -!!! tip "Подсказка" - Если для тестирования Вам, помимо запросов к приложению FastAPI, необходимо вызывать асинхронные функции (например, для подключения к базе данных с помощью асинхронного драйвера), то ознакомьтесь со страницей [Асинхронное тестирование](../advanced/async-tests.md){.internal-link target=_blank} в расширенном руководстве. +**FastAPI** предоставляет тот же самый `starlette.testclient` как `fastapi.testclient`. Это всего лишь небольшое удобство для Вас, как разработчика. + +/// + +/// tip | Подсказка + +Если для тестирования Вам, помимо запросов к приложению FastAPI, необходимо вызывать асинхронные функции (например, для подключения к базе данных с помощью асинхронного драйвера), то ознакомьтесь со страницей [Асинхронное тестирование](../advanced/async-tests.md){.internal-link target=_blank} в расширенном руководстве. + +/// ## Разделение тестов и приложения @@ -50,7 +60,7 @@ ### Файл приложения **FastAPI** -Допустим, структура файлов Вашего приложения похожа на ту, что описана на странице [Более крупные приложения](./bigger-applications.md){.internal-link target=_blank}: +Допустим, структура файлов Вашего приложения похожа на ту, что описана на странице [Более крупные приложения](bigger-applications.md){.internal-link target=_blank}: ``` . @@ -62,9 +72,7 @@ Здесь файл `main.py` является "точкой входа" в Ваше приложение и содержит инициализацию Вашего приложения **FastAPI**: -```Python -{!../../../docs_src/app_testing/main.py!} -``` +{* ../../docs_src/app_testing/main.py *} ### Файл тестов @@ -80,9 +88,8 @@ Так как оба файла находятся в одной директории, для импорта объекта приложения из файла `main` в файл `test_main` Вы можете использовать относительный импорт: -```Python hl_lines="3" -{!../../../docs_src/app_testing/test_main.py!} -``` +{* ../../docs_src/app_testing/test_main.py hl[3] *} + ...и писать дальше тесты, как и раньше. @@ -110,50 +117,65 @@ Обе *операции пути* требуют наличия в запросе заголовка `X-Token`. -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python - {!> ../../../docs_src/app_testing/app_b_an_py310/main.py!} - ``` +```Python +{!> ../../docs_src/app_testing/app_b_an_py310/main.py!} +``` -=== "Python 3.9+" +//// - ```Python - {!> ../../../docs_src/app_testing/app_b_an_py39/main.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python +{!> ../../docs_src/app_testing/app_b_an_py39/main.py!} +``` - ```Python - {!> ../../../docs_src/app_testing/app_b_an/main.py!} - ``` +//// -=== "Python 3.10+ без Annotated" +//// tab | Python 3.8+ - !!! tip "Подсказка" - По возможности используйте версию с `Annotated`. +```Python +{!> ../../docs_src/app_testing/app_b_an/main.py!} +``` - ```Python - {!> ../../../docs_src/app_testing/app_b_py310/main.py!} - ``` +//// -=== "Python 3.8+ без Annotated" +//// tab | Python 3.10+ без Annotated - !!! tip "Подсказка" - По возможности используйте версию с `Annotated`. +/// tip | Подсказка - ```Python - {!> ../../../docs_src/app_testing/app_b/main.py!} - ``` +По возможности используйте версию с `Annotated`. -### Расширенный файл тестов +/// -Теперь обновим файл `test_main.py`, добавив в него тестов: +```Python +{!> ../../docs_src/app_testing/app_b_py310/main.py!} +``` + +//// + +//// tab | Python 3.8+ без Annotated + +/// tip | Подсказка + +По возможности используйте версию с `Annotated`. + +/// ```Python -{!> ../../../docs_src/app_testing/app_b/test_main.py!} +{!> ../../docs_src/app_testing/app_b/main.py!} ``` +//// + +### Расширенный файл тестов + +Теперь обновим файл `test_main.py`, добавив в него тестов: + +{* ../../docs_src/app_testing/app_b/test_main.py *} + + Если Вы не знаете, как передать информацию в запросе, можете воспользоваться поисковиком (погуглить) и задать вопрос: "Как передать информацию в запросе с помощью `httpx`", можно даже спросить: "Как передать информацию в запросе с помощью `requests`", поскольку дизайн HTTPX основан на дизайне Requests. Затем Вы просто применяете найденные ответы в тестах. @@ -168,10 +190,13 @@ Для получения дополнительной информации о передаче данных на бэкенд с помощью `httpx` или `TestClient` ознакомьтесь с документацией HTTPX. -!!! info "Информация" - Обратите внимание, что `TestClient` принимает данные, которые можно конвертировать в JSON, но не модели Pydantic. +/// info | Информация + +Обратите внимание, что `TestClient` принимает данные, которые можно конвертировать в JSON, но не модели Pydantic. + +Если в Ваших тестах есть модели Pydantic и Вы хотите отправить их в тестируемое приложение, то можете использовать функцию `jsonable_encoder`, описанную на странице [Кодировщик совместимый с JSON](encoder.md){.internal-link target=_blank}. - Если в Ваших тестах есть модели Pydantic и Вы хотите отправить их в тестируемое приложение, то можете использовать функцию `jsonable_encoder`, описанную на странице [Кодировщик совместимый с JSON](encoder.md){.internal-link target=_blank}. +/// ## Запуск тестов diff --git a/docs/ru/docs/virtual-environments.md b/docs/ru/docs/virtual-environments.md new file mode 100644 index 000000000..777adaf22 --- /dev/null +++ b/docs/ru/docs/virtual-environments.md @@ -0,0 +1,839 @@ +# Виртуальная среда + +При работе с проектами в Python рекомендуется использовать **виртуальную среду разработки** (или какой-нибудь другой подобный механизм). Это нужно для того, чтобы изолировать устанавливаемые пакеты для каждого отдельного проекта. + +/// info | Дополнительная информация + +Если вы уже знакомы с виртуальными средами разработки, знаете как их создавать и использовать, то вы можете свободно пропустить данный раздел. 🤓 + +/// + +/// tip | Подсказка + +**Виртуальная среда** и **переменная окружения** это две разные вещи. + +**Переменная окружения** это системная переменная, которую могут использовать программы. + +**Виртуальная среда** это папка, содержащая файлы. + +/// + +/// info | Дополнительная информация + +В этом разделе мы научим вас пользоваться виртуальными средами разработки и расскажем, как они работают. + +Если же вы готовы воспользоваться инструментом, **который умеет управлять всем, что касается Python-проектов**, +(включая установку Python), то попробуйте uv. + +/// + +## Создание проекта + +В первую очередь, создайте директорию для вашего проекта. + +Я обычно создаю папку под названием `code` внутри моего домашнего каталога `/home/user`. + +Затем внутри данной папки я создаю отдельную директорию под каждый свой проект. + +
+ +```console +// Перейдите в домашний каталог +$ cd +// Создайте отдельную папку под все будущие программные проекты (code) +$ mkdir code +// Войдите в директорию code +$ cd code +// Создайте директрорию под данный проект (awesome-project) +$ mkdir awesome-project +// Перейдите в созданную директорию проекта +$ cd awesome-project +``` + +
+ +## Создание виртуальной среды разработки + +Начиная работу с Python-проектом, сразу же создавайте виртуальную среду разработки +**внутри вашего проекта**. + +/// tip | Подсказка + +Виртуальная среда разработки создается один раз, и в дальнейшем, работая с проектом, этого больше делать не придется. + +/// + +//// tab | `venv` + +Для создания виртуальной среды вы можете воспользоваться модулем `venv`, который является частью встроенной библиотеки Python. + +
+ +```console +$ python -m venv .venv +``` + +
+ +/// details | Что делает эта команда? + +* `python`: использовать программу под именем `python` +* `-m`: вызывать модуль как скрипт, в следующей инструкции мы скажем какой именно модуль вызвать +* `venv`: использовать модуль под названием `venv`, который обычно устанавливается вместе с Python +* `.venv`: создать виртуальную среду разработки в новой директории `.venv` + +/// + +//// + +//// tab | `uv` + +Если вы установили `uv`, то вы можете им воспользоваться для создания виртуальной среды разработки. + +
+ +```console +$ uv venv +``` + +
+ +/// tip | Подсказка + +По умолчанию `uv` создаст виртуальную среду разработки в папке под названием `.venv`. + +Но вы можете это изменить, передав дополнительный аргумент с именем директории. + +/// + +//// + +Данная команда создаст новую виртуальную среду разработки в папке `.venv`. + +/// details | `.venv` или другое имя? + +Вы можете поместить виртуальную среду разработки в папку с другим именем, но традиционным (конвенциональным) названием является `.venv` . + +/// + +## Активация виртуальной среды разработки + +Активируйте виртуальную среду разработки, и тогда любая запускаемая Python-команда или устанавливаемый пакет будут ее использовать. + +/// tip | Подсказка + +При работе над проектом делайте это **каждый раз** при запуске **новой сессии в терминале**. + +/// + +//// tab | Linux, macOS + +
+ +```console +$ source .venv/bin/activate +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ .venv\Scripts\Activate.ps1 +``` + +
+ +//// + +//// tab | Windows Bash + +Или при использовании Bash для Windows (напр. Git Bash): + +
+ +```console +$ source .venv/Scripts/activate +``` + +
+ +//// + +## Проверка активации виртуальной среды + +Проверьте, активна ли виртуальная среда (удостоверимся, что предыдущая команда сработала). + +/// tip | Подсказка + +Убедитесь в том, что все работает так, как нужно и вы используете именно ту виртуальную среду разработки, которую нужно. Делать это необязательно, но желательно. + +/// + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
+ +Если данная команда показывает, что исполняемый файл `python` (`.venv\bin\python`), находится внутри виртуальной среды вашего проекта (у нас это `awesome-project`), значит все отработало как нужно. 🎉 + +//// + +//// tab | Windows PowerShell + +
+ +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
+ +Если данная команда показывает, что исполняемый файл `python` (`.venv\Scripts\python`), находится внутри виртуальной среды вашего проекта (у нас это `awesome-project`), значит все отработало как нужно. 🎉 + +//// + +## Обновление `pip` + +/// tip | Подсказка + +Если вы используете `uv`, то вы должны будете его использовать для установки пакетов вместо `pip`, поэтому обновлять `pip` вам ненужно. 😎 + +/// + +Если для установки пакетов вы используете `pip` (он устанавливается по умолчанию вместе с Python), то обновите `pip` до последней версии. + +Большинство экзотических ошибок, возникающих при установке пакетов, устраняется предварительным обновлением `pip`. + +/// tip | Подсказка + +Обычно это делается только один раз, сразу после создания виртуальной среды разработки. + +/// + +Убедитесь в том, что виртуальная среда активирована (с помощью вышеуказанной команды) и запустите следующую команду: + +
+ +```console +$ python -m pip install --upgrade pip + +---> 100% +``` + +
+ +## Добавление `.gitignore` + +Если вы используете **Git** (а вы должны его использовать), то добавьте файл `.gitignore` и исключите из Git всё, что находится в папке `.venv`. + +/// tip | Подсказка + +Если для создания виртуальной среды вы используете `uv`, то для вас все уже сделано и вы можете пропустить этот шаг. 😎 + +/// + +/// tip | Подсказка + +Это делается один раз, сразу после создания виртуальной среды разработки. + +/// + +
+ +```console +$ echo "*" > .venv/.gitignore +``` + +
+ +/// details | Что делает эта команда? + +* `echo "*"`: напечатать `*` в консоли (следующий шаг это слегка изменит) +* `>`: все что находится слева от `>` не печатать в консоль, но записать в файл находящийся справа от `>` +* `.gitignore`: имя файла, в который нужно записать текст. + +`*` в Git означает "всё". Т.е. будет проигнорировано всё, что содержится в папке `.venv`. + +Данная команда создаст файл `.gitignore` следующего содержания: + +```gitignore +* +``` + +/// + +## Установка пакетов + +После установки виртуальной среды, вы можете устанавливать в нее пакеты. + +/// tip | Подсказка + +Сделайте это **один раз**, при установке или обновлении пакетов, нужных вашему проекту. + +Если вам понадобится обновить версию пакета или добавить новый пакет, то вы должны будете **сделать это снова**. + +/// + +### Установка пакетов напрямую + +Если вы торопитесь и не хотите объявлять зависимости проекта в отдельном файле, то вы можете установить их напрямую. + +/// tip | Подсказка + +Объявление пакетов, которые использует ваш проект, и их версий в отдельном файле (например, в `requirements.txt` или в `pyproject.toml`) - это отличная идея. + +/// + +//// tab | `pip` + +
+ +```console +$ pip install "fastapi[standard]" + +---> 100% +``` + +
+ +//// + +//// tab | `uv` + +Если вы используете `uv`: + +
+ +```console +$ uv pip install "fastapi[standard]" +---> 100% +``` + +
+ +//// + +### Установка из `requirements.txt` + +Если у вас есть `requirements.txt`, то вы можете использовать его для установки пакетов. + +//// tab | `pip` + +
+ +```console +$ pip install -r requirements.txt +---> 100% +``` + +
+ +//// + +//// tab | `uv` + +Если вы используете `uv`: + +
+ +```console +$ uv pip install -r requirements.txt +---> 100% +``` + +
+ +//// + +/// details | `requirements.txt` + +`requirements.txt` с парочкой пакетов внутри выглядит приблизительно так: + +```requirements.txt +fastapi[standard]==0.113.0 +pydantic==2.8.0 +``` + +/// + +## Запуск программы + +После активации виртуальной среды разработки вы можете запустить свою программу и она будет использовать версию Python и пакеты, установленные в виртуальной среде. + +
+ +```console +$ python main.py + +Hello World +``` + +
+ +## Настройка редактора + +Вероятно, вы захотите воспользоваться редактором. Убедитесь, что вы настроили его на использование той самой виртуальной среды, которую вы создали. (Скорее всего, она автоматически будет обнаружена). Это позволит вам использовать авто-завершение и выделение ошибок в редакторе. + +Например: + +* VS Code +* PyCharm + +/// tip | Подсказка + +Обычно это делается один раз, при создании виртуальной среды разработки. + +/// + +## Деактивация виртуальной среды разработки + +По окончании работы над проектом вы можете деактивировать виртуальную среду. + +
+ +```console +$ deactivate +``` + +
+ +Таким образом, при запуске `python`, будет использована версия `python` установленная глобально, а не из этой виртуальной среды вместе с установленными в ней пакетами. + +## Все готово к работе + +Теперь вы готовы к тому, чтобы начать работу над своим проектом. + + + +/// tip | Подсказка + +Хотите разобраться со всем, что написано выше? + +Продолжайте читать. 👇🤓 + +/// + +## Зачем использовать виртуальную среду? + +Для работы с FastAPI вам потребуется установить Python. + +После этого вам нужно будет **установить** FastAPI и другие **пакеты**, которые вы собираетесь использовать. + +Для установки пакетов обычно используют `pip`, который устанавливается вместе с Python (или же используют альтернативные решения). + +Тем не менее, если вы просто используете `pip` напрямую, то пакеты будут установлены в **глобальное Python-окружение** (глобально установленный Python). + +### Проблема + +Так в чем же проблема с установкой пакетов в глобальную среду Python? + +В какой-то момент вам, вероятно, придется писать множество разных программ, которые используют различные пакеты. 😱 + +Например, вы создаете проект `philosophers-stone`, который зависит от пакета под названием **`harry`, версии `1`**. Таким образом, вам нужно установить `harry`. + +```mermaid +flowchart LR + stone(philosophers-stone) -->|requires| harry-1[harry v1] +``` + +Затем, в какой-то момент, вы создаете другой проект под названием `prisoner-of-azkaban`, и этот проект тоже зависит от `harry`, но он уже использует **`harry` версии `3`**. + +```mermaid +flowchart LR + azkaban(prisoner-of-azkaban) --> |requires| harry-3[harry v3] +``` + +Проблема заключается в том, что при установке в глобальное окружение, а не в локальную виртуальную среду разработки, вам нужно будет выбирать, какую версию пакета `harry` устанавливать. + +Если вам нужен `philosophers-stone`, то вам нужно сначала установить `harry` версии `1`: + +
+ +```console +$ pip install "harry==1" +``` + +
+ +И тогда в вашем глобальном окружении Python будет установлен `harry` версии `1`: + +```mermaid +flowchart LR + subgraph global[global env] + harry-1[harry v1] + end + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) -->|requires| harry-1 + end +``` + +Но если позднее вы захотите запустить `prisoner-of-azkaban`, то вам нужно будет удалить `harry` версии 1, и установить `harry` версии `3` (при установке пакета версии `3` поверх пакета версии `1`, пакет версии `1` удаляется автоматически). + +
+ +```console +$ pip install "harry==3" +``` + +
+ +И тогда, в вашей глобальной среде окружения Python, будет установлен пакет `harry` версии `3`. + +И когда вы снова попытаетесь запустить `philosophers-stone`, то существует вероятность того, что он не будет работать, так как он использует `harry` версии `1`. + +```mermaid +flowchart LR + subgraph global[global env] + harry-1[harry v1] + style harry-1 fill:#ccc,stroke-dasharray: 5 5 + harry-3[harry v3] + end + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) -.-x|⛔️| harry-1 + end + subgraph azkaban-project[prisoner-of-azkaban project] + azkaban(prisoner-of-azkaban) --> |requires| harry-3 + end +``` + +/// tip | Подсказка + +В пакетах Python очень часто стараются изо всех сил избегать внесения критических изменений в новые версии, но лучше перестраховаться и планово устанавливать новые версии, а затем запускать тесты, чтобы проверить, все ли работает правильно. + +/// + +Теперь представьте, что это происходит со многими другими пакетами, которые используются в ваших проектах. С этим очень сложно справиться. И скорее всего, в конечном итоге вы будете запускать некоторые проекты с некоторыми несовместимыми зависимостями и не будете знать, почему что-то не работает. + +Кроме того, в зависимости от вашей операционной системы (напр. Linux, Windows, macOS), она может поставляться с уже установленным Python. Вероятно, что в этом случае в ней уже установлены системные пакеты определенных версий. Если вы устанавливаете пакеты глобально, то вы можете **поломать** программы, являющиеся частью ОС. + +## Куда устанавливаются пакеты? + +Когда вы устанавливаете Python, то на вашей машине создается некоторое количество директорий, содержащих некоторое количество файлов. + +Среди них есть каталоги, отвечающие за хранение всех устанавливаемых вами пакетов. + +Когда вы запустите команду: + +
+ +```console +// Не запускайте эту команду, это просто пример 🤓 +$ pip install "fastapi[standard]" +---> 100% +``` + +
+ +То будет скачан сжатый файл, содержащий код FastAPI, обычно скачивание происходит с PyPI. + +Также будут скачаны файлы, содержащие пакеты, которые использует FastAPI. + +Затем все файлы будут извлечены и помещены в директорию на вашем компьютере. + +По умолчанию эти файлы будут загружены и извлечены в один из каталогов установки Python, т.е. в глобальную среду. + +## Что такое виртуальная среда разработки? + +Решением проблемы размещения всех пакетов в глобальной среде будет использование отдельной виртуальной среды под каждый проект, над которым вы работаете. + +Виртуальная среда это обычная папка, очень похожая на глобальную, куда вы можете устанавливать пакеты для вашего проекта. + +Таким образом, каждый проект будет иметь свою отдельную виртуальную среду разработки (в директории `.venv`) вместе со своими пакетами. + +```mermaid +flowchart TB + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) --->|requires| harry-1 + subgraph venv1[.venv] + harry-1[harry v1] + end + end + subgraph azkaban-project[prisoner-of-azkaban project] + azkaban(prisoner-of-azkaban) --->|requires| harry-3 + subgraph venv2[.venv] + harry-3[harry v3] + end + end + stone-project ~~~ azkaban-project +``` + +## Что означает активация виртуальной среды? + +Когда вы активируете виртуальную среду разработки, например, так: + +//// tab | Linux, macOS + +
+ +```console +$ source .venv/bin/activate +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ .venv\Scripts\Activate.ps1 +``` + +
+ +//// + +//// tab | Windows Bash + +Или если вы воспользуетесь Bash под Windows (напр. Git Bash): + +
+ +```console +$ source .venv/Scripts/activate +``` + +
+ +//// + + +Эта команда создаст или изменит некоторые [переменные окружения](environment-variables.md){.internal-link target=_blank}, которые будут доступны для последующих команд. + +Одной из таких переменных является `PATH`. + +/// tip | Подсказка + +Вы можете узнать больше о переменной окружения `PATH` в разделе [Переменные окружения](environment-variables.md#path-environment-variable){.internal-link target=_blank}. + +/// + +При активации виртуальной среды путь `.venv/bin` (для Linux и macOS) или `.venv\Scripts` (для Windows) добавляется в переменную окружения `PATH`. + +Предположим, что до активации виртуальной среды переменная `PATH` выглядела так: + +//// tab | Linux, macOS + +```plaintext +/usr/bin:/bin:/usr/sbin:/sbin +``` + +Это означает, что система ищет программы в следующих каталогах: + +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Windows\System32 +``` + +Это означает, что система ищет программы в: + +* `C:\Windows\System32` + +//// + +После активации виртуальной среды переменная окружение `PATH` будет выглядеть примерно так: + +//// tab | Linux, macOS + +```plaintext +/home/user/code/awesome-project/.venv/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +Это означает, что система теперь будет искать программы в: + +```plaintext +/home/user/code/awesome-project/.venv/bin +``` + +прежде чем начать искать в других каталогах. + +Таким образом, когда вы введете в консоль `python`, система будет искать Python в + +```plaintext +/home/user/code/awesome-project/.venv/bin/python +``` + +и будет использовать именно его. + +//// + +//// tab | Windows + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts;C:\Windows\System32 +``` + +Это означает, что система в первую очередь начнет искать программы в: + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts +``` + +прежде чем начать искать в других директориях. + +Таким образом, если вы введете в консоль команду `python`, то система найдет Python в: + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +и использует его. + +//// + +Очень важной деталью является то, что путь к виртуальной среде будет помещен в самое начало переменной `PATH`. Система обнаружит данный путь к Python раньше, чем какой-либо другой. Таким образом, при запуске команды `python`, будет использован именно Python из виртуальной среды разработки, а не какой-нибудь другой (например, Python из глобальной среды) + +Активация виртуальной среды разработки также меняет и несколько других вещей, но данная функция является основной. + +## Проверка виртуальной среды + +Когда вы проверяете активна ли виртуальная среда разработки, например, так: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
+ +//// + +Это означает, что будет использоваться `python` **из виртуальной среды разработки**. + +Вы используете `which` для Linux и macOS и `Get-Command` для Windows PowerShell. + +Эта команда работает следующим образом: она проверяет переменную окружения `PATH`, проходя по очереди каждый указанный путь в поисках программы под названием `python`. И когда она её находит, то возвращает путь к данной программе. + +Основной момент при вызове команды `python` состоит в том, какой именно "`python`" будет запущен. + +Таким образом, вы можете убедиться, что используете правильную виртуальную среду разработки. + +/// tip | Подсказка + +Легко активировать одну виртуальную среду, вызвать один Python и **перейти к следующему проекту**. + +И следующий проект не будет работать потому, что вы используете **неправильный Python** из виртуальной среды другого проекта. + +Так что, будет нелишним проверить, какой `python` вы используете. 🤓 + +/// + +## Зачем деактивируют виртуальную среду? + +Предположим, что вы работаете над проектом `philosophers-stone`, **активируете виртуальную среду разработки**, устанавливаете пакеты и работаете с данной средой. + +И позже вам понадобилось поработать с **другим проектом** `prisoner-of-azkaban`. + +Вы переходите к этому проекту: + +
+ +```console +$ cd ~/code/prisoner-of-azkaban +``` + +
+ +Если вы не деактивировали виртуальное окружение проекта `philosophers-stone`, то при запуске `python` через консоль будет вызван Python из `philosophers-stone` + +
+ +```console +$ cd ~/code/prisoner-of-azkaban + +$ python main.py + +// Error importing sirius, it's not installed 😱 +Traceback (most recent call last): + File "main.py", line 1, in + import sirius +``` + +
+ +Но если вы деактивируете виртуальную среду разработки и активируете новую среду для `prisoner-of-askaban`, то вы тогда запустите Python из виртуального окружения `prisoner-of-azkaban`. + +
+ +```console +$ cd ~/code/prisoner-of-azkaban + +// Вам не требуется находится в старой директории для деактивации среды разработки, вы можете это сделать откуда угодно, даже из каталога другого проекта, в который вы перешли. 😎 +$ deactivate + +// Активируйте виртуальную среду разработки в prisoner-of-azkaban/.venv 🚀 +$ source .venv/bin/activate + +// Тепреь, когда вы запустите python, он найдет пакет sirius, установленный в виртуальной среде ✨ +$ python main.py + +Я торжественно клянусь в этом! 🐺 +``` + +
+ +## Альтернативы + +Это простое руководство поможет вам начать работу и научит тому, как всё работает **изнутри**. + +Существует много альтернативных решений для работы с виртуальными средами разработки, с программными зависимостями, а также с проектами. + +Когда вы будете готовы использовать единый инструмент для управления проектом, программными зависимостями, виртуальными средами разработки и т.д., то я рекомендую вам попробовать uv. + +`uv` может очень многое. Он умеет: + +* **Устанавливать Python**, включая установку различных версий +* Управлять средой виртуального окружения вашего проекта +* Устанавливать **пакеты** +* Управлять пакетами и их версиями внутри вашего проекта +* Удостовериться, что вы используете **точный** набор пакетов и версий при установке, включая зависимости. Таким образом, вы можете быть уверенны, что проект, запускается в production, точно также, как и при разработке, этот механизм называется *locking* +* Многие другие вещи + +## Заключение + +Если вы прочитали и поняли всё это, то теперь вы знаете **гораздо больше** о виртуальных средах разработки, чем многие другие разработчики. 🤓 + +Скорее всего, знание этих деталей будет полезно вам в будущем. Когда вы будете отлаживать что-то, кажущееся сложным, вы будете знать, **как это работает под капотом**. 😎 diff --git a/docs/tr/docs/about/index.md b/docs/tr/docs/about/index.md new file mode 100644 index 000000000..e9dee5217 --- /dev/null +++ b/docs/tr/docs/about/index.md @@ -0,0 +1,3 @@ +# Hakkında + +FastAPI, tasarımı, ilham kaynağı ve daha fazlası hakkında. 🤓 diff --git a/docs/tr/docs/advanced/index.md b/docs/tr/docs/advanced/index.md new file mode 100644 index 000000000..836e63c8a --- /dev/null +++ b/docs/tr/docs/advanced/index.md @@ -0,0 +1,36 @@ +# Gelişmiş Kullanıcı Rehberi + +## Ek Özellikler + +[Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} sayfası **FastAPI**'ın tüm ana özelliklerini tanıtmaya yetecektir. + +İlerleyen bölümlerde diğer seçenekler, konfigürasyonlar ve ek özellikleri göreceğiz. + +/// tip | İpucu + +Sonraki bölümler **mutlaka "gelişmiş" olmak zorunda değildir**. + +Kullanım şeklinize bağlı olarak, çözümünüz bu bölümlerden birinde olabilir. + +/// + +## Önce Öğreticiyi Okuyun + +[Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} sayfasındaki bilgilerle **FastAPI**'nın çoğu özelliğini kullanabilirsiniz. + +Sonraki bölümler bu sayfayı okuduğunuzu ve bu ana fikirleri bildiğinizi varsayarak hazırlanmıştır. + +## Diğer Kurslar + +[Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} sayfası ve bu **Gelişmiş Kullanıcı Rehberi**, öğretici bir kılavuz (bir kitap gibi) şeklinde yazılmıştır ve **FastAPI'ı öğrenmek** için yeterli olsa da, ek kurslarla desteklemek isteyebilirsiniz. + +Belki de öğrenme tarzınıza daha iyi uyduğu için başka kursları tercih edebilirsiniz. + +Bazı kurs sağlayıcıları ✨ [**FastAPI destekçileridir**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, bu FastAPI ve **ekosisteminin** sürekli ve sağlıklı bir şekilde **gelişmesini** sağlar. + +Ayrıca, size **iyi bir öğrenme deneyimi** sağlamakla kalmayıp, **iyi ve sağlıklı bir framework** olan FastAPI'a ve ve **topluluğuna** (yani size) olan gerçek bağlılıklarını gösterir. + +Onların kurslarını denemek isteyebilirsiniz: + +* Talk Python Training +* Test-Driven Development diff --git a/docs/tr/docs/advanced/security/index.md b/docs/tr/docs/advanced/security/index.md new file mode 100644 index 000000000..709f74c72 --- /dev/null +++ b/docs/tr/docs/advanced/security/index.md @@ -0,0 +1,19 @@ +# Gelişmiş Güvenlik + +## Ek Özellikler + +[Tutorial - User Guide: Security](../../tutorial/security/index.md){.internal-link target=_blank} sayfasında ele alınanların dışında güvenlikle ilgili bazı ek özellikler vardır. + +/// tip | İpucu + +Sonraki bölümler **mutlaka "gelişmiş" olmak zorunda değildir**. + +Kullanım şeklinize bağlı olarak, çözümünüz bu bölümlerden birinde olabilir. + +/// + +## Önce Öğreticiyi Okuyun + +Sonraki bölümler [Tutorial - User Guide: Security](../../tutorial/security/index.md){.internal-link target=_blank} sayfasını okuduğunuzu varsayarak hazırlanmıştır. + +Bu bölümler aynı kavramlara dayanır, ancak bazı ek işlevsellikler sağlar. diff --git a/docs/tr/docs/advanced/testing-websockets.md b/docs/tr/docs/advanced/testing-websockets.md new file mode 100644 index 000000000..ddacca449 --- /dev/null +++ b/docs/tr/docs/advanced/testing-websockets.md @@ -0,0 +1,13 @@ +# WebSockets'i Test Etmek + +WebSockets testi yapmak için `TestClient`'ı kullanabilirsiniz. + +Bu işlem için, `TestClient`'ı bir `with` ifadesinde kullanarak WebSocket'e bağlanabilirsiniz: + +{* ../../docs_src/app_testing/tutorial002.py hl[27:31] *} + +/// note | Not + +Daha fazla detay için Starlette'in Websockets'i Test Etmek dokümantasyonunu inceleyin. + +/// diff --git a/docs/tr/docs/advanced/wsgi.md b/docs/tr/docs/advanced/wsgi.md new file mode 100644 index 000000000..00815a4b2 --- /dev/null +++ b/docs/tr/docs/advanced/wsgi.md @@ -0,0 +1,35 @@ +# WSGI - Flask, Django ve Daha Fazlasını FastAPI ile Kullanma + +WSGI uygulamalarını [Sub Applications - Mounts](sub-applications.md){.internal-link target=_blank}, [Behind a Proxy](behind-a-proxy.md){.internal-link target=_blank} bölümlerinde gördüğünüz gibi bağlayabilirsiniz. + +Bunun için `WSGIMiddleware` ile Flask, Django vb. WSGI uygulamanızı sarmalayabilir ve FastAPI'ya bağlayabilirsiniz. + +## `WSGIMiddleware` Kullanımı + +`WSGIMiddleware`'ı projenize dahil edin. + +Ardından WSGI (örneğin Flask) uygulamanızı middleware ile sarmalayın. + +Son olarak da bir yol altında bağlama işlemini gerçekleştirin. + +{* ../../docs_src/wsgi/tutorial001.py hl[2:3,23] *} + +## Kontrol Edelim + +Artık `/v1/` yolunun altındaki her istek Flask uygulaması tarafından işlenecektir. + +Geri kalanı ise **FastAPI** tarafından işlenecektir. + +Eğer uygulamanızı çalıştırıp http://localhost:8000/v1/ adresine giderseniz, Flask'tan gelen yanıtı göreceksiniz: + +```txt +Hello, World from Flask! +``` + +Eğer http://localhost:8000/v2/ adresine giderseniz, FastAPI'dan gelen yanıtı göreceksiniz: + +```JSON +{ + "message": "Hello World" +} +``` diff --git a/docs/tr/docs/alternatives.md b/docs/tr/docs/alternatives.md new file mode 100644 index 000000000..c98b966b5 --- /dev/null +++ b/docs/tr/docs/alternatives.md @@ -0,0 +1,483 @@ +# Alternatifler, İlham Kaynakları ve Karşılaştırmalar + +**FastAPI**'ya neler ilham verdi? Diğer alternatiflerle karşılaştırıldığında farkları neler? **FastAPI** diğer alternatiflerinden neler öğrendi? + +## Giriş + +Başkalarının daha önceki çalışmaları olmasaydı, **FastAPI** var olmazdı. + +Geçmişte oluşturulan pek çok araç **FastAPI**'a ilham kaynağı olmuştur. + +Yıllardır yeni bir framework oluşturmaktan kaçınıyordum. Başlangıçta **FastAPI**'ın çözdüğü sorunları çözebilmek için pek çok farklı framework, eklenti ve araç kullanmayı denedim. + +Ancak bir noktada, geçmişteki diğer araçlardan en iyi fikirleri alarak bütün bu çözümleri kapsayan, ayrıca bütün bunları Python'ın daha önce mevcut olmayan özelliklerini (Python 3.6+ ile gelen tip belirteçleri) kullanarak yapan bir şey üretmekten başka seçenek kalmamıştı. + +## Daha Önce Geliştirilen Araçlar + +### Django + +Django geniş çapta güvenilen, Python ekosistemindeki en popüler web framework'üdür. Instagram gibi sistemleri geliştirmede kullanılmıştır. + +MySQL ve PostgreSQL gibi ilişkisel veritabanlarıyla nispeten sıkı bir şekilde bağlantılıdır. Bu nedenle Couchbase, MongoDB ve Cassandra gibi NoSQL veritabanlarını ana veritabanı motoru olarak kullanmak pek de kolay değil. + +Modern ön uçlarda (React, Vue.js ve Angular gibi) veya diğer sistemler (örneğin nesnelerin interneti cihazları) tarafından kullanılan API'lar yerine arka uçta HTML üretmek için oluşturuldu. + +### Django REST Framework + +Django REST framework'ü, Django'nun API kabiliyetlerini arttırmak için arka planda Django kullanan esnek bir araç grubu olarak oluşturuldu. + +Üstelik Mozilla, Red Hat ve Eventbrite gibi pek çok şirket tarafından kullanılıyor. + +**Otomatik API dökümantasyonu**nun ilk örneklerinden biri olduğu için, **FastAPI** arayışına ilham veren ilk fikirlerden biri oldu. + +/// note | Not + +Django REST Framework'ü, aynı zamanda **FastAPI**'ın dayandığı Starlette ve Uvicorn'un da yaratıcısı olan Tom Christie tarafından geliştirildi. + +/// + +/// check | **FastAPI**'a nasıl ilham verdi? + +Kullanıcılar için otomatik API dökümantasyonu sunan bir web arayüzüne sahip olmalı. + +/// + +### Flask + +Flask bir mikro framework olduğundan Django gibi framework'lerin aksine veritabanı entegrasyonu gibi Django ile gelen pek çok özelliği direkt barındırmaz. + +Sağladığı basitlik ve esneklik NoSQL veritabanlarını ana veritabanı sistemi olarak kullanmak gibi şeyler yapmaya olanak sağlar. + +Yapısı oldukça basit olduğundan öğrenmesi de nispeten basittir, tabii dökümantasyonu bazı noktalarda biraz teknik hale geliyor. + +Ayrıca Django ile birlikte gelen veritabanı, kullanıcı yönetimi ve diğer pek çok özelliğe ihtiyaç duymayan uygulamalarda da yaygın olarak kullanılıyor. Ancak bu tür özelliklerin pek çoğu eklentiler ile eklenebiliyor. + +Uygulama parçalarının böyle ayrılıyor oluşu ve istenilen özelliklerle genişletilebilecek bir mikro framework olmak tam da benim istediğim bir özellikti. + +Flask'ın basitliği göz önünde bulundurulduğu zaman, API geliştirmek için iyi bir seçim gibi görünüyordu. Sıradaki şey ise Flask için bir "Django REST Framework"! + +/// check | **FastAPI**'a nasıl ilham verdi? + +Gereken araçları ve parçaları birleştirip eşleştirmeyi kolaylaştıracak bir mikro framework olmalı. + +Basit ve kullanması kolay bir yönlendirme sistemine sahip olmalı. + +/// + +### Requests + +**FastAPI** aslında **Requests**'in bir alternatifi değil. İkisininde kapsamı oldukça farklı. + +Aslında Requests'i bir FastAPI uygulamasının *içinde* kullanmak daha olağan olurdu. + +Ama yine de, FastAPI, Requests'ten oldukça ilham aldı. + +**Requests**, API'lar ile bir istemci olarak *etkileşime geçmeyi* sağlayan bir kütüphaneyken **FastAPI** bir sunucu olarak API'lar oluşturmaya yarar. + +Öyle ya da böyle zıt uçlarda olmalarına rağmen birbirlerini tamamlıyorlar. + +Requests oldukça basit ve sezgisel bir tasarıma sahip, kullanması da mantıklı varsayılan değerlerle oldukça kolay. Ama aynı zamanda çok güçlü ve gayet özelleştirilebilir. + +Bu yüzden resmi web sitede de söylendiği gibi: + +> Requests, tüm zamanların en çok indirilen Python paketlerinden biridir. + +Kullanım şekli oldukça basit. Örneğin bir `GET` isteği yapmak için aşağıdaki yeterli: + +```Python +response = requests.get("http://example.com/some/url") +``` + +Bunun FastAPI'deki API *yol işlemi* şöyle görünür: + +```Python hl_lines="1" +@app.get("/some/url") +def read_url(): + return {"message": "Hello World!"} +``` + +`requests.get(...)` ile `@app.get(...)` arasındaki benzerliklere bakın. + +/// check | **FastAPI**'a nasıl ilham verdi? + +* Basit ve sezgisel bir API'ya sahip olmalı. +* HTTP metot isimlerini (işlemlerini) anlaşılır olacak bir şekilde, direkt kullanmalı. +* Mantıklı varsayılan değerlere ve buna rağmen güçlü bir özelleştirme desteğine sahip olmalı. + +/// + +### Swagger / OpenAPI + +Benim Django REST Framework'ünden istediğim ana özellik otomatik API dökümantasyonuydu. + +Daha sonra API'ları dökümanlamak için Swagger adında JSON (veya JSON'un bir uzantısı olan YAML'ı) kullanan bir standart olduğunu buldum. + +Üstelik Swagger API'ları için zaten halihazırda oluşturulmuş bir web arayüzü vardı. Yani, bir API için Swagger dökümantasyonu oluşturmak bu arayüzü otomatik olarak kullanabilmek demekti. + +Swagger bir noktada Linux Foundation'a verildi ve adı OpenAPI olarak değiştirildi. + +İşte bu yüzden versiyon 2.0 hakkında konuşurken "Swagger", versiyon 3 ve üzeri için ise "OpenAPI" adını kullanmak daha yaygın. + +/// check | **FastAPI**'a nasıl ilham verdi? + +API spesifikasyonları için özel bir şema yerine bir açık standart benimseyip kullanmalı. + +Ayrıca standarda bağlı kullanıcı arayüzü araçlarını entegre etmeli: + +* Swagger UI +* ReDoc + +Yukarıdaki ikisi oldukça popüler ve istikrarlı olduğu için seçildi, ancak hızlı bir araştırma yaparak **FastAPI** ile kullanabileceğiniz pek çok OpenAPI alternatifi arayüz bulabilirsiniz. + +/// + +### Flask REST framework'leri + +Pek çok Flask REST framework'ü var, fakat bunları biraz araştırdıktan sonra pek çoğunun artık geliştirilmediğini ve göze batan bazı sorunlarının olduğunu gördüm. + +### Marshmallow + +API sistemlerine gereken ana özelliklerden biri de koddan veriyi alıp ağ üzerinde gönderilebilecek bir şeye çevirmek, yani veri dönüşümü. Bu işleme veritabanındaki veriyi içeren bir objeyi JSON objesine çevirmek, `datetime` objelerini metinlere çevirmek gibi örnekler verilebilir. + +API'lara gereken bir diğer büyük özellik ise veri doğrulamadır, yani verinin çeşitli parametrelere bağlı olarak doğru ve tutarlı olduğundan emin olmaktır. Örneğin bir alanın `int` olmasına karar verdiniz, daha sonra rastgele bir metin değeri almasını istemezsiniz. Bu özellikle sisteme dışarıdan gelen veri için kullanışlı bir özellik oluyor. + +Bir veri doğrulama sistemi olmazsa bütün bu kontrolleri koda dökerek kendiniz yapmak zorunda kalırdınız. + +Marshmallow bu özellikleri sağlamak için geliştirilmişti. Benim de geçmişte oldukça sık kullandığım harika bir kütüphanedir. + +Ama... Python'un tip belirteçleri gelmeden önce oluşturulmuştu. Yani her şemayı tanımlamak için Marshmallow'un sunduğu spesifik araçları ve sınıfları kullanmanız gerekiyordu. + +/// check | **FastAPI**'a nasıl ilham verdi? + +Kod kullanarak otomatik olarak veri tipini ve veri doğrulamayı belirten "şemalar" tanımlamalı. + +/// + +### Webargs + +API'ların ihtiyacı olan bir diğer önemli özellik ise gelen isteklerdeki verileri Python objelerine ayrıştırabilmektir. + +Webargs, Flask gibi bir kaç framework'ün üzerinde bunu sağlamak için geliştirilen bir araçtır. + +Veri doğrulama için arka planda Marshmallow kullanıyor, hatta aynı geliştiriciler tarafından oluşturuldu. + +Webargs da harika bir araç ve onu da geçmişte henüz **FastAPI** yokken çok kullandım. + +/// info | Bilgi + +Webargs aynı Marshmallow geliştirileri tarafından oluşturuldu. + +/// + +/// check | **FastAPI**'a nasıl ilham verdi? + +Gelen istek verisi için otomatik veri doğrulamaya sahip olmalı. + +/// + +### APISpec + +Marshmallow ve Webargs eklentiler olarak; veri doğrulama, ayrıştırma ve dönüştürmeyi sağlıyor. + +Ancak dökümantasyondan hala ses seda yok. Daha sonrasında ise APISpec geldi. + +APISpec pek çok framework için bir eklenti olarak kullanılıyor (Starlette için de bir eklentisi var). + +Şemanın tanımını yol'a istek geldiğinde çalışan her bir fonksiyonun döküman dizesinin içine YAML formatında olacak şekilde yazıyorsunuz o da OpenAPI şemaları üretiyor. + +Flask, Starlette, Responder ve benzerlerinde bu şekilde çalışıyor. + +Fakat sonrasında yine mikro sözdizimi problemiyle karşılaşıyoruz. Python metinlerinin içinde koskoca bir YAML oluyor. + +Editör bu konuda pek yardımcı olamaz. Üstelik eğer parametreleri ya da Marshmallow şemalarını değiştirip YAML kodunu güncellemeyi unutursak artık döküman geçerliliğini yitiriyor. + +/// info | Bilgi + +APISpec de aynı Marshmallow geliştiricileri tarafından oluşturuldu. + +/// + +/// check | **FastAPI**'a nasıl ilham verdi? + +API'lar için açık standart desteği olmalı (OpenAPI gibi). + +/// + +### Flask-apispec + +Flask-apispec ise Webargs, Marshmallow ve APISpec'i birbirine bağlayan bir Flask eklentisi. + +Webargs ve Marshmallow'daki bilgiyi APISpec ile otomatik OpenAPI şemaları üretmek için kullanıyor. + +Hak ettiği değeri görmeyen, harika bir araç. Piyasadaki çoğu Flask eklentisinden çok daha popüler olmalı. Hak ettiği değeri görmüyor oluşunun sebebi ise dökümantasyonun çok kısa ve soyut olması olabilir. + +Böylece Flask-apispec, Python döküman dizilerine YAML gibi farklı bir syntax yazma sorununu çözmüş oldu. + +**FastAPI**'ı geliştirene dek benim favori arka uç kombinasyonum Flask'in yanında Marshmallow ve Webargs ile birlikte Flask-apispec idi. + +Bunu kullanmak, bir kaç full-stack Flask projesi oluşturucusunun yaratılmasına yol açtı. Bunlar benim (ve bir kaç harici ekibin de) şimdiye kadar kullandığı asıl stackler: + +* https://github.com/tiangolo/full-stack +* https://github.com/tiangolo/full-stack-flask-couchbase +* https://github.com/tiangolo/full-stack-flask-couchdb + +Aynı full-stack üreticiler [**FastAPI** Proje Üreticileri](project-generation.md){.internal-link target=_blank}'nin de temelini oluşturdu. + +/// info | Bilgi + +Flask-apispec de aynı Marshmallow geliştiricileri tarafından üretildi. + +/// + +/// check | **FastAPI**'a nasıl ilham oldu? + +Veri dönüşümü ve veri doğrulamayı tanımlayan kodu kullanarak otomatik olarak OpenAPI şeması oluşturmalı. + +/// + +### NestJS (and Angular) + +Bu Python teknolojisi bile değil. NestJS, Angulardan ilham almış olan bir JavaScript (TypeScript) NodeJS framework'ü. + +Flask-apispec ile yapılabileceklere nispeten benzeyen bir şey elde ediyor. + +Angular 2'den ilham alan, içine gömülü bir bağımlılık enjeksiyonu sistemi var. Bildiğim diğer tüm bağımlılık enjeksiyonu sistemlerinde olduğu gibi"bağımlılık"ları önceden kaydetmenizi gerektiriyor. Böylece projeyi daha detaylı hale getiriyor ve kod tekrarını da arttırıyor. + +Parametreler TypeScript tipleri (Python tip belirteçlerine benzer) ile açıklandığından editör desteği oldukça iyi. + +Ama TypeScript verileri kod JavaScript'e derlendikten sonra korunmadığından, bunlara dayanarak aynı anda veri doğrulaması, veri dönüşümü ve dökümantasyon tanımlanamıyor. Bundan ve bazı tasarım tercihlerinden dolayı veri doğrulaması, dönüşümü ve otomatik şema üretimi için pek çok yere dekorator eklemek gerekiyor. Bu da projeyi oldukça detaylandırıyor. + +İç içe geçen derin modelleri pek iyi işleyemiyor. Yani eğer istekteki JSON gövdesi derin bir JSON objesiyse düzgün bir şekilde dökümante edilip doğrulanamıyor. + +/// check | **FastAPI**'a nasıl ilham oldu? + +Güzel bir editör desteği için Python tiplerini kullanmalı. + +Güçlü bir bağımlılık enjeksiyon sistemine sahip olmalı. Kod tekrarını minimuma indirecek bir yol bulmalı. + +/// + +### Sanic + +Sanic, `asyncio`'ya dayanan son derece hızlı Python kütüphanelerinden biriydi. Flask'a epey benzeyecek şekilde geliştirilmişti. + +/// note | Teknik detaylar + +İçerisinde standart Python `asyncio` döngüsü yerine `uvloop` kullanıldı. Hızının asıl kaynağı buydu. + +Uvicorn ve Starlette'e ilham kaynağı olduğu oldukça açık, şu anda ikisi de açık karşılaştırmalarda Sanicten daha hızlı gözüküyor. + +/// + +/// check | **FastAPI**'a nasıl ilham oldu? + +Uçuk performans sağlayacak bir yol bulmalı. + +Tam da bu yüzden **FastAPI** Starlette'e dayanıyor, çünkü Starlette şu anda kullanılabilir en hızlı framework. (üçüncü parti karşılaştırmalı testlerine göre) + +/// + +### Falcon + +Falcon ise bir diğer yüksek performanslı Python framework'ü. Minimal olacak şekilde Hug gibi diğer framework'lerin temeli olabilmek için tasarlandı. + +İki parametre kabul eden fonksiyonlar şeklinde tasarlandı, biri "istek" ve diğeri ise "cevap". Sonra isteğin çeşitli kısımlarını **okuyor**, cevaba ise bir şeyler **yazıyorsunuz**. Bu tasarımdan dolayı istek parametrelerini ve gövdelerini standart Python tip belirteçlerini kullanarak fonksiyon parametreleriyle belirtmek mümkün değil. + +Yani veri doğrulama, veri dönüştürme ve dökümantasyonun hepsi kodda yer almalı, otomatik halledemiyoruz. Ya da Falcon üzerine bir framework olarak uygulanmaları gerekiyor, aynı Hug'da olduğu gibi. Bu ayrım Falcon'un tasarımından esinlenen, istek ve cevap objelerini parametre olarak işleyen diğer kütüphanelerde de yer alıyor. + +/// check | **FastAPI**'a nasıl ilham oldu? + +Harika bir performans'a sahip olmanın yollarını bulmalı. + +Hug ile birlikte (Hug zaten Falcon'a dayandığından) **FastAPI**'ın fonksiyonlarda `cevap` parametresi belirtmesinde ilham kaynağı oldu. + +FastAPI'da opsiyonel olmasına rağmen, daha çok header'lar, çerezler ve alternatif durum kodları belirlemede kullanılıyor. + +/// + +### Molten + +**FastAPI**'ı geliştirmenin ilk aşamalarında Molten'ı keşfettim. Pek çok ortak fikrimiz vardı: + +* Python'daki tip belirteçlerini baz alıyordu. +* Bunlara bağlı olarak veri doğrulaması ve dökümantasyon sağlıyordu. +* Bir bağımlılık enjeksiyonu sistemi vardı. + +Veri doğrulama, veri dönüştürme ve dökümantasyon için Pydantic gibi bir üçüncü parti kütüphane kullanmıyor, kendi içerisinde bunlara sahip. Yani bu veri tipi tanımlarını tekrar kullanmak pek de kolay değil. + +Biraz daha detaylı ayarlamalara gerek duyuyor. Ayrıca ASGI yerine WSGI'a dayanıyor. Yani Uvicorn, Starlette ve Sanic gibi araçların yüksek performansından faydalanacak şekilde tasarlanmamış. + +Bağımlılık enjeksiyonu sistemi bağımlılıkların önceden kaydedilmesini ve sonrasında belirlenen veri tiplerine göre çözülmesini gerektiriyor. Yani spesifik bir tip, birden fazla bileşen ile belirlenemiyor. + +Yol'lar fonksiyonun üstünde endpoint'i işleyen dekoratörler yerine farklı yerlerde tanımlanan fonksiyonlarla belirlenir. Bu Flask (ve Starlette) yerine daha çok Django'nun yaklaşımına daha yakın bir metot. Bu, kodda nispeten birbiriyle sıkı ilişkili olan şeyleri ayırmaya sebep oluyor. + +/// check | **FastAPI**'a nasıl ilham oldu? + +Model özelliklerinin "standart" değerlerini kullanarak veri tipleri için ekstra veri doğrulama koşulları tanımlamalı. Bu editör desteğini geliştiriyor ve daha önceden Pydantic'te yoktu. + +Bu aslında Pydantic'in de aynı doğrulama stiline geçmesinde ilham kaynağı oldu. Şu anda bütün bu özellikler Pydantic'in yapısında yer alıyor. + +/// + +### Hug + +Hug, Python tip belirteçlerini kullanarak API parametrelerinin tipini belirlemeyi uygulayan ilk framework'lerdendi. Bu, diğer araçlara da ilham kaynağı olan harika bir fikirdi. + +Tip belirlerken standart Python veri tipleri yerine kendi özel tiplerini kullandı, yine de bu ileriye dönük devasa bir adımdı. + +Hug ayrıca tüm API'ı JSON ile ifade eden özel bir şema oluşturan ilk framework'lerdendir. + +OpenAPI veya JSON Şeması gibi bir standarda bağlı değildi. Yani Swagger UI gibi diğer araçlarla entegre etmek kolay olmazdı. Ama yine de, bu oldukça yenilikçi bir fikirdi. + +Ayrıca ilginç ve çok rastlanmayan bir özelliği vardı: aynı framework'ü kullanarak hem API'lar hem de CLI'lar oluşturmak mümkündü. + +Senkron çalışan Python web framework'lerinin standardına (WSGI) dayandığından dolayı Websocket'leri ve diğer şeyleri işleyemiyor, ancak yine de yüksek performansa sahip. + +/// info | Bilgi + +Hug, Python dosyalarında bulunan dahil etme satırlarını otomatik olarak sıralayan harika bir araç olan `isort`'un geliştiricisi Timothy Crosley tarafından geliştirildi. + +/// + +/// check | **FastAPI**'a nasıl ilham oldu? + +Hug, APIStar'ın çeşitli kısımlarında esin kaynağı oldu ve APIStar'la birlikte en umut verici bulduğum araçlardan biriydi. + +**FastAPI**, Python tip belirteçlerini kullanarak parametre belirlemede ve API'ı otomatık tanımlayan bir şema üretmede de Hug'a esinlendi. + +**FastAPI**'ın header ve çerez tanımlamak için fonksiyonlarda `response` parametresini belirtmesinde de Hug'dan ilham alındı. + +/// + +### APIStar (<= 0.5) + +**FastAPI**'ı geliştirmeye başlamadan hemen önce **APIStar** sunucusunu buldum. Benim aradığım şeylerin neredeyse hepsine sahipti ve harika bir tasarımı vardı. + +Benim şimdiye kadar gördüğüm Python tip belirteçlerini kullanarak parametre ve istekler belirlemeyi uygulayan ilk framework'lerdendi (Molten ve NestJS'den önce). APIStar'ı da aşağı yukarı Hug ile aynı zamanlarda buldum. Fakat APIStar OpenAPI standardını kullanıyordu. + +Farklı yerlerdeki tip belirteçlerine bağlı olarak otomatik veri doğrulama, veri dönüştürme ve OpenAPI şeması oluşturma desteği sunuyordu. + +Gövde şema tanımları Pydantic ile aynı Python tip belirteçlerini kullanmıyordu, biraz daha Marsmallow'a benziyordu. Dolayısıyla editör desteği de o kadar iyi olmazdı ama APIStar eldeki en iyi seçenekti. + +O dönemlerde karşılaştırmalarda en iyi performansa sahipti (yalnızca Starlette'e kaybediyordu). + +Başlangıçta otomatik API dökümantasyonu sunan bir web arayüzü yoktu, ama ben ona Swagger UI ekleyebileceğimi biliyordum. + +Bağımlılık enjeksiyon sistemi vardı. Yukarıda bahsettiğim diğer araçlar gibi bundaki sistem de bileşenlerin önceden kaydedilmesini gerektiriyordu. Yine de harika bir özellikti. + +Güvenlik entegrasyonu olmadığından dolayı APIStar'ı hiç bir zaman tam bir projede kullanamadım. Bu yüzden Flask-apispec'e bağlı full-stack proje üreticilerde sahip olduğum özellikleri tamamen değiştiremedim. Bu güvenlik entegrasyonunu ekleyen bir PR oluşturmak da projelerim arasında yer alıyordu. + +Sonrasında ise projenin odağı değişti. + +Geliştiricinin Starlette'e odaklanması gerekince proje de artık bir API web framework'ü olmayı bıraktı. + +Artık APIStar, OpenAPI özelliklerini doğrulamak için bir dizi araç sunan bir proje haline geldi. + +/// info | Bilgi + +APIStar, aşağıdaki projeleri de üreten Tom Christie tarafından geliştirildi: + +* Django REST Framework +* **FastAPI**'ın da dayandığı Starlette +* Starlette ve **FastAPI** tarafından da kullanılan Uvicorn + +/// + +/// check | **FastAPI**'a nasıl ilham oldu? + +Var oldu. + +Aynı Python veri tipleriyle birden fazla şeyi belirleme (veri doğrulama, veri dönüştürme ve dökümantasyon), bir yandan da harika bir editör desteği sunma, benim muhteşem bulduğum bir fikirdi. + +Uzunca bir süre boyunca benzer bir framework arayıp pek çok farklı alternatifi denedikten sonra, APIStar en iyi seçenekti. + +Sonra APIStar bir sunucu olmayı bıraktı ve Starlette oluşturuldu. Starlette, böyle bir sunucu sistemi için daha iyi bir temel sunuyordu. Bu da **FastAPI**'ın son esin kaynağıydı. + +Ben bu önceki araçlardan öğrendiklerime dayanarak **FastAPI**'ın özelliklerini arttırıp geliştiriyor, tip desteği sistemi ve diğer kısımları iyileştiriyorum ancak yine de **FastAPI**'ı APIStar'ın "ruhani varisi" olarak görüyorum. + +/// + +## **FastAPI** Tarafından Kullanılanlar + +### Pydantic + +Pydantic Python tip belirteçlerine dayanan; veri doğrulama, veri dönüştürme ve dökümantasyon tanımlamak (JSON Şema kullanarak) için bir kütüphanedir. + +Tip belirteçleri kullanıyor olması onu aşırı sezgisel yapıyor. + +Marshmallow ile karşılaştırılabilir. Ancak karşılaştırmalarda Marshmallowdan daha hızlı görünüyor. Aynı Python tip belirteçlerine dayanıyor ve editör desteği de harika. + +/// check | **FastAPI** nerede kullanıyor? + +Bütün veri doğrulama, veri dönüştürme ve JSON Şemasına bağlı otomatik model dökümantasyonunu halletmek için! + +**FastAPI** yaptığı her şeyin yanı sıra bu JSON Şema verisini alıp daha sonra OpenAPI'ya yerleştiriyor. + +/// + +### Starlette + +Starlette hafif bir ASGI framework'ü ve yüksek performanslı asyncio servisleri oluşturmak için ideal. + +Kullanımı çok kolay ve sezgisel, kolaylıkla genişletilebilecek ve modüler bileşenlere sahip olacak şekilde tasarlandı. + +Sahip olduğu bir kaç özellik: + +* Cidden etkileyici bir performans. +* WebSocket desteği. +* İşlem-içi arka plan görevleri. +* Başlatma ve kapatma olayları. +* HTTPX ile geliştirilmiş bir test istemcisi. +* CORS, GZip, Static Files ve Streaming cevapları desteği. +* Session ve çerez desteği. +* Kodun %100'ü test kapsamında. +* Kodun %100'ü tip belirteçleriyle desteklenmiştir. +* Yalnızca bir kaç zorunlu bağımlılığa sahip. + +Starlette şu anda test edilen en hızlı Python framework'ü. Yalnızca bir sunucu olan Uvicorn'a yeniliyor, o da zaten bir framework değil. + +Starlette bütün temel web mikro framework işlevselliğini sağlıyor. + +Ancak otomatik veri doğrulama, veri dönüştürme ve dökümantasyon sağlamyor. + +Bu, **FastAPI**'ın onun üzerine tamamen Python tip belirteçlerine bağlı olarak eklediği (Pydantic ile) ana şeylerden biri. **FastAPI** bunun yanında artı olarak bağımlılık enjeksiyonu sistemi, güvenlik araçları, OpenAPI şema üretimi ve benzeri özellikler de ekliyor. + +/// note | Teknik Detaylar + +ASGI, Django'nun ana ekibi tarafından geliştirilen yeni bir "standart". Bir "Python standardı" (PEP) olma sürecinde fakat henüz bir standart değil. + +Bununla birlikte, halihazırda birçok araç tarafından bir "standart" olarak kullanılmakta. Bu, Uvicorn'u farklı ASGI sunucularıyla (Daphne veya Hypercorn gibi) değiştirebileceğiniz veya `python-socketio` gibi ASGI ile uyumlu araçları ekleyebileciğiniz için birlikte çalışılabilirliği büyük ölçüde arttırıyor. + +/// + +/// check | **FastAPI** nerede kullanıyor? + +Tüm temel web kısımlarında üzerine özellikler eklenerek kullanılmakta. + +`FastAPI` sınıfının kendisi direkt olarak `Starlette` sınıfını miras alıyor! + +Yani, Starlette ile yapabileceğiniz her şeyi, Starlette'in bir nevi güçlendirilmiş hali olan **FastAPI** ile doğrudan yapabilirsiniz. + +/// + +### Uvicorn + +Uvicorn, uvlook ile httptools üzerine kurulu ışık hzında bir ASGI sunucusudur. + +Bir web framework'ünden ziyade bir sunucudur, yani yollara bağlı yönlendirme yapmanızı sağlayan araçları yoktur. Bu daha çok Starlette (ya da **FastAPI**) gibi bir framework'ün sunucuya ek olarak sağladığı bir şeydir. + +Starlette ve **FastAPI** için tavsiye edilen sunucu Uvicorndur. + +/// check | **FastAPI** neden tavsiye ediyor? + +**FastAPI** uygulamalarını çalıştırmak için ana web sunucusu Uvicorn! + +Gunicorn ile birleştirdiğinizde asenkron ve çoklu işlem destekleyen bir sunucu elde ediyorsunuz! + +Daha fazla detay için [Deployment](deployment/index.md){.internal-link target=_blank} bölümünü inceleyebilirsiniz. + +/// + +## Karşılaştırma ve Hız + +Uvicorn, Starlette ve FastAPI arasındakı farkı daha iyi anlamak ve karşılaştırma yapmak için [Kıyaslamalar](benchmarks.md){.internal-link target=_blank} bölümüne bakın! diff --git a/docs/tr/docs/async.md b/docs/tr/docs/async.md new file mode 100644 index 000000000..558a79cb7 --- /dev/null +++ b/docs/tr/docs/async.md @@ -0,0 +1,407 @@ +# Concurrency ve async / await + +*path operasyon fonksiyonu* için `async def `sözdizimi, asenkron kod, eşzamanlılık ve paralellik hakkında bazı ayrıntılar. + +## Aceleniz mi var? + +TL;DR: + +Eğer `await` ile çağrılması gerektiğini belirten üçüncü taraf kütüphaneleri kullanıyorsanız, örneğin: + +```Python +results = await some_library() +``` + +O zaman *path operasyon fonksiyonunu* `async def` ile tanımlayın örneğin: + +```Python hl_lines="2" +@app.get('/') +async def read_results(): + results = await some_library() + return results +``` + +/// note | Not + +Sadece `async def` ile tanımlanan fonksiyonlar içinde `await` kullanabilirsiniz. + +/// + +--- + +Eğer bir veritabanı, bir API, dosya sistemi vb. ile iletişim kuran bir üçüncü taraf bir kütüphane kullanıyorsanız ve `await` kullanımını desteklemiyorsa, (bu şu anda çoğu veritabanı kütüphanesi için geçerli bir durumdur), o zaman *path operasyon fonksiyonunuzu* `def` kullanarak normal bir şekilde tanımlayın, örneğin: + +```Python hl_lines="2" +@app.get('/') +def results(): + results = some_library() + return results +``` + +--- + +Eğer uygulamanız (bir şekilde) başka bir şeyle iletişim kurmak ve onun cevap vermesini beklemek zorunda değilse, `async def` kullanın. + +--- + +Sadece bilmiyorsanız, normal `def` kullanın. + +--- + +**Not**: *path operasyon fonksiyonlarınızda* `def` ve `async def`'i ihtiyaç duyduğunuz gibi karıştırabilir ve her birini sizin için en iyi seçeneği kullanarak tanımlayabilirsiniz. FastAPI onlarla doğru olanı yapacaktır. + +Her neyse, yukarıdaki durumlardan herhangi birinde, FastAPI yine de asenkron olarak çalışacak ve son derece hızlı olacaktır. + +Ancak yukarıdaki adımları takip ederek, bazı performans optimizasyonları yapılabilecektir. + +## Teknik Detaylar + +Python'un modern versiyonlarında **`async` ve `await`** sözdizimi ile **"coroutines"** kullanan **"asenkron kod"** desteğine sahiptir. + +Bu ifadeyi aşağıdaki bölümlerde daha da ayrıntılı açıklayalım: + +* **Asenkron kod** +* **`async` ve `await`** +* **Coroutines** + +## Asenkron kod + +Asenkron kod programlama dilinin 💬 bilgisayara / programa 🤖 kodun bir noktasında, *başka bir kodun* bir yerde bitmesini 🤖 beklemesi gerektiğini söylemenin bir yoludur. Bu *başka koda* "slow-file" denir 📝. + +Böylece, bu süreçte bilgisayar "slow-file" 📝 tamamlanırken gidip başka işler yapabilir. + +Sonra bilgisayar / program 🤖 her fırsatı olduğunda o noktada yaptığı tüm işleri 🤖 bitirene kadar geri dönücek. Ve 🤖 yapması gerekeni yaparak, beklediği görevlerden herhangi birinin bitip bitmediğini görecek. + +Ardından, 🤖 bitirmek için ilk görevi alır ("slow-file" 📝) ve onunla ne yapması gerekiyorsa onu devam ettirir. + +Bu "başka bir şey için bekle" normalde, aşağıdakileri beklemek gibi (işlemcinin ve RAM belleğinin hızına kıyasla) nispeten "yavaş" olan I/O işlemlerine atıfta bulunur: + +* istemci tarafından ağ üzerinden veri göndermek +* ağ üzerinden istemciye gönderilen veriler +* sistem tarafından okunacak ve programınıza verilecek bir dosya içeriği +* programınızın diske yazılmak üzere sisteme verdiği dosya içerikleri +* uzak bir API işlemi +* bir veritabanı bitirme işlemi +* sonuçları döndürmek için bir veritabanı sorgusu +* vb. + +Yürütme süresi çoğunlukla I/O işlemleri beklenerek tüketildiğinden bunlara "I/O bağlantılı" işlemler denir. + +Buna "asenkron" denir, çünkü bilgisayar/program yavaş görevle "senkronize" olmak zorunda değildir, görevin tam olarak biteceği anı bekler, hiçbir şey yapmadan, görev sonucunu alabilmek ve çalışmaya devam edebilmek için . + +Bunun yerine, "asenkron" bir sistem olarak, bir kez bittiğinde, bilgisayarın / programın yapması gerekeni bitirmesi için biraz (birkaç mikrosaniye) sırada bekleyebilir ve ardından sonuçları almak için geri gelebilir ve onlarla çalışmaya devam edebilir. + +"Senkron" ("asenkron"un aksine) için genellikle "sıralı" terimini de kullanırlar, çünkü bilgisayar/program, bu adımlar beklemeyi içerse bile, farklı bir göreve geçmeden önce tüm adımları sırayla izler. + + +### Eşzamanlılık (Concurrency) ve Burgerler + + +Yukarıda açıklanan bu **asenkron** kod fikrine bazen **"eşzamanlılık"** da denir. **"Paralellikten"** farklıdır. + +**Eşzamanlılık** ve **paralellik**, "aynı anda az ya da çok olan farklı işler" ile ilgilidir. + +Ancak *eşzamanlılık* ve *paralellik* arasındaki ayrıntılar oldukça farklıdır. + + +Farkı görmek için burgerlerle ilgili aşağıdaki hikayeyi hayal edin: + +### Eşzamanlı Burgerler + + + +Aşkınla beraber 😍 dışarı hamburger yemeye çıktınız 🍔, kasiyer 💁 öndeki insanlardan sipariş alırken siz sıraya girdiniz. + +Sıra sizde ve sen aşkın 😍 ve kendin için 2 çılgın hamburger 🍔 söylüyorsun. + +Ödemeyi yaptın 💸. + +Kasiyer 💁 mutfakdaki aşçıya 👨‍🍳 hamburgerleri 🍔 hazırlaması gerektiğini söyler ve aşçı bunu bilir (o an önceki müşterilerin siparişlerini hazırlıyor olsa bile). + +Kasiyer 💁 size bir sıra numarası verir. + +Beklerken askınla 😍 bir masaya oturur ve uzun bir süre konuşursunuz(Burgerleriniz çok çılgın olduğundan ve hazırlanması biraz zaman alıyor ✨🍔✨). + +Hamburgeri beklerkenki zamanı 🍔, aşkının ne kadar zeki ve tatlı olduğuna hayran kalarak harcayabilirsin ✨😍✨. + +Aşkınla 😍 konuşurken arada sıranın size gelip gelmediğini kontrol ediyorsun. + +Nihayet sıra size geldi. Tezgaha gidip hamburgerleri 🍔kapıp masaya geri dönüyorsun. + +Aşkınla hamburgerlerinizi yiyor 🍔 ve iyi vakit geçiriyorsunuz ✨. + +--- + +Bu hikayedeki bilgisayar / program 🤖 olduğunuzu hayal edin. + +Sırada beklerken boştasın 😴, sıranı beklerken herhangi bir "üretim" yapmıyorsun. Ama bu sıra hızlı çünkü kasiyer sadece siparişleri alıyor (onları hazırlamıyor), burada bir sıknıtı yok. + +Sonra sıra size geldiğinde gerçekten "üretken" işler yapabilirsiniz 🤓, menüyü oku, ne istediğine larar ver, aşkının seçimini al 😍, öde 💸, doğru kartı çıkart, ödemeyi kontrol et, faturayı kontrol et, siparişin doğru olup olmadığını kontrol et, vb. + +Ama hamburgerler 🍔 hazır olmamasına rağmen Kasiyer 💁 ile işiniz "duraklıyor" ⏸, çünkü hamburgerlerin hazır olmasını bekliyoruz 🕙. + +Ama tezgahtan uzaklaşıp sıranız gelene kadarmasanıza dönebilir 🔀 ve dikkatinizi aşkınıza 😍 verebilirsiniz vr bunun üzerine "çalışabilirsiniz" ⏯ 🤓. Artık "üretken" birşey yapıyorsunuz 🤓, sevgilinle 😍 flört eder gibi. + +Kasiyer 💁 "Hamburgerler hazır !" 🍔 dediğinde ve görüntülenen numara sizin numaranız olduğunda hemen koşup hamburgerlerinizi almaya çalışmıyorsunuz. Biliyorsunuzki kimse sizin hamburgerlerinizi 🍔 çalmayacak çünkü sıra sizin. + +Yani Aşkınızın😍 hikayeyi bitirmesini bekliyorsunuz (çalışmayı bitir ⏯ / görev işleniyor.. 🤓), nazikçe gülümseyin ve hamburger yemeye gittiğinizi söyleyin ⏸. + +Ardından tezgaha 🔀, şimdi biten ilk göreve ⏯ gidin, Hamburgerleri 🍔 alın, teşekkür edin ve masaya götürün. sayacın bu adımı tamamlanır ⏹. Bu da yeni bir görev olan "hamburgerleri ye" 🔀 ⏯ görevini başlatırken "hamburgerleri al" ⏹ görevini bitirir. + +### Parallel Hamburgerler + +Şimdi bunların "Eşzamanlı Hamburger" değil, "Paralel Hamburger" olduğunu düşünelim. + +Hamburger 🍔 almak için 😍 aşkınla Paralel fast food'a gidiyorsun. + +Birden fazla kasiyer varken (varsayalım 8) sıraya girdiniz👩‍🍳👨‍🍳👩‍🍳👨‍🍳👩‍🍳👨‍🍳👩‍🍳👨‍🍳 ve sıranız gelene kadar bekliyorsunuz. + +Sizden önceki herkez ayrılmadan önce hamburgerlerinin 🍔 hazır olmasını bekliyor 🕙. Çünkü kasiyerlerin her biri bir hamburger hazırlanmadan önce bir sonraki siparişe geçmiiyor. + +Sonunda senin sıran, aşkın 😍 ve kendin için 2 hamburger 🍔 siparişi verdiniz. + +Ödemeyi yaptınız 💸. + +Kasiyer mutfağa gider 👨‍🍳. + +Sırada bekliyorsunuz 🕙, kimse sizin burgerinizi 🍔 almaya çalışmıyor çünkü sıra sizin. + +Sen ve aşkın 😍 sıranızı korumak ve hamburgerleri almakla o kadar meşgulsünüz ki birbirinize vakit 🕙 ayıramıyorsunuz 😞. + +İşte bu "senkron" çalışmadır. Kasiyer/aşçı 👨‍🍳ile senkron hareket ediyorsunuz. Bu yüzden beklemek 🕙 ve kasiyer/aşçı burgeri 🍔bitirip size getirdiğinde orda olmak zorundasınız yoksa başka biri alabilir. + +Sonra kasiyeri/aşçı 👨‍🍳 nihayet hamburgerlerinizle 🍔, uzun bir süre sonra 🕙 tezgaha geri geliyor. + +Burgerlerinizi 🍔 al ve aşkınla masanıza doğru ilerle 😍. + +Sadece burgerini yiyorsun 🍔 ve bitti ⏹. + +Bekleyerek çok fazla zaman geçtiğinden 🕙 konuşmaya çok fazla vakit kalmadı 😞. + +--- + +Paralel burger senaryosunda ise, siz iki işlemcili birer robotsunuz 🤖 (sen ve sevgilin 😍), Beklıyorsunuz 🕙 hem konuşarak güzel vakit geçirirken ⏯ hem de sıranızı bekliyorsunuz 🕙. + +Mağazada ise 8 işlemci bulunuyor (Kasiyer/aşçı) 👩‍🍳👨‍🍳👩‍🍳👨‍🍳👩‍🍳👨‍🍳👩‍🍳👨‍🍳. Eşzamanlı burgerde yalnızca 2 kişi olabiliyordu (bir kasiyer ve bir aşçı) 💁 👨‍🍳. + +Ama yine de bu en iyisi değil 😞. + +--- + +Bu hikaye burgerler 🍔 için paralel. + +Bir gerçek hayat örneği verelim. Bir banka hayal edin. + +Bankaların çoğunda birkaç kasiyer 👨‍💼👨‍💼👨‍💼👨‍💼 ve uzun bir sıra var 🕙🕙🕙🕙🕙🕙🕙🕙. + +Tüm işi sırayla bir müşteri ile yapan tüm kasiyerler 👨‍💼⏯. + +Ve uzun süre kuyrukta beklemek 🕙 zorundasın yoksa sıranı kaybedersin. + +Muhtemelen ayak işlerı yaparken sevgilini 😍 bankaya 🏦 getirmezsin. + +### Burger Sonucu + +Bu "aşkınla fast food burgerleri" senaryosunda, çok fazla bekleme olduğu için 🕙, eşzamanlı bir sisteme sahip olmak çok daha mantıklı ⏸🔀⏯. + +Web uygulamalarının çoğu için durum böyledir. + +Pek çok kullanıcı var, ama sunucunuz pek de iyi olmayan bir bağlantı ile istek atmalarını bekliyor. + +Ve sonra yanıtların geri gelmesi için tekrar 🕙 bekliyor + +Bu "bekleme" 🕙 mikrosaniye cinsinden ölçülür, yine de, hepsini toplarsak çok fazla bekleme var. + +Bu nedenle, web API'leri için asenkron ⏸🔀⏯ kod kullanmak çok daha mantıklı. + +Mevcut popüler Python frameworklerinin çoğu (Flask ve Django gibi), Python'daki yeni asenkron özellikler mevcut olmadan önce yazıldı. Bu nedenle, dağıtılma biçimleri paralel yürütmeyi ve yenisi kadar güçlü olmayan eski bir eşzamansız yürütme biçimini destekler. + +Asenkron web (ASGI) özelliği, WebSockets için destek eklemek için Django'ya eklenmiş olsa da. + +Asenkron çalışabilme NodeJS in popüler olmasının sebebi (paralel olamasa bile) ve Go dilini güçlü yapan özelliktir. + +Ve bu **FastAPI** ile elde ettiğiniz performans düzeyiyle aynıdır. + +Aynı anda paralellik ve asenkronluğa sahip olabildiğiniz için, test edilen NodeJS çerçevelerinin çoğundan daha yüksek performans elde edersiniz ve C'ye daha yakın derlenmiş bir dil olan Go ile eşit bir performans elde edersiniz (bütün teşekkürler Starlette'e ). + +### Eşzamanlılık paralellikten daha mı iyi? + +Hayır! Hikayenin ahlakı bu değil. + +Eşzamanlılık paralellikten farklıdır. Ve çok fazla bekleme içeren **belirli** senaryolarda daha iyidir. Bu nedenle, genellikle web uygulamaları için paralellikten çok daha iyidir. Ama her şey için değil. + +Yanı, bunu aklınızda oturtmak için aşağıdaki kısa hikayeyi hayal edin: + +> Büyük, kirli bir evi temizlemelisin. + +*Evet, tüm hikaye bu*. + +--- + +Beklemek yok 🕙. Hiçbir yerde. Sadece evin birden fazla yerinde yapılacak fazlasıyla iş var. + +You could have turns as in the burgers example, first the living room, then the kitchen, but as you are not waiting 🕙 for anything, just cleaning and cleaning, the turns wouldn't affect anything. +Hamburger örneğindeki gibi dönüşleriniz olabilir, önce oturma odası, sonra mutfak, ama hiçbir şey için 🕙 beklemediğinizden, sadece temizlik, temizlik ve temizlik, dönüşler hiçbir şeyi etkilemez. + +Sıralı veya sırasız (eşzamanlılık) bitirmek aynı zaman alır ve aynı miktarda işi yaparsınız. + +Ama bu durumda, 8 eski kasiyer/aşçı - yeni temizlikçiyi getirebilseydiniz 👩‍🍳👨‍🍳👩‍🍳👨‍🍳👩‍🍳👨‍🍳👩‍🍳👨‍🍳 ve her birini (artı siz) evin bir bölgesini temizlemek için görevlendirseydiniz, ekstra yardımla tüm işleri **paralel** olarak yapabilir ve çok daha erken bitirebilirdiniz. + +Bu senaryoda, temizlikçilerin her biri (siz dahil) birer işlemci olacak ve üzerine düşeni yapacaktır. + +Yürütme süresinin çoğu (beklemek yerine) iş yapıldığından ve bilgisayardaki iş bir CPU tarafından yapıldığından, bu sorunlara "CPU bound" diyorlar". + +--- + +CPU'ya bağlı işlemlerin yaygın örnekleri, karmaşık matematik işlemleri gerektiren işlerdir. + +Örneğin: + +* **Ses** veya **görüntü işleme**. +* **Bilgisayar görüsü**: bir görüntü milyonlarca pikselden oluşur, her pikselin 3 değeri / rengi vardır, bu pikseller üzerinde aynı anda bir şeyler hesaplamayı gerektiren işleme. +* **Makine Öğrenimi**: Çok sayıda "matris" ve "vektör" çarpımı gerektirir. Sayıları olan ve hepsini aynı anda çarpan büyük bir elektronik tablo düşünün. +* **Derin Öğrenme**: Bu, Makine Öğreniminin bir alt alanıdır, dolayısıyla aynısı geçerlidir. Sadece çarpılacak tek bir sayı tablosu değil, büyük bir sayı kümesi vardır ve çoğu durumda bu modelleri oluşturmak ve/veya kullanmak için özel işlemciler kullanırsınız. + +### Eşzamanlılık + Paralellik: Web + Makine Öğrenimi + +**FastAPI** ile web geliştirme için çok yaygın olan eşzamanlılıktan yararlanabilirsiniz (NodeJS'in aynı çekiciliği). + +Ancak, Makine Öğrenimi sistemlerindekile gibi **CPU'ya bağlı** iş yükleri için paralellik ve çoklu işlemenin (birden çok işlemin paralel olarak çalışması) avantajlarından da yararlanabilirsiniz. + +Buna ek olarak Python'un **Veri Bilimi**, Makine Öğrenimi ve özellikle Derin Öğrenme için ana dil olduğu gerçeği, FastAPI'yi Veri Bilimi / Makine Öğrenimi web API'leri ve uygulamaları için çok iyi bir seçenek haline getirir. + +Production'da nasıl oldugunu görmek için şu bölüme bakın [Deployment](deployment/index.md){.internal-link target=_blank}. + +## `async` ve `await` + +Python'un modern sürümleri, asenkron kodu tanımlamanın çok sezgisel bir yoluna sahiptir. Bu, normal "sequentıal" (sıralı) kod gibi görünmesini ve doğru anlarda sizin için "awaıt" ile bekleme yapmasını sağlar. + +Sonuçları vermeden önce beklemeyi gerektirecek ve yeni Python özelliklerini destekleyen bir işlem olduğunda aşağıdaki gibi kodlayabilirsiniz: + +```Python +burgers = await get_burgers(2) +``` + +Buradaki `await` anahtari Python'a, sonuçları `burgers` degiskenine atamadan önce `get_burgers(2)` kodunun işini bitirmesini 🕙 beklemesi gerektiğini söyler. Bununla Python, bu ara zamanda başka bir şey 🔀 ⏯ yapabileceğini bilecektir (başka bir istek almak gibi). + + `await`kodunun çalışması için, eşzamansızlığı destekleyen bir fonksiyonun içinde olması gerekir. Bunu da yapmak için fonksiyonu `async def` ile tanımlamamız yeterlidir: + +```Python hl_lines="1" +async def get_burgers(number: int): + # burgerleri oluşturmak için asenkron birkaç iş + return burgers +``` + +...`def` yerine: + +```Python hl_lines="2" +# bu kod asenkron değil +def get_sequential_burgers(number: int): + # burgerleri oluşturmak için senkron bırkaç iş + return burgers +``` + +`async def` ile Python, bu fonksıyonun içinde, `await` ifadelerinin farkında olması gerektiğini ve çalışma zamanı gelmeden önce bu işlevin yürütülmesini "duraklatabileceğini" ve başka bir şey yapabileceğini 🔀 bilir. + +`async def` fonksiyonunu çağırmak istediğinizde, onu "awaıt" ıle kullanmanız gerekir. Yani, bu işe yaramaz: + +```Python +# Bu işe yaramaz, çünkü get_burgers, şu şekilde tanımlandı: async def +burgers = get_burgers(2) +``` + +--- + +Bu nedenle, size onu `await` ile çağırabileceğinizi söyleyen bir kitaplık kullanıyorsanız, onu `async def` ile tanımlanan *path fonksiyonu* içerisinde kullanmanız gerekir, örneğin: + +```Python hl_lines="2-3" +@app.get('/burgers') +async def read_burgers(): + burgers = await get_burgers(2) + return burgers +``` + +### Daha fazla teknik detay + +`await` in yalnızca `async def` ile tanımlanan fonksıyonların içinde kullanılabileceğini fark etmişsinizdir. + +Ama aynı zamanda, `async def` ile tanımlanan fonksiyonların "await" ile beklenmesi gerekir. Bu nedenle, "`async def` içeren fonksiyonlar yalnızca "`async def` ile tanımlanan fonksiyonların içinde çağrılabilir. + + +Yani yumurta mı tavukdan, tavuk mu yumurtadan gibi ilk `async` fonksiyonu nasıl çağırılır? + +**FastAPI** ile çalışıyorsanız bunun için endişelenmenize gerek yok, çünkü bu "ilk" fonksiyon sizin *path fonksiyonunuz* olacak ve FastAPI doğru olanı nasıl yapacağını bilecek. + +Ancak FastAPI olmadan `async` / `await` kullanmak istiyorsanız, resmi Python belgelerini kontrol edin. + +### Asenkron kodun diğer biçimleri + +Bu `async` ve `await` kullanimi oldukça yenidir. + +Ancak asenkron kodla çalışmayı çok daha kolay hale getirir. + +Aynı sözdizimi (hemen hemen aynı) son zamanlarda JavaScript'in modern sürümlerine de dahil edildi (Tarayıcı ve NodeJS'de). + +Ancak bundan önce, asenkron kodu işlemek oldukça karmaşık ve zordu. + +Python'un önceki sürümlerinde, threadlerı veya Gevent kullanıyor olabilirdin. Ancak kodu anlamak, hata ayıklamak ve düşünmek çok daha karmaşık olurdu. + +NodeJS / Browser JavaScript'in önceki sürümlerinde, "callback" kullanırdınız. Bu da callbacks cehennemine yol açar. + +## Coroutine'ler + +**Coroutine**, bir `async def` fonksiyonu tarafından döndürülen değer için çok süslü bir terimdir. Python bunun bir fonksiyon gibi bir noktada başlayıp biteceğini bilir, ancak içinde bir `await` olduğunda dahili olarak da duraklatılabilir ⏸. + +Ancak, `async` ve `await` ile asenkron kod kullanmanın tüm bu işlevselliği, çoğu zaman "Coroutine" kullanmak olarak adlandırılır. Go'nun ana özelliği olan "Goroutines" ile karşılaştırılabilir. + +## Sonuç + +Aynı ifadeyi yukarıdan görelim: + +> Python'ın modern sürümleri, **"async" ve "await"** sözdizimi ile birlikte **"coroutines"** adlı bir özelliği kullanan **"asenkron kod"** desteğine sahiptir. + +Şimdi daha mantıklı gelmeli. ✨ + +FastAPI'ye (Starlette aracılığıyla) güç veren ve bu kadar etkileyici bir performansa sahip olmasını sağlayan şey budur. + +## Çok Teknik Detaylar + +/// warning + +Muhtemelen burayı atlayabilirsiniz. + +Bunlar, **FastAPI**'nin altta nasıl çalıştığına dair çok teknik ayrıntılardır. + +Biraz teknik bilginiz varsa (co-routines, threads, blocking, vb)ve FastAPI'nin "async def" ile normal "def" arasındaki farkı nasıl işlediğini merak ediyorsanız, devam edin. + +/// + +### Path fonksiyonu + +"async def" yerine normal "def" ile bir *yol işlem işlevi* bildirdiğinizde, doğrudan çağrılmak yerine (sunucuyu bloke edeceğinden) daha sonra beklenen harici bir iş parçacığı havuzunda çalıştırılır. + +Yukarıda açıklanan şekilde çalışmayan başka bir asenkron framework'den geliyorsanız ve küçük bir performans kazancı (yaklaşık 100 nanosaniye) için "def" ile *path fonksiyonu* tanımlamaya alışkınsanız, **FastAPI**'de tam tersi olacağını unutmayın. Bu durumlarda, *path fonksiyonu* G/Ç engelleyen durum oluşturmadıkça "async def" kullanmak daha iyidir. + +Yine de, her iki durumda da, **FastAPI**'nin önceki frameworkden [hala daha hızlı](index.md#performans){.internal-link target=_blank} (veya en azından karşılaştırılabilir) olma olasılığı vardır. + +### Bagımlılıklar + +Aynısı bağımlılıklar için de geçerlidir. Bir bağımlılık, "async def" yerine standart bir "def" işleviyse, harici iş parçacığı havuzunda çalıştırılır. + +### Alt-bağımlıklar + +Birbirini gerektiren (fonksiyonlarin parametreleri olarak) birden fazla bağımlılık ve alt bağımlılıklarınız olabilir, bazıları 'async def' ve bazıları normal 'def' ile oluşturulabilir. Yine de normal 'def' ile oluşturulanlar, "await" kulanilmadan harici bir iş parçacığında (iş parçacığı havuzundan) çağrılır. + +### Diğer yardımcı fonksiyonlar + +Doğrudan çağırdığınız diğer herhangi bir yardımcı fonksiyonu, normal "def" veya "async def" ile tanimlayabilirsiniz. FastAPI onu çağırma şeklinizi etkilemez. + +Bu, FastAPI'nin sizin için çağırdığı fonksiyonlarin tam tersidir: *path fonksiyonu* ve bağımlılıklar. + +Yardımcı program fonksiyonunuz 'def' ile normal bir işlevse, bir iş parçacığı havuzunda değil doğrudan (kodunuzda yazdığınız gibi) çağrılır, işlev 'async def' ile oluşturulmuşsa çağırıldığı yerde 'await' ile beklemelisiniz. + +--- + +Yeniden, bunlar, onları aramaya geldiğinizde muhtemelen işinize yarayacak çok teknik ayrıntılardır. + +Aksi takdirde, yukarıdaki bölümdeki yönergeleri iyi bilmelisiniz: Aceleniz mi var?. diff --git a/docs/tr/docs/benchmarks.md b/docs/tr/docs/benchmarks.md index 1ce3c758f..eb5472869 100644 --- a/docs/tr/docs/benchmarks.md +++ b/docs/tr/docs/benchmarks.md @@ -1,34 +1,34 @@ # Kıyaslamalar -Bağımsız TechEmpower kıyaslamaları gösteriyor ki Uvicorn'la beraber çalışan **FastAPI** uygulamaları Python'un en hızlı frameworklerinden birisi , sadece Starlette ve Uvicorn'dan daha düşük sıralamada (FastAPI bu frameworklerin üzerine kurulu). (*) +Bağımsız TechEmpower kıyaslamaları gösteriyor ki en hızlı Python frameworklerinden birisi olan Uvicorn ile çalıştırılan **FastAPI** uygulamaları, sadece Starlette ve Uvicorn'dan daha düşük sıralamada (FastAPI bu frameworklerin üzerine kurulu) yer alıyor. (*) Fakat kıyaslamaları ve karşılaştırmaları incelerken şunları aklınızda bulundurmalısınız. -## Kıyaslamalar ve hız +## Kıyaslamalar ve Hız -Kıyaslamaları incelediğinizde, farklı özelliklere sahip birçok araçların eşdeğer olarak karşılaştırıldığını görmek yaygındır. +Kıyaslamaları incelediğinizde, farklı özelliklere sahip araçların eşdeğer olarak karşılaştırıldığını yaygın bir şekilde görebilirsiniz. -Özellikle, Uvicorn, Starlette ve FastAPI'ın birlikte karşılaştırıldığını görmek için (diğer birçok araç arasında). +Özellikle, (diğer birçok araç arasında) Uvicorn, Starlette ve FastAPI'ın birlikte karşılaştırıldığını görebilirsiniz. -Araç tarafından çözülen sorun ne kadar basitse, o kadar iyi performans alacaktır. Ve kıyaslamaların çoğu, araç tarafından sağlanan ek özellikleri test etmez. +Aracın çözdüğü problem ne kadar basitse, performansı o kadar iyi olacaktır. Ancak kıyaslamaların çoğu, aracın sağladığı ek özellikleri test etmez. Hiyerarşi şöyledir: * **Uvicorn**: bir ASGI sunucusu - * **Starlette**: (Uvicorn'u kullanır) bir web microframeworkü - * **FastAPI**: (Starlette'i kullanır) data validation vb. ile API'lar oluşturmak için çeşitli ek özelliklere sahip bir API frameworkü + * **Starlette**: (Uvicorn'u kullanır) bir web mikroframeworkü + * **FastAPI**: (Starlette'i kullanır) veri doğrulama vb. çeşitli ek özelliklere sahip, API oluşturmak için kullanılan bir API mikroframeworkü * **Uvicorn**: - * Sunucunun kendisi dışında ekstra bir kod içermediği için en iyi performansa sahip olacaktır - * Direkt olarak Uvicorn'da bir uygulama yazmazsınız. Bu, en azından Starlette tarafından sağlanan tüm kodu (veya **FastAPI**) az çok içermesi gerektiği anlamına gelir. Ve eğer bunu yaptıysanız, son uygulamanız bir framework kullanmak ve uygulama kodlarını ve bugları en aza indirmekle aynı ek yüke sahip olacaktır. + * Sunucunun kendisi dışında ekstra bir kod içermediği için en iyi performansa sahip olacaktır. + * Doğrudan Uvicorn ile bir uygulama yazmazsınız. Bu, yazdığınız kodun en azından Starlette tarafından sağlanan tüm kodu (veya **FastAPI**) az çok içermesi gerektiği anlamına gelir. Eğer bunu yaptıysanız, son uygulamanız bir framework kullanmak ve uygulama kodlarını ve hataları en aza indirmekle aynı ek yüke sahip olacaktır. * Eğer Uvicorn'u karşılaştırıyorsanız, Daphne, Hypercorn, uWSGI, vb. uygulama sunucuları ile karşılaştırın. * **Starlette**: - * Uvicorn'dan sonraki en iyi performansa sahip olacak. Aslında, Starlette çalışmak için Uvicorn'u kullanıyor. Dolayısıyla, muhtemelen daha fazla kod çalıştırmak zorunda kaldığında Uvicorn'dan sadece "daha yavaş" olabilir. - * Ancak routing based on paths ile vb. basit web uygulamaları oluşturmak için araçlar sağlar. - * Eğer Starlette'i karşılaştırıyorsanız, Sanic, Flask, Django, vb. frameworkler (veya microframeworkler) ile karşılaştırın. + * Uvicorn'dan sonraki en iyi performansa sahip olacaktır. İşin aslı, Starlette çalışmak için Uvicorn'u kullanıyor. Dolayısıyla, daha fazla kod çalıştırmaası gerektiğinden muhtemelen Uvicorn'dan sadece "daha yavaş" olabilir. + * Ancak yol bazlı yönlendirme vb. basit web uygulamaları oluşturmak için araçlar sağlar. + * Eğer Starlette'i karşılaştırıyorsanız, Sanic, Flask, Django, vb. frameworkler (veya mikroframeworkler) ile karşılaştırın. * **FastAPI**: - * Starlette'in Uvicorn'u kullandığı ve ondan daha hızlı olamayacağı gibi, **FastAPI** da Starlette'i kullanır, bu yüzden ondan daha hızlı olamaz. - * FastAPI, Starlette'e ek olarak daha fazla özellik sunar. Data validation ve serialization gibi API'lar oluştururken neredeyse ve her zaman ihtiyaç duyduğunuz özellikler. Ve bunu kullanarak, ücretsiz olarak otomatik dokümantasyon elde edersiniz (otomatik dokümantasyon çalışan uygulamalara ek yük getirmez, başlangıçta oluşturulur). - * FastAPI'ı kullanmadıysanız ve Starlette'i doğrudan kullandıysanız (veya başka bir araç, Sanic, Flask, Responder, vb.) tüm data validation'ı ve serialization'ı kendiniz sağlamanız gerekir. Dolayısıyla, son uygulamanız FastAPI kullanılarak oluşturulmuş gibi hâlâ aynı ek yüke sahip olacaktır. Çoğu durumda, uygulamalarda yazılan kodun büyük çoğunluğunu data validation ve serialization oluşturur. - * Dolayısıyla, FastAPI'ı kullanarak geliştirme süresinden, buglardan, kod satırlarından tasarruf edersiniz ve muhtemelen kullanmasaydınız aynı performansı (veya daha iyisini) elde edersiniz. (hepsini kodunuza uygulamak zorunda kalacağınız gibi) - * Eğer FastAPI'ı karşılaştırıyorsanız, Flask-apispec, NestJS, Molten, vb. gibi data validation, serialization ve dokümantasyon sağlayan bir web uygulaması frameworkü ile (veya araç setiyle) karşılaştırın. Entegre otomatik data validation, serialization ve dokümantasyon içeren frameworkler. + * Starlette'in Uvicorn'u kullandığı ve ondan daha hızlı olamayacağı gibi, **FastAPI**'da Starlette'i kullanır, dolayısıyla ondan daha hızlı olamaz. + * FastAPI, Starlette'e ek olarak daha fazla özellik sunar. Bunlar veri doğrulama ve dönüşümü gibi API'lar oluştururken neredeyse ve her zaman ihtiyaç duyduğunuz özelliklerdir. Ve bunu kullanarak, ücretsiz olarak otomatik dokümantasyon elde edersiniz (otomatik dokümantasyon çalışan uygulamalara ek yük getirmez, başlangıçta oluşturulur). + * FastAPI'ı kullanmadıysanız ve Starlette'i doğrudan kullandıysanız (veya başka bir araç, Sanic, Flask, Responder, vb.) tüm veri doğrulama ve dönüştürme araçlarını kendiniz geliştirmeniz gerekir. Dolayısıyla, son uygulamanız FastAPI kullanılarak oluşturulmuş gibi hâlâ aynı ek yüke sahip olacaktır. Çoğu durumda, uygulamalarda yazılan kodun büyük bir kısmını veri doğrulama ve dönüştürme kodları oluşturur. + * Dolayısıyla, FastAPI'ı kullanarak geliştirme süresinden, hatalardan, kod satırlarından tasarruf edersiniz ve kullanmadığınız durumda (birçok özelliği geliştirmek zorunda kalmakla birlikte) muhtemelen aynı performansı (veya daha iyisini) elde ederdiniz. + * Eğer FastAPI'ı karşılaştırıyorsanız, Flask-apispec, NestJS, Molten, vb. gibi veri doğrulama, dönüştürme ve dokümantasyon sağlayan bir web uygulaması frameworkü ile (veya araç setiyle) karşılaştırın. diff --git a/docs/tr/docs/deployment/cloud.md b/docs/tr/docs/deployment/cloud.md new file mode 100644 index 000000000..5639567d4 --- /dev/null +++ b/docs/tr/docs/deployment/cloud.md @@ -0,0 +1,17 @@ +# FastAPI Uygulamasını Bulut Sağlayıcılar Üzerinde Yayınlama + +FastAPI uygulamasını yayınlamak için hemen hemen **herhangi bir bulut sağlayıcıyı** kullanabilirsiniz. + +Büyük bulut sağlayıcıların çoğu FastAPI uygulamasını yayınlamak için kılavuzlara sahiptir. + +## Bulut Sağlayıcılar - Sponsorlar + +Bazı bulut sağlayıcılar ✨ [**FastAPI destekçileridir**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, bu FastAPI ve **ekosisteminin** sürekli ve sağlıklı bir şekilde **gelişmesini** sağlar. + +Ayrıca, size **iyi servisler** sağlamakla kalmayıp, **iyi ve sağlıklı bir framework** olan FastAPI'a bağlılıklarını gösterir. + +Bu hizmetleri denemek ve kılavuzlarını incelemek isteyebilirsiniz: + +* Platform.sh +* Porter +* Coherence diff --git a/docs/tr/docs/deployment/index.md b/docs/tr/docs/deployment/index.md new file mode 100644 index 000000000..e03bb4ee0 --- /dev/null +++ b/docs/tr/docs/deployment/index.md @@ -0,0 +1,21 @@ +# Deployment (Yayınlama) + +**FastAPI** uygulamasını deploy etmek oldukça kolaydır. + +## Deployment Ne Anlama Gelir? + +Bir uygulamayı **deploy** etmek (yayınlamak), uygulamayı **kullanıcılara erişilebilir hale getirmek** için gerekli adımları gerçekleştirmek anlamına gelir. + +Bir **Web API** için bu süreç normalde uygulamayı **uzak bir makineye** yerleştirmeyi, iyi performans, kararlılık vb. özellikler sağlayan bir **sunucu programı** ile **kullanıcılarınızın** uygulamaya etkili ve kesintisiz bir şekilde **erişebilmesini** kapsar. + +Bu, kodu sürekli olarak değiştirdiğiniz, hata alıp hata giderdiğiniz, geliştirme sunucusunu durdurup yeniden başlattığınız vb. **geliştirme** aşamalarının tam tersidir. + +## Deployment Stratejileri + +Kullanım durumunuza ve kullandığınız araçlara bağlı olarak bir kaç farklı yol izleyebilirsiniz. + +Bir dizi araç kombinasyonunu kullanarak kendiniz **bir sunucu yayınlayabilirsiniz**, yayınlama sürecinin bir kısmını sizin için gerçekleştiren bir **bulut hizmeti** veya diğer olası seçenekleri kullanabilirsiniz. + +**FastAPI** uygulamasını yayınlarken aklınızda bulundurmanız gereken ana kavramlardan bazılarını size göstereceğim (ancak bunların çoğu diğer web uygulamaları için de geçerlidir). + +Sonraki bölümlerde akılda tutulması gereken diğer ayrıntıları ve yayınlama tekniklerinden bazılarını göreceksiniz. ✨ diff --git a/docs/tr/docs/external-links.md b/docs/tr/docs/external-links.md deleted file mode 100644 index 78eaf1729..000000000 --- a/docs/tr/docs/external-links.md +++ /dev/null @@ -1,33 +0,0 @@ -# Harici Bağlantılar ve Makaleler - -**FastAPI** sürekli büyüyen harika bir topluluğa sahiptir. - -**FastAPI** ile alakalı birçok yazı, makale, araç ve proje bulunmaktadır. - -Bunlardan bazılarının tamamlanmamış bir listesi aşağıda bulunmaktadır. - -!!! tip "İpucu" - Eğer **FastAPI** ile alakalı henüz burada listelenmemiş bir makale, proje, araç veya başka bir şeyiniz varsa, bunu eklediğiniz bir Pull Request oluşturabilirsiniz. - -{% for section_name, section_content in external_links.items() %} - -## {{ section_name }} - -{% for lang_name, lang_content in section_content.items() %} - -### {{ lang_name }} - -{% for item in lang_content %} - -* {{ item.title }} by {{ item.author }}. - -{% endfor %} -{% endfor %} -{% endfor %} - -## Projeler - -`fastapi` konulu en son GitHub projeleri: - -
-
diff --git a/docs/tr/docs/fastapi-people.md b/docs/tr/docs/fastapi-people.md deleted file mode 100644 index 3e459036a..000000000 --- a/docs/tr/docs/fastapi-people.md +++ /dev/null @@ -1,178 +0,0 @@ -# FastAPI Topluluğu - -FastAPI, her kökenden insanı ağırlayan harika bir topluluğa sahip. - -## Yazan - Geliştiren - -Hey! 👋 - -İşte bu benim: - -{% if people %} -
-{% for user in people.maintainers %} - -
@{{ user.login }}
Answers: {{ user.answers }}
Pull Requests: {{ user.prs }}
-{% endfor %} - -
-{% endif %} - -Ben **FastAPI** 'nin yazarı ve geliştiricisiyim. Bununla ilgili daha fazla bilgiyi şurada okuyabilirsiniz: - [FastAPI yardım - yardım al - Yazar ile iletişime geç](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. - -... Burada size harika FastAPI topluluğunu göstermek istiyorum. - ---- - -**FastAPI** topluluğundan destek alıyor. Ve katkıda bulunanları vurgulamak istiyorum. - -İşte o mükemmel insanlar: - -* [GitHubdaki sorunları (issues) çözmelerinde diğerlerine yardım et](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}. -* [Pull Requests oluşturun](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. -* Pull Requests 'leri gözden geçirin, [özelliklede çevirileri](contributing.md#translations){.internal-link target=_blank}. - -Onlara bir alkış. 👏 🙇 - -## Geçen ayın en aktif kullanıcıları - -Bunlar geçen ay boyunca [GitHub' da başkalarına sorunlarında (issues) en çok yardımcı olan ](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank} kullanıcılar ☕ - -{% if people %} -
-{% for user in people.last_month_active %} - -
@{{ user.login }}
Issues replied: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Uzmanlar - -İşte **FastAPI Uzmanları**. 🤓 - -Bunlar *tüm zamanlar boyunca* [GitHub' da başkalarına sorunlarında (issues) en çok yardımcı olan](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank} kullanıcılar. - -Başkalarına yardım ederek uzman olduklarını kanıtladılar. ✨ - -{% if people %} -
-{% for user in people.experts %} - -
@{{ user.login }}
Issues replied: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## En fazla katkıda bulunanlar - -işte **En fazla katkıda bulunanlar**. 👷 - -Bu kullanıcılar en çok [Pull Requests oluşturan](help-fastapi.md#create-a-pull-request){.internal-link target=_blank} ve onu kaynak koduna *birleştirenler*. - -Kaynak koduna, belgelere, çevirilere vb. katkıda bulundular. 📦 - -{% if people %} -
-{% for user in people.top_contributors %} - -
@{{ user.login }}
Pull Requests: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -Çok fazla katkıda bulunan var (binden fazla), hepsini şurda görebilirsin: FastAPI GitHub Katkıda Bulunanlar. 👷 - -## En fazla inceleme yapanlar - -İşte **En fazla inceleme yapanlar**. 🕵️ - -### Çeviri için İncelemeler - -Yalnızca birkaç dil konuşabiliyorum (ve çok da iyi değilim 😅). Bu yüzden döküman çevirilerini [**onaylama yetkisi**](contributing.md#translations){.internal-link target=_blank} siz inceleyenlere aittir. Sizler olmadan diğer birkaç dilde dokümantasyon olmazdı. - ---- - -**En fazla inceleme yapanlar** 🕵️ kodun, belgelerin ve özellikle **çevirilerin** kalitesini sağlamak için diğerlerinden daha fazla pull requests incelemiştir. - -{% if people %} -
-{% for user in people.top_reviewers %} - -
@{{ user.login }}
Reviews: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Sponsorlar - -işte **Sponsorlarımız**. 😎 - -**FastAPI** ve diğer projelerde çalışmamı destekliyorlar, özellikle de GitHub Sponsorları. - -### Altın Sponsorlar - -{% if sponsors %} -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -### Gümüş Sponsorlar - -{% if sponsors %} -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -### Bronz Sponsorlar - -{% if sponsors %} -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -### Bireysel Sponsorlar - -{% if people %} -{% if people.sponsors_50 %} - -
-{% for user in people.sponsors_50 %} - - -{% endfor %} - -
- -{% endif %} -{% endif %} - -{% if people %} -
-{% for user in people.sponsors %} - - -{% endfor %} - -
-{% endif %} - -## Veriler hakkında - Teknik detaylar - -Bu sayfanın temel amacı, topluluğun başkalarına yardım etme çabasını vurgulamaktır. - -Özellikle normalde daha az görünür olan ve çoğu durumda daha zahmetli olan, diğerlerine sorunlar konusunda yardımcı olmak ve pull requests'leri gözden geçirmek gibi çabalar dahil. - -Veriler ayda bir hesaplanır, işte kaynak kodu okuyabilirsin :source code here. - -Burada sponsorların katkılarını da tekrardan vurgulamak isterim. - -Ayrıca algoritmayı, bölümleri, eşikleri vb. güncelleme hakkımı da saklı tutarım (her ihtimale karşı 🤷). diff --git a/docs/tr/docs/features.md b/docs/tr/docs/features.md index 8b143ffe7..5d40b1086 100644 --- a/docs/tr/docs/features.md +++ b/docs/tr/docs/features.md @@ -67,10 +67,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` şu anlama geliyor: +/// info - Key-Value çiftini direkt olarak `second_user_data` dictionarysine kaydet , yaptığın şey buna eşit olacak: `User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` şu anlama geliyor: + +Key-Value çiftini direkt olarak `second_user_data` dictionarysine kaydet , yaptığın şey buna eşit olacak: `User(id=4, name="Mary", joined="2018-11-30")` + +/// ### Editor desteği @@ -182,7 +185,7 @@ Bütün entegrasyonlar kullanımı kolay olmak üzere (zorunluluklar ile beraber ## Pydantic özellikleri -**FastAPI** ile Pydantic tamamiyle uyumlu ve üzerine kurulu. Yani FastAPI üzerine ekleme yapacağınız herhangi bir Pydantic kodu da çalışacaktır. +**FastAPI** ile Pydantic tamamiyle uyumlu ve üzerine kurulu. Yani FastAPI üzerine ekleme yapacağınız herhangi bir Pydantic kodu da çalışacaktır. Bunlara Pydantic üzerine kurulu ORM databaseler ve , ODM kütüphaneler de dahil olmak üzere. @@ -197,8 +200,6 @@ Aynı şekilde, databaseden gelen objeyi de **direkt olarak isteğe** de tamamiy * Eğer Python typelarını nasıl kullanacağını biliyorsan Pydantic kullanmayı da biliyorsundur. * Kullandığın geliştirme araçları ile iyi çalışır **IDE/linter/brain**: * Pydantic'in veri yapıları aslında sadece senin tanımladığın classlar; Bu yüzden doğrulanmış dataların ile otomatik tamamlama, linting ve mypy'ı kullanarak sorunsuz bir şekilde çalışabilirsin -* **Hızlı**: - * Benchmarklarda, Pydantic'in diğer bütün test edilmiş bütün kütüphanelerden daha hızlı. * **En kompleks** yapıları bile doğrula: * Hiyerarşik Pydantic modellerinin kullanımı ile beraber, Python `typing`’s `List` and `Dict`, vs gibi şeyleri doğrula. * Doğrulayıcılar en kompleks data şemalarının bile temiz ve kolay bir şekilde tanımlanmasına izin veriyor, ve hepsi JSON şeması olarak dokümante ediliyor diff --git a/docs/tr/docs/history-design-future.md b/docs/tr/docs/history-design-future.md new file mode 100644 index 000000000..8b2662bc3 --- /dev/null +++ b/docs/tr/docs/history-design-future.md @@ -0,0 +1,79 @@ +# Geçmişi, Tasarımı ve Geleceği + +Bir süre önce, bir **FastAPI** kullanıcısı sordu: + +> Bu projenin geçmişi nedir? Birkaç hafta içinde hiçbir yerden harika bir şeye dönüşmüş gibi görünüyor [...] + +İşte o geçmişin bir kısmı. + +## Alternatifler + +Bir süredir karmaşık gereksinimlere sahip API'lar oluşturuyor (Makine Öğrenimi, dağıtık sistemler, asenkron işler, NoSQL veritabanları vb.) ve farklı geliştirici ekiplerini yönetiyorum. + +Bu süreçte birçok alternatifi araştırmak, test etmek ve kullanmak zorunda kaldım. + +**FastAPI**'ın geçmişi, büyük ölçüde önceden geliştirilen araçların geçmişini kapsıyor. + +[Alternatifler](alternatives.md){.internal-link target=_blank} bölümünde belirtildiği gibi: + +
+ +Başkalarının daha önceki çalışmaları olmasaydı, **FastAPI** var olmazdı. + +Geçmişte oluşturulan pek çok araç **FastAPI**'a ilham kaynağı olmuştur. + +Yıllardır yeni bir framework oluşturmaktan kaçınıyordum. Başlangıçta **FastAPI**'ın çözdüğü sorunları çözebilmek için pek çok farklı framework, eklenti ve araç kullanmayı denedim. + +Ancak bir noktada, geçmişteki diğer araçlardan en iyi fikirleri alarak bütün bu çözümleri kapsayan, ayrıca bütün bunları Python'ın daha önce mevcut olmayan özelliklerini (Python 3.6+ ile gelen tip belirteçleri) kullanarak yapan bir şey üretmekten başka bir seçenek kalmamıştı. + +
+ +## Araştırma + +Önceki alternatifleri kullanarak hepsinden bir şeyler öğrenip, fikirler alıp, bunları kendim ve çalıştığım geliştirici ekipler için en iyi şekilde birleştirebilme şansım oldu. + +Mesela, ideal olarak standart Python tip belirteçlerine dayanması gerektiği açıktı. + +Ayrıca, en iyi yaklaşım zaten mevcut olan standartları kullanmaktı. + +Sonuç olarak, **FastAPI**'ı kodlamaya başlamadan önce, birkaç ay boyunca OpenAPI, JSON Schema, OAuth2 ve benzerlerinin tanımlamalarını inceledim. İlişkilerini, örtüştükleri noktaları ve farklılıklarını anlamaya çalıştım. + +## Tasarım + +Sonrasında, (**FastAPI** kullanan bir geliştirici olarak) sahip olmak istediğim "API"ı tasarlamak için biraz zaman harcadım. + +Çeşitli fikirleri en popüler Python editörlerinde test ettim: PyCharm, VS Code, Jedi tabanlı editörler. + +Bu test, en son Python Developer Survey'ine göre, kullanıcıların yaklaşık %80'inin kullandığı editörleri kapsıyor. + +Bu da demek oluyor ki **FastAPI**, Python geliştiricilerinin %80'inin kullandığı editörlerle test edildi. Ve diğer editörlerin çoğu benzer şekilde çalıştığından, avantajları neredeyse tüm editörlerde çalışacaktır. + +Bu şekilde, kod tekrarını mümkün olduğunca azaltmak, her yerde otomatik tamamlama, tip ve hata kontrollerine sahip olmak için en iyi yolları bulabildim. + +Hepsi, tüm geliştiriciler için en iyi geliştirme deneyimini sağlayacak şekilde. + +## Gereksinimler + +Çeşitli alternatifleri test ettikten sonra, avantajlarından dolayı **Pydantic**'i kullanmaya karar verdim. + +Sonra, JSON Schema ile tamamen uyumlu olmasını sağlamak, kısıtlama bildirimlerini tanımlamanın farklı yollarını desteklemek ve birkaç editördeki testlere dayanarak editör desteğini (tip kontrolleri, otomatik tamamlama) geliştirmek için katkıda bulundum. + +Geliştirme sırasında, diğer ana gereksinim olan **Starlette**'e de katkıda bulundum. + +## Geliştirme + +**FastAPI**'ı oluşturmaya başladığımda, parçaların çoğu zaten yerindeydi, tasarım tanımlanmıştı, gereksinimler ve araçlar hazırdı, standartlar ve tanımlamalar hakkındaki bilgi net ve tazeydi. + +## Gelecek + +Şimdiye kadar, **FastAPI**'ın fikirleriyle birçok kişiye faydalı olduğu apaçık ortada. + +Birçok kullanım durumuna daha iyi uyduğu için, önceki alternatiflerin yerine seçiliyor. + +Ben ve ekibim dahil, birçok geliştirici ve ekip projelerinde **FastAPI**'ya bağlı. + +Tabi, geliştirilecek birçok özellik ve iyileştirme mevcut. + +**FastAPI**'ın önünde harika bir gelecek var. + +[Yardımlarınız](help-fastapi.md){.internal-link target=_blank} çok değerlidir. diff --git a/docs/tr/docs/how-to/general.md b/docs/tr/docs/how-to/general.md new file mode 100644 index 000000000..cbfa7beb2 --- /dev/null +++ b/docs/tr/docs/how-to/general.md @@ -0,0 +1,39 @@ +# Genel - Nasıl Yapılır - Tarifler + +Bu sayfada genel ve sıkça sorulan sorular için dokümantasyonun diğer sayfalarına yönlendirmeler bulunmaktadır. + +## Veri Filtreleme - Güvenlik + +Döndürmeniz gereken veriden fazlasını döndürmediğinizden emin olmak için, [Tutorial - Response Model - Return Type](../tutorial/response-model.md){.internal-link target=_blank} sayfasını okuyun. + +## Dokümantasyon Etiketleri - OpenAPI + +*Yol operasyonlarınıza* etiketler ekleyerek dokümantasyon arayüzünde gruplar halinde görünmesini sağlamak için, [Tutorial - Path Operation Configurations - Tags](../tutorial/path-operation-configuration.md#tags){.internal-link target=_blank} sayfasını okuyun. + +## Dokümantasyon Özeti ve Açıklaması - OpenAPI + +*Yol operasyonlarınıza* özet ve açıklama ekleyip dokümantasyon arayüzünde görünmesini sağlamak için, [Tutorial - Path Operation Configurations - Summary and Description](../tutorial/path-operation-configuration.md#summary-and-description){.internal-link target=_blank} sayfasını okuyun. + +## Yanıt Açıklaması Dokümantasyonu - OpenAPI + +Dokümantasyon arayüzünde yer alan yanıt açıklamasını tanımlamak için, [Tutorial - Path Operation Configurations - Response description](../tutorial/path-operation-configuration.md#response-description){.internal-link target=_blank} sayfasını okuyun. + +## *Yol Operasyonunu* Kullanımdan Kaldırma - OpenAPI + +Bir *yol işlemi*ni kullanımdan kaldırmak ve bunu dokümantasyon arayüzünde göstermek için, [Tutorial - Path Operation Configurations - Deprecation](../tutorial/path-operation-configuration.md#deprecate-a-path-operation){.internal-link target=_blank} sayfasını okuyun. + +## Herhangi Bir Veriyi JSON Uyumlu Hale Getirme + +Herhangi bir veriyi JSON uyumlu hale getirmek için, [Tutorial - JSON Compatible Encoder](../tutorial/encoder.md){.internal-link target=_blank} sayfasını okuyun. + +## OpenAPI Meta Verileri - Dokümantasyon + +OpenAPI şemanıza lisans, sürüm, iletişim vb. meta veriler eklemek için, [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md){.internal-link target=_blank} sayfasını okuyun. + +## OpenAPI Bağlantı Özelleştirme + +OpenAPI bağlantısını özelleştirmek (veya kaldırmak) için, [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md#openapi-url){.internal-link target=_blank} sayfasını okuyun. + +## OpenAPI Dokümantasyon Bağlantıları + +Dokümantasyonu arayüzünde kullanılan bağlantıları güncellemek için, [Tutorial - Metadata and Docs URLs](../tutorial/metadata.md#docs-urls){.internal-link target=_blank} sayfasını okuyun. diff --git a/docs/tr/docs/how-to/index.md b/docs/tr/docs/how-to/index.md new file mode 100644 index 000000000..26dd9026c --- /dev/null +++ b/docs/tr/docs/how-to/index.md @@ -0,0 +1,13 @@ +# Nasıl Yapılır - Tarifler + +Burada çeşitli konular hakkında farklı tarifler veya "nasıl yapılır" kılavuzları yer alıyor. + +Bu fikirlerin büyük bir kısmı aşağı yukarı **bağımsız** olacaktır, çoğu durumda bunları sadece **projenize** hitap ediyorsa incelemelisiniz. + +Projeniz için ilginç ve yararlı görünen bir şey varsa devam edin ve inceleyin, aksi halde bunları atlayabilirsiniz. + +/// tip | İpucu + +**FastAPI**'ı düzgün (ve önerilen) şekilde öğrenmek istiyorsanız [Öğretici - Kullanıcı Rehberi](../tutorial/index.md){.internal-link target=_blank}'ni bölüm bölüm okuyun. + +/// diff --git a/docs/tr/docs/index.md b/docs/tr/docs/index.md index ac8830880..f666e2d06 100644 --- a/docs/tr/docs/index.md +++ b/docs/tr/docs/index.md @@ -1,3 +1,9 @@ +# FastAPI + + +

FastAPI

@@ -5,11 +11,11 @@ FastAPI framework, yüksek performanslı, öğrenmesi oldukça kolay, kodlaması hızlı, kullanıma hazır

- - Test + + Test - - Coverage + + Coverage Package version @@ -23,11 +29,11 @@ **Dokümantasyon**: https://fastapi.tiangolo.com -**Kaynak Kod**: https://github.com/tiangolo/fastapi +**Kaynak Kod**: https://github.com/fastapi/fastapi --- -FastAPI, Python 3.8+'nin standart tip belirteçlerine dayalı, modern ve hızlı (yüksek performanslı) API'lar oluşturmak için kullanılabilecek web framework'tür. +FastAPI, Python 'nin standart tip belirteçlerine dayalı, modern ve hızlı (yüksek performanslı) API'lar oluşturmak için kullanılabilecek web framework'tür. Temel özellikleri şunlardır: @@ -63,7 +69,7 @@ Temel özellikleri şunlardır: "_[...] Bugünlerde **FastAPI**'ı çok fazla kullanıyorum. [...] Aslında bunu ekibimin **Microsoft'taki Machine Learning servislerinin** tamamında kullanmayı planlıyorum. Bunlardan bazıları **Windows**'un ana ürünlerine ve **Office** ürünlerine entegre ediliyor._" -

Kabir Khan - Microsoft (ref)
+
Kabir Khan - Microsoft (ref)
--- @@ -115,12 +121,10 @@ Eğer API yerine, terminalde kullanılmak üzere bir Starlette. -* Data tarafı için Pydantic. +* Data tarafı için Pydantic. ## Kurulum @@ -134,7 +138,7 @@ $ pip install fastapi -Uygulamamızı kullanılabilir hale getirmek için Uvicorn ya da Hypercorn gibi bir ASGI sunucusuna ihtiyacımız olacak. +Uygulamamızı kullanılabilir hale getirmek için Uvicorn ya da Hypercorn gibi bir ASGI sunucusuna ihtiyacımız olacak.
@@ -331,7 +335,7 @@ Bu işlemi standart modern Python tipleriyle yapıyoruz. Yeni bir sözdizimi yapısını, bir kütüphane özel metod veya sınıfları öğrenmeye gerek yoktur. -Hepsi sadece **Python 3.8+** standartlarına dayalıdır. +Hepsi sadece **Python** standartlarına dayalıdır. Örnek olarak, `int` tanımlamak için: @@ -445,7 +449,7 @@ Daha fazla bilgi için, bu bölüme bir göz at email_validator - email doğrulaması için. +* email-validator - email doğrulaması için. * pydantic-settings - ayar yönetimi için. * pydantic-extra-types - Pydantic ile birlikte kullanılabilecek ek tipler için. @@ -453,15 +457,15 @@ Starlette tarafında kullanılan: * httpx - Eğer `TestClient` yapısını kullanacaksanız gereklidir. * jinja2 - Eğer varsayılan template konfigürasyonunu kullanacaksanız gereklidir. -* python-multipart - Eğer `request.form()` ile form dönüşümü desteğini kullanacaksanız gereklidir. +* python-multipart - Eğer `request.form()` ile form dönüşümü desteğini kullanacaksanız gereklidir. * itsdangerous - `SessionMiddleware` desteği için gerekli. * pyyaml - `SchemaGenerator` desteği için gerekli (Muhtemelen FastAPI kullanırken ihtiyacınız olmaz). -* ujson - `UJSONResponse` kullanacaksanız gerekli. Hem FastAPI hem de Starlette tarafından kullanılan: * uvicorn - oluşturduğumuz uygulamayı servis edecek web sunucusu görevini üstlenir. * orjson - `ORJSONResponse` kullanacaksanız gereklidir. +* ujson - `UJSONResponse` kullanacaksanız gerekli. Bunların hepsini `pip install fastapi[all]` ile yükleyebilirsin. diff --git a/docs/tr/docs/learn/index.md b/docs/tr/docs/learn/index.md new file mode 100644 index 000000000..52e3aa54d --- /dev/null +++ b/docs/tr/docs/learn/index.md @@ -0,0 +1,5 @@ +# Öğren + +**FastAPI** öğrenmek için giriş bölümleri ve öğreticiler burada yer alıyor. + +Burayı, bir **kitap**, bir **kurs**, ve FastAPI öğrenmenin **resmi** ve önerilen yolu olarak düşünülebilirsiniz. 😎 diff --git a/docs/tr/docs/newsletter.md b/docs/tr/docs/newsletter.md deleted file mode 100644 index 22ca1b1e2..000000000 --- a/docs/tr/docs/newsletter.md +++ /dev/null @@ -1,5 +0,0 @@ -# FastAPI ve Arkadaşları Bülteni - - - - diff --git a/docs/tr/docs/project-generation.md b/docs/tr/docs/project-generation.md new file mode 100644 index 000000000..c9dc24acc --- /dev/null +++ b/docs/tr/docs/project-generation.md @@ -0,0 +1,84 @@ +# Proje oluşturma - Şablonlar + +Başlamak için bir proje oluşturucu kullanabilirsiniz, çünkü sizin için önceden yapılmış birçok başlangıç ​​kurulumu, güvenlik, veritabanı ve temel API endpoinlerini içerir. + +Bir proje oluşturucu, her zaman kendi ihtiyaçlarınıza göre güncellemeniz ve uyarlamanız gereken esnek bir kuruluma sahip olacaktır, ancak bu, projeniz için iyi bir başlangıç ​​noktası olabilir. + +## Full Stack FastAPI PostgreSQL + +GitHub: https://github.com/tiangolo/full-stack-fastapi-postgresql + +### Full Stack FastAPI PostgreSQL - Özellikler + +* Full **Docker** entegrasyonu (Docker based). +* Docker Swarm Mode ile deployment. +* **Docker Compose** entegrasyonu ve lokal geliştirme için optimizasyon. +* Uvicorn ve Gunicorn ile **Production ready** Python web server'ı. +* Python **FastAPI** backend: + * **Hızlı**: **NodeJS** ve **Go** ile eşit, çok yüksek performans (Starlette ve Pydantic'e teşekkürler). + * **Sezgisel**: Editor desteğı. Otomatik tamamlama. Daha az debugging. + * **Kolay**: Kolay öğrenip kolay kullanmak için tasarlandı. Daha az döküman okuma daha çok iş. + * **Kısa**: Minimum kod tekrarı. Her parametre bildiriminde birden çok özellik. + * **Güçlü**: Production-ready. Otomatik interaktif dökümantasyon. + * **Standartlara dayalı**: API'ler için açık standartlara dayanır (ve tamamen uyumludur): OpenAPI ve JSON Şeması. + * **Birçok diger özelliği** dahili otomatik doğrulama, serialization, interaktif dokümantasyon, OAuth2 JWT token ile authentication, vb. +* **Güvenli şifreleme** . +* **JWT token** kimlik doğrulama. +* **SQLAlchemy** models (Flask dan bağımsızdır. Celery worker'ları ile kullanılabilir). +* Kullanıcılar için temel başlangıç ​​modeli (gerektiği gibi değiştirin ve kaldırın). +* **Alembic** migration. +* **CORS** (Cross Origin Resource Sharing). +* **Celery** worker'ları ile backend içerisinden seçilen işleri çalıştırabilirsiniz. +* **Pytest**'e dayalı, Docker ile entegre REST backend testleri ile veritabanından bağımsız olarak tam API etkileşimini test edebilirsiniz. Docker'da çalıştığı için her seferinde sıfırdan yeni bir veri deposu oluşturabilir (böylece ElasticSearch, MongoDB, CouchDB veya ne istersen kullanabilirsin ve sadece API'nin çalışıp çalışmadığını test edebilirsin). +* Atom Hydrogen veya Visual Studio Code Jupyter gibi uzantılarla uzaktan veya Docker içi geliştirme için **Jupyter Çekirdekleri** ile kolay Python entegrasyonu. +* **Vue** ile frontend: + * Vue CLI ile oluşturulmuş. + * Dahili **JWT kimlik doğrulama**. + * Dahili Login. + * Login sonrası, Kontrol paneli. + * Kullanıcı oluşturma ve düzenleme kontrol paneli + * Kendi kendine kullanıcı sürümü. + * **Vuex**. + * **Vue-router**. + * **Vuetify** güzel material design kompanentleri için. + * **TypeScript**. + * **Nginx** tabanlı Docker sunucusu (Vue-router için yapılandırılmış). + * Docker ile multi-stage yapı, böylece kodu derlemeniz, kaydetmeniz veya işlemeniz gerekmez. + * Derleme zamanında Frontend testi (devre dışı bırakılabilir). + * Mümkün olduğu kadar modüler yapılmıştır, bu nedenle kutudan çıktığı gibi çalışır, ancak Vue CLI ile yeniden oluşturabilir veya ihtiyaç duyduğunuz şekilde oluşturabilir ve istediğinizi yeniden kullanabilirsiniz. +* **PGAdmin** PostgreSQL database admin tool'u, PHPMyAdmin ve MySQL ile kolayca değiştirilebilir. +* **Flower** ile Celery job'larını monitörleme. +* **Traefik** ile backend ve frontend arasında yük dengeleme, böylece her ikisini de aynı domain altında, path ile ayrılmış, ancak farklı kapsayıcılar tarafından sunulabilirsiniz. +* Let's Encrypt **HTTPS** sertifikalarının otomatik oluşturulması dahil olmak üzere Traefik entegrasyonu. +* GitLab **CI** (sürekli entegrasyon), backend ve frontend testi dahil. + +## Full Stack FastAPI Couchbase + +GitHub: https://github.com/tiangolo/full-stack-fastapi-couchbase + +⚠️ **UYARI** ⚠️ + +Sıfırdan bir projeye başlıyorsanız alternatiflerine bakın. + +Örneğin, Full Stack FastAPI PostgreSQL daha iyi bir alternatif olabilir, aktif olarak geliştiriliyor ve kullanılıyor. Ve yeni özellik ve ilerlemelere sahip. + +İsterseniz Couchbase tabanlı generator'ı kullanmakta özgürsünüz, hala iyi çalışıyor olmalı ve onunla oluşturulmuş bir projeniz varsa bu da sorun değil (ve muhtemelen zaten ihtiyaçlarınıza göre güncellediniz). + +Bununla ilgili daha fazla bilgiyi repo belgelerinde okuyabilirsiniz. + +## Full Stack FastAPI MongoDB + +... müsaitliğime ve diğer faktörlere bağlı olarak daha sonra gelebilir. 😅 🎉 + +## Machine Learning modelleri, spaCy ve FastAPI + +GitHub: https://github.com/microsoft/cookiecutter-spacy-fastapi + +### Machine Learning modelleri, spaCy ve FastAPI - Features + +* **spaCy** NER model entegrasyonu. +* **Azure Cognitive Search** yerleşik istek biçimi. +* Uvicorn ve Gunicorn ile **Production ready** Python web server'ı. +* Dahili **Azure DevOps** Kubernetes (AKS) CI/CD deployment. +* **Multilingual**, Proje kurulumu sırasında spaCy'nin yerleşik dillerinden birini kolayca seçin. +* **Esnetilebilir** diğer frameworkler (Pytorch, Tensorflow) ile de çalışır sadece spaCy değil. diff --git a/docs/tr/docs/python-types.md b/docs/tr/docs/python-types.md index 3b9ab9050..b44aa3b9d 100644 --- a/docs/tr/docs/python-types.md +++ b/docs/tr/docs/python-types.md @@ -12,16 +12,18 @@ Bu pythonda tip belirteçleri için **hızlı bir başlangıç / bilgi tazeleme **FastAPI** kullanmayacak olsanız bile tür belirteçleri hakkında bilgi edinmenizde fayda var. -!!! not - Python uzmanıysanız ve tip belirteçleri ilgili her şeyi zaten biliyorsanız, sonraki bölüme geçin. +/// note | Not + +Python uzmanıysanız ve tip belirteçleri ilgili her şeyi zaten biliyorsanız, sonraki bölüme geçin. + +/// ## Motivasyon Basit bir örnek ile başlayalım: -```Python -{!../../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} + Programın çıktısı: @@ -35,9 +37,8 @@ Fonksiyon sırayla şunları yapar: * `title()` ile değişkenlerin ilk karakterlerini büyütür. * Değişkenleri aralarında bir boşlukla beraber Birleştirir. -```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### Düzenle @@ -79,9 +80,8 @@ Bu kadar. İşte bunlar "tip belirteçleri": -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + Bu, aşağıdaki gibi varsayılan değerleri bildirmekle aynı şey değildir: @@ -109,9 +109,8 @@ Aradığınızı bulana kadar seçenekleri kaydırabilirsiniz: Bu fonksiyon, zaten tür belirteçlerine sahip: -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + Editör değişkenlerin tiplerini bildiğinden, yalnızca otomatik tamamlama değil, hata kontrolleri de sağlar: @@ -119,9 +118,8 @@ Editör değişkenlerin tiplerini bildiğinden, yalnızca otomatik tamamlama de Artık `age` değişkenini `str(age)` olarak kullanmanız gerektiğini biliyorsunuz: -```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## Tip bildirme @@ -140,9 +138,8 @@ Yalnızca `str` değil, tüm standart Python tiplerinin bildirebilirsiniz. * `bool` * `bytes` -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### Tip parametreleri ile Generic tipler @@ -158,9 +155,8 @@ Bu tür tip belirteçlerini desteklemek için özel olarak mevcuttur. From `typing`, import `List` (büyük harf olan `L` ile): -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[1] *} + Değişkenin tipini yine iki nokta üstüste (`:`) ile belirleyin. @@ -168,14 +164,16 @@ tip olarak `List` kullanın. Liste, bazı dahili tipleri içeren bir tür olduğundan, bunları köşeli parantez içine alırsınız: -```Python hl_lines="4" -{!../../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[4] *} + -!!! ipucu - Köşeli parantez içindeki bu dahili tiplere "tip parametreleri" denir. +/// tip | Ipucu - Bu durumda `str`, `List`e iletilen tür parametresidir. +Köşeli parantez içindeki bu dahili tiplere "tip parametreleri" denir. + +Bu durumda `str`, `List`e iletilen tür parametresidir. + +/// Bunun anlamı şudur: "`items` değişkeni bir `list`tir ve bu listedeki öğelerin her biri bir `str`dir". @@ -193,9 +191,8 @@ Ve yine, editör bunun bir `str` ​​olduğunu biliyor ve bunun için destek s `Tuple` ve `set`lerin tiplerini bildirmek için de aynısını yapıyoruz: -```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial007.py!} -``` +{* ../../docs_src/python_types/tutorial007.py hl[1,4] *} + Bu şu anlama geliyor: @@ -210,9 +207,8 @@ Bir `dict` tanımlamak için virgülle ayrılmış iki parametre verebilirsiniz. İkinci parametre ise `dict` değerinin `value` değeri içindir: -```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial008.py!} -``` +{* ../../docs_src/python_types/tutorial008.py hl[1,4] *} + Bu şu anlama gelir: @@ -225,7 +221,7 @@ Bu şu anlama gelir: `Optional` bir değişkenin `str`gibi bir tipi olabileceğini ama isteğe bağlı olarak tipinin `None` olabileceğini belirtir: ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` `str` yerine `Optional[str]` kullanmak editorün bu değerin her zaman `str` tipinde değil bazen `None` tipinde de olabileceğini belirtir ve hataları tespit etmemizde yardımcı olur. @@ -249,15 +245,13 @@ Bir değişkenin tipini bir sınıf ile bildirebilirsiniz. Diyelim ki `name` değerine sahip `Person` sınıfınız var: -```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + Sonra bir değişkeni 'Person' tipinde tanımlayabilirsiniz: -```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + Ve yine bütün editör desteğini alırsınız: @@ -265,7 +259,7 @@ Ve yine bütün editör desteğini alırsınız: ## Pydantic modelleri -Pydantic veri doğrulaması yapmak için bir Python kütüphanesidir. +Pydantic veri doğrulaması yapmak için bir Python kütüphanesidir. Verilerin "biçimini" niteliklere sahip sınıflar olarak düzenlersiniz. @@ -277,12 +271,14 @@ Ve ortaya çıkan nesne üzerindeki bütün editör desteğini alırsınız. Resmi Pydantic dokümanlarından alınmıştır: -```Python -{!../../../docs_src/python_types/tutorial011.py!} -``` +{* ../../docs_src/python_types/tutorial011.py *} + -!!! info - Daha fazla şey öğrenmek için Pydantic'i takip edin. +/// info + +Daha fazla şey öğrenmek için Pydantic'i takip edin. + +/// **FastAPI** tamamen Pydantic'e dayanmaktadır. @@ -310,5 +306,8 @@ Bütün bunlar kulağa soyut gelebilir. Merak etme. Tüm bunları çalışırken Önemli olan, standart Python türlerini tek bir yerde kullanarak (daha fazla sınıf, dekoratör vb. eklemek yerine), **FastAPI**'nin bizim için işi yapmasını sağlamak. -!!! info - Tüm öğreticiyi zaten okuduysanız ve türler hakkında daha fazla bilgi için geri döndüyseniz, iyi bir kaynak: the "cheat sheet" from `mypy`. +/// info + +Tüm öğreticiyi zaten okuduysanız ve türler hakkında daha fazla bilgi için geri döndüyseniz, iyi bir kaynak: the "cheat sheet" from `mypy`. + +/// diff --git a/docs/tr/docs/resources/index.md b/docs/tr/docs/resources/index.md new file mode 100644 index 000000000..fc71a9ca1 --- /dev/null +++ b/docs/tr/docs/resources/index.md @@ -0,0 +1,3 @@ +# Kaynaklar + +Ek kaynaklar, dış bağlantılar, makaleler ve daha fazlası. ✈️ diff --git a/docs/tr/docs/tutorial/cookie-params.md b/docs/tr/docs/tutorial/cookie-params.md new file mode 100644 index 000000000..f07508c2f --- /dev/null +++ b/docs/tr/docs/tutorial/cookie-params.md @@ -0,0 +1,35 @@ +# Çerez (Cookie) Parametreleri + +`Query` (Sorgu) ve `Path` (Yol) parametrelerini tanımladığınız şekilde çerez parametreleri tanımlayabilirsiniz. + +## Import `Cookie` + +Öncelikle, `Cookie`'yi projenize dahil edin: + +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[3] *} + +## `Cookie` Parametrelerini Tanımlayın + +Çerez parametrelerini `Path` veya `Query` tanımlaması yapar gibi tanımlayın. + +İlk değer varsayılan değerdir; tüm ekstra doğrulama veya belirteç parametrelerini kullanabilirsiniz: + +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9] *} + +/// note | Teknik Detaylar + +`Cookie` sınıfı `Path` ve `Query` sınıflarının kardeşidir. Diğerleri gibi `Param` sınıfını miras alan bir sınıftır. + +Ancak `fastapi`'dan projenize dahil ettiğiniz `Query`, `Path`, `Cookie` ve diğerleri aslında özel sınıflar döndüren birer fonksiyondur. + +/// + +/// info | Bilgi + +Çerez tanımlamak için `Cookie` sınıfını kullanmanız gerekmektedir, aksi taktirde parametreler sorgu parametreleri olarak yorumlanır. + +/// + +## Özet + +Çerez tanımlamalarını `Cookie` sınıfını kullanarak `Query` ve `Path` tanımlar gibi tanımlayın. diff --git a/docs/tr/docs/tutorial/first-steps.md b/docs/tr/docs/tutorial/first-steps.md new file mode 100644 index 000000000..2d2949b50 --- /dev/null +++ b/docs/tr/docs/tutorial/first-steps.md @@ -0,0 +1,335 @@ +# İlk Adımlar + +En sade FastAPI dosyası şu şekilde görünür: + +{* ../../docs_src/first_steps/tutorial001.py *} + +Yukarıdaki içeriği bir `main.py` dosyasına kopyalayalım. + +Uygulamayı çalıştıralım: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [28720] +INFO: Started server process [28722] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +/// note | Not + +`uvicorn main:app` komutunu şu şekilde açıklayabiliriz: + +* `main`: dosya olan `main.py` (yani Python "modülü"). +* `app`: ise `main.py` dosyasının içerisinde `app = FastAPI()` satırında oluşturduğumuz `FastAPI` nesnesi. +* `--reload`: kod değişikliklerinin ardından sunucuyu otomatik olarak yeniden başlatır. Bu parameteyi sadece geliştirme aşamasında kullanmalıyız. + +/// + +Çıktı olarak şöyle bir satır ile karşılaşacaksınız: + +```hl_lines="4" +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +Bu satır, yerel makinenizde uygulamanızın çalıştığı bağlantıyı gösterir. + +### Kontrol Edelim + +Tarayıcınızı açıp http://127.0.0.1:8000 bağlantısına gidin. + +Şu şekilde bir JSON yanıtı ile karşılaşacağız: + +```JSON +{"message": "Hello World"} +``` + +### Etkileşimli API Dokümantasyonu + +Şimdi http://127.0.0.1:8000/docs bağlantısını açalım. + +Swagger UI tarafından sağlanan otomatik etkileşimli bir API dokümantasyonu göreceğiz: + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### Alternatif API Dokümantasyonu + +Şimdi http://127.0.0.1:8000/redoc bağlantısını açalım. + +ReDoc tarafından sağlanan otomatik dokümantasyonu göreceğiz: + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +### OpenAPI + +**FastAPI**, **OpenAPI** standardını kullanarak tüm API'ınızın tamamını tanımlayan bir "şema" oluşturur. + +#### "Şema" + +"Şema", bir şeyin tanımı veya açıklamasıdır. Geliştirilen koddan ziyade soyut bir açıklamadır. + +#### API "Şeması" + +Bu durumda, OpenAPI, API şemasını nasıl tanımlayacağınızı belirten bir şartnamedir. + +Bu şema tanımı, API yollarınızla birlikte yollarınızın aldığı olası parametreler gibi tanımlamaları içerir. + +#### Veri "Şeması" + +"Şema" terimi, JSON içeriği gibi bazı verilerin şeklini de ifade edebilir. + +Bu durumda, JSON özellikleri ve sahip oldukları veri türleri gibi anlamlarına gelir. + +#### OpenAPI ve JSON Şema + +OpenAPI, API'niz için bir API şeması tanımlar. Ve bu şema, JSON veri şemaları standardı olan **JSON Şema** kullanılarak API'niz tarafından gönderilen ve alınan verilerin tanımlarını (veya "şemalarını") içerir. + +#### `openapi.json` Dosyasına Göz At + +Ham OpenAPI şemasının nasıl göründüğünü merak ediyorsanız, FastAPI otomatik olarak tüm API'ınızın tanımlamalarını içeren bir JSON (şeması) oluşturur. + +Bu şemayı direkt olarak http://127.0.0.1:8000/openapi.json bağlantısından görüntüleyebilirsiniz. + +Aşağıdaki gibi başlayan bir JSON ile karşılaşacaksınız: + +```JSON +{ + "openapi": "3.1.0", + "info": { + "title": "FastAPI", + "version": "0.1.0" + }, + "paths": { + "/items/": { + "get": { + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + + + +... +``` + +#### OpenAPI Ne İşe Yarar? + +OpenAPI şeması, FastAPI projesinde bulunan iki etkileşimli dokümantasyon sistemine güç veren şeydir. + +OpenAPI'ya dayalı düzinelerce alternatif etkileşimli dokümantasyon aracı mevcuttur. **FastAPI** ile oluşturulmuş uygulamanıza bu alternatiflerden herhangi birini kolayca ekleyebilirsiniz. + +Ayrıca, API'ınızla iletişim kuracak önyüz, mobil veya IoT uygulamaları gibi istemciler için otomatik olarak kod oluşturabilirsiniz. + +## Adım Adım Özetleyelim + +### Adım 1: `FastAPI`yı Projemize Dahil Edelim + +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} + +`FastAPI`, API'niz için tüm işlevselliği sağlayan bir Python sınıfıdır. + +/// note | Teknik Detaylar + +`FastAPI` doğrudan `Starlette`'i miras alan bir sınıftır. + +Starlette'in tüm işlevselliğini `FastAPI` ile de kullanabilirsiniz. + +/// + +### Adım 2: Bir `FastAPI` "Örneği" Oluşturalım + +{* ../../docs_src/first_steps/tutorial001.py hl[3] *} + +Burada `app` değişkeni `FastAPI` sınıfının bir örneği olacaktır. + +Bu, tüm API'yı oluşturmak için ana etkileşim noktası olacaktır. + +Bu `app` değişkeni, `uvicorn` komutunda atıfta bulunulan değişkenin ta kendisidir. + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Uygulamanızı aşağıdaki gibi oluşturursanız: + +{* ../../docs_src/first_steps/tutorial002.py hl[3] *} + +Ve bunu `main.py` dosyasına yerleştirirseniz eğer `uvicorn` komutunu şu şekilde çalıştırabilirsiniz: + +
+ +```console +$ uvicorn main:my_awesome_api --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +### Adım 3: Bir *Yol Operasyonu* Oluşturalım + +#### Yol + +Burada "yol" bağlantıda bulunan ilk `/` ile başlayan ve sonrasında gelen kısmı ifade eder. + +Yani, şu şekilde bir bağlantıda: + +``` +https://example.com/items/foo +``` + +... yol şöyle olur: + +``` +/items/foo +``` + +/// info | Bilgi + +"Yol" genellikle "endpoint" veya "route" olarak adlandırılır. + +/// + +Bir API oluştururken, "yol", "kaynaklar" ile "endişeleri" ayırmanın ana yöntemidir. + +#### Operasyonlar + +Burada "operasyon" HTTP "metodlarından" birini ifade eder. + +Bunlardan biri: + +* `POST` +* `GET` +* `PUT` +* `DELETE` + +...veya daha az kullanılan diğerleri: + +* `OPTIONS` +* `HEAD` +* `PATCH` +* `TRACE` + +HTTP protokolünde, bu "metodlardan" birini (veya daha fazlasını) kullanarak her bir yol ile iletişim kurabilirsiniz. + +--- + +API oluştururkan, belirli bir amaca hizmet eden belirli HTTP metodlarını kullanırsınız. + +Normalde kullanılan: + +* `POST`: veri oluşturmak. +* `GET`: veri okumak. +* `PUT`: veriyi güncellemek. +* `DELETE`: veriyi silmek. + +Bu nedenle, OpenAPI'da HTTP metodlarından her birine "operasyon" denir. + +Biz de onları "**operasyonlar**" olarak adlandıracağız. + +#### Bir *Yol Operasyonu Dekoratörü* Tanımlayalım + +{* ../../docs_src/first_steps/tutorial001.py hl[6] *} + +`@app.get("/")` dekoratörü, **FastAPI**'a hemen altındaki fonksiyonun aşağıdaki durumlardan sorumlu olduğunu söyler: + +* get operasyonu ile +* `/` yoluna gelen istekler + +/// info | `@decorator` Bilgisi + +Python'da `@something` sözdizimi "dekoratör" olarak adlandırılır. + +Dekoratörler, dekoratif bir şapka gibi (sanırım terim buradan geliyor) fonksiyonların üzerlerine yerleştirilirler. + +Bir "dekoratör" hemen altında bulunan fonksiyonu alır ve o fonksiyon ile bazı işlemler gerçekleştirir. + +Bizim durumumuzda, kullandığımız dekoratör, **FastAPI**'a altındaki fonksiyonun `/` yoluna gelen `get` metodlu isteklerden sorumlu olduğunu söyler. + +Bu bir **yol operasyonu dekoratörüdür**. + +/// + +Ayrıca diğer operasyonları da kullanabilirsiniz: + +* `@app.post()` +* `@app.put()` +* `@app.delete()` + +Daha az kullanılanları da kullanabilirsiniz: + +* `@app.options()` +* `@app.head()` +* `@app.patch()` +* `@app.trace()` + +/// tip | İpucu + +Her işlemi (HTTP metod) istediğiniz gibi kullanmakta özgürsünüz. + +**FastAPI** herhangi bir özel amacı veya anlamı olması konusunda ısrarcı olmaz. + +Buradaki bilgiler bir gereklilik değil, bir kılavuz olarak sunulmaktadır. + +Mesela GraphQL kullanırkan genelde tüm işlemleri yalnızca `POST` operasyonunu kullanarak gerçekleştirirsiniz. + +/// + +### Adım 4: **Yol Operasyonu Fonksiyonunu** Tanımlayın + +Aşağıdaki, bizim **yol operasyonu fonksiyonumuzdur**: + +* **yol**: `/` +* **operasyon**: `get` +* **fonksiyon**: "dekoratör"ün (`@app.get("/")`'in) altındaki fonksiyondur. + +{* ../../docs_src/first_steps/tutorial001.py hl[7] *} + +Bu bir Python fonksiyonudur. + +Bu fonksiyon bir `GET` işlemi kullanılarak "`/`" bağlantısına bir istek geldiğinde **FastAPI** tarafından çağrılır. + +Bu durumda bu fonksiyon bir `async` fonksiyondur. + +--- + +Bu fonksiyonu `async def` yerine normal bir fonksiyon olarak da tanımlayabilirsiniz. + +{* ../../docs_src/first_steps/tutorial003.py hl[7] *} + +/// note | Not + +Eğer farkı bilmiyorsanız, [Async: *"Aceleniz mi var?"*](../async.md#in-a-hurry){.internal-link target=_blank} sayfasını kontrol edebilirsiniz. + +/// + +### Adım 5: İçeriği Geri Döndürün + +{* ../../docs_src/first_steps/tutorial001.py hl[8] *} + +Bir `dict`, `list` veya `str`, `int` gibi tekil değerler döndürebilirsiniz. + +Ayrıca, Pydantic modelleri de döndürebilirsiniz (bu konu ileriki aşamalarda irdelenecektir). + +Otomatik olarak JSON'a dönüştürülecek (ORM'ler vb. dahil) başka birçok nesne ve model vardır. En beğendiklerinizi kullanmayı deneyin, yüksek ihtimalle destekleniyordur. + +## Özet + +* `FastAPI`'yı projemize dahil ettik. +* Bir `app` örneği oluşturduk. +* Bir **yol operasyonu dekoratörü** (`@app.get("/")` gibi) yazdık. +* Bir **yol operasyonu fonksiyonu** (`def root(): ...` gibi) yazdık. +* Geliştirme sunucumuzu (`uvicorn main:app --reload` gibi) çalıştırdık. diff --git a/docs/tr/docs/tutorial/first_steps.md b/docs/tr/docs/tutorial/first_steps.md deleted file mode 100644 index b39802f5d..000000000 --- a/docs/tr/docs/tutorial/first_steps.md +++ /dev/null @@ -1,336 +0,0 @@ -# İlk Adımlar - -En basit FastAPI dosyası şu şekildedir: - -```Python -{!../../../docs_src/first_steps/tutorial001.py!} -``` - -Bunu bir `main.py` dosyasına kopyalayın. - -Projeyi çalıştırın: - -
- -```console -$ uvicorn main:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -INFO: Started reloader process [28720] -INFO: Started server process [28722] -INFO: Waiting for application startup. -INFO: Application startup complete. -``` - -
- -!!! note - `uvicorn main:app` komutu şunu ifade eder: - - * `main`: `main.py` dosyası (the Python "module"). - * `app`: `main.py` dosyası içerisinde `app = FastAPI()` satırıyla oluşturulan nesne. - * `--reload`: Kod değişikliği sonrasında sunucunun yeniden başlatılmasını sağlar. Yalnızca geliştirme için kullanın. - -Çıktıda şu şekilde bir satır vardır: - -```hl_lines="4" -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -Bu satır, yerel makinenizde uygulamanızın sunulduğu URL'yi gösterir. - -### Kontrol Et - -Tarayıcınızda http://127.0.0.1:8000 adresini açın. - -Bir JSON yanıtı göreceksiniz: - -```JSON -{"message": "Hello World"} -``` - -### İnteraktif API dokümantasyonu - -http://127.0.0.1:8000/docs adresine gidin. - -Otomatik oluşturulmuş( Swagger UI tarafından sağlanan) interaktif bir API dokümanı göreceksiniz: - -![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) - -### Alternatif API dokümantasyonu - -Şimdi, http://127.0.0.1:8000/redoc adresine gidin. - -Otomatik oluşturulmuş(ReDoc tarafından sağlanan) bir API dokümanı göreceksiniz: - -![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) - -### OpenAPI - -**FastAPI**, **OpenAPI** standardını kullanarak tüm API'lerinizi açıklayan bir "şema" oluşturur. - -#### "Şema" - -Bir "şema", bir şeyin tanımı veya açıklamasıdır. Soyut bir açıklamadır, uygulayan kod değildir. - -#### API "şemaları" - -Bu durumda, OpenAPI, API şemasını nasıl tanımlayacağınızı belirten şartnamelerdir. - -Bu şema tanımı, API yollarınızı, aldıkları olası parametreleri vb. içerir. - -#### Data "şema" - -"Şema" terimi, JSON içeriği gibi bazı verilerin şeklini de ifade edebilir. - -Bu durumda, JSON öznitelikleri ve sahip oldukları veri türleri vb. anlamına gelir. - -#### OpenAPI and JSON Şema - -OpenAPI, API'niz için bir API şeması tanımlar. Ve bu şema, JSON veri şemaları standardı olan **JSON Şema** kullanılarak API'niz tarafından gönderilen ve alınan verilerin tanımlarını (veya "şemalarını") içerir. - -#### `openapi.json` kontrol et - -OpenAPI şemasının nasıl göründüğünü merak ediyorsanız, FastAPI otomatik olarak tüm API'nizin açıklamalarını içeren bir JSON (şema) oluşturur. - -Doğrudan şu adreste görebilirsiniz: http://127.0.0.1:8000/openapi.json. - -Aşağıdaki gibi bir şeyle başlayan bir JSON gösterecektir: - -```JSON -{ - "openapi": "3.0.2", - "info": { - "title": "FastAPI", - "version": "0.1.0" - }, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - - - -... -``` - -#### OpenAPI ne içindir? - -OpenAPI şeması, dahili olarak bulunan iki etkileşimli dokümantasyon sistemine güç veren şeydir. - -Ve tamamen OpenAPI'ye dayalı düzinelerce alternatif vardır. **FastAPI** ile oluşturulmuş uygulamanıza bu alternatiflerden herhangi birini kolayca ekleyebilirsiniz. - -API'nizle iletişim kuran istemciler için otomatik olarak kod oluşturmak için de kullanabilirsiniz. Örneğin, frontend, mobil veya IoT uygulamaları. - -## Adım adım özet - -### Adım 1: `FastAPI`yi içe aktarın - -```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} -``` - -`FastAPI`, API'niz için tüm fonksiyonları sağlayan bir Python sınıfıdır. - -!!! note "Teknik Detaylar" - `FastAPI` doğrudan `Starlette` kalıtım alan bir sınıftır. - - Tüm Starlette fonksiyonlarını `FastAPI` ile de kullanabilirsiniz. - -### Adım 2: Bir `FastAPI` örneği oluşturun - -```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} -``` - -Burada `app` değişkeni `FastAPI` sınıfının bir örneği olacaktır. - -Bu tüm API'yi oluşturmak için ana etkileşim noktası olacaktır. - -`uvicorn` komutunda atıfta bulunulan `app` ile aynıdır. - -
- -```console -$ uvicorn main:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -Uygulamanızı aşağıdaki gibi oluşturursanız: - -```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} -``` - -Ve bunu `main.py` dosyasına koyduktan sonra `uvicorn` komutunu şu şekilde çağırabilirsiniz: - -
- -```console -$ uvicorn main:my_awesome_api --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -### Adım 3: *Path işlemleri* oluşturmak - -#### Path - -Burada "Path" URL'de ilk "\" ile başlayan son bölümü ifade eder. - -Yani, şu şekilde bir URL'de: - -``` -https://example.com/items/foo -``` - -... path şöyle olabilir: - -``` -/items/foo -``` - -!!! info - Genellikle bir "path", "endpoint" veya "route" olarak adlandırılabilir. - -Bir API oluştururken, "path", "resource" ile "concern" ayırmanın ana yoludur. - -#### İşlemler - -Burada "işlem" HTTP methodlarından birini ifade eder. - -Onlardan biri: - -* `POST` -* `GET` -* `PUT` -* `DELETE` - -... ve daha egzotik olanları: - -* `OPTIONS` -* `HEAD` -* `PATCH` -* `TRACE` - -HTTP protokolünde, bu "methodlardan" birini (veya daha fazlasını) kullanarak her path ile iletişim kurabilirsiniz. - ---- - -API'lerinizi oluştururkan, belirli bir işlemi gerçekleştirirken belirli HTTP methodlarını kullanırsınız. - -Normalde kullanılan: - -* `POST`: veri oluşturmak. -* `GET`: veri okumak. -* `PUT`: veriyi güncellemek. -* `DELETE`: veriyi silmek. - -Bu nedenle, OpenAPI'de HTTP methodlarından her birine "işlem" denir. - -Bizde onlara "**işlemler**" diyeceğiz. - -#### Bir *Path işlem decoratorleri* tanımlanmak - -```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} -``` - -`@app.get("/")` **FastAPI'ye** aşağıdaki fonksiyonun adresine giden istekleri işlemekten sorumlu olduğunu söyler: - -* path `/` -* get işlemi kullanılarak - - -!!! info "`@decorator` Bilgisi" - Python `@something` şeklinde ifadeleri "decorator" olarak adlandırır. - - Decoratoru bir fonksiyonun üzerine koyarsınız. Dekoratif bir şapka gibi (Sanırım terim buradan gelmektedir). - - Bir "decorator" fonksiyonu alır ve bazı işlemler gerçekleştir. - - Bizim durumumzda decarator **FastAPI'ye** fonksiyonun bir `get` işlemi ile `/` pathine geldiğini söyler. - - Bu **path işlem decoratordür** - -Ayrıca diğer işlemleri de kullanabilirsiniz: - -* `@app.post()` -* `@app.put()` -* `@app.delete()` - -Ve daha egzotik olanları: - -* `@app.options()` -* `@app.head()` -* `@app.patch()` -* `@app.trace()` - -!!! tip - Her işlemi (HTTP method) istediğiniz gibi kullanmakta özgürsünüz. - - **FastAPI** herhangi bir özel anlamı zorlamaz. - - Buradaki bilgiler bir gereklilik değil, bir kılavuz olarak sunulmaktadır. - - Örneğin, GraphQL kullanırkan normalde tüm işlemleri yalnızca `POST` işlemini kullanarak gerçekleştirirsiniz. - -### Adım 4: **path işlem fonksiyonunu** tanımlayın - -Aşağıdakiler bizim **path işlem fonksiyonlarımızdır**: - -* **path**: `/` -* **işlem**: `get` -* **function**: "decorator"ün altındaki fonksiyondur (`@app.get("/")` altında). - -```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} -``` - -Bu bir Python fonksiyonudur. - -Bir `GET` işlemi kullanarak "`/`" URL'sine bir istek geldiğinde **FastAPI** tarafından çağrılır. - -Bu durumda bir `async` fonksiyonudur. - ---- - -Bunu `async def` yerine normal bir fonksiyon olarakta tanımlayabilirsiniz. - -```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} -``` - -!!! note - - Eğer farkı bilmiyorsanız, [Async: *"Acelesi var?"*](../async.md#in-a-hurry){.internal-link target=_blank} kontrol edebilirsiniz. - -### Adım 5: İçeriği geri döndürün - - -```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} -``` - -Bir `dict`, `list` döndürebilir veya `str`, `int` gibi tekil değerler döndürebilirsiniz. - -Ayrıca, Pydantic modellerini de döndürebilirsiniz. (Bununla ilgili daha sonra ayrıntılı bilgi göreceksiniz.) - -Otomatik olarak JSON'a dönüştürülecek(ORM'ler vb. dahil) başka birçok nesne ve model vardır. En beğendiklerinizi kullanmayı deneyin, yüksek ihtimalle destekleniyordur. - -## Özet - -* `FastAPI`'yi içe aktarın. -* Bir `app` örneği oluşturun. -* **path işlem decorator** yazın. (`@app.get("/")` gibi) -* **path işlem fonksiyonu** yazın. (`def root(): ...` gibi) -* Development sunucunuzu çalıştırın. (`uvicorn main:app --reload` gibi) diff --git a/docs/tr/docs/tutorial/path-params.md b/docs/tr/docs/tutorial/path-params.md new file mode 100644 index 000000000..e1707a5d9 --- /dev/null +++ b/docs/tr/docs/tutorial/path-params.md @@ -0,0 +1,258 @@ +# Yol Parametreleri + +Yol "parametrelerini" veya "değişkenlerini" Python string biçimlemede kullanılan sözdizimi ile tanımlayabilirsiniz. + +{* ../../docs_src/path_params/tutorial001.py hl[6:7] *} + +Yol parametresi olan `item_id`'nin değeri, fonksiyonunuza `item_id` argümanı olarak aktarılacaktır. + +Eğer bu örneği çalıştırıp http://127.0.0.1:8000/items/foo sayfasına giderseniz, şöyle bir çıktı ile karşılaşırsınız: + +```JSON +{"item_id":"foo"} +``` + +## Tip İçeren Yol Parametreleri + +Standart Python tip belirteçlerini kullanarak yol parametresinin tipini fonksiyonun içerisinde tanımlayabilirsiniz. + +{* ../../docs_src/path_params/tutorial002.py hl[7] *} + +Bu durumda, `item_id` bir `int` olarak tanımlanacaktır. + +/// check | Ek bilgi + +Bu sayede, fonksiyon içerisinde hata denetimi, kod tamamlama gibi konularda editör desteğine kavuşacaksınız. + +/// + +## Veri Dönüşümü + +Eğer bu örneği çalıştırıp tarayıcınızda http://127.0.0.1:8000/items/3 sayfasını açarsanız, şöyle bir yanıt ile karşılaşırsınız: + +```JSON +{"item_id":3} +``` + +/// check | Ek bilgi + +Dikkatinizi çekerim ki, fonksiyonunuzun aldığı (ve döndürdüğü) değer olan `3` bir string `"3"` değil aksine bir Python `int`'idir. + +Bu tanımlamayla birlikte, **FastAPI** size otomatik istek "ayrıştırma" özelliği sağlar. + +/// + +## Veri Doğrulama + +Eğer tarayıcınızda http://127.0.0.1:8000/items/foo sayfasını açarsanız, şuna benzer güzel bir HTTP hatası ile karşılaşırsınız: + +```JSON +{ + "detail": [ + { + "type": "int_parsing", + "loc": [ + "path", + "item_id" + ], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "foo", + "url": "https://errors.pydantic.dev/2.1/v/int_parsing" + } + ] +} +``` + +Çünkü burada `item_id` yol parametresi `int` tipinde bir değer beklerken `"foo"` yani `string` tipinde bir değer almıştı. + +Aynı hata http://127.0.0.1:8000/items/4.2 sayfasında olduğu gibi `int` yerine `float` bir değer verseydik de ortaya çıkardı. + +/// check | Ek bilgi + +Böylece, aynı Python tip tanımlaması ile birlikte, **FastAPI** veri doğrulama özelliği sağlar. + +Dikkatinizi çekerim ki, karşılaştığınız hata, doğrulamanın geçersiz olduğu mutlak noktayı da açık bir şekilde belirtiyor. + +Bu özellik, API'ınızla iletişime geçen kodu geliştirirken ve ayıklarken inanılmaz derecede yararlı olacaktır. + +/// + +## Dokümantasyon + +Ayrıca, tarayıcınızı http://127.0.0.1:8000/docs adresinde açarsanız, aşağıdaki gibi otomatik ve interaktif bir API dökümantasyonu ile karşılaşırsınız: + + + +/// check | Ek bilgi + +Üstelik, sadece aynı Python tip tanımlaması ile, **FastAPI** size otomatik ve interaktif (Swagger UI ile entegre) bir dokümantasyon sağlar. + +Dikkatinizi çekerim ki, yol parametresi integer olarak tanımlanmıştır. + +/// + +## Standartlara Dayalı Avantajlar, Alternatif Dokümantasyon + +Oluşturulan şema OpenAPI standardına uygun olduğu için birçok uyumlu araç mevcuttur. + +Bu sayede, **FastAPI**'ın bizzat kendisi http://127.0.0.1:8000/redoc sayfasından erişebileceğiniz alternatif (ReDoc kullanan) bir API dokümantasyonu sağlar: + + + +Aynı şekilde, farklı diller için kod türetme araçları da dahil olmak üzere çok sayıda uyumlu araç bulunur. + +## Pydantic + +Tüm veri doğrulamaları Pydantic tarafından arka planda gerçekleştirilir, bu sayede tüm avantajlardan faydalanabilirsiniz. Böylece, emin ellerde olduğunuzu hissedebilirsiniz. + +Aynı tip tanımlamalarını `str`, `float`, `bool` ve diğer karmaşık veri tipleri ile kullanma imkanınız vardır. + +Bunlardan birkaçı, bu eğitimin ileriki bölümlerinde irdelenmiştir. + +## Sıralama Önem Arz Eder + +*Yol operasyonları* tasarlarken sabit yol barındıran durumlar ile karşılaşabilirsiniz. + +Farz edelim ki `/users/me` yolu geçerli kullanıcı hakkında bilgi almak için kullanılıyor olsun. + +Benzer şekilde `/users/{user_id}` gibi tanımlanmış ve belirli bir kullanıcı hakkında veri almak için kullanıcının ID bilgisini kullanan bir yolunuz da mevcut olabilir. + +*Yol operasyonları* sıralı bir şekilde gözden geçirildiğinden dolayı `/users/me` yolunun `/users/{user_id}` yolundan önce tanımlanmış olmasından emin olmanız gerekmektedir: + +{* ../../docs_src/path_params/tutorial003.py hl[6,11] *} + +Aksi halde, `/users/{user_id}` yolu `"me"` değerinin `user_id` parametresi için gönderildiğini "düşünerek" `/users/me` ile de eşleşir. + +Benzer şekilde, bir yol operasyonunu yeniden tanımlamanız mümkün değildir: + +{* ../../docs_src/path_params/tutorial003b.py hl[6,11] *} + +Yol, ilk kısım ile eşleştiğinden dolayı her koşulda ilk yol operasyonu kullanılacaktır. + +## Ön Tanımlı Değerler + +Eğer *yol parametresi* alan bir *yol operasyonunuz* varsa ve alabileceği *yol parametresi* değerlerinin ön tanımlı olmasını istiyorsanız, standart Python `Enum` tipini kullanabilirsiniz. + +### Bir `Enum` Sınıfı Oluşturalım + +`Enum` sınıfını projemize dahil edip `str` ile `Enum` sınıflarını miras alan bir alt sınıf yaratalım. + +`str` sınıfı miras alındığından dolayı, API dokümanı, değerlerin `string` tipinde olması gerektiğini anlayabilecek ve doğru bir şekilde işlenecektir. + +Sonrasında, sınıf içerisinde, mevcut ve geçerli değerler olacak olan sabit değerli özelliklerini oluşturalım: + +{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *} + +/// info | Bilgi + +3.4 sürümünden beri enumerationlar (ya da enumlar) Python'da mevcuttur. + +/// + +/// tip | İpucu + +Merak ediyorsanız söyleyeyim, "AlexNet", "ResNet" ve "LeNet" isimleri Makine Öğrenmesi modellerini temsil eder. + +/// + +### Bir *Yol Parametresi* Tanımlayalım + +Sonrasında, yarattığımız enum sınıfını (`ModelName`) kullanarak tip belirteci aracılığıyla bir *yol parametresi* oluşturalım: + +{* ../../docs_src/path_params/tutorial005.py hl[16] *} + +### Dokümana Göz Atalım + +*Yol parametresi* için mevcut değerler ön tanımlı olduğundan dolayı, interaktif döküman onları güzel bir şekilde gösterebilir: + + + +### Python *Enumerationları* ile Çalışmak + +*Yol parametresinin* değeri bir *enumeration üyesi* olacaktır. + +#### *Enumeration Üyelerini* Karşılaştıralım + +Parametreyi, yarattığınız enum olan `ModelName` içerisindeki *enumeration üyesi* ile karşılaştırabilirsiniz: + +{* ../../docs_src/path_params/tutorial005.py hl[17] *} + +#### *Enumeration Değerini* Edinelim + +`model_name.value` veya genel olarak `your_enum_member.value` tanımlarını kullanarak (bu durumda bir `str` olan) gerçek değere ulaşabilirsiniz: + +{* ../../docs_src/path_params/tutorial005.py hl[20] *} + +/// tip | İpucu + +`"lenet"` değerine `ModelName.lenet.value` tanımı ile de ulaşabilirsiniz. + +/// + +#### *Enumeration Üyelerini* Döndürelim + +JSON gövdesine (örneğin bir `dict`) gömülü olsalar bile *yol operasyonundaki* *enum üyelerini* döndürebilirsiniz. + +Bu üyeler istemciye iletilmeden önce kendilerine karşılık gelen değerlerine (bu durumda string) dönüştürüleceklerdir: + +{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *} + +İstemci tarafında şuna benzer bir JSON yanıtı ile karşılaşırsınız: + +```JSON +{ + "model_name": "alexnet", + "message": "Deep Learning FTW!" +} +``` + +## Yol İçeren Yol Parametreleri + +Farz edelim ki elinizde `/files/{file_path}` isminde bir *yol operasyonu* var. + +Fakat `file_path` değerinin `home/johndoe/myfile.txt` gibi bir *yol* barındırmasını istiyorsunuz. + +Sonuç olarak, oluşturmak istediğin URL `/files/home/johndoe/myfile.txt` gibi bir şey olacaktır. + +### OpenAPI Desteği + +Test etmesi ve tanımlaması zor senaryolara sebebiyet vereceğinden dolayı OpenAPI, *yol* barındıran *yol parametrelerini* tanımlayacak bir çözüm sunmuyor. + +Ancak bunu, Starlette kütüphanesinin dahili araçlarından birini kullanarak **FastAPI**'da gerçekleştirebilirsiniz. + +Parametrenin bir yol içermesi gerektiğini belirten herhangi bir doküman eklemememize rağmen dokümanlar yine de çalışacaktır. + +### Yol Dönüştürücü + +Direkt olarak Starlette kütüphanesinden gelen bir opsiyon sayesinde aşağıdaki gibi *yol* içeren bir *yol parametresi* bağlantısı tanımlayabilirsiniz: + +``` +/files/{file_path:path} +``` + +Bu durumda, parametrenin adı `file_path` olacaktır ve son kısım olan `:path` kısmı, parametrenin herhangi bir *yol* ile eşleşmesi gerektiğini belirtecektir. + +Böylece şunun gibi bir kullanım yapabilirsiniz: + +{* ../../docs_src/path_params/tutorial004.py hl[6] *} + +/// tip | İpucu + +Parametrenin başında `/home/johndoe/myfile.txt` yolunda olduğu gibi (`/`) işareti ile birlikte kullanmanız gerektiği durumlar olabilir. + +Bu durumda, URL, `files` ile `home` arasında iki eğik çizgiye (`//`) sahip olup `/files//home/johndoe/myfile.txt` gibi gözükecektir. + +/// + +## Özet + +**FastAPI** ile kısa, sezgisel ve standart Python tip tanımlamaları kullanarak şunları elde edersiniz: + +* Editör desteği: hata denetimi, otomatik tamamlama, vb. +* Veri "dönüştürme" +* Veri doğrulama +* API tanımlamaları ve otomatik dokümantasyon + +Ve sadece, bunları bir kez tanımlamanız yeterli. + +Diğer frameworkler ile karşılaştırıldığında (ham performans dışında), üstte anlatılan durum muhtemelen **FastAPI**'ın göze çarpan başlıca avantajıdır. diff --git a/docs/tr/docs/tutorial/query-params.md b/docs/tr/docs/tutorial/query-params.md new file mode 100644 index 000000000..4aa0a82b1 --- /dev/null +++ b/docs/tr/docs/tutorial/query-params.md @@ -0,0 +1,189 @@ +# Sorgu Parametreleri + +Fonksiyonda yol parametrelerinin parçası olmayan diğer tanımlamalar otomatik olarak "sorgu" parametresi olarak yorumlanır. + +{* ../../docs_src/query_params/tutorial001.py hl[9] *} + +Sorgu, bağlantıdaki `?` kısmından sonra gelen ve `&` işareti ile ayrılan anahtar-değer çiftlerinin oluşturduğu bir kümedir. + +Örneğin, aşağıdaki bağlantıda: + +``` +http://127.0.0.1:8000/items/?skip=0&limit=10 +``` + +...sorgu parametreleri şunlardır: + +* `skip`: değeri `0`'dır +* `limit`: değeri `10`'dır + +Parametreler bağlantının bir parçası oldukları için doğal olarak string olarak değerlendirilirler. + +Fakat, Python tipleri ile tanımlandıkları zaman (yukarıdaki örnekte `int` oldukları gibi), parametreler o tiplere dönüştürülür ve o tipler çerçevesinde doğrulanırlar. + +Yol parametreleri için geçerli olan her türlü işlem aynı şekilde sorgu parametreleri için de geçerlidir: + +* Editör desteği (şüphesiz) +* Veri "ayrıştırma" +* Veri doğrulama +* Otomatik dokümantasyon + +## Varsayılanlar + +Sorgu parametreleri, adres yolunun sabit bir parçası olmadıklarından dolayı isteğe bağlı ve varsayılan değere sahip olabilirler. + +Yukarıdaki örnekte `skip=0` ve `limit=10` varsayılan değere sahiplerdir. + +Yani, aşağıdaki bağlantıya gitmek: + +``` +http://127.0.0.1:8000/items/ +``` + +şu adrese gitmek ile aynı etkiye sahiptir: + +``` +http://127.0.0.1:8000/items/?skip=0&limit=10 +``` + +Ancak, mesela şöyle bir adresi ziyaret ederseniz: + +``` +http://127.0.0.1:8000/items/?skip=20 +``` + +Fonksiyonunuzdaki parametre değerleri aşağıdaki gibi olacaktır: + +* `skip=20`: çünkü bağlantıda böyle tanımlandı. +* `limit=10`: çünkü varsayılan değer buydu. + +## İsteğe Bağlı Parametreler + +Aynı şekilde, varsayılan değerlerini `None` olarak atayarak isteğe bağlı parametreler tanımlayabilirsiniz: + +{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *} + +Bu durumda, `q` fonksiyon parametresi isteğe bağlı olacak ve varsayılan değer olarak `None` alacaktır. + +/// check | Ek bilgi + +Ayrıca, dikkatinizi çekerim ki; **FastAPI**, `item_id` parametresinin bir yol parametresi olduğunu ve `q` parametresinin yol değil bir sorgu parametresi olduğunu fark edecek kadar beceriklidir. + +/// + +## Sorgu Parametresi Tip Dönüşümü + +Aşağıda görüldüğü gibi dönüştürülmek üzere `bool` tipleri de tanımlayabilirsiniz: + +{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *} + +Bu durumda, eğer şu adrese giderseniz: + +``` +http://127.0.0.1:8000/items/foo?short=1 +``` + +veya + +``` +http://127.0.0.1:8000/items/foo?short=True +``` + +veya + +``` +http://127.0.0.1:8000/items/foo?short=true +``` + +veya + +``` +http://127.0.0.1:8000/items/foo?short=on +``` + +veya + +``` +http://127.0.0.1:8000/items/foo?short=yes +``` + +veya adres, herhangi farklı bir harf varyasyonu içermesi durumuna rağmen (büyük harf, sadece baş harfi büyük kelime, vb.) fonksiyonunuz, `bool` tipli `short` parametresini `True` olarak algılayacaktır. Aksi halde `False` olarak algılanacaktır. + + +## Çoklu Yol ve Sorgu Parametreleri + +**FastAPI** neyin ne olduğunu ayırt edebileceğinden dolayı aynı anda birden fazla yol ve sorgu parametresi tanımlayabilirsiniz. + +Ve parametreleri, herhangi bir sıraya koymanıza da gerek yoktur. + +İsimlerine göre belirleneceklerdir: + +{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *} + +## Zorunlu Sorgu Parametreleri + +Türü yol olmayan bir parametre (şu ana kadar sadece sorgu parametrelerini gördük) için varsayılan değer tanımlarsanız o parametre zorunlu olmayacaktır. + +Parametre için belirli bir değer atamak istemeyip parametrenin sadece isteğe bağlı olmasını istiyorsanız değerini `None` olarak atayabilirsiniz. + +Fakat, bir sorgu parametresini zorunlu yapmak istiyorsanız varsayılan bir değer atamamanız yeterli olacaktır: + +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} + +Burada `needy` parametresi `str` tipinden oluşan zorunlu bir sorgu parametresidir. + +Eğer tarayıcınızda şu bağlantıyı: + +``` +http://127.0.0.1:8000/items/foo-item +``` + +...`needy` parametresini eklemeden açarsanız şuna benzer bir hata ile karşılaşırsınız: + +```JSON +{ + "detail": [ + { + "type": "missing", + "loc": [ + "query", + "needy" + ], + "msg": "Field required", + "input": null, + "url": "https://errors.pydantic.dev/2.1/v/missing" + } + ] +} +``` + +`needy` zorunlu bir parametre olduğundan dolayı bağlantıda tanımlanması gerekir: + +``` +http://127.0.0.1:8000/items/foo-item?needy=sooooneedy +``` + +...bu iş görür: + +```JSON +{ + "item_id": "foo-item", + "needy": "sooooneedy" +} +``` + +Ve elbette, bazı parametreleri zorunlu, bazılarını varsayılan değerli ve bazılarını tamamen opsiyonel olarak tanımlayabilirsiniz: + +{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *} + +Bu durumda, 3 tane sorgu parametresi var olacaktır: + +* `needy`, zorunlu bir `str`. +* `skip`, varsayılan değeri `0` olan bir `int`. +* `limit`, isteğe bağlı bir `int`. + +/// tip | İpucu + +Ayrıca, [Yol Parametrelerinde](path-params.md#on-tanml-degerler){.internal-link target=_blank} de kullanıldığı şekilde `Enum` sınıfından faydalanabilirsiniz. + +/// diff --git a/docs/tr/docs/tutorial/request-forms.md b/docs/tr/docs/tutorial/request-forms.md new file mode 100644 index 000000000..e4e04f5f9 --- /dev/null +++ b/docs/tr/docs/tutorial/request-forms.md @@ -0,0 +1,69 @@ +# Form Verisi + +İstek gövdesinde JSON verisi yerine form alanlarını karşılamanız gerketiğinde `Form` sınıfını kullanabilirsiniz. + +/// info | Bilgi + +Formları kullanmak için öncelikle `python-multipart` paketini indirmeniz gerekmektedir. + +Örneğin `pip install python-multipart`. + +/// + +## `Form` Sınıfını Projenize Dahil Edin + +`Form` sınıfını `fastapi`'den projenize dahil edin: + +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[3] *} + +## `Form` Parametrelerini Tanımlayın + +Form parametrelerini `Body` veya `Query` için yaptığınız gibi oluşturun: + +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[9] *} + +Örneğin, OAuth2 spesifikasyonunun kullanılabileceği ("şifre akışı" olarak adlandırılan) yollardan birinde, form alanları olarak "username" ve "password" gönderilmesi gerekir. + +Bu spesifikasyon form alanlarını adlandırırken isimlerinin birebir `username` ve `password` olmasını ve JSON verisi yerine form verisi olarak gönderilmesini gerektirir. + +`Form` sınıfıyla tanımlama yaparken `Body`, `Query`, `Path` ve `Cookie` sınıflarında kullandığınız aynı validasyon, örnekler, isimlendirme (örneğin `username` yerine `user-name` kullanımı) ve daha fazla konfigurasyonu kullanabilirsiniz. + +/// info | Bilgi + +`Form` doğrudan `Body` sınıfını miras alan bir sınıftır. + +/// + +/// tip | İpucu + +Form gövdelerini tanımlamak için `Form` sınıfını kullanmanız gerekir; çünkü bu olmadan parametreler sorgu parametreleri veya gövde (JSON) parametreleri olarak yorumlanır. + +/// + +## "Form Alanları" Hakkında + +HTML formlarının (`
`) verileri sunucuya gönderirken JSON'dan farklı özel bir kodlama kullanır. + +**FastAPI** bu verilerin JSON yerine doğru şekilde okunmasını sağlayacaktır. + +/// note | Teknik Detaylar + +Form verileri normalde `application/x-www-form-urlencoded` medya tipiyle kodlanır. + +Ancak form içerisinde dosyalar yer aldığında `multipart/form-data` olarak kodlanır. Bir sonraki bölümde dosyaların işlenmesi hakkında bilgi edineceksiniz. + +Form kodlama türleri ve form alanları hakkında daha fazla bilgi edinmek istiyorsanız MDN web docs for POST sayfasını ziyaret edebilirsiniz. + +/// + +/// warning | Uyarı + +*Yol operasyonları* içerisinde birden fazla `Form` parametresi tanımlayabilirsiniz ancak bunlarla birlikte JSON verisi kabul eden `Body` alanları tanımlayamazsınız çünkü bu durumda istek gövdesi `application/json` yerine `application/x-www-form-urlencoded` ile kodlanmış olur. + +Bu **FastAPI**'ın getirdiği bir kısıtlama değildir, HTTP protokolünün bir parçasıdır. + +/// + +## Özet + +Form verisi girdi parametreleri tanımlamak için `Form` sınıfını kullanın. diff --git a/docs/tr/docs/tutorial/static-files.md b/docs/tr/docs/tutorial/static-files.md new file mode 100644 index 000000000..db30f13bc --- /dev/null +++ b/docs/tr/docs/tutorial/static-files.md @@ -0,0 +1,40 @@ +# Statik Dosyalar + +`StaticFiles`'ı kullanarak statik dosyaları bir yol altında sunabilirsiniz. + +## `StaticFiles` Kullanımı + +* `StaticFiles` sınıfını projenize dahil edin. +* Bir `StaticFiles()` örneğini belirli bir yola bağlayın. + +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} + +/// note | Teknik Detaylar + +Projenize dahil etmek için `from starlette.staticfiles import StaticFiles` kullanabilirsiniz. + +**FastAPI**, geliştiricilere kolaylık sağlamak amacıyla `starlette.staticfiles`'ı `fastapi.staticfiles` olarak sağlar. Ancak `StaticFiles` sınıfı aslında doğrudan Starlette'den gelir. + +/// + +### Bağlama (Mounting) Nedir? + +"Bağlamak", belirli bir yola tamamen "bağımsız" bir uygulama eklemek anlamına gelir ve ardından tüm alt yollara gelen istekler bu uygulama tarafından işlenir. + +Bu, bir `APIRouter` kullanmaktan farklıdır çünkü bağlanmış bir uygulama tamamen bağımsızdır. Ana uygulamanızın OpenAPI ve dokümanlar, bağlanmış uygulamadan hiçbir şey içermez, vb. + +[Advanced User Guide](../advanced/index.md){.internal-link target=_blank} bölümünde daha fazla bilgi edinebilirsiniz. + +## Detaylar + +`"/static"` ifadesi, bu "alt uygulamanın" "bağlanacağı" alt yolu belirtir. Bu nedenle, `"/static"` ile başlayan her yol, bu uygulama tarafından işlenir. + +`directory="static"` ifadesi, statik dosyalarınızı içeren dizinin adını belirtir. + +`name="static"` ifadesi, alt uygulamanın **FastAPI** tarafından kullanılacak ismini belirtir. + +Bu parametrelerin hepsi "`static`"den farklı olabilir, bunları kendi uygulamanızın ihtiyaçlarına göre belirleyebilirsiniz. + +## Daha Fazla Bilgi + +Daha fazla detay ve seçenek için Starlette'in Statik Dosyalar hakkındaki dokümantasyonunu incelleyin. diff --git a/docs/uk/docs/alternatives.md b/docs/uk/docs/alternatives.md index e71257976..1acbe237a 100644 --- a/docs/uk/docs/alternatives.md +++ b/docs/uk/docs/alternatives.md @@ -30,12 +30,17 @@ Це був один із перших прикладів **автоматичної документації API**, і саме це була одна з перших ідей, яка надихнула на «пошук» **FastAPI**. -!!! Примітка - Django REST Framework створив Том Крісті. Той самий творець Starlette і Uvicorn, на яких базується **FastAPI**. +/// note | Примітка +Django REST Framework створив Том Крісті. Той самий творець Starlette і Uvicorn, на яких базується **FastAPI**. -!!! Перегляньте "Надихнуло **FastAPI** на" - Мати автоматичний веб-інтерфейс документації API. +/// + +/// check | Надихнуло **FastAPI** на + +Мати автоматичний веб-інтерфейс документації API. + +/// ### Flask @@ -51,11 +56,13 @@ Flask — це «мікрофреймворк», він не включає ін Враховуючи простоту Flask, він здавався хорошим підходом для створення API. Наступним, що знайшов, був «Django REST Framework» для Flask. -!!! Переглянте "Надихнуло **FastAPI** на" - Бути мікрофреймоворком. Зробити легким комбінування та поєднання необхідних інструментів та частин. +/// check | Надихнуло **FastAPI** на - Мати просту та легку у використанні систему маршрутизації. +Бути мікрофреймоворком. Зробити легким комбінування та поєднання необхідних інструментів та частин. + Мати просту та легку у використанні систему маршрутизації. + +/// ### Requests @@ -91,11 +98,13 @@ def read_url(): Зверніть увагу на схожість у `requests.get(...)` і `@app.get(...)`. -!!! Перегляньте "Надихнуло **FastAPI** на" - * Майте простий та інтуїтивно зрозумілий API. - * Використовуйте імена (операції) методів HTTP безпосередньо, простим та інтуїтивно зрозумілим способом. - * Розумні параметри за замовчуванням, але потужні налаштування. +/// check | Надихнуло **FastAPI** на + +* Майте простий та інтуїтивно зрозумілий API. + * Використовуйте імена (операції) методів HTTP безпосередньо, простим та інтуїтивно зрозумілим способом. + * Розумні параметри за замовчуванням, але потужні налаштування. +/// ### Swagger / OpenAPI @@ -109,15 +118,18 @@ def read_url(): Тому, коли говорять про версію 2.0, прийнято говорити «Swagger», а про версію 3+ «OpenAPI». -!!! Перегляньте "Надихнуло **FastAPI** на" - Прийняти і використовувати відкритий стандарт для специфікацій API замість спеціальної схеми. +/// check | Надихнуло **FastAPI** на + +Прийняти і використовувати відкритий стандарт для специфікацій API замість спеціальної схеми. - Інтегрувати інструменти інтерфейсу на основі стандартів: + Інтегрувати інструменти інтерфейсу на основі стандартів: - * Інтерфейс Swagger - * ReDoc + * Інтерфейс Swagger + * ReDoc - Ці два було обрано через те, що вони досить популярні та стабільні, але, виконавши швидкий пошук, ви можете знайти десятки додаткових альтернативних інтерфейсів для OpenAPI (які можна використовувати з **FastAPI**). + Ці два було обрано через те, що вони досить популярні та стабільні, але, виконавши швидкий пошук, ви можете знайти десятки додаткових альтернативних інтерфейсів для OpenAPI (які можна використовувати з **FastAPI**). + +/// ### Фреймворки REST для Flask @@ -135,8 +147,11 @@ Marshmallow створено для забезпечення цих функці Але він був створений до того, як існували підказки типу Python. Отже, щоб визначити кожну схему, вам потрібно використовувати спеціальні утиліти та класи, надані Marshmallow. -!!! Перегляньте "Надихнуло **FastAPI** на" - Використовувати код для автоматичного визначення "схем", які надають типи даних і перевірку. +/// check | Надихнуло **FastAPI** на + +Використовувати код для автоматичного визначення "схем", які надають типи даних і перевірку. + +/// ### Webargs @@ -148,11 +163,17 @@ Webargs — це інструмент, створений, щоб забезпе Це чудовий інструмент, і я також часто використовував його, перш ніж створити **FastAPI**. -!!! Інформація - Webargs був створений тими ж розробниками Marshmallow. +/// info | Інформація + +Webargs був створений тими ж розробниками Marshmallow. + +/// + +/// check | Надихнуло **FastAPI** на -!!! Перегляньте "Надихнуло **FastAPI** на" - Мати автоматичну перевірку даних вхідного запиту. +Мати автоматичну перевірку даних вхідного запиту. + +/// ### APISpec @@ -172,12 +193,17 @@ Marshmallow і Webargs забезпечують перевірку, аналіз Редактор тут нічим не може допомогти. І якщо ми змінимо параметри чи схеми Marshmallow і забудемо також змінити цю строку документа YAML, згенерована схема буде застарілою. -!!! Інформація - APISpec був створений тими ж розробниками Marshmallow. +/// info | Інформація + +APISpec був створений тими ж розробниками Marshmallow. + +/// +/// check | Надихнуло **FastAPI** на -!!! Перегляньте "Надихнуло **FastAPI** на" - Підтримувати відкритий стандарт API, OpenAPI. +Підтримувати відкритий стандарт API, OpenAPI. + +/// ### Flask-apispec @@ -199,11 +225,17 @@ Marshmallow і Webargs забезпечують перевірку, аналіз І ці самі генератори повного стеку були основою [**FastAPI** генераторів проектів](project-generation.md){.internal-link target=_blank}. -!!! Інформація - Flask-apispec був створений тими ж розробниками Marshmallow. +/// info | Інформація + +Flask-apispec був створений тими ж розробниками Marshmallow. + +/// -!!! Перегляньте "Надихнуло **FastAPI** на" - Створення схеми OpenAPI автоматично з того самого коду, який визначає серіалізацію та перевірку. +/// check | Надихнуло **FastAPI** на + +Створення схеми OpenAPI автоматично з того самого коду, який визначає серіалізацію та перевірку. + +/// ### NestJS (та Angular) @@ -219,24 +251,33 @@ Marshmallow і Webargs забезпечують перевірку, аналіз Він не дуже добре обробляє вкладені моделі. Отже, якщо тіло JSON у запиті є об’єктом JSON із внутрішніми полями, які, у свою чергу, є вкладеними об’єктами JSON, його неможливо належним чином задокументувати та перевірити. -!!! Перегляньте "Надихнуло **FastAPI** на" - Використовувати типи Python, щоб мати чудову підтримку редактора. +/// check | Надихнуло **FastAPI** на + +Використовувати типи Python, щоб мати чудову підтримку редактора. - Мати потужну систему впровадження залежностей. Знайдіть спосіб звести до мінімуму повторення коду. + Мати потужну систему впровадження залежностей. Знайдіть спосіб звести до мінімуму повторення коду. + +/// ### Sanic Це був один із перших надзвичайно швидких фреймворків Python на основі `asyncio`. Він був дуже схожий на Flask. -!!! Примітка "Технічні деталі" - Він використовував `uvloop` замість стандартного циклу Python `asyncio`. Ось що зробило його таким швидким. +/// note | Технічні деталі + +Він використовував `uvloop` замість стандартного циклу Python `asyncio`. Ось що зробило його таким швидким. - Це явно надихнуло Uvicorn і Starlette, які зараз швидші за Sanic у відкритих тестах. + Це явно надихнуло Uvicorn і Starlette, які зараз швидші за Sanic у відкритих тестах. -!!! Перегляньте "Надихнуло **FastAPI** на" - Знайти спосіб отримати божевільну продуктивність. +/// - Ось чому **FastAPI** базується на Starlette, оскільки це найшвидша доступна структура (перевірена тестами сторонніх розробників). +/// check | Надихнуло **FastAPI** на + +Знайти спосіб отримати божевільну продуктивність. + + Ось чому **FastAPI** базується на Starlette, оскільки це найшвидша доступна структура (перевірена тестами сторонніх розробників). + +/// ### Falcon @@ -246,12 +287,15 @@ Falcon — ще один високопродуктивний фреймворк Таким чином, перевірка даних, серіалізація та документація повинні виконуватися в коді, а не автоматично. Або вони повинні бути реалізовані як фреймворк поверх Falcon, як Hug. Така сама відмінність спостерігається в інших фреймворках, натхненних дизайном Falcon, що мають один об’єкт запиту та один об’єкт відповіді як параметри. -!!! Перегляньте "Надихнуло **FastAPI** на" - Знайти способи отримати чудову продуктивність. +/// check | Надихнуло **FastAPI** на - Разом із Hug (оскільки Hug базується на Falcon) надихнув **FastAPI** оголосити параметр `response` у функціях. +Знайти способи отримати чудову продуктивність. - Хоча у FastAPI це необов’язково, і використовується в основному для встановлення заголовків, файлів cookie та альтернативних кодів стану. + Разом із Hug (оскільки Hug базується на Falcon) надихнув **FastAPI** оголосити параметр `response` у функціях. + + Хоча у FastAPI це необов’язково, і використовується в основному для встановлення заголовків, файлів cookie та альтернативних кодів стану. + +/// ### Molten @@ -269,12 +313,15 @@ Falcon — ще один високопродуктивний фреймворк Маршрути оголошуються в одному місці з використанням функцій, оголошених в інших місцях (замість використання декораторів, які можна розмістити безпосередньо поверх функції, яка обробляє кінцеву точку). Це ближче до того, як це робить Django, ніж до Flask (і Starlette). Він розділяє в коді речі, які відносно тісно пов’язані. -!!! Перегляньте "Надихнуло **FastAPI** на" - Визначити додаткові перевірки для типів даних, використовуючи значення "за замовчуванням" атрибутів моделі. Це покращує підтримку редактора, а раніше вона була недоступна в Pydantic. +/// check | Надихнуло **FastAPI** на + +Визначити додаткові перевірки для типів даних, використовуючи значення "за замовчуванням" атрибутів моделі. Це покращує підтримку редактора, а раніше вона була недоступна в Pydantic. - Це фактично надихнуло оновити частини Pydantic, щоб підтримувати той самий стиль оголошення перевірки (всі ці функції вже доступні в Pydantic). + Це фактично надихнуло оновити частини Pydantic, щоб підтримувати той самий стиль оголошення перевірки (всі ці функції вже доступні в Pydantic). -### Hug +/// + +### Hug Hug був одним із перших фреймворків, який реалізував оголошення типів параметрів API за допомогою підказок типу Python. Це була чудова ідея, яка надихнула інші інструменти зробити те саме. @@ -288,15 +335,21 @@ Hug був одним із перших фреймворків, який реа Оскільки він заснований на попередньому стандарті для синхронних веб-фреймворків Python (WSGI), він не може працювати з Websockets та іншими речами, хоча він також має високу продуктивність. -!!! Інформація - Hug створив Тімоті Крослі, той самий творець `isort`, чудовий інструмент для автоматичного сортування імпорту у файлах Python. +/// info | Інформація + +Hug створив Тімоті Крослі, той самий творець `isort`, чудовий інструмент для автоматичного сортування імпорту у файлах Python. + +/// -!!! Перегляньте "Надихнуло **FastAPI** на" - Hug надихнув частину APIStar і був одним із найбільш перспективних інструментів, поряд із APIStar. +/// check | Надихнуло **FastAPI** на - Hug надихнув **FastAPI** на використання підказок типу Python для оголошення параметрів і автоматичного створення схеми, що визначає API. +Hug надихнув частину APIStar і був одним із найбільш перспективних інструментів, поряд із APIStar. - Hug надихнув **FastAPI** оголосити параметр `response` у функціях для встановлення заголовків і файлів cookie. + Hug надихнув **FastAPI** на використання підказок типу Python для оголошення параметрів і автоматичного створення схеми, що визначає API. + + Hug надихнув **FastAPI** оголосити параметр `response` у функціях для встановлення заголовків і файлів cookie. + +/// ### APIStar (<= 0,5) @@ -322,25 +375,31 @@ Hug був одним із перших фреймворків, який реа Тепер APIStar — це набір інструментів для перевірки специфікацій OpenAPI, а не веб-фреймворк. -!!! Інформація - APIStar створив Том Крісті. Той самий хлопець, який створив: +/// info | Інформація + +APIStar створив Том Крісті. Той самий хлопець, який створив: - * Django REST Framework - * Starlette (на якому базується **FastAPI**) - * Uvicorn (використовується Starlette і **FastAPI**) + * Django REST Framework + * Starlette (на якому базується **FastAPI**) + * Uvicorn (використовується Starlette і **FastAPI**) -!!! Перегляньте "Надихнуло **FastAPI** на" - Існувати. +/// - Ідею оголошення кількох речей (перевірки даних, серіалізації та документації) за допомогою тих самих типів Python, які в той же час забезпечували чудову підтримку редактора, я вважав геніальною ідеєю. +/// check | Надихнуло **FastAPI** на - І після тривалого пошуку подібної структури та тестування багатьох різних альтернатив, APIStar став найкращим доступним варіантом. +Існувати. - Потім APIStar перестав існувати як сервер, і було створено Starlette, який став новою кращою основою для такої системи. Це стало останнім джерелом натхнення для створення **FastAPI**. Я вважаю **FastAPI** «духовним спадкоємцем» APIStar, удосконалюючи та розширюючи функції, систему введення тексту та інші частини на основі досвіду, отриманого від усіх цих попередніх інструментів. + Ідею оголошення кількох речей (перевірки даних, серіалізації та документації) за допомогою тих самих типів Python, які в той же час забезпечували чудову підтримку редактора, я вважав геніальною ідеєю. + + І після тривалого пошуку подібної структури та тестування багатьох різних альтернатив, APIStar став найкращим доступним варіантом. + + Потім APIStar перестав існувати як сервер, і було створено Starlette, який став новою кращою основою для такої системи. Це стало останнім джерелом натхнення для створення **FastAPI**. Я вважаю **FastAPI** «духовним спадкоємцем» APIStar, удосконалюючи та розширюючи функції, систему введення тексту та інші частини на основі досвіду, отриманого від усіх цих попередніх інструментів. + +/// ## Використовується **FastAPI** -### Pydantic +### Pydantic Pydantic — це бібліотека для визначення перевірки даних, серіалізації та документації (за допомогою схеми JSON) на основі підказок типу Python. @@ -348,10 +407,13 @@ Pydantic — це бібліотека для визначення переві Його можна порівняти з Marshmallow. Хоча він швидший за Marshmallow у тестах. Оскільки він базується на тих самих підказках типу Python, підтримка редактора чудова. -!!! Перегляньте "**FastAPI** використовує його для" - Виконання перевірки всіх даних, серіалізації даних і автоматичної документацію моделі (на основі схеми JSON). +/// check | **FastAPI** використовує його для - Потім **FastAPI** бере ці дані схеми JSON і розміщує їх у OpenAPI, окремо від усіх інших речей, які він робить. +Виконання перевірки всіх даних, серіалізації даних і автоматичної документацію моделі (на основі схеми JSON). + + Потім **FastAPI** бере ці дані схеми JSON і розміщує їх у OpenAPI, окремо від усіх інших речей, які він робить. + +/// ### Starlette @@ -380,17 +442,23 @@ Starlette надає всі основні функції веб-мікрофр Це одна з головних речей, які **FastAPI** додає зверху, все на основі підказок типу Python (з використанням Pydantic). Це, а також система впровадження залежностей, утиліти безпеки, створення схеми OpenAPI тощо. -!!! Примітка "Технічні деталі" - ASGI — це новий «стандарт», який розробляється членами основної команди Django. Це ще не «стандарт Python» (PEP), хоча вони в процесі цього. +/// note | Технічні деталі + +ASGI — це новий «стандарт», який розробляється членами основної команди Django. Це ще не «стандарт Python» (PEP), хоча вони в процесі цього. - Тим не менш, він уже використовується як «стандарт» кількома інструментами. Це значно покращує сумісність, оскільки ви можете переключити Uvicorn на будь-який інший сервер ASGI (наприклад, Daphne або Hypercorn), або ви можете додати інструменти, сумісні з ASGI, як-от `python-socketio`. + Тим не менш, він уже використовується як «стандарт» кількома інструментами. Це значно покращує сумісність, оскільки ви можете переключити Uvicorn на будь-який інший сервер ASGI (наприклад, Daphne або Hypercorn), або ви можете додати інструменти, сумісні з ASGI, як-от `python-socketio`. -!!! Перегляньте "**FastAPI** використовує його для" - Керування всіма основними веб-частинами. Додавання функцій зверху. +/// - Сам клас `FastAPI` безпосередньо успадковує клас `Starlette`. +/// check | **FastAPI** використовує його для - Отже, усе, що ви можете робити зі Starlette, ви можете робити це безпосередньо за допомогою **FastAPI**, оскільки це, по суті, Starlette на стероїдах. +Керування всіма основними веб-частинами. Додавання функцій зверху. + + Сам клас `FastAPI` безпосередньо успадковує клас `Starlette`. + + Отже, усе, що ви можете робити зі Starlette, ви можете робити це безпосередньо за допомогою **FastAPI**, оскільки це, по суті, Starlette на стероїдах. + +/// ### Uvicorn @@ -400,12 +468,15 @@ Uvicorn — це блискавичний сервер ASGI, побудован Це рекомендований сервер для Starlette і **FastAPI**. -!!! Перегляньте "**FastAPI** рекомендує це як" - Основний веб-сервер для запуску програм **FastAPI**. +/// check | **FastAPI** рекомендує це як + +Основний веб-сервер для запуску програм **FastAPI**. + + Ви можете поєднати його з Gunicorn, щоб мати асинхронний багатопроцесний сервер. - Ви можете поєднати його з Gunicorn, щоб мати асинхронний багатопроцесний сервер. + Додаткову інформацію див. у розділі [Розгортання](deployment/index.md){.internal-link target=_blank}. - Додаткову інформацію див. у розділі [Розгортання](deployment/index.md){.internal-link target=_blank}. +/// ## Орієнтири та швидкість diff --git a/docs/uk/docs/fastapi-cli.md b/docs/uk/docs/fastapi-cli.md new file mode 100644 index 000000000..6bbbbc326 --- /dev/null +++ b/docs/uk/docs/fastapi-cli.md @@ -0,0 +1,83 @@ +# FastAPI CLI + +**FastAPI CLI** це програма командного рядка, яку Ви можете використовувати, щоб обслуговувати Ваш додаток FastAPI, керувати Вашими FastApi проектами, тощо. + +Коли Ви встановлюєте FastApi (тобто виконуєте `pip install "fastapi[standard]"`), Ви також встановлюєте пакунок `fastapi-cli`, цей пакунок надає команду `fastapi` в терміналі. + +Для запуску Вашого FastAPI проекту для розробки, Ви можете скористатись командою `fastapi dev`: + +
+ +```console +$ fastapi dev main.py +INFO Using path main.py +INFO Resolved absolute path /home/user/code/awesomeapp/main.py +INFO Searching for package file structure from directories with __init__.py files +INFO Importing from /home/user/code/awesomeapp + + ╭─ Python module file ─╮ + │ │ + │ 🐍 main.py │ + │ │ + ╰──────────────────────╯ + +INFO Importing module main +INFO Found importable FastAPI app + + ╭─ Importable FastAPI app ─╮ + │ │ + │ from main import app │ + │ │ + ╰──────────────────────────╯ + +INFO Using import string main:app + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + fastapi run + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [2265862] using WatchFiles +INFO: Started server process [2265873] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +Програма командного рядка `fastapi` це **FastAPI CLI**. + +FastAPI CLI приймає шлях до Вашої Python програми (напр. `main.py`) і автоматично виявляє екземпляр `FastAPI` (зазвичай названий `app`), обирає коректний процес імпорту, а потім обслуговує його. + +Натомість, для запуску у продакшн використовуйте `fastapi run`. 🚀 + +Всередині **FastAPI CLI** використовує Uvicorn, високопродуктивний, production-ready, ASGI cервер. 😎 + +## `fastapi dev` + +Використання `fastapi dev` ініціює режим розробки. + +За замовчуванням, **автоматичне перезавантаження** увімкнене, автоматично перезавантажуючи сервер кожного разу, коли Ви змінюєте Ваш код. Це ресурсо-затратно, та може бути менш стабільним, ніж коли воно вимкнене. Ви повинні використовувати його тільки під час розробки. Воно також слухає IP-адресу `127.0.0.1`, що є IP Вашого девайсу для самостійної комунікації з самим собою (`localhost`). + +## `fastapi run` + +Виконання `fastapi run` запустить FastAPI у продакшн-режимі за замовчуванням. + +За замовчуванням, **автоматичне перезавантаження** вимкнене. Воно також прослуховує IP-адресу `0.0.0.0`, що означає всі доступні IP адреси, тим самим даючи змогу будь-кому комунікувати з девайсом. Так Ви зазвичай будете запускати його у продакшн, наприклад у контейнері. + +В більшості випадків Ви можете (і маєте) мати "termination proxy", який обробляє HTTPS для Вас, це залежить від способу розгортання вашого додатку, Ваш провайдер може зробити це для Вас, або Вам потрібно налаштувати його самостійно. + +/// tip + +Ви можете дізнатись більше про це у [документації про розгортування](deployment/index.md){.internal-link target=_blank}. + +/// diff --git a/docs/uk/docs/fastapi-people.md b/docs/uk/docs/fastapi-people.md deleted file mode 100644 index b32f0e5ce..000000000 --- a/docs/uk/docs/fastapi-people.md +++ /dev/null @@ -1,178 +0,0 @@ -# Люди FastAPI - -FastAPI має дивовижну спільноту, яка вітає людей різного походження. - -## Творець – Супроводжувач - -Привіт! 👋 - -Це я: - -{% if people %} -
-{% for user in people.maintainers %} - -
@{{ user.login }}
Answers: {{ user.answers }}
Pull Requests: {{ user.prs }}
-{% endfor %} - -
-{% endif %} - -Я - творець і супроводжувач **FastAPI**. Детальніше про це можна прочитати в [Довідка FastAPI - Отримати довідку - Зв'язатися з автором](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. - -...Але тут я хочу показати вам спільноту. - ---- - -**FastAPI** отримує велику підтримку від спільноти. І я хочу відзначити їхній внесок. - -Це люди, які: - -* [Допомагають іншим із проблемами (запитаннями) у GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}. -* [Створюють пул реквести](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. -* Переглядають пул реквести, [особливо важливо для перекладів](contributing.md#translations){.internal-link target=_blank}. - -Оплески їм. 👏 🙇 - -## Найбільш активні користувачі минулого місяця - -Це користувачі, які [найбільше допомагали іншим із проблемами (запитаннями) у GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank} протягом минулого місяця. ☕ - -{% if people %} -
-{% for user in people.last_month_active %} - -
@{{ user.login }}
Issues replied: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Експерти - -Ось **експерти FastAPI**. 🤓 - -Це користувачі, які [найбільше допомагали іншим із проблемами (запитаннями) у GitHub](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank} протягом *всього часу*. - -Вони зарекомендували себе як експерти, допомагаючи багатьом іншим. ✨ - -{% if people %} -
-{% for user in people.experts %} - -
@{{ user.login }}
Issues replied: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Найкращі контрибютори - -Ось **Найкращі контрибютори**. 👷 - -Ці користувачі [створили найбільшу кількість пул реквестів](help-fastapi.md#create-a-pull-request){.internal-link target=_blank} які були *змержені*. - -Вони надали програмний код, документацію, переклади тощо. 📦 - -{% if people %} -
-{% for user in people.top_contributors %} - -
@{{ user.login }}
Pull Requests: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -Є багато інших контрибюторів (більше сотні), їх усіх можна побачити на сторінці FastAPI GitHub Contributors. 👷 - -## Найкращі рецензенти - -Ці користувачі є **Найкращими рецензентами**. 🕵️ - -### Рецензенти на переклади - -Я розмовляю лише кількома мовами (і не дуже добре 😅). Отже, рецензенти – це ті, хто має [**повноваження схвалювати переклади**](contributing.md#translations){.internal-link target=_blank} документації. Без них не було б документації кількома іншими мовами. - ---- - -**Найкращі рецензенти** 🕵️ переглянули більшість пул реквестів від інших, забезпечуючи якість коду, документації і особливо **перекладів**. - -{% if people %} -
-{% for user in people.top_reviewers %} - -
@{{ user.login }}
Reviews: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Спонсори - -Це **Спонсори**. 😎 - -Вони підтримують мою роботу з **FastAPI** (та іншими), переважно через GitHub Sponsors. - -{% if sponsors %} - -{% if sponsors.gold %} - -### Золоті спонсори - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Срібні спонсори - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Бронзові спонсори - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -{% endif %} - -### Індивідуальні спонсори - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
- -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
- -{% endfor %} -{% endif %} - -## Про дані - технічні деталі - -Основна мета цієї сторінки – висвітлити зусилля спільноти, щоб допомогти іншим. - -Особливо враховуючи зусилля, які зазвичай менш помітні, а в багатьох випадках більш важкі, як-от допомога іншим із проблемами та перегляд пул реквестів перекладів. - -Дані розраховуються щомісяця, ви можете ознайомитися з вихідним кодом тут. - -Тут я також підкреслюю внески спонсорів. - -Я також залишаю за собою право оновлювати алгоритми підрахунку, види рейтингів, порогові значення тощо (про всяк випадок 🤷). diff --git a/docs/uk/docs/features.md b/docs/uk/docs/features.md new file mode 100644 index 000000000..7d679d8ee --- /dev/null +++ b/docs/uk/docs/features.md @@ -0,0 +1,189 @@ +# Функціональні можливості + +## Функціональні можливості FastAPI + +**FastAPI** надає вам такі можливості: + +### Використання відкритих стандартів + +* OpenAPI для створення API, включаючи оголошення шляхів, операцій, параметрів, тіл запитів, безпеки тощо. +* Автоматична документація моделей даних за допомогою JSON Schema (оскільки OpenAPI базується саме на JSON Schema). +* Розроблено на основі цих стандартів після ретельного аналізу, а не як додатковий рівень поверх основної архітектури. +* Це також дає змогу автоматично **генерувати код клієнта** багатьма мовами. + +### Автоматична генерація документації + +Інтерактивна документація API та вебінтерфейс для його дослідження. Оскільки фреймворк базується на OpenAPI, є кілька варіантів, два з яких включені за замовчуванням. + +* Swagger UI — дозволяє інтерактивно переглядати API, викликати та тестувати його прямо у браузері. + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* Альтернативна документація API за допомогою ReDoc. + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### Тільки сучасний Python + +FastAPI використовує стандартні **типи Python** (завдяки Pydantic). Вам не потрібно вивчати новий синтаксис — лише стандартний сучасний Python. + +Якщо вам потрібне коротке нагадування про використання типів у Python (навіть якщо ви не використовуєте FastAPI), перегляньте короткий підручник: [Вступ до типів Python](python-types.md){.internal-link target=_blank}. + +Ось приклад стандартного Python-коду з типами: + +```Python +from datetime import date +from pydantic import BaseModel + +# Оголошення змінної як 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) +``` + +/// info | Інформація + +`**second_user_data` означає: + +Передати ключі та значення словника `second_user_data` як аргументи у вигляді "ключ-значення", еквівалентно `User(id=4, name="Mary", joined="2018-11-30")`. + +/// + +### Підтримка редакторів (IDE) + +Фреймворк спроєктований так, щоб бути легким і інтуїтивно зрозумілим. Усі рішення тестувалися у різних редакторах ще до початку розробки, щоб забезпечити найкращий досвід програмування. + +За результатами опитувань розробників Python однією з найпопулярніших функцій є "автодоповнення". + +**FastAPI** повністю підтримує автодоповнення у всіх місцях, тому вам рідко доведеться повертатися до документації. + +Приклад автодоповнення у редакторах: + +* у Visual Studio Code: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +* у PyCharm: + +![editor support](https://fastapi.tiangolo.com/img/pycharm-completion.png) + +### Короткий код +FastAPI має розумні налаштування **за замовчуванням**, але всі параметри можна налаштовувати відповідно до ваших потреб. Однак за замовчуванням все "просто працює". + +### Валідація +* Підтримка валідації для більшості (або всіх?) **типів даних Python**, зокрема: + * JSON-об'єктів (`dict`). + * JSON-списків (`list`) з визначенням типів елементів. + * Рядків (`str`) із мінімальною та максимальною довжиною. + * Чисел (`int`, `float`) з обмеженнями мінімальних та максимальних значень тощо. + +* Валідація складніших типів, таких як: + * URL. + * Email. + * UUID. + * ...та інші. + +Уся валідація виконується через надійний та перевірений **Pydantic**. + +### Безпека та автентифікація + +**FastAPI** підтримує вбудовану автентифікацію та авторизацію, без прив’язки до конкретних баз даних чи моделей даних. + +Підтримуються всі схеми безпеки OpenAPI, включаючи: + +* HTTP Basic. +* **OAuth2** (також із підтримкою **JWT-токенів**). Див. підручник: [OAuth2 із JWT](tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. +* Ключі API в: + * Заголовках. + * Параметрах запиту. + * Cookies тощо. + +А також усі можливості безпеки від Starlette (зокрема **сесійні cookies**). + +Усі вони створені як багаторазові інструменти та компоненти, які легко інтегруються з вашими системами, сховищами даних, реляційними та NoSQL базами даних тощо. + +### Впровадження залежностей + +**FastAPI** містить надзвичайно просту у використанні, але потужну систему впровадження залежностей. + +* Залежності можуть мати власні залежності, утворюючи ієрархію або **"граф залежностей"**. +* Усі залежності автоматично керуються фреймворком. +* Усі залежності можуть отримувати дані з запитів і розширювати **обмеження операції за шляхом** та автоматичну документацію. +* **Автоматична валідація** навіть для параметрів *операцій шляху*, визначених у залежностях. +* Підтримка складних систем автентифікації користувачів, **з'єднань із базами даних** тощо. +* **Жодних обмежень** щодо використання баз даних, фронтендів тощо, але водночас проста інтеграція з усіма ними. + +### Немає обмежень на "плагіни" + +Або іншими словами, вони не потрібні – просто імпортуйте та використовуйте необхідний код. + +Будь-яка інтеграція спроєктована настільки просто (з використанням залежностей), що ви можете створити "плагін" для свого застосунку всього у 2 рядках коду, використовуючи ту саму структуру та синтаксис, що й для ваших *операцій шляху*. + +### Протестовано + +* 100% покриття тестами. +* 100% анотована типами кодова база. +* Використовується у робочих середовищах. + +## Можливості Starlette + +**FastAPI** повністю сумісний із (та побудований на основі) Starlette. Тому будь-який додатковий код Starlette, який ви маєте, також працюватиме. + +**FastAPI** фактично є підкласом **Starlette**. Тому, якщо ви вже знайомі зі Starlette або використовуєте його, більшість функціональності працюватиме так само. + +З **FastAPI** ви отримуєте всі можливості **Starlette** (адже FastAPI — це, по суті, Starlette на стероїдах): + +* Разюча продуктивність. Це один із найшвидших фреймворків на Python, на рівні з **NodeJS** і **Go**. +* Підтримка **WebSocket**. +* Фонові задачі у процесі. +* Події запуску та завершення роботи. +* Клієнт для тестування, побудований на HTTPX. +* Підтримка **CORS**, **GZip**, статичних файлів, потокових відповідей. +* Підтримка **сесій** і **cookie**. +* 100% покриття тестами. +* 100% анотована типами кодова база. + +## Можливості Pydantic + +**FastAPI** повністю сумісний із (та побудований на основі) Pydantic. Тому будь-який додатковий код Pydantic, який ви маєте, також працюватиме. + +Включаючи зовнішні бібліотеки, побудовані також на Pydantic, такі як ORM, ODM для баз даних. + +Це також означає, що в багатьох випадках ви можете передати той самий об'єкт, який отримуєте з запиту, **безпосередньо в базу даних**, оскільки все автоматично перевіряється. + +Те ж саме відбувається й у зворотному напрямку — у багатьох випадках ви можете просто передати об'єкт, який отримуєте з бази даних, **безпосередньо клієнту**. + +З **FastAPI** ви отримуєте всі можливості **Pydantic** (адже FastAPI базується на Pydantic для обробки всіх даних): + +* **Ніякої плутанини** : + * Не потрібно вчити нову мову для визначення схем. + * Якщо ви знаєте типи Python, ви знаєте, як використовувати Pydantic. +* Легко працює з вашим **IDE/лінтером/мозком**: + * Оскільки структури даних Pydantic є просто екземплярами класів, які ви визначаєте; автодоповнення, лінтинг, mypy і ваша інтуїція повинні добре працювати з вашими перевіреними даними. +* Валідація **складних структур**: + * Використання ієрархічних моделей Pydantic. Python `typing`, `List` і `Dict` тощо. + * Валідатори дозволяють чітко і просто визначати, перевіряти й документувати складні схеми даних у вигляді JSON-схеми. + * Ви можете мати глибоко **вкладені JSON об'єкти** та перевірити та анотувати їх всі. +* **Розширюваність**: + * Pydantic дозволяє визначати користувацькі типи даних або розширювати валідацію методами в моделі декоратором `validator`. +* 100% покриття тестами. diff --git a/docs/uk/docs/index.md b/docs/uk/docs/index.md index fad693f79..b573ee259 100644 --- a/docs/uk/docs/index.md +++ b/docs/uk/docs/index.md @@ -5,11 +5,11 @@ Готовий до продакшину, високопродуктивний, простий у вивченні та швидкий для написання коду фреймворк

- - Test + + Test - - Coverage + + Coverage Package version @@ -23,11 +23,11 @@ **Документація**: https://fastapi.tiangolo.com -**Програмний код**: https://github.com/tiangolo/fastapi +**Програмний код**: https://github.com/fastapi/fastapi --- -FastAPI - це сучасний, швидкий (високопродуктивний), вебфреймворк для створення API за допомогою Python 3.8+,в основі якого лежить стандартна анотація типів Python. +FastAPI - це сучасний, швидкий (високопродуктивний), вебфреймворк для створення API за допомогою Python,в основі якого лежить стандартна анотація типів Python. Ключові особливості: @@ -64,7 +64,7 @@ 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._" -

Kabir Khan - Microsoft (ref)
+
Kabir Khan - Microsoft (ref)
--- @@ -88,7 +88,7 @@ FastAPI - це сучасний, швидкий (високопродуктив "_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- @@ -110,12 +110,10 @@ FastAPI - це сучасний, швидкий (високопродуктив ## Вимоги -Python 3.8+ - FastAPI стоїть на плечах гігантів: * Starlette для web частини. -* Pydantic для частини даних. +* Pydantic для частини даних. ## Вставновлення @@ -129,7 +127,7 @@ $ pip install fastapi
-Вам також знадобиться сервер ASGI для продакшину, наприклад Uvicorn або Hypercorn. +Вам також знадобиться сервер ASGI для продакшину, наприклад Uvicorn або Hypercorn.
@@ -326,7 +324,7 @@ def update_item(item_id: int, item: Item): Вам не потрібно вивчати новий синтаксис, методи чи класи конкретної бібліотеки тощо. -Використовуючи стандартний **Python 3.8+**. +Використовуючи стандартний **Python**. Наприклад, для `int`: @@ -439,7 +437,7 @@ item: Item Pydantic використовує: -* email_validator - для валідації електронної пошти. +* email-validator - для валідації електронної пошти. * pydantic-settings - для управління налаштуваннями. * pydantic-extra-types - для додаткових типів, що можуть бути використані з Pydantic. @@ -448,15 +446,15 @@ Starlette використовує: * httpx - Необхідно, якщо Ви хочете використовувати `TestClient`. * jinja2 - Необхідно, якщо Ви хочете використовувати шаблони як конфігурацію за замовчуванням. -* python-multipart - Необхідно, якщо Ви хочете підтримувати "розбір" форми за допомогою `request.form()`. +* python-multipart - Необхідно, якщо Ви хочете підтримувати "розбір" форми за допомогою `request.form()`. * itsdangerous - Необхідно для підтримки `SessionMiddleware`. * pyyaml - Необхідно для підтримки Starlette `SchemaGenerator` (ймовірно, вам це не потрібно з FastAPI). -* ujson - Необхідно, якщо Ви хочете використовувати `UJSONResponse`. FastAPI / Starlette використовують: * uvicorn - для сервера, який завантажує та обслуговує вашу програму. * orjson - Необхідно, якщо Ви хочете використовувати `ORJSONResponse`. +* ujson - Необхідно, якщо Ви хочете використовувати `UJSONResponse`. Ви можете встановити все це за допомогою `pip install fastapi[all]`. diff --git a/docs/uk/docs/learn/index.md b/docs/uk/docs/learn/index.md new file mode 100644 index 000000000..7f9f21e57 --- /dev/null +++ b/docs/uk/docs/learn/index.md @@ -0,0 +1,5 @@ +# Навчання + +У цьому розділі надані вступні та навчальні матеріали для вивчення FastAPI. + +Це можна розглядати як **книгу**, **курс**, або **офіційний** та рекомендований спосіб освоїти FastAPI. 😎 diff --git a/docs/uk/docs/python-types.md b/docs/uk/docs/python-types.md index 6c8e29016..676bafb15 100644 --- a/docs/uk/docs/python-types.md +++ b/docs/uk/docs/python-types.md @@ -12,16 +12,18 @@ Python підтримує додаткові "підказки типу" ("type Але навіть якщо ви ніколи не використаєте **FastAPI**, вам буде корисно дізнатись трохи про них. -!!! note - Якщо ви експерт у Python і ви вже знаєте усе про анотації типів - перейдіть до наступного розділу. +/// note + +Якщо ви експерт у Python і ви вже знаєте усе про анотації типів - перейдіть до наступного розділу. + +/// ## Мотивація Давайте почнемо з простого прикладу: -```Python -{!../../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} + Виклик цієї програми виводить: @@ -35,9 +37,8 @@ John Doe * Конвертує кожну літеру кожного слова у верхній регістр за допомогою `title()`. * Конкатенує їх разом із пробілом по середині. -```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### Редагуйте це @@ -79,9 +80,8 @@ John Doe Це "type hints": -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + Це не те саме, що оголошення значень за замовчуванням, як це було б з: @@ -109,9 +109,8 @@ John Doe Перевірте цю функцію, вона вже має анотацію типу: -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + Оскільки редактор знає типи змінних, ви не тільки отримаєте автозаповнення, ви також отримаєте перевірку помилок: @@ -119,9 +118,8 @@ John Doe Тепер ви знаєте, щоб виправити це, вам потрібно перетворити `age` у строку з допомогою `str(age)`: -```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## Оголошення типів @@ -140,9 +138,8 @@ John Doe * `bool` * `bytes` -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### Generic-типи з параметрами типів @@ -164,45 +161,55 @@ John Doe Наприклад, давайте визначимо змінну, яка буде `list` із `str`. -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +З модуля `typing`, імпортуємо `List` (з великої літери `L`): - З модуля `typing`, імпортуємо `List` (з великої літери `L`): +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial006.py!} +``` + +Оголосимо змінну з тим самим синтаксисом двокрапки (`:`). + +Як тип вкажемо `List`, який ви імпортували з `typing`. + +Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки: - ``` Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +```Python hl_lines="4" +{!> ../../docs_src/python_types/tutorial006.py!} +``` - Оголосимо змінну з тим самим синтаксисом двокрапки (`:`). +//// - Як тип вкажемо `List`, який ви імпортували з `typing`. +//// tab | Python 3.9 і вище - Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки: +Оголосимо змінну з тим самим синтаксисом двокрапки (`:`). - ```Python hl_lines="4" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +Як тип вкажемо `list`. -=== "Python 3.9 і вище" +Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки: - Оголосимо змінну з тим самим синтаксисом двокрапки (`:`). +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial006_py39.py!} +``` - Як тип вкажемо `list`. +//// - Оскільки список є типом, який містить деякі внутрішні типи, ви поміщаєте їх у квадратні дужки: +/// info - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006_py39.py!} - ``` +Ці внутрішні типи в квадратних дужках називаються "параметрами типу". -!!! info - Ці внутрішні типи в квадратних дужках називаються "параметрами типу". +У цьому випадку, `str` це параметр типу переданий у `List` (або `list` у Python 3.9 і вище). - У цьому випадку, `str` це параметр типу переданий у `List` (або `list` у Python 3.9 і вище). +/// Це означає: "змінна `items` це `list`, і кожен з елементів у цьому списку - `str`". -!!! tip - Якщо ви використовуєте Python 3.9 і вище, вам не потрібно імпортувати `List` з `typing`, ви можете використовувати натомість тип `list`. +/// tip + +Якщо ви використовуєте Python 3.9 і вище, вам не потрібно імпортувати `List` з `typing`, ви можете використовувати натомість тип `list`. + +/// Зробивши це, ваш редактор може надати підтримку навіть під час обробки елементів зі списку: @@ -218,17 +225,21 @@ John Doe Ви повинні зробити те ж саме, щоб оголосити `tuple` і `set`: -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial007.py!} - ``` +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial007.py!} +``` + +//// -=== "Python 3.9 і вище" +//// tab | Python 3.9 і вище - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial007_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial007_py39.py!} +``` + +//// Це означає: @@ -243,17 +254,21 @@ John Doe Другий параметр типу для значення у `dict`: -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial008.py!} +``` + +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008.py!} - ``` +//// tab | Python 3.9 і вище -=== "Python 3.9 і вище" +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial008_py39.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008_py39.py!} - ``` +//// Це означає: @@ -269,17 +284,21 @@ John Doe У Python 3.10 також є **альтернативний синтаксис**, у якому ви можете розділити можливі типи за допомогою вертикальної смуги (`|`). -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial008b.py!} +``` + +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008b.py!} - ``` +//// tab | Python 3.10 і вище -=== "Python 3.10 і вище" +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial008b_py310.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008b_py310.py!} - ``` +//// В обох випадках це означає, що `item` може бути `int` або `str`. @@ -290,7 +309,7 @@ John Doe У Python 3.6 і вище (включаючи Python 3.10) ви можете оголосити його, імпортувавши та використовуючи `Optional` з модуля `typing`. ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` Використання `Optional[str]` замість просто `str` дозволить редактору допомогти вам виявити помилки, коли ви могли б вважати, що значенням завжди є `str`, хоча насправді воно також може бути `None`. @@ -299,69 +318,81 @@ John Doe Це також означає, що в Python 3.10 ви можете використовувати `Something | None`: -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009.py!} - ``` +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial009.py!} +``` -=== "Python 3.8 і вище - альтернатива" +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009b.py!} - ``` +//// tab | Python 3.8 і вище - альтернатива -=== "Python 3.10 і вище" +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial009b.py!} +``` - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial009_py310.py!} - ``` +//// + +//// tab | Python 3.10 і вище + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial009_py310.py!} +``` + +//// #### Generic типи Ці типи, які приймають параметри типу у квадратних дужках, називаються **Generic types** or **Generics**, наприклад: -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище + +* `List` +* `Tuple` +* `Set` +* `Dict` +* `Union` +* `Optional` +* ...та інші. - * `List` - * `Tuple` - * `Set` - * `Dict` - * `Union` - * `Optional` - * ...та інші. +//// -=== "Python 3.9 і вище" +//// tab | Python 3.9 і вище - Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині): +Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині): - * `list` - * `tuple` - * `set` - * `dict` +* `list` +* `tuple` +* `set` +* `dict` - І те саме, що й у Python 3.8, із модуля `typing`: +І те саме, що й у Python 3.8, із модуля `typing`: - * `Union` - * `Optional` - * ...та інші. +* `Union` +* `Optional` +* ...та інші. -=== "Python 3.10 і вище" +//// - Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині): +//// tab | Python 3.10 і вище - * `list` - * `tuple` - * `set` - * `dict` +Ви можете використовувати ті самі вбудовані типи, як generic (з квадратними дужками та типами всередині): - І те саме, що й у Python 3.8, із модуля `typing`: +* `list` +* `tuple` +* `set` +* `dict` - * `Union` - * `Optional` (так само як у Python 3.8) - * ...та інші. +І те саме, що й у Python 3.8, із модуля `typing`: - У Python 3.10, як альтернатива використанню `Union` та `Optional`, ви можете використовувати вертикальну смугу (`|`) щоб оголосити об'єднання типів. +* `Union` +* `Optional` (так само як у Python 3.8) +* ...та інші. + +У Python 3.10, як альтернатива використанню `Union` та `Optional`, ви можете використовувати вертикальну смугу (`|`) щоб оголосити об'єднання типів. + +//// ### Класи як типи @@ -369,15 +400,13 @@ John Doe Скажімо, у вас є клас `Person` з імʼям: -```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + Потім ви можете оголосити змінну типу `Person`: -```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + І знову ж таки, ви отримуєте всю підтримку редактора: @@ -385,7 +414,7 @@ John Doe ## Pydantic моделі -Pydantic це бібліотека Python для валідації даних. +Pydantic це бібліотека Python для валідації даних. Ви оголошуєте «форму» даних як класи з атрибутами. @@ -397,26 +426,35 @@ John Doe Приклад з документації Pydantic: -=== "Python 3.8 і вище" +//// tab | Python 3.8 і вище - ```Python - {!> ../../../docs_src/python_types/tutorial011.py!} - ``` +```Python +{!> ../../docs_src/python_types/tutorial011.py!} +``` -=== "Python 3.9 і вище" +//// - ```Python - {!> ../../../docs_src/python_types/tutorial011_py39.py!} - ``` +//// tab | Python 3.9 і вище -=== "Python 3.10 і вище" +```Python +{!> ../../docs_src/python_types/tutorial011_py39.py!} +``` - ```Python - {!> ../../../docs_src/python_types/tutorial011_py310.py!} - ``` +//// -!!! info - Щоб дізнатись більше про Pydantic, перегляньте його документацію. +//// tab | Python 3.10 і вище + +```Python +{!> ../../docs_src/python_types/tutorial011_py310.py!} +``` + +//// + +/// info + +Щоб дізнатись більше про Pydantic, перегляньте його документацію. + +/// **FastAPI** повністю базується на Pydantic. @@ -444,5 +482,8 @@ John Doe Важливо те, що за допомогою стандартних типів Python в одному місці (замість того, щоб додавати більше класів, декораторів тощо), **FastAPI** зробить багато роботи за вас. -!!! info - Якщо ви вже пройшли весь навчальний посібник і повернулися, щоб дізнатися більше про типи, ось хороший ресурс "шпаргалка" від `mypy`. +/// info + +Якщо ви вже пройшли весь навчальний посібник і повернулися, щоб дізнатися більше про типи, ось хороший ресурс "шпаргалка" від `mypy`. + +/// diff --git a/docs/uk/docs/tutorial/body-fields.md b/docs/uk/docs/tutorial/body-fields.md index eee993cbe..7ddd9d104 100644 --- a/docs/uk/docs/tutorial/body-fields.md +++ b/docs/uk/docs/tutorial/body-fields.md @@ -6,98 +6,39 @@ Спочатку вам потрібно імпортувати це: -=== "Python 3.10+" +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *} - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} - ``` +/// warning -=== "Python 3.9+" +Зверніть увагу, що `Field` імпортується прямо з `pydantic`, а не з `fastapi`, як всі інші (`Query`, `Path`, `Body` тощо). - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! tip - Варто користуватись `Annotated` версією, якщо це можливо. - - ```Python hl_lines="2" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - Варто користуватись `Annotated` версією, якщо це можливо. - - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` - -!!! warning - Зверніть увагу, що `Field` імпортується прямо з `pydantic`, а не з `fastapi`, як всі інші (`Query`, `Path`, `Body` тощо). +/// ## Оголошення атрибутів моделі Ви можете використовувати `Field` з атрибутами моделі: -=== "Python 3.10+" - - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} - ``` +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *} -=== "Python 3.9+" - - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="12-15" - {!> ../../../docs_src/body_fields/tutorial001_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! tip - Варто користуватись `Annotated` версією, якщо це можливо.. - - ```Python hl_lines="9-12" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +`Field` працює так само, як `Query`, `Path` і `Body`, у нього такі самі параметри тощо. -=== "Python 3.8+ non-Annotated" +/// note | Технічні деталі - !!! tip - Варто користуватись `Annotated` версією, якщо це можливо.. +Насправді, `Query`, `Path` та інші, що ви побачите далі, створюють об'єкти підкласів загального класу `Param`, котрий сам є підкласом класу `FieldInfo` з Pydantic. - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +І `Field` від Pydantic також повертає екземпляр `FieldInfo`. -`Field` працює так само, як `Query`, `Path` і `Body`, у нього такі самі параметри тощо. +`Body` також безпосередньо повертає об'єкти підкласу `FieldInfo`. І є інші підкласи, які ви побачите пізніше, що є підкласами класу Body. -!!! note "Технічні деталі" - Насправді, `Query`, `Path` та інші, що ви побачите далі, створюють об'єкти підкласів загального класу `Param`, котрий сам є підкласом класу `FieldInfo` з Pydantic. +Пам'ятайте, що коли ви імпортуєте 'Query', 'Path' та інше з 'fastapi', вони фактично є функціями, які повертають спеціальні класи. - І `Field` від Pydantic також повертає екземпляр `FieldInfo`. +/// - `Body` також безпосередньо повертає об'єкти підкласу `FieldInfo`. І є інші підкласи, які ви побачите пізніше, що є підкласами класу Body. +/// tip - Пам'ятайте, що коли ви імпортуєте 'Query', 'Path' та інше з 'fastapi', вони фактично є функціями, які повертають спеціальні класи. +Зверніть увагу, що кожен атрибут моделі із типом, значенням за замовчуванням та `Field` має ту саму структуру, що й параметр *функції обробки шляху*, з `Field` замість `Path`, `Query` і `Body`. -!!! tip - Зверніть увагу, що кожен атрибут моделі із типом, значенням за замовчуванням та `Field` має ту саму структуру, що й параметр *функції обробки шляху*, з `Field` замість `Path`, `Query` і `Body`. +/// ## Додавання додаткової інформації @@ -105,9 +46,12 @@ Ви дізнаєтеся більше про додавання додаткової інформації пізніше у документації, коли вивчатимете визначення прикладів. -!!! warning - Додаткові ключі, передані в `Field`, також будуть присутні у згенерованій схемі OpenAPI для вашого додатка. - Оскільки ці ключі не обов'язково можуть бути частиною специфікації OpenAPI, деякі інструменти OpenAPI, наприклад, [OpenAPI валідатор](https://validator.swagger.io/), можуть не працювати з вашою згенерованою схемою. +/// warning + +Додаткові ключі, передані в `Field`, також будуть присутні у згенерованій схемі OpenAPI для вашого додатка. +Оскільки ці ключі не обов'язково можуть бути частиною специфікації OpenAPI, деякі інструменти OpenAPI, наприклад, [OpenAPI валідатор](https://validator.swagger.io/), можуть не працювати з вашою згенерованою схемою. + +/// ## Підсумок diff --git a/docs/uk/docs/tutorial/body-multiple-params.md b/docs/uk/docs/tutorial/body-multiple-params.md new file mode 100644 index 000000000..e2acf8a70 --- /dev/null +++ b/docs/uk/docs/tutorial/body-multiple-params.md @@ -0,0 +1,170 @@ +# Тіло запиту - Декілька параметрів + +Тепер, коли ми розглянули використання `Path` та `Query`, розгляньмо більш просунуті способи оголошення тіла запиту в **FastAPI**. + +## Змішування `Path`, `Query` та параметрів тіла запиту + +По-перше, звісно, Ви можете вільно змішувати оголошення параметрів `Path`, `Query` та тіла запиту, і **FastAPI** правильно їх обробить. + +Також Ви можете оголосити параметри тіла як необов’язкові, встановивши для них значення за замовчуванням `None`: + +{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *} + +/// note | Примітка + +Зверніть увагу, що в цьому випадку параметр `item`, який береться з тіла запиту, є необов'язковим, оскільки має значення за замовчуванням `None`. + +/// + +## Декілька параметрів тіла запиту + +У попередньому прикладі *операція шляху* очікувала JSON з атрибутами `Item`, наприклад: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` +Але Ви також можете оголосити декілька параметрів тіла, наприклад `item` та `user`: + +{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *} + +У цьому випадку **FastAPI** розпізнає, що є кілька параметрів тіла (два параметри є моделями Pydantic). + +Тому він використає назви параметрів як ключі (назви полів) у тілі запиту, очікуючи: + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + } +} +``` + +/// note | Примітка + +Зверніть увагу, що хоча `item` оголошено, так само як і раніше, тепер він очікується в тілі під ключем `item`. + +/// + +**FastAPI** автоматично конвертує дані із запиту таким чином, щоб параметр `item` отримав свій вміст, і те ж саме стосується `user`. + +Він виконає валідацію складених даних і задокументує їх відповідним чином у схемі OpenAPI та в автоматичній документації. + +## Одиничні значення в тілі запиту + +Так само як є `Query` і `Path` для визначення додаткових даних для параметрів запиту та шляху, **FastAPI** надає еквівалентний `Body`. + +Наприклад, розширюючи попередню модель, Ви можете вирішити додати ще один ключ `importance` в те ж саме тіло запиту разом із `item` і `user`. + +Якщо Ви оголосите його як є, то, оскільки це одиничне значення, **FastAPI** припускатиме, що це параметр запиту (query parameter). + +Але Ви можете вказати **FastAPI** обробляти його як інший ключ тіла (body key), використовуючи `Body`: + +{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *} + +У цьому випадку **FastAPI** очікуватиме тіло запиту у такому вигляді: + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + }, + "importance": 5 +} +``` +Знову ж таки, **FastAPI** конвертуватиме типи даних, перевірятиме їх, створюватиме документацію тощо. + +## Декілька body та query параметрів + +Звісно, Ви можете оголошувати додаткові query параметри запиту, коли це необхідно, на додаток до будь-яких параметрів тіла запиту. + +Оскільки за замовчуванням окремі значення інтерпретуються як параметри запиту, Вам не потрібно явно додавати `Query`, можна просто використати: + +```Python +q: Union[str, None] = None +``` + +Або в Python 3.10 та вище: + +```Python +q: str | None = None +``` + +Наприклад: + +{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *} + + +/// info | Інформація + +`Body` також має ті самі додаткові параметри валідації та метаданих, що й `Query`, `Path` та інші, які Ви побачите пізніше. + +/// + +## Вкладений поодинокий параметр тіла запиту + +Припустимо, у вас є лише один параметр тіла запиту `item` з моделі Pydantic `Item`. + +За замовчуванням **FastAPI** очікуватиме, що тіло запиту міститиме вміст безпосередньо. + +Але якщо Ви хочете, щоб він очікував JSON з ключем `item`, а всередині — вміст моделі (так, як це відбувається при оголошенні додаткових параметрів тіла), Ви можете використати спеціальний параметр `Body` — `embed`: + +```Python +item: Item = Body(embed=True) +``` + +як у прикладі: + +{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *} + +У цьому випадку **FastAPI** очікуватиме тіло запиту такого вигляду: + +```JSON hl_lines="2" +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + } +} +``` + +замість: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +## Підсумок + +Ви можете додавати кілька параметрів тіла до Вашої *функції операції шляху* (*path operation function*), навіть якщо запит може мати лише одне тіло. + +Але **FastAPI** обробить це, надасть Вам потрібні дані у функції, перевірить їх та задокументує коректну схему в *операції шляху*. + +Також Ви можете оголошувати окремі значення, які будуть отримані як частина тіла запиту. + +Крім того, Ви можете вказати **FastAPI** вбудовувати тіло в ключ, навіть якщо оголошено лише один параметр. diff --git a/docs/uk/docs/tutorial/body-nested-models.md b/docs/uk/docs/tutorial/body-nested-models.md new file mode 100644 index 000000000..abc33f2eb --- /dev/null +++ b/docs/uk/docs/tutorial/body-nested-models.md @@ -0,0 +1,245 @@ +# Тіло запиту - Вкладені моделі + +З **FastAPI** Ви можете визначати, перевіряти, документувати та використовувати моделі, які можуть бути вкладені на будь-яку глибину (завдяки Pydantic). + +## Поля списку + +Ви можете визначити атрибут як підтип. Наприклад, Python-список (`list`): + +{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *} + +Це зробить `tags` списком, хоча не визначається тип елементів списку. + +## Поля списку з параметром типу + +Але Python має специфічний спосіб оголошення списків з внутрішніми типами або "параметрами типу": +### Імпортуємо `List` з модуля typing + +У Python 3.9 і вище можна використовувати стандартний `list` для оголошення таких типів, як ми побачимо нижче. 💡 + +Але в Python версії до 3.9 (від 3.6 і вище) спочатку потрібно імпортувати `List` з модуля стандартної бібліотеки Python `typing`: + +{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *} + +### Оголошення `list` з параметром типу + +Щоб оголосити типи з параметрами типу (внутрішніми типами), такими як `list`, `dict`, `tuple`: + +* Якщо Ви використовуєте версію Python до 3.9, імпортуйте їх відповідну версію з модуля `typing`. +* Передайте внутрішні типи як "параметри типу", використовуючи квадратні дужки: `[` and `]`. + +У Python 3.9 це буде виглядати так: + +```Python +my_list: list[str] +``` + +У версіях Python до 3.9 це виглядає так: + +```Python +from typing import List + +my_list: List[str] +``` + +Це стандартний синтаксис Python для оголошення типів. + +Використовуйте той самий стандартний синтаксис для атрибутів моделей з внутрішніми типами. + +Отже, у нашому прикладі, ми можемо зробити `tags` саме "списком рядків": + +{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *} + +## Типи множин + +Але потім ми подумали, що теги не повинні повторюватися, вони, ймовірно, повинні бути унікальними рядками. + +І Python має спеціальний тип даних для множин унікальних елементів — це `set`. + +Тому ми можемо оголосити `tags` як множину рядків: + +{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *} + +Навіть якщо Ви отримаєте запит з дубльованими даними, він буде перетворений у множину унікальних елементів. + +І коли Ви будете виводити ці дані, навіть якщо джерело містить дублікати, вони будуть виведені як множина унікальних елементів. + +І це буде анотовано/документовано відповідно. + +## Вкладені моделі + +Кожен атрибут моделі Pydantic має тип. + +Але цей тип сам може бути іншою моделлю Pydantic. + +Отже, Ви можете оголосити глибоко вкладені JSON "об'єкти" з конкретними іменами атрибутів, типами та перевірками. + +Усе це, вкладене без обмежень. + +### Визначення підмоделі + +Наприклад, ми можемо визначити модель `Image`: + +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *} + +### Використання підмоделі як типу + +А потім ми можемо використовувати її як тип атрибута: + +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *} + +Це означатиме, що **FastAPI** очікуватиме тіло запиту такого вигляду: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2, + "tags": ["rock", "metal", "bar"], + "image": { + "url": "http://example.com/baz.jpg", + "name": "The Foo live" + } +} +``` + +Завдяки такій декларації у **FastAPI** Ви отримуєте: + +* Підтримку в редакторі (автозавершення тощо), навіть для вкладених моделей +* Конвертацію даних +* Валідацію даних +* Автоматичну документацію + +## Спеціальні типи та валідація + +Окрім звичайних типів, таких як `str`, `int`, `float`, та ін. Ви можете використовувати складніші типи, які наслідують `str`. + +Щоб побачити всі доступні варіанти, ознайомтеся з оглядом типів у Pydantic. Деякі приклади будуть у наступних розділах. + +Наприклад, у моделі `Image` є поле `url`, тому ми можемо оголосити його як `HttpUrl` від Pydantic замість `str`: + +{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *} + +Рядок буде перевірено як дійсну URL-адресу і задокументовано в JSON Schema / OpenAPI як URL. + +## Атрибути зі списками підмоделей + +У Pydantic Ви можете використовувати моделі як підтипи для `list`, `set` тощо: + +{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *} + +Це означає, що **FastAPI** буде очікувати (конвертувати, валідувати, документувати тощо) JSON тіло запиту у вигляді: + +```JSON hl_lines="11" +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2, + "tags": [ + "rock", + "metal", + "bar" + ], + "images": [ + { + "url": "http://example.com/baz.jpg", + "name": "The Foo live" + }, + { + "url": "http://example.com/dave.jpg", + "name": "The Baz" + } + ] +} +``` + +/// info | Інформація + +Зверніть увагу, що тепер ключ `images` містить список об'єктів зображень. + +/// + +## Глибоко вкладені моделі + +Ви можете визначати вкладені моделі довільної глибини: + +{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *} + +/// info | Інформація + +Зверніть увагу, що в моделі `Offer` є список `Item`ів, які, своєю чергою, можуть мати необов'язковий список `Image`ів. + +/// + +## Тіла запитів, що складаються зі списків + +Якщо верхній рівень JSON тіла, яке Ви очікуєте, є JSON `масивом` (у Python — `list`), Ви можете оголосити тип у параметрі функції, як і в моделях Pydantic: + +```Python +images: List[Image] +``` +або в Python 3.9 і вище: + +```Python +images: list[Image] +``` + +наприклад: + +{* ../../docs_src/body_nested_models/tutorial008_py39.py hl[13] *} + +## Підтримка в редакторі всюди + +Ви отримаєте підтримку в редакторі всюди. + +Навіть для елементів у списках: + + + +Ви не змогли б отримати таку підтримку в редакторі, якби працювали напряму зі `dict`, а не з моделями Pydantic. + +Але Вам не потрібно турбуватися про це: вхідні dict'и автоматично конвертуються, а вихідні дані автоматично перетворюються в JSON. + +## Тіла з довільними `dict` + +Ви також можете оголосити тіло як `dict` з ключами одного типу та значеннями іншого типу. + +Це корисно, якщо Ви не знаєте наперед, які імена полів будуть дійсними (як у випадку з моделями Pydantic). + +Це буде корисно, якщо Ви хочете приймати ключі, які заздалегідь невідомі. + +--- + +Це також зручно, якщо Ви хочете мати ключі іншого типу (наприклад, `int`). + +Ось що ми розглянемо далі. + +У цьому випадку Ви можете приймати будь-який `dict`, якщо його ключі — це `int`, а значення — `float`: + +{* ../../docs_src/body_nested_models/tutorial009_py39.py hl[7] *} + +/// tip | Порада + +Майте на увазі, що в JSON тілі ключі можуть бути лише рядками (`str`). + +Але Pydantic автоматично конвертує дані. + +Це означає, що навіть якщо клієнти вашого API надсилатимуть ключі у вигляді рядків, якщо вони містять цілі числа, Pydantic конвертує їх і проведе валідацію. + +Тобто `dict`, який Ви отримаєте як `weights`, матиме ключі типу `int` та значення типу `float`. + +/// + +## Підсумок + +З **FastAPI** Ви маєте максимальну гнучкість завдяки моделям Pydantic, зберігаючи при цьому код простим, коротким та елегантним. + +А також отримуєте всі переваги: + +* Підтримка в редакторі (автодоповнення всюди!) +* Конвертація даних (парсинг/сериалізація) +* Валідація даних +* Документація схем +* Автоматичне створення документації diff --git a/docs/uk/docs/tutorial/body.md b/docs/uk/docs/tutorial/body.md index 9759e7f45..38fed7bb8 100644 --- a/docs/uk/docs/tutorial/body.md +++ b/docs/uk/docs/tutorial/body.md @@ -6,30 +6,23 @@ Ваш API майже завжди має надсилати тіло **відповіді**. Але клієнтам не обов’язково потрібно постійно надсилати тіла **запитів**. -Щоб оголосити тіло **запиту**, ви використовуєте Pydantic моделі з усією їх потужністю та перевагами. +Щоб оголосити тіло **запиту**, ви використовуєте Pydantic моделі з усією їх потужністю та перевагами. -!!! info - Щоб надіслати дані, ви повинні використовувати один із: `POST` (більш поширений), `PUT`, `DELETE` або `PATCH`. +/// info - Надсилання тіла із запитом `GET` має невизначену поведінку в специфікаціях, проте воно підтримується FastAPI лише для дуже складних/екстремальних випадків використання. +Щоб надіслати дані, ви повинні використовувати один із: `POST` (більш поширений), `PUT`, `DELETE` або `PATCH`. - Оскільки це не рекомендується, інтерактивна документація з Swagger UI не відображатиме документацію для тіла запиту під час використання `GET`, і проксі-сервери в середині можуть не підтримувати її. +Надсилання тіла із запитом `GET` має невизначену поведінку в специфікаціях, проте воно підтримується FastAPI лише для дуже складних/екстремальних випадків використання. -## Імпортуйте `BaseModel` від Pydantic - -Спочатку вам потрібно імпортувати `BaseModel` з `pydantic`: +Оскільки це не рекомендується, інтерактивна документація з Swagger UI не відображатиме документацію для тіла запиту під час використання `GET`, і проксі-сервери в середині можуть не підтримувати її. -=== "Python 3.8 і вище" +/// - ```Python hl_lines="4" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +## Імпортуйте `BaseModel` від Pydantic -=== "Python 3.10 і вище" +Спочатку вам потрібно імпортувати `BaseModel` з `pydantic`: - ```Python hl_lines="2" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +{* ../../docs_src/body/tutorial001.py hl[4] *} ## Створіть свою модель даних @@ -37,17 +30,7 @@ Використовуйте стандартні типи Python для всіх атрибутів: -=== "Python 3.8 і вище" - - ```Python hl_lines="7-11" - {!> ../../../docs_src/body/tutorial001.py!} - ``` - -=== "Python 3.10 і вище" - - ```Python hl_lines="5-9" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +{* ../../docs_src/body/tutorial001.py hl[7:11] *} Так само, як і при оголошенні параметрів запиту, коли атрибут моделі має значення за замовчуванням, він не є обов’язковим. В іншому випадку це потрібно. Використовуйте `None`, щоб зробити його необов'язковим. @@ -75,17 +58,7 @@ Щоб додати модель даних до вашої *операції шляху*, оголосіть її так само, як ви оголосили параметри шляху та запиту: -=== "Python 3.8 і вище" - - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial001.py!} - ``` - -=== "Python 3.10 і вище" - - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +{* ../../docs_src/body/tutorial001.py hl[18] *} ...і вкажіть її тип як модель, яку ви створили, `Item`. @@ -134,32 +107,25 @@ -!!! tip - Якщо ви використовуєте PyCharm як ваш редактор, ви можете використати Pydantic PyCharm Plugin. - - Він покращує підтримку редакторів для моделей Pydantic за допомогою: +/// tip - * автозаповнення - * перевірки типу - * рефакторингу - * пошуку - * інспекції +Якщо ви використовуєте PyCharm як ваш редактор, ви можете використати Pydantic PyCharm Plugin. -## Використовуйте модель +Він покращує підтримку редакторів для моделей Pydantic за допомогою: -Усередині функції ви можете отримати прямий доступ до всіх атрибутів об’єкта моделі: +* автозаповнення +* перевірки типу +* рефакторингу +* пошуку +* інспекції -=== "Python 3.8 і вище" +/// - ```Python hl_lines="21" - {!> ../../../docs_src/body/tutorial002.py!} - ``` +## Використовуйте модель -=== "Python 3.10 і вище" +Усередині функції ви можете отримати прямий доступ до всіх атрибутів об’єкта моделі: - ```Python hl_lines="19" - {!> ../../../docs_src/body/tutorial002_py310.py!} - ``` +{* ../../docs_src/body/tutorial002.py hl[21] *} ## Тіло запиту + параметри шляху @@ -167,17 +133,7 @@ **FastAPI** розпізнає, що параметри функції, які відповідають параметрам шляху, мають бути **взяті з шляху**, а параметри функції, які оголошуються як моделі Pydantic, **взяті з тіла запиту**. -=== "Python 3.8 і вище" - - ```Python hl_lines="17-18" - {!> ../../../docs_src/body/tutorial003.py!} - ``` - -=== "Python 3.10 і вище" - - ```Python hl_lines="15-16" - {!> ../../../docs_src/body/tutorial003_py310.py!} - ``` +{* ../../docs_src/body/tutorial003.py hl[17:18] *} ## Тіло запиту + шлях + параметри запиту @@ -185,17 +141,7 @@ **FastAPI** розпізнає кожен з них і візьме дані з потрібного місця. -=== "Python 3.8 і вище" - - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial004.py!} - ``` - -=== "Python 3.10 і вище" - - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial004_py310.py!} - ``` +{* ../../docs_src/body/tutorial004.py hl[18] *} Параметри функції будуть розпізнаватися наступним чином: @@ -203,10 +149,13 @@ * Якщо параметр має **сингулярний тип** (наприклад, `int`, `float`, `str`, `bool` тощо), він буде інтерпретуватися як параметр **запиту**. * Якщо параметр оголошується як тип **Pydantic моделі**, він інтерпретується як **тіло** запиту. -!!! note - FastAPI буде знати, що значення "q" не є обов'язковим через значення за замовчуванням "= None". +/// note + +FastAPI буде знати, що значення "q" не є обов'язковим через значення за замовчуванням "= None". + +`Optional` у `Optional[str]` не використовується FastAPI, але дозволить вашому редактору надати вам кращу підтримку та виявляти помилки. - `Optional` у `Optional[str]` не використовується FastAPI, але дозволить вашому редактору надати вам кращу підтримку та виявляти помилки. +/// ## Без Pydantic diff --git a/docs/uk/docs/tutorial/cookie-params.md b/docs/uk/docs/tutorial/cookie-params.md index 199b93839..b320645cb 100644 --- a/docs/uk/docs/tutorial/cookie-params.md +++ b/docs/uk/docs/tutorial/cookie-params.md @@ -6,41 +6,7 @@ Спочатку імпортуйте `Cookie`: -=== "Python 3.10+" - - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! tip - Бажано використовувати `Annotated` версію, якщо це можливо. - - ```Python hl_lines="1" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - Бажано використовувати `Annotated` версію, якщо це можливо. - - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[3] *} ## Визначення параметрів `Cookie` @@ -48,48 +14,20 @@ Перше значення це значення за замовчуванням, ви можете також передати всі додаткові параметри валідації чи анотації: -=== "Python 3.10+" - - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="10" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! tip - Бажано використовувати `Annotated` версію, якщо це можливо. +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9] *} - ```Python hl_lines="7" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +/// note | Технічні Деталі -=== "Python 3.8+ non-Annotated" +`Cookie` це "сестра" класів `Path` і `Query`. Вони наслідуються від одного батьківського класу `Param`. +Але пам'ятайте, що коли ви імпортуєте `Query`, `Path`, `Cookie` та інше з `fastapi`, це фактично функції, що повертають спеціальні класи. - !!! tip - Бажано використовувати `Annotated` версію, якщо це можливо. +/// - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +/// info -!!! note "Технічні Деталі" - `Cookie` це "сестра" класів `Path` і `Query`. Вони наслідуються від одного батьківського класу `Param`. - Але пам'ятайте, що коли ви імпортуєте `Query`, `Path`, `Cookie` та інше з `fastapi`, це фактично функції, що повертають спеціальні класи. +Для визначення cookies ви маєте використовувати `Cookie`, тому що в іншому випадку параметри будуть інтерпритовані, як параметри запиту. -!!! info - Для визначення cookies ви маєте використовувати `Cookie`, тому що в іншому випадку параметри будуть інтерпритовані, як параметри запиту. +/// ## Підсумки diff --git a/docs/uk/docs/tutorial/debugging.md b/docs/uk/docs/tutorial/debugging.md new file mode 100644 index 000000000..b0e5344f8 --- /dev/null +++ b/docs/uk/docs/tutorial/debugging.md @@ -0,0 +1,112 @@ +# Налагодження (Debugging) + +Ви можете під'єднати дебагер у Вашому редакторі коду, наприклад, у Visual Studio Code або PyCharm. + +## Виклик `uvicorn` + +У Вашому FastAPI-додатку імпортуйте та запустіть `uvicorn` безпосередньо: + +{* ../../docs_src/debugging/tutorial001.py hl[1,15] *} + +### Про `__name__ == "__main__"` + +Головна мета використання `__name__ == "__main__"` — це забезпечення виконання певного коду тільки тоді, коли файл запускається безпосередньо: + +
+ +```console +$ python myapp.py +``` + +
+ +але не виконується при його імпорті в інший файл, наприклад: + +```Python +from myapp import app +``` + +#### Детальніше + +Припустимо, Ваш файл називається `myapp.py`. + +Якщо Ви запустите його так: + +
+ +```console +$ python myapp.py +``` + +
+ +тоді внутрішня змінна `__name__`, яка створюється автоматично Python, матиме значення `"__main__"`. + +Отже, цей блок коду: + +```Python + uvicorn.run(app, host="0.0.0.0", port=8000) +``` + +буде виконаний. + +--- + +Це не станеться, якщо Ви імпортуєте цей модуль (файл). + +Якщо у Вас є інший файл, наприклад `importer.py`, з наступним кодом: + +```Python +from myapp import app + +# Додатковий код +``` + +У цьому випадку автоматично створена змінна у файлі `myapp.py` не матиме значення змінної `__name__` як `"__main__"`. + +Отже, рядок: + +```Python + uvicorn.run(app, host="0.0.0.0", port=8000) +``` + +не буде виконано. + +/// info | Інформація + +Більш детальну інформацію можна знайти в офіційній документації Python. + +/// + +## Запуск коду з вашим дебагером + +Оскільки Ви запускаєте сервер Uvicorn безпосередньо з Вашого коду, Ви можете запустити вашу Python програму (ваш FastAPI додаток) безпосередньо з дебагера. + +--- + +Наприклад, у Visual Studio Code Ви можете: + +* Перейдіть на вкладку "Debug". +* Натисніть "Add configuration...". +* Виберіть "Python" +* Запустіть дебагер з опцією "`Python: Current File (Integrated Terminal)`". + +Це запустить сервер з Вашим **FastAPI** кодом, зупиниться на точках зупину тощо. + +Ось як це може виглядати: + + + +--- +Якщо Ви використовуєте PyCharm, ви можете: + +* Відкрити меню "Run". +* Вибрати опцію "Debug...". +* Потім з'явиться контекстне меню. +* Вибрати файл для налагодження (у цьому випадку, `main.py`). + +Це запустить сервер з Вашим **FastAPI** кодом, зупиниться на точках зупину тощо. + +Ось як це може виглядати: + + diff --git a/docs/uk/docs/tutorial/encoder.md b/docs/uk/docs/tutorial/encoder.md index b6583341f..f202c7989 100644 --- a/docs/uk/docs/tutorial/encoder.md +++ b/docs/uk/docs/tutorial/encoder.md @@ -20,17 +20,7 @@ Вона приймає об'єкт, такий як Pydantic model, і повертає його версію, сумісну з JSON: -=== "Python 3.10+" - - ```Python hl_lines="4 21" - {!> ../../../docs_src/encoder/tutorial001_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="5 22" - {!> ../../../docs_src/encoder/tutorial001.py!} - ``` +{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *} У цьому прикладі вона конвертує Pydantic model у `dict`, а `datetime` у `str`. @@ -38,5 +28,8 @@ Вона не повертає велику строку `str`, яка містить дані у форматі JSON (як строка). Вона повертає стандартну структуру даних Python (наприклад `dict`) із значеннями та підзначеннями, які є сумісними з JSON. -!!! Примітка - `jsonable_encoder` фактично використовується **FastAPI** внутрішньо для перетворення даних. Проте вона корисна в багатьох інших сценаріях. +/// note | Примітка + +`jsonable_encoder` фактично використовується **FastAPI** внутрішньо для перетворення даних. Проте вона корисна в багатьох інших сценаріях. + +/// diff --git a/docs/uk/docs/tutorial/extra-data-types.md b/docs/uk/docs/tutorial/extra-data-types.md index ec5ec0d18..5da942b6e 100644 --- a/docs/uk/docs/tutorial/extra-data-types.md +++ b/docs/uk/docs/tutorial/extra-data-types.md @@ -36,7 +36,7 @@ * `datetime.timedelta`: * Пайтонівський `datetime.timedelta`. * У запитах та відповідях буде представлений як `float` загальної кількості секунд. - * Pydantic також дозволяє представляти це як "ISO 8601 time diff encoding", більше інформації дивись у документації. + * Pydantic також дозволяє представляти це як "ISO 8601 time diff encoding", більше інформації дивись у документації. * `frozenset`: * У запитах і відповідях це буде оброблено так само, як і `set`: * У запитах список буде зчитано, дублікати будуть видалені та він буде перетворений на `set`. @@ -49,82 +49,14 @@ * `Decimal`: * Стандартний Пайтонівський `Decimal`. * У запитах і відповідях це буде оброблено так само, як і `float`. -* Ви можете перевірити всі дійсні типи даних Pydantic тут: типи даних Pydantic. +* Ви можете перевірити всі дійсні типи даних Pydantic тут: типи даних Pydantic. ## Приклад Ось приклад *path operation* з параметрами, використовуючи деякі з вищезазначених типів. -=== "Python 3.10+" - - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="1 3 13-17" - {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! tip - Бажано використовувати `Annotated` версію, якщо це можливо. - - ```Python hl_lines="1 2 11-15" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - Бажано використовувати `Annotated` версію, якщо це можливо. - - ```Python hl_lines="1 2 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *} Зверніть увагу, що параметри всередині функції мають свій звичайний тип даних, і ви можете, наприклад, виконувати звичайні маніпуляції з датами, такі як: -=== "Python 3.10+" - - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="19-20" - {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! tip - Бажано використовувати `Annotated` версію, якщо це можливо. - - ```Python hl_lines="17-18" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - Бажано використовувати `Annotated` версію, якщо це можливо. - - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *} diff --git a/docs/uk/docs/tutorial/first-steps.md b/docs/uk/docs/tutorial/first-steps.md new file mode 100644 index 000000000..e910c4ccc --- /dev/null +++ b/docs/uk/docs/tutorial/first-steps.md @@ -0,0 +1,328 @@ +# Перші кроки + +Найпростіший файл FastAPI може виглядати так: + +{* ../../docs_src/first_steps/tutorial001.py *} + +Скопіюйте це до файлу `main.py`. + +Запустіть сервер: + +
+ +```console +$ fastapi dev main.py +INFO Using path main.py +INFO Resolved absolute path /home/user/code/awesomeapp/main.py +INFO Searching for package file structure from directories with __init__.py files +INFO Importing from /home/user/code/awesomeapp + + ╭─ Python module file ─╮ + │ │ + │ 🐍 main.py │ + │ │ + ╰──────────────────────╯ + +INFO Importing module main +INFO Found importable FastAPI app + + ╭─ Importable FastAPI app ─╮ + │ │ + │ from main import app │ + │ │ + ╰──────────────────────────╯ + +INFO Using import string main:app + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + fastapi run + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [2265862] using WatchFiles +INFO: Started server process [2265873] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +У консолі буде рядок приблизно такого змісту: + +```hl_lines="4" +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +Цей рядок показує URL, за яким додаток запускається на вашій локальній машині. + +### Перевірте + +Відкрийте браузер та введіть адресу http://127.0.0.1:8000. + +Ви побачите у відповідь таке повідомлення у форматі JSON: + +```JSON +{"message": "Hello World"} +``` + +### Інтерактивна API документація + +Перейдемо сюди http://127.0.0.1:8000/docs. + +Ви побачите автоматичну інтерактивну API документацію (створену завдяки Swagger UI): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### Альтернативна API документація + +Тепер перейдемо сюди http://127.0.0.1:8000/redoc. + +Ви побачите альтернативну автоматичну документацію (створену завдяки ReDoc): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +### OpenAPI + +**FastAPI** генерує "схему" з усім вашим API, використовуючи стандарт **OpenAPI** для визначення API. + +#### "Схема" + +"Схема" - це визначення або опис чогось. Це не код, який його реалізує, а просто абстрактний опис. + +#### API "схема" + +У цьому випадку, OpenAPI є специфікацією, яка визначає, як описати схему вашого API. + +Це визначення схеми включає шляхи (paths) вашого API, можливі параметри, які вони приймають тощо. + +#### "Схема" даних + +Термін "схема" також може відноситися до структури даних, наприклад, JSON. + +У цьому випадку це означає - атрибути JSON і типи даних, які вони мають тощо. + +#### OpenAPI і JSON Schema + +OpenAPI описує схему для вашого API. І ця схема включає визначення (або "схеми") даних, що надсилаються та отримуються вашим API за допомогою **JSON Schema**, стандарту для схем даних JSON. + +#### Розглянемо `openapi.json` + +Якщо вас цікавить, як виглядає вихідна схема OpenAPI, то FastAPI автоматично генерує JSON-схему з усіма описами API. + +Ознайомитися можна за посиланням: http://127.0.0.1:8000/openapi.json. + +Ви побачите приблизно такий JSON: + +```JSON +{ + "openapi": "3.1.0", + "info": { + "title": "FastAPI", + "version": "0.1.0" + }, + "paths": { + "/items/": { + "get": { + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + + + +... +``` + +#### Для чого потрібний OpenAPI + +Схема OpenAPI є основою для обох систем інтерактивної документації. + +Існують десятки альтернативних інструментів, заснованих на OpenAPI. Ви можете легко додати будь-який з них до **FastAPI** додатку. + +Ви також можете використовувати OpenAPI для автоматичної генерації коду для клієнтів, які взаємодіють з API. Наприклад, для фронтенд-, мобільних або IoT-додатків + +## А тепер крок за кроком + +### Крок 1: імпортуємо `FastAPI` + +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} + +`FastAPI` це клас у Python, який надає всю функціональність для API. + +/// note | Технічні деталі + +`FastAPI` це клас, який успадковується безпосередньо від `Starlette`. + +Ви також можете використовувати всю функціональність Starlette у `FastAPI`. + +/// + +### Крок 2: створюємо екземпляр `FastAPI` + +{* ../../docs_src/first_steps/tutorial001.py hl[3] *} +Змінна `app` є екземпляром класу `FastAPI`. + +Це буде головна точка для створення і взаємодії з API. + +### Крок 3: визначте операцію шляху (path operation) + +#### Шлях (path) + +"Шлях" це частина URL, яка йде одразу після символу `/`. + +Отже, у такому URL, як: + +``` +https://example.com/items/foo +``` + +...шлях буде: + +``` +/items/foo +``` + +/// info | Додаткова інформація + +"Шлях" (path) також зазвичай називають "ендпоінтом" (endpoint) або "маршрутом" (route). + +/// + +При створенні API, "шлях" є основним способом розділення "завдань" і "ресурсів". +#### Operation + +"Операція" (operation) тут означає один з "методів" HTTP. + +Один з: + +* `POST` +* `GET` +* `PUT` +* `DELETE` + +...та більш екзотичних: + +* `OPTIONS` +* `HEAD` +* `PATCH` +* `TRACE` + +У HTTP-протоколі можна спілкуватися з кожним шляхом, використовуючи один (або кілька) з цих "методів". + +--- + +При створенні API зазвичай використовуються конкретні методи HTTP для виконання певних дій. + +Як правило, використовують: + +* `POST`: для створення даних. +* `GET`: для читання даних. +* `PUT`: для оновлення даних. +* `DELETE`: для видалення даних. + +В OpenAPI кожен HTTP метод називається "операція". + +Ми також будемо дотримуватися цього терміна. + +#### Визначте декоратор операції шляху (path operation decorator) + +{* ../../docs_src/first_steps/tutorial001.py hl[6] *} +Декоратор `@app.get("/")` вказує **FastAPI**, що функція нижче, відповідає за обробку запитів, які надходять до неї: + +* шлях `/` +* використовуючи get операцію + +/// info | `@decorator` Додаткова інформація + +Синтаксис `@something` у Python називається "декоратором". + +Ви розташовуєте його над функцією. Як гарний декоративний капелюх (мабуть, звідти походить термін). + +"Декоратор" приймає функцію нижче і виконує з нею якусь дію. + +У нашому випадку, цей декоратор повідомляє **FastAPI**, що функція нижче відповідає **шляху** `/` і **операції** `get`. + +Це і є "декоратор операції шляху (path operation decorator)". + +/// + +Можна також використовувати операції: + +* `@app.post()` +* `@app.put()` +* `@app.delete()` + +І більш екзотичні: + +* `@app.options()` +* `@app.head()` +* `@app.patch()` +* `@app.trace()` + +/// tip | Порада + +Ви можете використовувати кожну операцію (HTTP-метод) на свій розсуд. + +**FastAPI** не нав'язує жодного певного значення для кожного методу. + +Наведена тут інформація є рекомендацією, а не обов'язковою вимогою. + +Наприклад, під час використання GraphQL зазвичай усі дії виконуються тільки за допомогою `POST` операцій. + +/// + +### Крок 4: визначте **функцію операції шляху (path operation function)** + +Ось "**функція операції шляху**": + +* **шлях**: це `/`. +* **операція**: це `get`. +* **функція**: це функція, яка знаходиться нижче "декоратора" (нижче `@app.get("/")`). + +{* ../../docs_src/first_steps/tutorial001.py hl[7] *} + +Це звичайна функція Python. + +FastAPI викликатиме її щоразу, коли отримає запит до URL із шляхом "/", використовуючи операцію `GET`. + +У даному випадку це асинхронна функція. + +--- + +Ви також можете визначити її як звичайну функцію замість `async def`: + +{* ../../docs_src/first_steps/tutorial003.py hl[7] *} + +/// note | Примітка + +Якщо не знаєте в чому різниця, подивіться [Конкурентність: *"Поспішаєш?"*](../async.md#in-a-hurry){.internal-link target=_blank}. + +/// + +### Крок 5: поверніть результат + +{* ../../docs_src/first_steps/tutorial001.py hl[8] *} + +Ви можете повернути `dict`, `list`, а також окремі значення `str`, `int`, ітд. + +Також можна повернути моделі Pydantic (про це ви дізнаєтесь пізніше). + +Існує багато інших об'єктів і моделей, які будуть автоматично конвертовані в JSON (зокрема ORM тощо). Спробуйте використати свої улюблені, велика ймовірність, що вони вже підтримуються. + +## Підіб'ємо підсумки + +* Імпортуємо `FastAPI`. +* Створюємо екземпляр `app`. +* Пишемо **декоратор операції шляху** як `@app.get("/")`. +* Пишемо **функцію операції шляху**; наприклад, `def root(): ...`. +* Запускаємо сервер у режимі розробки `fastapi dev`. diff --git a/docs/uk/docs/tutorial/header-params.md b/docs/uk/docs/tutorial/header-params.md new file mode 100644 index 000000000..09c70a4f6 --- /dev/null +++ b/docs/uk/docs/tutorial/header-params.md @@ -0,0 +1,91 @@ +# Header-параметри + +Ви можете визначати параметри заголовків, так само як визначаєте `Query`, `Path` і `Cookie` параметри. + +## Імпорт `Header` + +Спочатку імпортуйте `Header`: + +{* ../../docs_src/header_params/tutorial001_an_py310.py hl[3] *} + +## Оголошення параметрів `Header` + +Потім оголосіть параметри заголовків, використовуючи ту ж структуру, що й для `Path`, `Query` та `Cookie`. + +Ви можете визначити значення за замовчуванням, а також усі додаткові параметри валідації або анотації: + +{* ../../docs_src/header_params/tutorial001_an_py310.py hl[9] *} + +/// note | Технічні деталі + +`Header`є "сестринським" класом для `Path`, `Query` і `Cookie`. Він також успадковується від загального класу `Param`. + +Але пам’ятайте, що при імпорті `Query`, `Path`, `Header` та інших із `fastapi`, то насправді вони є функціями, які повертають спеціальні класи. + +/// + +/// info | Інформація + +Щоб оголосити заголовки, потрібно використовувати `Header`, інакше параметри будуть інтерпретуватися як параметри запиту. + +/// + +## Автоматичне перетворення + +`Header` має додатковий функціонал порівняно з `Path`, `Query` та `Cookie`. + +Більшість стандартних заголовків розділяються символом «дефіс», також відомим як «мінус» (`-`). + +Але змінна, така як `user-agent`, є недійсною в Python. + +Тому, за замовчуванням, `Header` автоматично перетворює символи підкреслення (`_`) на дефіси (`-`) для отримання та документування заголовків. + +Оскільки заголовки HTTP не чутливі до регістру, Ви можете використовувати стандартний стиль Python ("snake_case"). + +Тому Ви можете використовувати `user_agent`, як зазвичай у коді Python, замість того щоб писати з великої літери, як `User_Agent` або щось подібне. + +Якщо Вам потрібно вимкнути автоматичне перетворення підкреслень у дефіси, встановіть `convert_underscores` в `Header` значення `False`: + +{* ../../docs_src/header_params/tutorial002_an_py310.py hl[10] *} + +/// warning | Увага + +Перед тим як встановити значення `False` для `convert_underscores` пам’ятайте, що деякі HTTP-проксі та сервери не підтримують заголовки з підкресленнями. + +/// + +## Дубльовані заголовки + +Можливо отримати дубльовані заголовки, тобто той самий заголовок із кількома значеннями. + +Це можна визначити, використовуючи список у типізації параметра. + +Ви отримаєте всі значення дубльованого заголовка у вигляді `list` у Python. + +Наприклад, щоб оголосити заголовок `X-Token`, який може з’являтися більше ніж один раз: + +{* ../../docs_src/header_params/tutorial003_an_py310.py hl[9] *} + +Якщо Ви взаємодієте з цією операцією шляху, надсилаючи два HTTP-заголовки, наприклад: + +``` +X-Token: foo +X-Token: bar +``` + +Відповідь буде така: + +```JSON +{ + "X-Token values": [ + "bar", + "foo" + ] +} +``` + +## Підсумок + +Оголошуйте заголовки за допомогою `Header`, використовуючи той самий підхід, що й для `Query`, `Path` та `Cookie`. + +Не хвилюйтеся про підкреслення у змінних — **FastAPI** автоматично конвертує їх. diff --git a/docs/uk/docs/tutorial/index.md b/docs/uk/docs/tutorial/index.md index e5bae74bc..92c3e77a3 100644 --- a/docs/uk/docs/tutorial/index.md +++ b/docs/uk/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ...який також включає `uvicorn`, який ви можете використовувати як сервер, який запускає ваш код. -!!! note - Ви також можете встановити його частина за частиною. +/// note - Це те, що ви, ймовірно, зробили б, коли захочете розгорнути свою програму у виробничому середовищі: +Ви також можете встановити його частина за частиною. - ``` - pip install fastapi - ``` +Це те, що ви, ймовірно, зробили б, коли захочете розгорнути свою програму у виробничому середовищі: - Також встановіть `uvicorn`, щоб він працював як сервер: +``` +pip install fastapi +``` + +Також встановіть `uvicorn`, щоб він працював як сервер: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +І те саме для кожної з опціональних залежностей, які ви хочете використовувати. - І те саме для кожної з опціональних залежностей, які ви хочете використовувати. +/// ## Розширений посібник користувача diff --git a/docs/uk/docs/tutorial/path-params.md b/docs/uk/docs/tutorial/path-params.md new file mode 100644 index 000000000..e7df1f19a --- /dev/null +++ b/docs/uk/docs/tutorial/path-params.md @@ -0,0 +1,261 @@ +# Path Параметри + +Ви можете визначити "параметри" або "змінні" шляху, використовуючи синтаксис форматованих рядків: + +{* ../../docs_src/path_params/tutorial001.py hl[6:7] *} + +Значення параметра шляху `item_id` передається у функцію як аргумент `item_id`. + +Якщо запустити цей приклад та перейти за посиланням http://127.0.0.1:8000/items/foo, то отримаємо таку відповідь: + +```JSON +{"item_id":"foo"} +``` + +## Path параметри з типами + +Ви можете визначити тип параметра шляху у функції, використовуючи стандартні анотації типів Python: + +{* ../../docs_src/path_params/tutorial002.py hl[7] *} + +У такому випадку `item_id` визначається як `int`. + +/// check | Примітка + +Це дасть можливість підтримки редактора всередині функції з перевірками помилок, автодоповнення тощо. + +/// + +## Перетворення даних + +Якщо запустити цей приклад і перейти за посиланням http://127.0.0.1:8000/items/3, то отримаєте таку відповідь: + +```JSON +{"item_id":3} +``` + +/// check | Примітка + +Зверніть увагу, що значення, яке отримала (і повернула) ваша функція, — це `3`. Це Python `int`, а не рядок `"3"`. + +Отже, з таким оголошенням типу **FastAPI** автоматично виконує "парсинг" запитів. + +/// + +## Перевірка даних + +Якщо ж відкрити у браузері посилання http://127.0.0.1:8000/items/foo, то побачимо цікаву HTTP-помилку: + +```JSON +{ + "detail": [ + { + "type": "int_parsing", + "loc": [ + "path", + "item_id" + ], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "foo", + "url": "https://errors.pydantic.dev/2.1/v/int_parsing" + } + ] +} +``` +тому що параметр шляху має значення `"foo"`, яке не є типом `int`. + +Таку саму помилку отримаємо, якщо передати `float` замість `int`, як бачимо, у цьому прикладі: http://127.0.0.1:8000/items/4.2 + +/// check | Примітка + +Отже, **FastAPI** надає перевірку типів з таким самим оголошенням типу в Python. + +Зверніть увагу, що помилка також чітко вказує саме на те місце, де валідація не пройшла. + +Це неймовірно корисно під час розробки та дебагінгу коду, що взаємодіє з вашим API. + +/// + +## Документація + +Тепер коли відкриєте свій браузер за посиланням http://127.0.0.1:8000/docs, то побачите автоматично згенеровану, інтерактивну API-документацію: + + + +/// check | Примітка + +Знову ж таки, лише з цим самим оголошенням типу в Python, FastAPI надає вам автоматичну, інтерактивну документацію (з інтеграцією Swagger UI). + +Зверніть увагу, що параметр шляху оголошений як ціле число. + + +/// + +## Переваги стандартизації, альтернативна документація + +І оскільки згенерована схема відповідає стандарту OpenAPI, існує багато сумісних інструментів. + +З цієї причини FastAPI також надає альтернативну документацію API (використовуючи ReDoc), до якої можна отримати доступ за посиланням http://127.0.0.1:8000/redoc: + + + +Таким чином, існує багато сумісних інструментів, включаючи інструменти для генерації коду для багатьох мов. + + +## Pydantic + +Вся валідація даних виконується за лаштунками за допомогою Pydantic, тому Ви отримуєте всі переваги від його використання. І можете бути впевнені, що все в надійних руках. + +Ви можете використовувати ті самі оголошення типів з `str`, `float`, `bool` та багатьма іншими складними типами даних. + +Декілька з них будуть розглянуті в наступних розділах посібника. + +## Порядок має значення + +При створенні *операцій шляху* можуть виникати ситуації, коли шлях фіксований. + +Наприклад, `/users/me`. Припустимо, що це шлях для отримання даних про поточного користувача. + +А також у вас може бути шлях `/users/{user_id}`, щоб отримати дані про конкретного користувача за його ID. + +Оскільки *операції шляху* оцінюються по черзі, Ви повинні переконатися, що шлях для `/users/me` оголошений перед шляхом для `/users/{user_id}`: + +{* ../../docs_src/path_params/tutorial003.py hl[6,11] *} + +Інакше шлях для `/users/{user_id}` також буде відповідати для `/users/me`, "вважаючи", що він отримує параметр `user_id` зі значенням `"me"`. + +Аналогічно, Ви не можете оголосити операцію шляху: + +{* ../../docs_src/path_params/tutorial003b.py hl[6,11] *} + +Перша операція буде завжди використовуватися, оскільки шлях збігається першим. +## Попередньо визначені значення + +Якщо у вас є *операція шляху*, яка приймає *параметр шляху*, але Ви хочете, щоб можливі допустимі значення *параметра шляху* були попередньо визначені, Ви можете використати стандартний Python Enum. + +### Створення класу `Enum` + +Імпортуйте `Enum` і створіть підклас, що наслідується від `str` та `Enum`. + +Наслідуючи від `str`, документація API зможе визначити, що значення повинні бути типу `string`, і правильно їх відобразить. + +Після цього створіть атрибути класу з фіксованими значеннями, які будуть доступними допустимими значеннями: + +{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *} + +/// info | Додаткова інформація + +Перелічення (або enums) доступні в Python починаючи з версії 3.4. + +/// + +/// tip | Порада + +Якщо вам цікаво, "AlexNet", "ResNet" та "LeNet" — це просто назви ML моделей Machine Learning. + +/// + + +### Оголосіть *параметр шляху* + +Потім створіть *параметр шляху* з анотацією типу, використовуючи створений вами клас enum (`ModelName`): + +{* ../../docs_src/path_params/tutorial005.py hl[16] *} + +### Перевірка документації + +Оскільки доступні значення для *параметра шляху* визначені заздалегідь, інтерактивна документація зможе красиво їх відобразити: + + + +### Робота з *перелічуваннями* у Python + +Значення *параметра шляху* буде елементом *перелічування*. + +#### Порівняння *елементів перелічування* + +Ви можете порівнювати його з *елементами перелічування* у створеному вами enum `ModelName`: + +{* ../../docs_src/path_params/tutorial005.py hl[17] *} + +#### Отримання *значення перелічування* + +Ви можете отримати фактичне значення (у цьому випадку це `str`), використовуючи `model_name.value`, або загалом `your_enum_member.value`: + +{* ../../docs_src/path_params/tutorial005.py hl[20] *} + +/// tip | Порада + +Ви також можете отримати доступ до значення `"lenet"`, використовуючи `ModelName.lenet.value`. + +/// + + +#### Повернення *елементів перелічування* + +Ви можете повертати *елементи перелічування* з вашої *операції шляху*, навіть вкладені у JSON-тіло (наприклад, `dict`). + +Вони будуть перетворені на відповідні значення (у цьому випадку рядки) перед поверненням клієнту: + +{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *} + +На стороні клієнта Ви отримаєте відповідь у форматі JSON, наприклад: + +```JSON +{ + "model_name": "alexnet", + "message": "Deep Learning FTW!" +} +``` + +## Path-параметри, що містять шляхи + +Припустимо, у вас є *операція шляху* з маршрутом `/files/{file_path}`. + +Але вам потрібно, щоб `file_path` містив *шлях*, наприклад `home/johndoe/myfile.txt`. + +Отже, URL для цього файлу виглядатиме так: `/files/home/johndoe/myfile.txt`. + + + +### Підтримка OpenAPI + +OpenAPI не підтримує спосіб оголошення *параметра шляху*, що містить *шлях* всередині, оскільки це може призвести до сценаріїв, які складно тестувати та визначати. + +Однак (одначе), Ви все одно можете зробити це в **FastAPI**, використовуючи один із внутрішніх інструментів Starlette. + +Документація все ще працюватиме, хоча й не додаватиме опису про те, що параметр повинен містити шлях. + +### Конвертер шляху + +Використовуючи опцію безпосередньо зі Starlette, Ви можете оголосити *параметр шляху*, що містить *шлях*, використовуючи URL на кшталт: + +``` +/files/{file_path:path} +``` +У цьому випадку ім'я параметра — `file_path`, а остання частина `:path` вказує на те, що параметр повинен відповідати будь-якому *шляху*. + +Отже, Ви можете використати його так: + +{* ../../docs_src/path_params/tutorial004.py hl[6] *} + +/// tip | Порада + +Вам може знадобитися, щоб параметр містив `/home/johndoe/myfile.txt` із початковою косою рискою (`/`). + +У такому випадку URL виглядатиме так: `/files//home/johndoe/myfile.txt`, із подвійною косою рискою (`//`) між `files` і `home`. + +/// + +## Підсумок + +З **FastAPI**, використовуючи короткі, інтуїтивно зрозумілі та стандартні оголошення типів Python, Ви отримуєте: + +* Підтримку в редакторі: перевірка помилок, автодоповнення тощо. +* "Парсинг" даних +* Валідацію даних +* Анотацію API та автоматичну документацію + +І вам потрібно оголосити їх лише один раз. + +Це, ймовірно, основна видима перевага **FastAPI** порівняно з альтернативними фреймворками (окрім високої продуктивності). diff --git a/docs/uk/docs/tutorial/query-params.md b/docs/uk/docs/tutorial/query-params.md new file mode 100644 index 000000000..16bb42af3 --- /dev/null +++ b/docs/uk/docs/tutorial/query-params.md @@ -0,0 +1,192 @@ +# Query Параметри + +Коли Ви оголошуєте інші параметри функції, які не є частиною параметрів шляху, вони автоматично інтерпретуються як "query" параметри. + +{* ../../docs_src/query_params/tutorial001.py hl[9] *} + +Query параметри — це набір пар ключ-значення, що йдуть після символу `?` в URL, розділені символами `&`. + +Наприклад, в URL: + +``` +http://127.0.0.1:8000/items/?skip=0&limit=10 +``` + +...query параметрами є: + +* `skip`: зі значенням `0` +* `limit`: зі значенням `10` + +Оскільки вони є частиною URL, вони "за замовчуванням" є рядками. + +Але коли Ви оголошуєте їх із типами Python (у наведеному прикладі як `int`), вони перетворюються на цей тип і проходять перевірку відповідності. + +Увесь той самий процес, який застосовується до параметрів шляху, також застосовується до query параметрів: + +* Підтримка в редакторі (автодоповнення, перевірка помилок) +* "Парсинг" даних +* Валідація даних +* Автоматична документація + + +## Значення за замовчуванням + +Оскільки query параметри не є фіксованою частиною шляху, вони можуть бути необов’язковими та мати значення за замовчуванням. + +У наведеному вище прикладі вони мають значення за замовчуванням: `skip=0` і `limit=10`. + +Отже, результат переходу за URL: + +``` +http://127.0.0.1:8000/items/ +``` +буде таким самим, як і перехід за посиланням: + +``` +http://127.0.0.1:8000/items/?skip=0&limit=10 +``` + +Але якщо Ви перейдете, наприклад, за посиланням: + +``` +http://127.0.0.1:8000/items/?skip=20 +``` + +Значення параметрів у вашій функції будуть такими: + +* `skip=20`: оскільки Ви вказали його в URL +* `limit=10`: оскільки це значення за замовчуванням + +## Необов'язкові параметри + +Аналогічно, Ви можете оголосити необов’язкові query параметри, встановивши для них значення за замовчуванням `None`: + +{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *} + +У цьому випадку параметр функції `q` буде необов’язковим і за замовчуванням матиме значення `None`. + +/// check | Примітка + +Також зверніть увагу, що **FastAPI** достатньо розумний, щоб визначити, що параметр шляху `item_id` є параметром шляху, а `q` — ні, отже, це query параметр. + +/// + +## Перетворення типу Query параметра + +Ви також можете оголошувати параметри типу `bool`, і вони будуть автоматично конвертовані: + +{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *} + +У цьому випадку, якщо Ви звернетесь до: + + +``` +http://127.0.0.1:8000/items/foo?short=1 +``` + +або + +``` +http://127.0.0.1:8000/items/foo?short=True +``` + +або + +``` +http://127.0.0.1:8000/items/foo?short=true +``` + +або + +``` +http://127.0.0.1:8000/items/foo?short=on +``` + +або + +``` +http://127.0.0.1:8000/items/foo?short=yes +``` + +або будь-який інший варіант написання (великі літери, перша літера велика тощо), ваша функція побачить параметр `short` зі значенням `True` з типом даних `bool`. В іншому випадку – `False`. + +## Кілька path і query параметрів + +Ви можете одночасно оголошувати кілька path і query параметрів, і **FastAPI** автоматично визначить, який з них до чого належить. + + +Не потрібно дотримуватись певного порядку їх оголошення. + +Вони визначаються за назвою: + +{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *} + +## Обов’язкові Query параметри + +Якщо Ви оголошуєте значення за замовчуванням для параметрів, які не є path-параметрами (у цьому розділі ми бачили поки що лише path параметри), тоді вони стають необов’язковими. + +Якщо Ви не хочете вказувати конкретні значення, але хочете зробити параметр опціональним, задайте `None` як значення за замовчуванням. + +Але якщо Ви хочете зробити query параметр обов’язковим, просто не вказуйте для нього значення за замовчуванням: + +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} + +Тут `needy` – обов’язковий query параметр типу `str`. + +Якщо Ви відкриєте у браузері URL-адресу: + +``` +http://127.0.0.1:8000/items/foo-item +``` + +...без додавання обов’язкового параметра `needy`, Ви побачите помилку: + +```JSON +{ + "detail": [ + { + "type": "missing", + "loc": [ + "query", + "needy" + ], + "msg": "Field required", + "input": null, + "url": "https://errors.pydantic.dev/2.1/v/missing" + } + ] +} +``` + +Оскільки `needy` є обов’язковим параметром, вам потрібно вказати його в URL: + +``` +http://127.0.0.1:8000/items/foo-item?needy=sooooneedy +``` + +...цей запит поверне: + +```JSON +{ + "item_id": "foo-item", + "needy": "sooooneedy" +} +``` + + +Звичайно, Ви можете визначити деякі параметри як обов’язкові, інші зі значенням за замовчуванням, а ще деякі — повністю опціональні: + +{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *} + +У цьому випадку є 3 query параметри: + +* `needy`, обов’язковий `str`. +* `skip`, `int` зі значенням за замовчуванням `0`. +* `limit`, опціональний `int`. + + +/// tip | Підказка + +Ви також можете використовувати `Enum`-и, так само як і з [Path Parameters](path-params.md#predefined-values){.internal-link target=_blank}. + +/// diff --git a/docs/uk/docs/tutorial/request-files.md b/docs/uk/docs/tutorial/request-files.md new file mode 100644 index 000000000..18b7cc01c --- /dev/null +++ b/docs/uk/docs/tutorial/request-files.md @@ -0,0 +1,175 @@ +# Запит файлів + +Ви можете визначити файли, які будуть завантажуватися клієнтом, використовуючи `File`. + +/// info | Інформація + +Щоб отримувати завантажені файли, спочатку встановіть python-multipart. + +Переконайтеся, що Ви створили [віртуальне середовище](../virtual-environments.md){.internal-link target=_blank}, активували його та встановили пакет, наприклад: + +```console +$ pip install python-multipart +``` + +Це необхідно, оскільки завантажені файли передаються у вигляді "форматованих даних форми". + +/// + +## Імпорт `File` + +Імпортуйте `File` та `UploadFile` з `fastapi`: + +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[3] *} + +## Визначення параметрів `File` + +Створіть параметри файлів так само як Ви б створювали `Body` або `Form`: + +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[9] *} + +/// info | Інформація + +`File` — це клас, який безпосередньо успадковує `Form`. + +Але пам’ятайте, що коли Ви імпортуєте `Query`, `Path`, `File` та інші з `fastapi`, це насправді функції, які повертають спеціальні класи. + +/// + +/// tip | Підказка + +Щоб оголосити тіла файлів, Вам потрібно використовувати `File`, тому що інакше параметри будуть інтерпретовані як параметри запиту або параметри тіла (JSON). + +/// + +Файли будуть завантажені у вигляді "форматованих даних форми". + +Якщо Ви оголосите тип параметра функції обробника маршруту як `bytes`, **FastAPI** прочитає файл за Вас, і Ви отримаєте його вміст у вигляді `bytes`. + +Однак майте на увазі, що весь вміст буде збережено в пам'яті. Це працюватиме добре для малих файлів. + +Але в деяких випадках Вам може знадобитися `UploadFile`. + +## Параметри файлу з `UploadFile` + +Визначте параметр файлу з типом `UploadFile`: + +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[14] *} + +Використання `UploadFile` має кілька переваг перед `bytes`: + +* Вам не потрібно використовувати `File()` у значенні за замовчуванням параметра. +* Використовується "буферизований" файл: + * Файл зберігається в пам'яті до досягнення певного обмеження, після чого він записується на диск. +* Це означає, що він добре працює для великих файлів, таких як зображення, відео, великі двійкові файли тощо, не споживаючи всю пам'ять. +Ви можете отримати метадані про завантажений файл. +* Він має file-like `асинхронний файловий інтерфейс` interface. +* Він надає фактичний об'єкт Python `SpooledTemporaryFile`, який можна передавати безпосередньо іншим бібліотекам. + +### `UploadFile` + +`UploadFile` має такі атрибути: + +* `filename`: Рядок `str` з оригінальною назвою файлу, який був завантажений (наприклад, `myimage.jpg`). +* `content_type`: Рядок `str` з MIME-типом (наприклад, `image/jpeg`). +* `file`: Об'єкт SpooledTemporaryFile (файлоподібний об'єкт). Це фактичний файловий об'єкт Python, який можна безпосередньо передавати іншим функціям або бібліотекам, що очікують "файлоподібний" об'єкт. + +`UploadFile` має такі асинхронні `async` методи. Вони викликають відповідні методи файлу під капотом (використовуючи внутрішній `SpooledTemporaryFile`). + +* `write(data)`: Записує `data` (`str` або `bytes`) у файл. +* `read(size)`: Читає `size` (`int`) байтів/символів з файлу. +* `seek(offset)`: Переміщується до позиції `offset` (`int`) у файлі. + * Наприклад, `await myfile.seek(0)` поверне курсор на початок файлу. + * This is especially useful if you run `await myfile.read()` once and then need to read the contents again. Це особливо корисно, якщо Ви виконуєте await `await myfile.read()` один раз, а потім потрібно знову прочитати вміст. +* `close()`: Закриває файл. + +Оскільки всі ці методи є асинхронними `async`, Вам потрібно використовувати "await": + +Наприклад, всередині `async` *функції обробки шляху* Ви можете отримати вміст за допомогою: + +```Python +contents = await myfile.read() +``` +Якщо Ви знаходитесь у звичайній `def` *функції обробки шляху*, Ви можете отримати доступ до `UploadFile.file` безпосередньо, наприклад: + +```Python +contents = myfile.file.read() +``` + +/// note | Технічні деталі `async` + +Коли Ви використовуєте `async` методи, **FastAPI** виконує файлові операції у пулі потоків та очікує їх завершення. + +/// + +/// note | Технічні деталі Starlette + +`UploadFile` у **FastAPI** успадковується безпосередньо від `UploadFile` у **Starlette**, але додає деякі необхідні частини, щоб зробити його сумісним із **Pydantic** та іншими компонентами FastAPI. + +/// + +## Що таке "Form Data" + +Спосіб, у який HTML-форми (`
`) надсилають дані на сервер, зазвичай використовує "спеціальне" кодування, відмінне від JSON. + +**FastAPI** забезпечує правильне зчитування цих даних з відповідної частини запиту, а не з JSON. + +/// note | Технічні деталі + +Дані з форм зазвичай кодуються за допомогою "media type" `application/x-www-form-urlencoded`, якщо вони не містять файлів. + +Але якщо форма містить файли, вона кодується у форматі `multipart/form-data`. Якщо Ви використовуєте `File`, **FastAPI** визначить, що потрібно отримати файли з відповідної частини тіла запиту. + +Щоб дізнатися більше про ці типи кодування та формові поля, ознайомтеся з документацією MDN щодо POST. + +/// + +/// warning | Увага + +Ви можете оголосити кілька параметрів `File` і `Form` в *операції шляху*, але Ви не можете одночасно оголошувати поля `Body`, які мають надходити у форматі JSON, оскільки тіло запиту буде закодоване у форматі `multipart/form-data`, а не `application/json`. + +Це не обмеження **FastAPI**, а особливість протоколу HTTP. + +/// + +## Опціональне Завантаження Файлів + +Файл можна зробити необов’язковим, використовуючи стандартні анотації типів і встановлюючи значення за замовчуванням `None`: + +{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *} + +## `UploadFile` із Додатковими Мета Даними + +Ви також можете використовувати `File()` разом із `UploadFile`, наприклад, для встановлення додаткових метаданих: + +{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *} + +## Завантаження Кількох Файлів + +Можна завантажувати кілька файлів одночасно. + +Вони будуть пов’язані з одним і тим самим "form field", який передається у вигляді "form data". + +Щоб це реалізувати, потрібно оголосити список `bytes` або `UploadFile`: + +{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *} + +Ви отримаєте, як і було оголошено, `list` із `bytes` або `UploadFile`. + +/// note | Технічні деталі + +Ви також можете використати `from starlette.responses import HTMLResponse`. + +**FastAPI** надає ті ж самі `starlette.responses`, що й `fastapi.responses`, для зручності розробників. Однак більшість доступних відповідей надходять безпосередньо від Starlette. + +/// + +### Завантаження декількох файлів із додатковими метаданими + +Так само як і раніше, Ви можете використовувати `File()`, щоб встановити додаткові параметри навіть для `UploadFile`: + +{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *} + +## Підсумок + +Використовуйте `File`, `bytes`та `UploadFile`, щоб оголошувати файли для завантаження у запитах, які надсилаються у вигляді form data. diff --git a/docs/uk/docs/tutorial/request-form-models.md b/docs/uk/docs/tutorial/request-form-models.md new file mode 100644 index 000000000..7f5759e79 --- /dev/null +++ b/docs/uk/docs/tutorial/request-form-models.md @@ -0,0 +1,78 @@ +# Моделі форм (Form Models) + +У FastAPI Ви можете використовувати **Pydantic-моделі** для оголошення **полів форми**. + +/// info | Інформація + +Щоб використовувати форми, спочатку встановіть python-multipart. + +Переконайтеся, що Ви створили [віртуальне середовище](../virtual-environments.md){.internal-link target=_blank}, активували його, а потім встановили бібліотеку, наприклад: + +```console +$ pip install python-multipart +``` + +/// + +/// note | Підказка + +Ця функція підтримується, починаючи з FastAPI версії `0.113.0`. 🤓 + +/// + +## Використання Pydantic-моделей для форм + +Вам просто потрібно оголосити **Pydantic-модель** з полями, які Ви хочете отримати як **поля форми**, а потім оголосити параметр як `Form`: + +{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *} + +**FastAPI** **витягне** дані для **кожного поля** з **формових даних** у запиті та надасть вам Pydantic-модель, яку Ви визначили. + +## Перевірка документації + +Ви можете перевірити це в UI документації за `/docs`: + +
+ +
+ +## Заборона додаткових полів форми + +У деяких особливих випадках (ймовірно, рідко) Ви можете **обмежити** форму лише тими полями, які були оголошені в Pydantic-моделі, і **заборонити** будь-які **додаткові** поля. + +/// note | Підказка + +Ця функція підтримується, починаючи з FastAPI версії `0.114.0`. 🤓 + +/// + +Ви можете використати конфігурацію Pydantic-моделі, щоб заборонити `forbid` будь-які додаткові `extra` поля: + +{* ../../docs_src/request_form_models/tutorial002_an_py39.py hl[12] *} + +Якщо клієнт спробує надіслати додаткові дані, він отримає **відповідь з помилкою**. + +Наприклад, якщо клієнт спробує надіслати наступні поля форми: + +* `username`: `Rick` +* `password`: `Portal Gun` +* `extra`: `Mr. Poopybutthole` + +Він отримає відповідь із помилкою, яка повідомляє, що поле `extra` не дозволено: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["body", "extra"], + "msg": "Extra inputs are not permitted", + "input": "Mr. Poopybutthole" + } + ] +} +``` + +## Підсумок + +Ви можете використовувати Pydantic-моделі для оголошення полів форми у FastAPI. 😎 diff --git a/docs/uk/docs/tutorial/request-forms-and-files.md b/docs/uk/docs/tutorial/request-forms-and-files.md new file mode 100644 index 000000000..a089ef945 --- /dev/null +++ b/docs/uk/docs/tutorial/request-forms-and-files.md @@ -0,0 +1,41 @@ +# Запити з формами та файлами + +У FastAPI Ви можете одночасно отримувати файли та поля форми, використовуючи `File` і `Form`. + +/// info | Інформація + +Щоб отримувати завантажені файли та/або дані форми, спочатку встановіть python-multipart. + +Переконайтеся, що Ви створили [віртуальне середовище](../virtual-environments.md){.internal-link target=_blank}, активували його, а потім встановили бібліотеку, наприклад: + +```console +$ pip install python-multipart +``` + +/// + +## Імпорт `File` та `Form` + +{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[3] *} + +## Оголошення параметрів `File` та `Form` + +Створіть параметри файлів та форми так само як і для `Body` або `Query`: + +{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[10:12] *} + +Файли та поля форми будуть завантажені як формові дані, і Ви отримаєте як файли, так і введені користувачем поля. + +Ви також можете оголосити деякі файли як `bytes`, а деякі як `UploadFile`. + +/// warning | Увага + +Ви можете оголосити кілька параметрів `File` і `Form` в операції *шляху*, але не можете одночасно оголошувати `Body`-поля, які очікуєте отримати у форматі JSON, оскільки запит матиме тіло, закодоване за допомогою `multipart/form-data`, а не `application/json`. + +Це не обмеження **FastAPI**, а частина протоколу HTTP. + +/// + +## Підсумок + +Використовуйте `File` та `Form` разом, коли вам потрібно отримувати дані форми та файли в одному запиті. diff --git a/docs/uk/docs/tutorial/request-forms.md b/docs/uk/docs/tutorial/request-forms.md new file mode 100644 index 000000000..10c58a73e --- /dev/null +++ b/docs/uk/docs/tutorial/request-forms.md @@ -0,0 +1,73 @@ +# Дані форми + +Якщо Вам потрібно отримувати поля форми замість JSON, Ви можете використовувати `Form`. + +/// info | Інформація + +Щоб використовувати форми, спочатку встановіть `python-multipart`. + +Переконайтеся, що Ви створили [віртуальне середовище](../virtual-environments.md){.internal-link target=_blank}, активували його, і потім встановили бібліотеку, наприклад: + +```console +$ pip install python-multipart +``` + +/// + +## Імпорт `Form` + +Імпортуйте `Form` з `fastapi`: + +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[3] *} + +## Оголошення параметрів `Form` + +Створюйте параметри форми так само як Ви б створювали `Body` або `Query`: + +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[9] *} + +Наприклад, один зі способів використання специфікації OAuth2 (так званий "password flow") вимагає надсилати `username` та `password` як поля форми. + +spec вимагає, щоб ці поля мали точні назви `username` і `password` та надсилалися у вигляді полів форми, а не JSON. + +З `Form` Ви можете оголошувати ті ж конфігурації, що і з `Body` (та `Query`, `Path`, `Cookie`), включаючи валідацію, приклади, псевдоніми (наприклад, `user-name` замість `username`) тощо. + +/// info | Інформація + +`Form` — це клас, який безпосередньо наслідується від `Body`. + +/// + +/// tip | Порада + +Щоб оголосити тіло форми, потрібно явно використовувати `Form`, оскільки без нього параметри будуть інтерпретуватися як параметри запиту або тіла (JSON). + +/// + +## Про "поля форми" + +HTML-форми (`
`) надсилають дані на сервер у "спеціальному" кодуванні, яке відрізняється від JSON. + +**FastAPI** подбає про те, щоб зчитати ці дані з правильного місця, а не з JSON. + +/// note | Технічні деталі + +Дані з форм зазвичай кодуються за допомогою "типу медіа" `application/x-www-form-urlencoded`. + +Але якщо форма містить файли, вона кодується як `multipart/form-data`. Ви дізнаєтеся про обробку файлів у наступному розділі. + +Якщо Ви хочете дізнатися більше про ці кодування та поля форм, зверніться до MDN вебдокументації для POST. + +/// + +/// warning | Попередження + +Ви можете оголосити кілька параметрів `Form` в *операції шляху*, але не можете одночасно оголосити поля `Body`, які Ви очікуєте отримати у форматі JSON, оскільки тіло запиту буде закодовано у форматі `application/x-www-form-urlencoded`, а не `application/json`. + +Це не обмеження **FastAPI**, а частина HTTP-протоколу. + +/// + +## Підсумок + +Використовуйте `Form` для оголошення вхідних параметрів у вигляді даних форми. diff --git a/docs/uk/docs/tutorial/static-files.md b/docs/uk/docs/tutorial/static-files.md new file mode 100644 index 000000000..a84782d8f --- /dev/null +++ b/docs/uk/docs/tutorial/static-files.md @@ -0,0 +1,40 @@ +# Статичні файли + +Ви можете автоматично надавати статичні файли з каталогу, використовуючи `StaticFiles`. + +## Використання `StaticFiles` + +* Імпортуйте `StaticFiles`. +* "Під'єднати" екземпляр `StaticFiles()` з вказанням необхідного шляху. + +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} + +/// note | Технічні деталі + +Ви також можете використовувати `from starlette.staticfiles import StaticFiles`. + +**FastAPI** надає той самий `starlette.staticfiles`, що й `fastapi.staticfiles` для зручності розробників. Але фактично він безпосередньо походить із Starlette. + +/// + +### Що таке "Під'єднання" + +"Під'єднання" означає додавання повноцінного "незалежного" застосунку за певним шляхом, який потім обробляє всі під шляхи. + +Це відрізняється від використання `APIRouter`, оскільки під'єднаний застосунок є повністю незалежним. OpenAPI та документація вашого основного застосунку не будуть знати нічого про ваш під'єднаний застосунок. + +Ви можете дізнатися більше про це в [Посібнику для просунутих користувачів](../advanced/index.md){.internal-link target=_blank}. + +## Деталі + +Перше `"/static"` вказує на під шлях, за яким буде "під'єднано" цей новий "застосунок". Тому будь-який шлях, який починається з `"/static"`, буде оброблятися ним. + +`directory="static"` визначає каталог, що містить ваші статичні файли. + +`name="static"` це ім'я, яке можна використовувати всередині **FastAPI**. + +Усі ці параметри можуть бути змінені відповідно до потреб і особливостей вашого застосунку. + +## Додаткова інформація + +Детальніше про налаштування та можливості можна дізнатися в документації Starlette про статичні файли. diff --git a/docs/uk/docs/tutorial/testing.md b/docs/uk/docs/tutorial/testing.md new file mode 100644 index 000000000..25fc370d6 --- /dev/null +++ b/docs/uk/docs/tutorial/testing.md @@ -0,0 +1,240 @@ +# Тестування + +Тестування **FastAPI** додатків є простим та ефективним завдяки бібліотеці Starlette, яка базується на HTTPX. +Оскільки HTTPX розроблений на основі Requests, його API є інтуїтивно зрозумілим для тих, хто вже знайомий з Requests. + +З його допомогою Ви можете використовувати pytest безпосередньо з **FastAPI**. + +## Використання `TestClient` + +/// info | Інформація + +Щоб використовувати `TestClient`, спочатку встановіть `httpx`. + +Переконайтеся, що Ви створили [віртуальне середовище](../virtual-environments.md){.internal-link target=_blank}, активували його, а потім встановили саму бібліотеку, наприклад: + +```console +$ pip install httpx +``` + +/// + +Імпортуйте `TestClient`. + +Створіть `TestClient`, передавши йому Ваш застосунок **FastAPI**. + +Створюйте функції з іменами, що починаються з `test_` (це стандартна угода для `pytest`). + +Використовуйте об'єкт `TestClient` так само як і `httpx`. + +Записуйте прості `assert`-вирази зі стандартними виразами Python, які потрібно перевірити (це також стандарт для `pytest`). + +{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *} + + +/// tip | Порада + +Зверніть увагу, що тестові функції — це звичайні `def`, а не `async def`. + +Виклики клієнта також звичайні, без використання `await`. + +Це дозволяє використовувати `pytest` без зайвих ускладнень. + +/// + +/// note | Технічні деталі + +Ви також можете використовувати `from starlette.testclient import TestClient`. + +**FastAPI** надає той самий `starlette.testclient` під назвою `fastapi.testclient` для зручності розробників, але він безпосередньо походить із Starlette. + +/// + +/// tip | Порада + +Якщо Вам потрібно викликати `async`-функції у ваших тестах, окрім відправлення запитів до FastAPI-застосунку (наприклад, асинхронні функції роботи з базою даних), перегляньте [Асинхронні тести](../advanced/async-tests.md){.internal-link target=_blank} у розширеному керівництві. + +/// + +## Розділення тестів + +У реальному застосунку Ваші тести, ймовірно, будуть в окремому файлі. + +Також Ваш **FastAPI**-застосунок може складатися з кількох файлів або модулів тощо. + +### Файл застосунку **FastAPI** + +Припустимо, у Вас є структура файлів, описана в розділі [Більші застосунки](bigger-applications.md){.internal-link target=_blank}: + +``` +. +├── app +│   ├── __init__.py +│   └── main.py +``` +У файлі `main.py` знаходиться Ваш застосунок **FastAPI** : + +{* ../../docs_src/app_testing/main.py *} + +### Файл тестування + +Ви можете створити файл `test_main.py` з Вашими тестами. Він може знаходитися в тому ж пакеті Python (у тій самій директорії з файлом `__init__.py`): + + +``` hl_lines="5" +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +Оскільки цей файл знаходиться в тому ж пакеті, Ви можете використовувати відносний імпорт, щоб імпортувати об'єкт `app` із модуля `main` (`main.py`): + +{* ../../docs_src/app_testing/test_main.py hl[3] *} + + +...і написати код для тестів так само як і раніше. + +## Тестування: розширений приклад + +Тепер розширимо цей приклад і додамо більше деталей, щоб побачити, як тестувати різні частини. + +### Розширений файл застосунку **FastAPI** + +Залишимо ту саму структуру файлів: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +Припустимо, що тепер файл `main.py` із Вашим **FastAPI**-застосунком містить додаткові операції шляху (**path operations**). + +Він має `GET`-операцію, яка може повертати помилку. + +Він має `POST`-операцію, яка може повертати кілька помилок. + +Обидві операції шляху вимагають заголовок `X-Token`. + +//// tab | Python 3.10+ + +```Python +{!> ../../docs_src/app_testing/app_b_an_py310/main.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python +{!> ../../docs_src/app_testing/app_b_an_py39/main.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python +{!> ../../docs_src/app_testing/app_b_an/main.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Порада + +Бажано використовувати версію з `Annotated`, якщо це можливо + +/// + +```Python +{!> ../../docs_src/app_testing/app_b_py310/main.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Порада + +Бажано використовувати версію з `Annotated`, якщо це можливо + +/// + +```Python +{!> ../../docs_src/app_testing/app_b/main.py!} +``` + +//// + +### Розширений тестовий файл + +Потім Ви можете оновити `test_main.py`, додавши розширені тести: + +{* ../../docs_src/app_testing/app_b/test_main.py *} + +Коли Вам потрібно передати клієнту інформацію в запиті, але Ви не знаєте, як це зробити, Ви можете пошукати (наприклад, у Google) спосіб реалізації в `httpx`, або навіть у `requests`, оскільки HTTPX розроблений на основі дизайну Requests. + +Далі Ви просто повторюєте ці ж дії у ваших тестах. + +Наприклад: + +* Щоб передати *path* або *query* параметр, додайте його безпосередньо до URL. +* Щоб передати тіло JSON, передайте Python-об'єкт (наприклад, `dict`) у параметр `json`. +* Якщо потрібно надіслати *Form Data* замість JSON, використовуйте параметр `data`. +* Щоб передати заголовки *headers*, використовуйте `dict` у параметрі `headers`. +* Для *cookies* використовуйте `dict` у параметрі `cookies`. + +Докладніше про передачу даних у бекенд (за допомогою `httpx` або `TestClient`) можна знайти в документації HTTPX. + +/// info | Інформація + +Зверніть увагу, що `TestClient` отримує дані, які можна конвертувати в JSON, а не Pydantic-моделі. +Якщо у Вас є Pydantic-модель у тесті, і Ви хочете передати її дані в додаток під час тестування, Ви можете використати `jsonable_encoder`, описаний у розділі [JSON Compatible Encoder](encoder.md){.internal-link target=_blank}. + +/// + +## Запуск тестів + +Після цього вам потрібно встановити `pytest`. + +Переконайтеся, що Ви створили [віртуальне середовище]{.internal-link target=_blank}, активували його і встановили необхідні пакети, наприклад: + +
+ +```console +$ pip install pytest + +---> 100% +``` + +
+ +`pytest` автоматично знайде файли з тестами, виконає їх і надасть вам результати. + +Запустіть тести за допомогою: + +
+ +```console +$ pytest + +================ test session starts ================ +platform linux -- Python 3.6.9, pytest-5.3.5, py-1.8.1, pluggy-0.13.1 +rootdir: /home/user/code/superawesome-cli/app +plugins: forked-1.1.3, xdist-1.31.0, cov-2.8.1 +collected 6 items + +---> 100% + +test_main.py ...... [100%] + +================= 1 passed in 0.03s ================= +``` + +
diff --git a/docs/ur/docs/benchmarks.md b/docs/ur/docs/benchmarks.md index 9fc793e6f..8d583de2f 100644 --- a/docs/ur/docs/benchmarks.md +++ b/docs/ur/docs/benchmarks.md @@ -1,5 +1,4 @@ # بینچ مارکس - انڈیپنڈنٹ ٹیک امپور بینچ مارک **FASTAPI** Uvicorn کے تحت چلنے والی ایپلی کیشنز کو ایک تیز رفتار Python فریم ورک میں سے ایک ، صرف Starlette اور Uvicorn کے نیچے ( FASTAPI کے ذریعہ اندرونی طور پر استعمال کیا جاتا ہے ) (*) لیکن جب بینچ مارک اور موازنہ کی جانچ پڑتال کرتے ہو تو آپ کو مندرجہ ذیل بات ذہن میں رکھنی چاہئے. @@ -14,39 +13,39 @@ درجہ بندی کی طرح ہے: -
    -
  • ASGI :Uvicorn سرور
  • +
      +
    • سرور ASGI :Uvicorn
      • -
      • Starlette: (Uvicorn استعمال کرتا ہے) ایک ویب مائیکرو فریم ورک
      • +
      • Starlette: (Uvicorn استعمال کرتا ہے) ایک ویب مائیکرو فریم ورک
        • -
        • FastAPI: (Starlette کا استعمال کرتا ہے) ایک API مائکرو فریم ورک جس میں APIs بنانے کے لیے کئی اضافی خصوصیات ہیں، ڈیٹا کی توثیق وغیرہ کے ساتھ۔
        • +
        • FastAPI: (Starlette کا استعمال کرتا ہے) ایک API مائکرو فریم ورک جس میں APIs بنانے کے لیے کئی اضافی خصوصیات ہیں، ڈیٹا کی توثیق وغیرہ کے ساتھ۔
    -
      -
    • Uvicorn:
    • +
        +
      • Uvicorn:
        • -
        • بہترین کارکردگی ہوگی، کیونکہ اس میں سرور کے علاوہ زیادہ اضافی کوڈ نہیں ہے۔
        • -
        • آپ براہ راست Uvicorn میں درخواست نہیں لکھیں گے۔ اس کا مطلب یہ ہوگا کہ آپ کے کوڈ میں کم و بیش، کم از کم، Starlette (یا FastAPI) کی طرف سے فراہم کردہ تمام کوڈ شامل کرنا ہوں گے۔ اور اگر آپ نے ایسا کیا تو، آپ کی حتمی ایپلیکیشن کا وہی اوور ہیڈ ہوگا جیسا کہ ایک فریم ورک استعمال کرنے اور آپ کے ایپ کوڈ اور کیڑے کو کم سے کم کرنا۔
        • -
        • اگر آپ Uvicorn کا موازنہ کر رہے ہیں تو اس کا موازنہ Daphne، Hypercorn، uWSGI وغیرہ ایپلیکیشن سرورز سے کریں۔
        • +
        • بہترین کارکردگی ہوگی، کیونکہ اس میں سرور کے علاوہ زیادہ اضافی کوڈ نہیں ہے۔
        • +
        • آپ براہ راست Uvicorn میں درخواست نہیں لکھیں گے۔ اس کا مطلب یہ ہوگا کہ آپ کے کوڈ میں کم و بیش، کم از کم، Starlette (یا FastAPI) کی طرف سے فراہم کردہ تمام کوڈ شامل کرنا ہوں گے۔ اور اگر آپ نے ایسا کیا تو، آپ کی حتمی ایپلیکیشن کا وہی اوور ہیڈ ہوگا جیسا کہ ایک فریم ورک استعمال کرنے اور آپ کے ایپ کوڈ اور کیڑے کو کم سے کم کرنا۔
        • +
        • اگر آپ Uvicorn کا موازنہ کر رہے ہیں تو اس کا موازنہ Daphne، Hypercorn، uWSGI وغیرہ ایپلیکیشن سرورز سے کریں۔
      -
        -
      • Starlette:
      • +
          +
        • Starlette:
          • -
          • Uvicorn کے بعد اگلی بہترین کارکردگی ہوگی۔ درحقیقت، Starlette چلانے کے لیے Uvicorn کا استعمال کرتی ہے۔ لہذا، یہ شاید زیادہ کوڈ پر عمل درآمد کرکے Uvicorn سے "سست" ہوسکتا ہے۔
          • -
          • لیکن یہ آپ کو آسان ویب ایپلیکیشنز بنانے کے لیے ٹولز فراہم کرتا ہے، راستوں پر مبنی روٹنگ کے ساتھ، وغیرہ۔
          • -
          • اگر آپ سٹارلیٹ کا موازنہ کر رہے ہیں تو اس کا موازنہ Sanic، Flask، Django وغیرہ سے کریں۔ ویب فریم ورکس (یا مائیکرو فریم ورکس)
          • +
          • Uvicorn کے بعد اگلی بہترین کارکردگی ہوگی۔ درحقیقت، Starlette چلانے کے لیے Uvicorn کا استعمال کرتی ہے۔ لہذا، یہ شاید زیادہ کوڈ پر عمل درآمد کرکے Uvicorn سے "سست" ہوسکتا ہے۔
          • +
          • لیکن یہ آپ کو آسان ویب ایپلیکیشنز بنانے کے لیے ٹولز فراہم کرتا ہے، راستوں پر مبنی روٹنگ کے ساتھ، وغیرہ۔>
          • +
          • اگر آپ سٹارلیٹ کا موازنہ کر رہے ہیں تو اس کا موازنہ Sanic، Flask، Django وغیرہ سے کریں۔ ویب فریم ورکس (یا مائیکرو فریم ورکس)
        -
          -
        • FastAPI:
        • +
            +
          • FastAPI:
            • -
            • جس طرح سے Uvicorn Starlette کا استعمال کرتا ہے اور اس سے تیز نہیں ہو سکتا، Starlette FastAPI کا استعمال کرتا ہے، اس لیے یہ اس سے تیز نہیں ہو سکتا۔
            • -
            • Starlette FastAPI کے اوپری حصے میں مزید خصوصیات فراہم کرتا ہے۔ وہ خصوصیات جن کی آپ کو APIs بناتے وقت تقریباً ہمیشہ ضرورت ہوتی ہے، جیسے ڈیٹا کی توثیق اور سیریلائزیشن۔ اور اسے استعمال کرنے سے، آپ کو خودکار دستاویزات مفت میں مل جاتی ہیں (خودکار دستاویزات چلنے والی ایپلی کیشنز میں اوور ہیڈ کو بھی شامل نہیں کرتی ہیں، یہ اسٹارٹ اپ پر تیار ہوتی ہیں)۔
            • -
            • اگر آپ نے FastAPI کا استعمال نہیں کیا ہے اور Starlette کو براہ راست استعمال کیا ہے (یا کوئی دوسرا ٹول، جیسے Sanic، Flask، Responder، وغیرہ) آپ کو تمام ڈیٹا کی توثیق اور سیریلائزیشن کو خود نافذ کرنا ہوگا۔ لہذا، آپ کی حتمی ایپلیکیشن اب بھی وہی اوور ہیڈ ہوگی جیسا کہ اسے FastAPI کا استعمال کرتے ہوئے بنایا گیا تھا۔ اور بہت سے معاملات میں، یہ ڈیٹا کی توثیق اور سیریلائزیشن ایپلی کیشنز میں لکھے گئے کوڈ کی سب سے بڑی مقدار ہے۔
            • -
            • لہذا، FastAPI کا استعمال کرکے آپ ترقیاتی وقت، Bugs، کوڈ کی لائنوں کی بچت کر رہے ہیں، اور شاید آپ کو وہی کارکردگی (یا بہتر) ملے گی اگر آپ اسے استعمال نہیں کرتے (جیسا کہ آپ کو یہ سب اپنے کوڈ میں لاگو کرنا ہوگا۔ )
            • -
            • اگر آپ FastAPI کا موازنہ کر رہے ہیں، تو اس کا موازنہ ویب ایپلیکیشن فریم ورک (یا ٹولز کے سیٹ) سے کریں جو ڈیٹا کی توثیق، سیریلائزیشن اور دستاویزات فراہم کرتا ہے، جیسے Flask-apispec، NestJS، Molten، وغیرہ۔ مربوط خودکار ڈیٹا کی توثیق، سیریلائزیشن اور دستاویزات کے ساتھ فریم ورک۔
            • +
            • جس طرح سے Uvicorn Starlette کا استعمال کرتا ہے اور اس سے تیز نہیں ہو سکتا، Starlette FastAPI کا استعمال کرتا ہے، اس لیے یہ اس سے تیز نہیں ہو سکتا۔
            • +
            • Starlette FastAPI کے اوپری حصے میں مزید خصوصیات فراہم کرتا ہے۔ وہ خصوصیات جن کی آپ کو APIs بناتے وقت تقریباً ہمیشہ ضرورت ہوتی ہے، جیسے ڈیٹا کی توثیق اور سیریلائزیشن۔ اور اسے استعمال کرنے سے، آپ کو خودکار دستاویزات مفت میں مل جاتی ہیں (خودکار دستاویزات چلنے والی ایپلی کیشنز میں اوور ہیڈ کو بھی شامل نہیں کرتی ہیں، یہ اسٹارٹ اپ پر تیار ہوتی ہیں)۔
            • +
            • اگر آپ نے FastAPI کا استعمال نہیں کیا ہے اور Starlette کو براہ راست استعمال کیا ہے (یا کوئی دوسرا ٹول، جیسے Sanic، Flask، Responder، وغیرہ) آپ کو تمام ڈیٹا کی توثیق اور سیریلائزیشن کو خود نافذ کرنا ہوگا۔ لہذا، آپ کی حتمی ایپلیکیشن اب بھی وہی اوور ہیڈ ہوگی جیسا کہ اسے FastAPI کا استعمال کرتے ہوئے بنایا گیا تھا۔ اور بہت سے معاملات میں، یہ ڈیٹا کی توثیق اور سیریلائزیشن ایپلی کیشنز میں لکھے گئے کوڈ کی سب سے بڑی مقدار ہے۔
            • +
            • لہذا، FastAPI کا استعمال کرکے آپ ترقیاتی وقت، Bugs، کوڈ کی لائنوں کی بچت کر رہے ہیں، اور شاید آپ کو وہی کارکردگی (یا بہتر) ملے گی اگر آپ اسے استعمال نہیں کرتے (جیسا کہ آپ کو یہ سب اپنے کوڈ میں لاگو کرنا ہوگا۔ )>
            • +
            • اگر آپ FastAPI کا موازنہ کر رہے ہیں، تو اس کا موازنہ ویب ایپلیکیشن فریم ورک (یا ٹولز کے سیٹ) سے کریں جو ڈیٹا کی توثیق، سیریلائزیشن اور دستاویزات فراہم کرتا ہے، جیسے Flask-apispec، NestJS، Molten، وغیرہ۔ مربوط خودکار ڈیٹا کی توثیق، سیریلائزیشن اور دستاویزات کے ساتھ فریم ورک۔
          diff --git a/docs/vi/docs/deployment/index.md b/docs/vi/docs/deployment/index.md new file mode 100644 index 000000000..24ffdc71b --- /dev/null +++ b/docs/vi/docs/deployment/index.md @@ -0,0 +1,21 @@ +# Triển khai + +Triển khai một ứng dụng **FastAPI** khá dễ dàng. + +## Triển khai là gì + +Triển khai một ứng dụng có nghĩa là thực hiện các bước cần thiết để làm cho nó **sẵn sàng phục vụ người dùng**. + +Đối với một **API web**, điều này có nghĩa là đặt nó trong một **máy chủ từ xa**, với một **chương trình máy chủ** cung cấp hiệu suất tốt, ổn định, v.v., để người dùng của bạn có thể truy cập ứng dụng của bạn một cách hiệu quả và không bị gián đoạn hoặc gặp vấn đề. + +Điều này trái ngược với các **giai đoạn phát triển**, trong đó bạn liên tục thay đổi mã, phá vỡ nó và sửa nó, ngừng và khởi động lại máy chủ phát triển, v.v. + +## Các Chiến lược Triển khai + +Có nhiều cách để triển khai ứng dụng của bạn tùy thuộc vào trường hợp sử dụng của bạn và các công cụ mà bạn sử dụng. + +Bạn có thể **triển khai một máy chủ** của riêng bạn bằng cách sử dụng một sự kết hợp các công cụ, hoặc bạn có thể sử dụng một **dịch vụ cloud** để làm một số công việc cho bạn, hoặc các tùy chọn khác. + +Tôi sẽ chỉ ra một số khái niệm chính cần thiết khi triển khai một ứng dụng **FastAPI** (mặc dù hầu hết nó áp dụng cho bất kỳ loại ứng dụng web nào). + +Bạn sẽ thấy nhiều chi tiết cần thiết và một số kỹ thuật để triển khai trong các phần tiếp theo. ✨ diff --git a/docs/vi/docs/deployment/versions.md b/docs/vi/docs/deployment/versions.md new file mode 100644 index 000000000..04de393e7 --- /dev/null +++ b/docs/vi/docs/deployment/versions.md @@ -0,0 +1,93 @@ +# Về các phiên bản của FastAPI + +**FastAPI** đã được sử dụng ở quy mô thực tế (production) trong nhiều ứng dụng và hệ thống. Và phạm vi kiểm thử được giữ ở mức 100%. Nhưng việc phát triển của nó vẫn đang diễn ra nhanh chóng. + +Các tính năng mới được bổ sung thường xuyên, lỗi được sửa định kỳ, và mã nguồn vẫn đang được cải thiện liên tục + +Đó là lí do các phiên bản hiện tại vẫn còn là 0.x.x, điều này phản ánh rằng mỗi phiên bản có thể có các thay đổi gây mất tương thích. Điều này tuân theo các quy ước về Semantic Versioning. + +Bạn có thể tạo ra sản phẩm thực tế với **FastAPI** ngay bây giờ (và bạn có thể đã làm điều này trong một thời gian dài), bạn chỉ cần đảm bảo rằng bạn sử dụng một phiên bản hoạt động đúng với các đoạn mã còn lại của bạn. + +## Cố định phiên bản của `fastapi` + +Điều đầu tiên bạn nên làm là "cố định" phiên bản của **FastAPI** bạn đang sử dụng để phiên bản mới nhất mà bạn biết hoạt động đúng với ứng dụng của bạn. + +Ví dụ, giả sử bạn đang sử dụng phiên bản `0.112.0` trong ứng dụng của bạn. + +Nếu bạn sử dụng một tệp `requirements.txt` bạn có thể chỉ định phiên bản với: + +```txt +fastapi[standard]==0.112.0 +``` + +Như vậy, bạn sẽ sử dụng chính xác phiên bản `0.112.0`. + +Hoặc bạn cũng có thể cố định nó với: + +```txt +fastapi[standard]>=0.112.0,<0.113.0 +``` + +Như vậy, bạn sẽ sử dụng các phiên bản `0.112.0` trở lên, nhưng nhỏ hơn `0.113.0`, ví dụ, một phiên bản `0.112.2` vẫn được chấp nhận. + +Nếu bạn sử dụng bất kỳ công cụ nào để quản lý cài đặt của bạn, như `uv`, Poetry, Pipenv, hoặc bất kỳ công cụ nào khác, chúng đều có một cách để bạn có thể định nghĩa các phiên bản cụ thể cho các gói của bạn. + +## Các phiên bản có sẵn + +Bạn có thể xem các phiên bản có sẵn (ví dụ để kiểm tra phiên bản mới nhất) trong [Release Notes](../release-notes.md){.internal-link target=_blank}. + +## Về các phiên bản + +Theo quy ước về Semantic Versioning, bất kỳ phiên bản nào bên dưới `1.0.0` có thể thêm các thay đổi gây mất tương thích. + +**FastAPI** cũng theo quy ước rằng bất kỳ thay đổi phiên bản "PATCH" nào là cho các lỗi và các thay đổi không gây mất tương thích. + +/// tip + +"PATCH" là số cuối cùng, ví dụ, trong `0.2.3`, phiên bản PATCH là `3`. + +/// + +Vì vậy, bạn có thể cố định đến một phiên bản như: + +```txt +fastapi>=0.45.0,<0.46.0 +``` + +Các thay đổi gây mất tương thích và các tính năng mới được thêm vào trong các phiên bản "MINOR". + +/// tip + +"MINOR" là số ở giữa, ví dụ, trong `0.2.3`, phiên bản MINOR là `2`. + +/// + +## Nâng cấp các phiên bản của FastAPI + +Bạn nên thêm các bài kiểm tra (tests) cho ứng dụng của bạn. + +Với **FastAPI** điều này rất dễ dàng (nhờ vào Starlette), kiểm tra tài liệu: [Testing](../tutorial/testing.md){.internal-link target=_blank} + +Sau khi bạn có các bài kiểm tra, bạn có thể nâng cấp phiên bản **FastAPI** lên một phiên bản mới hơn, và đảm bảo rằng tất cả mã của bạn hoạt động đúng bằng cách chạy các bài kiểm tra của bạn. + +Nếu mọi thứ đang hoạt động, hoặc sau khi bạn thực hiện các thay đổi cần thiết, và tất cả các bài kiểm tra của bạn đều đi qua, thì bạn có thể cố định phiên bản của `fastapi` đến phiên bản mới hơn. + +## Về Starlette + +Bạn không nên cố định phiên bản của `starlette`. + +Các phiên bản khác nhau của **FastAPI** sẽ sử dụng một phiên bản Starlette mới hơn. + +Vì vậy, bạn có thể để **FastAPI** sử dụng phiên bản Starlette phù hợp. + +## Về Pydantic + +Pydantic bao gồm các bài kiểm tra của riêng nó cho **FastAPI**, vì vậy các phiên bản mới hơn của Pydantic (trên `1.0.0`) luôn tương thích với **FastAPI**. + +Bạn có thể cố định Pydantic đến bất kỳ phiên bản nào trên `1.0.0` mà bạn muốn. + +Ví dụ: + +```txt +pydantic>=2.7.0,<3.0.0 +``` diff --git a/docs/vi/docs/environment-variables.md b/docs/vi/docs/environment-variables.md new file mode 100644 index 000000000..dd06f8959 --- /dev/null +++ b/docs/vi/docs/environment-variables.md @@ -0,0 +1,300 @@ +# Biến môi trường (Environment Variables) + +/// tip + +Nếu bạn đã biết về "biến môi trường" và cách sử dụng chúng, bạn có thể bỏ qua phần này. + +/// + +Một biến môi trường (còn được gọi là "**env var**") là một biến mà tồn tại **bên ngoài** đoạn mã Python, ở trong **hệ điều hành**, và có thể được đọc bởi đoạn mã Python của bạn (hoặc bởi các chương trình khác). + +Các biến môi trường có thể được sử dụng để xử lí **các thiết lập** của ứng dụng, như một phần của **các quá trình cài đặt** Python, v.v. + +## Tạo và Sử dụng các Biến Môi Trường + +Bạn có thể **tạo** và sử dụng các biến môi trường trong **shell (terminal)**, mà không cần sử dụng Python: + +//// tab | Linux, macOS, Windows Bash + +
          + +```console +// Bạn có thể tạo một biến môi trường MY_NAME với +$ export MY_NAME="Wade Wilson" + +// Sau đó bạn có thể sử dụng nó với các chương trình khác, như +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
          + +//// + +//// tab | Windows PowerShell + +
          + +```console +// Tạo một biến môi trường MY_NAME +$ $Env:MY_NAME = "Wade Wilson" + +// Sử dụng nó với các chương trình khác, như là +$ echo "Hello $Env:MY_NAME" + +Hello Wade Wilson +``` + +
          + +//// + +## Đọc các Biến Môi Trường trong Python + +Bạn cũng có thể tạo các biến môi trường **bên ngoài** đoạn mã Python, trong terminal (hoặc bằng bất kỳ phương pháp nào khác), và sau đó **đọc chúng trong Python**. + +Ví dụ, bạn có một file `main.py` với: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// tip + +Tham số thứ hai cho `os.getenv()` là giá trị mặc định để trả về. + +Nếu không được cung cấp, nó mặc định là `None`, ở đây chúng ta cung cấp `"World"` là giá trị mặc định để sử dụng. + +/// + +Sau đó bạn có thể gọi chương trình Python: + +//// tab | Linux, macOS, Windows Bash + +
          + +```console +// Ở đây chúng ta chưa cài đặt biến môi trường +$ python main.py + +// Vì chúng ta chưa cài đặt biến môi trường, chúng ta nhận được giá trị mặc định + +Hello World from Python + +// Nhưng nếu chúng ta tạo một biến môi trường trước đó +$ export MY_NAME="Wade Wilson" + +// Và sau đó gọi chương trình lại +$ python main.py + +// Bây giờ nó có thể đọc biến môi trường + +Hello Wade Wilson from Python +``` + +
          + +//// + +//// tab | Windows PowerShell + +
          + +```console +// Ở đây chúng ta chưa cài đặt biến môi trường +$ python main.py + +// Vì chúng ta chưa cài đặt biến môi trường, chúng ta nhận được giá trị mặc định + +Hello World from Python + +// Nhưng nếu chúng ta tạo một biến môi trường trước đó +$ $Env:MY_NAME = "Wade Wilson" + +// Và sau đó gọi chương trình lại +$ python main.py + +// Bây giờ nó có thể đọc biến môi trường + +Hello Wade Wilson from Python +``` + +
          + +//// + +Vì các biến môi trường có thể được tạo bên ngoài đoạn mã Python, nhưng có thể được đọc bởi đoạn mã Python, và không cần được lưu trữ (commit vào `git`) cùng với các file khác, nên chúng thường được sử dụng để lưu các thiết lập hoặc **cấu hình**. + +Bạn cũng có thể tạo ra một biến môi trường dành riêng cho một **lần gọi chương trình**, chỉ có thể được sử dụng bởi chương trình đó, và chỉ trong thời gian chạy của chương trình. + +Để làm điều này, tạo nó ngay trước chương trình đó, trên cùng một dòng: + +
          + +```console +// Tạo một biến môi trường MY_NAME cho lần gọi chương trình này +$ MY_NAME="Wade Wilson" python main.py + +// Bây giờ nó có thể đọc biến môi trường + +Hello Wade Wilson from Python + +// Biến môi trường không còn tồn tại sau đó +$ python main.py + +Hello World from Python +``` + +
          + +/// tip + +Bạn có thể đọc thêm về điều này tại The Twelve-Factor App: Config. + +/// + +## Các Kiểu (Types) và Kiểm tra (Validation) + +Các biến môi trường có thể chỉ xử lí **chuỗi ký tự**, vì chúng nằm bên ngoài đoạn mã Python và phải tương thích với các chương trình khác và phần còn lại của hệ thống (và thậm chí với các hệ điều hành khác, như Linux, Windows, macOS). + +Điều này có nghĩa là **bất kỳ giá trị nào** được đọc trong Python từ một biến môi trường **sẽ là một `str`**, và bất kỳ hành động chuyển đổi sang kiểu dữ liệu khác hoặc hành động kiểm tra nào cũng phải được thực hiện trong đoạn mã. + +Bạn sẽ học thêm về việc sử dụng biến môi trường để xử lí **các thiết lập ứng dụng** trong [Hướng dẫn nâng cao - Các thiết lập và biến môi trường](./advanced/settings.md){.internal-link target=_blank}. + +## Biến môi trường `PATH` + +Có một biến môi trường **đặc biệt** được gọi là **`PATH`** được sử dụng bởi các hệ điều hành (Linux, macOS, Windows) nhằm tìm các chương trình để thực thi. + +Giá trị của biến môi trường `PATH` là một chuỗi dài được tạo bởi các thư mục được phân tách bởi dấu hai chấm `:` trên Linux và macOS, và bởi dấu chấm phẩy `;` trên Windows. + +Ví dụ, biến môi trường `PATH` có thể có dạng như sau: + +//// tab | Linux, macOS + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +Điều này có nghĩa là hệ thống sẽ tìm kiếm các chương trình trong các thư mục: + +* `/usr/local/bin` +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32 +``` + +Điều này có nghĩa là hệ thống sẽ tìm kiếm các chương trình trong các thư mục: + +* `C:\Program Files\Python312\Scripts` +* `C:\Program Files\Python312` +* `C:\Windows\System32` + +//// + +Khi bạn gõ một **lệnh** trong terminal, hệ điều hành **tìm kiếm** chương trình trong **mỗi thư mục** được liệt kê trong biến môi trường `PATH`. + +Ví dụ, khi bạn gõ `python` trong terminal, hệ điều hành tìm kiếm một chương trình được gọi `python` trong **thư mục đầu tiên** trong danh sách đó. + +Nếu tìm thấy, nó sẽ **sử dụng** nó. Nếu không tìm thấy, nó sẽ tiếp tục tìm kiếm trong **các thư mục khác**. + +### Cài đặt Python và cập nhật biến môi trường `PATH` + +Khi bạn cài đặt Python, bạn có thể được hỏi nếu bạn muốn cập nhật biến môi trường `PATH`. + +//// tab | Linux, macOS + +Giả sử bạn cài đặt Python vào thư mục `/opt/custompython/bin`. + +Nếu bạn chọn cập nhật biến môi trường `PATH`, thì cài đặt sẽ thêm `/opt/custompython/bin` vào biến môi trường `PATH`. + +Nó có thể có dạng như sau: + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin +``` + +Như vậy, khi bạn gõ `python` trong terminal, hệ thống sẽ tìm thấy chương trình Python trong `/opt/custompython/bin` (thư mục cuối) và sử dụng nó. + +//// + +//// tab | Windows + +Giả sử bạn cài đặt Python vào thư mục `C:\opt\custompython\bin`. + +Nếu bạn chọn cập nhật biến môi trường `PATH`, thì cài đặt sẽ thêm `C:\opt\custompython\bin` vào biến môi trường `PATH`. + +Nó có thể có dạng như sau: + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin +``` + +Như vậy, khi bạn gõ `python` trong terminal, hệ thống sẽ tìm thấy chương trình Python trong `C:\opt\custompython\bin` (thư mục cuối) và sử dụng nó. + +//// + +Vậy, nếu bạn gõ: + +
          + +```console +$ python +``` + +
          + +//// tab | Linux, macOS + +Hệ thống sẽ **tìm kiếm** chương trình `python` trong `/opt/custompython/bin` và thực thi nó. + +Nó tương đương với việc bạn gõ: + +
          + +```console +$ /opt/custompython/bin/python +``` + +
          + +//// + +//// tab | Windows + +Hệ thống sẽ **tìm kiếm** chương trình `python` trong `C:\opt\custompython\bin\python` và thực thi nó. + +Nó tương đương với việc bạn gõ: + +
          + +```console +$ C:\opt\custompython\bin\python +``` + +
          + +//// + +Thông tin này sẽ hữu ích khi bạn học về [Môi trường ảo](virtual-environments.md){.internal-link target=_blank}. + +## Kết luận + +Với những thông tin này, bạn có thể hiểu được **các biến môi trường là gì** và **cách sử dụng chúng trong Python**. + +Bạn có thể đọc thêm về chúng tại Wikipedia cho Biến môi trường. + +Trong nhiều trường hợp, cách các biến môi trường trở nên hữu ích và có thể áp dụng không thực sự rõ ràng ngay từ đầu, nhưng chúng sẽ liên tục xuất hiện trong rất nhiều tình huống khi bạn phát triển ứng dụng, vì vậy việc hiểu biết về chúng là hữu ích. + +Chẳng hạn, bạn sẽ cần những thông tin này khi bạn học về [Môi trường ảo](virtual-environments.md). diff --git a/docs/vi/docs/fastapi-cli.md b/docs/vi/docs/fastapi-cli.md new file mode 100644 index 000000000..d9e315ae4 --- /dev/null +++ b/docs/vi/docs/fastapi-cli.md @@ -0,0 +1,75 @@ +# FastAPI CLI + +**FastAPI CLI** là một chương trình dòng lệnh có thể được sử dụng để phục vụ ứng dụng FastAPI của bạn, quản lý dự án FastAPI của bạn và nhiều hoạt động khác. + +Khi bạn cài đặt FastAPI (vd với `pip install "fastapi[standard]"`), nó sẽ bao gồm một gói được gọi là `fastapi-cli`, gói này cung cấp lệnh `fastapi` trong terminal. + +Để chạy ứng dụng FastAPI của bạn cho quá trình phát triển (development), bạn có thể sử dụng lệnh `fastapi dev`: + +
          + +```console +$ fastapi dev main.py + + FastAPI Starting development server 🚀 + + Searching for package file structure from directories with + __init__.py files + Importing from /home/user/code/awesomeapp + + module 🐍 main.py + + code Importing the FastAPI app object from the module with the + following code: + + from main import app + + app Using import string: main:app + + server Server started at http://127.0.0.1:8000 + server Documentation at http://127.0.0.1:8000/docs + + tip Running in development mode, for production use: + fastapi run + + Logs: + + INFO Will watch for changes in these directories: + ['/home/user/code/awesomeapp'] + INFO Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to + quit) + INFO Started reloader process [383138] using WatchFiles + INFO Started server process [383153] + INFO Waiting for application startup. + INFO Application startup complete. +``` + +
          + +Chương trình dòng lệnh `fastapi` là **FastAPI CLI**. + +FastAPI CLI nhận đường dẫn đến chương trình Python của bạn (vd `main.py`) và tự động phát hiện đối tượng `FastAPI` (thường được gọi là `app`), xác định quá trình nhập đúng, và sau đó chạy nó (serve). + +Đối với vận hành thực tế (production), bạn sẽ sử dụng `fastapi run` thay thế. 🚀 + +Ở bên trong, **FastAPI CLI** sử dụng Uvicorn, một server ASGI có hiệu suất cao, sẵn sàng cho vận hành thực tế (production). 😎 + +## `fastapi dev` + +Chạy `fastapi dev` sẽ khởi động quá trình phát triển. + +Mặc định, **auto-reload** được bật, tự động tải lại server khi bạn thay đổi code của bạn. Điều này tốn nhiều tài nguyên và có thể kém ổn định hơn khi nó bị tắt. Bạn nên sử dụng nó cho quá trình phát triển. Nó cũng lắng nghe địa chỉ IP `127.0.0.1`, đó là địa chỉ IP của máy tính để tự giao tiếp với chính nó (`localhost`). + +## `fastapi run` + +Chạy `fastapi run` mặc định sẽ khởi động FastAPI cho quá trình vận hành thực tế. + +Mặc định, **auto-reload** bị tắt. Nó cũng lắng nghe địa chỉ IP `0.0.0.0`, đó là tất cả các địa chỉ IP có sẵn, như vậy nó sẽ được truy cập công khai bởi bất kỳ ai có thể giao tiếp với máy tính. Đây là cách bạn thường chạy nó trong sản phẩm hoàn thiện, ví dụ trong một container. + +Trong hầu hết các trường hợp, bạn sẽ (và nên) có một "proxy điểm cuối (termination proxy)" xử lý HTTPS cho bạn, điều này sẽ phụ thuộc vào cách bạn triển khai ứng dụng của bạn, nhà cung cấp có thể làm điều này cho bạn, hoặc bạn có thể cần thiết lập nó. + +/// tip + +Bạn có thể tìm hiểu thêm về FastAPI CLI trong [tài liệu triển khai](deployment/index.md){.internal-link target=_blank}. + +/// diff --git a/docs/vi/docs/features.md b/docs/vi/docs/features.md index 306aeb359..2220d9fa5 100644 --- a/docs/vi/docs/features.md +++ b/docs/vi/docs/features.md @@ -64,10 +64,13 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` nghĩa là: +/// info - Truyền các khóa và giá trị của dict `second_user_data` trực tiếp như các tham số kiểu key-value, tương đương với: `User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` nghĩa là: + +Truyền các khóa và giá trị của dict `second_user_data` trực tiếp như các tham số kiểu key-value, tương đương với: `User(id=4, name="Mary", joined="2018-11-30")` + +/// ### Được hỗ trợ từ các trình soạn thảo @@ -172,7 +175,7 @@ Với **FastAPI**, bạn có được tất cả những tính năng của **Sta ## Tính năng của Pydantic -**FastAPI** tương thích đầy đủ với (và dựa trên) Pydantic. Do đó, bất kì code Pydantic nào bạn thêm vào cũng sẽ hoạt động. +**FastAPI** tương thích đầy đủ với (và dựa trên) Pydantic. Do đó, bất kì code Pydantic nào bạn thêm vào cũng sẽ hoạt động. Bao gồm các thư viện bên ngoài cũng dựa trên Pydantic, như ORMs, ODMs cho cơ sở dữ liệu. diff --git a/docs/vi/docs/index.md b/docs/vi/docs/index.md index 3f416dbec..5c6b7e8a4 100644 --- a/docs/vi/docs/index.md +++ b/docs/vi/docs/index.md @@ -1,3 +1,9 @@ +# FastAPI + + +

          FastAPI

          @@ -5,11 +11,11 @@ FastAPI framework, hiệu năng cao, dễ học, dễ code, sẵn sàng để tạo ra sản phẩm

          - - Test + + Test - - Coverage + + Coverage Package version @@ -23,15 +29,15 @@ **Tài liệu**: https://fastapi.tiangolo.com -**Mã nguồn**: https://github.com/tiangolo/fastapi +**Mã nguồn**: https://github.com/fastapi/fastapi --- -FastAPI là một web framework hiện đại, hiệu năng cao để xây dựng web APIs với Python 3.8+ dựa trên tiêu chuẩn Python type hints. +FastAPI là một web framework hiện đại, hiệu năng cao để xây dựng web APIs với Python dựa trên tiêu chuẩn Python type hints. Những tính năng như: -* **Nhanh**: Hiệu năng rất cao khi so sánh với **NodeJS** và **Go** (cảm ơn Starlette và Pydantic). [Một trong những Python framework nhanh nhất](#performance). +* **Nhanh**: Hiệu năng rất cao khi so sánh với **NodeJS** và **Go** (cảm ơn Starlette và Pydantic). [Một trong những Python framework nhanh nhất](#hieu-nang). * **Code nhanh**: Tăng tốc độ phát triển tính năng từ 200% tới 300%. * * **Ít lỗi hơn**: Giảm khoảng 40% những lỗi phát sinh bởi con người (nhà phát triển). * * **Trực giác tốt hơn**: Được các trình soạn thảo hỗ tuyệt vời. Completion mọi nơi. Ít thời gian gỡ lỗi. @@ -63,7 +69,7 @@ Những tính năng như: "_[...] Tôi đang sử dụng **FastAPI** vô cùng nhiều vào những ngày này. [...] Tôi thực sự đang lên kế hoạch sử dụng nó cho tất cả các nhóm **dịch vụ ML tại Microsoft**. Một vài trong số đó đang tích hợp vào sản phẩm lõi của **Window** và một vài sản phẩm cho **Office**._" -

          Kabir Khan - Microsoft (ref)
          +
          Kabir Khan - Microsoft (ref)
          --- @@ -87,7 +93,7 @@ Những tính năng như: "_Thành thật, những gì bạn đã xây dựng nhìn siêu chắc chắn và bóng bẩy. Theo nhiều cách, nó là những gì tôi đã muốn Hug trở thành - thật sự truyền cảm hứng để thấy ai đó xây dựng nó._" -
          Timothy Crosley - người tạo ra Hug (ref)
          +
          Timothy Crosley - người tạo ra Hug (ref)
          --- @@ -116,12 +122,10 @@ Nếu bạn đang xây dựng một CLIStarlette cho phần web. -* Pydantic cho phần data. +* Pydantic cho phần data. ## Cài đặt @@ -332,7 +336,7 @@ Bạn định nghĩa bằng cách sử dụng các kiểu dữ liệu chuẩn c Bạn không phải học một cú pháp mới, các phương thức và class của một thư viện cụ thể nào. -Chỉ cần sử dụng các chuẩn của **Python 3.8+**. +Chỉ cần sử dụng các chuẩn của **Python**. Ví dụ, với một tham số kiểu `int`: @@ -448,22 +452,21 @@ Independent TechEmpower benchmarks cho thấy các ứng dụng **FastAPI** ch Sử dụng bởi Pydantic: -* ujson - "Parse" JSON nhanh hơn. -* email_validator - cho email validation. +* email-validator - cho email validation. Sử dụng Starlette: * httpx - Bắt buộc nếu bạn muốn sử dụng `TestClient`. * jinja2 - Bắt buộc nếu bạn muốn sử dụng cấu hình template engine mặc định. -* python-multipart - Bắt buộc nếu bạn muốn hỗ trợ "parsing", form với `request.form()`. +* python-multipart - Bắt buộc nếu bạn muốn hỗ trợ "parsing", form với `request.form()`. * itsdangerous - Bắt buộc để hỗ trợ `SessionMiddleware`. * pyyaml - Bắt buộc để hỗ trợ `SchemaGenerator` cho Starlette (bạn có thể không cần nó trong FastAPI). -* ujson - Bắt buộc nếu bạn muốn sử dụng `UJSONResponse`. Sử dụng bởi FastAPI / Starlette: * uvicorn - Server để chạy ứng dụng của bạn. * orjson - Bắt buộc nếu bạn muốn sử dụng `ORJSONResponse`. +* ujson - Bắt buộc nếu bạn muốn sử dụng `UJSONResponse`. Bạn có thể cài đặt tất cả những dependency trên với `pip install "fastapi[all]"`. diff --git a/docs/vi/docs/python-types.md b/docs/vi/docs/python-types.md index 4999caac3..403e89930 100644 --- a/docs/vi/docs/python-types.md +++ b/docs/vi/docs/python-types.md @@ -12,16 +12,18 @@ Bằng việc khai báo kiểu dữ liệu cho các biến của bạn, các tr Nhưng thậm chí nếu bạn không bao giờ sử dụng **FastAPI**, bạn sẽ được lợi từ việc học một ít về chúng. -!!! note - Nếu bạn là một chuyên gia về Python, và bạn đã biết mọi thứ về gợi ý kiểu dữ liệu, bỏ qua và đi tới chương tiếp theo. +/// note + +Nếu bạn là một chuyên gia về Python, và bạn đã biết mọi thứ về gợi ý kiểu dữ liệu, bỏ qua và đi tới chương tiếp theo. + +/// ## Động lực Hãy bắt đầu với một ví dụ đơn giản: -```Python -{!../../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} + Kết quả khi gọi chương trình này: @@ -35,9 +37,8 @@ Hàm thực hiện như sau: * Chuyển đổi kí tự đầu tiên của mỗi biến sang kiểu chữ hoa với `title()`. * Nối chúng lại với nhau bằng một kí tự trắng ở giữa. -```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### Sửa đổi @@ -79,9 +80,8 @@ Chính là nó. Những thứ đó là "type hints": -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + Đó không giống như khai báo những giá trị mặc định giống như: @@ -109,9 +109,8 @@ Với cái đó, bạn có thể cuộn, nhìn thấy các lựa chọn, cho đ Kiểm tra hàm này, nó đã có gợi ý kiểu dữ liệu: -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + Bởi vì trình soạn thảo biết kiểu dữ liệu của các biến, bạn không chỉ có được completion, bạn cũng được kiểm tra lỗi: @@ -119,9 +118,8 @@ Bởi vì trình soạn thảo biết kiểu dữ liệu của các biến, bạ Bây giờ bạn biết rằng bạn phải sửa nó, chuyển `age` sang một xâu với `str(age)`: -```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## Khai báo các kiểu dữ liệu @@ -140,9 +138,8 @@ Bạn có thể sử dụng, ví dụ: * `bool` * `bytes` -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### Các kiểu dữ liệu tổng quát với tham số kiểu dữ liệu @@ -170,45 +167,55 @@ Nếu bạn có thể sử dụng **phiên bản cuối cùng của Python**, s Ví dụ, hãy định nghĩa một biến là `list` các `str`. -=== "Python 3.9+" +//// tab | Python 3.9+ + +Khai báo biến với cùng dấu hai chấm (`:`). + +Tương tự kiểu dữ liệu `list`. + +Như danh sách là một kiểu dữ liệu chứa một vài kiểu dữ liệu có sẵn, bạn đặt chúng trong các dấu ngoặc vuông: + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial006_py39.py!} +``` - Khai báo biến với cùng dấu hai chấm (`:`). +//// - Tương tự kiểu dữ liệu `list`. +//// tab | Python 3.8+ - Như danh sách là một kiểu dữ liệu chứa một vài kiểu dữ liệu có sẵn, bạn đặt chúng trong các dấu ngoặc vuông: +Từ `typing`, import `List` (với chữ cái `L` viết hoa): - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial006.py!} +``` -=== "Python 3.8+" +Khai báo biến với cùng dấu hai chấm (`:`). - Từ `typing`, import `List` (với chữ cái `L` viết hoa): +Tương tự như kiểu dữ liệu, `List` bạn import từ `typing`. - ``` Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +Như danh sách là một kiểu dữ liệu chứa các kiểu dữ liệu có sẵn, bạn đặt chúng bên trong dấu ngoặc vuông: - Khai báo biến với cùng dấu hai chấm (`:`). +```Python hl_lines="4" +{!> ../../docs_src/python_types/tutorial006.py!} +``` - Tương tự như kiểu dữ liệu, `List` bạn import từ `typing`. +//// - Như danh sách là một kiểu dữ liệu chứa các kiểu dữ liệu có sẵn, bạn đặt chúng bên trong dấu ngoặc vuông: +/// info - ```Python hl_lines="4" - {!> ../../../docs_src/python_types/tutorial006.py!} - ``` +Các kiểu dữ liệu có sẵn bên trong dấu ngoặc vuông được gọi là "tham số kiểu dữ liệu". -!!! info - Các kiểu dữ liệu có sẵn bên trong dấu ngoặc vuông được gọi là "tham số kiểu dữ liệu". +Trong trường hợp này, `str` là tham số kiểu dữ liệu được truyền tới `List` (hoặc `list` trong Python 3.9 trở lên). - Trong trường hợp này, `str` là tham số kiểu dữ liệu được truyền tới `List` (hoặc `list` trong Python 3.9 trở lên). +/// Có nghĩa là: "biến `items` là một `list`, và mỗi phần tử trong danh sách này là một `str`". -!!! tip - Nếu bạn sử dụng Python 3.9 hoặc lớn hơn, bạn không phải import `List` từ `typing`, bạn có thể sử dụng `list` để thay thế. +/// tip + +Nếu bạn sử dụng Python 3.9 hoặc lớn hơn, bạn không phải import `List` từ `typing`, bạn có thể sử dụng `list` để thay thế. + +/// Bằng cách này, trình soạn thảo của bạn có thể hỗ trợ trong khi xử lí các phần tử trong danh sách: @@ -224,17 +231,21 @@ Và do vậy, trình soạn thảo biết nó là một `str`, và cung cấp s Bạn sẽ làm điều tương tự để khai báo các `tuple` và các `set`: -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial007_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial007_py39.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial007.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial007.py!} - ``` +//// Điều này có nghĩa là: @@ -249,17 +260,21 @@ Tham số kiểu dữ liệu đầu tiên dành cho khóa của `dict`. Tham số kiểu dữ liệu thứ hai dành cho giá trị của `dict`. -=== "Python 3.9+" +//// tab | Python 3.9+ - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008_py39.py!} - ``` +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial008_py39.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ + +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial008.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008.py!} - ``` +//// Điều này có nghĩa là: @@ -278,17 +293,21 @@ In Python 3.10 there's also a **new syntax** where you can put the possible type Trong Python 3.10 cũng có một **cú pháp mới** mà bạn có thể đặt những kiểu giá trị khả thi phân cách bởi một dấu sổ dọc (`|`). -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial008b_py310.py!} - ``` +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial008b_py310.py!} +``` + +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial008b.py!} - ``` +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial008b.py!} +``` + +//// Trong cả hai trường hợp có nghĩa là `item` có thể là một `int` hoặc `str`. @@ -299,7 +318,7 @@ Bạn có thể khai báo một giá trị có thể có một kiểu dữ liệ Trong Python 3.6 hoặc lớn hơn (bao gồm Python 3.10) bạn có thể khai báo nó bằng các import và sử dụng `Optional` từ mô đun `typing`. ```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009.py!} +{!../../docs_src/python_types/tutorial009.py!} ``` Sử dụng `Optional[str]` thay cho `str` sẽ cho phép trình soạn thảo giúp bạn phát hiện các lỗi mà bạn có thể gặp như một giá trị luôn là một `str`, trong khi thực tế nó rất có thể là `None`. @@ -308,23 +327,29 @@ Sử dụng `Optional[str]` thay cho `str` sẽ cho phép trình soạn thảo g Điều này cũng có nghĩa là trong Python 3.10, bạn có thể sử dụng `Something | None`: -=== "Python 3.10+" +//// tab | Python 3.10+ + +```Python hl_lines="1" +{!> ../../docs_src/python_types/tutorial009_py310.py!} +``` + +//// + +//// tab | Python 3.8+ - ```Python hl_lines="1" - {!> ../../../docs_src/python_types/tutorial009_py310.py!} - ``` +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial009.py!} +``` -=== "Python 3.8+" +//// - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009.py!} - ``` +//// tab | Python 3.8+ alternative -=== "Python 3.8+ alternative" +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial009b.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial009b.py!} - ``` +//// #### Sử dụng `Union` hay `Optional` @@ -343,9 +368,8 @@ Nó chỉ là về các từ và tên. Nhưng những từ đó có thể ảnh Cho một ví dụ, hãy để ý hàm này: -```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009c.py!} -``` +{* ../../docs_src/python_types/tutorial009c.py hl[1,4] *} + Tham số `name` được định nghĩa là `Optional[str]`, nhưng nó **không phải là tùy chọn**, bạn không thể gọi hàm mà không có tham số: @@ -361,9 +385,8 @@ say_hi(name=None) # This works, None is valid 🎉 Tin tốt là, khi bạn sử dụng Python 3.10, bạn sẽ không phải lo lắng về điều đó, bạn sẽ có thể sử dụng `|` để định nghĩa hợp của các kiểu dữ liệu một cách đơn giản: -```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial009c_py310.py!} -``` +{* ../../docs_src/python_types/tutorial009c_py310.py hl[1,4] *} + Và sau đó, bạn sẽ không phải lo rằng những cái tên như `Optional` và `Union`. 😎 @@ -372,47 +395,53 @@ Và sau đó, bạn sẽ không phải lo rằng những cái tên như `Optiona Những kiểu dữ liệu này lấy tham số kiểu dữ liệu trong dấu ngoặc vuông được gọi là **Kiểu dữ liệu tổng quát**, cho ví dụ: -=== "Python 3.10+" +//// tab | Python 3.10+ + +Bạn có thể sử dụng các kiểu dữ liệu có sẵn như là kiểu dữ liệu tổng quát (với ngoặc vuông và kiểu dữ liệu bên trong): + +* `list` +* `tuple` +* `set` +* `dict` - Bạn có thể sử dụng các kiểu dữ liệu có sẵn như là kiểu dữ liệu tổng quát (với ngoặc vuông và kiểu dữ liệu bên trong): +Và tương tự với Python 3.6, từ mô đun `typing`: - * `list` - * `tuple` - * `set` - * `dict` +* `Union` +* `Optional` (tương tự như Python 3.6) +* ...và các kiểu dữ liệu khác. - Và tương tự với Python 3.6, từ mô đun `typing`: +Trong Python 3.10, thay vì sử dụng `Union` và `Optional`, bạn có thể sử dụng sổ dọc ('|') để khai báo hợp của các kiểu dữ liệu, điều đó tốt hơn và đơn giản hơn nhiều. - * `Union` - * `Optional` (tương tự như Python 3.6) - * ...và các kiểu dữ liệu khác. +//// - Trong Python 3.10, thay vì sử dụng `Union` và `Optional`, bạn có thể sử dụng sổ dọc ('|') để khai báo hợp của các kiểu dữ liệu, điều đó tốt hơn và đơn giản hơn nhiều. +//// tab | Python 3.9+ -=== "Python 3.9+" +Bạn có thể sử dụng các kiểu dữ liệu có sẵn tương tự như (với ngoặc vuông và kiểu dữ liệu bên trong): - Bạn có thể sử dụng các kiểu dữ liệu có sẵn tương tự như (với ngoặc vuông và kiểu dữ liệu bên trong): +* `list` +* `tuple` +* `set` +* `dict` - * `list` - * `tuple` - * `set` - * `dict` +Và tương tự với Python 3.6, từ mô đun `typing`: - Và tương tự với Python 3.6, từ mô đun `typing`: +* `Union` +* `Optional` +* ...and others. - * `Union` - * `Optional` - * ...and others. +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - * `List` - * `Tuple` - * `Set` - * `Dict` - * `Union` - * `Optional` - * ...và các kiểu khác. +* `List` +* `Tuple` +* `Set` +* `Dict` +* `Union` +* `Optional` +* ...và các kiểu khác. + +//// ### Lớp như kiểu dữ liệu @@ -420,15 +449,13 @@ Bạn cũng có thể khai báo một lớp như là kiểu dữ liệu của m Hãy nói rằng bạn muốn có một lớp `Person` với một tên: -```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + Sau đó bạn có thể khai báo một biến có kiểu là `Person`: -```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + Và lại một lần nữa, bạn có được tất cả sự hỗ trợ từ trình soạn thảo: @@ -440,7 +467,7 @@ Nó không có nghĩa "`one_person`" là một **lớp** gọi là `Person`. ## Pydantic models -Pydantic là một thư viện Python để validate dữ liệu hiệu năng cao. +Pydantic là một thư viện Python để validate dữ liệu hiệu năng cao. Bạn có thể khai báo "hình dạng" của dữa liệu như là các lớp với các thuộc tính. @@ -452,56 +479,71 @@ Và bạn nhận được tất cả sự hỗ trợ của trình soạn thảo Một ví dụ từ tài liệu chính thức của Pydantic: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python - {!> ../../../docs_src/python_types/tutorial011_py310.py!} - ``` +```Python +{!> ../../docs_src/python_types/tutorial011_py310.py!} +``` + +//// -=== "Python 3.9+" +//// tab | Python 3.9+ + +```Python +{!> ../../docs_src/python_types/tutorial011_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python +{!> ../../docs_src/python_types/tutorial011.py!} +``` - ```Python - {!> ../../../docs_src/python_types/tutorial011_py39.py!} - ``` +//// -=== "Python 3.8+" +/// info - ```Python - {!> ../../../docs_src/python_types/tutorial011.py!} - ``` +Để học nhiều hơn về Pydantic, tham khảo tài liệu của nó. -!!! info - Để học nhiều hơn về Pydantic, tham khảo tài liệu của nó. +/// **FastAPI** được dựa hoàn toàn trên Pydantic. Bạn sẽ thấy nhiều ví dụ thực tế hơn trong [Hướng dẫn sử dụng](tutorial/index.md){.internal-link target=_blank}. -!!! tip - Pydantic có một hành vi đặc biệt khi bạn sử dụng `Optional` hoặc `Union[Something, None]` mà không có giá trị mặc dịnh, bạn có thể đọc nhiều hơn về nó trong tài liệu của Pydantic về Required Optional fields. +/// tip +Pydantic có một hành vi đặc biệt khi bạn sử dụng `Optional` hoặc `Union[Something, None]` mà không có giá trị mặc dịnh, bạn có thể đọc nhiều hơn về nó trong tài liệu của Pydantic về Required Optional fields. + +/// ## Type Hints với Metadata Annotations Python cũng có một tính năng cho phép đặt **metadata bổ sung** trong những gợi ý kiểu dữ liệu này bằng cách sử dụng `Annotated`. -=== "Python 3.9+" +//// tab | Python 3.9+ + +Trong Python 3.9, `Annotated` là một phần của thư viện chuẩn, do đó bạn có thể import nó từ `typing`. - Trong Python 3.9, `Annotated` là một phần của thư viện chuẩn, do đó bạn có thể import nó từ `typing`. +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial013_py39.py!} +``` - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial013_py39.py!} - ``` +//// -=== "Python 3.8+" +//// tab | Python 3.8+ - Ở phiên bản dưới Python 3.9, bạn import `Annotated` từ `typing_extensions`. +Ở phiên bản dưới Python 3.9, bạn import `Annotated` từ `typing_extensions`. - Nó đã được cài đặt sẵng cùng với **FastAPI**. +Nó đã được cài đặt sẵng cùng với **FastAPI**. - ```Python hl_lines="1 4" - {!> ../../../docs_src/python_types/tutorial013.py!} - ``` +```Python hl_lines="1 4" +{!> ../../docs_src/python_types/tutorial013.py!} +``` + +//// Python bản thân nó không làm bất kì điều gì với `Annotated`. Với các trình soạn thảo và các công cụ khác, kiểu dữ liệu vẫn là `str`. @@ -514,10 +556,13 @@ Bây giờ, bạn chỉ cần biết rằng `Annotated` tồn tại, và nó là Sau đó, bạn sẽ thấy sự **mạnh mẽ** mà nó có thể làm. -!!! tip - Thực tế, cái này là **tiêu chuẩn của Python**, nghĩa là bạn vẫn sẽ có được **trải nghiệm phát triển tốt nhất có thể** với trình soạn thảo của bạn, với các công cụ bạn sử dụng để phân tích và tái cấu trúc code của bạn, etc. ✨ +/// tip + +Thực tế, cái này là **tiêu chuẩn của Python**, nghĩa là bạn vẫn sẽ có được **trải nghiệm phát triển tốt nhất có thể** với trình soạn thảo của bạn, với các công cụ bạn sử dụng để phân tích và tái cấu trúc code của bạn, etc. ✨ + +Và code của bạn sẽ tương thích với nhiều công cụ và thư viện khác của Python. 🚀 - Và code của bạn sẽ tương thích với nhiều công cụ và thư viện khác của Python. 🚀 +/// ## Các gợi ý kiểu dữ liệu trong **FastAPI** @@ -541,5 +586,8 @@ Với **FastAPI**, bạn khai báo các tham số với gợi ý kiểu và bạ Điều quan trọng là bằng việc sử dụng các kiểu dữ liệu chuẩn của Python (thay vì thêm các lớp, decorators,...), **FastAPI** sẽ thực hiện nhiều công việc cho bạn. -!!! info - Nếu bạn đã đi qua toàn bộ các hướng dẫn và quay trở lại để tìm hiểu nhiều hơn về các kiểu dữ liệu, một tài nguyên tốt như "cheat sheet" từ `mypy`. +/// info + +Nếu bạn đã đi qua toàn bộ các hướng dẫn và quay trở lại để tìm hiểu nhiều hơn về các kiểu dữ liệu, một tài nguyên tốt như "cheat sheet" từ `mypy`. + +/// diff --git a/docs/vi/docs/tutorial/first-steps.md b/docs/vi/docs/tutorial/first-steps.md index 712f00852..901c8fd59 100644 --- a/docs/vi/docs/tutorial/first-steps.md +++ b/docs/vi/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ Tệp tin FastAPI đơn giản nhất có thể trông như này: -```Python -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} Sao chép sang một tệp tin `main.py`. @@ -24,12 +22,15 @@ $ uvicorn main:app --reload
-!!! note - Câu lệnh `uvicorn main:app` được giải thích như sau: +/// note + +Câu lệnh `uvicorn main:app` được giải thích như sau: + +* `main`: tệp tin `main.py` (một Python "mô đun"). +* `app`: một object được tạo ra bên trong `main.py` với dòng `app = FastAPI()`. +* `--reload`: làm server khởi động lại sau mỗi lần thay đổi. Chỉ sử dụng trong môi trường phát triển. - * `main`: tệp tin `main.py` (một Python "mô đun"). - * `app`: một object được tạo ra bên trong `main.py` với dòng `app = FastAPI()`. - * `--reload`: làm server khởi động lại sau mỗi lần thay đổi. Chỉ sử dụng trong môi trường phát triển. +/// Trong output, có một dòng giống như: @@ -130,22 +131,21 @@ Bạn cũng có thể sử dụng nó để sinh code tự động, với các c ### Bước 1: import `FastAPI` -```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI` là một Python class cung cấp tất cả chức năng cho API của bạn. -!!! note "Chi tiết kĩ thuật" - `FastAPI` là một class kế thừa trực tiếp `Starlette`. +/// note | Chi tiết kĩ thuật + +`FastAPI` là một class kế thừa trực tiếp `Starlette`. - Bạn cũng có thể sử dụng tất cả Starlette chức năng với `FastAPI`. +Bạn cũng có thể sử dụng tất cả Starlette chức năng với `FastAPI`. + +/// ### Bước 2: Tạo một `FastAPI` "instance" -```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[3] *} Biến `app` này là một "instance" của class `FastAPI`. @@ -165,9 +165,7 @@ $ uvicorn main:app --reload Nếu bạn tạo ứng dụng của bạn giống như: -```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} -``` +{* ../../docs_src/first_steps/tutorial002.py hl[3] *} Và đặt nó trong một tệp tin `main.py`, sau đó bạn sẽ gọi `uvicorn` giống như: @@ -199,8 +197,11 @@ https://example.com/items/foo /items/foo ``` -!!! info - Một đường dẫn cũng là một cách gọi chung cho một "endpoint" hoặc một "route". +/// info + +Một đường dẫn cũng là một cách gọi chung cho một "endpoint" hoặc một "route". + +/// Trong khi xây dựng một API, "đường dẫn" là các chính để phân tách "mối quan hệ" và "tài nguyên". @@ -241,25 +242,26 @@ Chúng ta cũng sẽ gọi chúng là "**các toán tử**". #### Định nghĩa moojt *decorator cho đường dẫn toán tử* -```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[6] *} `@app.get("/")` nói **FastAPI** rằng hàm bên dưới có trách nhiệm xử lí request tới: * đường dẫn `/` * sử dụng một toán tửget -!!! info Thông tin về "`@decorator`" - Cú pháp `@something` trong Python được gọi là một "decorator". +/// info | Thông tin về "`@decorator`" + +Cú pháp `@something` trong Python được gọi là một "decorator". + +Bạn đặt nó trên một hàm. Giống như một chiếc mũ xinh xắn (Tôi ddonas đó là lí do mà thuật ngữ này ra đời). - Bạn đặt nó trên một hàm. Giống như một chiếc mũ xinh xắn (Tôi ddonas đó là lí do mà thuật ngữ này ra đời). +Một "decorator" lấy một hàm bên dưới và thực hiện một vài thứ với nó. - Một "decorator" lấy một hàm bên dưới và thực hiện một vài thứ với nó. +Trong trường hợp của chúng ta, decorator này nói **FastAPI** rằng hàm bên dưới ứng với **đường dẫn** `/` và một **toán tử** `get`. - Trong trường hợp của chúng ta, decorator này nói **FastAPI** rằng hàm bên dưới ứng với **đường dẫn** `/` và một **toán tử** `get`. +Nó là một "**decorator đường dẫn toán tử**". - Nó là một "**decorator đường dẫn toán tử**". +/// Bạn cũng có thể sử dụng với các toán tử khác: @@ -274,14 +276,17 @@ Và nhiều hơn với các toán tử còn lại: * `@app.patch()` * `@app.trace()` -!!! tip - Bạn thoải mái sử dụng mỗi toán tử (phương thức HTTP) như bạn mơ ước. +/// tip + +Bạn thoải mái sử dụng mỗi toán tử (phương thức HTTP) như bạn mơ ước. + +**FastAPI** không bắt buộc bất kì ý nghĩa cụ thể nào. - **FastAPI** không bắt buộc bất kì ý nghĩa cụ thể nào. +Thông tin ở đây được biểu thị như là một chỉ dẫn, không phải là một yêu cầu bắt buộc. - Thông tin ở đây được biểu thị như là một chỉ dẫn, không phải là một yêu cầu bắt buộc. +Ví dụ, khi sử dụng GraphQL bạn thông thường thực hiện tất cả các hành động chỉ bằng việc sử dụng các toán tử `POST`. - Ví dụ, khi sử dụng GraphQL bạn thông thường thực hiện tất cả các hành động chỉ bằng việc sử dụng các toán tử `POST`. +/// ### Step 4: Định nghĩa **hàm cho đường dẫn toán tử** @@ -291,9 +296,7 @@ Và nhiều hơn với các toán tử còn lại: * **toán tử**: là `get`. * **hàm**: là hàm bên dưới "decorator" (bên dưới `@app.get("/")`). -```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[7] *} Đây là một hàm Python. @@ -305,18 +308,17 @@ Trong trường hợp này, nó là một hàm `async`. Bạn cũng có thể định nghĩa nó như là một hàm thông thường thay cho `async def`: -```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} -``` +{* ../../docs_src/first_steps/tutorial003.py hl[7] *} + +/// note -!!! note - Nếu bạn không biết sự khác nhau, kiểm tra [Async: *"Trong khi vội vàng?"*](../async.md#in-a-hurry){.internal-link target=_blank}. +Nếu bạn không biết sự khác nhau, kiểm tra [Async: *"Trong khi vội vàng?"*](../async.md#in-a-hurry){.internal-link target=_blank}. + +/// ### Bước 5: Nội dung trả về -```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[8] *} Bạn có thể trả về một `dict`, `list`, một trong những giá trị đơn như `str`, `int`,... diff --git a/docs/vi/docs/tutorial/index.md b/docs/vi/docs/tutorial/index.md index e8a93fe40..dfeeed8c5 100644 --- a/docs/vi/docs/tutorial/index.md +++ b/docs/vi/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ...dó cũng bao gồm `uvicorn`, bạn có thể sử dụng như một server để chạy code của bạn. -!!! note - Bạn cũng có thể cài đặt nó từng phần. +/// note - Đây là những gì bạn có thể sẽ làm một lần duy nhất bạn muốn triển khai ứng dụng của bạn lên production: +Bạn cũng có thể cài đặt nó từng phần. - ``` - pip install fastapi - ``` +Đây là những gì bạn có thể sẽ làm một lần duy nhất bạn muốn triển khai ứng dụng của bạn lên production: - Cũng cài đặt `uvicorn` để làm việc như một server: +``` +pip install fastapi +``` + +Cũng cài đặt `uvicorn` để làm việc như một server: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +Và tương tự với từng phụ thuộc tùy chọn mà bạn muốn sử dụng. - Và tương tự với từng phụ thuộc tùy chọn mà bạn muốn sử dụng. +/// ## Hướng dẫn nâng cao diff --git a/docs/vi/docs/tutorial/static-files.md b/docs/vi/docs/tutorial/static-files.md new file mode 100644 index 000000000..ecf8c2485 --- /dev/null +++ b/docs/vi/docs/tutorial/static-files.md @@ -0,0 +1,40 @@ +# Tệp tĩnh (Static Files) + +Bạn có thể triển khai tệp tĩnh tự động từ một thư mục bằng cách sử dụng StaticFiles. + +## Sử dụng `Tệp tĩnh` + +- Nhập `StaticFiles`. +- "Mount" a `StaticFiles()` instance in a specific path. + +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} + +/// note | Chi tiết kỹ thuật + +Bạn cũng có thể sử dụng `from starlette.staticfiles import StaticFiles`. + +**FastAPI** cung cấp cùng `starlette.staticfiles` như `fastapi.staticfiles` giúp đơn giản hóa việc sử dụng, nhưng nó thực sự đến từ Starlette. + +/// + +### "Mounting" là gì + +"Mounting" có nghĩa là thêm một ứng dụng "độc lập" hoàn chỉnh vào một đường dẫn cụ thể, sau đó ứng dụng đó sẽ chịu trách nhiệm xử lý tất cả các đường dẫn con. + +Điều này khác với việc sử dụng `APIRouter` vì một ứng dụng được gắn kết là hoàn toàn độc lập. OpenAPI và tài liệu từ ứng dụng chính của bạn sẽ không bao gồm bất kỳ thứ gì từ ứng dụng được gắn kết, v.v. + +Bạn có thể đọc thêm về điều này trong [Hướng dẫn Người dùng Nâng cao](../advanced/index.md){.internal-link target=\_blank}. + +## Chi tiết + +Đường dẫn đầu tiên `"/static"` là đường dẫn con mà "ứng dụng con" này sẽ được "gắn" vào. Vì vậy, bất kỳ đường dẫn nào bắt đầu bằng `"/static"` sẽ được xử lý bởi nó. + +Đường dẫn `directory="static"` là tên của thư mục chứa tệp tĩnh của bạn. + +Tham số `name="static"` đặt tên cho nó để có thể được sử dụng bên trong **FastAPI**. + +Tất cả các tham số này có thể khác với `static`, điều chỉnh chúng với phù hợp với ứng dụng của bạn. + +## Thông tin thêm + +Để biết thêm chi tiết và tùy chọn, hãy xem Starlette's docs about Static Files. diff --git a/docs/vi/docs/virtual-environments.md b/docs/vi/docs/virtual-environments.md new file mode 100644 index 000000000..22d8e153e --- /dev/null +++ b/docs/vi/docs/virtual-environments.md @@ -0,0 +1,842 @@ +# Môi trường ảo (Virtual Environments) + +Khi bạn làm việc trong các dự án Python, bạn có thể sử dụng một **môi trường ảo** (hoặc một cơ chế tương tự) để cách ly các gói bạn cài đặt cho mỗi dự án. + +/// info +Nếu bạn đã biết về các môi trường ảo, cách tạo chúng và sử dụng chúng, bạn có thể bỏ qua phần này. 🤓 + +/// + +/// tip + +Một **môi trường ảo** khác với một **biến môi trường (environment variable)**. + +Một **biến môi trường** là một biến trong hệ thống có thể được sử dụng bởi các chương trình. + +Một **môi trường ảo** là một thư mục với một số tệp trong đó. + +/// + +/// info + +Trang này sẽ hướng dẫn bạn cách sử dụng các **môi trường ảo** và cách chúng hoạt động. + +Nếu bạn đã sẵn sàng sử dụng một **công cụ có thể quản lý tất cả mọi thứ** cho bạn (bao gồm cả việc cài đặt Python), hãy thử uv. + +/// + +## Tạo một Dự án + +Đầu tiên, tạo một thư mục cho dự án của bạn. + +Cách tôi thường làm là tạo một thư mục có tên `code` trong thư mục `home/user`. + +Và trong thư mục đó, tôi tạo một thư mục cho mỗi dự án. + +
+ +```console +// Đi đến thư mục home +$ cd +// Tạo một thư mục cho tất cả các dự án của bạn +$ mkdir code +// Vào thư mục code +$ cd code +// Tạo một thư mục cho dự án này +$ mkdir awesome-project +// Vào thư mục dự án +$ cd awesome-project +``` + +
+ +## Tạo một Môi trường ảo + +Khi bạn bắt đầu làm việc với một dự án Python **trong lần đầu**, hãy tạo một môi trường ảo **trong thư mục dự án của bạn**. + +/// tip + +Bạn cần làm điều này **một lần cho mỗi dự án**, không phải mỗi khi bạn làm việc. +/// + +//// tab | `venv` + +Để tạo một môi trường ảo, bạn có thể sử dụng module `venv` có sẵn của Python. + +
+ +```console +$ python -m venv .venv +``` + +
+ +/// details | Cách các lệnh hoạt động + +* `python`: sử dụng chương trình `python` +* `-m`: gọi một module như một script, chúng ta sẽ nói về module đó sau +* `venv`: sử dụng module `venv` được cài đặt sẵn của Python +* `.venv`: tạo môi trường ảo trong thư mục mới `.venv` + +/// + +//// + +//// tab | `uv` + +Nếu bạn có `uv` được cài đặt, bạn có thể sử dụng nó để tạo một môi trường ảo. + +
+ +```console +$ uv venv +``` + +
+ +/// tip + +Mặc định, `uv` sẽ tạo một môi trường ảo trong một thư mục có tên `.venv`. + +Nhưng bạn có thể tùy chỉnh nó bằng cách thêm một đối số với tên thư mục. + +/// + +//// + +Lệnh này tạo một môi trường ảo mới trong một thư mục có tên `.venv`. + +/// details | `.venv` hoặc tên khác + +Bạn có thể tạo môi trường ảo trong một thư mục khác, nhưng thường người ta quy ước đặt nó là `.venv`. + +/// + +## Kích hoạt Môi trường ảo + +Kích hoạt môi trường ảo mới để bất kỳ lệnh Python nào bạn chạy hoặc gói nào bạn cài đặt sẽ sử dụng nó. + +/// tip + +Làm điều này **mỗi khi** bạn bắt đầu một **phiên terminal mới** để làm việc trên dự án. + +/// + +//// tab | Linux, macOS + +
+ +```console +$ source .venv/bin/activate +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ .venv\Scripts\Activate.ps1 +``` + +
+ +//// + +//// tab | Windows Bash + +Nếu bạn sử dụng Bash cho Windows (ví dụ: Git Bash): + +
+ +```console +$ source .venv/Scripts/activate +``` + +
+ +//// + +/// tip + +Mỗi khi bạn cài đặt thêm một **package mới** trong môi trường đó, hãy **kích hoạt** môi trường đó lại. + +Điều này đảm bảo rằng khi bạn sử dụng một **chương trình dòng lệnh (CLI)** được cài đặt từ gói đó, bạn sẽ dùng bản cài đặt từ môi trường ảo của mình thay vì bản được cài đặt toàn cục khác có thể có phiên bản khác với phiên bản bạn cần. + +/// + +## Kiểm tra xem Môi trường ảo đã được Kích hoạt chưa + +Kiểm tra xem môi trường ảo đã được kích hoạt chưa (lệnh trước đó đã hoạt động). + +/// tip + +Điều này là **không bắt buộc**, nhưng nó là một cách tốt để **kiểm tra** rằng mọi thứ đang hoạt động như mong đợi và bạn đang sử dụng đúng môi trường ảo mà bạn đã định. + +/// + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
+ +Nếu nó hiển thị `python` binary tại `.venv/bin/python`, trong dự án của bạn (trong trường hợp `awesome-project`), thì tức là nó hoạt động. 🎉 + +//// + +//// tab | Windows PowerShell + +
+ +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
+ +Nếu nó hiển thị `python` binary tại `.venv\Scripts\python`, trong dự án của bạn (trong trường hợp `awesome-project`), thì tức là nó hoạt động. 🎉 + +//// + +## Nâng cấp `pip` + +/// tip + +Nếu bạn sử dụng `uv` bạn sử dụng nó để cài đặt thay vì `pip`, thì bạn không cần cập nhật `pip`. 😎 + +/// + +Nếu bạn sử dụng `pip` để cài đặt gói (nó được cài đặt mặc định với Python), bạn nên **nâng cấp** nó lên phiên bản mới nhất. + +Nhiều lỗi khác nhau trong khi cài đặt gói được giải quyết chỉ bằng cách nâng cấp `pip` trước. + +/// tip + +Bạn thường làm điều này **một lần**, ngay sau khi bạn tạo môi trường ảo. + +/// + +Đảm bảo rằng môi trường ảo đã được kích hoạt (với lệnh trên) và sau đó chạy: + +
+ +```console +$ python -m pip install --upgrade pip + +---> 100% +``` + +
+ +## Thêm `.gitignore` + +Nếu bạn sử dụng **Git** (nên làm), hãy thêm một file `.gitignore` để Git bỏ qua mọi thứ trong `.venv`. + +/// tip + +Nếu bạn sử dụng `uv` để tạo môi trường ảo, nó đã tự động làm điều này cho bạn, bạn có thể bỏ qua bước này. 😎 + +/// + +/// tip + +Làm điều này **một lần**, ngay sau khi bạn tạo môi trường ảo. + +/// + +
+ +```console +$ echo "*" > .venv/.gitignore +``` + +
+ +/// details | Cách lệnh hoạt động + +* `echo "*"`: sẽ "in" văn bản `*` trong terminal (phần tiếp theo sẽ thay đổi điều đó một chút) +* `>`: bất kỳ văn bản nào được in ra terminal bởi lệnh trước `>` không được in ra mà thay vào đó được viết vào file ở phía bên phải của `>` +* `.gitignore`: tên của file mà văn bản sẽ được viết vào + +Và `*` với Git có nghĩa là "mọi thứ". Vì vậy, nó sẽ bỏ qua mọi thứ trong thư mục `.venv`. + +Lệnh này sẽ tạo một file `.gitignore` với nội dung: + +```gitignore +* +``` + +/// + +## Cài đặt gói (packages) + +Sau khi kích hoạt môi trường, bạn có thể cài đặt các gói trong đó. + +/// tip + +Thực hiện điều này **một lần** khi cài đặt hoặc cập nhật gói cần thiết cho dự án của bạn. + +Nếu bạn cần cập nhật phiên bản hoặc thêm một gói mới, bạn sẽ **thực hiện điều này lại**. + +/// + +### Cài đặt gói trực tiếp + +Nếu bạn cần cập nhật phiên bản hoặc thêm một gói mới, bạn sẽ **thực hiện điều này lại**. + +/// tip +Để quản lý dự án tốt hơn, hãy liệt kê tất cả các gói và phiên bản cần thiết trong một file (ví dụ `requirements.txt` hoặc `pyproject.toml`). + +/// + +//// tab | `pip` + +
+ +```console +$ pip install "fastapi[standard]" + +---> 100% +``` + +
+ +//// + +//// tab | `uv` + +Nếu bạn có `uv`: + +
+ +```console +$ uv pip install "fastapi[standard]" +---> 100% +``` + +
+ +//// + +### Cài đặt từ `requirements.txt` + +Nếu bạn có một tệp `requirements.txt`, bạn có thể sử dụng nó để cài đặt các gói. + +//// tab | `pip` + +
+ +```console +$ pip install -r requirements.txt +---> 100% +``` + +
+ +//// + +//// tab | `uv` + +Nếu bạn có `uv`: + +
+ +```console +$ uv pip install -r requirements.txt +---> 100% +``` + +
+ +//// + +/// details | `requirements.txt` + +Một tệp `requirements.txt` với một số gói sẽ trông như thế này: + +```requirements.txt +fastapi[standard]==0.113.0 +pydantic==2.8.0 +``` + +/// + +## Chạy Chương trình của bạn + +Sau khi kích hoạt môi trường ảo, bạn có thể chạy chương trình của mình, nó sẽ sử dụng Python trong môi trường ảo của bạn với các gói bạn đã cài đặt. + +
+ +```console +$ python main.py + +Hello World +``` + +
+ +## Cấu hình Trình soạn thảo của bạn + +Nếu bạn sử dụng một trình soạn thảo, hãy đảm bảo bạn cấu hình nó để sử dụng cùng môi trường ảo mà bạn đã tạo (trình soạn thảo sẽ tự động phát hiện môi trường ảo) để bạn có thể nhận được tính năng tự động hoàn thành câu lệnh (autocomplete) và in lỗi trực tiếp trong trình soạn thảo (inline errors). + +Ví dụ: + +* VS Code +* PyCharm + +/// tip + +Bạn thường chỉ cần làm điều này **một lần**, khi bạn tạo môi trường ảo. + +/// + +## Huỷ kích hoạt Môi trường ảo + +Khi bạn hoàn tất việc làm trên dự án của bạn, bạn có thể **huỷ kích hoạt** môi trường ảo. + +
+ +```console +$ deactivate +``` + +
+ +Như vậy, khi bạn chạy `python`, nó sẽ không chạy từ môi trường ảo đó với các gói đã cài đặt. + +## Sẵn sàng để Làm việc + +Bây giờ bạn đã sẵn sàng để làm việc trên dự án của mình rồi đấy. + +/// tip + +Bạn muốn hiểu tất cả những gì ở trên? + +Tiếp tục đọc. 👇🤓 + +/// + +## Tại sao cần Môi trường ảo + +Để làm việc với FastAPI, bạn cần cài đặt Python. + +Sau đó, bạn sẽ cần **cài đặt** FastAPI và bất kỳ **gói** nào mà bạn muốn sử dụng. + +Để cài đặt gói, bạn thường sử dụng lệnh `pip` có sẵn với Python (hoặc các phiên bản tương tự). + +Tuy nhiên, nếu bạn sử dụng `pip` trực tiếp, các gói sẽ được cài đặt trong **môi trường Python toàn cục** của bạn (phần cài đặt toàn cục của Python). + +### Vấn đề + +Vậy, vấn đề gì khi cài đặt gói trong môi trường Python toàn cục? + +Trong một vài thời điểm, bạn sẽ phải viết nhiều chương trình khác nhau phụ thuộc vào **các gói khác nhau**. Và một số dự án bạn thực hiện lại phụ thuộc vào **các phiên bản khác nhau** của cùng một gói. 😱 + +Ví dụ, bạn có thể tạo một dự án được gọi là `philosophers-stone`, chương trình này phụ thuộc vào một gói khác được gọi là **`harry`, sử dụng phiên bản `1`**. Vì vậy, bạn cần cài đặt `harry`. + +```mermaid +flowchart LR + stone(philosophers-stone) -->|phụ thuộc| harry-1[harry v1] +``` + +Sau đó, vào một vài thời điểm sau, bạn tạo một dự án khác được gọi là `prisoner-of-azkaban`, và dự án này cũng phụ thuộc vào `harry`, nhưng dự án này cần **`harry` phiên bản `3`**. + +```mermaid +flowchart LR + azkaban(prisoner-of-azkaban) --> |phụ thuộc| harry-3[harry v3] +``` + +Bây giờ, vấn đề là, nếu bạn cài đặt các gói toàn cục (trong môi trường toàn cục) thay vì trong một **môi trường ảo cục bộ**, bạn sẽ phải chọn phiên bản `harry` nào để cài đặt. + +Nếu bạn muốn chạy `philosophers-stone` bạn sẽ cần phải cài đặt `harry` phiên bản `1`, ví dụ với: + +
+ +```console +$ pip install "harry==1" +``` + +
+ +Và sau đó bạn sẽ có `harry` phiên bản `1` được cài đặt trong môi trường Python toàn cục của bạn. + +```mermaid +flowchart LR + subgraph global[môi trường toàn cục] + harry-1[harry v1] + end + subgraph stone-project[dự án philosophers-stone ] + stone(philosophers-stone) -->|phụ thuộc| harry-1 + end +``` + +Nhưng sau đó, nếu bạn muốn chạy `prisoner-of-azkaban`, bạn sẽ cần phải gỡ bỏ `harry` phiên bản `1` và cài đặt `harry` phiên bản `3` (hoặc chỉ cần cài đặt phiên bản `3` sẽ tự động gỡ bỏ phiên bản `1`). + +
+ +```console +$ pip install "harry==3" +``` + +
+ +Và sau đó bạn sẽ có `harry` phiên bản `3` được cài đặt trong môi trường Python toàn cục của bạn. + +Và nếu bạn cố gắng chạy `philosophers-stone` lại, có khả năng nó sẽ **không hoạt động** vì nó cần `harry` phiên bản `1`. + +```mermaid +flowchart LR + subgraph global[môi trường toàn cục] + harry-1[harry v1] + style harry-1 fill:#ccc,stroke-dasharray: 5 5 + harry-3[harry v3] + end + subgraph stone-project[dự án philosophers-stone ] + stone(philosophers-stone) -.-x|⛔️| harry-1 + end + subgraph azkaban-project[dự án prisoner-of-azkaban ] + azkaban(prisoner-of-azkaban) --> |phụ thuộc| harry-3 + end +``` + +/// tip + +Mặc dù các gói Python thường cố gắng **tránh các thay đổi làm hỏng code** trong **phiên bản mới**, nhưng để đảm bảo an toàn, bạn nên chủ động cài đặt phiên bản mới và chạy kiểm thử để xác nhận mọi thứ vẫn hoạt động đúng. + +/// + +Bây giờ, hãy hình dung về **nhiều** gói khác nhau mà tất cả các dự án của bạn phụ thuộc vào. Rõ ràng rất khó để quản lý. Điều này dẫn tới việc là bạn sẽ có nhiều dự án với **các phiên bản không tương thích** của các gói, và bạn có thể không biết tại sao một số thứ không hoạt động. + +Hơn nữa, tuỳ vào hệ điều hành của bạn (vd Linux, Windows, macOS), có thể đã có Python được cài đặt sẵn. Trong trường hợp ấy, một vài gói nhiều khả năng đã được cài đặt trước với các phiên bản **cần thiết cho hệ thống của bạn**. Nếu bạn cài đặt các gói trong môi trường Python toàn cục, bạn có thể sẽ **phá vỡ** một số chương trình đã được cài đặt sẵn cùng hệ thống. + +## Nơi các Gói được Cài đặt + +Khi bạn cài đặt Python, nó sẽ tạo ra một vài thư mục và tệp trong máy tính của bạn. + +Một vài thư mục này là những thư mục chịu trách nhiệm có tất cả các gói bạn cài đặt. + +Khi bạn chạy: + +
+ +```console +// Đừng chạy lệnh này ngay, đây chỉ là một ví dụ 🤓 +$ pip install "fastapi[standard]" +---> 100% +``` + +
+ +Lệnh này sẽ tải xuống một tệp nén với mã nguồn FastAPI, thường là từ PyPI. + +Nó cũng sẽ **tải xuống** các tệp cho các gói khác mà FastAPI phụ thuộc vào. + +Sau đó, nó sẽ **giải nén** tất cả các tệp đó và đưa chúng vào một thư mục trong máy tính của bạn. + +Mặc định, nó sẽ đưa các tệp đã tải xuống và giải nén vào thư mục được cài đặt cùng Python của bạn, đó là **môi trường toàn cục**. + +## Những Môi trường ảo là gì? + +Cách giải quyết cho vấn đề có tất cả các gói trong môi trường toàn cục là sử dụng một **môi trường ảo cho mỗi dự án** bạn làm việc. + +Một môi trường ảo là một **thư mục**, rất giống với môi trường toàn cục, trong đó bạn có thể cài đặt các gói cho một dự án. + +Vì vậy, mỗi dự án sẽ có một môi trường ảo riêng của nó (thư mục `.venv`) với các gói riêng của nó. + +```mermaid +flowchart TB + subgraph stone-project[dự án philosophers-stone ] + stone(philosophers-stone) --->|phụ thuộc| harry-1 + subgraph venv1[.venv] + harry-1[harry v1] + end + end + subgraph azkaban-project[dự án prisoner-of-azkaban ] + azkaban(prisoner-of-azkaban) --->|phụ thuộc| harry-3 + subgraph venv2[.venv] + harry-3[harry v3] + end + end + stone-project ~~~ azkaban-project +``` + +## Kích hoạt Môi trường ảo nghĩa là gì + +Khi bạn kích hoạt một môi trường ảo, ví dụ với: + +//// tab | Linux, macOS + +
+ +```console +$ source .venv/bin/activate +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ .venv\Scripts\Activate.ps1 +``` + +
+ +//// + +//// tab | Windows Bash + +Nếu bạn sử dụng Bash cho Windows (ví dụ Git Bash): + +
+ +```console +$ source .venv/Scripts/activate +``` + +
+ +//// + +Lệnh này sẽ tạo hoặc sửa đổi một số [biến môi trường](environment-variables.md){.internal-link target=_blank} mà sẽ được sử dụng cho các lệnh tiếp theo. + +Một trong số đó là biến `PATH`. + +/// tip + +Bạn có thể tìm hiểu thêm về biến `PATH` trong [Biến môi trường](environment-variables.md#path-environment-variable){.internal-link target=_blank} section. + +/// + +Kích hoạt môi trường ảo thêm đường dẫn `.venv/bin` (trên Linux và macOS) hoặc `.venv\Scripts` (trên Windows) vào biến `PATH`. + +Giả sử rằng trước khi kích hoạt môi trường, biến `PATH` như sau: + +//// tab | Linux, macOS + +```plaintext +/usr/bin:/bin:/usr/sbin:/sbin +``` + +Nghĩa là hệ thống sẽ tìm kiếm chương trình trong: + +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Windows\System32 +``` + +Nghĩa là hệ thống sẽ tìm kiếm chương trình trong: + +* `C:\Windows\System32` + +//// + +Sau khi kích hoạt môi trường ảo, biến `PATH` sẽ như sau: + +//// tab | Linux, macOS + +```plaintext +/home/user/code/awesome-project/.venv/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +Nghĩa là hệ thống sẽ bắt đầu tìm kiếm chương trình trong: + +```plaintext +/home/user/code/awesome-project/.venv/bin +``` + +trước khi tìm kiếm trong các thư mục khác. + +Vì vậy, khi bạn gõ `python` trong terminal, hệ thống sẽ tìm thấy chương trình Python trong: + +```plaintext +/home/user/code/awesome-project/.venv/bin/python +``` + +và sử dụng chương trình đó. + +//// + +//// tab | Windows + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts;C:\Windows\System32 +``` + +Nghĩa là hệ thống sẽ bắt đầu tìm kiếm chương trình trong: + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts +``` + +trước khi tìm kiếm trong các thư mục khác. + +Vì vậy, khi bạn gõ `python` trong terminal, hệ thống sẽ tìm thấy chương trình Python trong: + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +và sử dụng chương trình đó. + +//// + +Một chi tiết quan trọng là nó sẽ đưa địa chỉ của môi trường ảo vào **đầu** của biến `PATH`. Hệ thống sẽ tìm kiếm nó **trước** khi tìm kiếm bất kỳ Python nào khác có sẵn. Vì vậy, khi bạn chạy `python`, nó sẽ sử dụng Python **từ môi trường ảo** thay vì bất kỳ Python nào khác (ví dụ, Python từ môi trường toàn cục). + +Kích hoạt một môi trường ảo cũng thay đổi một vài thứ khác, nhưng đây là một trong những điều quan trọng nhất mà nó thực hiện. + +## Kiểm tra một Môi trường ảo + +Khi bạn kiểm tra một môi trường ảo đã được kích hoạt chưa, ví dụ với: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
+ +//// + + +Điều đó có nghĩa là chương trình `python` sẽ được sử dụng là chương trình **trong môi trường ảo**. + +Bạn sử dụng `which` trên Linux và macOS và `Get-Command` trên Windows PowerShell. + +Cách hoạt động của lệnh này là nó sẽ đi và kiểm tra biến `PATH`, đi qua **mỗi đường dẫn theo thứ tự**, tìm kiếm chương trình được gọi là `python`. Khi nó tìm thấy nó, nó sẽ **hiển thị cho bạn đường dẫn** đến chương trình đó. + +Điều quan trọng nhất là khi bạn gọi `python`, đó chính là chương trình `python` được thực thi. + +Vì vậy, bạn có thể xác nhận nếu bạn đang ở trong môi trường ảo đúng. + +/// tip + +Dễ dàng kích hoạt một môi trường ảo, cài đặt Python, và sau đó **chuyển đến một dự án khác**. + +Và dự án thứ hai **sẽ không hoạt động** vì bạn đang sử dụng **Python không đúng**, từ một môi trường ảo cho một dự án khác. + +Thật tiện lợi khi có thể kiểm tra `python` nào đang được sử dụng 🤓 + +/// + +## Tại sao lại Huỷ kích hoạt một Môi trường ảo + +Ví dụ, bạn có thể làm việc trên một dự án `philosophers-stone`, **kích hoạt môi trường ảo**, cài đặt các gói và làm việc với môi trường ảo đó. + +Sau đó, bạn muốn làm việc trên **dự án khác** `prisoner-of-azkaban`. + +Bạn đi đến dự án đó: + +
+ +```console +$ cd ~/code/prisoner-of-azkaban +``` + +
+ +Nếu bạn không tắt môi trường ảo cho `philosophers-stone`, khi bạn chạy `python` trong terminal, nó sẽ cố gắng sử dụng Python từ `philosophers-stone`. + +
+ +```console +$ cd ~/code/prisoner-of-azkaban + +$ python main.py + +// Lỗi khi import sirius, nó không được cài đặt 😱 +Traceback (most recent call last): + File "main.py", line 1, in + import sirius +``` + +
+ +Nếu bạn huỷ kích hoạt môi trường ảo hiện tại và kích hoạt môi trường ảo mới cho `prisoner-of-azkaban`, khi bạn chạy `python`, nó sẽ sử dụng Python từ môi trường ảo trong `prisoner-of-azkaban`. + +
+ +```console +$ cd ~/code/prisoner-of-azkaban + +// Bạn không cần phải ở trong thư mục trước để huỷ kích hoạt, bạn có thể làm điều đó ở bất kỳ đâu, ngay cả sau khi đi đến dự án khác 😎 +$ deactivate + +// Kích hoạt môi trường ảo trong prisoner-of-azkaban/.venv 🚀 +$ source .venv/bin/activate + +// Bây giờ khi bạn chạy python, nó sẽ tìm thấy gói sirius được cài đặt trong môi trường ảo này ✨ +$ python main.py + +I solemnly swear 🐺 + +(Tôi long trọng thề 🐺 - câu này được lấy từ Harry Potter, chú thích của người dịch) +``` + +
+ +## Các cách làm tương tự + +Đây là một hướng dẫn đơn giản để bạn có thể bắt đầu và hiểu cách mọi thứ hoạt động **bên trong**. + +Có nhiều **cách khác nhau** để quản lí các môi trường ảo, các gói phụ thuộc (requirements), và các dự án. + +Một khi bạn đã sẵn sàng và muốn sử dụng một công cụ để **quản lí cả dự án**, các gói phụ thuộc, các môi trường ảo, v.v. Tôi sẽ khuyên bạn nên thử uv. + +`uv` có thể làm nhiều thứ, chẳng hạn: + +* **Cài đặt Python** cho bạn, bao gồm nhiều phiên bản khác nhau +* Quản lí **các môi trường ảo** cho các dự án của bạn +* Cài đặt **các gói (packages)** +* Quản lí **các thành phần phụ thuộc và phiên bản** của các gói cho dự án của bạn +* Đảm bảo rằng bạn có một **tập hợp chính xác** các gói và phiên bản để cài đặt, bao gồm các thành phần phụ thuộc của chúng, để bạn có thể đảm bảo rằng bạn có thể chạy dự án của bạn trong sản xuất chính xác như trong máy tính của bạn trong khi phát triển, điều này được gọi là **locking** +* Và còn nhiều thứ khác nữa + +## Kết luận + +Nếu bạn đã đọc và hiểu hết những điều này, khá chắc là bây giờ bạn đã **biết nhiều hơn** về môi trường ảo so với kha khá lập trình viên khác đấy. 🤓 + +Những hiểu biết chi tiết này có thể sẽ hữu ích với bạn trong tương lai khi mà bạn cần gỡ lỗi một vài thứ phức tạp, và bạn đã có những hiểu biết về **ngọn ngành gốc rễ cách nó hoạt động**. 😎 diff --git a/docs/yo/docs/index.md b/docs/yo/docs/index.md index 101e13b6b..d6aa78b3d 100644 --- a/docs/yo/docs/index.md +++ b/docs/yo/docs/index.md @@ -1,3 +1,9 @@ +# FastAPI + + +

FastAPI

@@ -5,11 +11,11 @@ Ìlànà wẹ́ẹ́bù FastAPI, iṣẹ́ gíga, ó rọrùn láti kọ̀, o yára láti kóòdù, ó sì ṣetán fún iṣelọpọ ní lílo

- - Test + + Test - - Coverage + + Coverage Package version @@ -23,15 +29,15 @@ **Àkọsílẹ̀**: https://fastapi.tiangolo.com -**Orisun Kóòdù**: https://github.com/tiangolo/fastapi +**Orisun Kóòdù**: https://github.com/fastapi/fastapi --- -FastAPI jẹ́ ìgbàlódé, tí ó yára (iṣẹ-giga), ìlànà wẹ́ẹ́bù fún kikọ àwọn API pẹ̀lú Python 3.8+ èyí tí ó da lori àwọn ìtọ́kasí àmì irúfẹ́ Python. +FastAPI jẹ́ ìgbàlódé, tí ó yára (iṣẹ-giga), ìlànà wẹ́ẹ́bù fún kikọ àwọn API pẹ̀lú Python èyí tí ó da lori àwọn ìtọ́kasí àmì irúfẹ́ Python. Àwọn ẹya pàtàkì ni: -* **Ó yára**: Iṣẹ tí ó ga púpọ̀, tí ó wa ni ibamu pẹ̀lú **NodeJS** àti **Go** (ọpẹ si Starlette àti Pydantic). [Ọkan nínú àwọn ìlànà Python ti o yára jùlọ ti o wa](#performance). +* **Ó yára**: Iṣẹ tí ó ga púpọ̀, tí ó wa ni ibamu pẹ̀lú **NodeJS** àti **Go** (ọpẹ si Starlette àti Pydantic). [Ọkan nínú àwọn ìlànà Python ti o yára jùlọ ti o wa](#isesi). * **Ó yára láti kóòdù**: O mu iyara pọ si láti kọ àwọn ẹya tuntun kóòdù nipasẹ "Igba ìdá ọgọ́rùn-ún" (i.e. 200%) si "ọ̀ọ́dúrún ìdá ọgọ́rùn-ún" (i.e. 300%). * **Àìtọ́ kékeré**: O n din aṣiṣe ku bi ọgbon ìdá ọgọ́rùn-ún (i.e. 40%) ti eda eniyan (oṣiṣẹ kóòdù) fa. * * **Ọgbọ́n àti ìmọ̀**: Atilẹyin olootu nla. Ìparí nibi gbogbo. Àkókò díẹ̀ nipa wíwá ibi tí ìṣòro kóòdù wà. @@ -63,7 +69,7 @@ FastAPI jẹ́ ìgbàlódé, tí ó yára (iṣẹ-giga), ìlànà wẹ́ẹ́b "_[...] Mò ń lo **FastAPI** púpọ̀ ní lẹ́nu àìpẹ́ yìí. [...] Mo n gbero láti lo o pẹ̀lú àwọn ẹgbẹ mi fún gbogbo iṣẹ **ML wa ni Microsoft**. Diẹ nínú wọn ni afikun ti ifilelẹ àwọn ẹya ara ti ọja **Windows** wa pẹ̀lú àwọn ti **Office**._" -

Kabir Khan - Microsoft (ref)
+
Kabir Khan - Microsoft (ref)
--- @@ -87,7 +93,7 @@ FastAPI jẹ́ ìgbàlódé, tí ó yára (iṣẹ-giga), ìlànà wẹ́ẹ́b "_Ní tòótọ́, ohun tí o kọ dára ó sì tún dán. Ní ọ̀pọ̀lọpọ̀ ọ̀nà, ohun tí mo fẹ́ kí **Hug** jẹ́ nìyẹn - ó wúni lórí gan-an láti rí ẹnìkan tí ó kọ́ nǹkan bí èyí._" -
Timothy Crosley - Hug creator (ref)
+
Timothy Crosley - Hug creator (ref)
--- @@ -115,12 +121,10 @@ Ti o ba n kọ ohun èlò CLI láti ## Èròjà -Python 3.8+ - FastAPI dúró lórí àwọn èjìká tí àwọn òmíràn: * Starlette fún àwọn ẹ̀yà ayélujára. -* Pydantic fún àwọn ẹ̀yà àkójọf'áyẹ̀wò. +* Pydantic fún àwọn ẹ̀yà àkójọf'áyẹ̀wò. ## Fifi sórí ẹrọ @@ -331,7 +335,7 @@ O ṣe ìyẹn pẹ̀lú irúfẹ́ àmì ìtọ́kasí ìgbàlódé Python. O ò nílò láti kọ́ síńtáàsì tuntun, ìlànà tàbí ọ̀wọ́ kíláàsì kan pàtó, abbl (i.e. àti bẹbẹ lọ). -Ìtọ́kasí **Python 3.8+** +Ìtọ́kasí **Python** Fún àpẹẹrẹ, fún `int`: @@ -445,7 +449,7 @@ Láti ní òye síi nípa rẹ̀, wo abala àwọn email_validator - fún ifọwọsi ímeèlì. +* email-validator - fún ifọwọsi ímeèlì. * pydantic-settings - fún ètò ìsàkóso. * pydantic-extra-types - fún àfikún oríṣi láti lọ pẹ̀lú Pydantic. @@ -453,15 +457,15 @@ Láti ní òye síi nípa rẹ̀, wo abala àwọn httpx - Nílò tí ó bá fẹ́ láti lọ `TestClient`. * jinja2 - Nílò tí ó bá fẹ́ láti lọ iṣeto awoṣe aiyipada. -* python-multipart - Nílò tí ó bá fẹ́ láti ṣe àtìlẹ́yìn fún "àyẹ̀wò" fọọmu, pẹ̀lú `request.form()`. +* python-multipart - Nílò tí ó bá fẹ́ láti ṣe àtìlẹ́yìn fún "àyẹ̀wò" fọọmu, pẹ̀lú `request.form()`. * itsdangerous - Nílò fún àtìlẹ́yìn `SessionMiddleware`. * pyyaml - Nílò fún àtìlẹ́yìn Starlette's `SchemaGenerator` (ó ṣe ṣe kí ó má nílò rẹ̀ fún FastAPI). -* ujson - Nílò tí ó bá fẹ́ láti lọ `UJSONResponse`. Èyí tí FastAPI / Starlette ń lò: * uvicorn - Fún olupin tí yóò sẹ́ àmúyẹ àti tí yóò ṣe ìpèsè fún iṣẹ́ rẹ tàbí ohun èlò rẹ. * orjson - Nílò tí ó bá fẹ́ láti lọ `ORJSONResponse`. +* ujson - Nílò tí ó bá fẹ́ láti lọ `UJSONResponse`. Ó lè fi gbogbo àwọn wọ̀nyí sórí ẹrọ pẹ̀lú `pip install "fastapi[all]"`. diff --git a/docs/zh-hant/docs/about/index.md b/docs/zh-hant/docs/about/index.md new file mode 100644 index 000000000..5dcee68f2 --- /dev/null +++ b/docs/zh-hant/docs/about/index.md @@ -0,0 +1,3 @@ +# 關於 FastAPI + +關於 FastAPI、其設計、靈感來源等更多資訊。 🤓 diff --git a/docs/zh-hant/docs/async.md b/docs/zh-hant/docs/async.md new file mode 100644 index 000000000..6ab75d2ab --- /dev/null +++ b/docs/zh-hant/docs/async.md @@ -0,0 +1,442 @@ +# 並行與 async / await + +有關*路徑操作函式*的 `async def` 語法的細節與非同步 (asynchronous) 程式碼、並行 (concurrency) 與平行 (parallelism) 的一些背景知識。 + +## 趕時間嗎? + +TL;DR: + +如果你正在使用要求你以 `await` 語法呼叫的第三方函式庫,例如: + +```Python +results = await some_library() +``` + +然後,使用 `async def` 宣告你的*路徑操作函式*: + + +```Python hl_lines="2" +@app.get('/') +async def read_results(): + results = await some_library() + return results +``` + +/// note | 注意 + +你只能在 `async def` 建立的函式內使用 `await`。 + +/// + +--- + +如果你使用的是第三方函式庫並且它需要與某些外部資源(例如資料庫、API、檔案系統等)進行通訊,但不支援 `await`(目前大多數資料庫函式庫都是這樣),在這種情況下,你可以像平常一樣使用 `def` 宣告*路徑操作函式*,如下所示: + +```Python hl_lines="2" +@app.get('/') +def results(): + results = some_library() + return results +``` + +--- + +如果你的應用程式不需要與外部資源進行任何通訊並等待其回應,請使用 `async def`。 + +--- + +如果你不確定該用哪個,直接用 `def` 就好。 + +--- + +**注意**:你可以在*路徑操作函式*中混合使用 `def` 和 `async def` ,並使用最適合你需求的方式來定義每個函式。FastAPI 會幫你做正確的處理。 + +無論如何,在上述哪種情況下,FastAPI 仍將以非同步方式運行,並且速度非常快。 + +但透過遵循上述步驟,它將能進行一些效能最佳化。 + +## 技術細節 + +現代版本的 Python 支援使用 **「協程」** 的 **`async` 和 `await`** 語法來寫 **「非同步程式碼」**。 + +接下來我們逐一介紹: + +* **非同步程式碼** +* **`async` 和 `await`** +* **協程** + +## 非同步程式碼 + +非同步程式碼僅意味著程式語言 💬 有辦法告訴電腦/程式 🤖 在程式碼中的某個點,它 🤖 需要等待某些事情完成。讓我們假設這些事情被稱為「慢速檔案」📝。 + +因此,在等待「慢速檔案」📝 完成的這段時間,電腦可以去處理一些其他工作。 + +接著程式 🤖 會在有空檔時回來查看是否有等待的工作已經完成,並執行必要的後續操作。 + +接下來,它 🤖 完成第一個工作(例如我們的「慢速檔案」📝)並繼續執行相關的所有操作。 +這個「等待其他事情」通常指的是一些相對較慢的(與處理器和 RAM 記憶體的速度相比)的 I/O 操作,比如說: + +* 透過網路傳送來自用戶端的資料 +* 從網路接收來自用戶端的資料 +* 從磁碟讀取檔案內容 +* 將內容寫入磁碟 +* 遠端 API 操作 +* 資料庫操作 +* 資料庫查詢 +* 等等 + +由於大部分的執行時間都消耗在等待 I/O 操作上,因此這些操作被稱為 "I/O 密集型" 操作。 + +之所以稱為「非同步」,是因為電腦/程式不需要與那些耗時的任務「同步」,等待任務完成的精確時間,然後才能取得結果並繼續工作。 + +相反地,非同步系統在任務完成後,可以讓任務稍微等一下(幾微秒),等待電腦/程式完成手頭上的其他工作,然後再回來取得結果繼續進行。 + +相對於「非同步」(asynchronous),「同步」(synchronous)也常被稱作「順序性」(sequential),因為電腦/程式會依序執行所有步驟,即便這些步驟涉及等待,才會切換到其他任務。 + +### 並行與漢堡 + +上述非同步程式碼的概念有時也被稱為「並行」,它不同於「平行」。 + +並行和平行都與 "不同的事情或多或少同時發生" 有關。 + +但並行和平行之間的細節是完全不同的。 + +為了理解差異,請想像以下有關漢堡的故事: + +### 並行漢堡 + +你和你的戀人去速食店,排隊等候時,收銀員正在幫排在你前面的人點餐。😍 + + + +輪到你了,你給你與你的戀人點了兩個豪華漢堡。🍔🍔 + + + +收銀員通知廚房準備你的漢堡(儘管他們還在為前面其他顧客準備食物)。 + + + +之後你完成付款。💸 + +收銀員給你一個號碼牌。 + + + +在等待漢堡的同時,你可以與戀人選一張桌子,然後坐下來聊很長一段時間(因為漢堡十分豪華,準備特別費工。) + +這段時間,你還能欣賞你的戀人有多麼的可愛、聰明與迷人。✨😍✨ + + + +當你和戀人邊聊天邊等待時,你會不時地查看櫃檯上的顯示的號碼,確認是否已經輪到你了。 + +然後在某個時刻,終於輪到你了。你走到櫃檯,拿了漢堡,然後回到桌子上。 + + + +你和戀人享用這頓大餐,整個過程十分開心✨ + + + +/// info + +漂亮的插畫來自 Ketrina Thompson. 🎨 + +/// + +--- + +想像你是故事中的電腦或程式 🤖。 + +當你排隊時,你在放空😴,等待輪到你,沒有做任何「生產性」的事情。但這沒關係,因為收銀員只是接單(而不是準備食物),所以排隊速度很快。 + +然後,當輪到你時,你開始做真正「有生產力」的工作,處理菜單,決定你想要什麼,替戀人選擇餐點,付款,確認你給了正確的帳單或信用卡,檢查你是否被正確收費,確認訂單中的項目是否正確等等。 + +但是,即使你還沒有拿到漢堡,你與收銀員的工作已經「暫停」了 ⏸,因為你必須等待 🕙 漢堡準備好。 + +但當你離開櫃檯,坐到桌子旁,拿著屬於你的號碼等待時,你可以把注意力 🔀 轉移到戀人身上,並開始「工作」⏯ 🤓——也就是和戀人調情 😍。這時你又開始做一些非常「有生產力」的事情。 + +接著,收銀員 💁 將你的號碼顯示在櫃檯螢幕上,並告訴你「漢堡已經做好了」。但你不會瘋狂地立刻跳起來,因為顯示的號碼變成了你的。你知道沒有人會搶走你的漢堡,因為你有自己的號碼,他們也有他們的號碼。 + +所以你會等戀人講完故事(完成當前的工作 ⏯/正在進行的任務 🤓),然後微笑著溫柔地說你要去拿漢堡了 ⏸。 + +然後你走向櫃檯 🔀,回到已經完成的最初任務 ⏯,拿起漢堡,說聲謝謝,並帶回桌上。這就結束了與櫃檯的互動步驟/任務 ⏹,接下來會產生一個新的任務,「吃漢堡」 🔀 ⏯,而先前的「拿漢堡」任務已經完成了 ⏹。 + +### 平行漢堡 + +現在,讓我們來想像這裡不是「並行漢堡」,而是「平行漢堡」。 + +你和戀人一起去吃平行的速食餐。 + +你們站在隊伍中,前面有幾位(假設有 8 位)既是收銀員又是廚師的員工,他們同時接單並準備餐點。 + +所有排在你前面的人都在等著他們的漢堡準備好後才會離開櫃檯,因為每位收銀員在接完單後,馬上會去準備漢堡,然後才回來處理下一個訂單。 + + + +終於輪到你了,你為你和你的戀人點了兩個非常豪華的漢堡。 + +你付款了 💸。 + + + +收銀員走進廚房準備食物。 + +你站在櫃檯前等待 🕙,以免其他人先拿走你的漢堡,因為這裡沒有號碼牌系統。 + + + +由於你和戀人都忙著不讓別人搶走你的漢堡,等漢堡準備好時,你根本無法專心和戀人互動。😞 + +這是「同步」(synchronous)工作,你和收銀員/廚師 👨‍🍳 是「同步化」的。你必須等到 🕙 收銀員/廚師 👨‍🍳 完成漢堡並交給你的那一刻,否則別人可能會拿走你的餐點。 + + + +最終,經過長時間的等待 🕙,收銀員/廚師 👨‍🍳 拿著漢堡回來了。 + + + +你拿著漢堡,和你的戀人回到餐桌。 + +你們僅僅是吃完漢堡,然後就結束了。⏹ + + + +整個過程中沒有太多的談情說愛,因為大部分時間 🕙 都花在櫃檯前等待。😞 + +/// info + +漂亮的插畫來自 Ketrina Thompson. 🎨 + +/// + +--- + +在這個平行漢堡的情境下,你是一個程式 🤖 且有兩個處理器(你和戀人),兩者都在等待 🕙 並專注於等待櫃檯上的餐點 🕙,等待的時間非常長。 + +這家速食店有 8 個處理器(收銀員/廚師)。而並行漢堡店可能只有 2 個處理器(一位收銀員和一位廚師)。 + +儘管如此,最終的體驗並不是最理想的。😞 + +--- + +這是與漢堡類似的故事。🍔 + +一個更「現實」的例子,想像一間銀行。 + +直到最近,大多數銀行都有多位出納員 👨‍💼👨‍💼👨‍💼👨‍💼,以及一條長長的隊伍 🕙🕙🕙🕙🕙🕙🕙🕙。 + +所有的出納員都在一個接一個地滿足每位客戶的所有需求 👨‍💼⏯。 + +你必須長時間排隊 🕙,不然就會失去機會。 + +所以,你不會想帶你的戀人 😍 一起去銀行辦事 🏦。 + +### 漢堡結論 + +在「和戀人一起吃速食漢堡」的這個場景中,由於有大量的等待 🕙,使用並行系統 ⏸🔀⏯ 更有意義。 + +這也是大多數 Web 應用的情況。 + +許多用戶正在使用你的應用程式,而你的伺服器則在等待 🕙 這些用戶不那麼穩定的網路來傳送請求。 + +接著,再次等待 🕙 回應。 + +這種「等待」 🕙 通常以微秒來衡量,但累加起來,最終還是花費了很多等待時間。 + +這就是為什麼對於 Web API 來說,使用非同步程式碼 ⏸🔀⏯ 是非常有意義的。 + +這種類型的非同步性正是 NodeJS 成功的原因(儘管 NodeJS 不是平行的),這也是 Go 語言作為程式語言的一個強大優勢。 + +這與 **FastAPI** 所能提供的性能水平相同。 + +你可以同時利用並行性和平行性,進一步提升效能,這比大多數已測試的 NodeJS 框架都更快,並且與 Go 語言相當,而 Go 是一種更接近 C 的編譯語言(感謝 Starlette)。 + +### 並行比平行更好嗎? + +不是的!這不是故事的本意。 + +並行與平行不同。並行在某些 **特定** 的需要大量等待的情境下表現更好。正因如此,並行在 Web 應用程式開發中通常比平行更有優勢。但並不是所有情境都如此。 + +因此,為了平衡報導,想像下面這個短故事 + +> 你需要打掃一間又大又髒的房子。 + +*是的,這就是全部的故事。* + +--- + +這裡沒有任何需要等待 🕙 的地方,只需要在房子的多個地方進行大量的工作。 + +你可以像漢堡的例子那樣輪流進行,先打掃客廳,再打掃廚房,但由於你不需要等待 🕙 任何事情,只需要持續地打掃,輪流並不會影響任何結果。 + +無論輪流執行與否(並行),你都需要相同的工時完成任務,同時需要執行相同工作量。 + +但是,在這種情境下,如果你可以邀請8位前收銀員/廚師(現在是清潔工)來幫忙,每個人(加上你)負責房子的某個區域,這樣你就可以 **平行** 地更快完成工作。 + +在這個場景中,每個清潔工(包括你)都是一個處理器,完成工作的一部分。 + +由於大多數的執行時間都花在實際的工作上(而不是等待),而電腦中的工作由 CPU 完成,因此這些問題被稱為「CPU 密集型」。 + +--- + +常見的 CPU 密集型操作範例包括那些需要進行複雜數學計算的任務。 + +例如: + +* **音訊**或**圖像處理**; +* **電腦視覺**:一張圖片由數百萬個像素組成,每個像素有 3 個值/顏色,處理這些像素通常需要同時進行大量計算; +* **機器學習**: 通常需要大量的「矩陣」和「向量」運算。想像一個包含數字的巨大電子表格,並所有的數字同時相乘; +* **深度學習**: 這是機器學習的子領域,同樣適用。只不過這不僅僅是一張數字表格,而是大量的數據集合,並且在很多情況下,你會使用特殊的處理器來構建或使用這些模型。 + +### 並行 + 平行: Web + 機器學習 + +使用 **FastAPI**,你可以利用並行的優勢,這在 Web 開發中非常常見(這也是 NodeJS 的最大吸引力)。 + +但你也可以利用平行與多行程 (multiprocessing)(讓多個行程同時運行) 的優勢來處理機器學習系統中的 **CPU 密集型**工作。 + +這一點,再加上 Python 是 **資料科學**、機器學習,尤其是深度學習的主要語言,讓 **FastAPI** 成為資料科學/機器學習 Web API 和應用程式(以及許多其他應用程式)的絕佳選擇。 + +想了解如何在生產環境中實現這種平行性,請參見 [部屬](deployment/index.md){.internal-link target=_blank}。 + +## `async` 和 `await` + +現代 Python 版本提供一種非常直觀的方式定義非同步程式碼。這使得它看起來就像正常的「順序」程式碼,並在適當的時機「等待」。 + +當某個操作需要等待才能回傳結果,並且支援這些新的 Python 特性時,你可以像這樣編寫程式碼: + +```Python +burgers = await get_burgers(2) +``` + +這裡的關鍵是 `await`。它告訴 Python 必須等待 ⏸ `get_burgers(2)` 完成它的工作 🕙, 然後將結果儲存在 `burgers` 中。如此,Python 就可以在此期間去處理其他事情 🔀 ⏯ (例如接收另一個請求)。 + +要讓 `await` 運作,它必須位於支持非同步功能的函式內。為此,只需使用 `async def` 宣告函式: + +```Python hl_lines="1" +async def get_burgers(number: int): + # Do some asynchronous stuff to create the burgers + return burgers +``` + +...而不是 `def`: + +```Python hl_lines="2" +# This is not asynchronous +def get_sequential_burgers(number: int): + # Do some sequential stuff to create the burgers + return burgers +``` + +使用 `async def`,Python Python 知道在該函式內需要注意 `await`,並且它可以「暫停」 ⏸ 執行該函式,然後執行其他任務 🔀 後回來。 + +當你想要呼叫 `async def` 函式時,必須使用「await」。因此,這樣寫將無法運行: + +```Python +# This won't work, because get_burgers was defined with: async def +burgers = get_burgers(2) +``` + +--- + +如果你正在使用某個函式庫,它告訴你可以使用 `await` 呼叫它,那麼你需要用 `async def` 定義*路徑操作函式*,如: + +```Python hl_lines="2-3" +@app.get('/burgers') +async def read_burgers(): + burgers = await get_burgers(2) + return burgers +``` + +### 更多技術細節 + +你可能已經注意到,`await` 只能在 `async def` 定義的函式內使用。 + +但同時,使用 `async def` 定義的函式本身也必須被「等待」。所以,帶有 `async def` 函式只能在其他使用 `async def` 定義的函式內呼叫。 + +那麼,這就像「先有雞還是先有蛋」的問題,要如何呼叫第一個 `async` 函式呢? + +如果你使用 FastAPI,無需擔心這個問題,因為「第一個」函式將是你的*路徑操作函式*,FastAPI 會知道如何正確處理這個問題。 + +但如果你想在沒有 FastAPI 的情況下使用 `async` / `await`,你也可以這樣做。 + +### 編寫自己的非同步程式碼 + +Starlette (和 **FastAPI**) 是基於 AnyIO 實作的,這使得它們與 Python 標準函式庫相容 asyncioTrio。 + +特別是,你可以直接使用 AnyIO 來處理更複雜的並行使用案例,這些案例需要你在自己的程式碼中使用更高階的模式。 + +即使你不使用 **FastAPI**,你也可以使用 AnyIO 來撰寫自己的非同步應用程式,並獲得高相容性及一些好處(例如結構化並行)。 + +### 其他形式的非同步程式碼 + +使用 `async` 和 `await` 的風格在語言中相對較新。 + +但它使處理異步程式碼變得更加容易。 + +相同的語法(或幾乎相同的語法)最近也被包含在現代 JavaScript(無論是瀏覽器還是 NodeJS)中。 + +但在此之前,處理異步程式碼要更加複雜和困難。 + +在較舊的 Python 版本中,你可能會使用多執行緒或 Gevent。但這些程式碼要更難以理解、調試和思考。 + +在較舊的 NodeJS / 瀏覽器 JavaScript 中,你會使用「回呼」,這可能會導致回呼地獄。 + +## 協程 + +**協程** 只是 `async def` 函式所回傳的非常特殊的事物名稱。Python 知道它是一個類似函式的東西,可以啟動它,並且在某個時刻它會結束,但它也可能在內部暫停 ⏸,只要遇到 `await`。 + +這種使用 `async` 和 `await` 的非同步程式碼功能通常被概括為「協程」。這與 Go 語言的主要特性「Goroutines」相似。 + +## 結論 + +讓我們再次回顧之前的句子: + +> 現代版本的 Python 支持使用 **"協程"** 的 **`async` 和 `await`** 語法來寫 **"非同步程式碼"**。 + +現在應該能明白其含意了。✨ + +這些就是驅動 FastAPI(通過 Starlette)運作的原理,也讓它擁有如此驚人的效能。 + +## 非常技術性的細節 + +/// warning + +你大概可以跳過這段。 + +這裡是有關 FastAPI 內部技術細節。 + +如果你有相當多的技術背景(例如協程、執行緒、阻塞等),並且對 FastAPI 如何處理 `async def` 與常規 `def` 感到好奇,請繼續閱讀。 + +/// + +### 路徑操作函数 + +當你使用 `def` 而不是 `async def` 宣告*路徑操作函式*時,該函式會在外部的執行緒池(threadpool)中執行,然後等待結果,而不是直接呼叫(因為這樣會阻塞伺服器)。 + +如果你來自於其他不以這種方式運作的非同步框架,而且你習慣於使用普通的 `def` 定義僅進行簡單計算的*路徑操作函式*,目的是獲得微小的性能增益(大約 100 奈秒),請注意,在 FastAPI 中,效果會完全相反。在這些情況下,最好使用 `async def`除非你的*路徑操作函式*執行阻塞的 I/O 的程式碼。 + +不過,在這兩種情況下,**FastAPI** [仍然很快](index.md#_11){.internal-link target=_blank}至少與你之前的框架相當(或者更快)。 + +### 依賴項(Dependencies) + +同樣適用於[依賴項](tutorial/dependencies/index.md){.internal-link target=_blank}。如果依賴項是一個標準的 `def` 函式,而不是 `async def`,那麼它在外部的執行緒池被運行。 + +### 子依賴項 + +你可以擁有多個相互依賴的依賴項和[子依賴項](tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} (作為函式定義的參數),其中一些可能是用 `async def` 宣告,也可能是用 `def` 宣告。它們仍然可以正常運作,用 `def` 定義的那些將會在外部的執行緒中呼叫(來自執行緒池),而不是被「等待」。 + +### 其他輔助函式 + +你可以直接呼叫任何使用 `def` 或 `async def` 建立的其他輔助函式,FastAPI 不會影響你呼叫它們的方式。 + +這與 FastAPI 為你呼叫*路徑操作函式*和依賴項的邏輯有所不同。 + +如果你的輔助函式是用 `def` 宣告的,它將會被直接呼叫(按照你在程式碼中撰寫的方式),而不是在執行緒池中。如果該函式是用 `async def` 宣告,那麼你在呼叫時應該使用 `await` 等待其結果。 + +--- + +再一次強調,這些都是非常技術性的細節,如果你特地在尋找這些資訊,這些內容可能會對你有幫助。 + +否則,只需遵循上面提到的指引即可:趕時間嗎?. diff --git a/docs/zh-hant/docs/benchmarks.md b/docs/zh-hant/docs/benchmarks.md new file mode 100644 index 000000000..c59e8e71c --- /dev/null +++ b/docs/zh-hant/docs/benchmarks.md @@ -0,0 +1,34 @@ +# 基準測試 + +由第三方機構 TechEmpower 的基準測試表明在 Uvicorn 下運行的 **FastAPI** 應用程式是 最快的 Python 可用框架之一,僅次於 Starlette 和 Uvicorn 本身(於 FastAPI 內部使用)。 + +但是在查看基準得分和對比時,請注意以下幾點。 + +## 基準測試和速度 + +當你查看基準測試時,時常會見到幾個不同類型的工具被同時進行測試。 + +具體來說,是將 Uvicorn、Starlette 和 FastAPI 同時進行比較(以及許多其他工具)。 + +該工具解決的問題越簡單,其效能就越好。而且大多數基準測試不會測試該工具提供的附加功能。 + +層次結構如下: + +* **Uvicorn**:ASGI 伺服器 + * **Starlette**:(使用 Uvicorn)一個網頁微框架 + * **FastAPI**:(使用 Starlette)一個 API 微框架,具有用於建立 API 的多個附加功能、資料驗證等。 + +* **Uvicorn**: + * 具有最佳效能,因為除了伺服器本身之外,它沒有太多額外的程式碼。 + * 你不會直接在 Uvicorn 中編寫應用程式。這意味著你的程式碼必須或多或少地包含 Starlette(或 **FastAPI**)提供的所有程式碼。如果你這樣做,你的最終應用程式將具有與使用框架相同的開銷並最大限度地減少應用程式程式碼和錯誤。 + * 如果你要比較 Uvicorn,請將其與 Daphne、Hypercorn、uWSGI 等應用程式伺服器進行比較。 +* **Starlette**: + * 繼 Uvicorn 之後的次佳表現。事實上,Starlette 使用 Uvicorn 來運行。因此它將可能只透過執行更多程式碼而變得比 Uvicorn「慢」。 + * 但它為你提供了建立簡單網頁應用程式的工具,以及基於路徑的路由等。 + * 如果你要比較 Starlette,請將其與 Sanic、Flask、Django 等網頁框架(或微框架)進行比較。 +* **FastAPI**: + * 就像 Starlette 使用 Uvicorn 並不能比它更快一樣, **FastAPI** 使用 Starlette,所以它不能比它更快。 + * FastAPI 在 Starlette 基礎之上提供了更多功能。包含建構 API 時所需要的功能,例如資料驗證和序列化。FastAPI 可以幫助你自動產生 API 文件,(應用程式啟動時將會自動生成文件,所以不會增加應用程式運行時的開銷)。 + * 如果你沒有使用 FastAPI 而是直接使用 Starlette(或其他工具,如 Sanic、Flask、Responder 等),你將必須自行實現所有資料驗證和序列化。因此,你的最終應用程式仍然具有與使用 FastAPI 建置相同的開銷。在許多情況下,這種資料驗證和序列化是應用程式中編寫最大量的程式碼。 + * 因此透過使用 FastAPI,你可以節省開發時間、錯誤與程式碼數量,並且相比不使用 FastAPI 你很大可能會獲得相同或更好的效能(因為那樣你必須在程式碼中實現所有相同的功能)。 + * 如果你要與 FastAPI 比較,請將其與能夠提供資料驗證、序列化和文件的網頁應用程式框架(或工具集)進行比較,例如 Flask-apispec、NestJS、Molten 等框架。 diff --git a/docs/zh-hant/docs/deployment/cloud.md b/docs/zh-hant/docs/deployment/cloud.md new file mode 100644 index 000000000..29ebe3ff5 --- /dev/null +++ b/docs/zh-hant/docs/deployment/cloud.md @@ -0,0 +1,17 @@ +# 在雲端部署 FastAPI + +你幾乎可以使用**任何雲端供應商**來部署你的 FastAPI 應用程式。 + +在大多數情況下,主要的雲端供應商都有部署 FastAPI 的指南。 + +## 雲端供應商 - 贊助商 + +一些雲端供應商 ✨ [**贊助 FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨,這確保了 FastAPI 及其**生態系統**持續健康地**發展**。 + +這也展現了他們對 FastAPI 和其**社群**(包括你)的真正承諾,他們不僅希望為你提供**優質的服務**,還希望確保你擁有一個**良好且健康的框架**:FastAPI。🙇 + +你可能會想嘗試他們的服務,以下有他們的指南: + +* Platform.sh +* Porter +* Coherence diff --git a/docs/zh-hant/docs/deployment/index.md b/docs/zh-hant/docs/deployment/index.md new file mode 100644 index 000000000..1726562b4 --- /dev/null +++ b/docs/zh-hant/docs/deployment/index.md @@ -0,0 +1,21 @@ +# 部署 + +部署 **FastAPI** 應用程式相對容易。 + +## 部署是什麼意思 + +**部署**應用程式指的是執行一系列必要的步驟,使其能夠**讓使用者存取和使用**。 + +對於一個 **Web API**,部署通常涉及將其放置在**遠端伺服器**上,並使用性能優良且穩定的**伺服器程式**,確保使用者能夠高效、無中斷地存取應用程式,且不會遇到問題。 + +這與**開發**階段形成鮮明對比,在**開發**階段,你會不斷更改程式碼、破壞程式碼、修復程式碼,然後停止和重新啟動伺服器等。 + +## 部署策略 + +根據你的使用場景和使用工具,有多種方法可以實現此目的。 + +你可以使用一些工具自行**部署伺服器**,你也可以使用能為你完成部分工作的**雲端服務**,或其他可能的選項。 + +我將向你展示在部署 **FastAPI** 應用程式時你可能應該記住的一些主要概念(儘管其中大部分適用於任何其他類型的 Web 應用程式)。 + +在接下來的部分中,你將看到更多需要記住的細節以及一些技巧。 ✨ diff --git a/docs/zh-hant/docs/environment-variables.md b/docs/zh-hant/docs/environment-variables.md new file mode 100644 index 000000000..a1598fc01 --- /dev/null +++ b/docs/zh-hant/docs/environment-variables.md @@ -0,0 +1,298 @@ +# 環境變數 + +/// tip + +如果你已經知道什麼是「環境變數」並且知道如何使用它們,你可以放心跳過這一部分。 + +/// + +環境變數(也稱為「**env var**」)是一個獨立於 Python 程式碼**之外**的變數,它存在於**作業系統**中,可以被你的 Python 程式碼(或其他程式)讀取。 + +環境變數對於處理應用程式**設定**(作為 Python **安裝**的一部分等方面)非常有用。 + +## 建立和使用環境變數 + +你在 **shell(終端機)**中就可以**建立**和使用環境變數,並不需要用到 Python: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// 你可以使用以下指令建立一個名為 MY_NAME 的環境變數 +$ export MY_NAME="Wade Wilson" + +// 然後,你可以在其他程式中使用它,例如 +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// 建立一個名為 MY_NAME 的環境變數 +$ $Env:MY_NAME = "Wade Wilson" + +// 在其他程式中使用它,例如 +$ echo "Hello $Env:MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +## 在 Python 中讀取環境變數 + +你也可以在 Python **之外**的終端機中建立環境變數(或使用其他方法),然後在 Python 中**讀取**它們。 + +例如,你可以建立一個名為 `main.py` 的檔案,其中包含以下內容: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// tip + +第二個參數是 `os.getenv()` 的預設回傳值。 + +如果沒有提供,預設值為 `None`,這裡我們提供 `"World"` 作為預設值。 + +/// + +然後你可以呼叫這個 Python 程式: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// 這裡我們還沒有設定環境變數 +$ python main.py + +// 因為我們沒有設定環境變數,所以我們得到的是預設值 + +Hello World from Python + +// 但是如果我們事先建立過一個環境變數 +$ export MY_NAME="Wade Wilson" + +// 然後再次呼叫程式 +$ python main.py + +// 現在就可以讀取到環境變數了 + +Hello Wade Wilson from Python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// 這裡我們還沒有設定環境變數 +$ python main.py + +// 因為我們沒有設定環境變數,所以我們得到的是預設值 + +Hello World from Python + +// 但是如果我們事先建立過一個環境變數 +$ $Env:MY_NAME = "Wade Wilson" + +// 然後再次呼叫程式 +$ python main.py + +// 現在就可以讀取到環境變數了 + +Hello Wade Wilson from Python +``` + +
+ +//// + +由於環境變數可以在程式碼之外設定,但可以被程式碼讀取,並且不必與其他檔案一起儲存(提交到 `git`),因此通常用於配置或**設定**。 + +你還可以為**特定的程式呼叫**建立特定的環境變數,該環境變數僅對該程式可用,且僅在其執行期間有效。 + +要實現這一點,只需在同一行內(程式本身之前)建立它: + +
+ +```console +// 在這個程式呼叫的同一行中建立一個名為 MY_NAME 的環境變數 +$ MY_NAME="Wade Wilson" python main.py + +// 現在就可以讀取到環境變數了 + +Hello Wade Wilson from Python + +// 在此之後這個環境變數將不再存在 +$ python main.py + +Hello World from Python +``` + +
+ +/// tip + +你可以在 The Twelve-Factor App: 配置中了解更多資訊。 + +/// + +## 型別和驗證 + +這些環境變數只能處理**文字字串**,因為它們是位於 Python 範疇之外的,必須與其他程式和作業系統的其餘部分相容(甚至與不同的作業系統相容,如 Linux、Windows、macOS)。 + +這意味著從環境變數中讀取的**任何值**在 Python 中都將是一個 `str`,任何型別轉換或驗證都必須在程式碼中完成。 + +你將在[進階使用者指南 - 設定和環境變數](./advanced/settings.md)中了解更多關於使用環境變數處理**應用程式設定**的資訊。 + +## `PATH` 環境變數 + +有一個**特殊的**環境變數稱為 **`PATH`**,作業系統(Linux、macOS、Windows)用它來查找要執行的程式。 + +`PATH` 變數的值是一個長字串,由 Linux 和 macOS 上的冒號 `:` 分隔的目錄組成,而在 Windows 上則是由分號 `;` 分隔的。 + +例如,`PATH` 環境變數可能如下所示: + +//// tab | Linux, macOS + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +這意味著系統應該在以下目錄中查找程式: + +- `/usr/local/bin` +- `/usr/bin` +- `/bin` +- `/usr/sbin` +- `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32 +``` + +這意味著系統應該在以下目錄中查找程式: + +- `C:\Program Files\Python312\Scripts` +- `C:\Program Files\Python312` +- `C:\Windows\System32` + +//// + +當你在終端機中輸入一個**指令**時,作業系統會在 `PATH` 環境變數中列出的**每個目錄**中**查找**程式。 + +例如,當你在終端機中輸入 `python` 時,作業系統會在該列表中的**第一個目錄**中查找名為 `python` 的程式。 + +如果找到了,那麼作業系統將**使用它**;否則,作業系統會繼續在**其他目錄**中查找。 + +### 安裝 Python 並更新 `PATH` + +安裝 Python 時,可能會詢問你是否要更新 `PATH` 環境變數。 + +//// tab | Linux, macOS + +假設你安裝了 Python,並將其安裝在目錄 `/opt/custompython/bin` 中。 + +如果你選擇更新 `PATH` 環境變數,那麼安裝程式會將 `/opt/custompython/bin` 加入到 `PATH` 環境變數中。 + +它看起來大致會是這樣: + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin +``` + +如此一來,當你在終端機輸入 `python` 時,系統會在 `/opt/custompython/bin` 中找到 Python 程式(最後一個目錄)並使用它。 + +//// + +//// tab | Windows + +假設你安裝了 Python,並將其安裝在目錄 `C:\opt\custompython\bin` 中。 + +如果你選擇更新 `PATH` 環境變數(在 Python 安裝程式中,這個選項是名為 `Add Python x.xx to PATH` 的勾選框——譯者註),那麼安裝程式會將 `C:\opt\custompython\bin` 加入到 `PATH` 環境變數中。 + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin +``` + +如此一來,當你在終端機輸入 `python` 時,系統會在 `C:\opt\custompython\bin` 中找到 Python 程式(最後一個目錄)並使用它。 + +//// + +因此,如果你輸入: + +
+ +```console +$ python +``` + +
+ +//// tab | Linux, macOS + +系統會在 `/opt/custompython/bin` 中**找到** `python` 程式並執行它。 + +這大致等同於輸入以下指令: + +
+ +```console +$ /opt/custompython/bin/python +``` + +
+ +//// + +//// tab | Windows + +系統會在 `C:\opt\custompython\bin\python` 中**找到** `python` 程式並執行它。 + +這大致等同於輸入以下指令: + +
+ +```console +$ C:\opt\custompython\bin\python +``` + +
+ +//// + +當學習[虛擬環境](virtual-environments.md)時,這些資訊將會很有用。 + +## 結論 + +透過這個教學,你應該對**環境變數**是什麼以及如何在 Python 中使用它們有了基本的了解。 + +你也可以在環境變數 - 維基百科 (Wikipedia for Environment Variable) 中了解更多關於它們的資訊。 + +在許多情況下,環境變數的用途和適用性可能不會立刻顯現。但是在開發過程中,它們會在許多不同的場景中出現,因此瞭解它們是非常必要的。 + +例如,你在接下來的[虛擬環境](virtual-environments.md)章節中將需要這些資訊。 diff --git a/docs/zh-hant/docs/fastapi-cli.md b/docs/zh-hant/docs/fastapi-cli.md new file mode 100644 index 000000000..3c644ce46 --- /dev/null +++ b/docs/zh-hant/docs/fastapi-cli.md @@ -0,0 +1,83 @@ +# FastAPI CLI + +**FastAPI CLI** 是一個命令列程式,能用來運行你的 FastAPI 應用程式、管理你的 FastAPI 專案等。 + +當你安裝 FastAPI(例如使用 `pip install "fastapi[standard]"`),它會包含一個叫做 `fastapi-cli` 的套件,這個套件提供了 `fastapi` 命令。 + +要運行你的 FastAPI 應用程式來進行開發,你可以使用 `fastapi dev` 命令: + +
+ +```console +$ fastapi dev main.py +INFO Using path main.py +INFO Resolved absolute path /home/user/code/awesomeapp/main.py +INFO Searching for package file structure from directories with __init__.py files +INFO Importing from /home/user/code/awesomeapp + + ╭─ Python module file ─╮ + │ │ + │ 🐍 main.py │ + │ │ + ╰──────────────────────╯ + +INFO Importing module main +INFO Found importable FastAPI app + + ╭─ Importable FastAPI app ─╮ + │ │ + │ from main import app │ + │ │ + ╰──────────────────────────╯ + +INFO Using import string main:app + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + fastapi run + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [2265862] using WatchFiles +INFO: Started server process [2265873] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +`fastapi` 命令列程式就是 **FastAPI CLI**。 + +FastAPI CLI 接收你的 Python 程式路徑(例如 `main.py`),並自動檢測 FastAPI 實例(通常命名為 `app`),確定正確的引入模組流程,然後運行該應用程式。 + +在生產環境,你應該使用 `fastapi run` 命令。 🚀 + +**FastAPI CLI** 內部使用了 Uvicorn,這是一個高效能、適合生產環境的 ASGI 伺服器。 😎 + +## `fastapi dev` + +執行 `fastapi dev` 會啟動開發模式。 + +預設情況下,**auto-reload** 功能是啟用的,當你對程式碼進行修改時,伺服器會自動重新載入。這會消耗較多資源,並且可能比禁用時更不穩定。因此,你應該只在開發環境中使用此功能。它也會在 IP 位址 `127.0.0.1` 上監聽,這是用於你的機器與自身通訊的 IP 位址(`localhost`)。 + +## `fastapi run` + +執行 `fastapi run` 會以生產模式啟動 FastAPI。 + +預設情況下,**auto-reload** 功能是禁用的。它也會在 IP 位址 `0.0.0.0` 上監聽,表示會監聽所有可用的 IP 地址,這樣任何能與該機器通訊的人都可以公開存取它。這通常是你在生產環境中運行應用程式的方式,例如在容器中運行時。 + +在大多數情況下,你會(也應該)有一個「終止代理」來處理 HTTPS,這取決於你如何部署你的應用程式,你的服務供應商可能會為你做這件事,或者你需要自己設置它。 + +/// tip + +你可以在[部署文件](deployment/index.md){.internal-link target=_blank}中了解更多相關資訊。 + +/// diff --git a/docs/zh-hant/docs/features.md b/docs/zh-hant/docs/features.md new file mode 100644 index 000000000..3a1392b51 --- /dev/null +++ b/docs/zh-hant/docs/features.md @@ -0,0 +1,207 @@ +# 特性 + +## FastAPI 特性 + +**FastAPI** 提供了以下内容: + +### 建立在開放標準的基礎上 + +* 使用 OpenAPI 來建立 API,包含路徑操作、參數、請求內文、安全性等聲明。 +* 使用 JSON Schema(因為 OpenAPI 本身就是基於 JSON Schema)自動生成資料模型文件。 +* 經過縝密的研究後圍繞這些標準進行設計,而不是事後在已有系統上附加的一層功能。 +* 這也讓我們在多種語言中可以使用自動**用戶端程式碼生成**。 + +### 能夠自動生成文件 + +FastAPI 能生成互動式 API 文件和探索性的 Web 使用者介面。由於該框架基於 OpenAPI,因此有多種選擇,預設提供了兩種。 + +* Swagger UI 提供互動式探索,讓你可以直接從瀏覽器呼叫並測試你的 API 。 + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* ReDoc 提供結構性的文件,讓你可以在瀏覽器中查看。 + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + + +### 現代 Python + +這一切都基於標準的 **Python 型別**宣告(感謝 Pydantic)。無需學習新的語法,只需使用標準的現代 Python。 + +如果你需要 2 分鐘來學習如何使用 Python 型別(即使你不使用 FastAPI),可以看看這個簡短的教學:[Python 型別](python-types.md){.internal-link target=_blank}。 + +如果你寫帶有 Python 型別的程式碼: + +```python +from datetime import date + +from pydantic import BaseModel + +# 宣告一個變數為 string +# 並在函式中獲得 editor support +def main(user_id: str): + return user_id + + +# 宣告一個 Pydantic model +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) +``` + + +/// info + +`**second_user_data` 意思是: + +將 `second_user_data` 字典直接作為 key-value 引數傳遞,等同於:`User(id=4, name="Mary", joined="2018-11-30")` + +/// + +### 多種編輯器支援 + +整個框架的設計是為了讓使用變得簡單且直觀,在開始開發之前,所有決策都在多個編輯器上進行了測試,以確保提供最佳的開發體驗。 + +在最近的 Python 開發者調查中,我們能看到 被使用最多的功能是 autocompletion,此功能可以預測將要輸入文字,並自動補齊。 + +整個 **FastAPI** 框架就是基於這一點,任何地方都可以進行自動補齊。 + +你幾乎不需要經常來回看文件。 + +在這裡,你的編輯器可能會這樣幫助你: + +* Visual Studio Code 中: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +* PyCharm 中: + +![editor support](https://fastapi.tiangolo.com/img/pycharm-completion.png) + +你將能進行程式碼補齊,這是在之前你可能曾認為不可能的事。例如,請求 JSON body(可能是巢狀的)中的鍵 `price`。 + +這樣比較不會輸錯鍵名,不用來回翻看文件,也不用來回滾動尋找你最後使用的 `username` 或者 `user_name`。 + + + +### 簡潔 + +FastAPI 為你提供了**預設值**,讓你不必在初期進行繁瑣的配置,一切都可以自動運作。如果你有更具體的需求,則可以進行調整和自定義, + +但在大多數情況下,你只需要直接使用預設值,就能順利完成 API 開發。 + +### 驗證 + +所有的驗證都由完善且強大的 **Pydantic** 處理。 + +* 驗證大部分(甚至所有?)的 Python **資料型別**,包括: + * JSON 物件 (`dict`)。 + * JSON 陣列 (`list`) 定義項目型別。 + * 字串 (`str`) 欄位,定義最小或最大長度。 + * 數字 (`int`, `float`) 與其最大值和最小值等。 + +* 驗證外來的型別,比如: + * URL + * Email + * UUID + + +### 安全性及身份驗證 + +FastAPI 已經整合了安全性和身份驗證的功能,但不會強制與特定的資料庫或資料模型進行綁定。 + +OpenAPI 中定義的安全模式,包括: + +* HTTP 基本認證。 +* **OAuth2**(也使用 **JWT tokens**)。在 [OAuth2 with JWT](tutorial/security/oauth2-jwt.md){.internal-link target=_blank} 查看教學。 +* API 密鑰,在: + * 標頭(Header) + * 查詢參數 + * Cookies,等等。 + +加上来自 Starlette(包括 **session cookie**)的所有安全特性。 + +所有的這些都是可重複使用的工具和套件,可以輕鬆與你的系統、資料儲存(Data Stores)、關聯式資料庫(RDBMS)以及非關聯式資料庫(NoSQL)等等整合。 + + +### 依賴注入(Dependency Injection) + +FastAPI 有一個使用簡單,但是非常強大的依賴注入系統。 + +* 依賴項甚至可以有自己的依賴,從而形成一個層級或**依賴圖**的結構。 +* 所有**自動化處理**都由框架完成。 +* 依賴項不僅能從請求中提取資料,還能**對 API 的路徑操作進行強化**,並自動生成文檔。 +* 即使是依賴項中定義的*路徑操作參數*,也會**自動進行驗證**。 +* 支持複雜的用戶身份驗證系統、**資料庫連接**等。 +* 不與資料庫、前端等進行強制綁定,但能輕鬆整合它們。 + + +### 無限制「擴充功能」 + +或者說,無需其他額外配置,直接導入並使用你所需要的程式碼。 + +任何整合都被設計得非常簡單易用(通過依賴注入),你只需用與*路徑操作*相同的結構和語法,用兩行程式碼就能為你的應用程式建立一個「擴充功能」。 + + +### 測試 + +* 100% 的測試覆蓋率。 +* 100% 的程式碼有型別註釋。 +* 已能夠在生產環境應用程式中使用。 + +## Starlette 特性 + +**FastAPI** 完全相容且基於 Starlette。所以,你有其他的 Starlette 程式碼也能正常運作。FastAPI 繼承了 Starlette 的所有功能,如果你已經知道或者使用過 Starlette,大部分的功能會以相同的方式運作。 + +通過 **FastAPI** 你可以獲得所有 **Starlette** 的特性(FastAPI 就像加強版的 Starlette): + +* 性能極其出色。它是 Python 可用的最快框架之一,和 **NodeJS** 及 **Go** 相當。 +* **支援 WebSocket**。 +* 能在行程內處理背景任務。 +* 支援啟動和關閉事件。 +* 有基於 HTTPX 的測試用戶端。 +* 支援 **CORS**、GZip、靜態檔案、串流回應。 +* 支援 **Session 和 Cookie** 。 +* 100% 測試覆蓋率。 +* 100% 型別註釋的程式碼庫。 + +## Pydantic 特性 + +**FastAPI** 完全相容且基於 Pydantic。所以,你有其他 Pydantic 程式碼也能正常工作。 + +相容包括基於 Pydantic 的外部函式庫, 例如用於資料庫的 ORMs, ODMs。 + +這也意味著在很多情況下,你可以把從請求中獲得的物件**直接傳到資料庫**,因為所有資料都會自動進行驗證。 + +反之亦然,在很多情況下,你也可以把從資料庫中獲取的物件**直接傳給客戶端**。 + +通過 **FastAPI** 你可以獲得所有 **Pydantic** 的特性(FastAPI 基於 Pydantic 做了所有的資料處理): + +* **更簡單**: + * 不需要學習新的 micro-language 來定義結構。 + * 如果你知道 Python 型別,你就知道如何使用 Pydantic。 +* 和你的 **IDE/linter/brain** 都能好好配合: + * 因為 Pydantic 的資料結構其實就是你自己定義的類別實例,所以自動補齊、linting、mypy 以及你的直覺都能很好地在經過驗證的資料上發揮作用。 +* 驗證**複雜結構**: + * 使用 Pydantic 模型時,你可以把資料結構分層設計,並且用 Python 的 `List` 和 `Dict` 等型別來定義。 + * 驗證器讓我們可以輕鬆地定義和檢查複雜的資料結構,並把它們轉換成 JSON Schema 進行記錄。 + * 你可以擁有深層**巢狀的 JSON** 物件,並對它們進行驗證和註釋。 +* **可擴展**: + * Pydantic 讓我們可以定義客製化的資料型別,或者你可以使用帶有 validator 裝飾器的方法來擴展模型中的驗證功能。 +* 100% 測試覆蓋率。 diff --git a/docs/zh-hant/docs/how-to/index.md b/docs/zh-hant/docs/how-to/index.md new file mode 100644 index 000000000..db740140d --- /dev/null +++ b/docs/zh-hant/docs/how-to/index.md @@ -0,0 +1,13 @@ +# 使用指南 - 範例集 + +在這裡,你將會看到**不同主題**的範例或「如何使用」的指南。 + +大多數這些想法都是**獨立**的,在大多數情況下,你只需要研究那些直接適用於**你的專案**的東西。 + +如果有些東西看起來很有趣且對你的專案很有用的話再去讀它,否則你可能可以跳過它們。 + +/// tip + +如果你想要以結構化的方式**學習 FastAPI**(推薦),請前往[教學 - 使用者指南](../tutorial/index.md){.internal-link target=_blank}逐章閱讀。 + +/// diff --git a/docs/zh-hant/docs/index.md b/docs/zh-hant/docs/index.md new file mode 100644 index 000000000..81d99ede4 --- /dev/null +++ b/docs/zh-hant/docs/index.md @@ -0,0 +1,468 @@ +

+ FastAPI +

+

+ FastAPI 框架,高效能,易於學習,快速開發,適用於生產環境 +

+

+ + Test + + + Coverage + + + Package version + + + Supported Python versions + +

+ +--- + +**文件**: https://fastapi.tiangolo.com + +**程式碼**: https://github.com/fastapi/fastapi + +--- + +FastAPI 是一個現代、快速(高效能)的 web 框架,用於 Python 並採用標準 Python 型別提示。 + +主要特點包含: + +- **快速**: 非常高的效能,可與 **NodeJS** 和 **Go** 效能相當 (歸功於 Starlette and Pydantic)。 [FastAPI 是最快的 Python web 框架之一](#performance)。 +- **極速開發**: 提高開發功能的速度約 200% 至 300%。 \* +- **更少的 Bug**: 減少約 40% 的人為(開發者)導致的錯誤。 \* +- **直覺**: 具有出色的編輯器支援,處處都有自動補全以減少偵錯時間。 +- **簡單**: 設計上易於使用和學習,大幅減少閱讀文件的時間。 +- **簡潔**: 最小化程式碼重複性。可以通過不同的參數聲明來實現更豐富的功能,和更少的錯誤。 +- **穩健**: 立即獲得生產級可用的程式碼,還有自動生成互動式文件。 +- **標準化**: 基於 (且完全相容於) OpenAPIs 的相關標準:OpenAPI(之前被稱為 Swagger)和JSON Schema。 + +\* 基於內部開發團隊在建立生產應用程式時的測試預估。 + +## 贊助 + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} + +{% endfor -%} +{%- for sponsor in sponsors.silver -%} + +{% endfor %} +{% endif %} + + + +其他贊助商 + +## 評價 + +"_[...] 近期大量的使用 **FastAPI**。 [...] 目前正在計畫在**微軟**團隊的**機器學習**服務中導入。其中一些正在整合到核心的 **Windows** 產品和一些 **Office** 產品。_" + +
Kabir Khan - Microsoft (ref)
+ +--- + +"_我們使用 **FastAPI** 來建立產生**預測**結果的 **REST** 伺服器。 [for Ludwig]_" + +
Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber (ref)
+ +--- + +"_**Netflix** 很榮幸地宣布開源**危機管理**協調框架: **Dispatch**! [是使用 **FastAPI** 建構]_" + +
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (ref)
+ +--- + +"_我對 **FastAPI** 興奮得不得了。它太有趣了!_" + +
Brian Okken - Python Bytes podcast host (ref)
+ +--- + +"_老實說,你建造的東西看起來非常堅固和精緻。在很多方面,這就是我想要的,看到有人建造它真的很鼓舞人心。_" + +
Timothy Crosley - Hug creator (ref)
+ +--- + +"_如果您想學習一種用於構建 REST API 的**現代框架**,不能錯過 **FastAPI** [...] 它非常快速、且易於使用和學習 [...]_" + +"_我們的 **APIs** 已經改用 **FastAPI** [...] 我想你會喜歡它 [...]_" + +
Ines Montani - Matthew Honnibal - Explosion AI 創辦人 - spaCy creators (ref) - (ref)
+ +--- + +"_如果有人想要建立一個生產環境的 Python API,我強烈推薦 **FastAPI**,它**設計精美**,**使用簡單**且**高度可擴充**,它已成為我們 API 優先開發策略中的**關鍵組件**,並且驅動了許多自動化服務,例如我們的 Virtual TAC Engineer。_" + +
Deon Pillsbury - Cisco (ref)
+ +--- + +## **Typer**,命令列中的 FastAPI + + + +如果你不是在開發網頁 API,而是正在開發一個在終端機中運行的命令列應用程式,不妨嘗試 **Typer**。 + +**Typer** 是 FastAPI 的小兄弟。他立志成為命令列的 **FastAPI**。 ⌨️ 🚀 + +## 安裝需求 + +FastAPI 是站在以下巨人的肩膀上: + +- Starlette 負責網頁的部分 +- Pydantic 負責資料的部分 + +## 安裝 + +
+ +```console +$ pip install fastapi + +---> 100% +``` + +
+ +你同時也會需要 ASGI 伺服器用於生產環境,像是 UvicornHypercorn。 + +
+ +```console +$ pip install "uvicorn[standard]" + +---> 100% +``` + +
+ +## 範例 + +### 建立 + +- 建立一個 python 檔案 `main.py`,並寫入以下程式碼: + +```Python +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@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} +``` + +
+或可以使用 async def... + +如果你的程式使用 `async` / `await`,請使用 `async def`: + +```Python hl_lines="9 14" +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +async def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +async def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +**注意**: + +如果你不知道是否會用到,可以查看 _"In a hurry?"_ 章節中,關於 `async` 和 `await` 的部分。 + +
+ +### 運行 + +使用以下指令運行伺服器: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [28720] +INFO: Started server process [28722] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +
+關於指令 uvicorn main:app --reload... + +該指令 `uvicorn main:app` 指的是: + +- `main`:`main.py` 檔案(一個 python 的 "模組")。 +- `app`:在 `main.py` 檔案中,使用 `app = FastAPI()` 建立的物件。 +- `--reload`:程式碼更改後會自動重新啟動,請僅在開發時使用此參數。 + +
+ +### 檢查 + +使用瀏覽器開啟 http://127.0.0.1:8000/items/5?q=somequery。 + +你將會看到以下的 JSON 回應: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +你已經建立了一個具有以下功能的 API: + +- 透過路徑 `/` 和 `/items/{item_id}` 接受 HTTP 請求。 +- 以上路經都接受 `GET` 請求(也被稱為 HTTP _方法_)。 +- 路徑 `/items/{item_id}` 有一個 `int` 型別的 `item_id` 參數。 +- 路徑 `/items/{item_id}` 有一個 `str` 型別的查詢參數 `q`。 + +### 互動式 API 文件 + +使用瀏覽器開啟 http://127.0.0.1:8000/docs。 + +你會看到自動生成的互動式 API 文件(由 Swagger UI 生成): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### ReDoc API 文件 + +使用瀏覽器開啟 http://127.0.0.1:8000/redoc。 + +你將看到 ReDoc 文件 (由 ReDoc 生成): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## 範例升級 + +現在繼續修改 `main.py` 檔案,來接收一個帶有 body 的 `PUT` 請求。 + +我們使用 Pydantic 來使用標準的 Python 型別聲明請求。 + +```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} +``` + +伺服器將自動重新載入(因為在上一步中,你向 `uvicorn` 指令添加了 `--reload` 的選項)。 + +### 互動式 API 文件升級 + +使用瀏覽器開啟 http://127.0.0.1:8000/docs。 + +- 互動式 API 文件會自動更新,並加入新的 body 請求: + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +- 點擊 "Try it out" 按鈕, 你可以填寫參數並直接與 API 互動: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) + +- 然後點擊 "Execute" 按鈕,使用者介面將會向 API 發送請求,並將結果顯示在螢幕上: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) + +### ReDoc API 文件升級 + +使用瀏覽器開啟 http://127.0.0.1:8000/redoc。 + +- ReDoc API 文件會自動更新,並加入新的參數和 body 請求: + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### 總結 + +總結來說, 你就像宣告函式的參數型別一樣,只宣告了一次請求參數和請求主體參數等型別。 + +你使用 Python 標準型別來完成聲明。 + +你不需要學習新的語法、類別、方法或函式庫等等。 + +只需要使用 **Python 以上的版本**。 + +舉個範例,比如宣告 int 的型別: + +```Python +item_id: int +``` + +或是一個更複雜的 `Item` 模型: + +```Python +item: Item +``` + +在進行一次宣告後,你將獲得: + +- 編輯器支援: + - 自動補全 + - 型別檢查 +- 資料驗證: + - 驗證失敗時自動生成清楚的錯誤訊息 + - 可驗證多層巢狀的 JSON 物件 +- 轉換輸入的資料: 轉換來自網路請求到 Python 資料型別。包含以下數據: + - JSON + - 路徑參數 + - 查詢參數 + - Cookies + - 請求標頭 + - 表單 + - 文件 +- 轉換輸出的資料: 轉換 Python 資料型別到網路傳輸的 JSON: + - 轉換 Python 型別 (`str`、 `int`、 `float`、 `bool`、 `list` 等) + - `datetime` 物件 + - `UUID` 物件 + - 數據模型 + - ...還有其他更多 +- 自動生成的 API 文件,包含 2 種不同的使用介面: + - Swagger UI + - ReDoc + +--- + +回到前面的的程式碼範例,**FastAPI** 還會: + +- 驗證 `GET` 和 `PUT` 請求路徑中是否包含 `item_id`。 +- 驗證 `GET` 和 `PUT` 請求中的 `item_id` 是否是 `int` 型別。 + - 如果驗證失敗,將會返回清楚有用的錯誤訊息。 +- 查看 `GET` 請求中是否有命名為 `q` 的查詢參數 (例如 `http://127.0.0.1:8000/items/foo?q=somequery`)。 + - 因為 `q` 參數被宣告為 `= None`,所以是選填的。 + - 如果沒有宣告 `None`,則此參數將會是必填 (例如 `PUT` 範例的請求 body)。 +- 對於 `PUT` 的請求 `/items/{item_id}`,將會讀取 body 為 JSON: + - 驗證是否有必填屬性 `name` 且型別是 `str`。 + - 驗證是否有必填屬性 `price` 且型別是 `float`。 + - 驗證是否有選填屬性 `is_offer` 且型別是 `bool`。 + - 以上驗證都適用於多層次巢狀 JSON 物件。 +- 自動轉換 JSON 格式。 +- 透過 OpenAPI 文件來記錄所有內容,可以被用於: + - 互動式文件系統。 + - 自動為多種程式語言生成用戶端的程式碼。 +- 提供兩種交互式文件介面。 + +--- + +雖然我們只敘述了表面的功能,但其實你已經理解了它是如何執行。 + +試著修改以下程式碼: + +```Python + return {"item_name": item.name, "item_id": item_id} +``` + +從: + +```Python + ... "item_name": item.name ... +``` + +修改為: + +```Python + ... "item_price": item.price ... +``` + +然後觀察你的編輯器,會自動補全並且還知道他們的型別: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +有關更多功能的完整範例,可以參考 教學 - 使用者指南。 + +**劇透警告**: 教學 - 使用者指南內容有: + +- 對來自不同地方的**參數**進行宣告:像是 **headers**, **cookies**, **form 表單**以及**上傳檔案**。 +- 如何設定 **驗證限制** 像是 `maximum_length` or `regex`。 +- 簡單且非常容易使用的 **依賴注入** 系統。 +- 安全性和身份驗證,包含提供支援 **OAuth2**、**JWT tokens** 和 **HTTP Basic** 驗證。 +- 更進階 (但同樣簡單) 的宣告 **多層次的巢狀 JSON 格式** (感謝 Pydantic)。 +- **GraphQL** 與 Strawberry 以及其他的相關函式庫進行整合。 +- 更多其他的功能 (感謝 Starlette) 像是: + - **WebSockets** + - 於 HTTPX 和 `pytest` 的非常簡單測試 + - **CORS** + - **Cookie Sessions** + - ...以及更多 + +## 效能 + +來自獨立機構 TechEmpower 的測試結果,顯示在 Uvicorn 執行下的 **FastAPI** 是 最快的 Python 框架之一, 僅次於 Starlette 和 Uvicorn 本身 (兩者是 FastAPI 的底層)。 (\*) + +想了解更多訊息,可以參考 測試結果。 + +## 可選的依賴套件 + +用於 Pydantic: + +- email-validator - 用於電子郵件驗證。 +- pydantic-settings - 用於設定管理。 +- pydantic-extra-types - 用於與 Pydantic 一起使用的額外型別。 + +用於 Starlette: + +- httpx - 使用 `TestClient`時必須安裝。 +- jinja2 - 使用預設的模板配置時必須安裝。 +- python-multipart - 需要使用 `request.form()` 對表單進行 "解析" 時安裝。 +- itsdangerous - 需要使用 `SessionMiddleware` 支援時安裝。 +- pyyaml - 用於支援 Starlette 的 `SchemaGenerator` (如果你使用 FastAPI,可能不需要它)。 + +用於 FastAPI / Starlette: + +- uvicorn - 用於加載和運行應用程式的服務器。 +- orjson - 使用 `ORJSONResponse`時必須安裝。 +- ujson - 使用 `UJSONResponse` 時必須安裝。 + +你可以使用 `pip install "fastapi[all]"` 來安裝這些所有依賴套件。 + +## 授權 + +該項目遵循 MIT 許可協議。 diff --git a/docs/zh-hant/docs/learn/index.md b/docs/zh-hant/docs/learn/index.md new file mode 100644 index 000000000..eb7d7096a --- /dev/null +++ b/docs/zh-hant/docs/learn/index.md @@ -0,0 +1,5 @@ +# 學習 + +以下是學習 FastAPI 的入門介紹和教學。 + +你可以將其視為一本**書籍**或一門**課程**,這是**官方**認可並推薦的 FastAPI 學習方式。 😎 diff --git a/docs/zh-hant/docs/resources/index.md b/docs/zh-hant/docs/resources/index.md new file mode 100644 index 000000000..f4c70a3a0 --- /dev/null +++ b/docs/zh-hant/docs/resources/index.md @@ -0,0 +1,3 @@ +# 資源 + +額外的資源、外部連結、文章等。 ✈️ diff --git a/docs/zh-hant/docs/tutorial/first-steps.md b/docs/zh-hant/docs/tutorial/first-steps.md new file mode 100644 index 000000000..a557fa369 --- /dev/null +++ b/docs/zh-hant/docs/tutorial/first-steps.md @@ -0,0 +1,331 @@ +# 第一步 + +最簡單的 FastAPI 檔案可能看起來像這樣: + +{* ../../docs_src/first_steps/tutorial001.py *} + +將其複製到一個名為 `main.py` 的文件中。 + +執行即時重新載入伺服器(live server): + +
+ +```console +$ fastapi dev main.py +INFO Using path main.py +INFO Resolved absolute path /home/user/code/awesomeapp/main.py +INFO Searching for package file structure from directories with __init__.py files +INFO Importing from /home/user/code/awesomeapp + + ╭─ Python module file ─╮ + │ │ + │ 🐍 main.py │ + │ │ + ╰──────────────────────╯ + +INFO Importing module main +INFO Found importable FastAPI app + + ╭─ Importable FastAPI app ─╮ + │ │ + │ from main import app │ + │ │ + ╰──────────────────────────╯ + +INFO Using import string main:app + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + fastapi run + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [2265862] using WatchFiles +INFO: Started server process [2265873] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +在輸出中,有一列類似於: + +```hl_lines="4" +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +那列顯示了你的應用程式正在本地端機器上運行的 URL。 + +### 查看它 + +在瀏覽器中打開 http://127.0.0.1:8000. + +你將看到如下的 JSON 回應: + +```JSON +{"message": "Hello World"} +``` + +### 互動式 API 文件 + +現在,前往 http://127.0.0.1:8000/docs. + +你將看到自動的互動式 API 文件(由 Swagger UI 提供): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### 替代 API 文件 + +現在,前往 http://127.0.0.1:8000/redoc. + +你將看到另一種自動文件(由 ReDoc 提供): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +### OpenAPI + +**FastAPI** 使用定義 API 的 **OpenAPI** 標準來生成一個 「schema」 與你的所有 API。 + +#### 「Schema」 + +「schema」是對某個事物的定義或描述。它並不是實作它的程式碼,而僅僅是一個抽象的描述。 + +#### API 「schema」 + +在這種情況下,OpenAPI 是一個規範,它規定了如何定義 API 的 schema。 + +這個 schema 定義包含了你的 API 路徑、可能接收的參數等內容。 + +#### 資料 「schema」 + +「schema」這個術語也可能指某些資料的結構,比如 JSON 內容的結構。 + +在這種情況下,它指的是 JSON 的屬性、資料型別等。 + +#### OpenAPI 和 JSON Schema + +OpenAPI 定義了 API 的 schema。這個 schema 包含了使用 **JSON Schema** 定義的資料,這是 JSON 資料 schema 的標準。 + +#### 檢查 `openapi.json` + +如果你好奇原始的 OpenAPI schema 長什麼樣子,FastAPI 會自動生成一個包含所有 API 描述的 JSON (schema)。 + +你可以直接在 http://127.0.0.1:8000/openapi.json 查看它。 + +它會顯示一個 JSON,類似於: + +```JSON +{ + "openapi": "3.1.0", + "info": { + "title": "FastAPI", + "version": "0.1.0" + }, + "paths": { + "/items/": { + "get": { + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + + + +... +``` + +#### OpenAPI 的用途 + +OpenAPI schema 驅動了兩個互動式文件系統。 + +而且有許多替代方案,所有這些都是基於 OpenAPI。你可以輕鬆地將任何這些替代方案添加到使用 **FastAPI** 建置的應用程式中。 + +你也可以用它自動生成程式碼,讓前端、手機應用程式或物聯網設備等與你的 API 進行通訊。 + +## 逐步回顧 + +### 第一步:引入 `FastAPI` + +{* ../../docs_src/first_steps/tutorial001.py h1[1] *} + +`FastAPI` 是一個 Python 類別,提供所有 API 的全部功能。 + +/// note | Technical Details + +`FastAPI` 是一個直接繼承自 `Starlette` 的類別。 + +你同樣可以透過 `FastAPI` 來使用 Starlette 所有的功能。 + +/// + +### 第二步:建立一個 `FastAPI` 「實例」 + +{* ../../docs_src/first_steps/tutorial001.py h1[3] *} + +這裡的 `app` 變數將會是 `FastAPI` 類別的「實例」。 + +這將是你建立所有 API 的主要互動點。 + +### 第三步:建立一個 *路徑操作* + +#### 路徑 + +這裡的「路徑」指的是 URL 中自第一個 `/` 以後的部分。 + +例如,在 URL 中: + +``` +https://example.com/items/foo +``` + +……的路徑將會是: + +``` +/items/foo +``` + +/// info + +「路徑」也常被稱為「端點 endpoint」或「路由 route」。 + +/// + +在建置 API 時,「路徑」是分離「關注點」和「資源」的主要方式。 + +#### 操作 + +這裡的「操作」指的是 HTTP 的「方法」之一。 + +其中包括: + +* `POST` +* `GET` +* `PUT` +* `DELETE` + +……以及更少見的: + +* `OPTIONS` +* `HEAD` +* `PATCH` +* `TRACE` + +在 HTTP 協定中,你可以使用這些「方法」之一(或更多)與每個路徑進行通信。 + +--- + +在建置 API 時,你通常使用這些特定的 HTTP 方法來執行特定的動作。 + +通常你使用: + +* `POST`:用來建立資料。 +* `GET`:用來讀取資料。 +* `PUT`:用來更新資料。 +* `DELETE`:用來刪除資料。 + +所以,在 OpenAPI 中,每個 HTTP 方法都被稱為「操作」。 + +我們將會稱它們為「**操作**」。 + +#### 定義一個 *路徑操作裝飾器* + +{* ../../docs_src/first_steps/tutorial001.py h1[6] *} + +`@app.get("/")` 告訴 **FastAPI** 那個函式負責處理請求: + +* 路徑 `/` +* 使用 get操作 + +/// info | `@decorator` Info + +Python 中的 `@something` 語法被稱為「裝飾器」。 + +你把它放在一個函式上面。像一個漂亮的裝飾帽子(我猜這是術語的來源)。 + +一個「裝飾器」會對下面的函式做一些事情。 + +在這種情況下,這個裝飾器告訴 **FastAPI** 那個函式對應於 **路徑** `/` 和 **操作** `get`. + +這就是「**路徑操作裝飾器**」。 + +/// + +你也可以使用其他的操作: + +* `@app.post()` +* `@app.put()` +* `@app.delete()` + +以及更少見的: + +* `@app.options()` +* `@app.head()` +* `@app.patch()` +* `@app.trace()` + +/// tip + +你可以自由地使用每個操作(HTTP 方法)。 + +**FastAPI** 不強制任何特定的意義。 + +這裡的資訊作為一個指南,而不是要求。 + +例如,當使用 GraphQL 時,你通常只使用 `POST` 操作。 + +/// + +### 第四步:定義 **路徑操作函式** + +這是我們的「**路徑操作函式**」: + +* **path**: 是 `/`. +* **operation**: 是 `get`. +* **function**: 是裝飾器下面的函式(在 `@app.get("/")` 下面)。 + +{* ../../docs_src/first_steps/tutorial001.py h1[7] *} + +這就是一個 Python 函式。 + +它將會在 **FastAPI** 收到一個請求時被呼叫,使用 `GET` 操作。 + +在這種情況下,它是一個 `async` 函式。 + +--- + +你可以將它定義為一個正常的函式,而不是 `async def`: + +{* ../../docs_src/first_steps/tutorial003.py h1[7] *} + +/// note + +如果你不知道差別,請查看 [Async: *"In a hurry?"*](../async.md#in-a-hurry){.internal-link target=_blank}. + +/// + +### 第五步:回傳內容 + +{* ../../docs_src/first_steps/tutorial001.py h1[8] *} + +你可以返回一個 `dict`、`list`、單個值作為 `str`、`int` 等。 + +你也可以返回 Pydantic 模型(稍後你會看到更多關於這方面的內容)。 + +有很多其他物件和模型會自動轉換為 JSON(包括 ORMs,等等)。試用你最喜歡的,很有可能它們已經有支援。 + +## 回顧 + +* 引入 `FastAPI`. +* 建立一個 `app` 實例。 +* 寫一個 **路徑操作裝飾器** 使用裝飾器像 `@app.get("/")`。 +* 定義一個 **路徑操作函式**;例如,`def root(): ...`。 +* 使用命令 `fastapi dev` 執行開發伺服器。 diff --git a/docs/zh-hant/docs/tutorial/index.md b/docs/zh-hant/docs/tutorial/index.md new file mode 100644 index 000000000..ae0056f52 --- /dev/null +++ b/docs/zh-hant/docs/tutorial/index.md @@ -0,0 +1,102 @@ +# 教學 - 使用者指南 + +本教學將一步一步展示如何使用 **FastAPI** 及其大多數功能。 + +每個部分都是在前一部分的基礎上逐步建置的,但內容結構是按主題分開的,因此你可以直接跳到任何特定的部分,解決你具體的 API 需求。 + +它也被設計成可作為未來的參考,讓你隨時回來查看所需的內容。 + +## 運行程式碼 + +所有程式碼區塊都可以直接複製和使用(它們實際上是經過測試的 Python 檔案)。 + +要運行任何範例,請將程式碼複製到 `main.py` 檔案,並使用以下命令啟動 `fastapi dev`: + +
+ +```console +$ fastapi dev main.py +INFO Using path main.py +INFO Resolved absolute path /home/user/code/awesomeapp/main.py +INFO Searching for package file structure from directories with __init__.py files +INFO Importing from /home/user/code/awesomeapp + + ╭─ Python module file ─╮ + │ │ + │ 🐍 main.py │ + │ │ + ╰──────────────────────╯ + +INFO Importing module main +INFO Found importable FastAPI app + + ╭─ Importable FastAPI app ─╮ + │ │ + │ from main import app │ + │ │ + ╰──────────────────────────╯ + +INFO Using import string main:app + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + fastapi run + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [2265862] using WatchFiles +INFO: Started server process [2265873] +INFO: Waiting for application startup. +INFO: Application startup complete. + +``` + +
+ +**強烈建議**你編寫或複製程式碼、進行修改並在本地端運行。 + +在編輯器中使用它,才能真正體會到 FastAPI 的好處,可以看到你只需編寫少量程式碼,以及所有的型別檢查、自動補齊等功能。 + +--- + +## 安裝 FastAPI + +第一步是安裝 FastAPI。 + +確保你建立一個[虛擬環境](../virtual-environments.md){.internal-link target=_blank},啟用它,然後**安裝 FastAPI**: + +
+ +```console +$ pip install "fastapi[standard]" + +---> 100% +``` + +
+ +/// note + +當你使用 `pip install "fastapi[standard]"` 安裝時,會包含一些預設的可選標準依賴項。 + +如果你不想包含那些可選的依賴項,你可以使用 `pip install fastapi` 來安裝。 + +/// + +## 進階使用者指南 + +還有一個**進階使用者指南**你可以稍後閱讀。 + +**進階使用者指南**建立在這個教學之上,使用相同的概念,並教你一些額外的功能。 + +但首先你應該閱讀**教學 - 使用者指南**(你正在閱讀的內容)。 + +它被設計成你可以使用**教學 - 使用者指南**來建立一個完整的應用程式,然後根據你的需求,使用一些額外的想法來擴展它。 diff --git a/docs/zh-hant/docs/tutorial/query-param-models.md b/docs/zh-hant/docs/tutorial/query-param-models.md new file mode 100644 index 000000000..76ee74016 --- /dev/null +++ b/docs/zh-hant/docs/tutorial/query-param-models.md @@ -0,0 +1,68 @@ +# 查詢參數模型 + +如果你有一組具有相關性的**查詢參數**,你可以建立一個 **Pydantic 模型**來聲明它們。 + +這將允許你在**多個地方**去**重複使用模型**,並且一次性為所有參數聲明驗證和元資料 (metadata)。😎 + +/// note + +FastAPI 從 `0.115.0` 版本開始支援這個特性。🤓 + +/// + +## 使用 Pydantic 模型的查詢參數 + +在一個 **Pydantic 模型**中聲明你需要的**查詢參數**,然後將參數聲明為 `Query`: + +{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *} + +**FastAPI** 將會從請求的**查詢參數**中**提取**出**每個欄位**的資料,並將其提供給你定義的 Pydantic 模型。 + +## 查看文件 + +你可以在 `/docs` 頁面的 UI 中查看查詢參數: + +
+ +
+ +## 禁止額外的查詢參數 + +在一些特殊的使用場景中(可能不是很常見),你可能希望**限制**你要收到的查詢參數。 + +你可以使用 Pydantic 的模型設定來 `forbid`(禁止)任何 `extra`(額外)欄位: + +{* ../../docs_src/query_param_models/tutorial002_an_py310.py hl[10] *} + +如果客戶端嘗試在**查詢參數**中發送一些**額外的**資料,他們將會收到一個**錯誤**回應。 + +例如,如果客戶端嘗試發送一個值為 `plumbus` 的 `tool` 查詢參數,如: + +```http +https://example.com/items/?limit=10&tool=plumbus +``` + +他們將收到一個**錯誤**回應,告訴他們查詢參數 `tool` 是不允許的: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["query", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus" + } + ] +} +``` + +## 總結 + +你可以使用 **Pydantic 模型**在 **FastAPI** 中聲明**查詢參數**。😎 + +/// tip + +劇透警告:你也可以使用 Pydantic 模型來聲明 cookie 和 headers,但你將在本教學的後面部分閱讀到這部分內容。🤫 + +/// diff --git a/docs/zh-hant/docs/virtual-environments.md b/docs/zh-hant/docs/virtual-environments.md new file mode 100644 index 000000000..d8e31e08e --- /dev/null +++ b/docs/zh-hant/docs/virtual-environments.md @@ -0,0 +1,844 @@ +# 虛擬環境 + +當你在 Python 專案中工作時,你可能會需要使用一個**虛擬環境**(或類似的機制)來隔離你為每個專案安裝的套件。 + +/// info + +如果你已經了解虛擬環境,知道如何建立和使用它們,你可以考慮跳過這一部分。🤓 + +/// + +/// tip + +**虛擬環境**和**環境變數**是不同的。 + +**環境變數**是系統中的一個變數,可以被程式使用。 + +**虛擬環境**是一個包含一些檔案的目錄。 + +/// + +/// info + +這個頁面將教你如何使用**虛擬環境**以及了解它們的工作原理。 + +如果你計畫使用一個**可以為你管理一切的工具**(包括安裝 Python),試試 uv。 + +/// + +## 建立一個專案 + +首先,為你的專案建立一個目錄。 + +我(指原作者 —— 譯者注)通常會在我的主目錄下建立一個名為 `code` 的目錄。 + +在這個目錄下,我再為每個專案建立一個目錄。 + +
+ +```console +// 進入主目錄 +$ cd +// 建立一個用於存放所有程式碼專案的目錄 +$ mkdir code +// 進入 code 目錄 +$ cd code +// 建立一個用於存放這個專案的目錄 +$ mkdir awesome-project +// 進入這個專案的目錄 +$ cd awesome-project +``` + +
+ +## 建立一個虛擬環境 + +在開始一個 Python 專案的**第一時間**,**在你的專案內部**建立一個虛擬環境。 + +/// tip + +你只需要**在每個專案中操作一次**,而不是每次工作時都操作。 + +/// + +//// tab | `venv` + +你可以使用 Python 自帶的 `venv` 模組來建立一個虛擬環境。 + +
+ +```console +$ python -m venv .venv +``` + +
+ +/// details | 上述命令的含義 + +* `python`: 使用名為 `python` 的程式 +* `-m`: 以腳本的方式呼叫一個模組,我們將告訴它接下來使用哪個模組 +* `venv`: 使用名為 `venv` 的模組,這個模組通常隨 Python 一起安裝 +* `.venv`: 在新目錄 `.venv` 中建立虛擬環境 + +/// + +//// + +//// tab | `uv` + +如果你安裝了 `uv`,你也可以使用它來建立一個虛擬環境。 + +
+ +```console +$ uv venv +``` + +
+ +/// tip + +預設情況下,`uv` 會在一個名為 `.venv` 的目錄中建立一個虛擬環境。 + +但你可以透過傳遞一個額外的引數來自訂它,指定目錄的名稱。 + +/// + +//// + +這個命令會在一個名為 `.venv` 的目錄中建立一個新的虛擬環境。 + +/// details | `.venv`,或是其他名稱 + +你可以在不同的目錄下建立虛擬環境,但通常我們會把它命名為 `.venv`。 + +/// + +## 啟動虛擬環境 + +啟動新的虛擬環境來確保你運行的任何 Python 指令或安裝的套件都能使用到它。 + +/// tip + +**每次**開始一個**新的終端會話**來在這個專案工作時,你都需要執行這個操作。 + +/// + +//// tab | Linux, macOS + +
+ +```console +$ source .venv/bin/activate +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ .venv\Scripts\Activate.ps1 +``` + +
+ +//// + +//// tab | Windows Bash + +或者,如果你在 Windows 上使用 Bash(例如 Git Bash): + +
+ +```console +$ source .venv/Scripts/activate +``` + +
+ +//// + +/// tip + +每次你在這個環境中安裝一個**新的套件**時,都需要**重新啟動**這個環境。 + +這麼做確保了當你使用一個由這個套件安裝的**終端(CLI)程式**時,你使用的是你的虛擬環境中的程式,而不是全域安裝、可能版本不同的程式。 + +/// + +## 檢查虛擬環境是否啟動 + +檢查虛擬環境是否啟動(前面的指令是否生效)。 + +/// tip + +這是**非必需的**,但這是一個很好的方法,可以**檢查**一切是否按預期工作,以及你是否使用了你打算使用的虛擬環境。 + +/// + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
+ +如果它顯示了在你專案(在這個例子中是 `awesome-project`)的 `.venv/bin/python` 中的 `python` 二進位檔案,那麼它就生效了。🎉 + +//// + +//// tab | Windows PowerShell + +
+ +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
+ +如果它顯示了在你專案(在這個例子中是 `awesome-project`)的 `.venv\Scripts\python` 中的 `python` 二進位檔案,那麼它就生效了。🎉 + +//// + +## 升級 `pip` + +/// tip + +如果你使用 `uv` 來安裝內容,而不是 `pip`,那麼你就不需要升級 `pip`。😎 + +/// + +如果你使用 `pip` 來安裝套件(它是 Python 的預設元件),你應該將它**升級**到最新版本。 + +在安裝套件時出現的許多奇怪的錯誤都可以透過先升級 `pip` 來解決。 + +/// tip + +通常你只需要在建立虛擬環境後**執行一次**這個操作。 + +/// + +確保虛擬環境是啟動的(使用上面的指令),然後運行: + +
+ +```console +$ python -m pip install --upgrade pip + +---> 100% +``` + +
+ +## 加入 `.gitignore` + +如果你使用 **Git**(這是你應該使用的),加入一個 `.gitignore` 檔案來排除你的 `.venv` 中的所有內容。 + +/// tip + +如果你使用 `uv` 來建立虛擬環境,它會自動為你完成這個操作,你可以跳過這一步。😎 + +/// + +/// tip + +通常你只需要在建立虛擬環境後**執行一次**這個操作。 + +/// + +
+ +```console +$ echo "*" > .venv/.gitignore +``` + +
+ +/// details | 上述指令的含義 + +- `echo "*"`: 將在終端中「顯示」文本 `*`(接下來的部分會對這個操作進行一些修改) +- `>`: 使左邊的指令顯示到終端的任何內容實際上都不會被顯示,而是會被寫入到右邊的檔案中 +- `.gitignore`: 被寫入文本的檔案的名稱 + +而 `*` 對於 Git 來說意味著「所有內容」。所以,它會忽略 `.venv` 目錄中的所有內容。 + +該指令會建立一個名為 .gitignore 的檔案,內容如下: + +```gitignore +* +``` + +/// + +## 安裝套件 + +在啟用虛擬環境後,你可以在其中安裝套件。 + +/// tip + +當你需要安裝或升級套件時,執行本操作**一次**; + +如果你需要再升級版本或新增套件,你可以**再次執行此操作**。 + +/// + +### 直接安裝套件 + +如果你急於安裝,不想使用檔案來聲明專案的套件依賴,你可以直接安裝它們。 + +/// tip + +將程式所需的套件及其版本放在檔案中(例如 `requirements.txt` 或 `pyproject.toml`)是個好(而且非常好)的主意。 + +/// + +//// tab | `pip` + +
+ +```console +$ pip install "fastapi[standard]" + +---> 100% +``` + +
+ +//// + +//// tab | `uv` + +如果你有 `uv`: + +
+ +```console +$ uv pip install "fastapi[standard]" +---> 100% +``` + +
+ +//// + +### 從 `requirements.txt` 安裝 + +如果你有一個 `requirements.txt` 檔案,你可以使用它來安裝其中的套件。 + +//// tab | `pip` + +
+ +```console +$ pip install -r requirements.txt +---> 100% +``` + +
+ +//// + +//// tab | `uv` + +如果你有 `uv`: + +
+ +```console +$ uv pip install -r requirements.txt +---> 100% +``` + +
+ +//// + +/// details | 關於 `requirements.txt` + +一個包含一些套件的 `requirements.txt` 檔案看起來應該是這樣的: + +```requirements.txt +fastapi[standard]==0.113.0 +pydantic==2.8.0 +``` + +/// + +## 執行程式 + +在啟用虛擬環境後,你可以執行你的程式,它將使用虛擬環境中的 Python 和你在其中安裝的套件。 + +
+ +```console +$ python main.py + +Hello World +``` + +
+ +## 設定編輯器 + +你可能會用到編輯器,請確保設定它使用你建立的相同虛擬環境(它可能會自動偵測到),以便你可以獲得自動完成和内嵌錯誤提示。 + +例如: + +* VS Code +* PyCharm + +/// tip + +通常你只需要在建立虛擬環境時執行此操作**一次**。 + +/// + +## 退出虛擬環境 + +當你完成工作後,你可以**退出**虛擬環境。 + +
+ +```console +$ deactivate +``` + +
+ +這樣,當你執行 `python` 時它不會嘗試從已安裝套件的虛擬環境中執行。 + +## 開始工作 + +現在你已經準備好開始你的工作了。 + + + +/// tip + +你想要理解上面的所有內容嗎? + +繼續閱讀。👇🤓 + +/// + +## 為什麼要使用虛擬環境 + +你需要安裝 Python 才能使用 FastAPI。 + +接下來,你需要**安裝** FastAPI 以及你想使用的其他**套件**。 + +要安裝套件,你通常會使用隨 Python 一起提供的 `pip` 指令(或類似的替代工具)。 + +然而,如果你直接使用 `pip`,套件將會安裝在你的**全域 Python 環境**中(即 Python 的全域安裝)。 + +### 存在的問題 + +那麼,在全域 Python 環境中安裝套件有什麼問題呢? + +有時候,你可能會開發許多不同的程式,而這些程式各自依賴於**不同的套件**;有些專案甚至需要依賴於**相同套件的不同版本**。😱 + +例如,你可能會建立一個名為 `philosophers-stone` 的專案,這個程式依賴於另一個名為 **`harry` 的套件,並使用版本 `1`**。因此,你需要安裝 `harry`。 + +```mermaid +flowchart LR + stone(philosophers-stone) -->|需要| harry-1[harry v1] +``` + +然而,在此之後,你又建立了另一個名為 `prisoner-of-azkaban` 的專案,而這個專案也依賴於 `harry`,但需要的是 **`harry` 版本 `3`**。 + +```mermaid +flowchart LR + azkaban(prisoner-of-azkaban) --> |需要| harry-3[harry v3] +``` + +現在的問題是,如果你在全域環境中安裝套件而不是在本地**虛擬環境**中,你將面臨選擇安裝哪個版本的 `harry` 的困境。 + +如果你想運行 `philosophers-stone`,你需要先安裝 `harry` 版本 `1`,例如: + +
+ +```console +$ pip install "harry==1" +``` + +
+ +然後你會在全域 Python 環境中安裝 `harry` 版本 `1`。 + +```mermaid +flowchart LR + subgraph global[全域環境] + harry-1[harry v1] + end + subgraph stone-project[專案 philosophers-stone] + stone(philosophers-stone) -->|需要| harry-1 + end +``` + +但如果你想運行 `prisoner-of-azkaban`,你需要解除安裝 `harry` 版本 `1` 並安裝 `harry` 版本 `3`(或者只要你安裝版本 `3`,版本 `1` 就會自動移除)。 + +
+ +```console +$ pip install "harry==3" +``` + +
+ +於是,你在全域 Python 環境中安裝了 `harry` 版本 `3`。 + +如果你再次嘗試運行 `philosophers-stone`,很可能會**無法正常運作**,因為它需要的是 `harry` 版本 `1`。 + +```mermaid +flowchart LR + subgraph global[全域環境] + harry-1[harry v1] + style harry-1 fill:#ccc,stroke-dasharray: 5 5 + harry-3[harry v3] + end + subgraph stone-project[專案 philosophers-stone] + stone(philosophers-stone) -.-x|⛔️| harry-1 + end + subgraph azkaban-project[專案 prisoner-of-azkaban] + azkaban(prisoner-of-azkaban) --> |需要| harry-3 + end +``` + +/// tip + +Python 套件在推出**新版本**時通常會儘量**避免破壞性更改**,但最好還是要謹慎,在安裝新版本前進行測試,以確保一切能正常運行。 + +/// + +現在,想像一下如果有**許多**其他**套件**,它們都是你的**專案所依賴的**。這樣是非常難以管理的。你可能會發現有些專案使用了一些**不相容的套件版本**,而無法得知為什麼某些程式無法正常運作。 + +此外,取決於你的操作系統(例如 Linux、Windows、macOS),它可能已經預先安裝了 Python。在這種情況下,它可能已經有一些系統所需的套件和特定版本。如果你在全域 Python 環境中安裝套件,可能會**破壞**某些隨作業系統一起安裝的程式。 + +## 套件安裝在哪裡 + +當你安裝 Python 時,它會在你的電腦中建立一些目錄並放置一些檔案。 + +其中一些目錄專門用來存放你所安裝的所有套件。 + +當你運行: + +
+ +```console +// 先別去運行這個指令,這只是個示例 🤓 +$ pip install "fastapi[standard]" +---> 100% +``` + +
+ +這會從 PyPI 下載一個壓縮檔案,其中包含 FastAPI 的程式碼。 + +它還會**下載** FastAPI 所依賴的其他套件的檔案。 + +接著,它會**解壓**所有這些檔案,並將它們放在你的電腦中的某個目錄中。 + +預設情況下,這些下載和解壓的檔案會放置於隨 Python 安裝的目錄中,即**全域環境**。 + +## 什麼是虛擬環境 + +解決套件都安裝在全域環境中的問題方法是為你所做的每個專案使用一個**虛擬環境**。 + +虛擬環境是一個**目錄**,與全域環境非常相似,你可以在其中針對某個專案安裝套件。 + +這樣,每個專案都會有自己的虛擬環境(`.venv` 目錄),其中包含自己的套件。 + +```mermaid +flowchart TB + subgraph stone-project[專案 philosophers-stone] + stone(philosophers-stone) --->|需要| harry-1 + subgraph venv1[.venv] + harry-1[harry v1] + end + end + subgraph azkaban-project[專案 prisoner-of-azkaban] + azkaban(prisoner-of-azkaban) --->|需要| harry-3 + subgraph venv2[.venv] + harry-3[harry v3] + end + end + stone-project ~~~ azkaban-project +``` + +## 啟用虛擬環境意味著什麼 + +當你啟用了虛擬環境,例如: + +//// tab | Linux, macOS + +
+ +```console +$ source .venv/bin/activate +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ .venv\Scripts\Activate.ps1 +``` + +
+ +//// + +//// tab | Windows Bash + +或者如果你在 Windows 上使用 Bash(例如 Git Bash): + +
+ +```console +$ source .venv/Scripts/activate +``` + +
+ +//// + +這個命令會建立或修改一些[環境變數](environment-variables.md){.internal-link target=_blank},這些環境變數將在接下來的指令中可用。 + +其中之一是 `PATH` 變數。 + +/// tip + +你可以在 [環境變數](environment-variables.md#path-environment-variable){.internal-link target=_blank} 部分了解更多關於 `PATH` 環境變數的內容。 + +/// + +啟用虛擬環境會將其路徑 `.venv/bin`(在 Linux 和 macOS 上)或 `.venv\Scripts`(在 Windows 上)加入到 `PATH` 環境變數中。 + +假設在啟用環境之前,`PATH` 變數看起來像這樣: + +//// tab | Linux, macOS + +```plaintext +/usr/bin:/bin:/usr/sbin:/sbin +``` + +這意味著系統會在以下目錄中查找程式: + +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Windows\System32 +``` + +這意味著系統會在以下目錄中查找程式: + +* `C:\Windows\System32` + +//// + +啟用虛擬環境後,`PATH` 變數會變成這樣: + +//// tab | Linux, macOS + +```plaintext +/home/user/code/awesome-project/.venv/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +這意味著系統現在會首先在以下目錄中查找程式: + +```plaintext +/home/user/code/awesome-project/.venv/bin +``` + +然後再在其他目錄中查找。 + +因此,當你在終端機中輸入 `python` 時,系統會在以下目錄中找到 Python 程式: + +```plaintext +/home/user/code/awesome-project/.venv/bin/python +``` + +並使用這個。 + +//// + +//// tab | Windows + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts;C:\Windows\System32 +``` + +這意味著系統現在會首先在以下目錄中查找程式: + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts +``` + +然後再在其他目錄中查找。 + +因此,當你在終端機中輸入 `python` 時,系統會在以下目錄中找到 Python 程式: + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +並使用這個。 + +//// + +一個重要的細節是,虛擬環境路徑會被放在 `PATH` 變數的**開頭**。系統會在找到任何其他可用的 Python **之前**找到它。這樣,當你運行 `python` 時,它會使用**虛擬環境中的** Python,而不是任何其他 `python`(例如,全域環境中的 `python`)。 + +啟用虛擬環境還會改變其他一些內容,但這是它所做的最重要的事情之一。 + +## 檢查虛擬環境 + +當你檢查虛擬環境是否啟動時,例如: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
+ +//// + +這表示將使用的 `python` 程式是**在虛擬環境中**的那一個。 + +在 Linux 和 macOS 中使用 `which`,在 Windows PowerShell 中使用 `Get-Command`。 + +這個指令的運作方式是,它會在 `PATH` 環境變數中搜尋,依序**逐個路徑**查找名為 `python` 的程式。一旦找到,它會**顯示該程式的路徑**。 + +最重要的是,當你呼叫 `python` 時,將執行的就是這個確切的 "`python`"。 + +因此,你可以確認是否在正確的虛擬環境中。 + +/// tip + +啟動一個虛擬環境,取得一個 Python,然後**切換到另一個專案**是件很容易的事; + +但如果第二個專案**無法正常運作**,那可能是因為你使用了來自其他專案的虛擬環境的、**不正確的 Python**。 + +因此,檢查正在使用的 `python` 是非常實用的。🤓 + +/// + +## 為什麼要停用虛擬環境 + +例如,你可能正在一個專案 `philosophers-stone` 上工作,**啟動了該虛擬環境**,安裝了套件並使用了該環境, + +然後你想要在**另一個專案** `prisoner-of-azkaban` 上工作, + +你進入那個專案: + +
+ +```console +$ cd ~/code/prisoner-of-azkaban +``` + +
+ +如果你不去停用 `philosophers-stone` 的虛擬環境,當你在終端中執行 `python` 時,它會嘗試使用 `philosophers-stone` 中的 Python。 + +
+ +```console +$ cd ~/code/prisoner-of-azkaban + +$ python main.py + +// 匯入 sirius 錯誤,未安裝 😱 +Traceback (most recent call last): + File "main.py", line 1, in + import sirius +``` + +
+ +但如果你停用虛擬環境並啟用 `prisoner-of-askaban` 的新虛擬環境,那麼當你執行 `python` 時,它會使用 `prisoner-of-askaban` 中虛擬環境的 Python。 + +
+ +```console +$ cd ~/code/prisoner-of-azkaban + +// 你不需要在舊目錄中操作停用,你可以在任何地方操作停用,甚至在切換到另一個專案之後 😎 +$ deactivate + +// 啟用 prisoner-of-azkaban/.venv 中的虛擬環境 🚀 +$ source .venv/bin/activate + +// 現在當你執行 python 時,它會在這個虛擬環境中找到已安裝的 sirius 套件 ✨ +$ python main.py + +I solemnly swear 🐺 +``` + +
+ +## 替代方案 + +這是一個簡單的指南,幫助你入門並教會你如何理解一切**底層**的原理。 + +有許多**替代方案**來管理虛擬環境、套件依賴(requirements)、專案。 + +當你準備好並想要使用一個工具來**管理整個專案**、套件依賴、虛擬環境等,建議你嘗試 uv。 + +`uv` 可以執行許多操作,它可以: + +* 為你**安裝 Python**,包括不同的版本 +* 為你的專案管理**虛擬環境** +* 安裝**套件** +* 為你的專案管理套件的**依賴和版本** +* 確保你有一個**精確**的套件和版本集合來安裝,包括它們的依賴項,這樣你可以確保專案在生產環境中運行的狀態與開發時在你的電腦上運行的狀態完全相同,這被稱為**鎖定** +* 還有很多其他功能 + +## 結論 + +如果你讀過並理解了所有這些,現在**你對虛擬環境的了解已超過許多開發者**。🤓 + +未來當你為看起來複雜的問題除錯時,了解這些細節很可能會有所幫助,你會知道**它是如何在底層運作的**。😎 diff --git a/docs/zh-hant/mkdocs.yml b/docs/zh-hant/mkdocs.yml new file mode 100644 index 000000000..de18856f4 --- /dev/null +++ b/docs/zh-hant/mkdocs.yml @@ -0,0 +1 @@ +INHERIT: ../en/mkdocs.yml diff --git a/docs/zh/docs/advanced/additional-responses.md b/docs/zh/docs/advanced/additional-responses.md index 2a1e1ed89..362ef9460 100644 --- a/docs/zh/docs/advanced/additional-responses.md +++ b/docs/zh/docs/advanced/additional-responses.md @@ -16,23 +16,25 @@ **FastAPI**将采用该模型,生成其`JSON Schema`并将其包含在`OpenAPI`中的正确位置。 例如,要声明另一个具有状态码 `404` 和`Pydantic`模型 `Message` 的响应,可以写: -```Python hl_lines="18 22" -{!../../../docs_src/additional_responses/tutorial001.py!} -``` +{* ../../docs_src/additional_responses/tutorial001.py hl[18,22] *} + +/// note + +请记住,您必须直接返回 `JSONResponse` 。 +/// -!!! Note - 请记住,您必须直接返回 `JSONResponse` 。 +/// info -!!! Info - `model` 密钥不是OpenAPI的一部分。 - **FastAPI**将从那里获取`Pydantic`模型,生成` JSON Schema` ,并将其放在正确的位置。 - - 正确的位置是: - - 在键 `content` 中,其具有另一个`JSON`对象( `dict` )作为值,该`JSON`对象包含: - - 媒体类型的密钥,例如 `application/json` ,它包含另一个`JSON`对象作为值,该对象包含: - - 一个键` schema` ,它的值是来自模型的`JSON Schema`,正确的位置在这里。 - - **FastAPI**在这里添加了对OpenAPI中另一个地方的全局JSON模式的引用,而不是直接包含它。这样,其他应用程序和客户端可以直接使用这些JSON模式,提供更好的代码生成工具等。 +`model` 密钥不是OpenAPI的一部分。 +**FastAPI**将从那里获取`Pydantic`模型,生成` JSON Schema` ,并将其放在正确的位置。 +- 正确的位置是: + - 在键 `content` 中,其具有另一个`JSON`对象( `dict` )作为值,该`JSON`对象包含: + - 媒体类型的密钥,例如 `application/json` ,它包含另一个`JSON`对象作为值,该对象包含: + - 一个键` schema` ,它的值是来自模型的`JSON Schema`,正确的位置在这里。 + - **FastAPI**在这里添加了对OpenAPI中另一个地方的全局JSON模式的引用,而不是直接包含它。这样,其他应用程序和客户端可以直接使用这些JSON模式,提供更好的代码生成工具等。 +/// **在OpenAPI中为该路径操作生成的响应将是:** @@ -159,16 +161,20 @@ 例如,您可以添加一个额外的媒体类型` image/png` ,声明您的路径操作可以返回JSON对象(媒体类型 `application/json` )或PNG图像: -```Python hl_lines="19-24 28" -{!../../../docs_src/additional_responses/tutorial002.py!} -``` +{* ../../docs_src/additional_responses/tutorial002.py hl[19:24,28] *} + +/// note -!!! Note - - 请注意,您必须直接使用 `FileResponse` 返回图像。 +- 请注意,您必须直接使用 `FileResponse` 返回图像。 -!!! Info - - 除非在 `responses` 参数中明确指定不同的媒体类型,否则**FastAPI**将假定响应与主响应类具有相同的媒体类型(默认为` application/json` )。 - - 但是如果您指定了一个自定义响应类,并将 `None `作为其媒体类型,**FastAPI**将使用 `application/json` 作为具有关联模型的任何其他响应。 +/// + +/// info + +- 除非在 `responses` 参数中明确指定不同的媒体类型,否则**FastAPI**将假定响应与主响应类具有相同的媒体类型(默认为` application/json` )。 +- 但是如果您指定了一个自定义响应类,并将 `None `作为其媒体类型,**FastAPI**将使用 `application/json` 作为具有关联模型的任何其他响应。 + +/// ## 组合信息 您还可以联合接收来自多个位置的响应信息,包括 `response_model `、 `status_code` 和 `responses `参数。 @@ -181,9 +187,7 @@ 以及一个状态码为 `200` 的响应,它使用您的 `response_model` ,但包含自定义的 `example` : -```Python hl_lines="20-31" -{!../../../docs_src/additional_responses/tutorial003.py!} -``` +{* ../../docs_src/additional_responses/tutorial003.py hl[20:31] *} 所有这些都将被合并并包含在您的OpenAPI中,并在API文档中显示: @@ -209,9 +213,7 @@ new_dict = {**old_dict, "new key": "new value"} ``` 您可以使用该技术在路径操作中重用一些预定义的响应,并将它们与其他自定义响应相结合。 **例如:** -```Python hl_lines="13-17 26" -{!../../../docs_src/additional_responses/tutorial004.py!} -``` +{* ../../docs_src/additional_responses/tutorial004.py hl[13:17,26] *} ## 有关OpenAPI响应的更多信息 要了解您可以在响应中包含哪些内容,您可以查看OpenAPI规范中的以下部分: diff --git a/docs/zh/docs/advanced/additional-status-codes.md b/docs/zh/docs/advanced/additional-status-codes.md index 54ec9775b..b048a2a17 100644 --- a/docs/zh/docs/advanced/additional-status-codes.md +++ b/docs/zh/docs/advanced/additional-status-codes.md @@ -14,21 +14,25 @@ 要实现它,导入 `JSONResponse`,然后在其中直接返回你的内容,并将 `status_code` 设置为为你要的值。 -```Python hl_lines="4 25" -{!../../../docs_src/additional_status_codes/tutorial001.py!} -``` +{* ../../docs_src/additional_status_codes/tutorial001.py hl[4,25] *} -!!! warning "警告" - 当你直接返回一个像上面例子中的 `Response` 对象时,它会直接返回。 +/// warning | 警告 - FastAPI 不会用模型等对该响应进行序列化。 +当你直接返回一个像上面例子中的 `Response` 对象时,它会直接返回。 - 确保其中有你想要的数据,且返回的值为合法的 JSON(如果你使用 `JSONResponse` 的话)。 +FastAPI 不会用模型等对该响应进行序列化。 -!!! note "技术细节" - 你也可以使用 `from starlette.responses import JSONResponse`。  +确保其中有你想要的数据,且返回的值为合法的 JSON(如果你使用 `JSONResponse` 的话)。 - 出于方便,**FastAPI** 为开发者提供同 `starlette.responses` 一样的 `fastapi.responses`。但是大多数可用的响应都是直接来自 Starlette。`status` 也是一样。 +/// + +/// note | 技术细节 + +你也可以使用 `from starlette.responses import JSONResponse`。  + +出于方便,**FastAPI** 为开发者提供同 `starlette.responses` 一样的 `fastapi.responses`。但是大多数可用的响应都是直接来自 Starlette。`status` 也是一样。 + +/// ## OpenAPI 和 API 文档 diff --git a/docs/zh/docs/advanced/advanced-dependencies.md b/docs/zh/docs/advanced/advanced-dependencies.md new file mode 100644 index 000000000..8375bd48e --- /dev/null +++ b/docs/zh/docs/advanced/advanced-dependencies.md @@ -0,0 +1,65 @@ +# 高级依赖项 + +## 参数化的依赖项 + +我们之前看到的所有依赖项都是写死的函数或类。 + +但也可以为依赖项设置参数,避免声明多个不同的函数或类。 + +假设要创建校验查询参数 `q` 是否包含固定内容的依赖项。 + +但此处要把待检验的固定内容定义为参数。 + +## **可调用**实例 + +Python 可以把类实例变为**可调用项**。 + +这里说的不是类本身(类本就是可调用项),而是类实例。 + +为此,需要声明 `__call__` 方法: + +{* ../../docs_src/dependencies/tutorial011.py hl[10] *} + +本例中,**FastAPI** 使用 `__call__` 检查附加参数及子依赖项,稍后,还要调用它向*路径操作函数*传递值。 + +## 参数化实例 + +接下来,使用 `__init__` 声明用于**参数化**依赖项的实例参数: + +{* ../../docs_src/dependencies/tutorial011.py hl[7] *} + +本例中,**FastAPI** 不使用 `__init__`,我们要直接在代码中使用。 + +## 创建实例 + +使用以下代码创建类实例: + +{* ../../docs_src/dependencies/tutorial011.py hl[16] *} + +这样就可以**参数化**依赖项,它包含 `checker.fixed_content` 的属性 - `"bar"`。 + +## 把实例作为依赖项 + +然后,不要再在 `Depends(checker)` 中使用 `Depends(FixedContentQueryChecker)`, 而是要使用 `checker`,因为依赖项是类实例 - `checker`,不是类。 + +处理依赖项时,**FastAPI** 以如下方式调用 `checker`: + +```Python +checker(q="somequery") +``` + +……并用*路径操作函数*的参数 `fixed_content_included` 返回依赖项的值: + +{* ../../docs_src/dependencies/tutorial011.py hl[20] *} + +/// tip | 提示 + +本章示例有些刻意,也看不出有什么用处。 + +这个简例只是为了说明高级依赖项的运作机制。 + +在有关安全的章节中,工具函数将以这种方式实现。 + +只要能理解本章内容,就能理解安全工具背后的运行机制。 + +/// diff --git a/docs/zh/docs/advanced/async-tests.md b/docs/zh/docs/advanced/async-tests.md new file mode 100644 index 000000000..b5ac15b5b --- /dev/null +++ b/docs/zh/docs/advanced/async-tests.md @@ -0,0 +1,99 @@ +# 异步测试 + +您已经了解了如何使用 `TestClient` 测试 **FastAPI** 应用程序。但是到目前为止,您只了解了如何编写同步测试,而没有使用 `async` 异步函数。 + +在测试中能够使用异步函数可能会很有用,比如当您需要异步查询数据库的时候。想象一下,您想要测试向 FastAPI 应用程序发送请求,然后验证您的后端是否成功在数据库中写入了正确的数据,与此同时您使用了异步的数据库的库。 + +让我们看看如何才能实现这一点。 + +## pytest.mark.anyio + +如果我们想在测试中调用异步函数,那么我们的测试函数必须是异步的。 AnyIO 为此提供了一个简洁的插件,它允许我们指定一些测试函数要异步调用。 + +## HTTPX + +即使您的 **FastAPI** 应用程序使用普通的 `def` 函数而不是 `async def` ,它本质上仍是一个 `async` 异步应用程序。 + +`TestClient` 在内部通过一些“魔法”操作,使得您可以在普通的 `def` 测试函数中调用异步的 FastAPI 应用程序,并使用标准的 pytest。但当我们在异步函数中使用它时,这种“魔法”就不再生效了。由于测试以异步方式运行,我们无法在测试函数中继续使用 `TestClient`。 + +`TestClient` 是基于 HTTPX 的。幸运的是,我们可以直接使用它来测试API。 + +## 示例 + +举个简单的例子,让我们来看一个[更大的应用](../tutorial/bigger-applications.md){.internal-link target=_blank}和[测试](../tutorial/testing.md){.internal-link target=_blank}中描述的类似文件结构: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +文件 `main.py` 将包含: + +{* ../../docs_src/async_tests/main.py *} + +文件 `test_main.py` 将包含针对 `main.py` 的测试,现在它可能看起来如下: + +{* ../../docs_src/async_tests/test_main.py *} + +## 运行测试 + +您可以通过以下方式照常运行测试: + +
+ +```console +$ pytest + +---> 100% +``` + +
+ +## 详细说明 + +这个标记 `@pytest.mark.anyio` 会告诉 pytest 该测试函数应该被异步调用: + +{* ../../docs_src/async_tests/test_main.py hl[7] *} + +/// tip + +请注意,测试函数现在用的是 `async def`,而不是像以前使用 `TestClient` 时那样只是 `def` 。 + +/// + +我们现在可以使用应用程序创建一个 `AsyncClient` ,并使用 `await` 向其发送异步请求。 + +{* ../../docs_src/async_tests/test_main.py hl[9:12] *} + +这相当于: + +```Python +response = client.get('/') +``` + +我们曾经通过它向 `TestClient` 发出请求。 + +/// tip + +请注意,我们正在将 async/await 与新的 `AsyncClient` 一起使用——请求是异步的。 + +/// + +/// warning + +如果您的应用程序依赖于生命周期事件, `AsyncClient` 将不会触发这些事件。为了确保它们被触发,请使用 florimondmanca/asgi-lifespan 中的 `LifespanManager` 。 + +/// + +## 其他异步函数调用 + +由于测试函数现在是异步的,因此除了在测试中向 FastAPI 应用程序发送请求之外,您现在还可以调用(和使用 `await` 等待)其他 `async` 异步函数,就和您在代码中的其他任何地方调用它们的方法一样。 + +/// tip + +如果您在测试程序中集成异步函数调用的时候遇到一个 `RuntimeError: Task attached to a different loop` 的报错(例如,使用 MongoDB 的 MotorClient 时),请记住,只能在异步函数中实例化需要事件循环的对象,例如通过 `'@app.on_event("startup")` 回调函数进行初始化。 + +/// diff --git a/docs/zh/docs/advanced/behind-a-proxy.md b/docs/zh/docs/advanced/behind-a-proxy.md new file mode 100644 index 000000000..f8f61c8a3 --- /dev/null +++ b/docs/zh/docs/advanced/behind-a-proxy.md @@ -0,0 +1,357 @@ +# 使用代理 + +有些情况下,您可能要使用 Traefik 或 Nginx 等**代理**服务器,并添加应用不能识别的附加路径前缀配置。 + +此时,要使用 `root_path` 配置应用。 + +`root_path` 是 ASGI 规范提供的机制,FastAPI 就是基于此规范开发的(通过 Starlette)。 + +`root_path` 用于处理这些特定情况。 + +在挂载子应用时,也可以在内部使用。 + +## 移除路径前缀的代理 + +本例中,移除路径前缀的代理是指在代码中声明路径 `/app`,然后在应用顶层添加代理,把 **FastAPI** 应用放在 `/api/v1` 路径下。 + +本例的原始路径 `/app` 实际上是在 `/api/v1/app` 提供服务。 + +哪怕所有代码都假设只有 `/app`。 + +代理只在把请求传送给 Uvicorn 之前才会**移除路径前缀**,让应用以为它是在 `/app` 提供服务,因此不必在代码中加入前缀 `/api/v1`。 + +但之后,在(前端)打开 API 文档时,代理会要求在 `/openapi.json`,而不是 `/api/v1/openapi.json` 中提取 OpenAPI 概图。 + +因此, (运行在浏览器中的)前端会尝试访问 `/openapi.json`,但没有办法获取 OpenAPI 概图。 + +这是因为应用使用了以 `/api/v1` 为路径前缀的代理,前端要从 `/api/v1/openapi.json` 中提取 OpenAPI 概图。 + +```mermaid +graph LR + +browser("Browser") +proxy["Proxy on http://0.0.0.0:9999/api/v1/app"] +server["Server on http://127.0.0.1:8000/app"] + +browser --> proxy +proxy --> server +``` + +/// tip | 提示 + +IP `0.0.0.0` 常用于指程序监听本机或服务器上的所有有效 IP。 + +/// + +API 文档还需要 OpenAPI 概图声明 API `server` 位于 `/api/v1`(使用代理时的 URL)。例如: + +```JSON hl_lines="4-8" +{ + "openapi": "3.0.2", + // More stuff here + "servers": [ + { + "url": "/api/v1" + } + ], + "paths": { + // More stuff here + } +} +``` + +本例中的 `Proxy` 是 **Traefik**,`server` 是运行 FastAPI 应用的 **Uvicorn**。 + +### 提供 `root_path` + +为此,要以如下方式使用命令行选项 `--root-path`: + +
+ +```console +$ uvicorn main:app --root-path /api/v1 + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Hypercorn 也支持 `--root-path `选项。 + +/// note | 技术细节 + +ASGI 规范定义的 `root_path` 就是为了这种用例。 + +并且 `--root-path` 命令行选项支持 `root_path`。 + +/// + +### 查看当前的 `root_path` + +获取应用为每个请求使用的当前 `root_path`,这是 `scope` 字典的内容(也是 ASGI 规范的内容)。 + +我们在这里的信息里包含 `roo_path` 只是为了演示。 + +{* ../../docs_src/behind_a_proxy/tutorial001.py hl[8] *} + +然后,用以下命令启动 Uvicorn: + +
+ +```console +$ uvicorn main:app --root-path /api/v1 + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +返回的响应如下: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +### 在 FastAPI 应用里设置 `root_path` + +还有一种方案,如果不能提供 `--root-path` 或等效的命令行选项,则在创建 FastAPI 应用时要设置 `root_path` 参数。 + +{* ../../docs_src/behind_a_proxy/tutorial002.py hl[3] *} + +传递 `root_path` 给 `FastAPI` 与传递 `--root-path` 命令行选项给 Uvicorn 或 Hypercorn 一样。 + +### 关于 `root_path` + +注意,服务器(Uvicorn)只是把 `root_path` 传递给应用。 + +在浏览器中输入 http://127.0.0.1:8000/app 时能看到标准响应: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +它不要求访问 `http://127.0.0.1:800/api/v1/app`。 + +Uvicorn 预期代理在 `http://127.0.0.1:8000/app` 访问 Uvicorn,而在顶部添加 `/api/v1` 前缀是代理要做的事情。 + +## 关于移除路径前缀的代理 + +注意,移除路径前缀的代理只是配置代理的方式之一。 + +大部分情况下,代理默认都不会移除路径前缀。 + +(未移除路径前缀时)代理监听 `https://myawesomeapp.com` 等对象,如果浏览器跳转到 `https://myawesomeapp.com/api/v1/app`,且服务器(例如 Uvicorn)监听 `http://127.0.0.1:8000` 代理(未移除路径前缀) 会在同样的路径:`http://127.0.0.1:8000/api/v1/app` 访问 Uvicorn。 + +## 本地测试 Traefik + +您可以轻易地在本地使用 Traefik 运行移除路径前缀的试验。 + +下载 Traefik,这是一个二进制文件,需要解压文件,并在 Terminal 中直接运行。 + +然后创建包含如下内容的 `traefik.toml` 文件: + +```TOML hl_lines="3" +[entryPoints] + [entryPoints.http] + address = ":9999" + +[providers] + [providers.file] + filename = "routes.toml" +``` + +这个文件把 Traefik 监听端口设置为 `9999`,并设置要使用另一个文件 `routes.toml`。 + +/// tip | 提示 + +使用端口 9999 代替标准的 HTTP 端口 80,这样就不必使用管理员权限运行(`sudo`)。 + +/// + +接下来,创建 `routes.toml`: + +```TOML hl_lines="5 12 20" +[http] + [http.middlewares] + + [http.middlewares.api-stripprefix.stripPrefix] + prefixes = ["/api/v1"] + + [http.routers] + + [http.routers.app-http] + entryPoints = ["http"] + service = "app" + rule = "PathPrefix(`/api/v1`)" + middlewares = ["api-stripprefix"] + + [http.services] + + [http.services.app] + [http.services.app.loadBalancer] + [[http.services.app.loadBalancer.servers]] + url = "http://127.0.0.1:8000" +``` + +这个文件配置 Traefik 使用路径前缀 `/api/v1`。 + +然后,它把请求重定位到运行在 `http://127.0.0.1:8000` 上的 Uvicorn。 + +现在,启动 Traefik: + +
+ +```console +$ ./traefik --configFile=traefik.toml + +INFO[0000] Configuration loaded from file: /home/user/awesomeapi/traefik.toml +``` + +
+ +接下来,使用 Uvicorn 启动应用,并使用 `--root-path` 选项: + +
+ +```console +$ uvicorn main:app --root-path /api/v1 + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +### 查看响应 + +访问含 Uvicorn 端口的 URL:http://127.0.0.1:8000/app,就能看到标准响应: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +/// tip | 提示 + +注意,就算访问 `http://127.0.0.1:8000/app`,也显示从选项 `--root-path` 中提取的 `/api/v1`,这是 `root_path` 的值。 + +/// + +打开含 Traefik 端口的 URL,包含路径前缀:http://127.0.0.1:9999/api/v1/app。 + +得到同样的响应: + +```JSON +{ + "message": "Hello World", + "root_path": "/api/v1" +} +``` + +但这一次 URL 包含了代理提供的路径前缀:`/api/v1`。 + +当然,这是通过代理访问应用的方式,因此,路径前缀 `/app/v1` 版本才是**正确**的。 + +而不带路径前缀的版本(`http://127.0.0.1:8000/app`),则由 Uvicorn 直接提供,专供*代理*(Traefik)访问。 + +这演示了代理(Traefik)如何使用路径前缀,以及服务器(Uvicorn)如何使用选项 `--root-path` 中的 `root_path`。 + +### 查看文档 + +但这才是有趣的地方 ✨ + +访问应用的**官方**方式是通过含路径前缀的代理。因此,不出所料,如果没有在 URL 中添加路径前缀,直接访问通过 Uvicorn 运行的 API 文档,不能正常访问,因为需要通过代理才能访问。 + +输入 http://127.0.0.1:8000/docs 查看 API 文档: + + + +但输入**官方**链接 `/api/v1/docs`,并使用端口 `9999` 访问 API 文档,就能正常运行了!🎉 + +输入 http://127.0.0.1:9999/api/v1/docs 查看文档: + + + +一切正常。 ✔️ + +这是因为 FastAPI 在 OpenAPI 里使用 `root_path` 提供的 URL 创建默认 `server`。 + +## 附加的服务器 + +/// warning | 警告 + +此用例较难,可以跳过。 + +/// + +默认情况下,**FastAPI** 使用 `root_path` 的链接在 OpenAPI 概图中创建 `server`。 + +但也可以使用其它备选 `servers`,例如,需要同一个 API 文档与 staging 和生产环境交互。 + +如果传递自定义 `servers` 列表,并有 `root_path`( 因为 API 使用了代理),**FastAPI** 会在列表开头使用这个 `root_path` 插入**服务器**。 + +例如: + +{* ../../docs_src/behind_a_proxy/tutorial003.py hl[4:7] *} + +这段代码生产如下 OpenAPI 概图: + +```JSON hl_lines="5-7" +{ + "openapi": "3.0.2", + // More stuff here + "servers": [ + { + "url": "/api/v1" + }, + { + "url": "https://stag.example.com", + "description": "Staging environment" + }, + { + "url": "https://prod.example.com", + "description": "Production environment" + } + ], + "paths": { + // More stuff here + } +} +``` + +/// tip | 提示 + +注意,自动生成服务器时,`url` 的值 `/api/v1` 提取自 `roog_path`。 + +/// + +http://127.0.0.1:9999/api/v1/docs 的 API 文档所示如下: + + + +/// tip | 提示 + +API 文档与所选的服务器进行交互。 + +/// + +### 从 `root_path` 禁用自动服务器 + +如果不想让 **FastAPI** 包含使用 `root_path` 的自动服务器,则要使用参数 `root_path_in_servers=False`: + +{* ../../docs_src/behind_a_proxy/tutorial004.py hl[9] *} + +这样,就不会在 OpenAPI 概图中包含服务器了。 + +## 挂载子应用 + +如需挂载子应用(详见 [子应用 - 挂载](sub-applications.md){.internal-link target=_blank}),也要通过 `root_path` 使用代理,这与正常应用一样,别无二致。 + +FastAPI 在内部使用 `root_path`,因此子应用也可以正常运行。✨ diff --git a/docs/zh/docs/advanced/custom-response.md b/docs/zh/docs/advanced/custom-response.md index 155ce2882..22a9b4b51 100644 --- a/docs/zh/docs/advanced/custom-response.md +++ b/docs/zh/docs/advanced/custom-response.md @@ -12,8 +12,11 @@ 并且如果该 `Response` 有一个 JSON 媒体类型(`application/json`),比如使用 `JSONResponse` 或者 `UJSONResponse` 的时候,返回的数据将使用你在路径操作装饰器中声明的任何 Pydantic 的 `response_model` 自动转换(和过滤)。 -!!! note "说明" - 如果你使用不带有任何媒体类型的响应类,FastAPI 认为你的响应没有任何内容,所以不会在生成的OpenAPI文档中记录响应格式。 +/// note | 说明 + +如果你使用不带有任何媒体类型的响应类,FastAPI 认为你的响应没有任何内容,所以不会在生成的OpenAPI文档中记录响应格式。 + +/// ## 使用 `ORJSONResponse` @@ -21,21 +24,23 @@ 导入你想要使用的 `Response` 类(子类)然后在 *路径操作装饰器* 中声明它。 -```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial001b.py!} -``` +{* ../../docs_src/custom_response/tutorial001b.py hl[2,7] *} + +/// info | 提示 -!!! info "提示" - 参数 `response_class` 也会用来定义响应的「媒体类型」。 +参数 `response_class` 也会用来定义响应的「媒体类型」。 - 在这个例子中,HTTP 头的 `Content-Type` 会被设置成 `application/json`。 +在这个例子中,HTTP 头的 `Content-Type` 会被设置成 `application/json`。 - 并且在 OpenAPI 文档中也会这样记录。 +并且在 OpenAPI 文档中也会这样记录。 -!!! tip "小贴士" - `ORJSONResponse` 目前只在 FastAPI 中可用,而在 Starlette 中不可用。 +/// +/// tip | 小贴士 +`ORJSONResponse` 目前只在 FastAPI 中可用,而在 Starlette 中不可用。 + +/// ## HTML 响应 @@ -44,16 +49,17 @@ * 导入 `HTMLResponse`。 * 将 `HTMLResponse` 作为你的 *路径操作* 的 `response_class` 参数传入。 -```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial002.py!} -``` +{* ../../docs_src/custom_response/tutorial002.py hl[2,7] *} + +/// info | 提示 -!!! info "提示" - 参数 `response_class` 也会用来定义响应的「媒体类型」。 +参数 `response_class` 也会用来定义响应的「媒体类型」。 - 在这个例子中,HTTP 头的 `Content-Type` 会被设置成 `text/html`。 +在这个例子中,HTTP 头的 `Content-Type` 会被设置成 `text/html`。 - 并且在 OpenAPI 文档中也会这样记录。 +并且在 OpenAPI 文档中也会这样记录。 + +/// ### 返回一个 `Response` @@ -61,15 +67,19 @@ 和上面一样的例子,返回一个 `HTMLResponse` 看起来可能是这样: -```Python hl_lines="2 7 19" -{!../../../docs_src/custom_response/tutorial003.py!} -``` +{* ../../docs_src/custom_response/tutorial003.py hl[2,7,19] *} + +/// warning | 警告 + +*路径操作函数* 直接返回的 `Response` 不会被 OpenAPI 的文档记录(比如,`Content-Type` 不会被文档记录),并且在自动化交互文档中也是不可见的。 + +/// -!!! warning "警告" - *路径操作函数* 直接返回的 `Response` 不会被 OpenAPI 的文档记录(比如,`Content-Type` 不会被文档记录),并且在自动化交互文档中也是不可见的。 +/// info | 提示 -!!! info "提示" - 当然,实际的 `Content-Type` 头,状态码等等,将来自于你返回的 `Response` 对象。 +当然,实际的 `Content-Type` 头,状态码等等,将来自于你返回的 `Response` 对象。 + +/// ### OpenAPI 中的文档和重载 `Response` @@ -81,9 +91,7 @@ 比如像这样: -```Python hl_lines="7 23 21" -{!../../../docs_src/custom_response/tutorial004.py!} -``` +{* ../../docs_src/custom_response/tutorial004.py hl[7,23,21] *} 在这个例子中,函数 `generate_html_response()` 已经生成并返回 `Response` 对象而不是在 `str` 中返回 HTML。 @@ -99,10 +107,13 @@ 要记得你可以使用 `Response` 来返回任何其他东西,甚至创建一个自定义的子类。 -!!! note "技术细节" - 你也可以使用 `from starlette.responses import HTMLResponse`。 +/// note | 技术细节 + +你也可以使用 `from starlette.responses import HTMLResponse`。 + +**FastAPI** 提供了同 `fastapi.responses` 相同的 `starlette.responses` 只是为了方便开发者。但大多数可用的响应都直接来自 Starlette。 - **FastAPI** 提供了同 `fastapi.responses` 相同的 `starlette.responses` 只是为了方便开发者。但大多数可用的响应都直接来自 Starlette。 +/// ### `Response` @@ -120,9 +131,7 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它还将包含一个基于 media_type 的 Content-Type 头,并为文本类型附加一个字符集。 -```Python hl_lines="1 18" -{!../../../docs_src/response_directly/tutorial002.py!} -``` +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} ### `HTMLResponse` @@ -132,9 +141,7 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它 接受文本或字节并返回纯文本响应。 -```Python hl_lines="2 7 9" -{!../../../docs_src/custom_response/tutorial005.py!} -``` +{* ../../docs_src/custom_response/tutorial005.py hl[2,7,9] *} ### `JSONResponse` @@ -151,31 +158,31 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它 `UJSONResponse` 是一个使用 `ujson` 的可选 JSON 响应。 -!!! warning "警告" - 在处理某些边缘情况时,`ujson` 不如 Python 的内置实现那么谨慎。 +/// warning | 警告 + +在处理某些边缘情况时,`ujson` 不如 Python 的内置实现那么谨慎。 + +/// -```Python hl_lines="2 7" -{!../../../docs_src/custom_response/tutorial001.py!} -``` +{* ../../docs_src/custom_response/tutorial001.py hl[2,7] *} -!!! tip "小贴士" - `ORJSONResponse` 可能是一个更快的选择。 +/// tip | 小贴士 + +`ORJSONResponse` 可能是一个更快的选择。 + +/// ### `RedirectResponse` 返回 HTTP 重定向。默认情况下使用 307 状态代码(临时重定向)。 -```Python hl_lines="2 9" -{!../../../docs_src/custom_response/tutorial006.py!} -``` +{* ../../docs_src/custom_response/tutorial006.py hl[2,9] *} ### `StreamingResponse` 采用异步生成器或普通生成器/迭代器,然后流式传输响应主体。 -```Python hl_lines="2 14" -{!../../../docs_src/custom_response/tutorial007.py!} -``` +{* ../../docs_src/custom_response/tutorial007.py hl[2,14] *} #### 对类似文件的对象使用 `StreamingResponse` @@ -183,12 +190,13 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它 包括许多与云存储,视频处理等交互的库。 -```Python hl_lines="2 10-12 14" -{!../../../docs_src/custom_response/tutorial008.py!} -``` +{* ../../docs_src/custom_response/tutorial008.py hl[2,10:12,14] *} + +/// tip | 小贴士 + +注意在这里,因为我们使用的是不支持 `async` 和 `await` 的标准 `open()`,我们使用普通的 `def` 声明了路径操作。 -!!! tip "小贴士" - 注意在这里,因为我们使用的是不支持 `async` 和 `await` 的标准 `open()`,我们使用普通的 `def` 声明了路径操作。 +/// ### `FileResponse` @@ -203,9 +211,7 @@ FastAPI(实际上是 Starlette)将自动包含 Content-Length 的头。它 文件响应将包含适当的 `Content-Length`,`Last-Modified` 和 `ETag` 的响应头。 -```Python hl_lines="2 10" -{!../../../docs_src/custom_response/tutorial009.py!} -``` +{* ../../docs_src/custom_response/tutorial009.py hl[2,10] *} ## 额外文档 diff --git a/docs/zh/docs/advanced/dataclasses.md b/docs/zh/docs/advanced/dataclasses.md new file mode 100644 index 000000000..c74ce65c3 --- /dev/null +++ b/docs/zh/docs/advanced/dataclasses.md @@ -0,0 +1,97 @@ +# 使用数据类 + +FastAPI 基于 **Pydantic** 构建,前文已经介绍过如何使用 Pydantic 模型声明请求与响应。 + +但 FastAPI 还可以使用数据类(`dataclasses`): + +{* ../../docs_src/dataclasses/tutorial001.py hl[1,7:12,19:20] *} + +这还是借助于 **Pydantic** 及其内置的 `dataclasses`。 + +因此,即便上述代码没有显式使用 Pydantic,FastAPI 仍会使用 Pydantic 把标准数据类转换为 Pydantic 数据类(`dataclasses`)。 + +并且,它仍然支持以下功能: + +* 数据验证 +* 数据序列化 +* 数据存档等 + +数据类的和运作方式与 Pydantic 模型相同。实际上,它的底层使用的也是 Pydantic。 + +/// info | 说明 + +注意,数据类不支持 Pydantic 模型的所有功能。 + +因此,开发时仍需要使用 Pydantic 模型。 + +但如果数据类很多,这一技巧能给 FastAPI 开发 Web API 增添不少助力。🤓 + +/// + +## `response_model` 使用数据类 + +在 `response_model` 参数中使用 `dataclasses`: + +{* ../../docs_src/dataclasses/tutorial002.py hl[1,7:13,19] *} + +本例把数据类自动转换为 Pydantic 数据类。 + +API 文档中也会显示相关概图: + + + +## 在嵌套数据结构中使用数据类 + +您还可以把 `dataclasses` 与其它类型注解组合在一起,创建嵌套数据结构。 + +还有一些情况也可以使用 Pydantic 的 `dataclasses`。例如,在 API 文档中显示错误。 + +本例把标准的 `dataclasses` 直接替换为 `pydantic.dataclasses`: + +```{ .python .annotate hl_lines="1 5 8-11 14-17 23-25 28" } +{!../../docs_src/dataclasses/tutorial003.py!} +``` + +1. 本例依然要从标准的 `dataclasses` 中导入 `field`; + +2. 使用 `pydantic.dataclasses` 直接替换 `dataclasses`; + +3. `Author` 数据类包含 `Item` 数据类列表; + +4. `Author` 数据类用于 `response_model` 参数; + +5. 其它带有数据类的标准类型注解也可以作为请求体; + + 本例使用的是 `Item` 数据类列表; + +6. 这行代码返回的是包含 `items` 的字典,`items` 是数据类列表; + + FastAPI 仍能把数据序列化为 JSON; + +7. 这行代码中,`response_model` 的类型注解是 `Author` 数据类列表; + + 再一次,可以把 `dataclasses` 与标准类型注解一起使用; + +8. 注意,*路径操作函数*使用的是普通函数,不是异步函数; + + 与往常一样,在 FastAPI 中,可以按需组合普通函数与异步函数; + + 如果不清楚何时使用异步函数或普通函数,请参阅**急不可待?**一节中对 `async` 与 `await` 的说明; + +9. *路径操作函数*返回的不是数据类(虽然它可以返回数据类),而是返回内含数据的字典列表; + + FastAPI 使用(包含数据类的) `response_model` 参数转换响应。 + +把 `dataclasses` 与其它类型注解组合在一起,可以组成不同形式的复杂数据结构。 + +更多内容详见上述代码内的注释。 + +## 深入学习 + +您还可以把 `dataclasses` 与其它 Pydantic 模型组合在一起,继承合并的模型,把它们包含在您自己的模型里。 + +详见 Pydantic 官档 - 数据类。 + +## 版本 + +本章内容自 FastAPI `0.67.0` 版起生效。🔖 diff --git a/docs/zh/docs/advanced/events.md b/docs/zh/docs/advanced/events.md new file mode 100644 index 000000000..5ade0f0ff --- /dev/null +++ b/docs/zh/docs/advanced/events.md @@ -0,0 +1,173 @@ +# 生命周期事件 + +你可以定义在应用**启动**前执行的逻辑(代码)。这意味着在应用**开始接收请求**之前,这些代码只会被执行**一次**。 + +同样地,你可以定义在应用**关闭**时应执行的逻辑。在这种情况下,这段代码将在**处理可能的多次请求后**执行**一次**。 + +因为这段代码在应用开始接收请求**之前**执行,也会在处理可能的若干请求**之后**执行,它覆盖了整个应用程序的**生命周期**("生命周期"这个词很重要😉)。 + +这对于设置你需要在整个应用中使用的**资源**非常有用,这些资源在请求之间**共享**,你可能需要在之后进行**释放**。例如,数据库连接池,或加载一个共享的机器学习模型。 + +## 用例 + +让我们从一个示例用例开始,看看如何解决它。 + +假设你有几个**机器学习的模型**,你想要用它们来处理请求。 + +相同的模型在请求之间是共享的,因此并非每个请求或每个用户各自拥有一个模型。 + +假设加载模型可能**需要相当长的时间**,因为它必须从**磁盘**读取大量数据。因此你不希望每个请求都加载它。 + +你可以在模块/文件的顶部加载它,但这也意味着即使你只是在运行一个简单的自动化测试,它也会**加载模型**,这样测试将**变慢**,因为它必须在能够独立运行代码的其他部分之前等待模型加载完成。 + +这就是我们要解决的问题——在处理请求前加载模型,但只是在应用开始接收请求前,而不是代码执行时。 + +## 生命周期 lifespan + +你可以使用`FastAPI()`应用的`lifespan`参数和一个上下文管理器(稍后我将为你展示)来定义**启动**和**关闭**的逻辑。 + +让我们从一个例子开始,然后详细介绍。 + +我们使用`yield`创建了一个异步函数`lifespan()`像这样: + +```Python hl_lines="16 19" +{!../../docs_src/events/tutorial003.py!} +``` + +在这里,我们在 `yield` 之前将(虚拟的)模型函数放入机器学习模型的字典中,以此模拟加载模型的耗时**启动**操作。这段代码将在应用程序**开始处理请求之前**执行,即**启动**期间。 + +然后,在 `yield` 之后,我们卸载模型。这段代码将会在应用程序**完成处理请求后**执行,即在**关闭**之前。这可以释放诸如内存或 GPU 之类的资源。 + +/// tip | 提示 + +**关闭**事件只会在你停止应用时触发。 + +可能你需要启动一个新版本,或者你只是你厌倦了运行它。 🤷 + +/// + +## 生命周期函数 + +首先要注意的是,我们定义了一个带有 `yield` 的异步函数。这与带有 `yield` 的依赖项非常相似。 + +```Python hl_lines="14-19" +{!../../docs_src/events/tutorial003.py!} +``` + +这个函数在 `yield`之前的部分,会在应用启动前执行。 + +剩下的部分在 `yield` 之后,会在应用完成后执行。 + +## 异步上下文管理器 + +如你所见,这个函数有一个装饰器 `@asynccontextmanager` 。 + +它将函数转化为所谓的“**异步上下文管理器**”。 + +```Python hl_lines="1 13" +{!../../docs_src/events/tutorial003.py!} +``` + +在 Python 中, **上下文管理器**是一个你可以在 `with` 语句中使用的东西,例如,`open()` 可以作为上下文管理器使用。 + +```Python +with open("file.txt") as file: + file.read() +``` + +Python 的最近几个版本也有了一个**异步上下文管理器**,你可以通过 `async with` 来使用: + +```Python +async with lifespan(app): + await do_stuff() +``` + +你可以像上面一样创建了一个上下文管理器或者异步上下文管理器,它的作用是在进入 `with` 块时,执行 `yield` 之前的代码,并且在离开 `with` 块时,执行 `yield` 后面的代码。 + +但在我们上面的例子里,我们并不是直接使用,而是传递给 FastAPI 来供其使用。 + +`FastAPI()` 的 `lifespan` 参数接受一个**异步上下文管理器**,所以我们可以把我们新定义的上下文管理器 `lifespan` 传给它。 + +```Python hl_lines="22" +{!../../docs_src/events/tutorial003.py!} +``` + +## 替代事件(弃用) + +/// warning | 警告 + +配置**启动**和**关闭**事件的推荐方法是使用 `FastAPI()` 应用的 `lifespan` 参数,如前所示。如果你提供了一个 `lifespan` 参数,启动(`startup`)和关闭(`shutdown`)事件处理器将不再生效。要么使用 `lifespan`,要么配置所有事件,两者不能共用。 + +你可以跳过这一部分。 + +/// + +有一种替代方法可以定义在**启动**和**关闭**期间执行的逻辑。 + +**FastAPI** 支持定义在应用启动前,或应用关闭时执行的事件处理器(函数)。 + +事件函数既可以声明为异步函数(`async def`),也可以声明为普通函数(`def`)。 + +### `startup` 事件 + +使用 `startup` 事件声明 `app` 启动前运行的函数: + +{* ../../docs_src/events/tutorial001.py hl[8] *} + +本例中,`startup` 事件处理器函数为项目数据库(只是**字典**)提供了一些初始值。 + +**FastAPI** 支持多个事件处理器函数。 + +只有所有 `startup` 事件处理器运行完毕,**FastAPI** 应用才开始接收请求。 + +### `shutdown` 事件 + +使用 `shutdown` 事件声明 `app` 关闭时运行的函数: + +{* ../../docs_src/events/tutorial002.py hl[6] *} + +此处,`shutdown` 事件处理器函数在 `log.txt` 中写入一行文本 `Application shutdown`。 + +/// info | 说明 + +`open()` 函数中,`mode="a"` 指的是**追加**。因此这行文本会添加在文件已有内容之后,不会覆盖之前的内容。 + +/// + +/// tip | 提示 + +注意,本例使用 Python `open()` 标准函数与文件交互。 + +这个函数执行 I/O(输入/输出)操作,需要等待内容写进磁盘。 + +但 `open()` 函数不支持使用 `async` 与 `await`。 + +因此,声明事件处理函数要使用 `def`,不能使用 `asnyc def`。 + +/// + +### `startup` 和 `shutdown` 一起使用 + +启动和关闭的逻辑很可能是连接在一起的,你可能希望启动某个东西然后结束它,获取一个资源然后释放它等等。 + +在不共享逻辑或变量的不同函数中处理这些逻辑比较困难,因为你需要在全局变量中存储值或使用类似的方式。 + +因此,推荐使用 `lifespan` 。 + +## 技术细节 + +只是为好奇者提供的技术细节。🤓 + +在底层,这部分是生命周期协议的一部分,参见 ASGI 技术规范,定义了称为启动(`startup`)和关闭(`shutdown`)的事件。 + +/// info | 说明 + +有关事件处理器的详情,请参阅 Starlette 官档 - 事件。 + +包括如何处理生命周期状态,这可以用于程序的其他部分。 + +/// + +## 子应用 + +🚨 **FastAPI** 只会触发主应用中的生命周期事件,不包括[子应用 - 挂载](sub-applications.md){.internal-link target=_blank}中的。 diff --git a/docs/zh/docs/advanced/generate-clients.md b/docs/zh/docs/advanced/generate-clients.md index e222e479c..bcb9ba2bf 100644 --- a/docs/zh/docs/advanced/generate-clients.md +++ b/docs/zh/docs/advanced/generate-clients.md @@ -10,23 +10,13 @@ 一个常见的工具是 OpenAPI Generator。 -如果您正在开发**前端**,一个非常有趣的替代方案是 openapi-typescript-codegen。 +如果您正在开发**前端**,一个非常有趣的替代方案是 openapi-ts。 ## 生成一个 TypeScript 前端客户端 让我们从一个简单的 FastAPI 应用开始: -=== "Python 3.9+" - - ```Python hl_lines="7-9 12-13 16-17 21" - {!> ../../../docs_src/generate_clients/tutorial001_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="9-11 14-15 18 19 23" - {!> ../../../docs_src/generate_clients/tutorial001.py!} - ``` +{* ../../docs_src/generate_clients/tutorial001_py39.py hl[7:9,12:13,16:17,21] *} 请注意,*路径操作* 定义了他们所用于请求数据和回应数据的模型,所使用的模型是`Item` 和 `ResponseMessage`。 @@ -46,14 +36,14 @@ OpenAPI中所包含的模型里有相同的信息可以用于 **生成客户端 现在我们有了带有模型的应用,我们可以为前端生成客户端代码。 -#### 安装 `openapi-typescript-codegen` +#### 安装 `openapi-ts` -您可以使用以下工具在前端代码中安装 `openapi-typescript-codegen`: +您可以使用以下工具在前端代码中安装 `openapi-ts`:
```console -$ npm install openapi-typescript-codegen --save-dev +$ npm install @hey-api/openapi-ts --save-dev ---> 100% ``` @@ -62,7 +52,7 @@ $ npm install openapi-typescript-codegen --save-dev #### 生成客户端代码 -要生成客户端代码,您可以使用现在将要安装的命令行应用程序 `openapi`。 +要生成客户端代码,您可以使用现在将要安装的命令行应用程序 `openapi-ts`。 因为它安装在本地项目中,所以您可能无法直接使用此命令,但您可以将其放在 `package.json` 文件中。 @@ -75,12 +65,12 @@ $ npm install openapi-typescript-codegen --save-dev "description": "", "main": "index.js", "scripts": { - "generate-client": "openapi --input http://localhost:8000/openapi.json --output ./src/client --client axios" + "generate-client": "openapi-ts --input http://localhost:8000/openapi.json --output ./src/client --client axios" }, "author": "", "license": "", "devDependencies": { - "openapi-typescript-codegen": "^0.20.1", + "@hey-api/openapi-ts": "^0.27.38", "typescript": "^4.6.2" } } @@ -94,7 +84,7 @@ $ npm install openapi-typescript-codegen --save-dev $ npm run generate-client frontend-app@1.0.0 generate-client /home/user/code/frontend-app -> openapi --input http://localhost:8000/openapi.json --output ./src/client --client axios +> openapi-ts --input http://localhost:8000/openapi.json --output ./src/client --client axios ```
@@ -111,8 +101,11 @@ frontend-app@1.0.0 generate-client /home/user/code/frontend-app -!!! tip - 请注意, `name` 和 `price` 的自动补全,是通过其在`Item`模型(FastAPI)中的定义实现的。 +/// tip + +请注意, `name` 和 `price` 的自动补全,是通过其在`Item`模型(FastAPI)中的定义实现的。 + +/// 如果发送的数据字段不符,你也会看到编辑器的错误提示: @@ -128,17 +121,7 @@ frontend-app@1.0.0 generate-client /home/user/code/frontend-app 例如,您可以有一个用 `items` 的部分和另一个用于 `users` 的部分,它们可以用标签来分隔: -=== "Python 3.9+" - - ```Python hl_lines="21 26 34" - {!> ../../../docs_src/generate_clients/tutorial002_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="23 28 36" - {!> ../../../docs_src/generate_clients/tutorial002.py!} - ``` +{* ../../docs_src/generate_clients/tutorial002_py39.py hl[21,26,34] *} ### 生成带有标签的 TypeScript 客户端 @@ -185,17 +168,7 @@ FastAPI为每个*路径操作*使用一个**唯一ID**,它用于**操作ID** 然后,你可以将这个自定义函数作为 `generate_unique_id_function` 参数传递给 **FastAPI**: -=== "Python 3.9+" - - ```Python hl_lines="6-7 10" - {!> ../../../docs_src/generate_clients/tutorial003_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="8-9 12" - {!> ../../../docs_src/generate_clients/tutorial003.py!} - ``` +{* ../../docs_src/generate_clients/tutorial003_py39.py hl[6:7,10] *} ### 使用自定义操作ID生成TypeScript客户端 @@ -217,9 +190,7 @@ FastAPI为每个*路径操作*使用一个**唯一ID**,它用于**操作ID** 我们可以将 OpenAPI JSON 下载到一个名为`openapi.json`的文件中,然后使用以下脚本**删除此前缀的标签**: -```Python -{!../../../docs_src/generate_clients/tutorial004.py!} -``` +{* ../../docs_src/generate_clients/tutorial004.py *} 通过这样做,操作ID将从类似于 `items-get_items` 的名称重命名为 `get_items` ,这样客户端生成器就可以生成更简洁的方法名称。 @@ -234,12 +205,12 @@ FastAPI为每个*路径操作*使用一个**唯一ID**,它用于**操作ID** "description": "", "main": "index.js", "scripts": { - "generate-client": "openapi --input ./openapi.json --output ./src/client --client axios" + "generate-client": "openapi-ts --input ./openapi.json --output ./src/client --client axios" }, "author": "", "license": "", "devDependencies": { - "openapi-typescript-codegen": "^0.20.1", + "@hey-api/openapi-ts": "^0.27.38", "typescript": "^4.6.2" } } diff --git a/docs/zh/docs/advanced/index.md b/docs/zh/docs/advanced/index.md index 824f91f47..6525802fc 100644 --- a/docs/zh/docs/advanced/index.md +++ b/docs/zh/docs/advanced/index.md @@ -2,17 +2,20 @@ ## 额外特性 -主要的教程 [教程 - 用户指南](../tutorial/){.internal-link target=_blank} 应该足以让你了解 **FastAPI** 的所有主要特性。 +主要的教程 [教程 - 用户指南](../tutorial/index.md){.internal-link target=_blank} 应该足以让你了解 **FastAPI** 的所有主要特性。 你会在接下来的章节中了解到其他的选项、配置以及额外的特性。 -!!! tip - 接下来的章节**并不一定是**「高级的」。 +/// tip - 而且对于你的使用场景来说,解决方案很可能就在其中。 +接下来的章节**并不一定是**「高级的」。 + +而且对于你的使用场景来说,解决方案很可能就在其中。 + +/// ## 先阅读教程 -你可能仍会用到 **FastAPI** 主教程 [教程 - 用户指南](../tutorial/){.internal-link target=_blank} 中的大多数特性。 +你可能仍会用到 **FastAPI** 主教程 [教程 - 用户指南](../tutorial/index.md){.internal-link target=_blank} 中的大多数特性。 -接下来的章节我们认为你已经读过 [教程 - 用户指南](../tutorial/){.internal-link target=_blank},并且假设你已经知晓其中主要思想。 +接下来的章节我们认为你已经读过 [教程 - 用户指南](../tutorial/index.md){.internal-link target=_blank},并且假设你已经知晓其中主要思想。 diff --git a/docs/zh/docs/advanced/middleware.md b/docs/zh/docs/advanced/middleware.md new file mode 100644 index 000000000..c7b15b929 --- /dev/null +++ b/docs/zh/docs/advanced/middleware.md @@ -0,0 +1,95 @@ +# 高级中间件 + +用户指南介绍了如何为应用添加[自定义中间件](../tutorial/middleware.md){.internal-link target=_blank} 。 + +以及如何[使用 `CORSMiddleware` 处理 CORS](../tutorial/cors.md){.internal-link target=_blank}。 + +本章学习如何使用其它中间件。 + +## 添加 ASGI 中间件 + +因为 **FastAPI** 基于 Starlette,且执行 ASGI 规范,所以可以使用任意 ASGI 中间件。 + +中间件不必是专为 FastAPI 或 Starlette 定制的,只要遵循 ASGI 规范即可。 + +总之,ASGI 中间件是类,并把 ASGI 应用作为第一个参数。 + +因此,有些第三方 ASGI 中间件的文档推荐以如下方式使用中间件: + +```Python +from unicorn import UnicornMiddleware + +app = SomeASGIApp() + +new_app = UnicornMiddleware(app, some_config="rainbow") +``` + +但 FastAPI(实际上是 Starlette)提供了一种更简单的方式,能让内部中间件在处理服务器错误的同时,还能让自定义异常处理器正常运作。 + +为此,要使用 `app.add_middleware()` (与 CORS 中的示例一样)。 + +```Python +from fastapi import FastAPI +from unicorn import UnicornMiddleware + +app = FastAPI() + +app.add_middleware(UnicornMiddleware, some_config="rainbow") +``` + +`app.add_middleware()` 的第一个参数是中间件的类,其它参数则是要传递给中间件的参数。 + +## 集成中间件 + +**FastAPI** 为常见用例提供了一些中间件,下面介绍怎么使用这些中间件。 + +/// note | 技术细节 + +以下几个示例中也可以使用 `from starlette.middleware.something import SomethingMiddleware`。 + +**FastAPI** 在 `fastapi.middleware` 中提供的中间件只是为了方便开发者使用,但绝大多数可用的中间件都直接继承自 Starlette。 + +/// + +## `HTTPSRedirectMiddleware` + +强制所有传入请求必须是 `https` 或 `wss`。 + +任何传向 `http` 或 `ws` 的请求都会被重定向至安全方案。 + +{* ../../docs_src/advanced_middleware/tutorial001.py hl[2,6] *} + +## `TrustedHostMiddleware` + +强制所有传入请求都必须正确设置 `Host` 请求头,以防 HTTP 主机头攻击。 + +{* ../../docs_src/advanced_middleware/tutorial002.py hl[2,6:8] *} + +支持以下参数: + +* `allowed_hosts` - 允许的域名(主机名)列表。`*.example.com` 等通配符域名可以匹配子域名,或使用 `allowed_hosts=["*"]` 允许任意主机名,或省略中间件。 + +如果传入的请求没有通过验证,则发送 `400` 响应。 + +## `GZipMiddleware` + +处理 `Accept-Encoding` 请求头中包含 `gzip` 请求的 GZip 响应。 + +中间件会处理标准响应与流响应。 + +{* ../../docs_src/advanced_middleware/tutorial003.py hl[2,6] *} + +支持以下参数: + +* `minimum_size` - 小于最小字节的响应不使用 GZip。 默认值是 `500`。 + +## 其它中间件 + +除了上述中间件外,FastAPI 还支持其它ASGI 中间件。 + +例如: + +* Uvicorn 的 `ProxyHeadersMiddleware` +* MessagePack + +其它可用中间件详见 Starlette 官档 -  中间件ASGI Awesome 列表。 diff --git a/docs/zh/docs/advanced/openapi-callbacks.md b/docs/zh/docs/advanced/openapi-callbacks.md new file mode 100644 index 000000000..f021eb10a --- /dev/null +++ b/docs/zh/docs/advanced/openapi-callbacks.md @@ -0,0 +1,186 @@ +# OpenAPI 回调 + +您可以创建触发外部 API 请求的*路径操作* API,这个外部 API 可以是别人创建的,也可以是由您自己创建的。 + +API 应用调用外部 API 时的流程叫做**回调**。因为外部开发者编写的软件发送请求至您的 API,然后您的 API 要进行回调,并把请求发送至外部 API。 + +此时,我们需要存档外部 API 的*信息*,比如应该有哪些*路径操作*,返回什么样的请求体,应该返回哪种响应等。 + +## 使用回调的应用 + +示例如下。 + +假设要开发一个创建发票的应用。 + +发票包括 `id`、`title`(可选)、`customer`、`total` 等属性。 + +API 的用户 (外部开发者)要在您的 API 内使用 POST 请求创建一条发票记录。 + +(假设)您的 API 将: + +* 把发票发送至外部开发者的消费者 +* 归集现金 +* 把通知发送至 API 的用户(外部开发者) + * 通过(从您的 API)发送 POST 请求至外部 API (即**回调**)来完成 + +## 常规 **FastAPI** 应用 + +添加回调前,首先看下常规 API 应用是什么样子。 + +常规 API 应用包含接收 `Invoice` 请求体的*路径操作*,还有包含回调 URL 的查询参数 `callback_url`。 + +这部分代码很常规,您对绝大多数代码应该都比较熟悉了: + +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[10:14,37:54] *} + +/// tip | 提示 + +`callback_url` 查询参数使用 Pydantic 的 URL 类型。 + +/// + +此处唯一比较新的内容是*路径操作装饰器*中的 `callbacks=invoices_callback_router.routes` 参数,下文介绍。 + +## 存档回调 + +实际的回调代码高度依赖于您自己的 API 应用。 + +并且可能每个应用都各不相同。 + +回调代码可能只有一两行,比如: + +```Python +callback_url = "https://example.com/api/v1/invoices/events/" +requests.post(callback_url, json={"description": "Invoice paid", "paid": True}) +``` + +但回调最重要的部分可能是,根据 API 要发送给回调请求体的数据等内容,确保您的 API 用户(外部开发者)正确地实现*外部 API*。 + +因此,我们下一步要做的就是添加代码,为从 API 接收回调的*外部 API*存档。 + +这部分文档在 `/docs` 下的 Swagger API 文档中显示,并且会告诉外部开发者如何构建*外部 API*。 + +本例没有实现回调本身(只是一行代码),只有文档部分。 + +/// tip | 提示 + +实际的回调只是 HTTP 请求。 + +实现回调时,要使用 HTTPXRequests。 + +/// + +## 编写回调文档代码 + +应用不执行这部分代码,只是用它来*记录 外部 API* 。 + +但,您已经知道用 **FastAPI** 创建自动 API 文档有多简单了。 + +我们要使用与存档*外部 API* 相同的知识……通过创建外部 API 要实现的*路径操作*(您的 API 要调用的)。 + +/// tip | 提示 + +编写存档回调的代码时,假设您是*外部开发者*可能会用的上。并且您当前正在实现的是*外部 API*,不是*您自己的 API*。 + +临时改变(为外部开发者的)视角能让您更清楚该如何放置*外部 API* 响应和请求体的参数与 Pydantic 模型等。 + +/// + +### 创建回调的 `APIRouter` + +首先,新建包含一些用于回调的 `APIRouter`。 + +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[5,26] *} + +### 创建回调*路径操作* + +创建回调*路径操作*也使用之前创建的 `APIRouter`。 + +它看起来和常规 FastAPI *路径操作*差不多: + +* 声明要接收的请求体,例如,`body: InvoiceEvent` +* 还要声明要返回的响应,例如,`response_model=InvoiceEventReceived` + +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[17:19,22:23,29:33] *} + +回调*路径操作*与常规*路径操作*有两点主要区别: + +* 它不需要任何实际的代码,因为应用不会调用这段代码。它只是用于存档*外部 API*。因此,函数的内容只需要 `pass` 就可以了 +* *路径*可以包含 OpenAPI 3 表达式(详见下文),可以使用带参数的变量,以及发送至您的 API 的原始请求的部分 + +### 回调路径表达式 + +回调*路径*支持包含发送给您的 API 的原始请求的部分的 OpenAPI 3 表达式。 + +本例中是**字符串**: + +```Python +"{$callback_url}/invoices/{$request.body.id}" +``` + +因此,如果您的 API 用户(外部开发者)发送请求到您的 API: + +``` +https://yourapi.com/invoices/?callback_url=https://www.external.org/events +``` + +使用如下 JSON 请求体: + +```JSON +{ + "id": "2expen51ve", + "customer": "Mr. Richie Rich", + "total": "9999" +} +``` + +然后,您的 API 就会处理发票,并在某个点之后,发送回调请求至 `callback_url`(外部 API): + +``` +https://www.external.org/events/invoices/2expen51ve +``` + +JSON 请求体包含如下内容: + +```JSON +{ + "description": "Payment celebration", + "paid": true +} +``` + +它会预期*外部 API* 的响应包含如下 JSON 请求体: + +```JSON +{ + "ok": true +} +``` + +/// tip | 提示 + +注意,回调 URL包含 `callback_url` (`https://www.external.org/events`)中的查询参数,还有 JSON 请求体内部的发票 ID(`2expen51ve`)。 + +/// + +### 添加回调路由 + +至此,在上文创建的回调路由里就包含了*回调路径操作*(外部开发者要在外部 API 中实现)。 + +现在使用 API *路径操作装饰器*的参数 `callbacks`,从回调路由传递属性 `.routes`(实际上只是路由/路径操作的**列表**): + +{* ../../docs_src/openapi_callbacks/tutorial001.py hl[36] *} + +/// tip | 提示 + +注意,不能把路由本身(`invoices_callback_router`)传递给 `callback=`,要传递 `invoices_callback_router.routes` 中的 `.routes` 属性。 + +/// + +### 查看文档 + +现在,使用 Uvicorn 启动应用,打开 http://127.0.0.1:8000/docs。 + +就能看到文档的*路径操作*已经包含了**回调**的内容以及*外部 API*: + + diff --git a/docs/zh/docs/advanced/openapi-webhooks.md b/docs/zh/docs/advanced/openapi-webhooks.md new file mode 100644 index 000000000..92ae8db15 --- /dev/null +++ b/docs/zh/docs/advanced/openapi-webhooks.md @@ -0,0 +1,55 @@ +# OpenAPI 网络钩子 + +有些情况下,您可能想告诉您的 API **用户**,您的应用程序可以携带一些数据调用*他们的*应用程序(给它们发送请求),通常是为了**通知**某种**事件**。 + +这意味着,除了您的用户向您的 API 发送请求的一般情况,**您的 API**(或您的应用)也可以向**他们的系统**(他们的 API、他们的应用)**发送请求**。 + +这通常被称为**网络钩子**(Webhook)。 + +## 使用网络钩子的步骤 + +通常的过程是**您**在代码中**定义**要发送的消息,即**请求的主体**。 + +您还需要以某种方式定义您的应用程序将在**何时**发送这些请求或事件。 + +**用户**会以某种方式(例如在某个网页仪表板上)定义您的应用程序发送这些请求应该使用的 **URL**。 + +所有关于注册网络钩子的 URL 的**逻辑**以及发送这些请求的实际代码都由您决定。您可以在**自己的代码**中以任何想要的方式来编写它。 + +## 使用 `FastAPI` 和 OpenAPI 文档化网络钩子 + +使用 **FastAPI**,您可以利用 OpenAPI 来自定义这些网络钩子的名称、您的应用可以发送的 HTTP 操作类型(例如 `POST`、`PUT` 等)以及您的应用将发送的**请求体**。 + +这能让您的用户更轻松地**实现他们的 API** 来接收您的**网络钩子**请求,他们甚至可能能够自动生成一些自己的 API 代码。 + +/// info + +网络钩子在 OpenAPI 3.1.0 及以上版本中可用,FastAPI `0.99.0` 及以上版本支持。 + +/// + +## 带有网络钩子的应用程序 + +当您创建一个 **FastAPI** 应用程序时,有一个 `webhooks` 属性可以用来定义网络钩子,方式与您定义*路径操作*的时候相同,例如使用 `@app.webhooks.post()` 。 + +{* ../../docs_src/openapi_webhooks/tutorial001.py hl[9:13,36:53] *} + +您定义的网络钩子将被包含在 `OpenAPI` 的架构中,并出现在自动生成的**文档 UI** 中。 + +/// info + +`app.webhooks` 对象实际上只是一个 `APIRouter` ,与您在使用多个文件来构建应用程序时所使用的类型相同。 + +/// + +请注意,使用网络钩子时,您实际上并没有声明一个*路径*(比如 `/items/` ),您传递的文本只是这个网络钩子的**标识符**(事件的名称)。例如在 `@app.webhooks.post("new-subscription")` 中,网络钩子的名称是 `new-subscription` 。 + +这是因为我们预计**您的用户**会以其他方式(例如通过网页仪表板)来定义他们希望接收网络钩子的请求的实际 **URL 路径**。 + +### 查看文档 + +现在您可以启动您的应用程序并访问 http://127.0.0.1:8000/docs. + +您会看到您的文档不仅有正常的*路径操作*显示,现在还多了一些**网络钩子**: + + diff --git a/docs/zh/docs/advanced/path-operation-advanced-configuration.md b/docs/zh/docs/advanced/path-operation-advanced-configuration.md index 7da9f251e..12600eddb 100644 --- a/docs/zh/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/zh/docs/advanced/path-operation-advanced-configuration.md @@ -2,16 +2,17 @@ ## OpenAPI 的 operationId -!!! warning - 如果你并非 OpenAPI 的「专家」,你可能不需要这部分内容。 +/// warning + +如果你并非 OpenAPI 的「专家」,你可能不需要这部分内容。 + +/// 你可以在路径操作中通过参数 `operation_id` 设置要使用的 OpenAPI `operationId`。 务必确保每个操作路径的 `operation_id` 都是唯一的。 -```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial001.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial001.py hl[6] *} ### 使用 *路径操作函数* 的函数名作为 operationId @@ -19,25 +20,27 @@ 你应该在添加了所有 *路径操作* 之后执行此操作。 -```Python hl_lines="2 12 13 14 15 16 17 18 19 20 21 24" -{!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial002.py hl[2,12,13,14,15,16,17,18,19,20,21,24] *} + +/// tip + +如果你手动调用 `app.openapi()`,你应该在此之前更新 `operationId`。 + +/// + +/// warning -!!! tip - 如果你手动调用 `app.openapi()`,你应该在此之前更新 `operationId`。 +如果你这样做,务必确保你的每个 *路径操作函数* 的名字唯一。 -!!! warning - 如果你这样做,务必确保你的每个 *路径操作函数* 的名字唯一。 +即使它们在不同的模块中(Python 文件)。 - 即使它们在不同的模块中(Python 文件)。 +/// ## 从 OpenAPI 中排除 使用参数 `include_in_schema` 并将其设置为 `False` ,来从生成的 OpenAPI 方案中排除一个 *路径操作*(这样一来,就从自动化文档系统中排除掉了)。 -```Python hl_lines="6" -{!../../../docs_src/path_operation_advanced_configuration/tutorial003.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial003.py hl[6] *} ## docstring 的高级描述 @@ -48,6 +51,4 @@ 剩余部分不会出现在文档中,但是其他工具(比如 Sphinx)可以使用剩余部分。 -```Python hl_lines="19 20 21 22 23 24 25 26 27 28 29" -{!../../../docs_src/path_operation_advanced_configuration/tutorial004.py!} -``` +{* ../../docs_src/path_operation_advanced_configuration/tutorial004.py hl[19,20,21,22,23,24,25,26,27,28,29] *} diff --git a/docs/zh/docs/advanced/response-change-status-code.md b/docs/zh/docs/advanced/response-change-status-code.md index a289cf201..cc1f2a73e 100644 --- a/docs/zh/docs/advanced/response-change-status-code.md +++ b/docs/zh/docs/advanced/response-change-status-code.md @@ -20,9 +20,7 @@ 然后你可以在这个*临时*响应对象中设置`status_code`。 -```Python hl_lines="1 9 12" -{!../../../docs_src/response_change_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_change_status_code/tutorial001.py hl[1,9,12] *} 然后你可以像平常一样返回任何你需要的对象(例如一个`dict`或者一个数据库模型)。如果你声明了一个`response_model`,它仍然会被用来过滤和转换你返回的对象。 diff --git a/docs/zh/docs/advanced/response-cookies.md b/docs/zh/docs/advanced/response-cookies.md index 3e53c5319..d4b93d003 100644 --- a/docs/zh/docs/advanced/response-cookies.md +++ b/docs/zh/docs/advanced/response-cookies.md @@ -4,9 +4,7 @@ 你可以在 *路径函数* 中定义一个类型为 `Response`的参数,这样你就可以在这个临时响应对象中设置cookie了。 -```Python hl_lines="1 8-9" -{!../../../docs_src/response_cookies/tutorial002.py!} -``` +{* ../../docs_src/response_cookies/tutorial002.py hl[1,8:9] *} 而且你还可以根据你的需要响应不同的对象,比如常用的 `dict`,数据库model等。 @@ -24,24 +22,28 @@ 然后设置Cookies,并返回: -```Python hl_lines="10-12" -{!../../../docs_src/response_cookies/tutorial001.py!} -``` +{* ../../docs_src/response_cookies/tutorial001.py hl[10:12] *} -!!! tip - 需要注意,如果你直接反馈一个response对象,而不是使用`Response`入参,FastAPI则会直接反馈你封装的response对象。 +/// tip - 所以你需要确保你响应数据类型的正确性,如:你可以使用`JSONResponse`来兼容JSON的场景。 +需要注意,如果你直接反馈一个response对象,而不是使用`Response`入参,FastAPI则会直接反馈你封装的response对象。 - 同时,你也应当仅反馈通过`response_model`过滤过的数据。 +所以你需要确保你响应数据类型的正确性,如:你可以使用`JSONResponse`来兼容JSON的场景。 + +同时,你也应当仅反馈通过`response_model`过滤过的数据。 + +/// ### 更多信息 -!!! note "技术细节" - 你也可以使用`from starlette.responses import Response` 或者 `from starlette.responses import JSONResponse`。 +/// note | 技术细节 + +你也可以使用`from starlette.responses import Response` 或者 `from starlette.responses import JSONResponse`。 + +为了方便开发者,**FastAPI** 封装了相同数据类型,如`starlette.responses` 和 `fastapi.responses`。不过大部分response对象都是直接引用自Starlette。 - 为了方便开发者,**FastAPI** 封装了相同数据类型,如`starlette.responses` 和 `fastapi.responses`。不过大部分response对象都是直接引用自Starlette。 +因为`Response`对象可以非常便捷的设置headers和cookies,所以 **FastAPI** 同时也封装了`fastapi.Response`。 - 因为`Response`对象可以非常便捷的设置headers和cookies,所以 **FastAPI** 同时也封装了`fastapi.Response`。 +/// 如果你想查看所有可用的参数和选项,可以参考 Starlette帮助文档 diff --git a/docs/zh/docs/advanced/response-directly.md b/docs/zh/docs/advanced/response-directly.md index 797a878eb..4d9cd53f2 100644 --- a/docs/zh/docs/advanced/response-directly.md +++ b/docs/zh/docs/advanced/response-directly.md @@ -14,8 +14,11 @@ 事实上,你可以返回任意 `Response` 或者任意 `Response` 的子类。 -!!! tip "小贴士" - `JSONResponse` 本身是一个 `Response` 的子类。 +/// tip | 小贴士 + +`JSONResponse` 本身是一个 `Response` 的子类。 + +/// 当你返回一个 `Response` 时,**FastAPI** 会直接传递它。 @@ -32,14 +35,15 @@ 对于这些情况,在将数据传递给响应之前,你可以使用 `jsonable_encoder` 来转换你的数据。 -```Python hl_lines="4 6 20 21" -{!../../../docs_src/response_directly/tutorial001.py!} -``` +{* ../../docs_src/response_directly/tutorial001.py hl[4,6,20,21] *} + +/// note | 技术细节 + +你也可以使用 `from starlette.responses import JSONResponse`。 -!!! note "技术细节" - 你也可以使用 `from starlette.responses import JSONResponse`。 +出于方便,**FastAPI** 会提供与 `starlette.responses` 相同的 `fastapi.responses` 给开发者。但是大多数可用的响应都直接来自 Starlette。 - 出于方便,**FastAPI** 会提供与 `starlette.responses` 相同的 `fastapi.responses` 给开发者。但是大多数可用的响应都直接来自 Starlette。 +/// ## 返回自定义 `Response` @@ -51,9 +55,7 @@ 你可以把你的 XML 内容放到一个字符串中,放到一个 `Response` 中,然后返回。 -```Python hl_lines="1 18" -{!../../../docs_src/response_directly/tutorial002.py!} -``` +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} ## 说明 diff --git a/docs/zh/docs/advanced/response-headers.md b/docs/zh/docs/advanced/response-headers.md index 85dab15ac..fe2cb0da8 100644 --- a/docs/zh/docs/advanced/response-headers.md +++ b/docs/zh/docs/advanced/response-headers.md @@ -5,9 +5,7 @@ 你可以在你的*路径操作函数*中声明一个`Response`类型的参数(就像你可以为cookies做的那样)。 然后你可以在这个*临时*响应对象中设置头部。 -```Python hl_lines="1 7-8" -{!../../../docs_src/response_headers/tutorial002.py!} -``` +{* ../../docs_src/response_headers/tutorial002.py hl[1,7:8] *} 然后你可以像平常一样返回任何你需要的对象(例如一个`dict`或者一个数据库模型)。如果你声明了一个`response_model`,它仍然会被用来过滤和转换你返回的对象。 @@ -20,17 +18,19 @@ 你也可以在直接返回`Response`时添加头部。 按照[直接返回响应](response-directly.md){.internal-link target=_blank}中所述创建响应,并将头部作为附加参数传递: -```Python hl_lines="10-12" -{!../../../docs_src/response_headers/tutorial001.py!} -``` +{* ../../docs_src/response_headers/tutorial001.py hl[10:12] *} -!!! 注意 "技术细节" - 你也可以使用`from starlette.responses import Response`或`from starlette.responses import JSONResponse`。 - **FastAPI**提供了与`fastapi.responses`相同的`starlette.responses`,只是为了方便开发者。但是,大多数可用的响应都直接来自Starlette。 +/// note | 技术细节 - 由于`Response`经常用于设置头部和cookies,因此**FastAPI**还在`fastapi.Response`中提供了它。 +你也可以使用`from starlette.responses import Response`或`from starlette.responses import JSONResponse`。 + +**FastAPI**提供了与`fastapi.responses`相同的`starlette.responses`,只是为了方便开发者。但是,大多数可用的响应都直接来自Starlette。 + +由于`Response`经常用于设置头部和cookies,因此**FastAPI**还在`fastapi.Response`中提供了它。 + +/// ## 自定义头部 diff --git a/docs/zh/docs/advanced/security/http-basic-auth.md b/docs/zh/docs/advanced/security/http-basic-auth.md new file mode 100644 index 000000000..599429f9d --- /dev/null +++ b/docs/zh/docs/advanced/security/http-basic-auth.md @@ -0,0 +1,107 @@ +# HTTP 基础授权 + +最简单的用例是使用 HTTP 基础授权(HTTP Basic Auth)。 + +在 HTTP 基础授权中,应用需要请求头包含用户名与密码。 + +如果没有接收到 HTTP 基础授权,就返回 HTTP 401 `"Unauthorized"` 错误。 + +并返回含 `Basic` 值的请求头 `WWW-Authenticate`以及可选的 `realm` 参数。 + +HTTP 基础授权让浏览器显示内置的用户名与密码提示。 + +输入用户名与密码后,浏览器会把它们自动发送至请求头。 + +## 简单的 HTTP 基础授权 + +* 导入 `HTTPBasic` 与 `HTTPBasicCredentials` +* 使用 `HTTPBasic` 创建**安全概图** +* 在*路径操作*的依赖项中使用 `security` +* 返回类型为 `HTTPBasicCredentials` 的对象: + * 包含发送的 `username` 与 `password` + +{* ../../docs_src/security/tutorial006_an_py39.py hl[4,8,12] *} + +第一次打开 URL(或在 API 文档中点击 **Execute** 按钮)时,浏览器要求输入用户名与密码: + + + +## 检查用户名 + +以下是更完整的示例。 + +使用依赖项检查用户名与密码是否正确。 + +为此要使用 Python 标准模块 `secrets` 检查用户名与密码。 + +`secrets.compare_digest()` 需要仅包含 ASCII 字符(英语字符)的 `bytes` 或 `str`,这意味着它不适用于像`á`一样的字符,如 `Sebastián`。 + +为了解决这个问题,我们首先将 `username` 和 `password` 转换为使用 UTF-8 编码的 `bytes` 。 + +然后我们可以使用 `secrets.compare_digest()` 来确保 `credentials.username` 是 `"stanleyjobson"`,且 `credentials.password` 是`"swordfish"`。 + +{* ../../docs_src/security/tutorial007_an_py39.py hl[1,12:24] *} + +这类似于: + +```Python +if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"): + # Return some error + ... +``` + +但使用 `secrets.compare_digest()`,可以防御**时差攻击**,更加安全。 + +### 时差攻击 + +什么是**时差攻击**? + +假设攻击者试图猜出用户名与密码。 + +他们发送用户名为 `johndoe`,密码为 `love123` 的请求。 + +然后,Python 代码执行如下操作: + +```Python +if "johndoe" == "stanleyjobson" and "love123" == "swordfish": + ... +``` + +但就在 Python 比较完 `johndoe` 的第一个字母 `j` 与 `stanleyjobson` 的 `s` 时,Python 就已经知道这两个字符串不相同了,它会这么想,**没必要浪费更多时间执行剩余字母的对比计算了**。应用立刻就会返回**错误的用户或密码**。 + +但接下来,攻击者继续尝试 `stanleyjobsox` 和 密码 `love123`。 + +应用代码会执行类似下面的操作: + +```Python +if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": + ... +``` + +此时,Python 要对比 `stanleyjobsox` 与 `stanleyjobson` 中的 `stanleyjobso`,才能知道这两个字符串不一样。因此会多花费几微秒来返回**错误的用户或密码**。 + +#### 反应时间对攻击者的帮助 + +通过服务器花费了更多微秒才发送**错误的用户或密码**响应,攻击者会知道猜对了一些内容,起码开头字母是正确的。 + +然后,他们就可以放弃 `johndoe`,再用类似 `stanleyjobsox` 的内容进行尝试。 + +#### **专业**攻击 + +当然,攻击者不用手动操作,而是编写每秒能执行成千上万次测试的攻击程序,每次都会找到更多正确字符。 + +但是,在您的应用的**帮助**下,攻击者利用时间差,就能在几分钟或几小时内,以这种方式猜出正确的用户名和密码。 + +#### 使用 `secrets.compare_digest()` 修补 + +在此,代码中使用了 `secrets.compare_digest()`。 + +简单的说,它使用相同的时间对比 `stanleyjobsox` 和 `stanleyjobson`,还有 `johndoe` 和 `stanleyjobson`。对比密码时也一样。 + +在代码中使用 `secrets.compare_digest()` ,就可以安全地防御全面攻击了。 + +### 返回错误 + +检测到凭证不正确后,返回 `HTTPException` 及状态码 401(与无凭证时返回的内容一样),并添加请求头 `WWW-Authenticate`,让浏览器再次显示登录提示: + +{* ../../docs_src/security/tutorial007_an_py39.py hl[26:30] *} diff --git a/docs/zh/docs/advanced/security/index.md b/docs/zh/docs/advanced/security/index.md index fdc8075c7..267e7ced7 100644 --- a/docs/zh/docs/advanced/security/index.md +++ b/docs/zh/docs/advanced/security/index.md @@ -2,15 +2,18 @@ ## 附加特性 -除 [教程 - 用户指南: 安全性](../../tutorial/security/){.internal-link target=_blank} 中涵盖的功能之外,还有一些额外的功能来处理安全性. +除 [教程 - 用户指南: 安全性](../../tutorial/security/index.md){.internal-link target=_blank} 中涵盖的功能之外,还有一些额外的功能来处理安全性. -!!! tip "小贴士" - 接下来的章节 **并不一定是 "高级的"**. +/// tip | 小贴士 - 而且对于你的使用场景来说,解决方案很可能就在其中。 +接下来的章节 **并不一定是 "高级的"**. + +而且对于你的使用场景来说,解决方案很可能就在其中。 + +/// ## 先阅读教程 -接下来的部分假设你已经阅读了主要的 [教程 - 用户指南: 安全性](../../tutorial/security/){.internal-link target=_blank}. +接下来的部分假设你已经阅读了主要的 [教程 - 用户指南: 安全性](../../tutorial/security/index.md){.internal-link target=_blank}. 它们都基于相同的概念,但支持一些额外的功能. diff --git a/docs/zh/docs/advanced/security/oauth2-scopes.md b/docs/zh/docs/advanced/security/oauth2-scopes.md new file mode 100644 index 000000000..784c38490 --- /dev/null +++ b/docs/zh/docs/advanced/security/oauth2-scopes.md @@ -0,0 +1,274 @@ +# OAuth2 作用域 + +**FastAPI** 无缝集成 OAuth2 作用域(`Scopes`),可以直接使用。 + +作用域是更精密的权限系统,遵循 OAuth2 标准,与 OpenAPI 应用(和 API 自动文档)集成。 + +OAuth2 也是脸书、谷歌、GitHub、微软、推特等第三方身份验证应用使用的机制。这些身份验证应用在用户登录应用时使用 OAuth2 提供指定权限。 + +脸书、谷歌、GitHub、微软、推特就是 OAuth2 作用域登录。 + +本章介绍如何在 **FastAPI** 应用中使用 OAuth2 作用域管理验证与授权。 + +/// warning | 警告 + +本章内容较难,刚接触 FastAPI 的新手可以跳过。 + +OAuth2 作用域不是必需的,没有它,您也可以处理身份验证与授权。 + +但 OAuth2 作用域与 API(通过 OpenAPI)及 API 文档集成地更好。 + +不管怎么说,**FastAPI** 支持在代码中使用作用域或其它安全/授权需求项。 + +很多情况下,OAuth2 作用域就像一把牛刀。 + +但如果您确定要使用作用域,或对它有兴趣,请继续阅读。 + +/// + +## OAuth2 作用域与 OpenAPI + +OAuth2 规范的**作用域**是由空格分割的字符串组成的列表。 + +这些字符串支持任何格式,但不能包含空格。 + +作用域表示的是**权限**。 + +OpenAPI 中(例如 API 文档)可以定义**安全方案**。 + +这些安全方案在使用 OAuth2 时,还可以声明和使用作用域。 + +**作用域**只是(不带空格的)字符串。 + +常用于声明特定安全权限,例如: + +* 常见用例为,`users:read` 或 `users:write` +* 脸书和 Instagram 使用 `instagram_basic` +* 谷歌使用 `https://www.googleapis.com/auth/drive` + +/// info | 说明 + +OAuth2 中,**作用域**只是声明特定权限的字符串。 + +是否使用冒号 `:` 等符号,或是不是 URL 并不重要。 + +这些细节只是特定的实现方式。 + +对 OAuth2 来说,它们都只是字符串而已。 + +/// + +## 全局纵览 + +首先,快速浏览一下以下代码与**用户指南**中 [OAuth2 实现密码哈希与 Bearer JWT 令牌验证](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}一章中代码的区别。以下代码使用 OAuth2 作用域: + +{* ../../docs_src/security/tutorial005.py hl[2,4,8,12,46,64,105,107:115,121:124,128:134,139,153] *} + +下面,我们逐步说明修改的代码内容。 + +## OAuth2 安全方案 + +第一个修改的地方是,使用两个作用域 `me` 和 `items ` 声明 OAuth2 安全方案。 + +`scopes` 参数接收**字典**,键是作用域、值是作用域的描述: + +{* ../../docs_src/security/tutorial005.py hl[62:65] *} + +因为声明了作用域,所以登录或授权时会在 API 文档中显示。 + +此处,选择给予访问权限的作用域: `me` 和 `items`。 + +这也是使用脸书、谷歌、GitHub 登录时的授权机制。 + + + +## JWT 令牌作用域 + +现在,修改令牌*路径操作*,返回请求的作用域。 + +此处仍然使用 `OAuth2PasswordRequestForm`。它包含类型为**字符串列表**的 `scopes` 属性,且`scopes` 属性中包含要在请求里接收的每个作用域。 + +这样,返回的 JWT 令牌中就包含了作用域。 + +/// danger | 危险 + +为了简明起见,本例把接收的作用域直接添加到了令牌里。 + +但在您的应用中,为了安全,应该只把作用域添加到确实需要作用域的用户,或预定义的用户。 + +/// + +{* ../../docs_src/security/tutorial005.py hl[153] *} + +## 在*路径操作*与依赖项中声明作用域 + +接下来,为*路径操作* `/users/me/items/` 声明作用域 `items`。 + +为此,要从 `fastapi` 中导入并使用 `Security` 。 + +`Security` 声明依赖项的方式和 `Depends` 一样,但 `Security` 还能接收作用域(字符串)列表类型的参数 `scopes`。 + +此处使用与 `Depends` 相同的方式,把依赖项函数 `get_current_active_user` 传递给 `Security`。 + +同时,还传递了作用域**列表**,本例中只传递了一个作用域:`items`(此处支持传递更多作用域)。 + +依赖项函数 `get_current_active_user` 还能声明子依赖项,不仅可以使用 `Depends`,也可以使用 `Security`。声明子依赖项函数(`get_current_user`)及更多作用域。 + +本例要求使用作用域 `me`(还可以使用更多作用域)。 + +/// note | 笔记 + +不必在不同位置添加不同的作用域。 + +本例使用的这种方式只是为了展示 **FastAPI** 如何处理在不同层级声明的作用域。 + +/// + +{* ../../docs_src/security/tutorial005.py hl[4,139,166] *} + +/// info | 技术细节 + +`Security` 实际上是 `Depends` 的子类,而且只比 `Depends` 多一个参数。 + +但使用 `Security` 代替 `Depends`,**FastAPI** 可以声明安全作用域,并在内部使用这些作用域,同时,使用 OpenAPI 存档 API。 + +但实际上,从 `fastapi` 导入的 `Query`、`Path`、`Depends`、`Security` 等对象,只是返回特殊类的函数。 + +/// + +## 使用 `SecurityScopes` + +修改依赖项 `get_current_user`。 + +这是上面的依赖项使用的依赖项。 + +这里使用的也是之前创建的 OAuth2 方案,并把它声明为依赖项:`oauth2_scheme`。 + +该依赖项函数本身不需要作用域,因此,可以使用 `Depends` 和 `oauth2_scheme`。不需要指定安全作用域时,不必使用 `Security`。 + +此处还声明了从 `fastapi.security` 导入的 `SecurityScopes` 类型的特殊参数。 + +`SecuriScopes` 类与 `Request` 类似(`Request` 用于直接提取请求对象)。 + +{* ../../docs_src/security/tutorial005.py hl[8,105] *} + +## 使用 `scopes` + +参数 `security_scopes` 的类型是 `SecurityScopes`。 + +它的属性 `scopes` 是作用域列表,所有依赖项都把它作为子依赖项。也就是说所有**依赖**……这听起来有些绕,后文会有解释。 + +(类 `SecurityScopes` 的)`security_scopes` 对象还提供了单字符串类型的属性 `scope_str`,该属性是(要在本例中使用的)用空格分割的作用域。 + +此处还创建了后续代码中要复用(`raise`)的 `HTTPException` 。 + +该异常包含了作用域所需的(如有),以空格分割的字符串(使用 `scope_str`)。该字符串要放到包含作用域的 `WWW-Authenticate` 请求头中(这也是规范的要求)。 + +{* ../../docs_src/security/tutorial005.py hl[105,107:115] *} + +## 校验 `username` 与数据形状 + +我们可以校验是否获取了 `username`,并抽取作用域。 + +然后,使用 Pydantic 模型校验数据(捕获 `ValidationError` 异常),如果读取 JWT 令牌或使用 Pydantic 模型验证数据时出错,就会触发之前创建的 `HTTPException` 异常。 + +对此,要使用新的属性 `scopes` 更新 Pydantic 模型 `TokenData`。 + +使用 Pydantic 验证数据可以确保数据中含有由作用域组成的**字符串列表**,以及 `username` 字符串等内容。 + +反之,如果使用**字典**或其它数据结构,就有可能在后面某些位置破坏应用,形成安全隐患。 + +还可以使用用户名验证用户,如果没有用户,也会触发之前创建的异常。 + +{* ../../docs_src/security/tutorial005.py hl[46,116:127] *} + +## 校验 `scopes` + +接下来,校验所有依赖项和依赖要素(包括*路径操作*)所需的作用域。这些作用域包含在令牌的 `scopes` 里,如果不在其中就会触发 `HTTPException` 异常。 + +为此,要使用包含所有作用域**字符串列表**的 `security_scopes.scopes`, 。 + +{* ../../docs_src/security/tutorial005.py hl[128:134] *} + +## 依赖项树与作用域 + +再次查看这个依赖项树与作用域。 + +`get_current_active_user` 依赖项包含子依赖项 `get_current_user`,并在 `get_current_active_user`中声明了作用域 `"me"` 包含所需作用域列表 ,在 `security_scopes.scopes` 中传递给 `get_current_user`。 + +*路径操作*自身也声明了作用域,`"items"`,这也是 `security_scopes.scopes` 列表传递给 `get_current_user` 的。 + +依赖项与作用域的层级架构如下: + +* *路径操作* `read_own_items` 包含: + * 依赖项所需的作用域 `["items"]`: + * `get_current_active_user`: + * 依赖项函数 `get_current_active_user` 包含: + * 所需的作用域 `"me"` 包含依赖项: + * `get_current_user`: + * 依赖项函数 `get_current_user` 包含: + * 没有作用域需求其自身 + * 依赖项使用 `oauth2_scheme` + * `security_scopes` 参数的类型是 `SecurityScopes`: + * `security_scopes` 参数的属性 `scopes` 是包含上述声明的所有作用域的**列表**,因此: + * `security_scopes.scopes` 包含用于*路径操作*的 `["me", "items"]` + * `security_scopes.scopes` 包含*路径操作* `read_users_me` 的 `["me"]`,因为它在依赖项里被声明 + * `security_scopes.scopes` 包含用于*路径操作* `read_system_status` 的 `[]`(空列表),并且它的依赖项 `get_current_user` 也没有声明任何 `scope` + +/// tip | 提示 + +此处重要且**神奇**的事情是,`get_current_user` 检查每个*路径操作*时可以使用不同的 `scopes` 列表。 + +所有这些都依赖于在每个*路径操作*和指定*路径操作*的依赖树中的每个依赖项。 + +/// + +## `SecurityScopes` 的更多细节 + +您可以任何位置或多个位置使用 `SecurityScopes`,不一定非得在**根**依赖项中使用。 + +它总是在当前 `Security` 依赖项中和所有依赖因子对于**特定** *路径操作*和**特定**依赖树中安全作用域 + +因为 `SecurityScopes` 包含所有由依赖项声明的作用域,可以在核心依赖函数中用它验证所需作用域的令牌,然后再在不同的*路径操作*中声明不同作用域需求。 + +它们会为每个*路径操作*进行单独检查。 + +## 查看文档 + +打开 API 文档,进行身份验证,并指定要授权的作用域。 + + + +没有选择任何作用域,也可以进行**身份验证**,但访问 `/uses/me` 或 `/users/me/items` 时,会显示没有足够的权限。但仍可以访问 `/status/`。 + +如果选择了作用域 `me`,但没有选择作用域 `items`,则可以访问 `/users/me/`,但不能访问 `/users/me/items`。 + +这就是通过用户提供的令牌使用第三方应用访问这些*路径操作*时会发生的情况,具体怎样取决于用户授予第三方应用的权限。 + +## 关于第三方集成 + +本例使用 OAuth2 **密码**流。 + +这种方式适用于登录我们自己的应用,最好使用我们自己的前端。 + +因为我们能控制自己的前端应用,可以信任它接收 `username` 与 `password`。 + +但如果构建的是连接其它应用的 OAuth2 应用,比如具有与脸书、谷歌、GitHub 相同功能的第三方身份验证应用。那您就应该使用其它安全流。 + +最常用的是隐式流。 + +最安全的是代码流,但实现起来更复杂,而且需要更多步骤。因为它更复杂,很多第三方身份验证应用最终建议使用隐式流。 + +/// note | 笔记 + +每个身份验证应用都会采用不同方式会命名流,以便融合入自己的品牌。 + +但归根结底,它们使用的都是 OAuth2 标准。 + +/// + +**FastAPI** 的 `fastapi.security.oauth2` 里包含了所有 OAuth2 身份验证流工具。 + +## 装饰器 `dependencies` 中的 `Security` + +同样,您可以在装饰器的 `dependencies` 参数中定义 `Depends` 列表,(详见[路径操作装饰器依赖项](../../tutorial/dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank})),也可以把 `scopes` 与 `Security` 一起使用。 diff --git a/docs/zh/docs/advanced/settings.md b/docs/zh/docs/advanced/settings.md index 76070fb7f..e33da136f 100644 --- a/docs/zh/docs/advanced/settings.md +++ b/docs/zh/docs/advanced/settings.md @@ -8,44 +8,51 @@ ## 环境变量 -!!! tip - 如果您已经知道什么是"环境变量"以及如何使用它们,请随意跳到下面的下一节。 +/// tip + +如果您已经知道什么是"环境变量"以及如何使用它们,请随意跳到下面的下一节。 + +/// 环境变量(也称为"env var")是一种存在于 Python 代码之外、存在于操作系统中的变量,可以被您的 Python 代码(或其他程序)读取。 您可以在 shell 中创建和使用环境变量,而无需使用 Python: -=== "Linux、macOS、Windows Bash" +//// tab | Linux、macOS、Windows Bash + +
+ +```console +// 您可以创建一个名为 MY_NAME 的环境变量 +$ export MY_NAME="Wade Wilson" -
+// 然后您可以与其他程序一起使用它,例如 +$ echo "Hello $MY_NAME" - ```console - // 您可以创建一个名为 MY_NAME 的环境变量 - $ export MY_NAME="Wade Wilson" +Hello Wade Wilson +``` - // 然后您可以与其他程序一起使用它,例如 - $ echo "Hello $MY_NAME" +
- Hello Wade Wilson - ``` +//// -
+//// tab | Windows PowerShell -=== "Windows PowerShell" +
-
+```console +// 创建一个名为 MY_NAME 的环境变量 +$ $Env:MY_NAME = "Wade Wilson" - ```console - // 创建一个名为 MY_NAME 的环境变量 - $ $Env:MY_NAME = "Wade Wilson" +// 与其他程序一起使用它,例如 +$ echo "Hello $Env:MY_NAME" - // 与其他程序一起使用它,例如 - $ echo "Hello $Env:MY_NAME" +Hello Wade Wilson +``` - Hello Wade Wilson - ``` +
-
+//// ### 在 Python 中读取环境变量 @@ -60,10 +67,13 @@ name = os.getenv("MY_NAME", "World") print(f"Hello {name} from Python") ``` -!!! tip - `os.getenv()` 的第二个参数是要返回的默认值。 +/// tip + +`os.getenv()` 的第二个参数是要返回的默认值。 - 如果没有提供默认值,默认为 `None`,此处我们提供了 `"World"` 作为要使用的默认值。 +如果没有提供默认值,默认为 `None`,此处我们提供了 `"World"` 作为要使用的默认值。 + +/// 然后,您可以调用该 Python 程序: @@ -116,8 +126,11 @@ Hello World from Python -!!! tip - 您可以在 Twelve-Factor App: Config 中阅读更多相关信息。 +/// tip + +您可以在 Twelve-Factor App: Config 中阅读更多相关信息。 + +/// ### 类型和验证 @@ -127,7 +140,7 @@ Hello World from Python ## Pydantic 的 `Settings` -幸运的是,Pydantic 提供了一个很好的工具来处理来自环境变量的设置,即Pydantic: Settings management。 +幸运的是,Pydantic 提供了一个很好的工具来处理来自环境变量的设置,即Pydantic: Settings management。 ### 创建 `Settings` 对象 @@ -137,12 +150,13 @@ Hello World from Python 您可以使用与 Pydantic 模型相同的验证功能和工具,比如不同的数据类型和使用 `Field()` 进行附加验证。 -```Python hl_lines="2 5-8 11" -{!../../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[2,5:8,11] *} -!!! tip - 如果您需要一个快速的复制粘贴示例,请不要使用此示例,而应使用下面的最后一个示例。 +/// tip + +如果您需要一个快速的复制粘贴示例,请不要使用此示例,而应使用下面的最后一个示例。 + +/// 然后,当您创建该 `Settings` 类的实例(在此示例中是 `settings` 对象)时,Pydantic 将以不区分大小写的方式读取环境变量,因此,大写的变量 `APP_NAME` 仍将为属性 `app_name` 读取。 @@ -152,9 +166,7 @@ Hello World from Python 然后,您可以在应用程序中使用新的 `settings` 对象: -```Python hl_lines="18-20" -{!../../../docs_src/settings/tutorial001.py!} -``` +{* ../../docs_src/settings/tutorial001.py hl[18:20] *} ### 运行服务器 @@ -170,8 +182,11 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app -!!! tip - 要为单个命令设置多个环境变量,只需用空格分隔它们,并将它们全部放在命令之前。 +/// tip + +要为单个命令设置多个环境变量,只需用空格分隔它们,并将它们全部放在命令之前。 + +/// 然后,`admin_email` 设置将为 `"deadpool@example.com"`。 @@ -185,17 +200,17 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app 例如,您可以创建一个名为 `config.py` 的文件,其中包含以下内容: -```Python -{!../../../docs_src/settings/app01/config.py!} -``` +{* ../../docs_src/settings/app01/config.py *} 然后在一个名为 `main.py` 的文件中使用它: -```Python hl_lines="3 11-13" -{!../../../docs_src/settings/app01/main.py!} -``` -!!! tip - 您还需要一个名为 `__init__.py` 的文件,就像您在[Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}中看到的那样。 +{* ../../docs_src/settings/app01/main.py hl[3,11:13] *} + +/// tip + +您还需要一个名为 `__init__.py` 的文件,就像您在[Bigger Applications - Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}中看到的那样。 + +/// ## 在依赖项中使用设置 @@ -207,9 +222,7 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app 根据前面的示例,您的 `config.py` 文件可能如下所示: -```Python hl_lines="10" -{!../../../docs_src/settings/app02/config.py!} -``` +{* ../../docs_src/settings/app02/config.py hl[10] *} 请注意,现在我们不创建默认实例 `settings = Settings()`。 @@ -217,62 +230,25 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app 现在我们创建一个依赖项,返回一个新的 `config.Settings()`。 -=== "Python 3.9+" - - ```Python hl_lines="6 12-13" - {!> ../../../docs_src/settings/app02_an_py39/main.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="6 12-13" - {!> ../../../docs_src/settings/app02_an/main.py!} - ``` - -=== "Python 3.8+ 非注解版本" +{* ../../docs_src/settings/app02_an_py39/main.py hl[6,12:13] *} - !!! tip - 如果可能,请尽量使用 `Annotated` 版本。 +/// tip - ```Python hl_lines="5 11-12" - {!> ../../../docs_src/settings/app02/main.py!} - ``` +我们稍后会讨论 `@lru_cache`。 -!!! tip - 我们稍后会讨论 `@lru_cache`。 +目前,您可以将 `get_settings()` 视为普通函数。 - 目前,您可以将 `get_settings()` 视为普通函数。 +/// 然后,我们可以将其作为依赖项从“路径操作函数”中引入,并在需要时使用它。 -=== "Python 3.9+" - - ```Python hl_lines="17 19-21" - {!> ../../../docs_src/settings/app02_an_py39/main.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="17 19-21" - {!> ../../../docs_src/settings/app02_an/main.py!} - ``` - -=== "Python 3.8+ 非注解版本" - - !!! tip - 如果可能,请尽量使用 `Annotated` 版本。 - - ```Python hl_lines="16 18-20" - {!> ../../../docs_src/settings/app02/main.py!} - ``` +{* ../../docs_src/settings/app02_an_py39/main.py hl[17,19:21] *} ### 设置和测试 然后,在测试期间,通过创建 `get_settings` 的依赖项覆盖,很容易提供一个不同的设置对象: -```Python hl_lines="9-10 13 21" -{!../../../docs_src/settings/app02/test_main.py!} -``` +{* ../../docs_src/settings/app02/test_main.py hl[9:10,13,21] *} 在依赖项覆盖中,我们在创建新的 `Settings` 对象时为 `admin_email` 设置了一个新值,然后返回该新对象。 @@ -284,15 +260,21 @@ $ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp"uvicorn main:app 这种做法相当常见,有一个名称,这些环境变量通常放在一个名为 `.env` 的文件中,该文件被称为“dotenv”。 -!!! tip - 以点 (`.`) 开头的文件是 Unix-like 系统(如 Linux 和 macOS)中的隐藏文件。 +/// tip - 但是,dotenv 文件实际上不一定要具有确切的文件名。 +以点 (`.`) 开头的文件是 Unix-like 系统(如 Linux 和 macOS)中的隐藏文件。 + +但是,dotenv 文件实际上不一定要具有确切的文件名。 + +/// Pydantic 支持使用外部库从这些类型的文件中读取。您可以在Pydantic 设置: Dotenv (.env) 支持中阅读更多相关信息。 -!!! tip - 要使其工作,您需要执行 `pip install python-dotenv`。 +/// tip + +要使其工作,您需要执行 `pip install python-dotenv`。 + +/// ### `.env` 文件 @@ -307,14 +289,15 @@ APP_NAME="ChimichangApp" 然后,您可以使用以下方式更新您的 `config.py`: -```Python hl_lines="9-10" -{!../../../docs_src/settings/app03/config.py!} -``` +{* ../../docs_src/settings/app03/config.py hl[9:10] *} 在这里,我们在 Pydantic 的 `Settings` 类中创建了一个名为 `Config` 的类,并将 `env_file` 设置为我们想要使用的 dotenv 文件的文件名。 -!!! tip - `Config` 类仅用于 Pydantic 配置。您可以在Pydantic Model Config中阅读更多相关信息。 +/// tip + +`Config` 类仅用于 Pydantic 配置。您可以在Pydantic Model Config中阅读更多相关信息。 + +/// ### 使用 `lru_cache` 仅创建一次 `Settings` @@ -339,26 +322,7 @@ def get_settings(): 但是,由于我们在顶部使用了 `@lru_cache` 装饰器,因此只有在第一次调用它时,才会创建 `Settings` 对象一次。 ✔️ -=== "Python 3.9+" - - ```Python hl_lines="1 11" - {!> ../../../docs_src/settings/app03_an_py39/main.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="1 11" - {!> ../../../docs_src/settings/app03_an/main.py!} - ``` - -=== "Python 3.8+ 非注解版本" - - !!! tip - 如果可能,请尽量使用 `Annotated` 版本。 - - ```Python hl_lines="1 10" - {!> ../../../docs_src/settings/app03/main.py!} - ``` +{* ../../docs_src/settings/app03_an_py39/main.py hl[1,11] *} 然后,在下一次请求的依赖项中对 `get_settings()` 进行任何后续调用时,它不会执行 `get_settings()` 的内部代码并创建新的 `Settings` 对象,而是返回在第一次调用时返回的相同对象,一次又一次。 diff --git a/docs/zh/docs/advanced/sub-applications.md b/docs/zh/docs/advanced/sub-applications.md new file mode 100644 index 000000000..c42be2849 --- /dev/null +++ b/docs/zh/docs/advanced/sub-applications.md @@ -0,0 +1,67 @@ +# 子应用 - 挂载 + +如果需要两个独立的 FastAPI 应用,拥有各自独立的 OpenAPI 与文档,则需设置一个主应用,并**挂载**一个(或多个)子应用。 + +## 挂载 **FastAPI** 应用 + +**挂载**是指在特定路径中添加完全**独立**的应用,然后在该路径下使用*路径操作*声明的子应用处理所有事务。 + +### 顶层应用 + +首先,创建主(顶层)**FastAPI** 应用及其*路径操作*: + +{* ../../docs_src/sub_applications/tutorial001.py hl[3,6:8] *} + +### 子应用 + +接下来,创建子应用及其*路径操作*。 + +子应用只是另一个标准 FastAPI 应用,但这个应用是被**挂载**的应用: + +{* ../../docs_src/sub_applications/tutorial001.py hl[11,14:16] *} + +### 挂载子应用 + +在顶层应用 `app` 中,挂载子应用 `subapi`。 + +本例的子应用挂载在 `/subapi` 路径下: + +{* ../../docs_src/sub_applications/tutorial001.py hl[11,19] *} + +### 查看文档 + +如果主文件是 `main.py`,则用以下 `uvicorn` 命令运行主应用: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +查看文档 http://127.0.0.1:8000/docs。 + +下图显示的是主应用 API 文档,只包括其自有的*路径操作*。 + + + +然后查看子应用文档 http://127.0.0.1:8000/subapi/docs。 + +下图显示的是子应用的 API 文档,也是只包括其自有的*路径操作*,所有这些路径操作都在 `/subapi` 子路径前缀下。 + + + +两个用户界面都可以正常运行,因为浏览器能够与每个指定的应用或子应用会话。 + +### 技术细节:`root_path` + +以上述方式挂载子应用时,FastAPI 使用 ASGI 规范中的 `root_path` 机制处理挂载子应用路径之间的通信。 + +这样,子应用就可以为自动文档使用路径前缀。 + +并且子应用还可以再挂载子应用,一切都会正常运行,FastAPI 可以自动处理所有 `root_path`。 + +关于 `root_path` 及如何显式使用 `root_path` 的内容,详见[使用代理](behind-a-proxy.md){.internal-link target=_blank}一章。 diff --git a/docs/zh/docs/advanced/templates.md b/docs/zh/docs/advanced/templates.md new file mode 100644 index 000000000..8b7019ede --- /dev/null +++ b/docs/zh/docs/advanced/templates.md @@ -0,0 +1,125 @@ +# 模板 + +**FastAPI** 支持多种模板引擎。 + +Flask 等工具使用的 Jinja2 是最用的模板引擎。 + +在 Starlette 的支持下,**FastAPI** 应用可以直接使用工具轻易地配置 Jinja2。 + +## 安装依赖项 + +安装 `jinja2`: + +
+ +```console +$ pip install jinja2 + +---> 100% +``` + +
+ +## 使用 `Jinja2Templates` + +* 导入 `Jinja2Templates` +* 创建可复用的 `templates` 对象 +* 在返回模板的*路径操作*中声明 `Request` 参数 +* 使用 `templates` 渲染并返回 `TemplateResponse`, 传递模板的名称、request对象以及一个包含多个键值对(用于Jinja2模板)的"context"字典, + +{* ../../docs_src/templates/tutorial001.py hl[4,11,15:16] *} + +/// note | 笔记 + +在FastAPI 0.108.0,Starlette 0.29.0之前,`name`是第一个参数。 +并且,在此之前,`request`对象是作为context的一部分以键值对的形式传递的。 + +/// + +/// tip | 提示 + +通过声明 `response_class=HTMLResponse`,API 文档就能识别响应的对象是 HTML。 + +/// + +/// note | 技术细节 + +您还可以使用 `from starlette.templating import Jinja2Templates`。 + +**FastAPI** 的 `fastapi.templating` 只是为开发者提供的快捷方式。实际上,绝大多数可用响应都直接继承自 Starlette。 `Request` 与 `StaticFiles` 也一样。 + +/// + +## 编写模板 + +编写模板 `templates/item.html`,代码如下: + +```jinja hl_lines="7" +{!../../docs_src/templates/templates/item.html!} +``` + +### 模板上下文 + +在包含如下语句的html中: + +{% raw %} + +```jinja +Item ID: {{ id }} +``` + +{% endraw %} + +...这将显示你从"context"字典传递的 `id`: + +```Python +{"id": id} +``` + +例如。当ID为 `42`时, 会渲染成: + +```html +Item ID: 42 +``` + +### 模板 `url_for` 参数 + +你还可以在模板内使用 `url_for()`,其参数与*路径操作函数*的参数相同. + +所以,该部分: + +{% raw %} + +```jinja + +``` + +{% endraw %} + +...将生成一个与处理*路径操作函数* `read_item(id=id)`的URL相同的链接 + +例如。当ID为 `42`时, 会渲染成: + +```html + +``` + +## 模板与静态文件 + +你还可以在模板内部将 `url_for()`用于静态文件,例如你挂载的 `name="static"`的 `StaticFiles`。 + +```jinja hl_lines="4" +{!../../docs_src/templates/templates/item.html!} +``` + +本例中,它将链接到 `static/styles.css`中的CSS文件: + +```CSS hl_lines="4" +{!../../docs_src/templates/static/styles.css!} +``` + +因为使用了 `StaticFiles`, **FastAPI** 应用会自动提供位于 URL `/static/styles.css`的 CSS 文件。 + +## 更多说明 + +包括测试模板等更多详情,请参阅 Starlette 官方文档 - 模板。 diff --git a/docs/zh/docs/advanced/testing-dependencies.md b/docs/zh/docs/advanced/testing-dependencies.md new file mode 100644 index 000000000..8d53a6d49 --- /dev/null +++ b/docs/zh/docs/advanced/testing-dependencies.md @@ -0,0 +1,53 @@ +# 测试依赖项 + +## 测试时覆盖依赖项 + +有些场景下,您可能需要在测试时覆盖依赖项。 + +即不希望运行原有依赖项(及其子依赖项)。 + +反之,要在测试期间(或只是为某些特定测试)提供只用于测试的依赖项,并使用此依赖项的值替换原有依赖项的值。 + +### 用例:外部服务 + +常见实例是调用外部第三方身份验证应用。 + +向第三方应用发送令牌,然后返回经验证的用户。 + +但第三方服务商处理每次请求都可能会收费,并且耗时通常也比调用写死的模拟测试用户更长。 + +一般只要测试一次外部验证应用就够了,不必每次测试都去调用。 + +此时,最好覆盖调用外部验证应用的依赖项,使用返回模拟测试用户的自定义依赖项就可以了。 + +### 使用 `app.dependency_overrides` 属性 + +对于这些用例,**FastAPI** 应用支持 `app.dependency_overrides` 属性,该属性就是**字典**。 + +要在测试时覆盖原有依赖项,这个字典的键应当是原依赖项(函数),值是覆盖依赖项(另一个函数)。 + +这样一来,**FastAPI** 就会调用覆盖依赖项,不再调用原依赖项。 + +{* ../../docs_src/dependency_testing/tutorial001_an_py310.py hl[26:27,30] *} + +/// tip | 提示 + +**FastAPI** 应用中的任何位置都可以实现覆盖依赖项。 + +原依赖项可用于*路径操作函数*、*路径操作装饰器*(不需要返回值时)、`.include_router()` 调用等。 + +FastAPI 可以覆盖这些位置的依赖项。 + +/// + +然后,使用 `app.dependency_overrides` 把覆盖依赖项重置为空**字典**: + +```Python +app.dependency_overrides = {} +``` + +/// tip | 提示 + +如果只在某些测试时覆盖依赖项,您可以在测试开始时(在测试函数内)设置覆盖依赖项,并在结束时(在测试函数结尾)重置覆盖依赖项。 + +/// diff --git a/docs/zh/docs/advanced/testing-events.md b/docs/zh/docs/advanced/testing-events.md new file mode 100644 index 000000000..71b3739c3 --- /dev/null +++ b/docs/zh/docs/advanced/testing-events.md @@ -0,0 +1,5 @@ +# 测试事件:启动 - 关闭 + +使用 `TestClient` 和 `with` 语句,在测试中运行事件处理器(`startup` 与 `shutdown`)。 + +{* ../../docs_src/app_testing/tutorial003.py hl[9:12,20:24] *} diff --git a/docs/zh/docs/advanced/testing-websockets.md b/docs/zh/docs/advanced/testing-websockets.md new file mode 100644 index 000000000..5d713d5f7 --- /dev/null +++ b/docs/zh/docs/advanced/testing-websockets.md @@ -0,0 +1,13 @@ +# 测试 WebSockets + +测试 WebSockets 也使用 `TestClient`。 + +为此,要在 `with` 语句中使用 `TestClient` 连接 WebSocket。 + +{* ../../docs_src/app_testing/tutorial002.py hl[27:31] *} + +/// note | 笔记 + +更多细节详见 Starlette 官档 - 测试 WebSockets。 + +/// diff --git a/docs/zh/docs/advanced/using-request-directly.md b/docs/zh/docs/advanced/using-request-directly.md new file mode 100644 index 000000000..db0fcafdf --- /dev/null +++ b/docs/zh/docs/advanced/using-request-directly.md @@ -0,0 +1,56 @@ +# 直接使用请求 + +至此,我们已经使用多种类型声明了请求的各种组件。 + +并从以下对象中提取数据: + +* 路径参数 +* 请求头 +* Cookies +* 等 + +**FastAPI** 使用这种方式验证数据、转换数据,并自动生成 API 文档。 + +但有时,我们也需要直接访问 `Request` 对象。 + +## `Request` 对象的细节 + +实际上,**FastAPI** 的底层是 **Starlette**,**FastAPI** 只不过是在 **Starlette** 顶层提供了一些工具,所以能直接使用 Starlette 的 `Request` 对象。 + +但直接从 `Request` 对象提取数据时(例如,读取请求体),**FastAPI** 不会验证、转换和存档数据(为 API 文档使用 OpenAPI)。 + +不过,仍可以验证、转换与注释(使用 Pydantic 模型的请求体等)其它正常声明的参数。 + +但在某些特定情况下,还是需要提取 `Request` 对象。 + +## 直接使用 `Request` 对象 + +假设要在*路径操作函数*中获取客户端 IP 地址和主机。 + +此时,需要直接访问请求。 + +{* ../../docs_src/using_request_directly/tutorial001.py hl[1,7:8] *} + +把*路径操作函数*的参数类型声明为 `Request`,**FastAPI** 就能把 `Request` 传递到参数里。 + +/// tip | 提示 + +注意,本例除了声明请求参数之外,还声明了路径参数。 + +因此,能够提取、验证路径参数、并转换为指定类型,还可以用 OpenAPI 注释。 + +同样,您也可以正常声明其它参数,而且还可以提取 `Request`。 + +/// + +## `Request` 文档 + +更多细节详见 Starlette 官档 - `Request` 对象。 + +/// note | 技术细节 + +您也可以使用 `from starlette.requests import Request`。 + +**FastAPI** 的 `from fastapi import Request` 只是为开发者提供的快捷方式,但其实它直接继承自 Starlette。 + +/// diff --git a/docs/zh/docs/advanced/websockets.md b/docs/zh/docs/advanced/websockets.md index a5cbdd965..d91aacc03 100644 --- a/docs/zh/docs/advanced/websockets.md +++ b/docs/zh/docs/advanced/websockets.md @@ -34,30 +34,27 @@ $ pip install websockets 但这是一种专注于 WebSockets 的服务器端并提供一个工作示例的最简单方式: -```Python hl_lines="2 6-38 41-43" -{!../../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[2,6:38,41:43] *} ## 创建 `websocket` 在您的 **FastAPI** 应用程序中,创建一个 `websocket`: -```Python hl_lines="1 46-47" -{!../../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[1,46:47] *} + +/// note | 技术细节 -!!! note "技术细节" - 您也可以使用 `from starlette.websockets import WebSocket`。 +您也可以使用 `from starlette.websockets import WebSocket`。 - **FastAPI** 直接提供了相同的 `WebSocket`,只是为了方便开发人员。但它直接来自 Starlette。 +**FastAPI** 直接提供了相同的 `WebSocket`,只是为了方便开发人员。但它直接来自 Starlette。 + +/// ## 等待消息并发送消息 在您的 WebSocket 路由中,您可以使用 `await` 等待消息并发送消息。 -```Python hl_lines="48-52" -{!../../../docs_src/websockets/tutorial001.py!} -``` +{* ../../docs_src/websockets/tutorial001.py hl[48:52] *} 您可以接收和发送二进制、文本和 JSON 数据。 @@ -106,46 +103,15 @@ $ uvicorn main:app --reload 它们的工作方式与其他 FastAPI 端点/ *路径操作* 相同: -=== "Python 3.10+" - - ```Python hl_lines="68-69 82" - {!> ../../../docs_src/websockets/tutorial002_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="68-69 82" - {!> ../../../docs_src/websockets/tutorial002_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="69-70 83" - {!> ../../../docs_src/websockets/tutorial002_an.py!} - ``` - -=== "Python 3.10+ 非带注解版本" +{* ../../docs_src/websockets/tutorial002_an_py310.py hl[68:69,82] *} - !!! tip - 如果可能,请尽量使用 `Annotated` 版本。 +/// info - ```Python hl_lines="66-67 79" - {!> ../../../docs_src/websockets/tutorial002_py310.py!} - ``` +由于这是一个 WebSocket,抛出 `HTTPException` 并不是很合理,而是抛出 `WebSocketException`。 -=== "Python 3.8+ 非带注解版本" +您可以使用规范中定义的有效代码。 - !!! tip - 如果可能,请尽量使用 `Annotated` 版本。 - - ```Python hl_lines="68-69 81" - {!> ../../../docs_src/websockets/tutorial002.py!} - ``` - -!!! info - 由于这是一个 WebSocket,抛出 `HTTPException` 并不是很合理,而是抛出 `WebSocketException`。 - - 您可以使用规范中定义的有效代码。 +/// ### 尝试带有依赖项的 WebSockets @@ -164,8 +130,11 @@ $ uvicorn main:app --reload * "Item ID",用于路径。 * "Token",作为查询参数。 -!!! tip - 注意,查询参数 `token` 将由依赖项处理。 +/// tip + +注意,查询参数 `token` 将由依赖项处理。 + +/// 通过这样,您可以连接 WebSocket,然后发送和接收消息: @@ -175,17 +144,7 @@ $ uvicorn main:app --reload 当 WebSocket 连接关闭时,`await websocket.receive_text()` 将引发 `WebSocketDisconnect` 异常,您可以捕获并处理该异常,就像本示例中的示例一样。 -=== "Python 3.9+" - - ```Python hl_lines="79-81" - {!> ../../../docs_src/websockets/tutorial003_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="81-83" - {!> ../../../docs_src/websockets/tutorial003.py!} - ``` +{* ../../docs_src/websockets/tutorial003_py39.py hl[79:81] *} 尝试以下操作: @@ -199,12 +158,15 @@ $ uvicorn main:app --reload Client #1596980209979 left the chat ``` -!!! tip - 上面的应用程序是一个最小和简单的示例,用于演示如何处理和向多个 WebSocket 连接广播消息。 +/// tip + +上面的应用程序是一个最小和简单的示例,用于演示如何处理和向多个 WebSocket 连接广播消息。 + +但请记住,由于所有内容都在内存中以单个列表的形式处理,因此它只能在进程运行时工作,并且只能使用单个进程。 - 但请记住,由于所有内容都在内存中以单个列表的形式处理,因此它只能在进程运行时工作,并且只能使用单个进程。 +如果您需要与 FastAPI 集成更简单但更强大的功能,支持 Redis、PostgreSQL 或其他功能,请查看 [encode/broadcaster](https://github.com/encode/broadcaster)。 - 如果您需要与 FastAPI 集成更简单但更强大的功能,支持 Redis、PostgreSQL 或其他功能,请查看 [encode/broadcaster](https://github.com/encode/broadcaster)。 +/// ## 更多信息 diff --git a/docs/zh/docs/advanced/wsgi.md b/docs/zh/docs/advanced/wsgi.md index ad71280fc..363025a34 100644 --- a/docs/zh/docs/advanced/wsgi.md +++ b/docs/zh/docs/advanced/wsgi.md @@ -1,6 +1,6 @@ # 包含 WSGI - Flask,Django,其它 -您可以挂载多个 WSGI 应用,正如您在 [Sub Applications - Mounts](./sub-applications.md){.internal-link target=_blank}, [Behind a Proxy](./behind-a-proxy.md){.internal-link target=_blank} 中所看到的那样。 +您可以挂载多个 WSGI 应用,正如您在 [Sub Applications - Mounts](sub-applications.md){.internal-link target=_blank}, [Behind a Proxy](behind-a-proxy.md){.internal-link target=_blank} 中所看到的那样。 为此, 您可以使用 `WSGIMiddleware` 来包装你的 WSGI 应用,如:Flask,Django,等等。 @@ -12,9 +12,7 @@ 之后将其挂载到某一个路径下。 -```Python hl_lines="2-3 22" -{!../../../docs_src/wsgi/tutorial001.py!} -``` +{* ../../docs_src/wsgi/tutorial001.py hl[2:3,22] *} ## 检查 diff --git a/docs/zh/docs/async.md b/docs/zh/docs/async.md index 59eebd049..9e6962eb1 100644 --- a/docs/zh/docs/async.md +++ b/docs/zh/docs/async.md @@ -21,8 +21,11 @@ async def read_results(): return results ``` -!!! note - 你只能在被 `async def` 创建的函数内使用 `await` +/// note + +你只能在被 `async def` 创建的函数内使用 `await` + +/// --- @@ -136,8 +139,11 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和 -!!! info - 漂亮的插画来自 Ketrina Thompson. 🎨 +/// info + +漂亮的插画来自 Ketrina Thompson. 🎨 + +/// --- @@ -199,8 +205,11 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和 没有太多的交谈或调情,因为大部分时间 🕙 都在柜台前等待😞。 -!!! info - 漂亮的插画来自 Ketrina Thompson. 🎨 +/// info + +漂亮的插画来自 Ketrina Thompson. 🎨 + +/// --- @@ -242,7 +251,7 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和 这与 **FastAPI** 的性能水平相同。 -您可以同时拥有并行性和异步性,您可以获得比大多数经过测试的 NodeJS 框架更高的性能,并且与 Go 不相上下, Go 是一种更接近于 C 的编译语言(全部归功于 Starlette)。 +你可以同时拥有并行性和异步性,你可以获得比大多数经过测试的 NodeJS 框架更高的性能,并且与 Go 不相上下, Go 是一种更接近于 C 的编译语言(全部归功于 Starlette)。 ### 并发比并行好吗? @@ -266,7 +275,7 @@ Python 的现代版本支持通过一种叫**"协程"**——使用 `async` 和 但在这种情况下,如果你能带上 8 名前收银员/厨师,现在是清洁工一起清扫,他们中的每一个人(加上你)都能占据房子的一个区域来清扫,你就可以在额外的帮助下并行的更快地完成所有工作。 -在这个场景中,每个清洁工(包括您)都将是一个处理器,完成这个工作的一部分。 +在这个场景中,每个清洁工(包括你)都将是一个处理器,完成这个工作的一部分。 由于大多数执行时间是由实际工作(而不是等待)占用的,并且计算机中的工作是由 CPU 完成的,所以他们称这些问题为"CPU 密集型"。 @@ -283,9 +292,9 @@ CPU 密集型操作的常见示例是需要复杂的数学处理。 ### 并发 + 并行: Web + 机器学习 -使用 **FastAPI**,您可以利用 Web 开发中常见的并发机制的优势(NodeJS 的主要吸引力)。 +使用 **FastAPI**,你可以利用 Web 开发中常见的并发机制的优势(NodeJS 的主要吸引力)。 -并且,您也可以利用并行和多进程(让多个进程并行运行)的优点来处理与机器学习系统中类似的 **CPU 密集型** 工作。 +并且,你也可以利用并行和多进程(让多个进程并行运行)的优点来处理与机器学习系统中类似的 **CPU 密集型** 工作。 这一点,再加上 Python 是**数据科学**、机器学习(尤其是深度学习)的主要语言这一简单事实,使得 **FastAPI** 与数据科学/机器学习 Web API 和应用程序(以及其他许多应用程序)非常匹配。 @@ -295,7 +304,7 @@ CPU 密集型操作的常见示例是需要复杂的数学处理。 现代版本的 Python 有一种非常直观的方式来定义异步代码。这使它看起来就像正常的"顺序"代码,并在适当的时候"等待"。 -当有一个操作需要等待才能给出结果,且支持这个新的 Python 特性时,您可以编写如下代码: +当有一个操作需要等待才能给出结果,且支持这个新的 Python 特性时,你可以编写如下代码: ```Python burgers = await get_burgers(2) @@ -331,7 +340,7 @@ burgers = get_burgers(2) --- -因此,如果您使用的库告诉您可以使用 `await` 调用它,则需要使用 `async def` 创建路径操作函数 ,如: +因此,如果你使用的库告诉你可以使用 `await` 调用它,则需要使用 `async def` 创建路径操作函数 ,如: ```Python hl_lines="2-3" @app.get('/burgers') @@ -342,15 +351,15 @@ async def read_burgers(): ### 更多技术细节 -您可能已经注意到,`await` 只能在 `async def` 定义的函数内部使用。 +你可能已经注意到,`await` 只能在 `async def` 定义的函数内部使用。 但与此同时,必须"等待"通过 `async def` 定义的函数。因此,带 `async def` 的函数也只能在 `async def` 定义的函数内部调用。 那么,这关于先有鸡还是先有蛋的问题,如何调用第一个 `async` 函数? -如果您使用 **FastAPI**,你不必担心这一点,因为"第一个"函数将是你的路径操作函数,FastAPI 将知道如何做正确的事情。 +如果你使用 **FastAPI**,你不必担心这一点,因为"第一个"函数将是你的路径操作函数,FastAPI 将知道如何做正确的事情。 -但如果您想在没有 FastAPI 的情况下使用 `async` / `await`,则可以这样做。 +但如果你想在没有 FastAPI 的情况下使用 `async` / `await`,则可以这样做。 ### 编写自己的异步代码 @@ -358,7 +367,9 @@ Starlette (和 **FastAPI**) 是基于 AnyIO 来处理高级的并发用例,这些用例需要在自己的代码中使用更高级的模式。 -即使您没有使用 **FastAPI**,您也可以使用 AnyIO 编写自己的异步程序,使其拥有较高的兼容性并获得一些好处(例如, 结构化并发)。 +即使你没有使用 **FastAPI**,你也可以使用 AnyIO 编写自己的异步程序,使其拥有较高的兼容性并获得一些好处(例如, 结构化并发)。 + +我(指原作者 —— 译者注)基于 AnyIO 新建了一个库,作为一个轻量级的封装层,用来优化类型注解,同时提供了更好的**自动补全**、**内联错误提示**等功能。这个库还附带了一个友好的入门指南和教程,能帮助你**理解**并编写**自己的异步代码**:Asyncer。如果你有**结合使用异步代码和常规**(阻塞/同步)代码的需求,这个库会特别有用。 ### 其他形式的异步代码 @@ -392,34 +403,37 @@ Starlette (和 **FastAPI**) 是基于 I/O
的代码。 +如果你使用过另一个不以上述方式工作的异步框架,并且你习惯于用普通的 `def` 定义普通的仅计算路径操作函数,以获得微小的性能增益(大约100纳秒),请注意,在 FastAPI 中,效果将完全相反。在这些情况下,最好使用 `async def`,除非路径操作函数内使用执行阻塞 I/O 的代码。 -在这两种情况下,与您之前的框架相比,**FastAPI** 可能[仍然很快](/#performance){.internal-link target=_blank}。 +在这两种情况下,与你之前的框架相比,**FastAPI** 可能[仍然很快](index.md#_11){.internal-link target=_blank}。 ### 依赖 -这同样适用于[依赖](./tutorial/dependencies/index.md){.internal-link target=_blank}。如果一个依赖是标准的 `def` 函数而不是 `async def`,它将被运行在外部线程池中。 +这同样适用于[依赖](tutorial/dependencies/index.md){.internal-link target=_blank}。如果一个依赖是标准的 `def` 函数而不是 `async def`,它将被运行在外部线程池中。 ### 子依赖 -你可以拥有多个相互依赖的依赖以及[子依赖](./tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} (作为函数的参数),它们中的一些可能是通过 `async def` 声明,也可能是通过 `def` 声明。它们仍然可以正常工作,这些通过 `def` 声明的函数将会在外部线程中调用(来自线程池),而不是"被等待"。 +你可以拥有多个相互依赖的依赖以及[子依赖](tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} (作为函数的参数),它们中的一些可能是通过 `async def` 声明,也可能是通过 `def` 声明。它们仍然可以正常工作,这些通过 `def` 声明的函数将会在外部线程中调用(来自线程池),而不是"被等待"。 ### 其他函数 -您可直接调用通过 `def` 或 `async def` 创建的任何其他函数,FastAPI 不会影响您调用它们的方式。 +你可直接调用通过 `def` 或 `async def` 创建的任何其他函数,FastAPI 不会影响你调用它们的方式。 -这与 FastAPI 为您调用*路径操作函数*和依赖项的逻辑相反。 +这与 FastAPI 为你调用*路径操作函数*和依赖项的逻辑相反。 如果你的函数是通过 `def` 声明的,它将被直接调用(在代码中编写的地方),而不会在线程池中,如果这个函数通过 `async def` 声明,当在代码中调用时,你就应该使用 `await` 等待函数的结果。 @@ -427,4 +441,4 @@ Starlette (和 **FastAPI**) 是基于 赶时间吗?. +否则,你最好应该遵守的指导原则赶时间吗?. diff --git a/docs/zh/docs/contributing.md b/docs/zh/docs/contributing.md deleted file mode 100644 index 4ebd67315..000000000 --- a/docs/zh/docs/contributing.md +++ /dev/null @@ -1,468 +0,0 @@ -# 开发 - 贡献 - -首先,你最好先了解 [帮助 FastAPI 及获取帮助](help-fastapi.md){.internal-link target=_blank}的基本方式。 - -## 开发 - -如果你已经克隆了源码仓库,并且需要深入研究代码,下面是设置开发环境的指南。 - -### 通过 `venv` 管理虚拟环境 - -你可以使用 Python 的 `venv` 模块在一个目录中创建虚拟环境: - -
- -```console -$ python -m venv env -``` - -
- -这将使用 Python 程序创建一个 `./env/` 目录,然后你将能够为这个隔离的环境安装软件包。 - -### 激活虚拟环境 - -使用以下方法激活新环境: - -=== "Linux, macOS" - -
- - ```console - $ source ./env/bin/activate - ``` - -
- -=== "Windows PowerShell" - -
- - ```console - $ .\env\Scripts\Activate.ps1 - ``` - -
- -=== "Windows Bash" - - Or if you use Bash for Windows (e.g. Git Bash): - -
- - ```console - $ source ./env/Scripts/activate - ``` - -
- -要检查操作是否成功,运行: - -=== "Linux, macOS, Windows Bash" - -
- - ```console - $ which pip - - some/directory/fastapi/env/bin/pip - ``` - -
- -=== "Windows PowerShell" - -
- - ```console - $ Get-Command pip - - some/directory/fastapi/env/bin/pip - ``` - -
- -如果显示 `pip` 程序文件位于 `env/bin/pip` 则说明激活成功。 🎉 - - -!!! tip - 每一次你在该环境下使用 `pip` 安装了新软件包时,请再次激活该环境。 - - 这样可以确保你在使用由该软件包安装的终端程序时使用的是当前虚拟环境中的程序,而不是其他的可能是全局安装的程序。 - -### pip - -如上所述激活环境后: - -
- -```console -$ pip install -r requirements.txt - ----> 100% -``` - -
- -这将在虚拟环境中安装所有依赖和本地版本的 FastAPI。 - -#### 使用本地 FastAPI - -如果你创建一个导入并使用 FastAPI 的 Python 文件,然后使用虚拟环境中的 Python 运行它,它将使用你本地的 FastAPI 源码。 - -并且如果你更改该本地 FastAPI 的源码,由于它是通过 `-e` 安装的,当你再次运行那个 Python 文件,它将使用你刚刚编辑过的最新版本的 FastAPI。 - -这样,你不必再去重新"安装"你的本地版本即可测试所有更改。 - -### 格式化 - -你可以运行下面的脚本来格式化和清理所有代码: - -
- -```console -$ bash scripts/format.sh -``` - -
- -它还会自动对所有导入代码进行整理。 - -为了使整理正确进行,你需要在当前环境中安装本地的 FastAPI,即在运行上述段落中的命令时添加 `-e`。 - -### 格式化导入 - -还有另一个脚本可以格式化所有导入,并确保你没有未使用的导入代码: - -
- -```console -$ bash scripts/format-imports.sh -``` - -
- -由于它依次运行了多个命令,并修改和还原了许多文件,所以运行时间会更长一些,因此经常地使用 `scripts/format.sh` 然后仅在提交前执行 `scripts/format-imports.sh` 会更好一些。 - -## 文档 - -首先,请确保按上述步骤设置好环境,这将安装所有需要的依赖。 - -文档使用 MkDocs 生成。 - -并且在 `./scripts/docs.py` 中还有适用的额外工具/脚本来处理翻译。 - -!!! tip - 你不需要去了解 `./scripts/docs.py` 中的代码,只需在命令行中使用它即可。 - -所有文档均在 `./docs/en/` 目录中以 Markdown 文件格式保存。 - -许多的教程章节里包含有代码块。 - -在大多数情况下,这些代码块是可以直接运行的真实完整的应用程序。 - -实际上,这些代码块不是写在 Markdown 文件内的,它们是位于 `./docs_src/` 目录中的 Python 文件。 - -生成站点时,这些 Python 文件会被包含/注入到文档中。 - -### 用于测试的文档 - -大多数的测试实际上都是针对文档中的示例源文件运行的。 - -这有助于确保: - -* 文档始终是最新的。 -* 文档示例可以直接运行。 -* 绝大多数特性既在文档中得以阐述,又通过测试覆盖进行保障。 - -在本地开发期间,有一个脚本可以实时重载地构建站点并用来检查所做的任何更改: - -
- -```console -$ python ./scripts/docs.py live - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -它将在 `http://127.0.0.1:8008` 提供对文档的访问。 - -这样,你可以编辑文档/源文件并实时查看更改。 - -#### Typer CLI (可选) - -本指引向你展示了如何直接用 `python` 程序运行 `./scripts/docs.py` 中的脚本。 - -但你也可以使用 Typer CLI,而且在安装了补全功能后,你将可以在终端中对命令进行自动补全。 - -如果你打算安装 Typer CLI ,可以使用以下命令安装自动补全功能: - -
- -```console -$ typer --install-completion - -zsh completion installed in /home/user/.bashrc. -Completion will take effect once you restart the terminal. -``` - -
- -### 应用和文档同时运行 - -如果你使用以下方式运行示例程序: - -
- -```console -$ uvicorn tutorial001:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -由于 Uvicorn 默认使用 `8000` 端口 ,因此运行在 `8008` 端口上的文档不会与之冲突。 - -### 翻译 - -非常感谢你能够参与文档的翻译!这项工作需要社区的帮助才能完成。 🌎 🚀 - -以下是参与帮助翻译的步骤。 - -#### 建议和指南 - -* 在当前 已有的 pull requests 中查找你使用的语言,添加要求修改或同意合并的评审意见。 - -!!! tip - 你可以为已有的 pull requests 添加包含修改建议的评论。 - - 详情可查看关于 添加 pull request 评审意见 以同意合并或要求修改的文档。 - -* 在 issues 中查找是否有对你所用语言所进行的协作翻译。 - -* 每翻译一个页面新增一个 pull request。这将使其他人更容易对其进行评审。 - -对于我(译注:作者使用西班牙语和英语)不懂的语言,我将在等待其他人评审翻译之后将其合并。 - -* 你还可以查看是否有你所用语言的翻译,并对其进行评审,这将帮助我了解翻译是否正确以及能否将其合并。 - -* 使用相同的 Python 示例并且仅翻译文档中的文本。无需进行任何其他更改示例也能正常工作。 - -* 使用相同的图片、文件名以及链接地址。无需进行任何其他调整来让它们兼容。 - -* 你可以从 ISO 639-1 代码列表 表中查找你想要翻译语言的两位字母代码。 - -#### 已有的语言 - -假设你想将某个页面翻译成已经翻译了一些页面的语言,例如西班牙语。 - -对于西班牙语来说,它的两位字母代码是 `es`。所以西班牙语翻译的目录位于 `docs/es/`。 - -!!! tip - 主要("官方")语言是英语,位于 `docs/en/`目录。 - -现在为西班牙语文档运行实时服务器: - -
- -```console -// Use the command "live" and pass the language code as a CLI argument -$ python ./scripts/docs.py live es - -[INFO] Serving on http://127.0.0.1:8008 -[INFO] Start watching changes -[INFO] Start detecting changes -``` - -
- -现在你可以访问 http://127.0.0.1:8008 实时查看你所做的更改。 - -如果你查看 FastAPI 的线上文档网站,会看到每种语言都有所有页面。但是某些页面并未被翻译并且会有一处关于缺少翻译的提示。 - -但是当你像上面这样在本地运行文档时,你只会看到已经翻译的页面。 - -现在假设你要为 [Features](features.md){.internal-link target=_blank} 章节添加翻译。 - -* 复制下面的文件: - -``` -docs/en/docs/features.md -``` - -* 粘贴到你想要翻译语言目录的相同位置,比如: - -``` -docs/es/docs/features.md -``` - -!!! tip - 注意路径和文件名的唯一变化是语言代码,从 `en` 更改为 `es`。 - -* 现在打开位于英语文档目录下的 MkDocs 配置文件: - -``` -docs/en/docs/mkdocs.yml -``` - -* 在配置文件中找到 `docs/features.md` 所在的位置。结果像这样: - -```YAML hl_lines="8" -site_name: FastAPI -# More stuff -nav: -- FastAPI: index.md -- Languages: - - en: / - - es: /es/ -- features.md -``` - -* 打开你正在编辑的语言目录中的 MkDocs 配置文件,例如: - -``` -docs/es/docs/mkdocs.yml -``` - -* 将其添加到与英语文档完全相同的位置,例如: - -```YAML hl_lines="8" -site_name: FastAPI -# More stuff -nav: -- FastAPI: index.md -- Languages: - - en: / - - es: /es/ -- features.md -``` - -如果配置文件中还有其他条目,请确保你所翻译的新条目和它们之间的顺序与英文版本完全相同。 - -打开浏览器,现在你将看到文档展示了你所加入的新章节。 🎉 - -现在,你可以将它全部翻译完并在保存文件后进行预览。 - -#### 新语言 - -假设你想要为尚未有任何页面被翻译的语言添加翻译。 - -假设你想要添加克里奥尔语翻译,而且文档中还没有该语言的翻译。 - -点击上面提到的链接,可以查到"克里奥尔语"的代码为 `ht`。 - -下一步是运行脚本以生成新的翻译目录: - -
- -```console -// Use the command new-lang, pass the language code as a CLI argument -$ python ./scripts/docs.py new-lang ht - -Successfully initialized: docs/ht -Updating ht -Updating en -``` - -
- -现在,你可以在编辑器中查看新创建的目录 `docs/ht/`。 - -!!! tip - 在添加实际的翻译之前,仅以此创建首个 pull request 来设定新语言的配置。 - - 这样当你在翻译第一个页面时,其他人可以帮助翻译其他页面。🚀 - -首先翻译文档主页 `docs/ht/index.md`。 - -然后,你可以根据上面的"已有语言"的指引继续进行翻译。 - -##### 不支持的新语言 - -如果在运行实时服务器脚本时收到关于不支持该语言的错误,类似于: - -``` - raise TemplateNotFound(template) -jinja2.exceptions.TemplateNotFound: partials/language/xx.html -``` - -这意味着文档的主题不支持该语言(在这种例子中,编造的语言代码是 `xx`)。 - -但是别担心,你可以将主题语言设置为英语,然后翻译文档的内容。 - -如果你需要这么做,编辑新语言目录下的 `mkdocs.yml`,它将有类似下面的内容: - -```YAML hl_lines="5" -site_name: FastAPI -# More stuff -theme: - # More stuff - language: xx -``` - -将其中的 language 项从 `xx`(你的语言代码)更改为 `en`。 - -然后,你就可以再次启动实时服务器了。 - -#### 预览结果 - -当你通过 `live` 命令使用 `./scripts/docs.py` 中的脚本时,该脚本仅展示当前语言已有的文件和翻译。 - -但是当你完成翻译后,你可以像在线上展示一样测试所有内容。 - -为此,首先构建所有文档: - -
- -```console -// Use the command "build-all", this will take a bit -$ python ./scripts/docs.py build-all - -Updating es -Updating en -Building docs for: en -Building docs for: es -Successfully built docs for: es -Copying en index.md to README.md -``` - -
- -这将在 `./docs_build/` 目录中为每一种语言生成全部的文档。还包括添加所有缺少翻译的文件,并带有一条"此文件还没有翻译"的提醒。但是你不需要对该目录执行任何操作。 - -然后,它针对每种语言构建独立的 MkDocs 站点,将它们组合在一起,并在 `./site/` 目录中生成最终的输出。 - -然后你可以使用命令 `serve` 来运行生成的站点: - -
- -```console -// Use the command "serve" after running "build-all" -$ python ./scripts/docs.py serve - -Warning: this is a very simple server. For development, use mkdocs serve instead. -This is here only to preview a site with translations already built. -Make sure you run the build-all command first. -Serving at: http://127.0.0.1:8008 -``` - -
- -## 测试 - -你可以在本地运行下面的脚本来测试所有代码并生成 HTML 格式的覆盖率报告: - -
- -```console -$ bash scripts/test-cov-html.sh -``` - -
- -该命令生成了一个 `./htmlcov/` 目录,如果你在浏览器中打开 `./htmlcov/index.html` 文件,你可以交互式地浏览被测试所覆盖的代码区块,并注意是否缺少了任何区块。 diff --git a/docs/zh/docs/deployment/cloud.md b/docs/zh/docs/deployment/cloud.md index 398f61372..b086b7b6b 100644 --- a/docs/zh/docs/deployment/cloud.md +++ b/docs/zh/docs/deployment/cloud.md @@ -14,4 +14,3 @@ * Platform.sh * Porter -* Deta diff --git a/docs/zh/docs/deployment/concepts.md b/docs/zh/docs/deployment/concepts.md new file mode 100644 index 000000000..7a0b6c3d2 --- /dev/null +++ b/docs/zh/docs/deployment/concepts.md @@ -0,0 +1,330 @@ +# 部署概念 + +在部署 **FastAPI** 应用程序或任何类型的 Web API 时,有几个概念值得了解,通过掌握这些概念您可以找到**最合适的**方法来**部署您的应用程序**。 + +一些重要的概念是: + +* 安全性 - HTTPS +* 启动时运行 +* 重新启动 +* 复制(运行的进程数) +* 内存 +* 开始前的先前步骤 + +我们接下来了解它们将如何影响**部署**。 + +我们的最终目标是能够以**安全**的方式**为您的 API 客户端**提供服务,同时要**避免中断**,并且尽可能高效地利用**计算资源**( 例如服务器CPU资源)。 🚀 + +我将在这里告诉您更多关于这些**概念**的信息,希望能给您提供**直觉**来决定如何在非常不同的环境中部署 API,甚至在是尚不存在的**未来**的环境里。 + +通过考虑这些概念,您将能够**评估和设计**部署**您自己的 API**的最佳方式。 + +在接下来的章节中,我将为您提供更多部署 FastAPI 应用程序的**具体方法**。 + +但现在,让我们仔细看一下这些重要的**概念**。 这些概念也适用于任何其他类型的 Web API。 💡 + +## 安全性 - HTTPS + +在[上一章有关 HTTPS](https.md){.internal-link target=_blank} 中,我们了解了 HTTPS 如何为您的 API 提供加密。 + +我们还看到,HTTPS 通常由应用程序服务器的**外部**组件(**TLS 终止代理**)提供。 + +并且必须有某个东西负责**更新 HTTPS 证书**,它可以是相同的组件,也可以是不同的组件。 + + +### HTTPS 示例工具 + +您可以用作 TLS 终止代理的一些工具包括: + +* Traefik + * 自动处理证书更新 ✨ +* Caddy + * 自动处理证书更新 ✨ +* Nginx + * 使用 Certbot 等外部组件进行证书更新 +* HAProxy + * 使用 Certbot 等外部组件进行证书更新 +* 带有 Ingress Controller(如Nginx) 的 Kubernetes + * 使用诸如 cert-manager 之类的外部组件来进行证书更新 +* 由云服务商内部处理,作为其服务的一部分(请阅读下文👇) + +另一种选择是您可以使用**云服务**来完成更多工作,包括设置 HTTPS。 它可能有一些限制或向您收取更多费用等。但在这种情况下,您不必自己设置 TLS 终止代理。 + +我将在接下来的章节中向您展示一些具体示例。 + +--- + +接下来要考虑的概念都是关于运行实际 API 的程序(例如 Uvicorn)。 + +## 程序和进程 + +我们将讨论很多关于正在运行的“**进程**”的内容,因此弄清楚它的含义以及与“**程序**”这个词有什么区别是很有用的。 + +### 什么是程序 + +**程序**这个词通常用来描述很多东西: + +* 您编写的 **代码**,**Python 文件**。 +* 操作系统可以**执行**的**文件**,例如:`python`、`python.exe`或`uvicorn`。 +* 在操作系统上**运行**、使用CPU 并将内容存储在内存上的特定程序。 这也被称为**进程**。 + +### 什么是进程 + +**进程** 这个词通常以更具体的方式使用,仅指在操作系统中运行的东西(如上面的最后一点): + +* 在操作系统上**运行**的特定程序。 + * 这不是指文件,也不是指代码,它**具体**指的是操作系统正在**执行**和管理的东西。 +* 任何程序,任何代码,**只有在执行时才能做事**。 因此,是当有**进程正在运行**时。 +* 该进程可以由您或操作系统**终止**(或“杀死”)。 那时,它停止运行/被执行,并且它可以**不再做事情**。 +* 您计算机上运行的每个应用程序背后都有一些进程,每个正在运行的程序,每个窗口等。并且通常在计算机打开时**同时**运行许多进程。 +* **同一程序**可以有**多个进程**同时运行。 + +如果您检查操作系统中的“任务管理器”或“系统监视器”(或类似工具),您将能够看到许多正在运行的进程。 + +例如,您可能会看到有多个进程运行同一个浏览器程序(Firefox、Chrome、Edge 等)。 他们通常每个tab运行一个进程,再加上一些其他额外的进程。 + + + +--- + +现在我们知道了术语“进程”和“程序”之间的区别,让我们继续讨论部署。 + +## 启动时运行 + +在大多数情况下,当您创建 Web API 时,您希望它**始终运行**、不间断,以便您的客户端始终可以访问它。 这是当然的,除非您有特定原因希望它仅在某些情况下运行,但大多数时候您希望它不断运行并且**可用**。 + +### 在远程服务器中 + +当您设置远程服务器(云服务器、虚拟机等)时,您可以做的最简单的事情就是手动运行 Uvicorn(或类似的),就像本地开发时一样。 + +它将会在**开发过程中**发挥作用并发挥作用。 + +但是,如果您与服务器的连接丢失,**正在运行的进程**可能会终止。 + +如果服务器重新启动(例如更新后或从云提供商迁移后),您可能**不会注意到它**。 因此,您甚至不知道必须手动重新启动该进程。 所以,你的 API 将一直处于挂掉的状态。 😱 + + +### 启动时自动运行 + +一般来说,您可能希望服务器程序(例如 Uvicorn)在服务器启动时自动启动,并且不需要任何**人为干预**,让进程始终与您的 API 一起运行(例如 Uvicorn 运行您的 FastAPI 应用程序) 。 + +### 单独的程序 + +为了实现这一点,您通常会有一个**单独的程序**来确保您的应用程序在启动时运行。 在许多情况下,它还可以确保其他组件或应用程序也运行,例如数据库。 + +### 启动时运行的示例工具 + +可以完成这项工作的工具的一些示例是: + +* Docker +* Kubernetes +* Docker Compose +* Docker in Swarm Mode +* Systemd +* Supervisor +* 作为其服务的一部分由云提供商内部处理 +* 其他的... + +我将在接下来的章节中为您提供更具体的示例。 + + +## 重新启动 + +与确保应用程序在启动时运行类似,您可能还想确保它在挂掉后**重新启动**。 + +### 我们会犯错误 + +作为人类,我们总是会犯**错误**。 软件几乎*总是*在不同的地方隐藏着**bug**。 🐛 + +作为开发人员,当我们发现这些bug并实现新功能(也可能添加新bug😅)时,我们会不断改进代码。 + +### 自动处理小错误 + +使用 FastAPI 构建 Web API 时,如果我们的代码中存在错误,FastAPI 通常会将其包含到触发错误的单个请求中。 🛡 + +对于该请求,客户端将收到 **500 内部服务器错误**,但应用程序将继续处理下一个请求,而不是完全崩溃。 + +### 更大的错误 - 崩溃 + +尽管如此,在某些情况下,我们编写的一些代码可能会导致整个应用程序崩溃,从而导致 Uvicorn 和 Python 崩溃。 💥 + +尽管如此,您可能不希望应用程序因为某个地方出现错误而保持死机状态,您可能希望它**继续运行**,至少对于未破坏的*路径操作*。 + +### 崩溃后重新启动 + +但在那些严重错误导致正在运行的**进程**崩溃的情况下,您需要一个外部组件来负责**重新启动**进程,至少尝试几次...... + +/// tip + +...尽管如果整个应用程序只是**立即崩溃**,那么永远重新启动它可能没有意义。 但在这些情况下,您可能会在开发过程中注意到它,或者至少在部署后立即注意到它。 + + 因此,让我们关注主要情况,在**未来**的某些特定情况下,它可能会完全崩溃,但重新启动它仍然有意义。 + +/// + +您可能希望让这个东西作为 **外部组件** 负责重新启动您的应用程序,因为到那时,使用 Uvicorn 和 Python 的同一应用程序已经崩溃了,因此同一应用程序的相同代码中没有东西可以对此做出什么。 + +### 自动重新启动的示例工具 + +在大多数情况下,用于**启动时运行程序**的同一工具也用于处理自动**重新启动**。 + +例如,可以通过以下方式处理: + +* Docker +* Kubernetes +* Docker Compose +* Docker in Swarm mode +* Systemd +* Supervisor +* 作为其服务的一部分由云提供商内部处理 +* 其他的... + +## 复制 - 进程和内存 + +对于 FastAPI 应用程序,使用像 Uvicorn 这样的服务器程序,在**一个进程**中运行一次就可以同时为多个客户端提供服务。 + +但在许多情况下,您会希望同时运行多个工作进程。 + +### 多进程 - Workers + +如果您的客户端数量多于单个进程可以处理的数量(例如,如果虚拟机不是太大),并且服务器的 CPU 中有 **多个核心**,那么您可以让 **多个进程** 运行 同时处理同一个应用程序,并在它们之间分发所有请求。 + +当您运行同一 API 程序的**多个进程**时,它们通常称为 **workers**。 + +### 工作进程和端口 + +还记得文档 [About HTTPS](https.md){.internal-link target=_blank} 中只有一个进程可以侦听服务器中的端口和 IP 地址的一种组合吗? + +现在仍然是对的。 + +因此,为了能够同时拥有**多个进程**,必须有一个**单个进程侦听端口**,然后以某种方式将通信传输到每个工作进程。 + +### 每个进程的内存 + +现在,当程序将内容加载到内存中时,例如,将机器学习模型加载到变量中,或者将大文件的内容加载到变量中,所有这些都会消耗服务器的一点内存 (RAM) 。 + +多个进程通常**不共享任何内存**。 这意味着每个正在运行的进程都有自己的东西、变量和内存。 如果您的代码消耗了大量内存,**每个进程**将消耗等量的内存。 + +### 服务器内存 + +例如,如果您的代码加载 **1 GB 大小**的机器学习模型,则当您使用 API 运行一个进程时,它将至少消耗 1 GB RAM。 如果您启动 **4 个进程**(4 个工作进程),每个进程将消耗 1 GB RAM。 因此,您的 API 总共将消耗 **4 GB RAM**。 + +如果您的远程服务器或虚拟机只有 3 GB RAM,尝试加载超过 4 GB RAM 将导致问题。 🚨 + + +### 多进程 - 一个例子 + +在此示例中,有一个 **Manager Process** 启动并控制两个 **Worker Processes**。 + +该管理器进程可能是监听 IP 中的 **端口** 的进程。 它将所有通信传输到工作进程。 + +这些工作进程将是运行您的应用程序的进程,它们将执行主要计算以接收 **请求** 并返回 **响应**,并且它们将加载您放入 RAM 中的变量中的任何内容。 + + + +当然,除了您的应用程序之外,同一台机器可能还运行**其他进程**。 + +一个有趣的细节是,随着时间的推移,每个进程使用的 **CPU 百分比可能会发生很大变化,但内存 (RAM) 通常会或多或少保持稳定**。 + +如果您有一个每次执行相当数量的计算的 API,并且您有很多客户端,那么 **CPU 利用率** 可能也会保持稳定(而不是不断快速上升和下降)。 + +### 复制工具和策略示例 + +可以通过多种方法来实现这一目标,我将在接下来的章节中向您详细介绍具体策略,例如在谈论 Docker 和容器时。 + +要考虑的主要限制是必须有一个**单个**组件来处理**公共IP**中的**端口**。 然后它必须有一种方法将通信**传输**到复制的**进程/worker**。 + +以下是一些可能的组合和策略: + +* **Gunicorn** 管理 **Uvicorn workers** + * Gunicorn 将是监听 **IP** 和 **端口** 的 **进程管理器**,复制将通过 **多个 Uvicorn 工作进程** 进行 +* **Uvicorn** 管理 **Uvicorn workers** + * 一个 Uvicorn **进程管理器** 将监听 **IP** 和 **端口**,并且它将启动 **多个 Uvicorn 工作进程** +* **Kubernetes** 和其他分布式 **容器系统** + * **Kubernetes** 层中的某些东西将侦听 **IP** 和 **端口**。 复制将通过拥有**多个容器**,每个容器运行**一个 Uvicorn 进程** +* **云服务** 为您处理此问题 + * 云服务可能**为您处理复制**。 它可能会让您定义 **要运行的进程**,或要使用的 **容器映像**,在任何情况下,它很可能是 **单个 Uvicorn 进程**,并且云服务将负责复制它。 + + + +/// tip + +如果这些关于 **容器**、Docker 或 Kubernetes 的内容还没有多大意义,请不要担心。 + + 我将在以后的章节中向您详细介绍容器镜像、Docker、Kubernetes 等:[容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank}。 + +/// + +## 启动之前的步骤 + +在很多情况下,您希望在**启动**应用程序之前执行一些步骤。 + +例如,您可能想要运行**数据库迁移**。 + +但在大多数情况下,您只想执行这些步骤**一次**。 + +因此,在启动应用程序之前,您将需要一个**单个进程**来执行这些**前面的步骤**。 + +而且您必须确保它是运行前面步骤的单个进程, *即使*之后您为应用程序本身启动**多个进程**(多个worker)。 如果这些步骤由**多个进程**运行,它们会通过在**并行**运行来**重复**工作,并且如果这些步骤像数据库迁移一样需要小心处理,它们可能会导致每个进程和其他进程发生冲突。 + +当然,也有一些情况,多次运行前面的步骤也没有问题,这样的话就好办多了。 + +/// tip + +另外,请记住,根据您的设置,在某些情况下,您在开始应用程序之前**可能甚至不需要任何先前的步骤**。 + + 在这种情况下,您就不必担心这些。 🤷 + +/// + +### 前面步骤策略的示例 + +这将在**很大程度上取决于您部署系统的方式**,并且可能与您启动程序、处理重启等的方式有关。 + +以下是一些可能的想法: + +* Kubernetes 中的“Init Container”在应用程序容器之前运行 +* 一个 bash 脚本,运行前面的步骤,然后启动您的应用程序 + * 您仍然需要一种方法来启动/重新启动 bash 脚本、检测错误等。 + +/// tip + +我将在以后的章节中为您提供使用容器执行此操作的更具体示例:[容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank}。 + +/// + +## 资源利用率 + +您的服务器是一个**资源**,您可以通过您的程序消耗或**利用**CPU 上的计算时间以及可用的 RAM 内存。 + +您想要消耗/利用多少系统资源? 您可能很容易认为“不多”,但实际上,您可能希望在不崩溃的情况下**尽可能多地消耗**。 + +如果您支付了 3 台服务器的费用,但只使用了它们的一点点 RAM 和 CPU,那么您可能**浪费金钱** 💸,并且可能 **浪费服务器电力** 🌎,等等。 + +在这种情况下,最好只拥有 2 台服务器并使用更高比例的资源(CPU、内存、磁盘、网络带宽等)。 + +另一方面,如果您有 2 台服务器,并且正在使用 **100% 的 CPU 和 RAM**,则在某些时候,一个进程会要求更多内存,并且服务器将不得不使用磁盘作为“内存” (这可能会慢数千倍),甚至**崩溃**。 或者一个进程可能需要执行一些计算,并且必须等到 CPU 再次空闲。 + +在这种情况下,最好购买**一台额外的服务器**并在其上运行一些进程,以便它们都有**足够的 RAM 和 CPU 时间**。 + +由于某种原因,您的 API 的使用量也有可能出现**激增**。 也许它像病毒一样传播开来,或者也许其他一些服务或机器人开始使用它。 在这些情况下,您可能需要额外的资源来保证安全。 + +您可以将一个**任意数字**设置为目标,例如,资源利用率**在 50% 到 90%** 之间。 重点是,这些可能是您想要衡量和用来调整部署的主要内容。 + +您可以使用“htop”等简单工具来查看服务器中使用的 CPU 和 RAM 或每个进程使用的数量。 或者您可以使用更复杂的监控工具,这些工具可能分布在服务器等上。 + + +## 回顾 + +您在这里阅读了一些在决定如何部署应用程序时可能需要牢记的主要概念: + +* 安全性 - HTTPS +* 启动时运行 +* 重新启动 +* 复制(运行的进程数) +* 内存 +* 开始前的先前步骤 + +了解这些想法以及如何应用它们应该会给您足够的直觉在配置和调整部署时做出任何决定。 🤓 + +在接下来的部分中,我将为您提供更具体的示例,说明您可以遵循的可能策略。 🚀 diff --git a/docs/zh/docs/deployment/docker.md b/docs/zh/docs/deployment/docker.md new file mode 100644 index 000000000..f120ebfb8 --- /dev/null +++ b/docs/zh/docs/deployment/docker.md @@ -0,0 +1,760 @@ +# 容器中的 FastAPI - Docker + +部署 FastAPI 应用程序时,常见的方法是构建 **Linux 容器镜像**。 通常使用 **Docker** 完成。 然后,你可以通过几种可能的方式之一部署该容器镜像。 + +使用 Linux 容器有几个优点,包括**安全性**、**可复制性**、**简单性**等。 + +/// tip + +赶时间并且已经知道这些东西了? 跳转到下面的 [`Dockerfile` 👇](#fastapi-docker_1)。 + +/// + +
+Dockerfile Preview 👀 + +```Dockerfile +FROM python:3.9 + +WORKDIR /code + +COPY ./requirements.txt /code/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +COPY ./app /code/app + +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] + +# If running behind a proxy like Nginx or Traefik add --proxy-headers +# CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80", "--proxy-headers"] +``` + +
+ +## 什么是容器 + +容器(主要是 Linux 容器)是一种非常**轻量级**的打包应用程序的方式,其包括所有依赖项和必要的文件,同时它们可以和同一系统中的其他容器(或者其他应用程序/组件)相互隔离。 + +Linux 容器使用宿主机(如物理服务器、虚拟机、云服务器等)的Linux 内核运行。 这意味着它们非常轻量(与模拟整个操作系统的完整虚拟机相比)。 + +通过这样的方式,容器消耗**很少的资源**,与直接运行进程相当(虚拟机会消耗更多)。 + +容器的进程(通常只有一个)、文件系统和网络都运行在隔离的环境,这简化了部署、安全、开发等。 + +## 什么是容器镜像 + +**容器**是从**容器镜像**运行的。 + +容器镜像是容器中文件、环境变量和默认命令/程序的**静态**版本。 **静态**这里的意思是容器**镜像**还没有运行,只是打包的文件和元数据。 + +与存储静态内容的“**容器镜像**”相反,“**容器**”通常指正在运行的实例,即正在**执行的**。 + +当**容器**启动并运行时(从**容器镜像**启动),它可以创建或更改文件、环境变量等。这些更改将仅存在于该容器中,而不会持久化到底层的容器镜像中(不会保存到磁盘)。 + +容器镜像相当于**程序**和文件,例如 `python`命令 和某些文件 如`main.py`。 + +而**容器**本身(与**容器镜像**相反)是镜像的实际运行实例,相当于**进程**。 事实上,容器仅在有**进程运行**时才运行(通常它只是一个单独的进程)。 当容器中没有进程运行时,容器就会停止。 + + + +## 容器镜像 + +Docker 一直是创建和管理**容器镜像**和**容器**的主要工具之一。 + +还有一个公共 Docker Hub ,其中包含预制的 **官方容器镜像**, 适用于许多工具、环境、数据库和应用程序。 + +例如,有一个官方的 Python 镜像。 + +还有许多其他镜像用于不同的需要(例如数据库),例如: + + +* PostgreSQL +* MySQL +* MongoDB +* Redis, etc. + + +通过使用预制的容器镜像,可以非常轻松地**组合**并使用不同的工具。 例如,尝试一个新的数据库。 在大多数情况下,你可以使用**官方镜像**,只需为其配置环境变量即可。 + +这样,在许多情况下,你可以了解容器和 Docker,并通过许多不同的工具和组件重复使用这些知识。 + +因此,你可以运行带有不同内容的**多个容器**,例如数据库、Python 应用程序、带有 React 前端应用程序的 Web 服务器,并通过内部网络将它们连接在一起。 + +所有容器管理系统(如 Docker 或 Kubernetes)都集成了这些网络功能。 + +## 容器和进程 + +**容器镜像**通常在其元数据中包含启动**容器**时应运行的默认程序或命令以及要传递给该程序的参数。 与在命令行中的情况非常相似。 + +当 **容器** 启动时,它将运行该命令/程序(尽管你可以覆盖它并使其运行不同的命令/程序)。 + +只要**主进程**(命令或程序)在运行,容器就在运行。 + +容器通常有一个**单个进程**,但也可以从主进程启动子进程,这样你就可以在同一个容器中拥有**多个进程**。 + +但是,如果没有**至少一个正在运行的进程**,就不可能有一个正在运行的容器。 如果主进程停止,容器也会停止。 + + +## 为 FastAPI 构建 Docker 镜像 + +好吧,让我们现在构建一些东西! 🚀 + +我将向你展示如何基于 **官方 Python** 镜像 **从头开始** 为 FastAPI 构建 **Docker 镜像**。 + +这是你在**大多数情况**下想要做的,例如: + +* 使用 **Kubernetes** 或类似工具 +* 在 **Raspberry Pi** 上运行时 +* 使用可为你运行容器镜像的云服务等。 + +### 依赖项 + +你通常会在某个文件中包含应用程序的**依赖项**。 + +具体做法取决于你**安装**这些依赖时所使用的工具。 + +最常见的方法是创建一个`requirements.txt`文件,其中每行包含一个包名称和它的版本。 + +你当然也可以使用在[关于 FastAPI 版本](versions.md){.internal-link target=_blank} 中讲到的方法来设置版本范围。 + +例如,你的`requirements.txt`可能如下所示: + + +``` +fastapi>=0.68.0,<0.69.0 +pydantic>=1.8.0,<2.0.0 +uvicorn>=0.15.0,<0.16.0 +``` + +你通常会使用`pip`安装这些依赖项: + +
+ +```console +$ pip install -r requirements.txt +---> 100% +Successfully installed fastapi pydantic uvicorn +``` + +
+ +/// info + +还有其他文件格式和工具来定义和安装依赖项。 + + 我将在下面的部分中向你展示一个使用 Poetry 的示例。 👇 + +/// + +### 创建 **FastAPI** 代码 + +* 创建`app`目录并进入。 +* 创建一个空文件`__init__.py`。 +* 创建一个 `main.py` 文件: + + + +```Python +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@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} +``` + +### Dockerfile + +现在在相同的project目录创建一个名为`Dockerfile`的文件: + +```{ .dockerfile .annotate } +# (1) +FROM python:3.9 + +# (2) +WORKDIR /code + +# (3) +COPY ./requirements.txt /code/requirements.txt + +# (4) +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +# (5) +COPY ./app /code/app + +# (6) +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] +``` + +1. 从官方Python基础镜像开始。 + +2. 将当前工作目录设置为`/code`。 + + 这是我们放置`requirements.txt`文件和`app`目录的位置。 + +3. 将符合要求的文件复制到`/code`目录中。 + + 首先仅复制requirements.txt文件,而不复制其余代码。 + + 由于此文件**不经常更改**,Docker 将检测到它并在这一步中使用**缓存**,从而为下一步启用缓存。 + +4. 安装需求文件中的包依赖项。 + + `--no-cache-dir` 选项告诉 `pip` 不要在本地保存下载的包,因为只有当 `pip` 再次运行以安装相同的包时才会这样,但在与容器一起工作时情况并非如此。 + + /// note | 笔记 + + `--no-cache-dir` 仅与 `pip` 相关,与 Docker 或容器无关。 + + /// + + `--upgrade` 选项告诉 `pip` 升级软件包(如果已经安装)。 + + 因为上一步复制文件可以被 **Docker 缓存** 检测到,所以此步骤也将 **使用 Docker 缓存**(如果可用)。 + + 在开发过程中一次又一次构建镜像时,在此步骤中使用缓存将为你节省大量**时间**,而不是**每次**都**下载和安装**所有依赖项。 + + +5. 将“./app”目录复制到“/code”目录中。 + + 由于其中包含**更改最频繁**的所有代码,因此 Docker **缓存**不会轻易用于此操作或任何**后续步骤**。 + + 因此,将其放在`Dockerfile`**接近最后**的位置非常重要,以优化容器镜像的构建时间。 + +6. 设置**命令**来运行 `uvicorn` 服务器。 + + `CMD` 接受一个字符串列表,每个字符串都是你在命令行中输入的内容,并用空格分隔。 + + 该命令将从 **当前工作目录** 运行,即你上面使用`WORKDIR /code`设置的同一`/code`目录。 + + 因为程序将从`/code`启动,并且其中包含你的代码的目录`./app`,所以**Uvicorn**将能够从`app.main`中查看并**import**`app`。 + +/// tip + +通过单击代码中的每个数字气泡来查看每行的作用。 👆 + +/// + +你现在应该具有如下目录结构: +``` +. +├── app +│   ├── __init__.py +│ └── main.py +├── Dockerfile +└── requirements.txt +``` + + +#### 在 TLS 终止代理后面 + +如果你在 Nginx 或 Traefik 等 TLS 终止代理(负载均衡器)后面运行容器,请添加选项 `--proxy-headers`,这将告诉 Uvicorn 信任该代理发送的标头,告诉它应用程序正在 HTTPS 后面运行等信息 + +```Dockerfile +CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"] +``` + +#### Docker 缓存 + +这个`Dockerfile`中有一个重要的技巧,我们首先只单独复制**包含依赖项的文件**,而不是其余代码。 让我来告诉你这是为什么。 + +```Dockerfile +COPY ./requirements.txt /code/requirements.txt +``` + +Docker之类的构建工具是通过**增量**的方式来构建这些容器镜像的。具体做法是从`Dockerfile`顶部开始,每一条指令生成的文件都是镜像的“一层”,同过把这些“层”一层一层地叠加到基础镜像上,最后我们就得到了最终的镜像。 + +Docker 和类似工具在构建镜像时也会使用**内部缓存**,如果自上次构建容器镜像以来文件没有更改,那么它将**重新使用上次创建的同一层**,而不是再次复制文件并从头开始创建新层。 + +仅仅避免文件的复制不一定会有太多速度提升,但是如果在这一步使用了缓存,那么才可以**在下一步中使用缓存**。 例如,可以使用安装依赖项那条指令的缓存: + +```Dockerfile +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt +``` + + +包含包依赖项的文件**不会频繁更改**。 只复制该文件(不复制其他的应用代码),Docker 才能在这一步**使用缓存**。 + +Docker 进而能**使用缓存进行下一步**,即下载并安装这些依赖项。 这才是我们**节省大量时间**的地方。 ✨ ...可以避免无聊的等待。 😪😆 + +下载和安装依赖项**可能需要几分钟**,但使用**缓存**最多**只需要几秒钟**。 + +由于你在开发过程中会一次又一次地构建容器镜像以检查代码更改是否有效,因此可以累计节省大量时间。 + +在`Dockerfile`末尾附近,我们再添加复制代码的指令。 由于代码是**更改最频繁的**,所以将其放在最后,因为这一步之后的内容基本上都是无法使用缓存的。 + +```Dockerfile +COPY ./app /code/app +``` + +### 构建 Docker 镜像 + +现在所有文件都已就位,让我们构建容器镜像。 + +* 转到项目目录(在`Dockerfile`所在的位置,包含`app`目录)。 +* 构建你的 FastAPI 镜像: + + +
+ +```console +$ docker build -t myimage . + +---> 100% +``` + +
+ + +/// tip + +注意最后的 `.`,它相当于`./`,它告诉 Docker 用于构建容器镜像的目录。 + +在本例中,它是相同的当前目录(`.`)。 + +/// + +### 启动 Docker 容器 + +* 根据你的镜像运行容器: + +
+ +```console +$ docker run -d --name mycontainer -p 80:80 myimage +``` + +
+ +## 检查一下 + + +你应该能在Docker容器的URL中检查它,例如: http://192.168.99.100/items/5?q=somequeryhttp://127.0.0.1/items/5?q=somequery (或其他等价的,使用 Docker 主机). + +你会看到类似内容: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +## 交互式 API 文档 + +现在你可以转到 http://192.168.99.100/docshttp://127.0.0.1/docs (或其他等价的,使用 Docker 主机)。 + +你将看到自动交互式 API 文档(由 Swagger UI): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +## 备选的 API 文档 + +你还可以访问 http://192.168.99.100/redochttp://127.0.0.1/redoc (或其他等价的,使用 Docker 主机)。 + +你将看到备选的自动文档(由 ReDoc 提供): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## 使用单文件 FastAPI 构建 Docker 镜像 + +如果你的 FastAPI 是单个文件,例如没有`./app`目录的`main.py`,则你的文件结构可能如下所示: + +``` +. +├── Dockerfile +├── main.py +└── requirements.txt +``` + +然后你只需更改相应的路径即可将文件复制到`Dockerfile`中: + +```{ .dockerfile .annotate hl_lines="10 13" } +FROM python:3.9 + +WORKDIR /code + +COPY ./requirements.txt /code/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +# (1) +COPY ./main.py /code/ + +# (2) +CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] +``` + +1. 直接将`main.py`文件复制到`/code`目录中(不包含任何`./app`目录)。 + +2. 运行 Uvicorn 并告诉它从 `main` 导入 `app` 对象(而不是从 `app.main` 导入)。 + +然后调整Uvicorn命令使用新模块`main`而不是`app.main`来导入FastAPI 实例`app`。 + +## 部署概念 + +我们再谈谈容器方面的一些相同的[部署概念](concepts.md){.internal-link target=_blank}。 + +容器主要是一种简化**构建和部署**应用程序的过程的工具,但它们并不强制执行特定的方法来处理这些**部署概念**,并且有几种可能的策略。 + +**好消息**是,对于每种不同的策略,都有一种方法可以涵盖所有部署概念。 🎉 + +让我们从容器的角度回顾一下这些**部署概念**: + +* HTTPS +* 启动时运行 +* 重新启动 +* 复制(运行的进程数) +* 内存 +* 开始前的先前步骤 + + +## HTTPS + +如果我们只关注 FastAPI 应用程序的 **容器镜像**(以及稍后运行的 **容器**),HTTPS 通常会由另一个工具在 **外部** 处理。 + +它可以是另一个容器,例如使用 Traefik,处理 **HTTPS** 和 **自动**获取**证书**。 + +/// tip + +Traefik可以与 Docker、Kubernetes 等集成,因此使用它为容器设置和配置 HTTPS 非常容易。 + +/// + +或者,HTTPS 可以由云服务商作为其服务之一进行处理(同时仍在容器中运行应用程序)。 + +## 在启动和重新启动时运行 + +通常还有另一个工具负责**启动和运行**你的容器。 + +它可以直接是**Docker**, 或者**Docker Compose**、**Kubernetes**、**云服务**等。 + +在大多数(或所有)情况下,有一个简单的选项可以在启动时运行容器并在失败时重新启动。 例如,在 Docker 中,它是命令行选项 `--restart`。 + +如果不使用容器,让应用程序在启动时运行并重新启动可能会很麻烦且困难。 但在大多数情况下,当**使用容器**时,默认情况下会包含该功能。 ✨ + +## 复制 - 进程数 + +如果你有一个 集群, 比如 **Kubernetes**、Docker Swarm、Nomad 或其他类似的复杂系统来管理多台机器上的分布式容器,那么你可能希望在**集群级别**处理复制**,而不是在每个容器中使用**进程管理器**(如带有Worker的 Gunicorn) 。 + +像 Kubernetes 这样的分布式容器管理系统通常有一些集成的方法来处理**容器的复制**,同时仍然支持传入请求的**负载均衡**。 全部都在**集群级别**。 + +在这些情况下,你可能希望从头开始构建一个 **Docker 镜像**,如[上面所解释](#dockerfile)的那样,安装依赖项并运行 **单个 Uvicorn 进程**,而不是运行 Gunicorn 和 Uvicorn workers这种。 + + +### 负载均衡器 + +使用容器时,通常会有一些组件**监听主端口**。 它可能是处理 **HTTPS** 的 **TLS 终止代理** 或一些类似的工具的另一个容器。 + +由于该组件将接受请求的**负载**并(希望)以**平衡**的方式在worker之间分配该请求,因此它通常也称为**负载均衡器**。 + +/// tip + +用于 HTTPS **TLS 终止代理** 的相同组件也可能是 **负载均衡器**。 + +/// + +当使用容器时,你用来启动和管理容器的同一系统已经具有内部工具来传输来自该**负载均衡器**(也可以是**TLS 终止代理**) 的**网络通信**(例如HTTP请求)到你的应用程序容器。 + +### 一个负载均衡器 - 多个worker容器 + +当使用 **Kubernetes** 或类似的分布式容器管理系统时,使用其内部网络机制将允许单个在主 **端口** 上侦听的 **负载均衡器** 将通信(请求)传输到可能的 **多个** 运行你应用程序的容器。 + +运行你的应用程序的每个容器通常**只有一个进程**(例如,运行 FastAPI 应用程序的 Uvicorn 进程)。 它们都是**相同的容器**,运行相同的东西,但每个容器都有自己的进程、内存等。这样你就可以在 CPU 的**不同核心**, 甚至在**不同的机器**充分利用**并行化(parallelization)**。 + +具有**负载均衡器**的分布式容器系统将**将请求轮流分配**给你的应用程序的每个容器。 因此,每个请求都可以由运行你的应用程序的多个**复制容器**之一来处理。 + +通常,这个**负载均衡器**能够处理发送到集群中的*其他*应用程序的请求(例如发送到不同的域,或在不同的 URL 路径前缀下),并正确地将该通信传输到在集群中运行的*其他*应用程序的对应容器。 + + + + + + +### 每个容器一个进程 + +在这种类型的场景中,你可能希望**每个容器有一个(Uvicorn)进程**,因为你已经在集群级别处理复制。 + +因此,在这种情况下,你**不会**希望拥有像 Gunicorn 和 Uvicorn worker一样的进程管理器,或者 Uvicorn 使用自己的 Uvicorn worker。 你可能希望每个容器(但可能有多个容器)只有一个**单独的 Uvicorn 进程**。 + +在容器内拥有另一个进程管理器(就像使用 Gunicorn 或 Uvicorn 管理 Uvicorn 工作线程一样)只会增加**不必要的复杂性**,而你很可能已经在集群系统中处理这些复杂性了。 + +### 具有多个进程的容器 + +当然,在某些**特殊情况**,你可能希望拥有 **一个容器**,其中包含 **Gunicorn 进程管理器**,并在其中启动多个 **Uvicorn worker进程**。 + +在这些情况下,你可以使用 **官方 Docker 镜像**,其中包含 **Gunicorn** 作为运行多个 **Uvicorn 工作进程** 的进程管理器,以及一些默认设置来根据当前情况调整工作进程数量 自动CPU核心。 我将在下面的 [Gunicorn - Uvicorn 官方 Docker 镜像](#official-docker-image-with-gunicorn-uvicorn) 中告诉你更多相关信息。 + +下面一些什么时候这种做法有意义的示例: + + +#### 一个简单的应用程序 + +如果你的应用程序**足够简单**,你不需要(至少现在不需要)过多地微调进程数量,并且你可以使用自动默认值,那么你可能需要容器中的进程管理器 (使用官方 Docker 镜像),并且你在**单个服务器**而不是集群上运行它。 + +#### Docker Compose + +你可以使用 **Docker Compose** 部署到**单个服务器**(而不是集群),因此你没有一种简单的方法来管理容器的复制(使用 Docker Compose),同时保留共享网络和 **负载均衡**。 + +然后,你可能希望拥有一个**单个容器**,其中有一个**进程管理器**,在其中启动**多个worker进程**。 + +#### Prometheus和其他原因 + +你还可能有**其他原因**,这将使你更容易拥有一个带有**多个进程**的**单个容器**,而不是拥有每个容器中都有**单个进程**的**多个容器**。 + +例如(取决于你的设置)你可以在同一个容器中拥有一些工具,例如 Prometheus exporter,该工具应该有权访问**每个请求**。 + +在这种情况下,如果你有**多个容器**,默认情况下,当 Prometheus 来**读取metrics**时,它每次都会获取**单个容器**的metrics(对于处理该特定请求的容器),而不是获取所有复制容器的**累积metrics**。 + +在这种情况, 这种做法会更加简单:让**一个容器**具有**多个进程**,并在同一个容器上使用本地工具(例如 Prometheus exporter)收集所有内部进程的 Prometheus 指标并公开单个容器上的这些指标。 + +--- + +要点是,这些都**不是**你必须盲目遵循的**一成不变的规则**。 你可以根据这些思路**评估你自己的场景**并决定什么方法是最适合你的的系统,考虑如何管理以下概念: + +* 安全性 - HTTPS +* 启动时运行 +* 重新启动 +* 复制(运行的进程数) +* 内存 +* 开始前的先前步骤 + +## 内存 + +如果你**每个容器运行一个进程**,那么每个容器所消耗的内存或多或少是定义明确的、稳定的且有限的(如果它们是复制的,则不止一个)。 + +然后,你可以在容器管理系统的配置中设置相同的内存限制和要求(例如在 **Kubernetes** 中)。 这样,它将能够在**可用机器**中**复制容器**,同时考虑容器所需的内存量以及集群中机器中的可用内存量。 + +如果你的应用程序很**简单**,这可能**不是问题**,并且你可能不需要指定内存限制。 但是,如果你**使用大量内存**(例如使用**机器学习**模型),则应该检查你消耗了多少内存并调整**每台机器**中运行的**容器数量**(也许可以向集群添加更多机器)。 + +如果你**每个容器运行多个进程**(例如使用官方 Docker 镜像),你必须确保启动的进程数量不会消耗比可用内存**更多的内存**。 + +## 启动之前的步骤和容器 + +如果你使用容器(例如 Docker、Kubernetes),那么你可以使用两种主要方法。 + + +### 多个容器 + +如果你有 **多个容器**,可能每个容器都运行一个 **单个进程**(例如,在 **Kubernetes** 集群中),那么你可能希望有一个 **单独的容器** 执行以下操作: 在单个容器中运行单个进程执行**先前步骤**,即运行复制的worker容器之前。 + +/// info + +如果你使用 Kubernetes,这可能是 Init Container。 + +/// + +如果在你的用例中,运行前面的步骤**并行多次**没有问题(例如,如果你没有运行数据库迁移,而只是检查数据库是否已准备好),那么你也可以将它们放在开始主进程之前在每个容器中。 + +### 单容器 + +如果你有一个简单的设置,使用一个**单个容器**,然后启动多个**工作进程**(或者也只是一个进程),那么你可以在启动进程之前在应用程序同一个容器中运行先前的步骤。 官方 Docker 镜像内部支持这一点。 + +## 带有 Gunicorn 的官方 Docker 镜像 - Uvicorn + +有一个官方 Docker 镜像,其中包含与 Uvicorn worker一起运行的 Gunicorn,如上一章所述:[服务器工作线程 - Gunicorn 与 Uvicorn](server-workers.md){.internal-link target=_blank}。 + +该镜像主要在上述情况下有用:[具有多个进程和特殊情况的容器](#containers-with-multiple-processes-and-special-cases)。 + + + +* tiangolo/uvicorn-gunicorn-fastapi. + + +/// warning + +你很有可能不需要此基础镜像或任何其他类似的镜像,最好从头开始构建镜像,如[上面所述:为 FastAPI 构建 Docker 镜像](#build-a-docker-image-for-fastapi)。 + +/// + +该镜像包含一个**自动调整**机制,用于根据可用的 CPU 核心设置**worker进程数**。 + +它具有**合理的默认值**,但你仍然可以使用**环境变量**或配置文件更改和更新所有配置。 + +它还支持通过一个脚本运行**开始前的先前步骤** 。 + +/// tip + +要查看所有配置和选项,请转到 Docker 镜像页面: tiangolo/uvicorn-gunicorn-fastapi。 + +/// + +### 官方 Docker 镜像上的进程数 + +此镜像上的**进程数**是根据可用的 CPU **核心**自动计算的。 + +这意味着它将尝试尽可能多地**榨取**CPU 的**性能**。 + +你还可以使用 **环境变量** 等配置来调整它。 + +但这也意味着,由于进程数量取决于容器运行的 CPU,因此**消耗的内存量**也将取决于该数量。 + +因此,如果你的应用程序消耗大量内存(例如机器学习模型),并且你的服务器有很多 CPU 核心**但内存很少**,那么你的容器最终可能会尝试使用比实际情况更多的内存 可用,并且性能会下降很多(甚至崩溃)。 🚨 + +### 创建一个`Dockerfile` + +以下是如何根据此镜像创建`Dockerfile`: + + +```Dockerfile +FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9 + +COPY ./requirements.txt /app/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt + +COPY ./app /app +``` + +### 更大的应用程序 + +如果你按照有关创建[具有多个文件的更大应用程序](../tutorial/bigger-applications.md){.internal-link target=_blank}的部分进行操作,你的`Dockerfile`可能看起来这样: + +```Dockerfile hl_lines="7" +FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9 + +COPY ./requirements.txt /app/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt + +COPY ./app /app/app +``` + +### 何时使用 + +如果你使用 **Kubernetes** (或其他)并且你已经在集群级别设置 **复制**,并且具有多个 **容器**。 在这些情况下,你最好按照上面的描述 **从头开始构建镜像**:[为 FastAPI 构建 Docker 镜像](#build-a-docker-image-for-fastapi)。 + +该镜像主要在[具有多个进程的容器和特殊情况](#containers-with-multiple-processes-and-special-cases)中描述的特殊情况下有用。 例如,如果你的应用程序**足够简单**,基于 CPU 设置默认进程数效果很好,你不想在集群级别手动配置复制,并且不会运行更多进程, 或者你使用 **Docker Compose** 进行部署,在单个服务器上运行等。 + +## 部署容器镜像 + +拥有容器(Docker)镜像后,有多种方法可以部署它。 + +例如: + +* 在单个服务器中使用 **Docker Compose** +* 使用 **Kubernetes** 集群 +* 使用 Docker Swarm 模式集群 +* 使用Nomad等其他工具 +* 使用云服务获取容器镜像并部署它 + +## Docker 镜像与Poetry + +如果你使用 Poetry 来管理项目的依赖项,你可以使用 Docker 多阶段构建: + + + +```{ .dockerfile .annotate } +# (1) +FROM python:3.9 as requirements-stage + +# (2) +WORKDIR /tmp + +# (3) +RUN pip install poetry + +# (4) +COPY ./pyproject.toml ./poetry.lock* /tmp/ + +# (5) +RUN poetry export -f requirements.txt --output requirements.txt --without-hashes + +# (6) +FROM python:3.9 + +# (7) +WORKDIR /code + +# (8) +COPY --from=requirements-stage /tmp/requirements.txt /code/requirements.txt + +# (9) +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +# (10) +COPY ./app /code/app + +# (11) +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] +``` + +1. 这是第一阶段,称为`requirements-stage`。 + +2. 将 `/tmp` 设置为当前工作目录。 + + 这是我们生成文件`requirements.txt`的地方 + +3. 在此阶段安装Poetry。 + +4. 将`pyproject.toml`和`poetry.lock`文件复制到`/tmp`目录。 + + 因为它使用 `./poetry.lock*` (以 `*` 结尾),所以如果该文件尚不可用,它不会崩溃。 + +5. 生成`requirements.txt`文件。 + +6. 这是最后阶段,这里的任何内容都将保留在最终的容器镜像中。 + +7. 将当前工作目录设置为`/code`。 + +8. 将 `requirements.txt` 文件复制到 `/code` 目录。 + + 该文件仅存在于前一个阶段,这就是为什么我们使用 `--from-requirements-stage` 来复制它。 + +9. 安装生成的`requirements.txt`文件中的依赖项。 + +10. 将`app`目录复制到`/code`目录。 + +11. 运行`uvicorn`命令,告诉它使用从`app.main`导入的`app`对象。 + +/// tip + +单击气泡数字可查看每行的作用。 + +/// + +**Docker stage** 是 `Dockerfile` 的一部分,用作 **临时容器镜像**,仅用于生成一些稍后使用的文件。 + +第一阶段仅用于 **安装 Poetry** 并使用 Poetry 的 `pyproject.toml` 文件中的项目依赖项 **生成 `requirements.txt`**。 + +此`requirements.txt`文件将在**下一阶段**与`pip`一起使用。 + +在最终的容器镜像中**仅保留最后阶段**。 之前的阶段将被丢弃。 + +使用 Poetry 时,使用 **Docker 多阶段构建** 是有意义的,因为你实际上并不需要在最终的容器镜像中安装 Poetry 及其依赖项,你 **只需要** 生成用于安装项目依赖项的`requirements.txt`文件。 + +然后,在下一个(也是最后一个)阶段,你将或多或少地以与前面描述的相同的方式构建镜像。 + +### 在TLS 终止代理后面 - Poetry + +同样,如果你在 Nginx 或 Traefik 等 TLS 终止代理(负载均衡器)后面运行容器,请将选项`--proxy-headers`添加到命令中: + + +```Dockerfile +CMD ["uvicorn", "app.main:app", "--proxy-headers", "--host", "0.0.0.0", "--port", "80"] +``` + +## 回顾 + +使用容器系统(例如使用**Docker**和**Kubernetes**),处理所有**部署概念**变得相当简单: + +* HTTPS +* 启动时运行 +* 重新启动 +* 复制(运行的进程数) +* 内存 +* 开始前的先前步骤 + +在大多数情况下,你可能不想使用任何基础镜像,而是基于官方 Python Docker 镜像 **从头开始构建容器镜像** 。 + +处理好`Dockerfile`和 **Docker 缓存**中指令的**顺序**,你可以**最小化构建时间**,从而最大限度地提高生产力(并避免无聊)。 😎 + +在某些特殊情况下,你可能需要使用 FastAPI 的官方 Docker 镜像。 🤓 diff --git a/docs/zh/docs/deployment/https.md b/docs/zh/docs/deployment/https.md index cf01a4585..9c963d587 100644 --- a/docs/zh/docs/deployment/https.md +++ b/docs/zh/docs/deployment/https.md @@ -4,8 +4,11 @@ 但实际情况比这复杂得多。 -!!!提示 - 如果你很赶时间或不在乎,请继续阅读下一部分,下一部分会提供一个step-by-step的教程,告诉你怎么使用不同技术来把一切都配置好。 +/// note | 提示 + +如果你很赶时间或不在乎,请继续阅读下一部分,下一部分会提供一个step-by-step的教程,告诉你怎么使用不同技术来把一切都配置好。 + +/// 要从用户的视角**了解 HTTPS 的基础知识**,请查看 https://howhttps.works/。 @@ -69,8 +72,11 @@ 这个操作一般只需要在最开始执行一次。 -!!! tip - 域名这部分发生在 HTTPS 之前,由于这一切都依赖于域名和 IP 地址,所以先在这里提一下。 +/// tip + +域名这部分发生在 HTTPS 之前,由于这一切都依赖于域名和 IP 地址,所以先在这里提一下。 + +/// ### DNS @@ -116,8 +122,11 @@ TLS 终止代理可以访问一个或多个 **TLS 证书**(HTTPS 证书)。 这就是 **HTTPS**,它只是 **安全 TLS 连接** 内的普通 **HTTP**,而不是纯粹的(未加密的)TCP 连接。 -!!! tip - 请注意,通信加密发生在 **TCP 层**,而不是 HTTP 层。 +/// tip + +请注意,通信加密发生在 **TCP 层**,而不是 HTTP 层。 + +/// ### HTTPS 请求 diff --git a/docs/zh/docs/deployment/manually.md b/docs/zh/docs/deployment/manually.md index 15588043f..30ee7a1e9 100644 --- a/docs/zh/docs/deployment/manually.md +++ b/docs/zh/docs/deployment/manually.md @@ -5,7 +5,7 @@ 有 3 个主要可选方案: * Uvicorn:高性能 ASGI 服务器。 -* Hypercorn:与 HTTP/2 和 Trio 等兼容的 ASGI 服务器。 +* Hypercorn:与 HTTP/2 和 Trio 等兼容的 ASGI 服务器。 * Daphne:为 Django Channels 构建的 ASGI 服务器。 ## 服务器主机和服务器程序 @@ -23,77 +23,89 @@ 您可以使用以下命令安装 ASGI 兼容服务器: -=== "Uvicorn" +//// tab | Uvicorn - * Uvicorn,一个快如闪电 ASGI 服务器,基于 uvloop 和 httptools 构建。 +* Uvicorn,一个快如闪电 ASGI 服务器,基于 uvloop 和 httptools 构建。 -
+
+ +```console +$ pip install "uvicorn[standard]" + +---> 100% +``` - ```console - $ pip install "uvicorn[standard]" +
+ +/// tip - ---> 100% - ``` +通过添加`standard`,Uvicorn 将安装并使用一些推荐的额外依赖项。 -
+其中包括`uvloop`,它是`asyncio`的高性能替代品,它提供了巨大的并发性能提升。 - !!! tip - 通过添加`standard`,Uvicorn 将安装并使用一些推荐的额外依赖项。 +/// - 其中包括`uvloop`,它是`asyncio`的高性能替代品,它提供了巨大的并发性能提升。 +//// -=== "Hypercorn" +//// tab | Hypercorn - * Hypercorn,一个也与 HTTP/2 兼容的 ASGI 服务器。 +* Hypercorn,一个也与 HTTP/2 兼容的 ASGI 服务器。 -
+
- ```console - $ pip install hypercorn +```console +$ pip install hypercorn - ---> 100% - ``` +---> 100% +``` -
+
- ...或任何其他 ASGI 服务器。 +...或任何其他 ASGI 服务器。 +//// ## 运行服务器程序 您可以按照之前教程中的相同方式运行应用程序,但不使用`--reload`选项,例如: -=== "Uvicorn" +//// tab | Uvicorn + +
+ +```console +$ uvicorn main:app --host 0.0.0.0 --port 80 + +INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) +``` -
+
- ```console - $ uvicorn main:app --host 0.0.0.0 --port 80 +//// - INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) - ``` +//// tab | Hypercorn -
+
+```console +$ hypercorn main:app --bind 0.0.0.0:80 -=== "Hypercorn" +Running on 0.0.0.0:8080 over http (CTRL + C to quit) +``` -
+
- ```console - $ hypercorn main:app --bind 0.0.0.0:80 +//// - Running on 0.0.0.0:8080 over http (CTRL + C to quit) - ``` +/// warning -
+如果您正在使用`--reload`选项,请记住删除它。 -!!! warning - 如果您正在使用`--reload`选项,请记住删除它。 + `--reload` 选项消耗更多资源,并且更不稳定。 - `--reload` 选项消耗更多资源,并且更不稳定。 + 它在**开发**期间有很大帮助,但您**不应该**在**生产环境**中使用它。 - 它在**开发**期间有很大帮助,但您**不应该**在**生产环境**中使用它。 +/// ## Hypercorn with Trio diff --git a/docs/zh/docs/deployment/server-workers.md b/docs/zh/docs/deployment/server-workers.md index ee3de9b5d..eb0252a5c 100644 --- a/docs/zh/docs/deployment/server-workers.md +++ b/docs/zh/docs/deployment/server-workers.md @@ -13,16 +13,17 @@ 部署应用程序时,您可能希望进行一些**进程复制**,以利用**多核**并能够处理更多请求。 -正如您在上一章有关[部署概念](./concepts.md){.internal-link target=_blank}中看到的,您可以使用多种策略。 +正如您在上一章有关[部署概念](concepts.md){.internal-link target=_blank}中看到的,您可以使用多种策略。 在这里我将向您展示如何将 **Gunicorn** 与 **Uvicorn worker 进程** 一起使用。 -!!! info - 如果您正在使用容器,例如 Docker 或 Kubernetes,我将在下一章中告诉您更多相关信息:[容器中的 FastAPI - Docker](./docker.md){.internal-link target=_blank}。 +/// info - 特别是,当在 **Kubernetes** 上运行时,您可能**不想**使用 Gunicorn,而是运行 **每个容器一个 Uvicorn 进程**,但我将在本章后面告诉您这一点。 +如果您正在使用容器,例如 Docker 或 Kubernetes,我将在下一章中告诉您更多相关信息:[容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank}。 +特别是,当在 **Kubernetes** 上运行时,您可能**不想**使用 Gunicorn,而是运行 **每个容器一个 Uvicorn 进程**,但我将在本章后面告诉您这一点。 +/// ## Gunicorn with Uvicorn Workers @@ -169,7 +170,7 @@ $ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4 ## 容器和 Docker -在关于 [容器中的 FastAPI - Docker](./docker.md){.internal-link target=_blank} 的下一章中,我将介绍一些可用于处理其他 **部署概念** 的策略。 +在关于 [容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank} 的下一章中,我将介绍一些可用于处理其他 **部署概念** 的策略。 我还将向您展示 **官方 Docker 镜像**,其中包括 **Gunicorn 和 Uvicorn worker** 以及一些对简单情况有用的默认配置。 diff --git a/docs/zh/docs/deployment/versions.md b/docs/zh/docs/deployment/versions.md index 75b870139..228bb0765 100644 --- a/docs/zh/docs/deployment/versions.md +++ b/docs/zh/docs/deployment/versions.md @@ -42,8 +42,11 @@ fastapi>=0.45.0,<0.46.0 FastAPI 还遵循这样的约定:任何`PATCH`版本更改都是为了bug修复和non-breaking changes。 -!!! tip - "PATCH"是最后一个数字,例如,在`0.2.3`中,PATCH版本是`3`。 +/// tip + +"PATCH"是最后一个数字,例如,在`0.2.3`中,PATCH版本是`3`。 + +/// 因此,你应该能够固定到如下版本: @@ -53,8 +56,11 @@ fastapi>=0.45.0,<0.46.0 "MINOR"版本中会添加breaking changes和新功能。 -!!! tip - "MINOR"是中间的数字,例如,在`0.2.3`中,MINOR版本是`2`。 +/// tip + +"MINOR"是中间的数字,例如,在`0.2.3`中,MINOR版本是`2`。 + +/// ## 升级FastAPI版本 diff --git a/docs/zh/docs/environment-variables.md b/docs/zh/docs/environment-variables.md new file mode 100644 index 000000000..812278051 --- /dev/null +++ b/docs/zh/docs/environment-variables.md @@ -0,0 +1,298 @@ +# 环境变量 + +/// tip + +如果你已经知道什么是“环境变量”并且知道如何使用它们,你可以放心跳过这一部分。 + +/// + +环境变量(也称为“**env var**”)是一个独立于 Python 代码**之外**的变量,它存在于**操作系统**中,可以被你的 Python 代码(或其他程序)读取。 + +环境变量对于处理应用程序**设置**、作为 Python **安装**的一部分等方面非常有用。 + +## 创建和使用环境变量 + +你在 **shell(终端)**中就可以**创建**和使用环境变量,并不需要用到 Python: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// 你可以使用以下命令创建一个名为 MY_NAME 的环境变量 +$ export MY_NAME="Wade Wilson" + +// 然后,你可以在其他程序中使用它,例如 +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// 创建一个名为 MY_NAME 的环境变量 +$ $Env:MY_NAME = "Wade Wilson" + +// 在其他程序中使用它,例如 +$ echo "Hello $Env:MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +## 在 Python 中读取环境变量 + +你也可以在 Python **之外**的终端中创建环境变量(或使用任何其他方法),然后在 Python 中**读取**它们。 + +例如,你可以创建一个名为 `main.py` 的文件,其中包含以下内容: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// tip + +第二个参数是 `os.getenv()` 的默认返回值。 + +如果没有提供,默认值为 `None`,这里我们提供 `"World"` 作为默认值。 + +/// + +然后你可以调用这个 Python 程序: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// 这里我们还没有设置环境变量 +$ python main.py + +// 因为我们没有设置环境变量,所以我们得到的是默认值 + +Hello World from Python + +// 但是如果我们事先创建过一个环境变量 +$ export MY_NAME="Wade Wilson" + +// 然后再次调用程序 +$ python main.py + +// 现在就可以读取到环境变量了 + +Hello Wade Wilson from Python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// 这里我们还没有设置环境变量 +$ python main.py + +// 因为我们没有设置环境变量,所以我们得到的是默认值 + +Hello World from Python + +// 但是如果我们事先创建过一个环境变量 +$ $Env:MY_NAME = "Wade Wilson" + +// 然后再次调用程序 +$ python main.py + +// 现在就可以读取到环境变量了 + +Hello Wade Wilson from Python +``` + +
+ +//// + +由于环境变量可以在代码之外设置、但可以被代码读取,并且不必与其他文件一起存储(提交到 `git`),因此通常用于配置或**设置**。 + +你还可以为**特定的程序调用**创建特定的环境变量,该环境变量仅对该程序可用,且仅在其运行期间有效。 + +要实现这一点,只需在同一行内、程序本身之前创建它: + +
+ +```console +// 在这个程序调用的同一行中创建一个名为 MY_NAME 的环境变量 +$ MY_NAME="Wade Wilson" python main.py + +// 现在就可以读取到环境变量了 + +Hello Wade Wilson from Python + +// 在此之后这个环境变量将不会依然存在 +$ python main.py + +Hello World from Python +``` + +
+ +/// tip + +你可以在 The Twelve-Factor App: 配置中了解更多信息。 + +/// + +## 类型和验证 + +这些环境变量只能处理**文本字符串**,因为它们是处于 Python 范畴之外的,必须与其他程序和操作系统的其余部分兼容(甚至与不同的操作系统兼容,如 Linux、Windows、macOS)。 + +这意味着从环境变量中读取的**任何值**在 Python 中都将是一个 `str`,任何类型转换或验证都必须在代码中完成。 + +你将在[高级用户指南 - 设置和环境变量](./advanced/settings.md)中了解更多关于使用环境变量处理**应用程序设置**的信息。 + +## `PATH` 环境变量 + +有一个**特殊的**环境变量称为 **`PATH`**,操作系统(Linux、macOS、Windows)用它来查找要运行的程序。 + +`PATH` 变量的值是一个长字符串,由 Linux 和 macOS 上的冒号 `:` 分隔的目录组成,而在 Windows 上则是由分号 `;` 分隔的。 + +例如,`PATH` 环境变量可能如下所示: + +//// tab | Linux, macOS + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +这意味着系统应该在以下目录中查找程序: + +- `/usr/local/bin` +- `/usr/bin` +- `/bin` +- `/usr/sbin` +- `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32 +``` + +这意味着系统应该在以下目录中查找程序: + +- `C:\Program Files\Python312\Scripts` +- `C:\Program Files\Python312` +- `C:\Windows\System32` + +//// + +当你在终端中输入一个**命令**时,操作系统会在 `PATH` 环境变量中列出的**每个目录**中**查找**程序。 + +例如,当你在终端中输入 `python` 时,操作系统会在该列表中的**第一个目录**中查找名为 `python` 的程序。 + +如果找到了,那么操作系统将**使用它**;否则,操作系统会继续在**其他目录**中查找。 + +### 安装 Python 和更新 `PATH` + +安装 Python 时,可能会询问你是否要更新 `PATH` 环境变量。 + +//// tab | Linux, macOS + +假设你安装 Python 并最终将其安装在了目录 `/opt/custompython/bin` 中。 + +如果你同意更新 `PATH` 环境变量,那么安装程序将会将 `/opt/custompython/bin` 添加到 `PATH` 环境变量中。 + +它看起来大概会像这样: + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin +``` + +如此一来,当你在终端中输入 `python` 时,系统会在 `/opt/custompython/bin` 中找到 Python 程序(最后一个目录)并使用它。 + +//// + +//// tab | Windows + +假设你安装 Python 并最终将其安装在了目录 `C:\opt\custompython\bin` 中。 + +如果你同意更新 `PATH` 环境变量 (在 Python 安装程序中,这个操作是名为 `Add Python x.xx to PATH` 的复选框 —— 译者注),那么安装程序将会将 `C:\opt\custompython\bin` 添加到 `PATH` 环境变量中。 + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin +``` + +如此一来,当你在终端中输入 `python` 时,系统会在 `C:\opt\custompython\bin` 中找到 Python 程序(最后一个目录)并使用它。 + +//// + +因此,如果你输入: + +
+ +```console +$ python +``` + +
+ +//// tab | Linux, macOS + +系统会在 `/opt/custompython/bin` 中**找到** `python` 程序并运行它。 + +这和输入以下命令大致等价: + +
+ +```console +$ /opt/custompython/bin/python +``` + +
+ +//// + +//// tab | Windows + +系统会在 `C:\opt\custompython\bin\python` 中**找到** `python` 程序并运行它。 + +这和输入以下命令大致等价: + +
+ +```console +$ C:\opt\custompython\bin\python +``` + +
+ +//// + +当学习[虚拟环境](virtual-environments.md)时,这些信息将会很有用。 + +## 结论 + +通过这个教程,你应该对**环境变量**是什么以及如何在 Python 中使用它们有了基本的了解。 + +你也可以在环境变量 - 维基百科 (Wikipedia for Environment Variable) 中了解更多关于它们的信息。 + +在许多情况下,环境变量的用途和适用性并不是很明显。但是在开发过程中,它们会在许多不同的场景中出现,因此了解它们是很有必要的。 + +例如,你将在下一节关于[虚拟环境](virtual-environments.md)中需要这些信息。 diff --git a/docs/zh/docs/fastapi-cli.md b/docs/zh/docs/fastapi-cli.md new file mode 100644 index 000000000..8a70e1d80 --- /dev/null +++ b/docs/zh/docs/fastapi-cli.md @@ -0,0 +1,79 @@ +# FastAPI CLI + +**FastAPI CLI** 是一个命令行程序,你可以用它来部署和运行你的 FastAPI 应用程序,管理你的 FastAPI 项目,等等。 + +当你安装 FastAPI 时(例如使用 `pip install FastAPI` 命令),会包含一个名为 `fastapi-cli` 的软件包,该软件包在终端中提供 `fastapi` 命令。 + +要在开发环境中运行你的 FastAPI 应用,你可以使用 `fastapi dev` 命令: + +
+ +```console +$ fastapi dev main.py + + FastAPI Starting development server 🚀 + + Searching for package file structure from directories with + __init__.py files + Importing from /home/user/code/awesomeapp + + module 🐍 main.py + + code Importing the FastAPI app object from the module with the + following code: + + from main import app + + app Using import string: main:app + + server Server started at http://127.0.0.1:8000 + server Documentation at http://127.0.0.1:8000/docs + + tip Running in development mode, for production use: + fastapi run + + Logs: + + INFO Will watch for changes in these directories: + ['/home/user/code/awesomeapp'] + INFO Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to + quit) + INFO Started reloader process [383138] using WatchFiles + INFO Started server process [383153] + INFO Waiting for application startup. + INFO Application startup complete. +``` + +
+ +该命令行程序 `fastapi` 就是 **FastAPI CLI**。 + +FastAPI CLI 接收你的 Python 程序路径,自动检测包含 FastAPI 的变量(通常命名为 `app`)及其导入方式,然后启动服务。 + +在生产环境中,你应该使用 `fastapi run` 命令。🚀 + +在内部,**FastAPI CLI** 使用了 Uvicorn,这是一个高性能、适用于生产环境的 ASGI 服务器。😎 + +## `fastapi dev` + +当你运行 `fastapi dev` 时,它将以开发模式运行。 + +默认情况下,它会启用**自动重载**,因此当你更改代码时,它会自动重新加载服务器。该功能是资源密集型的,且相较不启用时更不稳定,因此你应该仅在开发环境下使用它。 + +默认情况下,它将监听 IP 地址 `127.0.0.1`,这是你的机器与自身通信的 IP 地址(`localhost`)。 + +## `fastapi run` + +当你运行 `fastapi run` 时,它默认以生产环境模式运行。 + +默认情况下,**自动重载是禁用的**。 + +它将监听 IP 地址 `0.0.0.0`,即所有可用的 IP 地址,这样任何能够与该机器通信的人都可以公开访问它。这通常是你在生产环境中运行它的方式,例如在容器中运行。 + +在大多数情况下,你会(且应该)有一个“终止代理”在上层为你处理 HTTPS,这取决于你如何部署应用程序,你的服务提供商可能会为你处理此事,或者你可能需要自己设置。 + +/// tip | 提示 + +你可以在 [deployment documentation](deployment/index.md){.internal-link target=_blank} 获得更多信息。 + +/// diff --git a/docs/zh/docs/fastapi-people.md b/docs/zh/docs/fastapi-people.md deleted file mode 100644 index 5d7b0923f..000000000 --- a/docs/zh/docs/fastapi-people.md +++ /dev/null @@ -1,178 +0,0 @@ -# FastAPI 社区 - -FastAPI 有一个非常棒的社区,它欢迎来自各个领域和背景的朋友。 - -## 创建者 & 维护者 - -嘿! 👋 - -这就是我: - -{% if people %} -
-{% for user in people.maintainers %} - -
@{{ user.login }}
Answers: {{ user.answers }}
Pull Requests: {{ user.prs }}
-{% endfor %} - -
-{% endif %} - -我是 **FastAPI** 的创建者和维护者. 你能在 [帮助 FastAPI - 获取帮助 - 与作者联系](help-fastapi.md#connect-with-the-author){.internal-link target=_blank} 阅读有关此内容的更多信息。 - -...但是在这里我想向您展示社区。 - ---- - -**FastAPI** 得到了社区的大力支持。因此我想突出他们的贡献。 - -这些人: - -* [帮助他人解决 GitHub 的 issues](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}。 -* [创建 Pull Requests](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}。 -* 审核 Pull Requests, 对于 [翻译](contributing.md#translations){.internal-link target=_blank} 尤为重要。 - -向他们致以掌声。 👏 🙇 - -## 上个月最活跃的用户 - -上个月这些用户致力于 [帮助他人解决 GitHub 的 issues](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}。 - -{% if people %} -
-{% for user in people.last_month_active %} - -
@{{ user.login }}
Issues replied: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## 专家组 - -以下是 **FastAPI 专家**。 🤓 - -这些用户一直以来致力于 [帮助他人解决 GitHub 的 issues](help-fastapi.md#help-others-with-issues-in-github){.internal-link target=_blank}。 - -他们通过帮助许多人而被证明是专家。✨ - -{% if people %} -
-{% for user in people.experts %} - -
@{{ user.login }}
Issues replied: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## 杰出贡献者 - -以下是 **杰出的贡献者**。 👷 - -这些用户 [创建了最多已被合并的 Pull Requests](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}。 - -他们贡献了源代码,文档,翻译等。 📦 - -{% if people %} -
-{% for user in people.top_contributors %} - -
@{{ user.login }}
Pull Requests: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -还有很多其他贡献者(超过100个),你可以在 FastAPI GitHub 贡献者页面 中看到他们。👷 - -## 杰出审核者 - -以下用户是「杰出的评审者」。 🕵️ - -### 翻译审核 - -我只会说少数几种语言(而且还不是很流利 😅)。所以,具备[能力去批准文档翻译](contributing.md#translations){.internal-link target=_blank} 是这些评审者们。如果没有它们,就不会有多语言文档。 - ---- - -**杰出的评审者** 🕵️ 评审了最多来自他人的 Pull Requests,他们保证了代码、文档尤其是 **翻译** 的质量。 - -{% if people %} -
-{% for user in people.top_reviewers %} - -
@{{ user.login }}
Reviews: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## 赞助商 - -以下是 **赞助商** 。😎 - -他们主要通过GitHub Sponsors支持我在 **FastAPI** (和其他项目)的工作。 - -{% if sponsors %} - -{% if sponsors.gold %} - -### 金牌赞助商 - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### 银牌赞助商 - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### 铜牌赞助商 - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -{% endif %} - -### 个人赞助 - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
- -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
- -{% endfor %} -{% endif %} - -## 关于数据 - 技术细节 - -该页面的目的是突出社区为帮助他人而付出的努力。 - -尤其是那些不引人注目且涉及更困难的任务,例如帮助他人解决问题或者评审翻译 Pull Requests。 - -该数据每月计算一次,您可以阅读 源代码。 - -这里也强调了赞助商的贡献。 - -我也保留更新算法,栏目,统计阈值等的权利(以防万一🤷)。 diff --git a/docs/zh/docs/features.md b/docs/zh/docs/features.md index 2db7f852a..24dc3e8ce 100644 --- a/docs/zh/docs/features.md +++ b/docs/zh/docs/features.md @@ -65,10 +65,13 @@ my_second_user: User = User(**second_user_data) ``` -!!! info - `**second_user_data` 意思是: +/// info - 直接将`second_user_data`字典的键和值直接作为key-value参数传递,等同于:`User(id=4, name="Mary", joined="2018-11-30")` +`**second_user_data` 意思是: + +直接将`second_user_data`字典的键和值直接作为key-value参数传递,等同于:`User(id=4, name="Mary", joined="2018-11-30")` + +/// ### 编辑器支持 @@ -179,7 +182,7 @@ FastAPI 有一个使用非常简单,但是非常强大的IDE/linter/brain** 适配: * 因为 pydantic 数据结构仅仅是你定义的类的实例;自动补全,linting,mypy 以及你的直觉应该可以和你验证的数据一起正常工作。 -* **更快**: - * 在 基准测试 中,Pydantic 比其他被测试的库都要快。 * 验证**复杂结构**: * 使用分层的 Pydantic 模型, Python `typing`的 `List` 和 `Dict` 等等。 * 验证器使我们能够简单清楚的将复杂的数据模式定义、检查并记录为 JSON Schema。 diff --git a/docs/zh/docs/help-fastapi.md b/docs/zh/docs/help-fastapi.md index 9b70d115a..09f37a44b 100644 --- a/docs/zh/docs/help-fastapi.md +++ b/docs/zh/docs/help-fastapi.md @@ -12,7 +12,7 @@ ## 订阅新闻邮件 -您可以订阅 [**FastAPI 和它的小伙伴** 新闻邮件](/newsletter/){.internal-link target=_blank}(不会经常收到) +您可以订阅 [**FastAPI 和它的小伙伴** 新闻邮件](newsletter.md){.internal-link target=_blank}(不会经常收到) * FastAPI 及其小伙伴的新闻 🚀 * 指南 📝 @@ -26,13 +26,13 @@ ## 在 GitHub 上为 **FastAPI** 加星 -您可以在 GitHub 上 **Star** FastAPI(只要点击右上角的星星就可以了): https://github.com/tiangolo/fastapi。⭐️ +您可以在 GitHub 上 **Star** FastAPI(只要点击右上角的星星就可以了): https://github.com/fastapi/fastapi。⭐️ **Star** 以后,其它用户就能更容易找到 FastAPI,并了解到已经有其他用户在使用它了。 ## 关注 GitHub 资源库的版本发布 -您还可以在 GitHub 上 **Watch** FastAPI,(点击右上角的 **Watch** 按钮)https://github.com/tiangolo/fastapi。👀 +您还可以在 GitHub 上 **Watch** FastAPI,(点击右上角的 **Watch** 按钮)https://github.com/fastapi/fastapi。👀 您可以选择只关注发布(**Releases only**)。 @@ -59,7 +59,7 @@ ## Tweet about **FastAPI** -Tweet about **FastAPI** 让我和大家知道您为什么喜欢 FastAPI。🎉 +Tweet about **FastAPI** 让我和大家知道您为什么喜欢 FastAPI。🎉 知道有人使用 **FastAPI**,我会很开心,我也想知道您为什么喜欢 FastAPI,以及您在什么项目/哪些公司使用 FastAPI,等等。 @@ -70,13 +70,13 @@ ## 在 GitHub 上帮助其他人解决问题 -您可以查看现有 issues,并尝试帮助其他人解决问题,说不定您能解决这些问题呢。🤓 +您可以查看现有 issues,并尝试帮助其他人解决问题,说不定您能解决这些问题呢。🤓 -如果帮助很多人解决了问题,您就有可能成为 [FastAPI 的官方专家](fastapi-people.md#experts){.internal-link target=_blank}。🎉 +如果帮助很多人解决了问题,您就有可能成为 [FastAPI 的官方专家](fastapi-people.md#_3){.internal-link target=_blank}。🎉 ## 监听 GitHub 资源库 -您可以在 GitHub 上「监听」FastAPI(点击右上角的 "watch" 按钮): https://github.com/tiangolo/fastapi. 👀 +您可以在 GitHub 上「监听」FastAPI(点击右上角的 "watch" 按钮): https://github.com/fastapi/fastapi. 👀 如果您选择 "Watching" 而不是 "Releases only",有人创建新 Issue 时,您会接收到通知。 @@ -84,7 +84,7 @@ ## 创建 Issue -您可以在 GitHub 资源库中创建 Issue,例如: +您可以在 GitHub 资源库中创建 Issue,例如: * 提出**问题**或**意见** * 提出新**特性**建议 @@ -96,9 +96,9 @@ 您可以创建 PR 为源代码做[贡献](contributing.md){.internal-link target=_blank},例如: * 修改文档错别字 -* 编辑这个文件,分享 FastAPI 的文章、视频、博客,不论是您自己的,还是您看到的都成 +* 编辑这个文件,分享 FastAPI 的文章、视频、博客,不论是您自己的,还是您看到的都成 * 注意,添加的链接要放在对应区块的开头 -* [翻译文档](contributing.md#translations){.internal-link target=_blank} +* [翻译文档](contributing.md#_8){.internal-link target=_blank} * 审阅别人翻译的文档 * 添加新的文档内容 * 修复现有问题/Bug @@ -108,11 +108,13 @@ 快加入 👥 Discord 聊天服务器 👥 和 FastAPI 社区里的小伙伴一起哈皮吧。 -!!! tip "提示" +/// tip | 提示 - 如有问题,请在 GitHub Issues 里提问,在这里更容易得到 [FastAPI 专家](fastapi-people.md#experts){.internal-link target=_blank}的帮助。 +如有问题,请在 GitHub Issues 里提问,在这里更容易得到 [FastAPI 专家](fastapi-people.md#_3){.internal-link target=_blank}的帮助。 - 聊天室仅供闲聊。 +聊天室仅供闲聊。 + +/// ### 别在聊天室里提问 @@ -120,7 +122,7 @@ GitHub Issues 里提供了模板,指引您提出正确的问题,有利于获得优质的回答,甚至可能解决您还没有想到的问题。而且就算答疑解惑要耗费不少时间,我还是会尽量在 GitHub 里回答问题。但在聊天室里,我就没功夫这么做了。😅 -聊天室里的聊天内容也不如 GitHub 里好搜索,聊天里的问答很容易就找不到了。只有在 GitHub Issues 里的问答才能帮助您成为 [FastAPI 专家](fastapi-people.md#experts){.internal-link target=_blank},在 GitHub Issues 中为您带来更多关注。 +聊天室里的聊天内容也不如 GitHub 里好搜索,聊天里的问答很容易就找不到了。只有在 GitHub Issues 里的问答才能帮助您成为 [FastAPI 专家](fastapi-people.md#_3){.internal-link target=_blank},在 GitHub Issues 中为您带来更多关注。 另一方面,聊天室里有成千上万的用户,在这里,您有很大可能遇到聊得来的人。😄 diff --git a/docs/zh/docs/history-design-future.md b/docs/zh/docs/history-design-future.md new file mode 100644 index 000000000..48cfef524 --- /dev/null +++ b/docs/zh/docs/history-design-future.md @@ -0,0 +1,78 @@ +# 历史、设计、未来 + +不久前,曾有 **FastAPI** 用户问过: + +> 这个项目有怎样的历史?好像它只用了几周就从默默无闻变得众所周知…… + +在此,我们简单回顾一下 **FastAPI** 的历史。 + +## 备选方案 + +有那么几年,我曾领导数个开发团队为诸多复杂需求创建各种 API,这些需求包括机器学习、分布系统、异步任务、NoSQL 数据库等领域。 + +作为工作的一部分,我需要调研很多备选方案、还要测试并且使用这些备选方案。 + +**FastAPI** 其实只是延续了这些前辈的历史。 + +正如[备选方案](alternatives.md){.internal-link target=_blank}一章所述: + +
+没有大家之前所做的工作,**FastAPI** 就不会存在。 + +以前创建的这些工具为它的出现提供了灵感。 + +在那几年中,我一直回避创建新的框架。首先,我尝试使用各种框架、插件、工具解决 **FastAPI** 现在的功能。 + +但到了一定程度之后,我别无选择,只能从之前的工具中汲取最优思路,并以尽量好的方式把这些思路整合在一起,使用之前甚至是不支持的语言特性(Python 3.6+ 的类型提示),从而创建一个能满足我所有需求的框架。 + +
+ +## 调研 + +通过使用之前所有的备选方案,我有机会从它们之中学到了很多东西,获取了很多想法,并以我和我的开发团队能想到的最好方式把这些思路整合成一体。 + +例如,大家都清楚,在理想状态下,它应该基于标准的 Python 类型提示。 + +而且,最好的方式是使用现有的标准。 + +因此,甚至在开发 **FastAPI** 前,我就花了几个月的时间研究 OpenAPI、JSON Schema、OAuth2 等规范。深入理解它们之间的关系、重叠及区别之处。 + +## 设计 + +然后,我又花了一些时间从用户角度(使用 FastAPI 的开发者)设计了开发者 **API**。 + +同时,我还在最流行的 Python 代码编辑器中测试了很多思路,包括 PyCharm、VS Code、基于 Jedi 的编辑器。 + +根据最新 Python 开发者调研报告显示,这几种编辑器覆盖了约 80% 的用户。 + +也就是说,**FastAPI** 针对差不多 80% 的 Python 开发者使用的编辑器进行了测试,而且其它大多数编辑器的工作方式也与之类似,因此,**FastAPI** 的优势几乎能在所有编辑器上体现。 + +通过这种方式,我就能找到尽可能减少代码重复的最佳方式,进而实现处处都有自动补全、类型提示与错误检查等支持。 + +所有这些都是为了给开发者提供最佳的开发体验。 + +## 需求项 + +经过测试多种备选方案,我最终决定使用 **Pydantic**,并充分利用它的优势。 + +我甚至为它做了不少贡献,让它完美兼容了 JSON Schema,支持多种方式定义约束声明,并基于多个编辑器,改进了它对编辑器支持(类型检查、自动补全)。 + +在开发期间,我还为 **Starlette** 做了不少贡献,这是另一个关键需求项。 + +## 开发 + +当我启动 **FastAPI** 开发的时候,绝大多数部件都已经就位,设计已经定义,需求项和工具也已经准备就绪,相关标准与规范的知识储备也非常清晰而新鲜。 + +## 未来 + +至此,**FastAPI** 及其理念已经为很多人所用。 + +对于很多用例,它比以前很多备选方案都更适用。 + +很多开发者和开发团队已经依赖 **FastAPI** 开发他们的项目(包括我和我的团队)。 + +但,**FastAPI** 仍有很多改进的余地,也还需要添加更多的功能。 + +总之,**FastAPI** 前景光明。 + +在此,我们衷心感谢[您的帮助](help-fastapi.md){.internal-link target=_blank}。 diff --git a/docs/zh/docs/how-to/configure-swagger-ui.md b/docs/zh/docs/how-to/configure-swagger-ui.md new file mode 100644 index 000000000..108e0cb95 --- /dev/null +++ b/docs/zh/docs/how-to/configure-swagger-ui.md @@ -0,0 +1,70 @@ +# 配置 Swagger UI + +你可以配置一些额外的 Swagger UI 参数. + +如果需要配置它们,可以在创建 `FastAPI()` 应用对象时或调用 `get_swagger_ui_html()` 函数时传递 `swagger_ui_parameters` 参数。 + +`swagger_ui_parameters` 接受一个直接传递给 Swagger UI的字典,包含配置参数键值对。 + +FastAPI会将这些配置转换为 **JSON**,使其与 JavaScript 兼容,因为这是 Swagger UI 需要的。 + +## 不使用语法高亮 + +比如,你可以禁用 Swagger UI 中的语法高亮。 + +当没有改变设置时,语法高亮默认启用: + + + +但是你可以通过设置 `syntaxHighlight` 为 `False` 来禁用 Swagger UI 中的语法高亮: + +{* ../../docs_src/configure_swagger_ui/tutorial001.py hl[3] *} + +...在此之后,Swagger UI 将不会高亮代码: + + + +## 改变主题 + +同样地,你也可以通过设置键 `"syntaxHighlight.theme"` 来设置语法高亮主题(注意中间有一个点): + +{* ../../docs_src/configure_swagger_ui/tutorial002.py hl[3] *} + +这个配置会改变语法高亮主题: + + + +## 改变默认 Swagger UI 参数 + +FastAPI 包含了一些默认配置参数,适用于大多数用例。 + +其包括这些默认配置参数: + +{* ../../fastapi/openapi/docs.py ln[7:23] *} + +你可以通过在 `swagger_ui_parameters` 中设置不同的值来覆盖它们。 + +比如,如果要禁用 `deepLinking`,你可以像这样传递设置到 `swagger_ui_parameters` 中: + +{* ../../docs_src/configure_swagger_ui/tutorial003.py hl[3] *} + +## 其他 Swagger UI 参数 + +查看其他 Swagger UI 参数,请阅读 docs for Swagger UI parameters。 + +## JavaScript-only 配置 + +Swagger UI 同样允许使用 **JavaScript-only** 配置对象(例如,JavaScript 函数)。 + +FastAPI 包含这些 JavaScript-only 的 `presets` 设置: + +```JavaScript +presets: [ + SwaggerUIBundle.presets.apis, + SwaggerUIBundle.SwaggerUIStandalonePreset +] +``` + +这些是 **JavaScript** 对象,而不是字符串,所以你不能直接从 Python 代码中传递它们。 + +如果你需要像这样使用 JavaScript-only 配置,你可以使用上述方法之一。覆盖所有 Swagger UI *path operation* 并手动编写任何你需要的 JavaScript。 diff --git a/docs/zh/docs/how-to/general.md b/docs/zh/docs/how-to/general.md new file mode 100644 index 000000000..e8b6dd3b2 --- /dev/null +++ b/docs/zh/docs/how-to/general.md @@ -0,0 +1,39 @@ +# 通用 - 如何操作 - 诀窍 + +这里是一些指向文档中其他部分的链接,用于解答一般性或常见问题。 + +## 数据过滤 - 安全性 + +为确保不返回超过需要的数据,请阅读 [教程 - 响应模型 - 返回类型](../tutorial/response-model.md){.internal-link target=_blank} 文档。 + +## 文档的标签 - OpenAPI + +在文档界面中添加**路径操作**的标签和进行分组,请阅读 [教程 - 路径操作配置 - Tags 参数](../tutorial/path-operation-configuration.md#tags){.internal-link target=_blank} 文档。 + +## 文档的概要和描述 - OpenAPI + +在文档界面中添加**路径操作**的概要和描述,请阅读 [教程 - 路径操作配置 - Summary 和 Description 参数](../tutorial/path-operation-configuration.md#summary-description){.internal-link target=_blank} 文档。 + +## 文档的响应描述 - OpenAPI + +在文档界面中定义并显示响应描述,请阅读 [教程 - 路径操作配置 - 响应描述](../tutorial/path-operation-configuration.md#response-description){.internal-link target=_blank} 文档。 + +## 文档弃用**路径操作** - OpenAPI + +在文档界面中显示弃用的**路径操作**,请阅读 [教程 - 路径操作配置 - 弃用](../tutorial/path-operation-configuration.md#deprecate-a-path-operation){.internal-link target=_blank} 文档。 + +## 将任何数据转换为 JSON 兼容格式 + +要将任何数据转换为 JSON 兼容格式,请阅读 [教程 - JSON 兼容编码器](../tutorial/encoder.md){.internal-link target=_blank} 文档。 + +## OpenAPI 元数据 - 文档 + +要添加 OpenAPI 的元数据,包括许可证、版本、联系方式等,请阅读 [教程 - 元数据和文档 URL](../tutorial/metadata.md){.internal-link target=_blank} 文档。 + +## OpenAPI 自定义 URL + +要自定义 OpenAPI 的 URL(或删除它),请阅读 [教程 - 元数据和文档 URL](../tutorial/metadata.md#openapi-url){.internal-link target=_blank} 文档。 + +## OpenAPI 文档 URL + +要更改用于自动生成文档的 URL,请阅读 [教程 - 元数据和文档 URL](../tutorial/metadata.md#docs-urls){.internal-link target=_blank}. diff --git a/docs/zh/docs/how-to/index.md b/docs/zh/docs/how-to/index.md new file mode 100644 index 000000000..ac097618b --- /dev/null +++ b/docs/zh/docs/how-to/index.md @@ -0,0 +1,13 @@ +# 如何操作 - 诀窍 + +在这里,你将看到关于**多个主题**的不同诀窍或“如何操作”指南。 + +这些方法多数是**相互独立**的,在大多数情况下,你只需在这些内容适用于**你的项目**时才需要学习它们。 + +如果某些内容看起来对你的项目有用,请继续查阅,否则请直接跳过它们。 + +/// tip | 小技巧 + +如果你想以系统的方式**学习 FastAPI**(推荐),请阅读 [教程 - 用户指南](../tutorial/index.md){.internal-link target=_blank} 的每一章节。 + +/// diff --git a/docs/zh/docs/index.md b/docs/zh/docs/index.md index d776e5813..94cf8745c 100644 --- a/docs/zh/docs/index.md +++ b/docs/zh/docs/index.md @@ -1,3 +1,9 @@ +# FastAPI + + +

FastAPI

@@ -5,26 +11,29 @@ FastAPI 框架,高性能,易于学习,高效编码,生产可用

- - Test + + Test - - Coverage + + Coverage Package version + + Supported Python versions +

--- **文档**: https://fastapi.tiangolo.com -**源码**: https://github.com/tiangolo/fastapi +**源码**: https://github.com/fastapi/fastapi --- -FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用 Python 3.8+ 并基于标准的 Python 类型提示。 +FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用 Python 并基于标准的 Python 类型提示。 关键特性: @@ -61,7 +70,7 @@ FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框 「_[...] 最近我一直在使用 **FastAPI**。[...] 实际上我正在计划将其用于我所在的**微软**团队的所有**机器学习服务**。其中一些服务正被集成进核心 **Windows** 产品和一些 **Office** 产品。_」 -
Kabir Khan - 微软 (ref)
+
Kabir Khan - 微软 (ref)
--- @@ -85,7 +94,7 @@ FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框 「_老实说,你的作品看起来非常可靠和优美。在很多方面,这就是我想让 **Hug** 成为的样子 - 看到有人实现了它真的很鼓舞人心。_」 -
Timothy Crosley - Hug 作者 (ref)
+
Timothy Crosley - Hug 作者 (ref)
--- @@ -107,12 +116,12 @@ FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框 ## 依赖 -Python 3.8 及更高版本 +Python 及更高版本 FastAPI 站在以下巨人的肩膀之上: * Starlette 负责 web 部分。 -* Pydantic 负责数据部分。 +* Pydantic 负责数据部分。 ## 安装 @@ -126,7 +135,7 @@ $ pip install fastapi -你还会需要一个 ASGI 服务器,生产环境可以使用 Uvicorn 或者 Hypercorn。 +你还会需要一个 ASGI 服务器,生产环境可以使用 Uvicorn 或者 Hypercorn
@@ -187,7 +196,7 @@ async def read_item(item_id: int, q: Union[str, None] = None): **Note**: -如果你不知道是否会用到,可以查看文档的 _"In a hurry?"_ 章节中 关于 `async` 和 `await` 的部分。 +如果你不知道是否会用到,可以查看文档的 _"In a hurry?"_ 章节中 关于 `async` 和 `await` 的部分
@@ -323,7 +332,7 @@ def update_item(item_id: int, item: Item): 你不需要去学习新的语法、了解特定库的方法或类,等等。 -只需要使用标准的 **Python 3.8 及更高版本**。 +只需要使用标准的 **Python 及更高版本**。 举个例子,比如声明 `int` 类型: @@ -410,7 +419,7 @@ item: Item ![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) -教程 - 用户指南 中有包含更多特性的更完整示例。 +教程 - 用户指南 中有包含更多特性的更完整示例。 **剧透警告**: 教程 - 用户指南中的内容有: @@ -431,30 +440,30 @@ item: Item 独立机构 TechEmpower 所作的基准测试结果显示,基于 Uvicorn 运行的 **FastAPI** 程序是 最快的 Python web 框架之一,仅次于 Starlette 和 Uvicorn 本身(FastAPI 内部使用了它们)。(*) -想了解更多,请查阅 基准测试 章节。 +想了解更多,请查阅 基准测试 章节。 ## 可选依赖 用于 Pydantic: -* email_validator - 用于 email 校验。 +* email-validator - 用于 email 校验。 用于 Starlette: * httpx - 使用 `TestClient` 时安装。 * jinja2 - 使用默认模板配置时安装。 -* python-multipart - 需要通过 `request.form()` 对表单进行「解析」时安装。 +* python-multipart - 需要通过 `request.form()` 对表单进行「解析」时安装。 * itsdangerous - 需要 `SessionMiddleware` 支持时安装。 * pyyaml - 使用 Starlette 提供的 `SchemaGenerator` 时安装(有 FastAPI 你可能并不需要它)。 * graphene - 需要 `GraphQLApp` 支持时安装。 -* ujson - 使用 `UJSONResponse` 时安装。 用于 FastAPI / Starlette: * uvicorn - 用于加载和运行你的应用程序的服务器。 * orjson - 使用 `ORJSONResponse` 时安装。 +* ujson - 使用 `UJSONResponse` 时安装。 -你可以通过 `pip install fastapi[all]` 命令来安装以上所有依赖。 +你可以通过 `pip install "fastapi[all]"` 命令来安装以上所有依赖。 ## 许可协议 diff --git a/docs/zh/docs/project-generation.md b/docs/zh/docs/project-generation.md new file mode 100644 index 000000000..48eb990df --- /dev/null +++ b/docs/zh/docs/project-generation.md @@ -0,0 +1,28 @@ +# FastAPI全栈模板 + +模板通常带有特定的设置,而且被设计为灵活和可定制的。这允许您根据项目的需求修改和调整它们,使它们成为一个很好的起点。🏁 + +您可以使用此模板开始,因为它包含了许多已经为您完成的初始设置、安全性、数据库和一些API端点。 + +代码仓: Full Stack FastAPI Template + +## FastAPI全栈模板 - 技术栈和特性 + +- ⚡ [**FastAPI**](https://fastapi.tiangolo.com) 用于Python后端API. + - 🧰 [SQLModel](https://sqlmodel.tiangolo.com) 用于Python和SQL数据库的集成(ORM)。 + - 🔍 [Pydantic](https://docs.pydantic.dev) FastAPI的依赖项之一,用于数据验证和配置管理。 + - 💾 [PostgreSQL](https://www.postgresql.org) 作为SQL数据库。 +- 🚀 [React](https://react.dev) 用于前端。 + - 💃 使用了TypeScript、hooks、[Vite](https://vitejs.dev)和其他一些现代化的前端技术栈。 + - 🎨 [Chakra UI](https://chakra-ui.com) 用于前端组件。 + - 🤖 一个自动化生成的前端客户端。 + - 🧪 [Playwright](https://playwright.dev)用于端到端测试。 + - 🦇 支持暗黑主题(Dark mode)。 +- 🐋 [Docker Compose](https://www.docker.com) 用于开发环境和生产环境。 +- 🔒 默认使用密码哈希来保证安全。 +- 🔑 JWT令牌用于权限验证。 +- 📫 使用邮箱来进行密码恢复。 +- ✅ 单元测试用了[Pytest](https://pytest.org). +- 📞 [Traefik](https://traefik.io) 用于反向代理和负载均衡。 +- 🚢 部署指南(Docker Compose)包含了如何起一个Traefik前端代理来自动化HTTPS认证。 +- 🏭 CI(持续集成)和 CD(持续部署)基于GitHub Actions。 diff --git a/docs/zh/docs/python-types.md b/docs/zh/docs/python-types.md index 6cdb4b588..5126cb847 100644 --- a/docs/zh/docs/python-types.md +++ b/docs/zh/docs/python-types.md @@ -12,16 +12,18 @@ 但即使你不会用到 **FastAPI**,了解一下类型提示也会让你从中受益。 -!!! note - 如果你已经精通 Python,并且了解关于类型提示的一切知识,直接跳到下一章节吧。 +/// note + +如果你已经精通 Python,并且了解关于类型提示的一切知识,直接跳到下一章节吧。 + +/// ## 动机 让我们从一个简单的例子开始: -```Python -{!../../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py *} + 运行这段程序将输出: @@ -35,9 +37,8 @@ John Doe * 通过 `title()` 将每个参数的第一个字母转换为大写形式。 * 中间用一个空格来拼接它们。 -```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial001.py!} -``` +{* ../../docs_src/python_types/tutorial001.py hl[2] *} + ### 修改示例 @@ -79,9 +80,8 @@ John Doe 这些就是"类型提示": -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial002.py!} -``` +{* ../../docs_src/python_types/tutorial002.py hl[1] *} + 这和声明默认值是不同的,例如: @@ -109,9 +109,8 @@ John Doe 下面是一个已经有类型提示的函数: -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial003.py!} -``` +{* ../../docs_src/python_types/tutorial003.py hl[1] *} + 因为编辑器已经知道了这些变量的类型,所以不仅能对代码进行补全,还能检查其中的错误: @@ -119,9 +118,8 @@ John Doe 现在你知道了必须先修复这个问题,通过 `str(age)` 把 `age` 转换成字符串: -```Python hl_lines="2" -{!../../../docs_src/python_types/tutorial004.py!} -``` +{* ../../docs_src/python_types/tutorial004.py hl[2] *} + ## 声明类型 @@ -140,9 +138,8 @@ John Doe * `bool` * `bytes` -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial005.py!} -``` +{* ../../docs_src/python_types/tutorial005.py hl[1] *} + ### 嵌套类型 @@ -158,9 +155,8 @@ John Doe 从 `typing` 模块导入 `List`(注意是大写的 `L`): -```Python hl_lines="1" -{!../../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[1] *} + 同样以冒号(`:`)来声明这个变量。 @@ -168,9 +164,8 @@ John Doe 由于列表是带有"子类型"的类型,所以我们把子类型放在方括号中: -```Python hl_lines="4" -{!../../../docs_src/python_types/tutorial006.py!} -``` +{* ../../docs_src/python_types/tutorial006.py hl[4] *} + 这表示:"变量 `items` 是一个 `list`,并且这个列表里的每一个元素都是 `str`"。 @@ -188,9 +183,8 @@ John Doe 声明 `tuple` 和 `set` 的方法也是一样的: -```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial007.py!} -``` +{* ../../docs_src/python_types/tutorial007.py hl[1,4] *} + 这表示: @@ -205,9 +199,8 @@ John Doe 第二个子类型声明 `dict` 的所有值: -```Python hl_lines="1 4" -{!../../../docs_src/python_types/tutorial008.py!} -``` +{* ../../docs_src/python_types/tutorial008.py hl[1,4] *} + 这表示: @@ -221,15 +214,13 @@ John Doe 假设你有一个名为 `Person` 的类,拥有 name 属性: -```Python hl_lines="1-3" -{!../../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[1:3] *} + 接下来,你可以将一个变量声明为 `Person` 类型: -```Python hl_lines="6" -{!../../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py hl[6] *} + 然后,你将再次获得所有的编辑器支持: @@ -237,7 +228,7 @@ John Doe ## Pydantic 模型 -Pydantic 是一个用来用来执行数据校验的 Python 库。 +Pydantic 是一个用来用来执行数据校验的 Python 库。 你可以将数据的"结构"声明为具有属性的类。 @@ -249,12 +240,14 @@ John Doe 下面的例子来自 Pydantic 官方文档: -```Python -{!../../../docs_src/python_types/tutorial010.py!} -``` +{* ../../docs_src/python_types/tutorial010.py *} + -!!! info - 想进一步了解 Pydantic,请阅读其文档. +/// info + +想进一步了解 Pydantic,请阅读其文档. + +/// 整个 **FastAPI** 建立在 Pydantic 的基础之上。 @@ -282,5 +275,8 @@ John Doe 最重要的是,通过使用标准的 Python 类型,只需要在一个地方声明(而不是添加更多的类、装饰器等),**FastAPI** 会为你完成很多的工作。 -!!! info - 如果你已经阅读了所有教程,回过头来想了解有关类型的更多信息,来自 `mypy` 的"速查表"是不错的资源。 +/// info + +如果你已经阅读了所有教程,回过头来想了解有关类型的更多信息,来自 `mypy` 的"速查表"是不错的资源。 + +/// diff --git a/docs/zh/docs/tutorial/background-tasks.md b/docs/zh/docs/tutorial/background-tasks.md index 94b75d4fd..40e61add7 100644 --- a/docs/zh/docs/tutorial/background-tasks.md +++ b/docs/zh/docs/tutorial/background-tasks.md @@ -15,9 +15,7 @@ 首先导入 `BackgroundTasks` 并在 *路径操作函数* 中使用类型声明 `BackgroundTasks` 定义一个参数: -```Python hl_lines="1 13" -{!../../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[1, 13] *} **FastAPI** 会创建一个 `BackgroundTasks` 类型的对象并作为该参数传入。 @@ -33,17 +31,13 @@ 由于写操作不使用 `async` 和 `await`,我们用普通的 `def` 定义函数: -```Python hl_lines="6-9" -{!../../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *} ## 添加后台任务 在你的 *路径操作函数* 里,用 `.add_task()` 方法将任务函数传到 *后台任务* 对象中: -```Python hl_lines="14" -{!../../../docs_src/background_tasks/tutorial001.py!} -``` +{* ../../docs_src/background_tasks/tutorial001.py hl[14] *} `.add_task()` 接收以下参数: @@ -57,41 +51,47 @@ **FastAPI** 知道在每种情况下该做什么以及如何复用同一对象,因此所有后台任务被合并在一起并且随后在后台运行: -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!} - ``` +{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13, 15, 22, 25] *} -=== "Python 3.9+" +//// - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +{* ../../docs_src/background_tasks/tutorial002_an_py39.py hl[13, 15, 22, 25] *} - ```Python hl_lines="14 16 23 26" - {!> ../../../docs_src/background_tasks/tutorial002_an.py!} - ``` +//// -=== "Python 3.10+ 没Annotated" +//// tab | Python 3.8+ - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +{* ../../docs_src/background_tasks/tutorial002_an.py hl[14, 16, 23, 26] *} - ```Python hl_lines="11 13 20 23" - {!> ../../../docs_src/background_tasks/tutorial002_py310.py!} - ``` +//// -=== "Python 3.8+ 没Annotated" +//// tab | Python 3.10+ 没Annotated - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +/// tip - ```Python hl_lines="13 15 22 25" - {!> ../../../docs_src/background_tasks/tutorial002.py!} - ``` +尽可能选择使用 `Annotated` 的版本。 + +/// + +{* ../../docs_src/background_tasks/tutorial002_py310.py hl[11, 13, 20, 23] *} + +//// + +//// tab | Python 3.8+ 没Annotated + +/// tip + +尽可能选择使用 `Annotated` 的版本。 + +/// + +{* ../../docs_src/background_tasks/tutorial002.py hl[13, 15, 22, 25] *} + +//// 该示例中,信息会在响应发出 *之后* 被写到 `log.txt` 文件。 @@ -117,8 +117,6 @@ 它们往往需要更复杂的配置,即消息/作业队列管理器,如RabbitMQ或Redis,但它们允许您在多个进程中运行后台任务,甚至是在多个服务器中。 -要查看示例,查阅 [Project Generators](../project-generation.md){.internal-link target=_blank},它们都包括已经配置的Celery。 - 但是,如果您需要从同一个**FastAPI**应用程序访问变量和对象,或者您需要执行小型后台任务(如发送电子邮件通知),您只需使用 `BackgroundTasks` 即可。 ## 回顾 diff --git a/docs/zh/docs/tutorial/bigger-applications.md b/docs/zh/docs/tutorial/bigger-applications.md index 138959566..318e10fd7 100644 --- a/docs/zh/docs/tutorial/bigger-applications.md +++ b/docs/zh/docs/tutorial/bigger-applications.md @@ -4,8 +4,11 @@ **FastAPI** 提供了一个方便的工具,可以在保持所有灵活性的同时构建你的应用程序。 -!!! info - 如果你来自 Flask,那这将相当于 Flask 的 Blueprints。 +/// info + +如果你来自 Flask,那这将相当于 Flask 的 Blueprints。 + +/// ## 一个文件结构示例 @@ -26,16 +29,19 @@ │   └── admin.py ``` -!!! tip - 上面有几个 `__init__.py` 文件:每个目录或子目录中都有一个。 +/// tip + +上面有几个 `__init__.py` 文件:每个目录或子目录中都有一个。 - 这就是能将代码从一个文件导入到另一个文件的原因。 +这就是能将代码从一个文件导入到另一个文件的原因。 - 例如,在 `app/main.py` 中,你可以有如下一行: +例如,在 `app/main.py` 中,你可以有如下一行: + +``` +from app.routers import items +``` - ``` - from app.routers import items - ``` +/// * `app` 目录包含了所有内容。并且它有一个空文件 `app/__init__.py`,因此它是一个「Python 包」(「Python 模块」的集合):`app`。 * 它包含一个 `app/main.py` 文件。由于它位于一个 Python 包(一个包含 `__init__.py` 文件的目录)中,因此它是该包的一个「模块」:`app.main`。 @@ -80,7 +86,7 @@ 你可以导入它并通过与 `FastAPI` 类相同的方式创建一个「实例」: ```Python hl_lines="1 3" title="app/routers/users.py" -{!../../../docs_src/bigger_applications/app/routers/users.py!} +{!../../docs_src/bigger_applications/app/routers/users.py!} ``` ### 使用 `APIRouter` 的*路径操作* @@ -90,7 +96,7 @@ 使用方式与 `FastAPI` 类相同: ```Python hl_lines="6 11 16" title="app/routers/users.py" -{!../../../docs_src/bigger_applications/app/routers/users.py!} +{!../../docs_src/bigger_applications/app/routers/users.py!} ``` 你可以将 `APIRouter` 视为一个「迷你 `FastAPI`」类。 @@ -99,8 +105,11 @@ 所有相同的 `parameters`、`responses`、`dependencies`、`tags` 等等。 -!!! tip - 在此示例中,该变量被命名为 `router`,但你可以根据你的想法自由命名。 +/// tip + +在此示例中,该变量被命名为 `router`,但你可以根据你的想法自由命名。 + +/// 我们将在主 `FastAPI` 应用中包含该 `APIRouter`,但首先,让我们来看看依赖项和另一个 `APIRouter`。 @@ -113,13 +122,16 @@ 现在我们将使用一个简单的依赖项来读取一个自定义的 `X-Token` 请求首部: ```Python hl_lines="1 4-6" title="app/dependencies.py" -{!../../../docs_src/bigger_applications/app/dependencies.py!} +{!../../docs_src/bigger_applications/app/dependencies.py!} ``` -!!! tip - 我们正在使用虚构的请求首部来简化此示例。 +/// tip + +我们正在使用虚构的请求首部来简化此示例。 + +但在实际情况下,使用集成的[安全性实用工具](security/index.md){.internal-link target=_blank}会得到更好的效果。 - 但在实际情况下,使用集成的[安全性实用工具](./security/index.md){.internal-link target=_blank}会得到更好的效果。 +/// ## 其他使用 `APIRouter` 的模块 @@ -144,7 +156,7 @@ 因此,我们可以将其添加到 `APIRouter` 中,而不是将其添加到每个路径操作中。 ```Python hl_lines="5-10 16 21" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` 由于每个*路径操作*的路径都必须以 `/` 开头,例如: @@ -163,8 +175,11 @@ async def read_item(item_id: str): 我们可以添加一个 `dependencies` 列表,这些依赖项将被添加到路由器中的所有*路径操作*中,并将针对向它们发起的每个请求执行/解决。 -!!! tip - 请注意,和[*路径操作装饰器*中的依赖项](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}很类似,没有值会被传递给你的*路径操作函数*。 +/// tip + +请注意,和[*路径操作装饰器*中的依赖项](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}很类似,没有值会被传递给你的*路径操作函数*。 + +/// 最终结果是项目相关的路径现在为: @@ -181,11 +196,17 @@ async def read_item(item_id: str): * 路由器的依赖项最先执行,然后是[装饰器中的 `dependencies`](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank},再然后是普通的参数依赖项。 * 你还可以添加[具有 `scopes` 的 `Security` 依赖项](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}。 -!!! tip - 在 `APIRouter`中具有 `dependencies` 可以用来,例如,对一整组的*路径操作*要求身份认证。即使这些依赖项并没有分别添加到每个路径操作中。 +/// tip + +在 `APIRouter`中具有 `dependencies` 可以用来,例如,对一整组的*路径操作*要求身份认证。即使这些依赖项并没有分别添加到每个路径操作中。 + +/// + +/// check -!!! check - `prefix`、`tags`、`responses` 以及 `dependencies` 参数只是(和其他很多情况一样)**FastAPI** 的一个用于帮助你避免代码重复的功能。 +`prefix`、`tags`、`responses` 以及 `dependencies` 参数只是(和其他很多情况一样)**FastAPI** 的一个用于帮助你避免代码重复的功能。 + +/// ### 导入依赖项 @@ -196,13 +217,16 @@ async def read_item(item_id: str): 因此,我们通过 `..` 对依赖项使用了相对导入: ```Python hl_lines="3" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` #### 相对导入如何工作 -!!! tip - 如果你完全了解导入的工作原理,请从下面的下一部分继续。 +/// tip + +如果你完全了解导入的工作原理,请从下面的下一部分继续。 + +/// 一个单点 `.`,例如: @@ -266,13 +290,16 @@ from ...dependencies import get_token_header 但是我们仍然可以添加*更多*将会应用于特定的*路径操作*的 `tags`,以及一些特定于该*路径操作*的额外 `responses`: ```Python hl_lines="30-31" title="app/routers/items.py" -{!../../../docs_src/bigger_applications/app/routers/items.py!} +{!../../docs_src/bigger_applications/app/routers/items.py!} ``` -!!! tip - 最后的这个路径操作将包含标签的组合:`["items","custom"]`。 +/// tip + +最后的这个路径操作将包含标签的组合:`["items","custom"]`。 - 并且在文档中也会有两个响应,一个用于 `404`,一个用于 `403`。 +并且在文档中也会有两个响应,一个用于 `404`,一个用于 `403`。 + +/// ## `FastAPI` 主体 @@ -291,7 +318,7 @@ from ...dependencies import get_token_header 我们甚至可以声明[全局依赖项](dependencies/global-dependencies.md){.internal-link target=_blank},它会和每个 `APIRouter` 的依赖项组合在一起: ```Python hl_lines="1 3 7" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` ### 导入 `APIRouter` @@ -299,7 +326,7 @@ from ...dependencies import get_token_header 现在,我们导入具有 `APIRouter` 的其他子模块: ```Python hl_lines="5" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` 由于文件 `app/routers/users.py` 和 `app/routers/items.py` 是同一 Python 包 `app` 一个部分的子模块,因此我们可以使用单个点 ` .` 通过「相对导入」来导入它们。 @@ -328,20 +355,23 @@ from .routers import items, users from app.routers import items, users ``` -!!! info - 第一个版本是「相对导入」: +/// info + +第一个版本是「相对导入」: - ```Python - from .routers import items, users - ``` +```Python +from .routers import items, users +``` - 第二个版本是「绝对导入」: +第二个版本是「绝对导入」: + +```Python +from app.routers import items, users +``` - ```Python - from app.routers import items, users - ``` +要了解有关 Python 包和模块的更多信息,请查阅关于 Modules 的 Python 官方文档。 - 要了解有关 Python 包和模块的更多信息,请查阅关于 Modules 的 Python 官方文档。 +/// ### 避免名称冲突 @@ -361,7 +391,7 @@ from .routers.users import router 因此,为了能够在同一个文件中使用它们,我们直接导入子模块: ```Python hl_lines="5" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` ### 包含 `users` 和 `items` 的 `APIRouter` @@ -369,29 +399,38 @@ from .routers.users import router 现在,让我们来包含来自 `users` 和 `items` 子模块的 `router`。 ```Python hl_lines="10-11" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` -!!! info - `users.router` 包含了 `app/routers/users.py` 文件中的 `APIRouter`。 +/// info - `items.router` 包含了 `app/routers/items.py` 文件中的 `APIRouter`。 +`users.router` 包含了 `app/routers/users.py` 文件中的 `APIRouter`。 + +`items.router` 包含了 `app/routers/items.py` 文件中的 `APIRouter`。 + +/// 使用 `app.include_router()`,我们可以将每个 `APIRouter` 添加到主 `FastAPI` 应用程序中。 它将包含来自该路由器的所有路由作为其一部分。 -!!! note "技术细节" - 实际上,它将在内部为声明在 `APIRouter` 中的每个*路径操作*创建一个*路径操作*。 +/// note | 技术细节 + +实际上,它将在内部为声明在 `APIRouter` 中的每个*路径操作*创建一个*路径操作*。 + +所以,在幕后,它实际上会像所有的东西都是同一个应用程序一样工作。 + +/// - 所以,在幕后,它实际上会像所有的东西都是同一个应用程序一样工作。 +/// check -!!! check - 包含路由器时,你不必担心性能问题。 +包含路由器时,你不必担心性能问题。 - 这将花费几微秒时间,并且只会在启动时发生。 +这将花费几微秒时间,并且只会在启动时发生。 - 因此,它不会影响性能。⚡ +因此,它不会影响性能。⚡ + +/// ### 包含一个有自定义 `prefix`、`tags`、`responses` 和 `dependencies` 的 `APIRouter` @@ -402,7 +441,7 @@ from .routers.users import router 对于此示例,它将非常简单。但是假设由于它是与组织中的其他项目所共享的,因此我们无法对其进行修改,以及直接在 `APIRouter` 中添加 `prefix`、`dependencies`、`tags` 等: ```Python hl_lines="3" title="app/internal/admin.py" -{!../../../docs_src/bigger_applications/app/internal/admin.py!} +{!../../docs_src/bigger_applications/app/internal/admin.py!} ``` 但是我们仍然希望在包含 `APIRouter` 时设置一个自定义的 `prefix`,以便其所有*路径操作*以 `/admin` 开头,我们希望使用本项目已经有的 `dependencies` 保护它,并且我们希望它包含自定义的 `tags` 和 `responses`。 @@ -410,7 +449,7 @@ from .routers.users import router 我们可以通过将这些参数传递给 `app.include_router()` 来完成所有的声明,而不必修改原始的 `APIRouter`: ```Python hl_lines="14-17" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` 这样,原始的 `APIRouter` 将保持不变,因此我们仍然可以与组织中的其他项目共享相同的 `app/internal/admin.py` 文件。 @@ -433,21 +472,24 @@ from .routers.users import router 这里我们这样做了...只是为了表明我们可以做到🤷: ```Python hl_lines="21-23" title="app/main.py" -{!../../../docs_src/bigger_applications/app/main.py!} +{!../../docs_src/bigger_applications/app/main.py!} ``` 它将与通过 `app.include_router()` 添加的所有其他*路径操作*一起正常运行。 -!!! info "特别的技术细节" - **注意**:这是一个非常技术性的细节,你也许可以**直接跳过**。 +/// info | 特别的技术细节 + +**注意**:这是一个非常技术性的细节,你也许可以**直接跳过**。 + +--- - --- +`APIRouter` 没有被「挂载」,它们与应用程序的其余部分没有隔离。 - `APIRouter` 没有被「挂载」,它们与应用程序的其余部分没有隔离。 +这是因为我们想要在 OpenAPI 模式和用户界面中包含它们的*路径操作*。 - 这是因为我们想要在 OpenAPI 模式和用户界面中包含它们的*路径操作*。 +由于我们不能仅仅隔离它们并独立于其余部分来「挂载」它们,因此*路径操作*是被「克隆的」(重新创建),而不是直接包含。 - 由于我们不能仅仅隔离它们并独立于其余部分来「挂载」它们,因此*路径操作*是被「克隆的」(重新创建),而不是直接包含。 +/// ## 查看自动化的 API 文档 diff --git a/docs/zh/docs/tutorial/body-fields.md b/docs/zh/docs/tutorial/body-fields.md index fb6c6d9b6..4cff58bfc 100644 --- a/docs/zh/docs/tutorial/body-fields.md +++ b/docs/zh/docs/tutorial/body-fields.md @@ -1,112 +1,53 @@ # 请求体 - 字段 -与使用 `Query`、`Path` 和 `Body` 在*路径操作函数*中声明额外的校验和元数据的方式相同,你可以使用 Pydantic 的 `Field` 在 Pydantic 模型内部声明校验和元数据。 +与在*路径操作函数*中使用 `Query`、`Path` 、`Body` 声明校验与元数据的方式一样,可以使用 Pydantic 的 `Field` 在 Pydantic 模型内部声明校验和元数据。 ## 导入 `Field` -首先,你必须导入它: +首先,从 Pydantic 中导入 `Field`: -=== "Python 3.10+" +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[4] *} - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} - ``` +/// warning | 警告 -=== "Python 3.9+" +注意,与从 `fastapi` 导入 `Query`,`Path`、`Body` 不同,要直接从 `pydantic` 导入 `Field` 。 - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! tip - 尽可能选择使用 `Annotated` 的版本。 - - ```Python hl_lines="2" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - 尽可能选择使用 `Annotated` 的版本。 - - ```Python hl_lines="4" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` - -!!! warning - 注意,`Field` 是直接从 `pydantic` 导入的,而不是像其他的(`Query`,`Path`,`Body` 等)都从 `fastapi` 导入。 +/// ## 声明模型属性 -然后,你可以对模型属性使用 `Field`: - -=== "Python 3.10+" - - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="12-15" - {!> ../../../docs_src/body_fields/tutorial001_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" +然后,使用 `Field` 定义模型的属性: - !!! tip - Prefer to use the `Annotated` version if possible. +{* ../../docs_src/body_fields/tutorial001_an_py310.py hl[11:14] *} - ```Python hl_lines="9-12" - {!> ../../../docs_src/body_fields/tutorial001_py310.py!} - ``` +`Field` 的工作方式和 `Query`、`Path`、`Body` 相同,参数也相同。 -=== "Python 3.8+ non-Annotated" +/// note | 技术细节 - !!! tip - Prefer to use the `Annotated` version if possible. +实际上,`Query`、`Path` 都是 `Params` 的子类,而 `Params` 类又是 Pydantic 中 `FieldInfo` 的子类。 - ```Python hl_lines="11-14" - {!> ../../../docs_src/body_fields/tutorial001.py!} - ``` +Pydantic 的 `Field` 返回也是 `FieldInfo` 的类实例。 -`Field` 的工作方式和 `Query`、`Path` 和 `Body` 相同,包括它们的参数等等也完全相同。 +`Body` 直接返回的也是 `FieldInfo` 的子类的对象。后文还会介绍一些 `Body` 的子类。 -!!! note "技术细节" - 实际上,`Query`、`Path` 和其他你将在之后看到的类,创建的是由一个共同的 `Params` 类派生的子类的对象,该共同类本身又是 Pydantic 的 `FieldInfo` 类的子类。 +注意,从 `fastapi` 导入的 `Query`、`Path` 等对象实际上都是返回特殊类的函数。 - Pydantic 的 `Field` 也会返回一个 `FieldInfo` 的实例。 +/// - `Body` 也直接返回 `FieldInfo` 的一个子类的对象。还有其他一些你之后会看到的类是 `Body` 类的子类。 +/// tip | 提示 - 请记住当你从 `fastapi` 导入 `Query`、`Path` 等对象时,他们实际上是返回特殊类的函数。 +注意,模型属性的类型、默认值及 `Field` 的代码结构与*路径操作函数*的参数相同,只不过是用 `Field` 替换了`Path`、`Query`、`Body`。 -!!! tip - 注意每个模型属性如何使用类型、默认值和 `Field` 在代码结构上和*路径操作函数*的参数是相同的,区别是用 `Field` 替换`Path`、`Query` 和 `Body`。 +/// -## 添加额外信息 +## 添加更多信息 -你可以在 `Field`、`Query`、`Body` 中声明额外的信息。这些信息将包含在生成的 JSON Schema 中。 +`Field`、`Query`、`Body` 等对象里可以声明更多信息,并且 JSON Schema 中也会集成这些信息。 -你将在文档的后面部分学习声明示例时,了解到更多有关添加额外信息的知识。 +*声明示例*一章中将详细介绍添加更多信息的知识。 -## 总结 +## 小结 -你可以使用 Pydantic 的 `Field` 为模型属性声明额外的校验和元数据。 +Pydantic 的 `Field` 可以为模型属性声明更多校验和元数据。 -你还可以使用额外的关键字参数来传递额外的 JSON Schema 元数据。 +传递 JSON Schema 元数据还可以使用更多关键字参数。 diff --git a/docs/zh/docs/tutorial/body-multiple-params.md b/docs/zh/docs/tutorial/body-multiple-params.md index c93ef2f5c..b4356fdcb 100644 --- a/docs/zh/docs/tutorial/body-multiple-params.md +++ b/docs/zh/docs/tutorial/body-multiple-params.md @@ -8,44 +8,13 @@ 你还可以通过将默认值设置为 `None` 来将请求体参数声明为可选参数: -=== "Python 3.10+" +{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *} - ```Python hl_lines="18-20" - {!> ../../../docs_src/body_multiple_params/tutorial001_an_py310.py!} - ``` +/// note -=== "Python 3.9+" +请注意,在这种情况下,将从请求体获取的 `item` 是可选的。因为它的默认值为 `None`。 - ```Python hl_lines="18-20" - {!> ../../../docs_src/body_multiple_params/tutorial001_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! tip - 尽可能选择使用 `Annotated` 的版本。 - - ```Python hl_lines="17-19" - {!> ../../../docs_src/body_multiple_params/tutorial001_py310.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - 尽可能选择使用 `Annotated` 的版本。 - - ```Python hl_lines="19-21" - {!> ../../../docs_src/body_multiple_params/tutorial001.py!} - ``` - -!!! note - 请注意,在这种情况下,将从请求体获取的 `item` 是可选的。因为它的默认值为 `None`。 +/// ## 多个请求体参数 @@ -62,17 +31,7 @@ 但是你也可以声明多个请求体参数,例如 `item` 和 `user`: -=== "Python 3.10+" - - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial002_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial002.py!} - ``` +{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *} 在这种情况下,**FastAPI** 将注意到该函数中有多个请求体参数(两个 Pydantic 模型参数)。 @@ -93,9 +52,11 @@ } ``` -!!! note - 请注意,即使 `item` 的声明方式与之前相同,但现在它被期望通过 `item` 键内嵌在请求体中。 +/// note +请注意,即使 `item` 的声明方式与之前相同,但现在它被期望通过 `item` 键内嵌在请求体中。 + +/// **FastAPI** 将自动对请求中的数据进行转换,因此 `item` 参数将接收指定的内容,`user` 参数也是如此。 @@ -112,41 +73,7 @@ 但是你可以使用 `Body` 指示 **FastAPI** 将其作为请求体的另一个键进行处理。 -=== "Python 3.10+" - - ```Python hl_lines="23" - {!> ../../../docs_src/body_multiple_params/tutorial003_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="23" - {!> ../../../docs_src/body_multiple_params/tutorial003_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="24" - {!> ../../../docs_src/body_multiple_params/tutorial003_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! tip - 尽可能选择使用 `Annotated` 的版本。 - - ```Python hl_lines="20" - {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - 尽可能选择使用 `Annotated` 的版本。 - - ```Python hl_lines="22" - {!> ../../../docs_src/body_multiple_params/tutorial003.py!} - ``` +{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *} 在这种情况下,**FastAPI** 将期望像这样的请求体: @@ -181,45 +108,13 @@ q: str = None 比如: -=== "Python 3.10+" - - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="28" - {!> ../../../docs_src/body_multiple_params/tutorial004_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! tip - 尽可能选择使用 `Annotated` 的版本。 - - ```Python hl_lines="25" - {!> ../../../docs_src/body_multiple_params/tutorial004_py310.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[27] *} - ```Python hl_lines="27" - {!> ../../../docs_src/body_multiple_params/tutorial004.py!} - ``` +/// info -!!! info - `Body` 同样具有与 `Query`、`Path` 以及其他后面将看到的类完全相同的额外校验和元数据参数。 +`Body` 同样具有与 `Query`、`Path` 以及其他后面将看到的类完全相同的额外校验和元数据参数。 +/// ## 嵌入单个请求体参数 @@ -235,41 +130,7 @@ item: Item = Body(embed=True) 比如: -=== "Python 3.10+" - - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="18" - {!> ../../../docs_src/body_multiple_params/tutorial005_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! tip - 尽可能选择使用 `Annotated` 的版本。 - - ```Python hl_lines="15" - {!> ../../../docs_src/body_multiple_params/tutorial005_py310.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - 尽可能选择使用 `Annotated` 的版本。 - - ```Python hl_lines="17" - {!> ../../../docs_src/body_multiple_params/tutorial005.py!} - ``` +{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *} 在这种情况下,**FastAPI** 将期望像这样的请求体: diff --git a/docs/zh/docs/tutorial/body-nested-models.md b/docs/zh/docs/tutorial/body-nested-models.md index c65308bef..df96d96b4 100644 --- a/docs/zh/docs/tutorial/body-nested-models.md +++ b/docs/zh/docs/tutorial/body-nested-models.md @@ -6,17 +6,7 @@ 你可以将一个属性定义为拥有子元素的类型。例如 Python `list`: -=== "Python 3.10+" - - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial001_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial001.py!} - ``` +{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *} 这将使 `tags` 成为一个由元素组成的列表。不过它没有声明每个元素的类型。 @@ -28,9 +18,7 @@ 首先,从 Python 的标准库 `typing` 模块中导入 `List`: -```Python hl_lines="1" -{!> ../../../docs_src/body_nested_models/tutorial002.py!} -``` +{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *} ### 声明具有子类型的 List @@ -51,23 +39,7 @@ my_list: List[str] 因此,在我们的示例中,我们可以将 `tags` 明确地指定为一个「字符串列表」: -=== "Python 3.10+" - - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial002_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial002_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial002.py!} - ``` +{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *} ## Set 类型 @@ -77,23 +49,7 @@ Python 具有一种特殊的数据类型来保存一组唯一的元素,即 `se 然后我们可以导入 `Set` 并将 `tag` 声明为一个由 `str` 组成的 `set`: -=== "Python 3.10+" - - ```Python hl_lines="12" - {!> ../../../docs_src/body_nested_models/tutorial003_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="14" - {!> ../../../docs_src/body_nested_models/tutorial003_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="1 14" - {!> ../../../docs_src/body_nested_models/tutorial003.py!} - ``` +{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *} 这样,即使你收到带有重复数据的请求,这些数据也会被转换为一组唯一项。 @@ -115,45 +71,13 @@ Pydantic 模型的每个属性都具有类型。 例如,我们可以定义一个 `Image` 模型: -=== "Python 3.10+" - - ```Python hl_lines="7-9" - {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="9-11" - {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="9-11" - {!> ../../../docs_src/body_nested_models/tutorial004.py!} - ``` +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *} ### 将子模型用作类型 然后我们可以将其用作一个属性的类型: -=== "Python 3.10+" - - ```Python hl_lines="18" - {!> ../../../docs_src/body_nested_models/tutorial004_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial004_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial004.py!} - ``` +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *} 这意味着 **FastAPI** 将期望类似于以下内容的请求体: @@ -182,27 +106,11 @@ Pydantic 模型的每个属性都具有类型。 除了普通的单一值类型(如 `str`、`int`、`float` 等)外,你还可以使用从 `str` 继承的更复杂的单一值类型。 -要了解所有的可用选项,请查看关于 来自 Pydantic 的外部类型 的文档。你将在下一章节中看到一些示例。 +要了解所有的可用选项,请查看关于 来自 Pydantic 的外部类型 的文档。你将在下一章节中看到一些示例。 例如,在 `Image` 模型中我们有一个 `url` 字段,我们可以把它声明为 Pydantic 的 `HttpUrl`,而不是 `str`: -=== "Python 3.10+" - - ```Python hl_lines="2 8" - {!> ../../../docs_src/body_nested_models/tutorial005_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="4 10" - {!> ../../../docs_src/body_nested_models/tutorial005_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="4 10" - {!> ../../../docs_src/body_nested_models/tutorial005.py!} - ``` +{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *} 该字符串将被检查是否为有效的 URL,并在 JSON Schema / OpenAPI 文档中进行记录。 @@ -210,23 +118,7 @@ Pydantic 模型的每个属性都具有类型。 你还可以将 Pydantic 模型用作 `list`、`set` 等的子类型: -=== "Python 3.10+" - - ```Python hl_lines="18" - {!> ../../../docs_src/body_nested_models/tutorial006_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial006_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="20" - {!> ../../../docs_src/body_nested_models/tutorial006.py!} - ``` +{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *} 这将期望(转换,校验,记录文档等)下面这样的 JSON 请求体: @@ -254,33 +146,23 @@ Pydantic 模型的每个属性都具有类型。 } ``` -!!! info - 请注意 `images` 键现在具有一组 image 对象是如何发生的。 +/// info -## 深度嵌套模型 +请注意 `images` 键现在具有一组 image 对象是如何发生的。 -你可以定义任意深度的嵌套模型: +/// -=== "Python 3.10+" - - ```Python hl_lines="7 12 18 21 25" - {!> ../../../docs_src/body_nested_models/tutorial007_py310.py!} - ``` +## 深度嵌套模型 -=== "Python 3.9+" +你可以定义任意深度的嵌套模型: - ```Python hl_lines="9 14 20 23 27" - {!> ../../../docs_src/body_nested_models/tutorial007_py39.py!} - ``` +{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *} -=== "Python 3.8+" +/// info - ```Python hl_lines="9 14 20 23 27" - {!> ../../../docs_src/body_nested_models/tutorial007.py!} - ``` +请注意 `Offer` 拥有一组 `Item` 而反过来 `Item` 又是一个可选的 `Image` 列表是如何发生的。 -!!! info - 请注意 `Offer` 拥有一组 `Item` 而反过来 `Item` 又是一个可选的 `Image` 列表是如何发生的。 +/// ## 纯列表请求体 @@ -292,17 +174,7 @@ images: List[Image] 例如: -=== "Python 3.9+" - - ```Python hl_lines="13" - {!> ../../../docs_src/body_nested_models/tutorial008_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="15" - {!> ../../../docs_src/body_nested_models/tutorial008.py!} - ``` +{* ../../docs_src/body_nested_models/tutorial008_py39.py hl[13] *} ## 无处不在的编辑器支持 @@ -332,26 +204,19 @@ images: List[Image] 在下面的例子中,你将接受任意键为 `int` 类型并且值为 `float` 类型的 `dict`: -=== "Python 3.9+" - - ```Python hl_lines="7" - {!> ../../../docs_src/body_nested_models/tutorial009_py39.py!} - ``` +{* ../../docs_src/body_nested_models/tutorial009_py39.py hl[7] *} -=== "Python 3.8+" +/// tip - ```Python hl_lines="9" - {!> ../../../docs_src/body_nested_models/tutorial009.py!} - ``` +请记住 JSON 仅支持将 `str` 作为键。 -!!! tip - 请记住 JSON 仅支持将 `str` 作为键。 +但是 Pydantic 具有自动转换数据的功能。 - 但是 Pydantic 具有自动转换数据的功能。 +这意味着,即使你的 API 客户端只能将字符串作为键发送,只要这些字符串内容仅包含整数,Pydantic 就会对其进行转换并校验。 - 这意味着,即使你的 API 客户端只能将字符串作为键发送,只要这些字符串内容仅包含整数,Pydantic 就会对其进行转换并校验。 +然后你接收的名为 `weights` 的 `dict` 实际上将具有 `int` 类型的键和 `float` 类型的值。 - 然后你接收的名为 `weights` 的 `dict` 实际上将具有 `int` 类型的键和 `float` 类型的值。 +/// ## 总结 diff --git a/docs/zh/docs/tutorial/body-updates.md b/docs/zh/docs/tutorial/body-updates.md index 43f20f8fc..87f88f255 100644 --- a/docs/zh/docs/tutorial/body-updates.md +++ b/docs/zh/docs/tutorial/body-updates.md @@ -6,9 +6,7 @@ 把输入数据转换为以 JSON 格式存储的数据(比如,使用 NoSQL 数据库时),可以使用 `jsonable_encoder`。例如,把 `datetime` 转换为 `str`。 -```Python hl_lines="30-35" -{!../../../docs_src/body_updates/tutorial001.py!} -``` +{* ../../docs_src/body_updates/tutorial001.py hl[30:35] *} `PUT` 用于接收替换现有数据的数据。 @@ -34,15 +32,17 @@ 即,只发送要更新的数据,其余数据保持不变。 -!!! Note "笔记" +/// note | 笔记 + +`PATCH` 没有 `PUT` 知名,也怎么不常用。 - `PATCH` 没有 `PUT` 知名,也怎么不常用。 +很多人甚至只用 `PUT` 实现部分更新。 - 很多人甚至只用 `PUT` 实现部分更新。 +**FastAPI** 对此没有任何限制,可以**随意**互换使用这两种操作。 - **FastAPI** 对此没有任何限制,可以**随意**互换使用这两种操作。 +但本指南也会分别介绍这两种操作各自的用途。 - 但本指南也会分别介绍这两种操作各自的用途。 +/// ### 使用 Pydantic 的 `exclude_unset` 参数 @@ -54,9 +54,7 @@ 然后再用它生成一个只含已设置(在请求中所发送)数据,且省略了默认值的 `dict`: -```Python hl_lines="34" -{!../../../docs_src/body_updates/tutorial002.py!} -``` +{* ../../docs_src/body_updates/tutorial002.py hl[34] *} ### 使用 Pydantic 的 `update` 参数 @@ -64,9 +62,7 @@ 例如,`stored_item_model.copy(update=update_data)`: -```Python hl_lines="35" -{!../../../docs_src/body_updates/tutorial002.py!} -``` +{* ../../docs_src/body_updates/tutorial002.py hl[35] *} ### 更新部分数据小结 @@ -83,19 +79,21 @@ * 把数据保存至数据库; * 返回更新后的模型。 -```Python hl_lines="30-37" -{!../../../docs_src/body_updates/tutorial002.py!} -``` +{* ../../docs_src/body_updates/tutorial002.py hl[30:37] *} + +/// tip | 提示 + +实际上,HTTP `PUT` 也可以完成相同的操作。 +但本节以 `PATCH` 为例的原因是,该操作就是为了这种用例创建的。 -!!! tip "提示" +/// - 实际上,HTTP `PUT` 也可以完成相同的操作。 - 但本节以 `PATCH` 为例的原因是,该操作就是为了这种用例创建的。 +/// note | 笔记 -!!! note "笔记" +注意,输入模型仍需验证。 - 注意,输入模型仍需验证。 +因此,如果希望接收的部分更新数据可以省略其他所有属性,则要把模型中所有的属性标记为可选(使用默认值或 `None`)。 - 因此,如果希望接收的部分更新数据可以省略其他所有属性,则要把模型中所有的属性标记为可选(使用默认值或 `None`)。 +为了区分用于**更新**所有可选值的模型与用于**创建**包含必选值的模型,请参照[更多模型](extra-models.md){.internal-link target=_blank} 一节中的思路。 - 为了区分用于**更新**所有可选值的模型与用于**创建**包含必选值的模型,请参照[更多模型](extra-models.md){.internal-link target=_blank} 一节中的思路。 +/// diff --git a/docs/zh/docs/tutorial/body.md b/docs/zh/docs/tutorial/body.md index 5cf53c0c2..3820fc747 100644 --- a/docs/zh/docs/tutorial/body.md +++ b/docs/zh/docs/tutorial/body.md @@ -1,55 +1,40 @@ # 请求体 -当你需要将数据从客户端(例如浏览器)发送给 API 时,你将其作为「请求体」发送。 +FastAPI 使用**请求体**从客户端(例如浏览器)向 API 发送数据。 -**请求**体是客户端发送给 API 的数据。**响应**体是 API 发送给客户端的数据。 +**请求体**是客户端发送给 API 的数据。**响应体**是 API 发送给客户端的数据。 -你的 API 几乎总是要发送**响应**体。但是客户端并不总是需要发送**请求**体。 +API 基本上肯定要发送**响应体**,但是客户端不一定发送**请求体**。 -我们使用 Pydantic 模型来声明**请求**体,并能够获得它们所具有的所有能力和优点。 +使用 Pydantic 模型声明**请求体**,能充分利用它的功能和优点。 -!!! info - 你不能使用 `GET` 操作(HTTP 方法)发送请求体。 +/// info | 说明 - 要发送数据,你必须使用下列方法之一:`POST`(较常见)、`PUT`、`DELETE` 或 `PATCH`。 +发送数据使用 `POST`(最常用)、`PUT`、`DELETE`、`PATCH` 等操作。 -## 导入 Pydantic 的 `BaseModel` +规范中没有定义使用 `GET` 发送请求体的操作,但不管怎样,FastAPI 也支持这种方式,只不过仅用于非常复杂或极端的用例。 -首先,你需要从 `pydantic` 中导入 `BaseModel`: +我们不建议使用 `GET`,因此,在 Swagger UI 交互文档中不会显示有关 `GET` 的内容,而且代理协议也不一定支持 `GET`。 -=== "Python 3.10+" +/// - ```Python hl_lines="2" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +## 导入 Pydantic 的 `BaseModel` -=== "Python 3.8+" +从 `pydantic` 中导入 `BaseModel`: - ```Python hl_lines="4" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +{* ../../docs_src/body/tutorial001_py310.py hl[2] *} ## 创建数据模型 -然后,将你的数据模型声明为继承自 `BaseModel` 的类。 - -使用标准的 Python 类型来声明所有属性: - -=== "Python 3.10+" +把数据模型声明为继承 `BaseModel` 的类。 - ```Python hl_lines="5-9" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +使用 Python 标准类型声明所有属性: -=== "Python 3.8+" +{* ../../docs_src/body/tutorial001_py310.py hl[5:9] *} - ```Python hl_lines="7-11" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +与声明查询参数一样,包含默认值的模型属性是可选的,否则就是必选的。默认值为 `None` 的模型属性也是可选的。 -和声明查询参数时一样,当一个模型属性具有默认值时,它不是必需的。否则它是一个必需属性。将默认值设为 `None` 可使其成为可选属性。 - -例如,上面的模型声明了一个这样的 JSON「`object`」(或 Python `dict`): +例如,上述模型声明如下 JSON **对象**(即 Python **字典**): ```JSON { @@ -60,7 +45,7 @@ } ``` -...由于 `description` 和 `tax` 是可选的(它们的默认值为 `None`),下面的 JSON「`object`」也将是有效的: +……由于 `description` 和 `tax` 是可选的(默认值为 `None`),下面的 JSON **对象**也有效: ```JSON { @@ -69,127 +54,109 @@ } ``` -## 声明为参数 - -使用与声明路径和查询参数的相同方式声明请求体,即可将其添加到「路径操作」中: - -=== "Python 3.10+" +## 声明请求体参数 - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial001_py310.py!} - ``` +使用与声明路径和查询参数相同的方式声明请求体,把请求体添加至*路径操作*: -=== "Python 3.8+" +{* ../../docs_src/body/tutorial001_py310.py hl[16] *} - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial001.py!} - ``` +……此处,请求体参数的类型为 `Item` 模型。 -...并且将它的类型声明为你创建的 `Item` 模型。 +## 结论 -## 结果 +仅使用 Python 类型声明,**FastAPI** 就可以: -仅仅使用了 Python 类型声明,**FastAPI** 将会: +* 以 JSON 形式读取请求体 +* (在必要时)把请求体转换为对应的类型 +* 校验数据: + * 数据无效时返回错误信息,并指出错误数据的确切位置和内容 +* 把接收的数据赋值给参数 `item` + * 把函数中请求体参数的类型声明为 `Item`,还能获得代码补全等编辑器支持 +* 为模型生成 JSON Schema,在项目中所需的位置使用 +* 这些概图是 OpenAPI 概图的部件,用于 API 文档 UI -* 将请求体作为 JSON 读取。 -* 转换为相应的类型(在需要时)。 -* 校验数据。 - * 如果数据无效,将返回一条清晰易读的错误信息,指出不正确数据的确切位置和内容。 -* 将接收的数据赋值到参数 `item` 中。 - * 由于你已经在函数中将它声明为 `Item` 类型,你还将获得对于所有属性及其类型的一切编辑器支持(代码补全等)。 -* 为你的模型生成 JSON 模式 定义,你还可以在其他任何对你的项目有意义的地方使用它们。 -* 这些模式将成为生成的 OpenAPI 模式的一部分,并且被自动化文档 UI 所使用。 +## API 文档 -## 自动化文档 +Pydantic 模型的 JSON 概图是 OpenAPI 生成的概图部件,可在 API 文档中显示: -你所定义模型的 JSON 模式将成为生成的 OpenAPI 模式的一部分,并且在交互式 API 文档中展示: + - +而且,还会用于 API 文档中使用了概图的*路径操作*: -而且还将在每一个需要它们的*路径操作*的 API 文档中使用: - - + ## 编辑器支持 -在你的编辑器中,你会在函数内部的任意地方得到类型提示和代码补全(如果你接收的是一个 `dict` 而不是 Pydantic 模型,则不会发生这种情况): - - +在编辑器中,函数内部均可使用类型提示、代码补全(如果接收的不是 Pydantic 模型,而是**字典**,就没有这样的支持): -你还会获得对不正确的类型操作的错误检查: + - +还支持检查错误的类型操作: -这并非偶然,整个框架都是围绕该设计而构建。 + -并且在进行任何实现之前,已经在设计阶段经过了全面测试,以确保它可以在所有的编辑器中生效。 +这并非偶然,整个 **FastAPI** 框架都是围绕这种思路精心设计的。 -Pydantic 本身甚至也进行了一些更改以支持此功能。 +并且,在 FastAPI 的设计阶段,我们就已经进行了全面测试,以确保 FastAPI 可以获得所有编辑器的支持。 -上面的截图取自 Visual Studio Code。 +我们还改进了 Pydantic,让它也支持这些功能。 -但是在 PyCharm 和绝大多数其他 Python 编辑器中你也会获得同样的编辑器支持: +虽然上面的截图取自 Visual Studio Code。 - +但 PyCharm 和大多数 Python 编辑器也支持同样的功能: -## 使用模型 + -在函数内部,你可以直接访问模型对象的所有属性: +/// tip | 提示 -=== "Python 3.10+" +使用 PyCharm 编辑器时,推荐安装 Pydantic PyCharm 插件。 - ```Python hl_lines="19" - {!> ../../../docs_src/body/tutorial002_py310.py!} - ``` +该插件用于完善 PyCharm 对 Pydantic 模型的支持,优化的功能如下: -=== "Python 3.8+" +* 自动补全 +* 类型检查 +* 代码重构 +* 查找 +* 代码审查 - ```Python hl_lines="21" - {!> ../../../docs_src/body/tutorial002.py!} - ``` +/// -## 请求体 + 路径参数 +## 使用模型 -你可以同时声明路径参数和请求体。 +在*路径操作*函数内部直接访问模型对象的属性: -**FastAPI** 将识别出与路径参数匹配的函数参数应**从路径中获取**,而声明为 Pydantic 模型的函数参数应**从请求体中获取**。 +{* ../../docs_src/body/tutorial002_py310.py hl[19] *} -=== "Python 3.10+" +## 请求体 + 路径参数 - ```Python hl_lines="15-16" - {!> ../../../docs_src/body/tutorial003_py310.py!} - ``` +**FastAPI** 支持同时声明路径参数和请求体。 -=== "Python 3.8+" +**FastAPI** 能识别与**路径参数**匹配的函数参数,还能识别从**请求体**中获取的类型为 Pydantic 模型的函数参数。 - ```Python hl_lines="17-18" - {!> ../../../docs_src/body/tutorial003.py!} - ``` +{* ../../docs_src/body/tutorial003_py310.py hl[15:16] *} ## 请求体 + 路径参数 + 查询参数 -你还可以同时声明**请求体**、**路径参数**和**查询参数**。 +**FastAPI** 支持同时声明**请求体**、**路径参数**和**查询参数**。 + +**FastAPI** 能够正确识别这三种参数,并从正确的位置获取数据。 -**FastAPI** 会识别它们中的每一个,并从正确的位置获取数据。 +{* ../../docs_src/body/tutorial004_py310.py hl[16] *} -=== "Python 3.10+" +函数参数按如下规则进行识别: - ```Python hl_lines="16" - {!> ../../../docs_src/body/tutorial004_py310.py!} - ``` +- **路径**中声明了相同参数的参数,是路径参数 +- 类型是(`int`、`float`、`str`、`bool` 等)**单类型**的参数,是**查询**参数 +- 类型是 **Pydantic 模型**的参数,是**请求体** -=== "Python 3.8+" +/// note | 笔记 - ```Python hl_lines="18" - {!> ../../../docs_src/body/tutorial004.py!} - ``` +因为默认值是 `None`, FastAPI 会把 `q` 当作可选参数。 -函数参数将依次按如下规则进行识别: +FastAPI 不使用 `Optional[str]` 中的 `Optional`, 但 `Optional` 可以让编辑器提供更好的支持,并检测错误。 -* 如果在**路径**中也声明了该参数,它将被用作路径参数。 -* 如果参数属于**单一类型**(比如 `int`、`float`、`str`、`bool` 等)它将被解释为**查询**参数。 -* 如果参数的类型被声明为一个 **Pydantic 模型**,它将被解释为**请求体**。 +/// ## 不使用 Pydantic -如果你不想使用 Pydantic 模型,你还可以使用 **Body** 参数。请参阅文档 [请求体 - 多个参数:请求体中的单一值](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}。 +即便不使用 Pydantic 模型也能使用 **Body** 参数。详见[请求体 - 多参数:请求体中的单值](body-multiple-params.md#_2){.internal-link target=\_blank}。 diff --git a/docs/zh/docs/tutorial/cookie-param-models.md b/docs/zh/docs/tutorial/cookie-param-models.md new file mode 100644 index 000000000..6a7b09e25 --- /dev/null +++ b/docs/zh/docs/tutorial/cookie-param-models.md @@ -0,0 +1,76 @@ +# Cookie 参数模型 + +如果您有一组相关的 **cookie**,您可以创建一个 **Pydantic 模型**来声明它们。🍪 + +这将允许您在**多个地方**能够**重用模型**,并且可以一次性声明所有参数的验证方式和元数据。😎 + +/// note + +自 FastAPI 版本 `0.115.0` 起支持此功能。🤓 + +/// + +/// tip + +此技术同样适用于 `Query` 、 `Cookie` 和 `Header` 。😎 + +/// + +## 带有 Pydantic 模型的 Cookie + +在 **Pydantic** 模型中声明所需的 **cookie** 参数,然后将参数声明为 `Cookie` : + +{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *} + +**FastAPI** 将从请求中接收到的 **cookie** 中**提取**出**每个字段**的数据,并提供您定义的 Pydantic 模型。 + +## 查看文档 + +您可以在文档 UI 的 `/docs` 中查看定义的 cookie: + +
+ +
+ +/// info + +请记住,由于**浏览器**以特殊方式**处理 cookie**,并在后台进行操作,因此它们**不会**轻易允许 **JavaScript** 访问这些 cookie。 + +如果您访问 `/docs` 的 **API 文档 UI**,您将能够查看您*路径操作*的 cookie **文档**。 + +但是即使您**填写数据**并点击“执行”,由于文档界面使用 **JavaScript**,cookie 将不会被发送。而您会看到一条**错误**消息,就好像您没有输入任何值一样。 + +/// + +## 禁止额外的 Cookie + +在某些特殊使用情况下(可能并不常见),您可能希望**限制**您想要接收的 cookie。 + +您的 API 现在可以控制自己的 cookie 同意。🤪🍪 + +您可以使用 Pydantic 的模型配置来禁止( `forbid` )任何额外( `extra` )字段: + +{* ../../docs_src/cookie_param_models/tutorial002_an_py39.py hl[10] *} + +如果客户尝试发送一些**额外的 cookie**,他们将收到**错误**响应。 + +可怜的 cookie 通知条,费尽心思为了获得您的同意,却被API 拒绝了。🍪 + +例如,如果客户端尝试发送一个值为 `good-list-please` 的 `santa_tracker` cookie,客户端将收到一个**错误**响应,告知他们 `santa_tracker` cookie 是不允许的: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["cookie", "santa_tracker"], + "msg": "Extra inputs are not permitted", + "input": "good-list-please", + } + ] +} +``` + +## 总结 + +您可以使用 **Pydantic 模型**在 **FastAPI** 中声明 **cookie**。😎 diff --git a/docs/zh/docs/tutorial/cookie-params.md b/docs/zh/docs/tutorial/cookie-params.md index f115f9677..495600814 100644 --- a/docs/zh/docs/tutorial/cookie-params.md +++ b/docs/zh/docs/tutorial/cookie-params.md @@ -1,98 +1,36 @@ # Cookie 参数 -你可以像定义 `Query` 参数和 `Path` 参数一样来定义 `Cookie` 参数。 + 定义 `Cookie` 参数与定义 `Query` 和 `Path` 参数一样。 ## 导入 `Cookie` -首先,导入 `Cookie`: +首先,导入 `Cookie`: -=== "Python 3.10+" - - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! tip - 尽可能选择使用 `Annotated` 的版本。 - - ```Python hl_lines="1" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - 尽可能选择使用 `Annotated` 的版本。 - - ```Python hl_lines="3" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[3] *} ## 声明 `Cookie` 参数 -声明 `Cookie` 参数的结构与声明 `Query` 参数和 `Path` 参数时相同。 - -第一个值是参数的默认值,同时也可以传递所有验证参数或注释参数,来校验参数: - - -=== "Python 3.10+" - - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001_an_py39.py!} - ``` - -=== "Python 3.8+" +声明 `Cookie` 参数的方式与声明 `Query` 和 `Path` 参数相同。 - ```Python hl_lines="10" - {!> ../../../docs_src/cookie_params/tutorial001_an.py!} - ``` +第一个值是默认值,还可以传递所有验证参数或注释参数: -=== "Python 3.10+ non-Annotated" - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +{* ../../docs_src/cookie_params/tutorial001_an_py310.py hl[9] *} - ```Python hl_lines="7" - {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} - ``` +/// note | 技术细节 -=== "Python 3.8+ non-Annotated" +`Cookie` 、`Path` 、`Query` 是**兄弟类**,都继承自共用的 `Param` 类。 - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +注意,从 `fastapi` 导入的 `Query`、`Path`、`Cookie` 等对象,实际上是返回特殊类的函数。 - ```Python hl_lines="9" - {!> ../../../docs_src/cookie_params/tutorial001.py!} - ``` +/// -!!! note "技术细节" - `Cookie` 、`Path` 、`Query`是兄弟类,它们都继承自公共的 `Param` 类 +/// info | 说明 - 但请记住,当你从 `fastapi` 导入的 `Query`、`Path`、`Cookie` 或其他参数声明函数,这些实际上是返回特殊类的函数。 +必须使用 `Cookie` 声明 cookie 参数,否则该参数会被解释为查询参数。 -!!! info - 你需要使用 `Cookie` 来声明 cookie 参数,否则参数将会被解释为查询参数。 +/// -## 总结 +## 小结 -使用 `Cookie` 声明 cookie 参数,使用方式与 `Query` 和 `Path` 类似。 +使用 `Cookie` 声明 cookie 参数的方式与 `Query` 和 `Path` 相同。 diff --git a/docs/zh/docs/tutorial/cors.md b/docs/zh/docs/tutorial/cors.md index ddd4e7682..a4f15f647 100644 --- a/docs/zh/docs/tutorial/cors.md +++ b/docs/zh/docs/tutorial/cors.md @@ -46,9 +46,7 @@ * 特定的 HTTP 方法(`POST`,`PUT`)或者使用通配符 `"*"` 允许所有方法。 * 特定的 HTTP headers 或者使用通配符 `"*"` 允许所有 headers。 -```Python hl_lines="2 6-11 13-19" -{!../../../docs_src/cors/tutorial001.py!} -``` +{* ../../docs_src/cors/tutorial001.py hl[2,6:11,13:19] *} 默认情况下,这个 `CORSMiddleware` 实现所使用的默认参数较为保守,所以你需要显式地启用特定的源、方法或者 headers,以便浏览器能够在跨域上下文中使用它们。 @@ -78,7 +76,10 @@ 更多关于 CORS 的信息,请查看 Mozilla CORS 文档。 -!!! note "技术细节" - 你也可以使用 `from starlette.middleware.cors import CORSMiddleware`。 +/// note | 技术细节 - 出于方便,**FastAPI** 在 `fastapi.middleware` 中为开发者提供了几个中间件。但是大多数可用的中间件都是直接来自 Starlette。 +你也可以使用 `from starlette.middleware.cors import CORSMiddleware`。 + +出于方便,**FastAPI** 在 `fastapi.middleware` 中为开发者提供了几个中间件。但是大多数可用的中间件都是直接来自 Starlette。 + +/// diff --git a/docs/zh/docs/tutorial/debugging.md b/docs/zh/docs/tutorial/debugging.md index 51801d498..734b85565 100644 --- a/docs/zh/docs/tutorial/debugging.md +++ b/docs/zh/docs/tutorial/debugging.md @@ -6,9 +6,7 @@ 在你的 FastAPI 应用中直接导入 `uvicorn` 并运行: -```Python hl_lines="1 15" -{!../../../docs_src/debugging/tutorial001.py!} -``` +{* ../../docs_src/debugging/tutorial001.py hl[1,15] *} ### 关于 `__name__ == "__main__"` @@ -70,8 +68,11 @@ from myapp import app uvicorn.run(app, host="0.0.0.0", port=8000) ``` -!!! info - 更多信息请检查 Python 官方文档. +/// info + +更多信息请检查 Python 官方文档. + +/// ## 使用你的调试器运行代码 diff --git a/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md index 1866da298..f07280790 100644 --- a/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/zh/docs/tutorial/dependencies/classes-as-dependencies.md @@ -6,17 +6,7 @@ 在前面的例子中, 我们从依赖项 ("可依赖对象") 中返回了一个 `dict`: -=== "Python 3.10+" - - ```Python hl_lines="7" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +{* ../../docs_src/dependencies/tutorial001_py310.py hl[7] *} 但是后面我们在路径操作函数的参数 `commons` 中得到了一个 `dict`。 @@ -79,45 +69,15 @@ fluffy = Cat(name="Mr Fluffy") 所以,我们可以将上面的依赖项 "可依赖对象" `common_parameters` 更改为类 `CommonQueryParams`: -=== "Python 3.10+" - - ```Python hl_lines="9-13" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="11-15" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +{* ../../docs_src/dependencies/tutorial002_py310.py hl[9:13] *} 注意用于创建类实例的 `__init__` 方法: -=== "Python 3.10+" - - ```Python hl_lines="10" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` - -=== "Python 3.6+" - - ```Python hl_lines="12" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +{* ../../docs_src/dependencies/tutorial002_py310.py hl[10] *} ...它与我们以前的 `common_parameters` 具有相同的参数: -=== "Python 3.10+" - - ```Python hl_lines="6" - {!> ../../../docs_src/dependencies/tutorial001_py310.py!} - ``` - -=== "Python 3.6+" - - ```Python hl_lines="9" - {!> ../../../docs_src/dependencies/tutorial001.py!} - ``` +{* ../../docs_src/dependencies/tutorial001_py310.py hl[6] *} 这些参数就是 **FastAPI** 用来 "处理" 依赖项的。 @@ -133,17 +93,7 @@ fluffy = Cat(name="Mr Fluffy") 现在,您可以使用这个类来声明你的依赖项了。 -=== "Python 3.10+" - - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial002_py310.py!} - ``` - -=== "Python 3.6+" - - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial002.py!} - ``` +{* ../../docs_src/dependencies/tutorial002_py310.py hl[17] *} **FastAPI** 调用 `CommonQueryParams` 类。这将创建该类的一个 "实例",该实例将作为参数 `commons` 被传递给你的函数。 @@ -183,17 +133,7 @@ commons = Depends(CommonQueryParams) ..就像: -=== "Python 3.10+" - - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial003_py310.py!} - ``` - -=== "Python 3.6+" - - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial003.py!} - ``` +{* ../../docs_src/dependencies/tutorial003_py310.py hl[17] *} 但是声明类型是被鼓励的,因为那样你的编辑器就会知道将传递什么作为参数 `commons` ,然后它可以帮助你完成代码,类型检查,等等: @@ -227,21 +167,14 @@ commons: CommonQueryParams = Depends() 同样的例子看起来像这样: -=== "Python 3.10+" - - ```Python hl_lines="17" - {!> ../../../docs_src/dependencies/tutorial004_py310.py!} - ``` +{* ../../docs_src/dependencies/tutorial004_py310.py hl[17] *} -=== "Python 3.6+" +... **FastAPI** 会知道怎么处理。 - ```Python hl_lines="19" - {!> ../../../docs_src/dependencies/tutorial004.py!} - ``` +/// tip -... **FastAPI** 会知道怎么处理。 +如果这看起来更加混乱而不是更加有帮助,那么请忽略它,你不*需要*它。 -!!! tip - 如果这看起来更加混乱而不是更加有帮助,那么请忽略它,你不*需要*它。 +这只是一个快捷方式。因为 **FastAPI** 关心的是帮助您减少代码重复。 - 这只是一个快捷方式。因为 **FastAPI** 关心的是帮助您减少代码重复。 +/// diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index 61ea371e5..51b3e9fc3 100644 --- a/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/zh/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -14,25 +14,27 @@ 该参数的值是由 `Depends()` 组成的 `list`: -```Python hl_lines="17" -{!../../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[17] *} 路径操作装饰器依赖项(以下简称为**“路径装饰器依赖项”**)的执行或解析方式和普通依赖项一样,但就算这些依赖项会返回值,它们的值也不会传递给*路径操作函数*。 -!!! tip "提示" +/// tip | 提示 - 有些编辑器会检查代码中没使用过的函数参数,并显示错误提示。 +有些编辑器会检查代码中没使用过的函数参数,并显示错误提示。 - 在*路径操作装饰器*中使用 `dependencies` 参数,可以确保在执行依赖项的同时,避免编辑器显示错误提示。 +在*路径操作装饰器*中使用 `dependencies` 参数,可以确保在执行依赖项的同时,避免编辑器显示错误提示。 - 使用路径装饰器依赖项还可以避免开发新人误会代码中包含无用的未使用参数。 +使用路径装饰器依赖项还可以避免开发新人误会代码中包含无用的未使用参数。 -!!! info "说明" +/// - 本例中,使用的是自定义响应头 `X-Key` 和 `X-Token`。 +/// info | 说明 - 但实际开发中,尤其是在实现安全措施时,最好使用 FastAPI 内置的[安全工具](../security/index.md){.internal-link target=_blank}(详见下一章)。 +本例中,使用的是自定义响应头 `X-Key` 和 `X-Token`。 + +但实际开发中,尤其是在实现安全措施时,最好使用 FastAPI 内置的[安全工具](../security/index.md){.internal-link target=_blank}(详见下一章)。 + +/// ## 依赖项错误和返回值 @@ -42,17 +44,13 @@ 路径装饰器依赖项可以声明请求的需求项(比如响应头)或其他子依赖项: -```Python hl_lines="6 11" -{!../../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[6,11] *} ### 触发异常 路径装饰器依赖项与正常的依赖项一样,可以 `raise` 异常: -```Python hl_lines="8 13" -{!../../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[8,13] *} ### 返回值 @@ -60,9 +58,7 @@ 因此,可以复用在其他位置使用过的、(能返回值的)普通依赖项,即使没有使用这个值,也会执行该依赖项: -```Python hl_lines="9 14" -{!../../../docs_src/dependencies/tutorial006.py!} -``` +{* ../../docs_src/dependencies/tutorial006.py hl[9,14] *} ## 为一组路径操作定义依赖项 diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md new file mode 100644 index 000000000..a863bb861 --- /dev/null +++ b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md @@ -0,0 +1,267 @@ +# 使用yield的依赖项 + +FastAPI支持在完成后执行一些额外步骤的依赖项. + +为此,你需要使用 `yield` 而不是 `return`,然后再编写这些额外的步骤(代码)。 + +/// tip | 提示 + +确保在每个依赖中只使用一次 `yield`。 + +/// + +/// note | 技术细节 + +任何一个可以与以下内容一起使用的函数: + +* `@contextlib.contextmanager` 或者 +* `@contextlib.asynccontextmanager` + +都可以作为 **FastAPI** 的依赖项。 + +实际上,FastAPI内部就使用了这两个装饰器。 + +/// + +## 使用 `yield` 的数据库依赖项 + +例如,你可以使用这种方式创建一个数据库会话,并在完成后关闭它。 + +在发送响应之前,只会执行 `yield` 语句及之前的代码: + +{* ../../docs_src/dependencies/tutorial007.py hl[2:4] *} + +生成的值会注入到 *路由函数* 和其他依赖项中: + +{* ../../docs_src/dependencies/tutorial007.py hl[4] *} + +`yield` 语句后面的代码会在创建响应后,发送响应前执行: + +{* ../../docs_src/dependencies/tutorial007.py hl[5:6] *} + +/// tip | 提示 + +你可以使用 `async` 或普通函数。 + +**FastAPI** 会像处理普通依赖一样,对每个依赖做正确的处理。 + +/// + +## 包含 `yield` 和 `try` 的依赖项 + +如果在包含 `yield` 的依赖中使用 `try` 代码块,你会捕获到使用依赖时抛出的任何异常。 + +例如,如果某段代码在另一个依赖中或在 *路由函数* 中使数据库事务"回滚"或产生任何其他错误,你将会在依赖中捕获到异常。 + +因此,你可以使用 `except SomeException` 在依赖中捕获特定的异常。 + +同样,你也可以使用 `finally` 来确保退出步骤得到执行,无论是否存在异常。 + +{* ../../docs_src/dependencies/tutorial007.py hl[3,5] *} +## 使用 `yield` 的子依赖项 + +你可以声明任意数量和层级的树状依赖,而且它们中的任何一个或所有的都可以使用 `yield`。 + +**FastAPI** 会确保每个带有 `yield` 的依赖中的"退出代码"按正确顺序运行。 + +例如,`dependency_c` 可以依赖于 `dependency_b`,而 `dependency_b` 则依赖于 `dependency_a`。 + +{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[6,14,22] *} + +所有这些依赖都可以使用 `yield`。 + +在这种情况下,`dependency_c` 在执行其退出代码时需要 `dependency_b`(此处称为 `dep_b`)的值仍然可用。 + +而 `dependency_b` 反过来则需要 `dependency_a`(此处称为 `dep_a` )的值在其退出代码中可用。 + +{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[18:19,26:27] *} + +同样,你可以混合使用带有 `yield` 或 `return` 的依赖。 + +你也可以声明一个依赖于多个带有 `yield` 的依赖,等等。 + +你可以拥有任何你想要的依赖组合。 + +**FastAPI** 将确保按正确的顺序运行所有内容。 + +/// note | 技术细节 + +这是由 Python 的上下文管理器完成的。 + +**FastAPI** 在内部使用它们来实现这一点。 + +/// + +## 包含 `yield` 和 `HTTPException` 的依赖项 + +你可以使用带有 `yield` 的依赖项,并且可以包含 `try` 代码块用于捕获异常。 + +同样,你可以在 `yield` 之后的退出代码中抛出一个 `HTTPException` 或类似的异常。 + +/// tip | 提示 + +这是一种相对高级的技巧,在大多数情况下你并不需要使用它,因为你可以在其他代码中抛出异常(包括 `HTTPException` ),例如在 *路由函数* 中。 + +但是如果你需要,你也可以在依赖项中做到这一点。🤓 + +/// + +{* ../../docs_src/dependencies/tutorial008b_an_py39.py hl[18:22,31] *} + +你还可以创建一个 [自定义异常处理器](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} 用于捕获异常(同时也可以抛出另一个 `HTTPException`)。 + +## 包含 `yield` 和 `except` 的依赖项 + +如果你在包含 `yield` 的依赖项中使用 `except` 捕获了一个异常,然后你没有重新抛出该异常(或抛出一个新异常),与在普通的Python代码中相同,FastAPI不会注意到发生了异常。 + +{* ../../docs_src/dependencies/tutorial008c_an_py39.py hl[15:16] *} + +在示例代码的情况下,客户端将会收到 *HTTP 500 Internal Server Error* 的响应,因为我们没有抛出 `HTTPException` 或者类似的异常,并且服务器也 **不会有任何日志** 或者其他提示来告诉我们错误是什么。😱 + +### 在包含 `yield` 和 `except` 的依赖项中一定要 `raise` + +如果你在使用 `yield` 的依赖项中捕获到了一个异常,你应该再次抛出捕获到的异常,除非你抛出 `HTTPException` 或类似的其他异常, + +你可以使用 `raise` 再次抛出捕获到的异常。 + +{* ../../docs_src/dependencies/tutorial008d_an_py39.py hl[17] *} + +现在客户端同样会得到 *HTTP 500 Internal Server Error* 响应,但是服务器日志会记录下我们自定义的 `InternalError`。 + +## 使用 `yield` 的依赖项的执行 + +执行顺序大致如下时序图所示。时间轴从上到下,每一列都代表交互或者代码执行的一部分。 + +```mermaid +sequenceDiagram + +participant client as Client +participant handler as Exception handler +participant dep as Dep with yield +participant operation as Path Operation +participant tasks as Background tasks + + Note over client,operation: Can raise exceptions, including HTTPException + client ->> dep: Start request + Note over dep: Run code up to yield + opt raise Exception + dep -->> handler: Raise Exception + handler -->> client: HTTP error response + end + dep ->> operation: Run dependency, e.g. DB session + opt raise + operation -->> dep: Raise Exception (e.g. HTTPException) + opt handle + dep -->> dep: Can catch exception, raise a new HTTPException, raise other exception + end + handler -->> client: HTTP error response + end + + operation ->> client: Return response to client + Note over client,operation: Response is already sent, can't change it anymore + opt Tasks + operation -->> tasks: Send background tasks + end + opt Raise other exception + tasks -->> tasks: Handle exceptions in the background task code + end +``` + +/// info | 说明 + +只会向客户端发送 **一次响应** ,可能是一个错误响应,也可能是来自 *路由函数* 的响应。 + +在发送了其中一个响应之后,就无法再发送其他响应了。 + +/// + +/// tip | 提示 + +这个时序图展示了 `HTTPException`,除此之外你也可以抛出任何你在使用 `yield` 的依赖项中或者[自定义异常处理器](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}中捕获的异常。 + +如果你引发任何异常,它将传递给使用 `yield` 的依赖项,包括 `HTTPException`。在大多数情况下你应当从使用 `yield` 的依赖项中重新抛出捕获的异常或者一个新的异常来确保它会被正确的处理。 + +/// + +## 包含 `yield`, `HTTPException`, `except` 的依赖项和后台任务 + +/// warning | 注意 + +你大概率不需要了解这些技术细节,可以跳过这一章节继续阅读后续的内容。 + +如果你使用的FastAPI的版本早于0.106.0,并且在使用后台任务中使用了包含 `yield` 的依赖项中的资源,那么这些细节会对你有一些用处。 + +/// + +### 包含 `yield` 和 `except` 的依赖项的技术细节 + +在FastAPI 0.110.0版本之前,如果使用了一个包含 `yield` 的依赖项,你在依赖项中使用 `except` 捕获了一个异常,但是你没有再次抛出该异常,这个异常会被自动抛出/转发到异常处理器或者内部服务错误处理器。 + +### 后台任务和使用 `yield` 的依赖项的技术细节 + +在FastAPI 0.106.0版本之前,在 `yield` 后面抛出异常是不可行的,因为 `yield` 之后的退出代码是在响应被发送之后再执行,这个时候异常处理器已经执行过了。 + +这样设计的目的主要是为了允许在后台任务中使用被依赖项`yield`的对象,因为退出代码会在后台任务结束后再执行。 + +然而这也意味着在等待响应通过网络传输的同时,非必要的持有一个 `yield` 依赖项中的资源(例如数据库连接),这一行为在FastAPI 0.106.0被改变了。 + +/// tip | 提示 + +除此之外,后台任务通常是一组独立的逻辑,应该被单独处理,并且使用它自己的资源(例如它自己的数据库连接)。 + +这样也会让你的代码更加简洁。 + +/// + +如果你之前依赖于这一行为,那么现在你应该在后台任务中创建并使用它自己的资源,不要在内部使用属于 `yield` 依赖项的资源。 + +例如,你应该在后台任务中创建一个新的数据库会话用于查询数据,而不是使用相同的会话。你应该将对象的ID作为参数传递给后台任务函数,然后在该函数中重新获取该对象,而不是直接将数据库对象作为参数。 + +## 上下文管理器 + +### 什么是"上下文管理器" + +"上下文管理器"是你可以在 `with` 语句中使用的任何Python对象。 + +例如,你可以使用`with`读取文件: + +```Python +with open("./somefile.txt") as f: + contents = f.read() + print(contents) +``` + +在底层,`open("./somefile.txt")`创建了一个被称为"上下文管理器"的对象。 + +当 `with` 代码块结束时,它会确保关闭文件,即使发生了异常也是如此。 + +当你使用 `yield` 创建一个依赖项时,**FastAPI** 会在内部将其转换为上下文管理器,并与其他相关工具结合使用。 + +### 在使用 `yield` 的依赖项中使用上下文管理器 + +/// warning | 注意 + +这是一个更为"高级"的想法。 + +如果你刚开始使用 **FastAPI** ,你可以暂时可以跳过它。 + +/// + +在Python中,你可以通过创建一个带有`__enter__()`和`__exit__()`方法的类来创建上下文管理器。 + +你也可以在 **FastAPI** 的 `yield` 依赖项中通过 `with` 或者 `async with` 语句来使用它们: + +{* ../../docs_src/dependencies/tutorial010.py hl[1:9,13] *} + +/// tip | 提示 + +另一种创建上下文管理器的方法是: + +* `@contextlib.contextmanager`或者 +* `@contextlib.asynccontextmanager` + +使用它们装饰一个只有单个 `yield` 的函数。这就是 **FastAPI** 内部对于 `yield` 依赖项的处理方式。 + +但是你不需要为FastAPI的依赖项使用这些装饰器(而且也不应该)。FastAPI会在内部为你处理这些。 + +/// diff --git a/docs/zh/docs/tutorial/dependencies/global-dependencies.md b/docs/zh/docs/tutorial/dependencies/global-dependencies.md index 3f7afa32c..797fd76b7 100644 --- a/docs/zh/docs/tutorial/dependencies/global-dependencies.md +++ b/docs/zh/docs/tutorial/dependencies/global-dependencies.md @@ -6,9 +6,7 @@ 这样一来,就可以为所有*路径操作*应用该依赖项: -```Python hl_lines="15" -{!../../../docs_src/dependencies/tutorial012.py!} -``` +{* ../../docs_src/dependencies/tutorial012.py hl[15] *} [*路径装饰器依赖项*](dependencies-in-path-operation-decorators.md){.internal-link target=_blank} 一章的思路均适用于全局依赖项, 在本例中,这些依赖项可以用于应用中的所有*路径操作*。 diff --git a/docs/zh/docs/tutorial/dependencies/index.md b/docs/zh/docs/tutorial/dependencies/index.md index 7a133061d..9eec69ed5 100644 --- a/docs/zh/docs/tutorial/dependencies/index.md +++ b/docs/zh/docs/tutorial/dependencies/index.md @@ -31,9 +31,7 @@ FastAPI 提供了简单易用,但功能强大的** read_users 这样,只编写一次代码,**FastAPI** 就可以为多个*路径操作*共享这段代码 。 -!!! check "检查" +/// check | 检查 + +注意,无需创建专门的类,并将之传递给 **FastAPI** 以进行「注册」或执行类似的操作。 - 注意,无需创建专门的类,并将之传递给 **FastAPI** 以进行「注册」或执行类似的操作。 +只要把它传递给 `Depends`,**FastAPI** 就知道该如何执行后续操作。 - 只要把它传递给 `Depends`,**FastAPI** 就知道该如何执行后续操作。 +/// ## 要不要使用 `async`? @@ -114,9 +112,11 @@ common_parameters --> read_users 上述这些操作都是可行的,**FastAPI** 知道该怎么处理。 -!!! note "笔记" +/// note | 笔记 + +如里不了解异步,请参阅[异步:*“着急了?”*](../../async.md){.internal-link target=_blank} 一章中 `async` 和 `await` 的内容。 - 如里不了解异步,请参阅[异步:*“着急了?”*](../../async.md){.internal-link target=_blank} 一章中 `async` 和 `await` 的内容。 +/// ## 与 OpenAPI 集成 diff --git a/docs/zh/docs/tutorial/dependencies/sub-dependencies.md b/docs/zh/docs/tutorial/dependencies/sub-dependencies.md index 58377bbfe..2e7746433 100644 --- a/docs/zh/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/zh/docs/tutorial/dependencies/sub-dependencies.md @@ -10,9 +10,7 @@ FastAPI 支持创建含**子依赖项**的依赖项。 下列代码创建了第一层依赖项: -```Python hl_lines="8-9" -{!../../../docs_src/dependencies/tutorial005.py!} -``` +{* ../../docs_src/dependencies/tutorial005.py hl[8:9] *} 这段代码声明了类型为 `str` 的可选查询参数 `q`,然后返回这个查询参数。 @@ -22,9 +20,7 @@ FastAPI 支持创建含**子依赖项**的依赖项。 接下来,创建另一个依赖项函数,并同时用该依赖项自身再声明一个依赖项(所以这也是一个「依赖项」): -```Python hl_lines="13" -{!../../../docs_src/dependencies/tutorial005.py!} -``` +{* ../../docs_src/dependencies/tutorial005.py hl[13] *} 这里重点说明一下声明的参数: @@ -37,15 +33,15 @@ FastAPI 支持创建含**子依赖项**的依赖项。 接下来,就可以使用依赖项: -```Python hl_lines="22" -{!../../../docs_src/dependencies/tutorial005.py!} -``` +{* ../../docs_src/dependencies/tutorial005.py hl[22] *} -!!! info "信息" +/// info | 信息 - 注意,这里在*路径操作函数*中只声明了一个依赖项,即 `query_or_cookie_extractor` 。 +注意,这里在*路径操作函数*中只声明了一个依赖项,即 `query_or_cookie_extractor` 。 - 但 **FastAPI** 必须先处理 `query_extractor`,以便在调用 `query_or_cookie_extractor` 时使用 `query_extractor` 返回的结果。 +但 **FastAPI** 必须先处理 `query_extractor`,以便在调用 `query_or_cookie_extractor` 时使用 `query_extractor` 返回的结果。 + +/// ```mermaid graph TB @@ -79,10 +75,12 @@ async def needy_dependency(fresh_value: str = Depends(get_value, use_cache=False 但它依然非常强大,能够声明任意嵌套深度的「图」或树状的依赖结构。 -!!! tip "提示" +/// tip | 提示 + +这些简单的例子现在看上去虽然没有什么实用价值, - 这些简单的例子现在看上去虽然没有什么实用价值, +但在**安全**一章中,您会了解到这些例子的用途, - 但在**安全**一章中,您会了解到这些例子的用途, +以及这些例子所能节省的代码量。 - 以及这些例子所能节省的代码量。 +/// diff --git a/docs/zh/docs/tutorial/encoder.md b/docs/zh/docs/tutorial/encoder.md index 859ebc2e8..e52aaa2ed 100644 --- a/docs/zh/docs/tutorial/encoder.md +++ b/docs/zh/docs/tutorial/encoder.md @@ -20,17 +20,7 @@ 它接收一个对象,比如Pydantic模型,并会返回一个JSON兼容的版本: -=== "Python 3.10+" - - ```Python hl_lines="4 21" - {!> ../../../docs_src/encoder/tutorial001_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="5 22" - {!> ../../../docs_src/encoder/tutorial001.py!} - ``` +{* ../../docs_src/encoder/tutorial001_py310.py hl[4,21] *} 在这个例子中,它将Pydantic模型转换为`dict`,并将`datetime`转换为`str`。 @@ -38,5 +28,8 @@ 这个操作不会返回一个包含JSON格式(作为字符串)数据的庞大的`str`。它将返回一个Python标准数据结构(例如`dict`),其值和子值都与JSON兼容。 -!!! note - `jsonable_encoder`实际上是FastAPI内部用来转换数据的。但是它在许多其他场景中也很有用。 +/// note + +`jsonable_encoder`实际上是FastAPI内部用来转换数据的。但是它在许多其他场景中也很有用。 + +/// diff --git a/docs/zh/docs/tutorial/extra-data-types.md b/docs/zh/docs/tutorial/extra-data-types.md index f4a77050c..b064ee551 100644 --- a/docs/zh/docs/tutorial/extra-data-types.md +++ b/docs/zh/docs/tutorial/extra-data-types.md @@ -36,7 +36,7 @@ * `datetime.timedelta`: * 一个 Python `datetime.timedelta`. * 在请求和响应中将表示为 `float` 代表总秒数。 - * Pydantic 也允许将其表示为 "ISO 8601 时间差异编码", 查看文档了解更多信息。 + * Pydantic 也允许将其表示为 "ISO 8601 时间差异编码", 查看文档了解更多信息。 * `frozenset`: * 在请求和响应中,作为 `set` 对待: * 在请求中,列表将被读取,消除重复,并将其转换为一个 `set`。 @@ -49,82 +49,14 @@ * `Decimal`: * 标准的 Python `Decimal`。 * 在请求和响应中被当做 `float` 一样处理。 -* 您可以在这里检查所有有效的pydantic数据类型: Pydantic data types. +* 您可以在这里检查所有有效的pydantic数据类型: Pydantic data types. ## 例子 下面是一个*路径操作*的示例,其中的参数使用了上面的一些类型。 -=== "Python 3.10+" - - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="1 3 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="1 3 13-17" - {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! tip - 尽可能选择使用 `Annotated` 的版本。 - - ```Python hl_lines="1 2 11-15" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - 尽可能选择使用 `Annotated` 的版本。 - - ```Python hl_lines="1 2 12-16" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[1,3,12:16] *} 注意,函数内的参数有原生的数据类型,你可以,例如,执行正常的日期操作,如: -=== "Python 3.10+" - - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="19-20" - {!> ../../../docs_src/extra_data_types/tutorial001_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! tip - 尽可能选择使用 `Annotated` 的版本。 - - ```Python hl_lines="17-18" - {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - 尽可能选择使用 `Annotated` 的版本。 - - ```Python hl_lines="18-19" - {!> ../../../docs_src/extra_data_types/tutorial001.py!} - ``` +{* ../../docs_src/extra_data_types/tutorial001_an_py310.py hl[18:19] *} diff --git a/docs/zh/docs/tutorial/extra-models.md b/docs/zh/docs/tutorial/extra-models.md index 06427a73d..ccfb3aa5a 100644 --- a/docs/zh/docs/tutorial/extra-models.md +++ b/docs/zh/docs/tutorial/extra-models.md @@ -1,63 +1,56 @@ -# 额外的模型 +# 更多模型 -我们从前面的示例继续,拥有多个相关的模型是很常见的。 +书接上文,多个关联模型这种情况很常见。 -对用户模型来说尤其如此,因为: +特别是用户模型,因为: -* **输入模型**需要拥有密码属性。 -* **输出模型**不应该包含密码。 -* **数据库模型**很可能需要保存密码的哈希值。 +* **输入模型**应该含密码 +* **输出模型**不应含密码 +* **数据库模型**需要加密的密码 -!!! danger - 永远不要存储用户的明文密码。始终存储一个可以用于验证的「安全哈希值」。 +/// danger | 危险 - 如果你尚未了解该知识,你可以在[安全章节](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}中学习何为「密码哈希值」。 +千万不要存储用户的明文密码。始终存储可以进行验证的**安全哈希值**。 -## 多个模型 - -下面是应该如何根据它们的密码字段以及使用位置去定义模型的大概思路: +如果不了解这方面的知识,请参阅[安全性中的章节](security/simple-oauth2.md#password-hashing){.internal-link target=_blank},了解什么是**密码哈希**。 -=== "Python 3.10+" +/// - ```Python hl_lines="7 9 14 20 22 27-28 31-33 38-39" - {!> ../../../docs_src/extra_models/tutorial001_py310.py!} - ``` +## 多个模型 -=== "Python 3.8+" +下面的代码展示了不同模型处理密码字段的方式,及使用位置的大致思路: - ```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" - {!> ../../../docs_src/extra_models/tutorial001.py!} - ``` +{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *} -### 关于 `**user_in.dict()` +### `**user_in.dict()` 简介 #### Pydantic 的 `.dict()` -`user_in` 是一个 `UserIn` 类的 Pydantic 模型. +`user_in` 是类 `UserIn` 的 Pydantic 模型。 -Pydantic 模型具有 `.dict()` 方法,该方法返回一个拥有模型数据的 `dict`。 +Pydantic 模型支持 `.dict()` 方法,能返回包含模型数据的**字典**。 -因此,如果我们像下面这样创建一个 Pydantic 对象 `user_in`: +因此,如果使用如下方式创建 Pydantic 对象 `user_in`: ```Python user_in = UserIn(username="john", password="secret", email="john.doe@example.com") ``` -然后我们调用: +就能以如下方式调用: ```Python user_dict = user_in.dict() ``` -现在我们有了一个数据位于变量 `user_dict` 中的 `dict`(它是一个 `dict` 而不是 Pydantic 模型对象)。 +现在,变量 `user_dict`中的就是包含数据的**字典**(变量 `user_dict` 是字典,不是 Pydantic 模型对象)。 -如果我们调用: +以如下方式调用: ```Python print(user_dict) ``` -我们将获得一个这样的 Python `dict`: +输出的就是 Python **字典**: ```Python { @@ -70,15 +63,15 @@ print(user_dict) #### 解包 `dict` -如果我们将 `user_dict` 这样的 `dict` 以 `**user_dict` 形式传递给一个函数(或类),Python将对其进行「解包」。它会将 `user_dict` 的键和值作为关键字参数直接传递。 +把**字典** `user_dict` 以 `**user_dict` 形式传递给函数(或类),Python 会执行**解包**操作。它会把 `user_dict` 的键和值作为关键字参数直接传递。 -因此,从上面的 `user_dict` 继续,编写: +因此,接着上面的 `user_dict` 继续编写如下代码: ```Python UserInDB(**user_dict) ``` -会产生类似于以下的结果: +就会生成如下结果: ```Python UserInDB( @@ -89,7 +82,7 @@ UserInDB( ) ``` -或者更确切地,直接使用 `user_dict` 来表示将来可能包含的任何内容: +或更精准,直接把可能会用到的内容与 `user_dict` 一起使用: ```Python UserInDB( @@ -100,34 +93,34 @@ UserInDB( ) ``` -#### 来自于其他模型内容的 Pydantic 模型 +#### 用其它模型中的内容生成 Pydantic 模型 -如上例所示,我们从 `user_in.dict()` 中获得了 `user_dict`,此代码: +上例中 ,从 `user_in.dict()` 中得到了 `user_dict`,下面的代码: ```Python user_dict = user_in.dict() UserInDB(**user_dict) ``` -等同于: +等效于: ```Python UserInDB(**user_in.dict()) ``` -...因为 `user_in.dict()` 是一个 `dict`,然后我们通过以`**`开头传递给 `UserInDB` 来使 Python「解包」它。 +……因为 `user_in.dict()` 是字典,在传递给 `UserInDB` 时,把 `**` 加在 `user_in.dict()` 前,可以让 Python 进行**解包**。 -这样,我们获得了一个来自于其他 Pydantic 模型中的数据的 Pydantic 模型。 +这样,就可以用其它 Pydantic 模型中的数据生成 Pydantic 模型。 -#### 解包 `dict` 和额外关键字 +#### 解包 `dict` 和更多关键字 -然后添加额外的关键字参数 `hashed_password=hashed_password`,例如: +接下来,继续添加关键字参数 `hashed_password=hashed_password`,例如: ```Python UserInDB(**user_in.dict(), hashed_password=hashed_password) ``` -...最终的结果如下: +……输出结果如下: ```Python UserInDB( @@ -139,101 +132,68 @@ UserInDB( ) ``` -!!! warning - 辅助性的额外函数只是为了演示可能的数据流,但它们显然不能提供任何真正的安全性。 +/// warning | 警告 -## 减少重复 +辅助的附加函数只是为了演示可能的数据流,但它们显然不能提供任何真正的安全机制。 -减少代码重复是 **FastAPI** 的核心思想之一。 +/// -因为代码重复会增加出现 bug、安全性问题、代码失步问题(当你在一个位置更新了代码但没有在其他位置更新)等的可能性。 +## 减少重复 -上面的这些模型都共享了大量数据,并拥有重复的属性名称和类型。 +**FastAPI** 的核心思想就是减少代码重复。 -我们可以做得更好。 +代码重复会导致 bug、安全问题、代码失步等问题(更新了某个位置的代码,但没有同步更新其它位置的代码)。 -我们可以声明一个 `UserBase` 模型作为其他模型的基类。然后我们可以创建继承该模型属性(类型声明,校验等)的子类。 +上面的这些模型共享了大量数据,拥有重复的属性名和类型。 -所有的数据转换、校验、文档生成等仍将正常运行。 +FastAPI 可以做得更好。 -这样,我们可以仅声明模型之间的差异部分(具有明文的 `password`、具有 `hashed_password` 以及不包括密码)。 +声明 `UserBase` 模型作为其它模型的基类。然后,用该类衍生出继承其属性(类型声明、验证等)的子类。 -=== "Python 3.10+" +所有数据转换、校验、文档等功能仍将正常运行。 - ```Python hl_lines="7 13-14 17-18 21-22" - {!> ../../../docs_src/extra_models/tutorial002_py310.py!} - ``` +这样,就可以仅声明模型之间的差异部分(具有明文的 `password`、具有 `hashed_password` 以及不包括密码)。 -=== "Python 3.8+" +通过这种方式,可以只声明模型之间的区别(分别包含明文密码、哈希密码,以及无密码的模型)。 - ```Python hl_lines="9 15-16 19-20 23-24" - {!> ../../../docs_src/extra_models/tutorial002.py!} - ``` +{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *} ## `Union` 或者 `anyOf` -你可以将一个响应声明为两种类型的 `Union`,这意味着该响应将是两种类型中的任何一种。 - -这将在 OpenAPI 中使用 `anyOf` 进行定义。 - -为此,请使用标准的 Python 类型提示 `typing.Union`: +响应可以声明为两种类型的 `Union` 类型,即该响应可以是两种类型中的任意类型。 +在 OpenAPI 中可以使用 `anyOf` 定义。 -!!! note - 定义一个 `Union` 类型时,首先包括最详细的类型,然后是不太详细的类型。在下面的示例中,更详细的 `PlaneItem` 位于 `Union[PlaneItem,CarItem]` 中的 `CarItem` 之前。 +为此,请使用 Python 标准类型提示 `typing.Union`: -=== "Python 3.10+" +/// note | 笔记 - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003_py310.py!} - ``` +定义 `Union` 类型时,要把详细的类型写在前面,然后是不太详细的类型。下例中,更详细的 `PlaneItem` 位于 `Union[PlaneItem,CarItem]` 中的 `CarItem` 之前。 -=== "Python 3.8+" +/// - ```Python hl_lines="1 14-15 18-20 33" - {!> ../../../docs_src/extra_models/tutorial003.py!} - ``` +{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *} ## 模型列表 -你可以用同样的方式声明由对象列表构成的响应。 +使用同样的方式也可以声明由对象列表构成的响应。 为此,请使用标准的 Python `typing.List`: -=== "Python 3.9+" - - ```Python hl_lines="18" - {!> ../../../docs_src/extra_models/tutorial004_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="1 20" - {!> ../../../docs_src/extra_models/tutorial004.py!} - ``` +{* ../../docs_src/extra_models/tutorial004_py39.py hl[18] *} ## 任意 `dict` 构成的响应 -你还可以使用一个任意的普通 `dict` 声明响应,仅声明键和值的类型,而不使用 Pydantic 模型。 - -如果你事先不知道有效的字段/属性名称(对于 Pydantic 模型是必需的),这将很有用。 - -在这种情况下,你可以使用 `typing.Dict`: - -=== "Python 3.9+" +任意的 `dict` 都能用于声明响应,只要声明键和值的类型,无需使用 Pydantic 模型。 - ```Python hl_lines="6" - {!> ../../../docs_src/extra_models/tutorial005_py39.py!} - ``` +事先不知道可用的字段 / 属性名时(Pydantic 模型必须知道字段是什么),这种方式特别有用。 -=== "Python 3.8+" +此时,可以使用 `typing.Dict`: - ```Python hl_lines="1 8" - {!> ../../../docs_src/extra_models/tutorial005.py!} - ``` +{* ../../docs_src/extra_models/tutorial005_py39.py hl[6] *} -## 总结 +## 小结 -使用多个 Pydantic 模型,并针对不同场景自由地继承。 +针对不同场景,可以随意使用不同的 Pydantic 模型继承定义的基类。 -如果一个实体必须能够具有不同的「状态」,你无需为每个状态的实体定义单独的数据模型。以用户「实体」为例,其状态有包含 `password`、包含 `password_hash` 以及不含密码。 +实体必须具有不同的**状态**时,不必为不同状态的实体单独定义数据模型。例如,用户**实体**就有包含 `password`、包含 `password_hash` 以及不含密码等多种状态。 diff --git a/docs/zh/docs/tutorial/first-steps.md b/docs/zh/docs/tutorial/first-steps.md index 30fae99cf..c4ff460e0 100644 --- a/docs/zh/docs/tutorial/first-steps.md +++ b/docs/zh/docs/tutorial/first-steps.md @@ -2,9 +2,7 @@ 最简单的 FastAPI 文件可能像下面这样: -```Python -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py *} 将其复制到 `main.py` 文件中。 @@ -24,13 +22,15 @@ $ uvicorn main:app --reload -!!! note - `uvicorn main:app` 命令含义如下: +/// note + +`uvicorn main:app` 命令含义如下: - * `main`:`main.py` 文件(一个 Python「模块」)。 - * `app`:在 `main.py` 文件中通过 `app = FastAPI()` 创建的对象。 - * `--reload`:让服务器在更新代码后重新启动。仅在开发时使用该选项。 +* `main`:`main.py` 文件(一个 Python「模块」)。 +* `app`:在 `main.py` 文件中通过 `app = FastAPI()` 创建的对象。 +* `--reload`:让服务器在更新代码后重新启动。仅在开发时使用该选项。 +/// 在输出中,会有一行信息像下面这样: @@ -132,22 +132,21 @@ OpenAPI 为你的 API 定义 API 模式。该模式中包含了你的 API 发送 ### 步骤 1:导入 `FastAPI` -```Python hl_lines="1" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[1] *} `FastAPI` 是一个为你的 API 提供了所有功能的 Python 类。 -!!! note "技术细节" - `FastAPI` 是直接从 `Starlette` 继承的类。 +/// note | 技术细节 + +`FastAPI` 是直接从 `Starlette` 继承的类。 + +你可以通过 `FastAPI` 使用所有的 Starlette 的功能。 - 你可以通过 `FastAPI` 使用所有的 Starlette 的功能。 +/// ### 步骤 2:创建一个 `FastAPI`「实例」 -```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[3] *} 这里的变量 `app` 会是 `FastAPI` 类的一个「实例」。 @@ -167,9 +166,7 @@ $ uvicorn main:app --reload 如果你像下面这样创建应用: -```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} -``` +{* ../../docs_src/first_steps/tutorial002.py hl[3] *} 将代码放入 `main.py` 文件中,然后你可以像下面这样运行 `uvicorn`: @@ -201,8 +198,11 @@ https://example.com/items/foo /items/foo ``` -!!! info - 「路径」也通常被称为「端点」或「路由」。 +/// info + +「路径」也通常被称为「端点」或「路由」。 + +/// 开发 API 时,「路径」是用来分离「关注点」和「资源」的主要手段。 @@ -243,25 +243,26 @@ https://example.com/items/foo #### 定义一个*路径操作装饰器* -```Python hl_lines="6" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[6] *} `@app.get("/")` 告诉 **FastAPI** 在它下方的函数负责处理如下访问请求: * 请求路径为 `/` * 使用 get 操作 -!!! info "`@decorator` Info" - `@something` 语法在 Python 中被称为「装饰器」。 +/// info | `@decorator` Info - 像一顶漂亮的装饰帽一样,将它放在一个函数的上方(我猜测这个术语的命名就是这么来的)。 +`@something` 语法在 Python 中被称为「装饰器」。 - 装饰器接收位于其下方的函数并且用它完成一些工作。 +像一顶漂亮的装饰帽一样,将它放在一个函数的上方(我猜测这个术语的命名就是这么来的)。 - 在我们的例子中,这个装饰器告诉 **FastAPI** 位于其下方的函数对应着**路径** `/` 加上 `get` **操作**。 +装饰器接收位于其下方的函数并且用它完成一些工作。 - 它是一个「**路径操作装饰器**」。 +在我们的例子中,这个装饰器告诉 **FastAPI** 位于其下方的函数对应着**路径** `/` 加上 `get` **操作**。 + +它是一个「**路径操作装饰器**」。 + +/// 你也可以使用其他的操作: @@ -276,14 +277,17 @@ https://example.com/items/foo * `@app.patch()` * `@app.trace()` -!!! tip - 您可以随意使用任何一个操作(HTTP方法)。 +/// tip + +您可以随意使用任何一个操作(HTTP方法)。 - **FastAPI** 没有强制要求操作有任何特定的含义。 +**FastAPI** 没有强制要求操作有任何特定的含义。 - 此处提供的信息仅作为指导,而不是要求。 +此处提供的信息仅作为指导,而不是要求。 - 比如,当使用 GraphQL 时通常你所有的动作都通过 `post` 一种方法执行。 +比如,当使用 GraphQL 时通常你所有的动作都通过 `post` 一种方法执行。 + +/// ### 步骤 4:定义**路径操作函数** @@ -293,9 +297,7 @@ https://example.com/items/foo * **操作**:是 `get`。 * **函数**:是位于「装饰器」下方的函数(位于 `@app.get("/")` 下方)。 -```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[7] *} 这是一个 Python 函数。 @@ -307,18 +309,17 @@ https://example.com/items/foo 你也可以将其定义为常规函数而不使用 `async def`: -```Python hl_lines="7" -{!../../../docs_src/first_steps/tutorial003.py!} -``` +{* ../../docs_src/first_steps/tutorial003.py hl[7] *} + +/// note -!!! note - 如果你不知道两者的区别,请查阅 [Async: *"In a hurry?"*](https://fastapi.tiangolo.com/async/#in-a-hurry){.internal-link target=_blank}。 +如果你不知道两者的区别,请查阅 [并发: *赶时间吗?*](../async.md#_1){.internal-link target=_blank}。 + +/// ### 步骤 5:返回内容 -```Python hl_lines="8" -{!../../../docs_src/first_steps/tutorial001.py!} -``` +{* ../../docs_src/first_steps/tutorial001.py hl[8] *} 你可以返回一个 `dict`、`list`,像 `str`、`int` 一样的单个值,等等。 diff --git a/docs/zh/docs/tutorial/handling-errors.md b/docs/zh/docs/tutorial/handling-errors.md index a0d66e557..0b887c292 100644 --- a/docs/zh/docs/tutorial/handling-errors.md +++ b/docs/zh/docs/tutorial/handling-errors.md @@ -25,10 +25,7 @@ ### 导入 `HTTPException` -```Python hl_lines="1" -{!../../../docs_src/handling_errors/tutorial001.py!} - -``` +{* ../../docs_src/handling_errors/tutorial001.py hl[1] *} ### 触发 `HTTPException` @@ -42,10 +39,7 @@ 本例中,客户端用 `ID` 请求的 `item` 不存在时,触发状态码为 `404` 的异常: -```Python hl_lines="11" -{!../../../docs_src/handling_errors/tutorial001.py!} - -``` +{* ../../docs_src/handling_errors/tutorial001.py hl[11] *} ### 响应结果 @@ -67,14 +61,15 @@ ``` -!!! tip "提示" +/// tip | 提示 - 触发 `HTTPException` 时,可以用参数 `detail` 传递任何能转换为 JSON 的值,不仅限于 `str`。 +触发 `HTTPException` 时,可以用参数 `detail` 传递任何能转换为 JSON 的值,不仅限于 `str`。 - 还支持传递 `dict`、`list` 等数据结构。 +还支持传递 `dict`、`list` 等数据结构。 - **FastAPI** 能自动处理这些数据,并将之转换为 JSON。 +**FastAPI** 能自动处理这些数据,并将之转换为 JSON。 +/// ## 添加自定义响应头 @@ -84,10 +79,7 @@ 但对于某些高级应用场景,还是需要添加自定义响应头: -```Python hl_lines="14" -{!../../../docs_src/handling_errors/tutorial002.py!} - -``` +{* ../../docs_src/handling_errors/tutorial002.py hl[14] *} ## 安装自定义异常处理器 @@ -99,10 +91,7 @@ 此时,可以用 `@app.exception_handler()` 添加自定义异常控制器: -```Python hl_lines="5-7 13-18 24" -{!../../../docs_src/handling_errors/tutorial003.py!} - -``` +{* ../../docs_src/handling_errors/tutorial003.py hl[5:7,13:18,24] *} 请求 `/unicorns/yolo` 时,路径操作会触发 `UnicornException`。 @@ -115,12 +104,13 @@ ``` -!!! note "技术细节" +/// note | 技术细节 - `from starlette.requests import Request` 和 `from starlette.responses import JSONResponse` 也可以用于导入 `Request` 和 `JSONResponse`。 +`from starlette.requests import Request` 和 `from starlette.responses import JSONResponse` 也可以用于导入 `Request` 和 `JSONResponse`。 - **FastAPI** 提供了与 `starlette.responses` 相同的 `fastapi.responses` 作为快捷方式,但大部分响应操作都可以直接从 Starlette 导入。同理,`Request` 也是如此。 +**FastAPI** 提供了与 `starlette.responses` 相同的 `fastapi.responses` 作为快捷方式,但大部分响应操作都可以直接从 Starlette 导入。同理,`Request` 也是如此。 +/// ## 覆盖默认异常处理器 @@ -140,10 +130,7 @@ 这样,异常处理器就可以接收 `Request` 与异常。 -```Python hl_lines="2 14-16" -{!../../../docs_src/handling_errors/tutorial004.py!} - -``` +{* ../../docs_src/handling_errors/tutorial004.py hl[2,14:16] *} 访问 `/items/foo`,可以看到默认的 JSON 错误信息: @@ -174,12 +161,13 @@ path -> item_id ### `RequestValidationError` vs `ValidationError` -!!! warning "警告" +/// warning | 警告 - 如果您觉得现在还用不到以下技术细节,可以先跳过下面的内容。 +如果您觉得现在还用不到以下技术细节,可以先跳过下面的内容。 +/// -`RequestValidationError` 是 Pydantic 的 `ValidationError` 的子类。 +`RequestValidationError` 是 Pydantic 的 `ValidationError` 的子类。 **FastAPI** 调用的就是 `RequestValidationError` 类,因此,如果在 `response_model` 中使用 Pydantic 模型,且数据有错误时,在日志中就会看到这个错误。 @@ -195,17 +183,15 @@ path -> item_id 例如,只为错误返回纯文本响应,而不是返回 JSON 格式的内容: -```Python hl_lines="3-4 9-11 22" -{!../../../docs_src/handling_errors/tutorial004.py!} - -``` +{* ../../docs_src/handling_errors/tutorial004.py hl[3:4,9:11,22] *} -!!! note "技术细节" +/// note | 技术细节 - 还可以使用 `from starlette.responses import PlainTextResponse`。 +还可以使用 `from starlette.responses import PlainTextResponse`。 - **FastAPI** 提供了与 `starlette.responses` 相同的 `fastapi.responses` 作为快捷方式,但大部分响应都可以直接从 Starlette 导入。 +**FastAPI** 提供了与 `starlette.responses` 相同的 `fastapi.responses` 作为快捷方式,但大部分响应都可以直接从 Starlette 导入。 +/// ### 使用 `RequestValidationError` 的请求体 @@ -213,10 +199,7 @@ path -> item_id 开发时,可以用这个请求体生成日志、调试错误,并返回给用户。 -```Python hl_lines="14" -{!../../../docs_src/handling_errors/tutorial005.py!} - -``` +{* ../../docs_src/handling_errors/tutorial005.py hl[14] *} 现在试着发送一个无效的 `item`,例如: @@ -279,10 +262,7 @@ FastAPI 支持先对异常进行某些处理,然后再使用 **FastAPI** 中 从 `fastapi.exception_handlers` 中导入要复用的默认异常处理器: -```Python hl_lines="2-5 15 21" -{!../../../docs_src/handling_errors/tutorial006.py!} - -``` +{* ../../docs_src/handling_errors/tutorial006.py hl[2:5,15,21] *} 虽然,本例只是输出了夸大其词的错误信息。 diff --git a/docs/zh/docs/tutorial/header-param-models.md b/docs/zh/docs/tutorial/header-param-models.md new file mode 100644 index 000000000..13366aebc --- /dev/null +++ b/docs/zh/docs/tutorial/header-param-models.md @@ -0,0 +1,56 @@ +# Header 参数模型 + +如果您有一组相关的 **header 参数**,您可以创建一个 **Pydantic 模型**来声明它们。 + +这将允许您在**多个地方**能够**重用模型**,并且可以一次性声明所有参数的验证和元数据。😎 + +/// note + +自 FastAPI 版本 `0.115.0` 起支持此功能。🤓 + +/// + +## 使用 Pydantic 模型的 Header 参数 + +在 **Pydantic 模型**中声明所需的 **header 参数**,然后将参数声明为 `Header` : + +{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *} + +**FastAPI** 将从请求中接收到的 **headers** 中**提取**出**每个字段**的数据,并提供您定义的 Pydantic 模型。 + +## 查看文档 + +您可以在文档 UI 的 `/docs` 中查看所需的 headers: + +
+ +
+ +## 禁止额外的 Headers + +在某些特殊使用情况下(可能并不常见),您可能希望**限制**您想要接收的 headers。 + +您可以使用 Pydantic 的模型配置来禁止( `forbid` )任何额外( `extra` )字段: + +{* ../../docs_src/header_param_models/tutorial002_an_py310.py hl[10] *} + +如果客户尝试发送一些**额外的 headers**,他们将收到**错误**响应。 + +例如,如果客户端尝试发送一个值为 `plumbus` 的 `tool` header,客户端将收到一个**错误**响应,告知他们 header 参数 `tool` 是不允许的: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["header", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus", + } + ] +} +``` + +## 总结 + +您可以使用 **Pydantic 模型**在 **FastAPI** 中声明 **headers**。😎 diff --git a/docs/zh/docs/tutorial/header-params.md b/docs/zh/docs/tutorial/header-params.md index 2701167b3..19bb455cf 100644 --- a/docs/zh/docs/tutorial/header-params.md +++ b/docs/zh/docs/tutorial/header-params.md @@ -1,216 +1,79 @@ # Header 参数 -你可以使用定义 `Query`, `Path` 和 `Cookie` 参数一样的方法定义 Header 参数。 +定义 `Header` 参数的方式与定义 `Query`、`Path`、`Cookie` 参数相同。 ## 导入 `Header` -首先导入 `Header`: +首先,导入 `Header`: -=== "Python 3.10+" - - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! tip - 尽可能选择使用 `Annotated` 的版本。 - - ```Python hl_lines="1" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - 尽可能选择使用 `Annotated` 的版本。 - - ```Python hl_lines="3" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` +{* ../../docs_src/header_params/tutorial001_an_py310.py hl[3] *} ## 声明 `Header` 参数 -然后使用和`Path`, `Query` and `Cookie` 一样的结构定义 header 参数 +然后,使用和 `Path`、`Query`、`Cookie` 一样的结构定义 header 参数。 -第一个值是默认值,你可以传递所有的额外验证或注释参数: +第一个值是默认值,还可以传递所有验证参数或注释参数: -=== "Python 3.10+" +{* ../../docs_src/header_params/tutorial001_an_py310.py hl[9] *} - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001_an_py310.py!} - ``` +/// note | 技术细节 -=== "Python 3.9+" +`Header` 是 `Path`、`Query`、`Cookie` 的**兄弟类**,都继承自共用的 `Param` 类。 - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001_an_py39.py!} - ``` +注意,从 `fastapi` 导入的 `Query`、`Path`、`Header` 等对象,实际上是返回特殊类的函数。 -=== "Python 3.8+" +/// - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial001_an.py!} - ``` +/// info | 说明 -=== "Python 3.10+ non-Annotated" +必须使用 `Header` 声明 header 参数,否则该参数会被解释为查询参数。 - !!! tip - 尽可能选择使用 `Annotated` 的版本。 - - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial001_py310.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - 尽可能选择使用 `Annotated` 的版本。 - - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial001.py!} - ``` - -!!! note "技术细节" - `Header` 是 `Path`, `Query` 和 `Cookie` 的兄弟类型。它也继承自通用的 `Param` 类. - - 但是请记得,当你从`fastapi`导入 `Query`, `Path`, `Header`, 或其他时,实际上导入的是返回特定类型的函数。 - -!!! info - 为了声明headers, 你需要使用`Header`, 因为否则参数将被解释为查询参数。 +/// ## 自动转换 -`Header` 在 `Path`, `Query` 和 `Cookie` 提供的功能之上有一点额外的功能。 - -大多数标准的headers用 "连字符" 分隔,也称为 "减号" (`-`)。 - -但是像 `user-agent` 这样的变量在Python中是无效的。 - -因此, 默认情况下, `Header` 将把参数名称的字符从下划线 (`_`) 转换为连字符 (`-`) 来提取并记录 headers. - -同时,HTTP headers 是大小写不敏感的,因此,因此可以使用标准Python样式(也称为 "snake_case")声明它们。 - -因此,您可以像通常在Python代码中那样使用 `user_agent` ,而不需要将首字母大写为 `User_Agent` 或类似的东西。 - -如果出于某些原因,你需要禁用下划线到连字符的自动转换,设置`Header`的参数 `convert_underscores` 为 `False`: - -=== "Python 3.10+" - - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial002_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="11" - {!> ../../../docs_src/header_params/tutorial002_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="12" - {!> ../../../docs_src/header_params/tutorial002_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! tip - 尽可能选择使用 `Annotated` 的版本。 - - ```Python hl_lines="8" - {!> ../../../docs_src/header_params/tutorial002_py310.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - 尽可能选择使用 `Annotated` 的版本。 - - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial002.py!} - ``` - -!!! warning - 在设置 `convert_underscores` 为 `False` 之前,请记住,一些HTTP代理和服务器不允许使用带有下划线的headers。 - - -## 重复的 headers - -有可能收到重复的headers。这意味着,相同的header具有多个值。 - -您可以在类型声明中使用一个list来定义这些情况。 - -你可以通过一个Python `list` 的形式获得重复header的所有值。 +`Header` 比 `Path`、`Query` 和 `Cookie` 提供了更多功能。 -比如, 为了声明一个 `X-Token` header 可以出现多次,你可以这样写: +大部分标准请求头用**连字符**分隔,即**减号**(`-`)。 -=== "Python 3.10+" +但是 `user-agent` 这样的变量在 Python 中是无效的。 - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_an_py310.py!} - ``` +因此,默认情况下,`Header` 把参数名中的字符由下划线(`_`)改为连字符(`-`)来提取并存档请求头 。 -=== "Python 3.9+" +同时,HTTP 的请求头不区分大小写,可以使用 Python 标准样式(即 **snake_case**)进行声明。 - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_an_py39.py!} - ``` +因此,可以像在 Python 代码中一样使用 `user_agent` ,无需把首字母大写为 `User_Agent` 等形式。 -=== "Python 3.8+" +如需禁用下划线自动转换为连字符,可以把 `Header` 的 `convert_underscores` 参数设置为 `False`: - ```Python hl_lines="10" - {!> ../../../docs_src/header_params/tutorial003_an.py!} - ``` +{* ../../docs_src/header_params/tutorial002_an_py310.py hl[10] *} -=== "Python 3.10+ non-Annotated" +/// warning | 警告 - !!! tip - Prefer to use the `Annotated` version if possible. +注意,使用 `convert_underscores = False` 要慎重,有些 HTTP 代理和服务器不支持使用带有下划线的请求头。 - ```Python hl_lines="7" - {!> ../../../docs_src/header_params/tutorial003_py310.py!} - ``` +/// -=== "Python 3.9+ non-Annotated" +## 重复的请求头 - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +有时,可能需要接收重复的请求头。即同一个请求头有多个值。 - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003_py39.py!} - ``` +类型声明中可以使用 `list` 定义多个请求头。 -=== "Python 3.8+ non-Annotated" +使用 Python `list` 可以接收重复请求头所有的值。 - !!! tip - 尽可能选择使用 `Annotated` 的版本。 +例如,声明 `X-Token` 多次出现的请求头,可以写成这样: - ```Python hl_lines="9" - {!> ../../../docs_src/header_params/tutorial003.py!} - ``` +{* ../../docs_src/header_params/tutorial003_an_py310.py hl[9] *} -如果你与*路径操作*通信时发送两个HTTP headers,就像: +与*路径操作*通信时,以下面的方式发送两个 HTTP 请求头: ``` X-Token: foo X-Token: bar ``` -响应会是: +响应结果是: ```JSON { @@ -221,8 +84,8 @@ X-Token: bar } ``` -## 回顾 +## 小结 -使用 `Header` 来声明 header , 使用和 `Query`, `Path` 与 `Cookie` 相同的模式。 +使用 `Header` 声明请求头的方式与 `Query`、`Path` 、`Cookie` 相同。 -不用担心变量中的下划线,**FastAPI** 会负责转换它们。 +不用担心变量中的下划线,**FastAPI** 可以自动转换。 diff --git a/docs/zh/docs/tutorial/index.md b/docs/zh/docs/tutorial/index.md index 6180d3de3..ab19f02c5 100644 --- a/docs/zh/docs/tutorial/index.md +++ b/docs/zh/docs/tutorial/index.md @@ -52,22 +52,25 @@ $ pip install "fastapi[all]" ......以上安装还包括了 `uvicorn`,你可以将其用作运行代码的服务器。 -!!! note - 你也可以分开来安装。 +/// note - 假如你想将应用程序部署到生产环境,你可能要执行以下操作: +你也可以分开来安装。 - ``` - pip install fastapi - ``` +假如你想将应用程序部署到生产环境,你可能要执行以下操作: - 并且安装`uvicorn`来作为服务器: +``` +pip install fastapi +``` + +并且安装`uvicorn`来作为服务器: + +``` +pip install "uvicorn[standard]" +``` - ``` - pip install "uvicorn[standard]" - ``` +然后对你想使用的每个可选依赖项也执行相同的操作。 - 然后对你想使用的每个可选依赖项也执行相同的操作。 +/// ## 进阶用户指南 diff --git a/docs/zh/docs/tutorial/metadata.md b/docs/zh/docs/tutorial/metadata.md index 3e669bc72..d29a1e6d0 100644 --- a/docs/zh/docs/tutorial/metadata.md +++ b/docs/zh/docs/tutorial/metadata.md @@ -1,105 +1,100 @@ -# 元数据和文档 URL - -你可以在 **FastAPI** 应用中自定义几个元数据配置。 - -## 标题、描述和版本 - -你可以设定: - -* **Title**:在 OpenAPI 和自动 API 文档用户界面中作为 API 的标题/名称使用。 -* **Description**:在 OpenAPI 和自动 API 文档用户界面中用作 API 的描述。 -* **Version**:API 版本,例如 `v2` 或者 `2.5.0`。 - * 如果你之前的应用程序版本也使用 OpenAPI 会很有用。 - -使用 `title`、`description` 和 `version` 来设置它们: - -```Python hl_lines="4-6" -{!../../../docs_src/metadata/tutorial001.py!} -``` - -通过这样设置,自动 API 文档看起来会像: - - - -## 标签元数据 - -你也可以使用参数 `openapi_tags`,为用于分组路径操作的不同标签添加额外的元数据。 - -它接受一个列表,这个列表包含每个标签对应的一个字典。 - -每个字典可以包含: - -* `name`(**必要**):一个 `str`,它与*路径操作*和 `APIRouter` 中使用的 `tags` 参数有相同的标签名。 -* `description`:一个用于简短描述标签的 `str`。它支持 Markdown 并且会在文档用户界面中显示。 -* `externalDocs`:一个描述外部文档的 `dict`: - * `description`:用于简短描述外部文档的 `str`。 - * `url`(**必要**):外部文档的 URL `str`。 - -### 创建标签元数据 - -让我们在带有标签的示例中为 `users` 和 `items` 试一下。 - -创建标签元数据并把它传递给 `openapi_tags` 参数: - -```Python hl_lines="3-16 18" -{!../../../docs_src/metadata/tutorial004.py!} -``` - -注意你可以在描述内使用 Markdown,例如「login」会显示为粗体(**login**)以及「fancy」会显示为斜体(_fancy_)。 - -!!! 提示 - 不必为你使用的所有标签都添加元数据。 - -### 使用你的标签 - -将 `tags` 参数和*路径操作*(以及 `APIRouter`)一起使用,将其分配给不同的标签: - -```Python hl_lines="21 26" -{!../../../docs_src/metadata/tutorial004.py!} -``` - -!!! 信息 - 阅读更多关于标签的信息[路径操作配置](../path-operation-configuration/#tags){.internal-link target=_blank}。 - -### 查看文档 - -如果你现在查看文档,它们会显示所有附加的元数据: - - - -### 标签顺序 - -每个标签元数据字典的顺序也定义了在文档用户界面显示的顺序。 - -例如按照字母顺序,即使 `users` 排在 `items` 之后,它也会显示在前面,因为我们将它的元数据添加为列表内的第一个字典。 - -## OpenAPI URL - -默认情况下,OpenAPI 模式服务于 `/openapi.json`。 - -但是你可以通过参数 `openapi_url` 对其进行配置。 - -例如,将其设置为服务于 `/api/v1/openapi.json`: - -```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial002.py!} -``` - -如果你想完全禁用 OpenAPI 模式,可以将其设置为 `openapi_url=None`,这样也会禁用使用它的文档用户界面。 - -## 文档 URLs - -你可以配置两个文档用户界面,包括: - -* **Swagger UI**:服务于 `/docs`。 - * 可以使用参数 `docs_url` 设置它的 URL。 - * 可以通过设置 `docs_url=None` 禁用它。 -* ReDoc:服务于 `/redoc`。 - * 可以使用参数 `redoc_url` 设置它的 URL。 - * 可以通过设置 `redoc_url=None` 禁用它。 - -例如,设置 Swagger UI 服务于 `/documentation` 并禁用 ReDoc: - -```Python hl_lines="3" -{!../../../docs_src/metadata/tutorial003.py!} -``` +# 元数据和文档 URL + +你可以在 FastAPI 应用程序中自定义多个元数据配置。 + +## API 元数据 + +你可以在设置 OpenAPI 规范和自动 API 文档 UI 中使用的以下字段: + +| 参数 | 类型 | 描述 | +|------------|------|-------------| +| `title` | `str` | API 的标题。 | +| `summary` | `str` | API 的简短摘要。 自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。. | +| `description` | `str` | API 的简短描述。可以使用Markdown。 | +| `version` | `string` | API 的版本。这是您自己的应用程序的版本,而不是 OpenAPI 的版本。例如 `2.5.0` 。 | +| `terms_of_service` | `str` | API 服务条款的 URL。如果提供,则必须是 URL。 | +| `contact` | `dict` | 公开的 API 的联系信息。它可以包含多个字段。
contact 字段
参数Type描述
namestr联系人/组织的识别名称。
urlstr指向联系信息的 URL。必须采用 URL 格式。
emailstr联系人/组织的电子邮件地址。必须采用电子邮件地址的格式。
| +| `license_info` | `dict` | 公开的 API 的许可证信息。它可以包含多个字段。
license_info 字段
参数类型描述
namestr必须的 (如果设置了license_info). 用于 API 的许可证名称。
identifierstr一个API的SPDX许可证表达。 The identifier field is mutually exclusive of the url field. 自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用。
urlstr用于 API 的许可证的 URL。必须采用 URL 格式。
| + +你可以按如下方式设置它们: + +{* ../../docs_src/metadata/tutorial001.py hl[4:6] *} + +/// tip + +您可以在 `description` 字段中编写 Markdown,它将在输出中呈现。 + +/// + +通过这样设置,自动 API 文档看起来会像: + + + +## 标签元数据 + +### 创建标签元数据 + +让我们在带有标签的示例中为 `users` 和 `items` 试一下。 + +创建标签元数据并把它传递给 `openapi_tags` 参数: + +{* ../../docs_src/metadata/tutorial004.py hl[3:16,18] *} + +注意你可以在描述内使用 Markdown,例如「login」会显示为粗体(**login**)以及「fancy」会显示为斜体(_fancy_)。 + +/// tip | 提示 + +不必为你使用的所有标签都添加元数据。 + +/// + +### 使用你的标签 + +将 `tags` 参数和*路径操作*(以及 `APIRouter`)一起使用,将其分配给不同的标签: + +{* ../../docs_src/metadata/tutorial004.py hl[21,26] *} + +/// info | 信息 + +阅读更多关于标签的信息[路径操作配置](path-operation-configuration.md#tags){.internal-link target=_blank}。 + +/// + +### 查看文档 + +如果你现在查看文档,它们会显示所有附加的元数据: + + + +### 标签顺序 + +每个标签元数据字典的顺序也定义了在文档用户界面显示的顺序。 + +例如按照字母顺序,即使 `users` 排在 `items` 之后,它也会显示在前面,因为我们将它的元数据添加为列表内的第一个字典。 + +## OpenAPI URL + +默认情况下,OpenAPI 模式服务于 `/openapi.json`。 + +但是你可以通过参数 `openapi_url` 对其进行配置。 + +例如,将其设置为服务于 `/api/v1/openapi.json`: + +{* ../../docs_src/metadata/tutorial002.py hl[3] *} + +如果你想完全禁用 OpenAPI 模式,可以将其设置为 `openapi_url=None`,这样也会禁用使用它的文档用户界面。 + +## 文档 URLs + +你可以配置两个文档用户界面,包括: + +* **Swagger UI**:服务于 `/docs`。 + * 可以使用参数 `docs_url` 设置它的 URL。 + * 可以通过设置 `docs_url=None` 禁用它。 +* ReDoc:服务于 `/redoc`。 + * 可以使用参数 `redoc_url` 设置它的 URL。 + * 可以通过设置 `redoc_url=None` 禁用它。 + +例如,设置 Swagger UI 服务于 `/documentation` 并禁用 ReDoc: + +{* ../../docs_src/metadata/tutorial003.py hl[3] *} diff --git a/docs/zh/docs/tutorial/middleware.md b/docs/zh/docs/tutorial/middleware.md index c9a7e7725..258ca7482 100644 --- a/docs/zh/docs/tutorial/middleware.md +++ b/docs/zh/docs/tutorial/middleware.md @@ -11,10 +11,13 @@ * 它可以对该**响应**做些什么或者执行任何需要的代码. * 然后它返回这个 **响应**. -!!! note "技术细节" - 如果你使用了 `yield` 关键字依赖, 依赖中的退出代码将在执行中间件*后*执行. +/// note | 技术细节 - 如果有任何后台任务(稍后记录), 它们将在执行中间件*后*运行. +如果你使用了 `yield` 关键字依赖, 依赖中的退出代码将在执行中间件*后*执行. + +如果有任何后台任务(稍后记录), 它们将在执行中间件*后*运行. + +/// ## 创建中间件 @@ -28,19 +31,23 @@ * 然后它将返回由相应的*路径操作*生成的 `response`. * 然后你可以在返回 `response` 前进一步修改它. -```Python hl_lines="8-9 11 14" -{!../../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[8:9,11,14] *} + +/// tip + +请记住可以 用'X-' 前缀添加专有自定义请求头. + +但是如果你想让浏览器中的客户端看到你的自定义请求头, 你需要把它们加到 CORS 配置 ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) 的 `expose_headers` 参数中,在 Starlette's CORS docs文档中. + +/// -!!! tip - 请记住可以 用'X-' 前缀添加专有自定义请求头. +/// note | 技术细节 - 但是如果你想让浏览器中的客户端看到你的自定义请求头, 你需要把它们加到 CORS 配置 ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) 的 `expose_headers` 参数中,在 Starlette's CORS docs文档中. +你也可以使用 `from starlette.requests import Request`. -!!! note "技术细节" - 你也可以使用 `from starlette.requests import Request`. +**FastAPI** 为了开发者方便提供了该对象. 但其实它直接来自于 Starlette. - **FastAPI** 为了开发者方便提供了该对象. 但其实它直接来自于 Starlette. +/// ### 在 `response` 的前和后 @@ -50,9 +57,7 @@ 例如你可以添加自定义请求头 `X-Process-Time` 包含以秒为单位的接收请求和生成响应的时间: -```Python hl_lines="10 12-13" -{!../../../docs_src/middleware/tutorial001.py!} -``` +{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *} ## 其他中间件 diff --git a/docs/zh/docs/tutorial/path-operation-configuration.md b/docs/zh/docs/tutorial/path-operation-configuration.md index f79b0e692..adeca2d3f 100644 --- a/docs/zh/docs/tutorial/path-operation-configuration.md +++ b/docs/zh/docs/tutorial/path-operation-configuration.md @@ -2,9 +2,11 @@ *路径操作装饰器*支持多种配置参数。 -!!! warning "警告" +/// warning | 警告 - 注意:以下参数应直接传递给**路径操作装饰器**,不能传递给*路径操作函数*。 +注意:以下参数应直接传递给**路径操作装饰器**,不能传递给*路径操作函数*。 + +/// ## `status_code` 状态码 @@ -14,25 +16,23 @@ 如果记不住数字码的涵义,也可以用 `status` 的快捷常量: -```Python hl_lines="3 17" -{!../../../docs_src/path_operation_configuration/tutorial001.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial001.py hl[3,17] *} 状态码在响应中使用,并会被添加到 OpenAPI 概图。 -!!! note "技术细节" +/// note | 技术细节 + +也可以使用 `from starlette import status` 导入状态码。 - 也可以使用 `from starlette import status` 导入状态码。 +**FastAPI** 的`fastapi.status` 和 `starlette.status` 一样,只是快捷方式。实际上,`fastapi.status` 直接继承自 Starlette。 - **FastAPI** 的`fastapi.status` 和 `starlette.status` 一样,只是快捷方式。实际上,`fastapi.status` 直接继承自 Starlette。 +/// ## `tags` 参数 `tags` 参数的值是由 `str` 组成的 `list` (一般只有一个 `str` ),`tags` 用于为*路径操作*添加标签: -```Python hl_lines="17 22 27" -{!../../../docs_src/path_operation_configuration/tutorial002.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial002.py hl[17,22,27] *} OpenAPI 概图会自动添加标签,供 API 文档接口使用: @@ -42,9 +42,7 @@ OpenAPI 概图会自动添加标签,供 API 文档接口使用: 路径装饰器还支持 `summary` 和 `description` 这两个参数: -```Python hl_lines="20-21" -{!../../../docs_src/path_operation_configuration/tutorial003.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial003.py hl[20:21] *} ## 文档字符串(`docstring`) @@ -52,9 +50,7 @@ OpenAPI 概图会自动添加标签,供 API 文档接口使用: 文档字符串支持 Markdown,能正确解析和显示 Markdown 的内容,但要注意文档字符串的缩进。 -```Python hl_lines="19-27" -{!../../../docs_src/path_operation_configuration/tutorial004.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial004.py hl[19:27] *} 下图为 Markdown 文本在 API 文档中的显示效果: @@ -64,19 +60,21 @@ OpenAPI 概图会自动添加标签,供 API 文档接口使用: `response_description` 参数用于定义响应的描述说明: -```Python hl_lines="21" -{!../../../docs_src/path_operation_configuration/tutorial005.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial005.py hl[21] *} + +/// info | 说明 + +注意,`response_description` 只用于描述响应,`description` 一般则用于描述*路径操作*。 -!!! info "说明" +/// - 注意,`response_description` 只用于描述响应,`description` 一般则用于描述*路径操作*。 +/// check | 检查 -!!! check "检查" +OpenAPI 规定每个*路径操作*都要有响应描述。 - OpenAPI 规定每个*路径操作*都要有响应描述。 +如果没有定义响应描述,**FastAPI** 则自动生成内容为 "Successful response" 的响应描述。 - 如果没有定义响应描述,**FastAPI** 则自动生成内容为 "Successful response" 的响应描述。 +/// @@ -84,9 +82,7 @@ OpenAPI 概图会自动添加标签,供 API 文档接口使用: `deprecated` 参数可以把*路径操作*标记为弃用,无需直接删除: -```Python hl_lines="16" -{!../../../docs_src/path_operation_configuration/tutorial006.py!} -``` +{* ../../docs_src/path_operation_configuration/tutorial006.py hl[16] *} API 文档会把该路径操作标记为弃用: diff --git a/docs/zh/docs/tutorial/path-params-numeric-validations.md b/docs/zh/docs/tutorial/path-params-numeric-validations.md index 9b41ad7cf..ff6242835 100644 --- a/docs/zh/docs/tutorial/path-params-numeric-validations.md +++ b/docs/zh/docs/tutorial/path-params-numeric-validations.md @@ -6,41 +6,7 @@ 首先,从 `fastapi` 导入 `Path`: -=== "Python 3.10+" - - ```Python hl_lines="1 3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="1 3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="3-4" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! tip - 尽可能选择使用 `Annotated` 的版本。 - - ```Python hl_lines="1" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - 尽可能选择使用 `Annotated` 的版本。 - - ```Python hl_lines="3" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` +{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *} ## 声明元数据 @@ -48,48 +14,17 @@ 例如,要声明路径参数 `item_id`的 `title` 元数据值,你可以输入: -=== "Python 3.10+" - - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py!} - ``` - -=== "Python 3.9+" +{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *} - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an_py39.py!} - ``` +/// note -=== "Python 3.8+" +路径参数总是必需的,因为它必须是路径的一部分。 - ```Python hl_lines="11" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_an.py!} - ``` +所以,你应该在声明时使用 `...` 将其标记为必需参数。 -=== "Python 3.10+ non-Annotated" +然而,即使你使用 `None` 声明路径参数或设置一个其他默认值也不会有任何影响,它依然会是必需参数。 - !!! tip - 尽可能选择使用 `Annotated` 的版本。 - - ```Python hl_lines="8" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001_py310.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - 尽可能选择使用 `Annotated` 的版本。 - - ```Python hl_lines="10" - {!> ../../../docs_src/path_params_numeric_validations/tutorial001.py!} - ``` - -!!! note - 路径参数总是必需的,因为它必须是路径的一部分。 - - 所以,你应该在声明时使用 `...` 将其标记为必需参数。 - - 然而,即使你使用 `None` 声明路径参数或设置一个其他默认值也不会有任何影响,它依然会是必需参数。 +/// ## 按需对参数排序 @@ -107,14 +42,7 @@ 因此,你可以将函数声明为: -=== "Python 3.8 non-Annotated" - - !!! tip - 尽可能选择使用 `Annotated` 的版本。 - - ```Python hl_lines="7" - {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} - ``` +{* ../../docs_src/path_params_numeric_validations/tutorial002.py hl[7] *} ## 按需对参数排序的技巧 @@ -124,9 +52,7 @@ Python 不会对该 `*` 做任何事情,但是它将知道之后的所有参数都应作为关键字参数(键值对),也被称为 kwargs,来调用。即使它们没有默认值。 -```Python hl_lines="7" -{!../../../docs_src/path_params_numeric_validations/tutorial003.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *} ## 数值校验:大于等于 @@ -134,9 +60,7 @@ Python 不会对该 `*` 做任何事情,但是它将知道之后的所有参 像下面这样,添加 `ge=1` 后,`item_id` 将必须是一个大于(`g`reater than)或等于(`e`qual)`1` 的整数。 -```Python hl_lines="8" -{!../../../docs_src/path_params_numeric_validations/tutorial004.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial004.py hl[8] *} ## 数值校验:大于和小于等于 @@ -145,9 +69,7 @@ Python 不会对该 `*` 做任何事情,但是它将知道之后的所有参 * `gt`:大于(`g`reater `t`han) * `le`:小于等于(`l`ess than or `e`qual) -```Python hl_lines="9" -{!../../../docs_src/path_params_numeric_validations/tutorial005.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial005.py hl[9] *} ## 数值校验:浮点数、大于和小于 @@ -159,9 +81,7 @@ Python 不会对该 `*` 做任何事情,但是它将知道之后的所有参 对于 lt 也是一样的。 -```Python hl_lines="11" -{!../../../docs_src/path_params_numeric_validations/tutorial006.py!} -``` +{* ../../docs_src/path_params_numeric_validations/tutorial006.py hl[11] *} ## 总结 @@ -174,18 +94,24 @@ Python 不会对该 `*` 做任何事情,但是它将知道之后的所有参 * `lt`:小于(`l`ess `t`han) * `le`:小于等于(`l`ess than or `e`qual) -!!! info - `Query`、`Path` 以及你后面会看到的其他类继承自一个共同的 `Param` 类(不需要直接使用它)。 +/// info + +`Query`、`Path` 以及你后面会看到的其他类继承自一个共同的 `Param` 类(不需要直接使用它)。 + +而且它们都共享相同的所有你已看到并用于添加额外校验和元数据的参数。 + +/// + +/// note | 技术细节 - 而且它们都共享相同的所有你已看到并用于添加额外校验和元数据的参数。 +当你从 `fastapi` 导入 `Query`、`Path` 和其他同类对象时,它们实际上是函数。 -!!! note "技术细节" - 当你从 `fastapi` 导入 `Query`、`Path` 和其他同类对象时,它们实际上是函数。 +当被调用时,它们返回同名类的实例。 - 当被调用时,它们返回同名类的实例。 +如此,你导入 `Query` 这个函数。当你调用它时,它将返回一个同样命名为 `Query` 的类的实例。 - 如此,你导入 `Query` 这个函数。当你调用它时,它将返回一个同样命名为 `Query` 的类的实例。 +因为使用了这些函数(而不是直接使用类),所以你的编辑器不会标记有关其类型的错误。 - 因为使用了这些函数(而不是直接使用类),所以你的编辑器不会标记有关其类型的错误。 +这样,你可以使用常规的编辑器和编码工具,而不必添加自定义配置来忽略这些错误。 - 这样,你可以使用常规的编辑器和编码工具,而不必添加自定义配置来忽略这些错误。 +/// diff --git a/docs/zh/docs/tutorial/path-params.md b/docs/zh/docs/tutorial/path-params.md index 1b428d662..ac9df0831 100644 --- a/docs/zh/docs/tutorial/path-params.md +++ b/docs/zh/docs/tutorial/path-params.md @@ -1,48 +1,50 @@ # 路径参数 -你可以使用与 Python 格式化字符串相同的语法来声明路径"参数"或"变量": +FastAPI 支持使用 Python 字符串格式化语法声明**路径参数**(**变量**): -```Python hl_lines="6-7" -{!../../../docs_src/path_params/tutorial001.py!} -``` +{* ../../docs_src/path_params/tutorial001.py hl[6:7] *} -路径参数 `item_id` 的值将作为参数 `item_id` 传递给你的函数。 +这段代码把路径参数 `item_id` 的值传递给路径函数的参数 `item_id`。 -所以,如果你运行示例并访问 http://127.0.0.1:8000/items/foo,将会看到如下响应: +运行示例并访问 http://127.0.0.1:8000/items/foo,可获得如下响应: ```JSON {"item_id":"foo"} ``` -## 有类型的路径参数 +## 声明路径参数的类型 -你可以使用标准的 Python 类型标注为函数中的路径参数声明类型。 +使用 Python 标准类型注解,声明路径操作函数中路径参数的类型。 -```Python hl_lines="7" -{!../../../docs_src/path_params/tutorial002.py!} -``` +{* ../../docs_src/path_params/tutorial002.py hl[7] *} + +本例把 `item_id` 的类型声明为 `int`。 + +/// check | 检查 -在这个例子中,`item_id` 被声明为 `int` 类型。 +类型声明将为函数提供错误检查、代码补全等编辑器支持。 -!!! check - 这将为你的函数提供编辑器支持,包括错误检查、代码补全等等。 +/// -## 数据转换 +## 数据转换 -如果你运行示例并打开浏览器访问 http://127.0.0.1:8000/items/3,将得到如下响应: +运行示例并访问 http://127.0.0.1:8000/items/3,返回的响应如下: ```JSON {"item_id":3} ``` -!!! check - 注意函数接收(并返回)的值为 3,是一个 Python `int` 值,而不是字符串 `"3"`。 +/// check | 检查 - 所以,**FastAPI** 通过上面的类型声明提供了对请求的自动"解析"。 +注意,函数接收并返回的值是 `3`( `int`),不是 `"3"`(`str`)。 + +**FastAPI** 通过类型声明自动**解析**请求中的数据。 + +/// ## 数据校验 -但如果你通过浏览器访问 http://127.0.0.1:8000/items/foo,你会看到一个清晰可读的 HTTP 错误: +通过浏览器访问 http://127.0.0.1:8000/items/foo,接收如下 HTTP 错误信息: ```JSON { @@ -59,176 +61,190 @@ } ``` -因为路径参数 `item_id` 传入的值为 `"foo"`,它不是一个 `int`。 +这是因为路径参数 `item_id` 的值 (`"foo"`)的类型不是 `int`。 + +值的类型不是 `int ` 而是浮点数(`float`)时也会显示同样的错误,比如: http://127.0.0.1:8000/items/4.2。 + +/// check | 检查 -如果你提供的是 `float` 而非整数也会出现同样的错误,比如: http://127.0.0.1:8000/items/4.2 +**FastAPI** 使用 Python 类型声明实现了数据校验。 -!!! check - 所以,通过同样的 Python 类型声明,**FastAPI** 提供了数据校验功能。 +注意,上面的错误清晰地指出了未通过校验的具体原因。 - 注意上面的错误同样清楚地指出了校验未通过的具体原因。 +这在开发调试与 API 交互的代码时非常有用。 - 在开发和调试与你的 API 进行交互的代码时,这非常有用。 +/// -## 文档 +## 查看文档 -当你打开浏览器访问 http://127.0.0.1:8000/docs,你将看到自动生成的交互式 API 文档: +访问 http://127.0.0.1:8000/docs,查看自动生成的 API 文档: - + -!!! check - 再一次,还是通过相同的 Python 类型声明,**FastAPI** 为你提供了自动生成的交互式文档(集成 Swagger UI)。 +/// check | 检查 - 注意这里的路径参数被声明为一个整数。 +还是使用 Python 类型声明,**FastAPI** 提供了(集成 Swagger UI 的)API 文档。 -## 基于标准的好处:可选文档 +注意,路径参数的类型是整数。 -由于生成的 API 模式来自于 OpenAPI 标准,所以有很多工具与其兼容。 +/// -正因如此,**FastAPI** 内置了一个可选的 API 文档(使用 Redoc): +## 基于标准的好处,备选文档 - +**FastAPI** 使用 OpenAPI 生成概图,所以能兼容很多工具。 -同样的,还有很多其他兼容的工具,包括适用于多种语言的代码生成工具。 +因此,**FastAPI** 还内置了 ReDoc 生成的备选 API 文档,可在此查看 http://127.0.0.1:8000/redoc: + + + +同样,还有很多兼容工具,包括多种语言的代码生成工具。 ## Pydantic -所有的数据校验都由 Pydantic 在幕后完成,所以你可以从它所有的优点中受益。并且你知道它在这方面非常胜任。 +FastAPI 充分地利用了 Pydantic 的优势,用它在后台校验数据。众所周知,Pydantic 擅长的就是数据校验。 -你可以使用同样的类型声明来声明 `str`、`float`、`bool` 以及许多其他的复合数据类型。 +同样,`str`、`float`、`bool` 以及很多复合数据类型都可以使用类型声明。 -本教程的下一章节将探讨其中的一些内容。 +下一章介绍详细内容。 ## 顺序很重要 -在创建*路径操作*时,你会发现有些情况下路径是固定的。 +有时,*路径操作*中的路径是写死的。 -比如 `/users/me`,我们假设它用来获取关于当前用户的数据. +比如要使用 `/users/me` 获取当前用户的数据。 -然后,你还可以使用路径 `/users/{user_id}` 来通过用户 ID 获取关于特定用户的数据。 +然后还要使用 `/users/{user_id}`,通过用户 ID 获取指定用户的数据。 -由于*路径操作*是按顺序依次运行的,你需要确保路径 `/users/me` 声明在路径 `/users/{user_id}`之前: -```Python hl_lines="6 11" -{!../../../docs_src/path_params/tutorial003.py!} -``` +由于*路径操作*是按顺序依次运行的,因此,一定要在 `/users/{user_id}` 之前声明 `/users/me` : + +{* ../../docs_src/path_params/tutorial003.py hl[6,11] *} -否则,`/users/{user_id}` 的路径还将与 `/users/me` 相匹配,"认为"自己正在接收一个值为 `"me"` 的 `user_id` 参数。 +否则,`/users/{user_id}` 将匹配 `/users/me`,FastAPI 会**认为**正在接收值为 `"me"` 的 `user_id` 参数。 ## 预设值 -如果你有一个接收路径参数的路径操作,但你希望预先设定可能的有效参数值,则可以使用标准的 Python `Enum` 类型。 +路径操作使用 Python 的 `Enum` 类型接收预设的*路径参数*。 -### 创建一个 `Enum` 类 +### 创建 `Enum` 类 -导入 `Enum` 并创建一个继承自 `str` 和 `Enum` 的子类。 +导入 `Enum` 并创建继承自 `str` 和 `Enum` 的子类。 -通过从 `str` 继承,API 文档将能够知道这些值必须为 `string` 类型并且能够正确地展示出来。 +通过从 `str` 继承,API 文档就能把值的类型定义为**字符串**,并且能正确渲染。 -然后创建具有固定值的类属性,这些固定值将是可用的有效值: +然后,创建包含固定值的类属性,这些固定值是可用的有效值: -```Python hl_lines="1 6-9" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *} + +/// info | 说明 + +Python 3.4 及之后版本支持枚举(即 enums)。 -!!! info - 枚举(或 enums)从 3.4 版本起在 Python 中可用。 +/// -!!! tip - 如果你想知道,"AlexNet"、"ResNet" 和 "LeNet" 只是机器学习中的模型名称。 +/// tip | 提示 + +**AlexNet**、**ResNet**、**LeNet** 是机器学习模型。 + +/// ### 声明*路径参数* -然后使用你定义的枚举类(`ModelName`)创建一个带有类型标注的*路径参数*: +使用 Enum 类(`ModelName`)创建使用类型注解的*路径参数*: -```Python hl_lines="16" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[16] *} ### 查看文档 -因为已经指定了*路径参数*的可用值,所以交互式文档可以恰当地展示它们: + API 文档会显示预定义*路径参数*的可用值: - + -### 使用 Python *枚举类型* +### 使用 Python _枚举类型_ -*路径参数*的值将是一个*枚举成员*。 +*路径参数*的值是枚举的元素。 -#### 比较*枚举成员* +#### 比较*枚举元素* -你可以将它与你创建的枚举类 `ModelName` 中的*枚举成员*进行比较: +枚举类 `ModelName` 中的*枚举元素*支持比较操作: -```Python hl_lines="17" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[17] *} #### 获取*枚举值* -你可以使用 `model_name.value` 或通常来说 `your_enum_member.value` 来获取实际的值(在这个例子中为 `str`): +使用 `model_name.value` 或 `your_enum_member.value` 获取实际的值(本例中为**字符串**): -```Python hl_lines="19" -{!../../../docs_src/path_params/tutorial005.py!} -``` +{* ../../docs_src/path_params/tutorial005.py hl[20] *} + +/// tip | 提示 + +使用 `ModelName.lenet.value` 也能获取值 `"lenet"`。 + +/// -!!! tip - 你也可以通过 `ModelName.lenet.value` 来获取值 `"lenet"`。 +#### 返回*枚举元素* -#### 返回*枚举成员* +即使嵌套在 JSON 请求体里(例如, `dict`),也可以从*路径操作*返回*枚举元素*。 -你可以从*路径操作*中返回*枚举成员*,即使嵌套在 JSON 结构中(例如一个 `dict` 中)。 +返回给客户端之前,要把枚举元素转换为对应的值(本例中为字符串): -在返回给客户端之前,它们将被转换为对应的值: +{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *} -```Python hl_lines="18-21" -{!../../../docs_src/path_params/tutorial005.py!} +客户端中的 JSON 响应如下: + +```JSON +{ + "model_name": "alexnet", + "message": "Deep Learning FTW!" +} ``` ## 包含路径的路径参数 -假设你有一个*路径操作*,它的路径为 `/files/{file_path}`。 +假设*路径操作*的路径为 `/files/{file_path}`。 -但是你需要 `file_path` 自身也包含*路径*,比如 `home/johndoe/myfile.txt`。 +但需要 `file_path` 中也包含*路径*,比如,`home/johndoe/myfile.txt`。 -因此,该文件的URL将类似于这样:`/files/home/johndoe/myfile.txt`。 +此时,该文件的 URL 是这样的:`/files/home/johndoe/myfile.txt`。 ### OpenAPI 支持 -OpenAPI 不支持任何方式去声明*路径参数*以在其内部包含*路径*,因为这可能会导致难以测试和定义的情况出现。 +OpenAPI 不支持声明包含路径的*路径参数*,因为这会导致测试和定义更加困难。 -不过,你仍然可以通过 Starlette 的一个内部工具在 **FastAPI** 中实现它。 +不过,仍可使用 Starlette 内置工具在 **FastAPI** 中实现这一功能。 -而且文档依旧可以使用,但是不会添加任何该参数应包含路径的说明。 +而且不影响文档正常运行,但是不会添加该参数包含路径的说明。 ### 路径转换器 -你可以使用直接来自 Starlette 的选项来声明一个包含*路径*的*路径参数*: +直接使用 Starlette 的选项声明包含*路径*的*路径参数*: ``` /files/{file_path:path} ``` -在这种情况下,参数的名称为 `file_path`,结尾部分的 `:path` 说明该参数应匹配任意的*路径*。 +本例中,参数名为 `file_path`,结尾部分的 `:path` 说明该参数应匹配*路径*。 -因此,你可以这样使用它: +用法如下: -```Python hl_lines="6" -{!../../../docs_src/path_params/tutorial004.py!} -``` +{* ../../docs_src/path_params/tutorial004.py hl[6] *} + +/// tip | 提示 + +注意,包含 `/home/johndoe/myfile.txt` 的路径参数要以斜杠(`/`)开头。 -!!! tip - 你可能会需要参数包含 `/home/johndoe/myfile.txt`,以斜杠(`/`)开头。 +本例中的 URL 是 `/files//home/johndoe/myfile.txt`。注意,`files` 和 `home` 之间要使用**双斜杠**(`//`)。 - 在这种情况下,URL 将会是 `/files//home/johndoe/myfile.txt`,在`files` 和 `home` 之间有一个双斜杠(`//`)。 +/// -## 总结 +## 小结 -使用 **FastAPI**,通过简短、直观和标准的 Python 类型声明,你将获得: +通过简短、直观的 Python 标准类型声明,**FastAPI** 可以获得: -* 编辑器支持:错误检查,代码补全等 -* 数据 "解析" -* 数据校验 -* API 标注和自动生成的文档 +- 编辑器支持:错误检查,代码自动补全等 +- 数据**解析** +- 数据校验 +- API 注解和 API 文档 -而且你只需要声明一次即可。 +只需要声明一次即可。 -这可能是 **FastAPI** 与其他框架相比主要的明显优势(除了原始性能以外)。 +这可能是除了性能以外,**FastAPI** 与其它框架相比的主要优势。 diff --git a/docs/zh/docs/tutorial/query-param-models.md b/docs/zh/docs/tutorial/query-param-models.md new file mode 100644 index 000000000..c6a79a71a --- /dev/null +++ b/docs/zh/docs/tutorial/query-param-models.md @@ -0,0 +1,68 @@ +# 查询参数模型 + +如果你有一组具有相关性的**查询参数**,你可以创建一个 **Pydantic 模型**来声明它们。 + +这将允许你在**多个地方**去**复用模型**,并且一次性为所有参数声明验证和元数据。😎 + +/// note + +FastAPI 从 `0.115.0` 版本开始支持这个特性。🤓 + +/// + +## 使用 Pydantic 模型的查询参数 + +在一个 **Pydantic 模型**中声明你需要的**查询参数**,然后将参数声明为 `Query`: + +{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *} + +**FastAPI** 将会从请求的**查询参数**中**提取**出**每个字段**的数据,并将其提供给你定义的 Pydantic 模型。 + +## 查看文档 + +你可以在 `/docs` 页面的 UI 中查看查询参数: + +
+ +
+ +## 禁止额外的查询参数 + +在一些特殊的使用场景中(可能不是很常见),你可能希望**限制**你要接收的查询参数。 + +你可以使用 Pydantic 的模型配置来 `forbid`(意为禁止 —— 译者注)任何 `extra`(意为额外的 —— 译者注)字段: + +{* ../../docs_src/query_param_models/tutorial002_an_py310.py hl[10] *} + +假设有一个客户端尝试在**查询参数**中发送一些**额外的**数据,它将会收到一个**错误**响应。 + +例如,如果客户端尝试发送一个值为 `plumbus` 的 `tool` 查询参数,如: + +```http +https://example.com/items/?limit=10&tool=plumbus +``` + +他们将收到一个**错误**响应,告诉他们查询参数 `tool` 是不允许的: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["query", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus" + } + ] +} +``` + +## 总结 + +你可以使用 **Pydantic 模型**在 **FastAPI** 中声明**查询参数**。😎 + +/// tip + +剧透警告:你也可以使用 Pydantic 模型来声明 cookie 和 headers,但你将在本教程的后面部分阅读到这部分内容。🤫 + +/// diff --git a/docs/zh/docs/tutorial/query-params-str-validations.md b/docs/zh/docs/tutorial/query-params-str-validations.md index 39253eb0d..c2f9a7e9f 100644 --- a/docs/zh/docs/tutorial/query-params-str-validations.md +++ b/docs/zh/docs/tutorial/query-params-str-validations.md @@ -4,17 +4,7 @@ 让我们以下面的应用程序为例: -=== "Python 3.10+" - - ```Python hl_lines="7" - {!> ../../../docs_src/query_params_str_validations/tutorial001_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="9" - {!> ../../../docs_src/query_params_str_validations/tutorial001.py!} - ``` +{* ../../docs_src/query_params_str_validations/tutorial001_py310.py hl[7] *} 查询参数 `q` 的类型为 `str`,默认值为 `None`,因此它是可选的。 @@ -26,17 +16,13 @@ 为此,首先从 `fastapi` 导入 `Query`: -```Python hl_lines="1" -{!../../../docs_src/query_params_str_validations/tutorial002.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[1] *} ## 使用 `Query` 作为默认值 现在,将 `Query` 用作查询参数的默认值,并将它的 `max_length` 参数设置为 50: -```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial002.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial002.py hl[9] *} 由于我们必须用 `Query(default=None)` 替换默认值 `None`,`Query` 的第一个参数同样也是用于定义默认值。 @@ -66,17 +52,13 @@ q: Union[str, None] = Query(default=None, max_length=50) 你还可以添加 `min_length` 参数: -```Python hl_lines="10" -{!../../../docs_src/query_params_str_validations/tutorial003.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial003.py hl[10] *} ## 添加正则表达式 你可以定义一个参数值必须匹配的正则表达式: -```Python hl_lines="11" -{!../../../docs_src/query_params_str_validations/tutorial004.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial004.py hl[11] *} 这个指定的正则表达式通过以下规则检查接收到的参数值: @@ -94,12 +76,13 @@ q: Union[str, None] = Query(default=None, max_length=50) 假设你想要声明查询参数 `q`,使其 `min_length` 为 `3`,并且默认值为 `fixedquery`: -```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial005.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial005.py hl[7] *} + +/// note -!!! note - 具有默认值还会使该参数成为可选参数。 +具有默认值还会使该参数成为可选参数。 + +/// ## 声明为必需参数 @@ -123,23 +106,7 @@ q: Union[str, None] = Query(default=None, min_length=3) 因此,当你在使用 `Query` 且需要声明一个值是必需的时,只需不声明默认参数: -```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial006.py!} -``` - -### 使用省略号(`...`)声明必需参数 - -有另一种方法可以显式的声明一个值是必需的,即将默认参数的默认值设为 `...` : - -```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial006b.py!} -``` - -!!! info - 如果你之前没见过 `...` 这种用法:它是一个特殊的单独值,它是 Python 的一部分并且被称为「省略号」。 - Pydantic 和 FastAPI 使用它来显式的声明需要一个值。 - -这将使 **FastAPI** 知道此查询参数是必需的。 +{* ../../docs_src/query_params_str_validations/tutorial006.py hl[7] *} ### 使用`None`声明必需参数 @@ -147,24 +114,13 @@ q: Union[str, None] = Query(default=None, min_length=3) 为此,你可以声明`None`是一个有效的类型,并仍然使用`default=...`: -```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial006c.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial006c.py hl[9] *} -!!! tip - Pydantic 是 FastAPI 中所有数据验证和序列化的核心,当你在没有设默认值的情况下使用 `Optional` 或 `Union[Something, None]` 时,它具有特殊行为,你可以在 Pydantic 文档中阅读有关必需可选字段的更多信息。 +/// tip -### 使用Pydantic中的`Required`代替省略号(`...`) - -如果你觉得使用 `...` 不舒服,你也可以从 Pydantic 导入并使用 `Required`: - -```Python hl_lines="2 8" -{!../../../docs_src/query_params_str_validations/tutorial006d.py!} -``` - -!!! tip - 请记住,在大多数情况下,当你需要某些东西时,可以简单地省略 `default` 参数,因此你通常不必使用 `...` 或 `Required` +Pydantic 是 FastAPI 中所有数据验证和序列化的核心,当你在没有设默认值的情况下使用 `Optional` 或 `Union[Something, None]` 时,它具有特殊行为,你可以在 Pydantic 文档中阅读有关必需可选字段的更多信息。 +/// ## 查询参数列表 / 多个值 @@ -172,9 +128,7 @@ q: Union[str, None] = Query(default=None, min_length=3) 例如,要声明一个可在 URL 中出现多次的查询参数 `q`,你可以这样写: -```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial011.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial011.py hl[9] *} 然后,输入如下网址: @@ -195,8 +149,11 @@ http://localhost:8000/items/?q=foo&q=bar } ``` -!!! tip - 要声明类型为 `list` 的查询参数,如上例所示,你需要显式地使用 `Query`,否则该参数将被解释为请求体。 +/// tip + +要声明类型为 `list` 的查询参数,如上例所示,你需要显式地使用 `Query`,否则该参数将被解释为请求体。 + +/// 交互式 API 文档将会相应地进行更新,以允许使用多个值: @@ -206,9 +163,7 @@ http://localhost:8000/items/?q=foo&q=bar 你还可以定义在没有任何给定值时的默认 `list` 值: -```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial012.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial012.py hl[9] *} 如果你访问: @@ -231,14 +186,15 @@ http://localhost:8000/items/ 你也可以直接使用 `list` 代替 `List [str]`: -```Python hl_lines="7" -{!../../../docs_src/query_params_str_validations/tutorial013.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial013.py hl[7] *} -!!! note - 请记住,在这种情况下 FastAPI 将不会检查列表的内容。 +/// note - 例如,`List[int]` 将检查(并记录到文档)列表的内容必须是整数。但是单独的 `list` 不会。 +请记住,在这种情况下 FastAPI 将不会检查列表的内容。 + +例如,`List[int]` 将检查(并记录到文档)列表的内容必须是整数。但是单独的 `list` 不会。 + +/// ## 声明更多元数据 @@ -246,22 +202,21 @@ http://localhost:8000/items/ 这些信息将包含在生成的 OpenAPI 模式中,并由文档用户界面和外部工具所使用。 -!!! note - 请记住,不同的工具对 OpenAPI 的支持程度可能不同。 +/// note + +请记住,不同的工具对 OpenAPI 的支持程度可能不同。 + +其中一些可能不会展示所有已声明的额外信息,尽管在大多数情况下,缺少的这部分功能已经计划进行开发。 - 其中一些可能不会展示所有已声明的额外信息,尽管在大多数情况下,缺少的这部分功能已经计划进行开发。 +/// 你可以添加 `title`: -```Python hl_lines="10" -{!../../../docs_src/query_params_str_validations/tutorial007.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial007.py hl[10] *} 以及 `description`: -```Python hl_lines="13" -{!../../../docs_src/query_params_str_validations/tutorial008.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial008.py hl[13] *} ## 别名参数 @@ -281,9 +236,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems 这时你可以用 `alias` 参数声明一个别名,该别名将用于在 URL 中查找查询参数值: -```Python hl_lines="9" -{!../../../docs_src/query_params_str_validations/tutorial009.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial009.py hl[9] *} ## 弃用参数 @@ -293,9 +246,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems 那么将参数 `deprecated=True` 传入 `Query`: -```Python hl_lines="18" -{!../../../docs_src/query_params_str_validations/tutorial010.py!} -``` +{* ../../docs_src/query_params_str_validations/tutorial010.py hl[18] *} 文档将会像下面这样展示它: diff --git a/docs/zh/docs/tutorial/query-params.md b/docs/zh/docs/tutorial/query-params.md index b1668a2d2..cc2e74b9e 100644 --- a/docs/zh/docs/tutorial/query-params.md +++ b/docs/zh/docs/tutorial/query-params.md @@ -1,86 +1,92 @@ # 查询参数 -声明不属于路径参数的其他函数参数时,它们将被自动解释为"查询字符串"参数 +声明的参数不是路径参数时,路径操作函数会把该参数自动解释为**查询**参数。 -```Python hl_lines="9" -{!../../../docs_src/query_params/tutorial001.py!} -``` +{* ../../docs_src/query_params/tutorial001.py hl[9] *} -查询字符串是键值对的集合,这些键值对位于 URL 的 `?` 之后,并以 `&` 符号分隔。 +查询字符串是键值对的集合,这些键值对位于 URL 的 `?` 之后,以 `&` 分隔。 -例如,在以下 url 中: +例如,以下 URL 中: ``` http://127.0.0.1:8000/items/?skip=0&limit=10 ``` -...查询参数为: +……查询参数为: -* `skip`:对应的值为 `0` -* `limit`:对应的值为 `10` +* `skip`:值为 `0` +* `limit`:值为 `10` -由于它们是 URL 的一部分,因此它们的"原始值"是字符串。 +这些值都是 URL 的组成部分,因此,它们的类型**本应**是字符串。 -但是,当你为它们声明了 Python 类型(在上面的示例中为 `int`)时,它们将转换为该类型并针对该类型进行校验。 +但声明 Python 类型(上例中为 `int`)之后,这些值就会转换为声明的类型,并进行类型校验。 -应用于路径参数的所有相同过程也适用于查询参数: +所有应用于路径参数的流程也适用于查询参数: -* (很明显的)编辑器支持 -* 数据"解析" +* (显而易见的)编辑器支持 +* 数据**解析** * 数据校验 -* 自动生成文档 +* API 文档 ## 默认值 -由于查询参数不是路径的固定部分,因此它们可以是可选的,并且可以有默认值。 +查询参数不是路径的固定内容,它是可选的,还支持默认值。 -在上面的示例中,它们具有 `skip=0` 和 `limit=10` 的默认值。 +上例用 `skip=0` 和 `limit=10` 设定默认值。 -因此,访问 URL: +访问 URL: ``` http://127.0.0.1:8000/items/ ``` -将与访问以下地址相同: +与访问以下地址相同: ``` http://127.0.0.1:8000/items/?skip=0&limit=10 ``` -但是,如果你访问的是: +但如果访问: ``` http://127.0.0.1:8000/items/?skip=20 ``` -函数中的参数值将会是: +查询参数的值就是: * `skip=20`:在 URL 中设定的值 * `limit=10`:使用默认值 ## 可选参数 -通过同样的方式,你可以将它们的默认值设置为 `None` 来声明可选查询参数: +同理,把默认值设为 `None` 即可声明**可选的**查询参数: -```Python hl_lines="7" -{!../../../docs_src/query_params/tutorial002.py!} -``` +{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *} + +本例中,查询参数 `q` 是可选的,默认值为 `None`。 + +/// check | 检查 + +注意,**FastAPI** 可以识别出 `item_id` 是路径参数,`q` 不是路径参数,而是查询参数。 + +/// + +/// note | 笔记 + +因为默认值为 `= None`,FastAPI 把 `q` 识别为可选参数。 -在这个例子中,函数参数 `q` 将是可选的,并且默认值为 `None`。 +FastAPI 不使用 `Optional[str]` 中的 `Optional`(只使用 `str`),但 `Optional[str]` 可以帮助编辑器发现代码中的错误。 -!!! check - 还要注意的是,**FastAPI** 足够聪明,能够分辨出参数 `item_id` 是路径参数而 `q` 不是,因此 `q` 是一个查询参数。 +/// ## 查询参数类型转换 -你还可以声明 `bool` 类型,它们将被自动转换: +参数还可以声明为 `bool` 类型,FastAPI 会自动转换参数类型: -```Python hl_lines="7" -{!../../../docs_src/query_params/tutorial003.py!} -``` -这个例子中,如果你访问: +{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *} + +本例中,访问: ``` http://127.0.0.1:8000/items/foo?short=1 @@ -110,42 +116,38 @@ http://127.0.0.1:8000/items/foo?short=on http://127.0.0.1:8000/items/foo?short=yes ``` -或任何其他的变体形式(大写,首字母大写等等),你的函数接收的 `short` 参数都会是布尔值 `True`。对于值为 `False` 的情况也是一样的。 +或其它任意大小写形式(大写、首字母大写等),函数接收的 `short` 参数都是布尔值 `True`。值为 `False` 时也一样。 ## 多个路径和查询参数 -你可以同时声明多个路径参数和查询参数,**FastAPI** 能够识别它们。 +**FastAPI** 可以识别同时声明的多个路径参数和查询参数。 -而且你不需要以任何特定的顺序来声明。 +而且声明查询参数的顺序并不重要。 -它们将通过名称被检测到: +FastAPI 通过参数名进行检测: -```Python hl_lines="6 8" -{!../../../docs_src/query_params/tutorial004.py!} -``` +{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *} -## 必需查询参数 +## 必选查询参数 -当你为非路径参数声明了默认值时(目前而言,我们所知道的仅有查询参数),则该参数不是必需的。 +为不是路径参数的参数声明默认值(至此,仅有查询参数),该参数就**不是必选**的了。 -如果你不想添加一个特定的值,而只是想使该参数成为可选的,则将默认值设置为 `None`。 +如果只想把参数设为**可选**,但又不想指定参数的值,则要把默认值设为 `None`。 -但当你想让一个查询参数成为必需的,不声明任何默认值就可以: +如果要把查询参数设置为**必选**,就不要声明默认值: -```Python hl_lines="6-7" -{!../../../docs_src/query_params/tutorial005.py!} -``` +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} -这里的查询参数 `needy` 是类型为 `str` 的必需查询参数。 +这里的查询参数 `needy` 是类型为 `str` 的必选查询参数。 -如果你在浏览器中打开一个像下面的 URL: +在浏览器中打开如下 URL: ``` http://127.0.0.1:8000/items/foo-item ``` -...因为没有添加必需的参数 `needy`,你将看到类似以下的错误: +……因为路径中没有必选参数 `needy`,返回的响应中会显示如下错误信息: ```JSON { @@ -162,13 +164,13 @@ http://127.0.0.1:8000/items/foo-item } ``` -由于 `needy` 是必需参数,因此你需要在 URL 中设置它的值: +`needy` 是必选参数,因此要在 URL 中设置值: ``` http://127.0.0.1:8000/items/foo-item?needy=sooooneedy ``` -...这样就正常了: +……这样就正常了: ```JSON { @@ -177,17 +179,18 @@ http://127.0.0.1:8000/items/foo-item?needy=sooooneedy } ``` -当然,你也可以定义一些参数为必需的,一些具有默认值,而某些则完全是可选的: +当然,把一些参数定义为必选,为另一些参数设置默认值,再把其它参数定义为可选,这些操作都是可以的: -```Python hl_lines="7" -{!../../../docs_src/query_params/tutorial006.py!} -``` +{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *} + +本例中有 3 个查询参数: + +* `needy`,必选的 `str` 类型参数 +* `skip`,默认值为 `0` 的 `int` 类型参数 +* `limit`,可选的 `int` 类型参数 -在这个例子中,有3个查询参数: +/// tip | 提示 -* `needy`,一个必需的 `str` 类型参数。 -* `skip`,一个默认值为 `0` 的 `int` 类型参数。 -* `limit`,一个可选的 `int` 类型参数。 +还可以像在[路径参数](path-params.md#_8){.internal-link target=_blank} 中那样使用 `Enum`。 -!!! tip - 你还可以像在 [路径参数](path-params.md#predefined-values){.internal-link target=_blank} 中那样使用 `Enum`。 +/// diff --git a/docs/zh/docs/tutorial/request-files.md b/docs/zh/docs/tutorial/request-files.md index 2c48f33ca..81ddc7238 100644 --- a/docs/zh/docs/tutorial/request-files.md +++ b/docs/zh/docs/tutorial/request-files.md @@ -2,39 +2,41 @@ `File` 用于定义客户端的上传文件。 -!!! info "说明" +/// info | 说明 - 因为上传文件以「表单数据」形式发送。 +因为上传文件以「表单数据」形式发送。 - 所以接收上传文件,要预先安装 `python-multipart`。 +所以接收上传文件,要预先安装 `python-multipart`。 - 例如: `pip install python-multipart`。 +例如: `pip install python-multipart`。 + +/// ## 导入 `File` 从 `fastapi` 导入 `File` 和 `UploadFile`: -```Python hl_lines="1" -{!../../../docs_src/request_files/tutorial001.py!} -``` +{* ../../docs_src/request_files/tutorial001.py hl[1] *} ## 定义 `File` 参数 创建文件(`File`)参数的方式与 `Body` 和 `Form` 一样: -```Python hl_lines="7" -{!../../../docs_src/request_files/tutorial001.py!} -``` +{* ../../docs_src/request_files/tutorial001.py hl[7] *} -!!! info "说明" +/// info | 说明 - `File` 是直接继承自 `Form` 的类。 +`File` 是直接继承自 `Form` 的类。 - 注意,从 `fastapi` 导入的 `Query`、`Path`、`File` 等项,实际上是返回特定类的函数。 +注意,从 `fastapi` 导入的 `Query`、`Path`、`File` 等项,实际上是返回特定类的函数。 -!!! tip "提示" +/// - 声明文件体必须使用 `File`,否则,FastAPI 会把该参数当作查询参数或请求体(JSON)参数。 +/// tip | 提示 + +声明文件体必须使用 `File`,否则,FastAPI 会把该参数当作查询参数或请求体(JSON)参数。 + +/// 文件作为「表单数据」上传。 @@ -48,9 +50,7 @@ 定义文件参数时使用 `UploadFile`: -```Python hl_lines="12" -{!../../../docs_src/request_files/tutorial001.py!} -``` +{* ../../docs_src/request_files/tutorial001.py hl[12] *} `UploadFile` 与 `bytes` 相比有更多优势: @@ -92,13 +92,17 @@ contents = await myfile.read() contents = myfile.file.read() ``` -!!! note "`async` 技术细节" +/// note | `async` 技术细节 - 使用 `async` 方法时,**FastAPI** 在线程池中执行文件方法,并 `await` 操作完成。 +使用 `async` 方法时,**FastAPI** 在线程池中执行文件方法,并 `await` 操作完成。 -!!! note "Starlette 技术细节" +/// - **FastAPI** 的 `UploadFile` 直接继承自 **Starlette** 的 `UploadFile`,但添加了一些必要功能,使之与 **Pydantic** 及 FastAPI 的其它部件兼容。 +/// note | Starlette 技术细节 + +**FastAPI** 的 `UploadFile` 直接继承自 **Starlette** 的 `UploadFile`,但添加了一些必要功能,使之与 **Pydantic** 及 FastAPI 的其它部件兼容。 + +/// ## 什么是 「表单数据」 @@ -106,43 +110,35 @@ contents = myfile.file.read() **FastAPI** 要确保从正确的位置读取数据,而不是读取 JSON。 -!!! note "技术细节" +/// note | 技术细节 - 不包含文件时,表单数据一般用 `application/x-www-form-urlencoded`「媒体类型」编码。 +不包含文件时,表单数据一般用 `application/x-www-form-urlencoded`「媒体类型」编码。 - 但表单包含文件时,编码为 `multipart/form-data`。使用了 `File`,**FastAPI** 就知道要从请求体的正确位置获取文件。 +但表单包含文件时,编码为 `multipart/form-data`。使用了 `File`,**FastAPI** 就知道要从请求体的正确位置获取文件。 - 编码和表单字段详见 MDN Web 文档的 POST 小节。 +编码和表单字段详见 MDN Web 文档的 POST 小节。 -!!! warning "警告" +/// - 可在一个*路径操作*中声明多个 `File` 和 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `multipart/form-data`,不是 `application/json`。 +/// warning | 警告 - 这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。 +可在一个*路径操作*中声明多个 `File` 和 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `multipart/form-data`,不是 `application/json`。 -## 可选文件上传 - -您可以通过使用标准类型注解并将 None 作为默认值的方式将一个文件参数设为可选: +这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。 -=== "Python 3.9+" +/// - ```Python hl_lines="7 14" - {!> ../../../docs_src/request_files/tutorial001_02_py310.py!} - ``` +## 可选文件上传 -=== "Python 3.8+" +您可以通过使用标准类型注解并将 None 作为默认值的方式将一个文件参数设为可选: - ```Python hl_lines="9 17" - {!> ../../../docs_src/request_files/tutorial001_02.py!} - ``` +{* ../../docs_src/request_files/tutorial001_02_py310.py hl[7,14] *} ## 带有额外元数据的 `UploadFile` 您也可以将 `File()` 与 `UploadFile` 一起使用,例如,设置额外的元数据: -```Python hl_lines="13" -{!../../../docs_src/request_files/tutorial001_03.py!} -``` +{* ../../docs_src/request_files/tutorial001_03.py hl[13] *} ## 多文件上传 @@ -152,42 +148,24 @@ FastAPI 支持同时上传多个文件。 上传多个文件时,要声明含 `bytes` 或 `UploadFile` 的列表(`List`): -=== "Python 3.9+" - - ```Python hl_lines="8 13" - {!> ../../../docs_src/request_files/tutorial002_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="10 15" - {!> ../../../docs_src/request_files/tutorial002.py!} - ``` +{* ../../docs_src/request_files/tutorial002_py39.py hl[8,13] *} 接收的也是含 `bytes` 或 `UploadFile` 的列表(`list`)。 -!!! note "技术细节" +/// note | 技术细节 + +也可以使用 `from starlette.responses import HTMLResponse`。 - 也可以使用 `from starlette.responses import HTMLResponse`。 +`fastapi.responses` 其实与 `starlette.responses` 相同,只是为了方便开发者调用。实际上,大多数 **FastAPI** 的响应都直接从 Starlette 调用。 - `fastapi.responses` 其实与 `starlette.responses` 相同,只是为了方便开发者调用。实际上,大多数 **FastAPI** 的响应都直接从 Starlette 调用。 +/// ### 带有额外元数据的多文件上传 和之前的方式一样, 您可以为 `File()` 设置额外参数, 即使是 `UploadFile`: -=== "Python 3.9+" - - ```Python hl_lines="16" - {!> ../../../docs_src/request_files/tutorial003_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="18" - {!> ../../../docs_src/request_files/tutorial003.py!} - ``` +{* ../../docs_src/request_files/tutorial003_py39.py hl[16] *} ## 小结 diff --git a/docs/zh/docs/tutorial/request-form-models.md b/docs/zh/docs/tutorial/request-form-models.md new file mode 100644 index 000000000..e639e4b9f --- /dev/null +++ b/docs/zh/docs/tutorial/request-form-models.md @@ -0,0 +1,78 @@ +# 表单模型 + +您可以使用 **Pydantic 模型**在 FastAPI 中声明**表单字段**。 + +/// info + +要使用表单,需预先安装 `python-multipart` 。 + +确保您创建、激活一个[虚拟环境](../virtual-environments.md){.internal-link target=_blank}后再安装。 + +```console +$ pip install python-multipart +``` + +/// + +/// note + +自 FastAPI 版本 `0.113.0` 起支持此功能。🤓 + +/// + +## 表单的 Pydantic 模型 + +您只需声明一个 **Pydantic 模型**,其中包含您希望接收的**表单字段**,然后将参数声明为 `Form` : + +{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *} + +**FastAPI** 将从请求中的**表单数据**中**提取**出**每个字段**的数据,并提供您定义的 Pydantic 模型。 + +## 检查文档 + +您可以在文档 UI 中验证它,地址为 `/docs` : + +
+ +
+ +## 禁止额外的表单字段 + +在某些特殊使用情况下(可能并不常见),您可能希望将表单字段**限制**为仅在 Pydantic 模型中声明过的字段,并**禁止**任何**额外**的字段。 + +/// note + +自 FastAPI 版本 `0.114.0` 起支持此功能。🤓 + +/// + +您可以使用 Pydantic 的模型配置来禁止( `forbid` )任何额外( `extra` )字段: + +{* ../../docs_src/request_form_models/tutorial002_an_py39.py hl[12] *} + +如果客户端尝试发送一些额外的数据,他们将收到**错误**响应。 + +例如,如果客户端尝试发送这样的表单字段: + +* `username`: `Rick` +* `password`: `Portal Gun` +* `extra`: `Mr. Poopybutthole` + +他们将收到一条错误响应,表明字段 `extra` 是不被允许的: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["body", "extra"], + "msg": "Extra inputs are not permitted", + "input": "Mr. Poopybutthole" + } + ] +} +``` + +## 总结 + +您可以使用 Pydantic 模型在 FastAPI 中声明表单字段。😎 diff --git a/docs/zh/docs/tutorial/request-forms-and-files.md b/docs/zh/docs/tutorial/request-forms-and-files.md index 70cd70f98..f72e5047a 100644 --- a/docs/zh/docs/tutorial/request-forms-and-files.md +++ b/docs/zh/docs/tutorial/request-forms-and-files.md @@ -2,35 +2,35 @@ FastAPI 支持同时使用 `File` 和 `Form` 定义文件和表单字段。 -!!! info "说明" +/// info | 说明 - 接收上传文件或表单数据,要预先安装 `python-multipart`。 +接收上传文件或表单数据,要预先安装 `python-multipart`。 - 例如,`pip install python-multipart`。 +例如,`pip install python-multipart`。 + +/// ## 导入 `File` 与 `Form` -```Python hl_lines="1" -{!../../../docs_src/request_forms_and_files/tutorial001.py!} -``` +{* ../../docs_src/request_forms_and_files/tutorial001.py hl[1] *} ## 定义 `File` 与 `Form` 参数 创建文件和表单参数的方式与 `Body` 和 `Query` 一样: -```Python hl_lines="8" -{!../../../docs_src/request_forms_and_files/tutorial001.py!} -``` +{* ../../docs_src/request_forms_and_files/tutorial001.py hl[8] *} 文件和表单字段作为表单数据上传与接收。 声明文件可以使用 `bytes` 或 `UploadFile` 。 -!!! warning "警告" +/// warning | 警告 + +可在一个*路径操作*中声明多个 `File` 与 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码为 `multipart/form-data`,不是 `application/json`。 - 可在一个*路径操作*中声明多个 `File` 与 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码为 `multipart/form-data`,不是 `application/json`。 +这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。 - 这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。 +/// ## 小结 diff --git a/docs/zh/docs/tutorial/request-forms.md b/docs/zh/docs/tutorial/request-forms.md index 6436ffbcd..ee03e82a7 100644 --- a/docs/zh/docs/tutorial/request-forms.md +++ b/docs/zh/docs/tutorial/request-forms.md @@ -2,27 +2,25 @@ 接收的不是 JSON,而是表单字段时,要使用 `Form`。 -!!! info "说明" +/// info | 说明 - 要使用表单,需预先安装 `python-multipart`。 +要使用表单,需预先安装 `python-multipart`。 - 例如,`pip install python-multipart`。 +例如,`pip install python-multipart`。 + +/// ## 导入 `Form` 从 `fastapi` 导入 `Form`: -```Python hl_lines="1" -{!../../../docs_src/request_forms/tutorial001.py!} -``` +{* ../../docs_src/request_forms/tutorial001.py hl[1] *} ## 定义 `Form` 参数 创建表单(`Form`)参数的方式与 `Body` 和 `Query` 一样: -```Python hl_lines="7" -{!../../../docs_src/request_forms/tutorial001.py!} -``` +{* ../../docs_src/request_forms/tutorial001.py hl[7] *} 例如,OAuth2 规范的 "密码流" 模式规定要通过表单字段发送 `username` 和 `password`。 @@ -30,13 +28,17 @@ 使用 `Form` 可以声明与 `Body` (及 `Query`、`Path`、`Cookie`)相同的元数据和验证。 -!!! info "说明" +/// info | 说明 + +`Form` 是直接继承自 `Body` 的类。 + +/// - `Form` 是直接继承自 `Body` 的类。 +/// tip | 提示 -!!! tip "提示" +声明表单体要显式使用 `Form` ,否则,FastAPI 会把该参数当作查询参数或请求体(JSON)参数。 - 声明表单体要显式使用 `Form` ,否则,FastAPI 会把该参数当作查询参数或请求体(JSON)参数。 +/// ## 关于 "表单字段" @@ -44,19 +46,23 @@ **FastAPI** 要确保从正确的位置读取数据,而不是读取 JSON。 -!!! note "技术细节" +/// note | 技术细节 + +表单数据的「媒体类型」编码一般为 `application/x-www-form-urlencoded`。 + +但包含文件的表单编码为 `multipart/form-data`。文件处理详见下节。 - 表单数据的「媒体类型」编码一般为 `application/x-www-form-urlencoded`。 +编码和表单字段详见 MDN Web 文档的 POST小节。 - 但包含文件的表单编码为 `multipart/form-data`。文件处理详见下节。 +/// - 编码和表单字段详见 MDN Web 文档的 POST小节。 +/// warning | 警告 -!!! warning "警告" +可在一个*路径操作*中声明多个 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `application/x-www-form-urlencoded`,不是 `application/json`。 - 可在一个*路径操作*中声明多个 `Form` 参数,但不能同时声明要接收 JSON 的 `Body` 字段。因为此时请求体的编码是 `application/x-www-form-urlencoded`,不是 `application/json`。 +这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。 - 这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。 +/// ## 小结 diff --git a/docs/zh/docs/tutorial/response-model.md b/docs/zh/docs/tutorial/response-model.md index e731b6989..049cd1223 100644 --- a/docs/zh/docs/tutorial/response-model.md +++ b/docs/zh/docs/tutorial/response-model.md @@ -8,26 +8,13 @@ * `@app.delete()` * 等等。 -=== "Python 3.10+" +{* ../../docs_src/response_model/tutorial001_py310.py hl[17,22,24:27] *} - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001_py310.py!} - ``` +/// note -=== "Python 3.9+" +注意,`response_model`是「装饰器」方法(`get`,`post` 等)的一个参数。不像之前的所有参数和请求体,它不属于*路径操作函数*。 - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="17 22 24-27" - {!> ../../../docs_src/response_model/tutorial001.py!} - ``` - -!!! note - 注意,`response_model`是「装饰器」方法(`get`,`post` 等)的一个参数。不像之前的所有参数和请求体,它不属于*路径操作函数*。 +/// 它接收的类型与你将为 Pydantic 模型属性所声明的类型相同,因此它可以是一个 Pydantic 模型,但也可以是一个由 Pydantic 模型组成的 `list`,例如 `List[Item]`。 @@ -42,22 +29,21 @@ FastAPI 将使用此 `response_model` 来: * 会将输出数据限制在该模型定义内。下面我们会看到这一点有多重要。 -!!! note "技术细节" - 响应模型在参数中被声明,而不是作为函数返回类型的注解,这是因为路径函数可能不会真正返回该响应模型,而是返回一个 `dict`、数据库对象或其他模型,然后再使用 `response_model` 来执行字段约束和序列化。 +/// note | 技术细节 + +响应模型在参数中被声明,而不是作为函数返回类型的注解,这是因为路径函数可能不会真正返回该响应模型,而是返回一个 `dict`、数据库对象或其他模型,然后再使用 `response_model` 来执行字段约束和序列化。 + +/// ## 返回与输入相同的数据 现在我们声明一个 `UserIn` 模型,它将包含一个明文密码属性。 -```Python hl_lines="9 11" -{!../../../docs_src/response_model/tutorial002.py!} -``` +{* ../../docs_src/response_model/tutorial002.py hl[9,11] *} 我们正在使用此模型声明输入数据,并使用同一模型声明输出数据: -```Python hl_lines="17-18" -{!../../../docs_src/response_model/tutorial002.py!} -``` +{* ../../docs_src/response_model/tutorial002.py hl[17:18] *} 现在,每当浏览器使用一个密码创建用户时,API 都会在响应中返回相同的密码。 @@ -65,52 +51,25 @@ FastAPI 将使用此 `response_model` 来: 但是,如果我们在其他的*路径操作*中使用相同的模型,则可能会将用户的密码发送给每个客户端。 -!!! danger - 永远不要存储用户的明文密码,也不要在响应中发送密码。 - -## 添加输出模型 +/// danger -相反,我们可以创建一个有明文密码的输入模型和一个没有明文密码的输出模型: +永远不要存储用户的明文密码,也不要在响应中发送密码。 -=== "Python 3.10+" +/// - ```Python hl_lines="9 11 16" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` +## 添加输出模型 -=== "Python 3.8+" +相反,我们可以创建一个有明文密码的输入模型和一个没有明文密码的输出模型: - ```Python hl_lines="9 11 16" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +{* ../../docs_src/response_model/tutorial003_py310.py hl[9,11,16] *} 这样,即便我们的*路径操作函数*将会返回包含密码的相同输入用户: -=== "Python 3.10+" - - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="24" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +{* ../../docs_src/response_model/tutorial003_py310.py hl[24] *} ...我们已经将 `response_model` 声明为了不包含密码的 `UserOut` 模型: -=== "Python 3.10+" - - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial003_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="22" - {!> ../../../docs_src/response_model/tutorial003.py!} - ``` +{* ../../docs_src/response_model/tutorial003_py310.py hl[22] *} 因此,**FastAPI** 将会负责过滤掉未在输出模型中声明的所有数据(使用 Pydantic)。 @@ -128,9 +87,7 @@ FastAPI 将使用此 `response_model` 来: 你的响应模型可以具有默认值,例如: -```Python hl_lines="11 13-14" -{!../../../docs_src/response_model/tutorial004.py!} -``` +{* ../../docs_src/response_model/tutorial004.py hl[11,13:14] *} * `description: Union[str, None] = None` 具有默认值 `None`。 * `tax: float = 10.5` 具有默认值 `10.5`. @@ -144,9 +101,7 @@ FastAPI 将使用此 `response_model` 来: 你可以设置*路径操作装饰器*的 `response_model_exclude_unset=True` 参数: -```Python hl_lines="24" -{!../../../docs_src/response_model/tutorial004.py!} -``` +{* ../../docs_src/response_model/tutorial004.py hl[24] *} 然后响应中将不会包含那些默认值,而是仅有实际设置的值。 @@ -159,16 +114,22 @@ FastAPI 将使用此 `response_model` 来: } ``` -!!! info - FastAPI 通过 Pydantic 模型的 `.dict()` 配合 该方法的 `exclude_unset` 参数 来实现此功能。 +/// info + +FastAPI 通过 Pydantic 模型的 `.dict()` 配合 该方法的 `exclude_unset` 参数 来实现此功能。 + +/// + +/// info + +你还可以使用: -!!! info - 你还可以使用: +* `response_model_exclude_defaults=True` +* `response_model_exclude_none=True` - * `response_model_exclude_defaults=True` - * `response_model_exclude_none=True` +参考 Pydantic 文档 中对 `exclude_defaults` 和 `exclude_none` 的描述。 - 参考 Pydantic 文档 中对 `exclude_defaults` 和 `exclude_none` 的描述。 +/// #### 默认值字段有实际值的数据 @@ -203,10 +164,13 @@ FastAPI 将使用此 `response_model` 来: 因此,它们将包含在 JSON 响应中。 -!!! tip - 请注意默认值可以是任何值,而不仅是`None`。 +/// tip - 它们可以是一个列表(`[]`),一个值为 `10.5`的 `float`,等等。 +请注意默认值可以是任何值,而不仅是`None`。 + +它们可以是一个列表(`[]`),一个值为 `10.5`的 `float`,等等。 + +/// ### `response_model_include` 和 `response_model_exclude` @@ -216,29 +180,31 @@ FastAPI 将使用此 `response_model` 来: 如果你只有一个 Pydantic 模型,并且想要从输出中移除一些数据,则可以使用这种快捷方法。 -!!! tip - 但是依然建议你使用上面提到的主意,使用多个类而不是这些参数。 +/// tip - 这是因为即使使用 `response_model_include` 或 `response_model_exclude` 来省略某些属性,在应用程序的 OpenAPI 定义(和文档)中生成的 JSON Schema 仍将是完整的模型。 +但是依然建议你使用上面提到的主意,使用多个类而不是这些参数。 - 这也适用于作用类似的 `response_model_by_alias`。 +这是因为即使使用 `response_model_include` 或 `response_model_exclude` 来省略某些属性,在应用程序的 OpenAPI 定义(和文档)中生成的 JSON Schema 仍将是完整的模型。 -```Python hl_lines="31 37" -{!../../../docs_src/response_model/tutorial005.py!} -``` +这也适用于作用类似的 `response_model_by_alias`。 + +/// -!!! tip - `{"name", "description"}` 语法创建一个具有这两个值的 `set`。 +{* ../../docs_src/response_model/tutorial005.py hl[31,37] *} - 等同于 `set(["name", "description"])`。 +/// tip + +`{"name", "description"}` 语法创建一个具有这两个值的 `set`。 + +等同于 `set(["name", "description"])`。 + +/// #### 使用 `list` 而不是 `set` 如果你忘记使用 `set` 而是使用 `list` 或 `tuple`,FastAPI 仍会将其转换为 `set` 并且正常工作: -```Python hl_lines="31 37" -{!../../../docs_src/response_model/tutorial006.py!} -``` +{* ../../docs_src/response_model/tutorial006.py hl[31,37] *} ## 总结 diff --git a/docs/zh/docs/tutorial/response-status-code.md b/docs/zh/docs/tutorial/response-status-code.md index 357831942..aa8032ada 100644 --- a/docs/zh/docs/tutorial/response-status-code.md +++ b/docs/zh/docs/tutorial/response-status-code.md @@ -1,89 +1,101 @@ # 响应状态码 -与指定响应模型的方式相同,你也可以在以下任意的*路径操作*中使用 `status_code` 参数来声明用于响应的 HTTP 状态码: +与指定响应模型的方式相同,在以下任意*路径操作*中,可以使用 `status_code` 参数声明用于响应的 HTTP 状态码: * `@app.get()` * `@app.post()` * `@app.put()` * `@app.delete()` -* 等等。 +* 等…… -```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} -``` +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} -!!! note - 注意,`status_code` 是「装饰器」方法(`get`,`post` 等)的一个参数。不像之前的所有参数和请求体,它不属于*路径操作函数*。 +/// note | 笔记 -`status_code` 参数接收一个表示 HTTP 状态码的数字。 +注意,`status_code` 是(`get`、`post` 等)**装饰器**方法中的参数。与之前的参数和请求体不同,不是*路径操作函数*的参数。 -!!! info - `status_code` 也能够接收一个 `IntEnum` 类型,比如 Python 的 `http.HTTPStatus`。 +/// -它将会: +`status_code` 参数接收表示 HTTP 状态码的数字。 -* 在响应中返回该状态码。 -* 在 OpenAPI 模式中(以及在用户界面中)将其记录为: +/// info | 说明 - +`status_code` 还能接收 `IntEnum` 类型,比如 Python 的 `http.HTTPStatus`。 -!!! note - 一些响应状态码(请参阅下一部分)表示响应没有响应体。 +/// - FastAPI 知道这一点,并将生成表明没有响应体的 OpenAPI 文档。 +它可以: + +* 在响应中返回状态码 +* 在 OpenAPI 概图(及用户界面)中存档: + + + +/// note | 笔记 + +某些响应状态码表示响应没有响应体(参阅下一章)。 + +FastAPI 可以进行识别,并生成表明无响应体的 OpenAPI 文档。 + +/// ## 关于 HTTP 状态码 -!!! note - 如果你已经了解什么是 HTTP 状态码,请跳到下一部分。 +/// note | 笔记 + +如果已经了解 HTTP 状态码,请跳到下一章。 + +/// + +在 HTTP 协议中,发送 3 位数的数字状态码是响应的一部分。 + +这些状态码都具有便于识别的关联名称,但是重要的还是数字。 + +简言之: + +* `100` 及以上的状态码用于返回**信息**。这类状态码很少直接使用。具有这些状态码的响应不能包含响应体 +* **`200`** 及以上的状态码用于表示**成功**。这些状态码是最常用的 + * `200` 是默认状态代码,表示一切**正常** + * `201` 表示**已创建**,通常在数据库中创建新记录后使用 + * `204` 是一种特殊的例子,表示**无内容**。该响应在没有为客户端返回内容时使用,因此,该响应不能包含响应体 +* **`300`** 及以上的状态码用于**重定向**。具有这些状态码的响应不一定包含响应体,但 `304`**未修改**是个例外,该响应不得包含响应体 +* **`400`** 及以上的状态码用于表示**客户端错误**。这些可能是第二常用的类型 + * `404`,用于**未找到**响应 + * 对于来自客户端的一般错误,可以只使用 `400` +* `500` 及以上的状态码用于表示服务器端错误。几乎永远不会直接使用这些状态码。应用代码或服务器出现问题时,会自动返回这些状态代码 -在 HTTP 协议中,你将发送 3 位数的数字状态码作为响应的一部分。 +/// tip | 提示 -这些状态码有一个识别它们的关联名称,但是重要的还是数字。 +状态码及适用场景的详情,请参阅 MDN 的 HTTP 状态码文档。 -简而言之: +/// -* `100` 及以上状态码用于「消息」响应。你很少直接使用它们。具有这些状态代码的响应不能带有响应体。 -* **`200`** 及以上状态码用于「成功」响应。这些是你最常使用的。 - * `200` 是默认状态代码,它表示一切「正常」。 - * 另一个例子会是 `201`,「已创建」。它通常在数据库中创建了一条新记录后使用。 - * 一个特殊的例子是 `204`,「无内容」。此响应在没有内容返回给客户端时使用,因此该响应不能包含响应体。 -* **`300`** 及以上状态码用于「重定向」。具有这些状态码的响应可能有或者可能没有响应体,但 `304`「未修改」是个例外,该响应不得含有响应体。 -* **`400`** 及以上状态码用于「客户端错误」响应。这些可能是你第二常使用的类型。 - * 一个例子是 `404`,用于「未找到」响应。 - * 对于来自客户端的一般错误,你可以只使用 `400`。 -* `500` 及以上状态码用于服务器端错误。你几乎永远不会直接使用它们。当你的应用程序代码或服务器中的某些部分出现问题时,它将自动返回这些状态代码之一。 +## 状态码名称快捷方式 -!!! tip - 要了解有关每个状态代码以及适用场景的更多信息,请查看 MDN 关于 HTTP 状态码的文档。 +再看下之前的例子: -## 记住名称的捷径 +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} -让我们再次看看之前的例子: +`201` 表示**已创建**的状态码。 -```Python hl_lines="6" -{!../../../docs_src/response_status_code/tutorial001.py!} -``` +但我们没有必要记住所有代码的含义。 -`201` 是表示「已创建」的状态码。 +可以使用 `fastapi.status` 中的快捷变量。 -但是你不必去记住每个代码的含义。 +{* ../../docs_src/response_status_code/tutorial002.py hl[1,6] *} -你可以使用来自 `fastapi.status` 的便捷变量。 +这只是一种快捷方式,具有相同的数字代码,但它可以使用编辑器的自动补全功能: -```Python hl_lines="1 6" -{!../../../docs_src/response_status_code/tutorial002.py!} -``` + -它们只是一种便捷方式,它们具有同样的数字代码,但是这样使用你就可以使用编辑器的自动补全功能来查找它们: +/// note | 技术细节 - +也可以使用 `from starlette import status`。 -!!! note "技术细节" - 你也可以使用 `from starlette import status`。 +为了让开发者更方便,**FastAPI** 提供了与 `starlette.status` 完全相同的 `fastapi.status`。但它直接来自于 Starlette。 - 为了给你(即开发者)提供方便,**FastAPI** 提供了与 `starlette.status` 完全相同的 `fastapi.status`。但它直接来自于 Starlette。 +/// ## 更改默认状态码 -稍后,在[高级用户指南](../advanced/response-change-status-code.md){.internal-link target=_blank}中你将了解如何返回与在此声明的默认状态码不同的状态码。 +[高级用户指南](../advanced/response-change-status-code.md){.internal-link target=_blank}中,将介绍如何返回与在此声明的默认状态码不同的状态码。 diff --git a/docs/zh/docs/tutorial/schema-extra-example.md b/docs/zh/docs/tutorial/schema-extra-example.md index ebc04da8b..6c132eed3 100644 --- a/docs/zh/docs/tutorial/schema-extra-example.md +++ b/docs/zh/docs/tutorial/schema-extra-example.md @@ -8,19 +8,9 @@ ## Pydantic `schema_extra` -您可以使用 `Config` 和 `schema_extra` 为Pydantic模型声明一个示例,如Pydantic 文档:定制 Schema 中所述: +您可以使用 `Config` 和 `schema_extra` 为Pydantic模型声明一个示例,如Pydantic 文档:定制 Schema 中所述: -=== "Python 3.10+" - - ```Python hl_lines="13-21" - {!> ../../../docs_src/schema_extra_example/tutorial001_py310.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="15-23" - {!> ../../../docs_src/schema_extra_example/tutorial001.py!} - ``` +{* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:21] *} 这些额外的信息将按原样添加到输出的JSON模式中。 @@ -28,20 +18,13 @@ 在 `Field`, `Path`, `Query`, `Body` 和其他你之后将会看到的工厂函数,你可以为JSON 模式声明额外信息,你也可以通过给工厂函数传递其他的任意参数来给JSON 模式声明额外信息,比如增加 `example`: -=== "Python 3.10+" - - ```Python hl_lines="2 8-11" - {!> ../../../docs_src/schema_extra_example/tutorial002_py310.py!} - ``` +{* ../../docs_src/schema_extra_example/tutorial002_py310.py hl[2,8:11] *} -=== "Python 3.8+" +/// warning - ```Python hl_lines="4 10-13" - {!> ../../../docs_src/schema_extra_example/tutorial002.py!} - ``` +请记住,传递的那些额外参数不会添加任何验证,只会添加注释,用于文档的目的。 -!!! warning - 请记住,传递的那些额外参数不会添加任何验证,只会添加注释,用于文档的目的。 +/// ## `Body` 额外参数 @@ -49,41 +32,7 @@ 比如,你可以将请求体的一个 `example` 传递给 `Body`: -=== "Python 3.10+" - - ```Python hl_lines="22-27" - {!> ../../../docs_src/schema_extra_example/tutorial003_an_py310.py!} - ``` - -=== "Python 3.9+" - - ```Python hl_lines="22-27" - {!> ../../../docs_src/schema_extra_example/tutorial003_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="23-28" - {!> ../../../docs_src/schema_extra_example/tutorial003_an.py!} - ``` - -=== "Python 3.10+ non-Annotated" - - !!! tip - 尽可能选择使用 `Annotated` 的版本。 - - ```Python hl_lines="18-23" - {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - 尽可能选择使用 `Annotated` 的版本。 - - ```Python hl_lines="20-25" - {!> ../../../docs_src/schema_extra_example/tutorial003.py!} - ``` +{* ../../docs_src/schema_extra_example/tutorial003_an_py310.py hl[22:27] *} ## 文档 UI 中的例子 diff --git a/docs/zh/docs/tutorial/security/first-steps.md b/docs/zh/docs/tutorial/security/first-steps.md index dda956417..225eb2695 100644 --- a/docs/zh/docs/tutorial/security/first-steps.md +++ b/docs/zh/docs/tutorial/security/first-steps.md @@ -20,36 +20,19 @@ 把下面的示例代码复制到 `main.py`: -=== "Python 3.9+" - - ```Python - {!> ../../../docs_src/security/tutorial001_an_py39.py!} - ``` - -=== "Python 3.8+" - - ```Python - {!> ../../../docs_src/security/tutorial001_an.py!} - ``` - -=== "Python 3.8+ non-Annotated" - - !!! tip - 尽可能选择使用 `Annotated` 的版本。 - - ```Python - {!> ../../../docs_src/security/tutorial001.py!} - ``` +{* ../../docs_src/security/tutorial001_an_py39.py *} ## 运行 -!!! info "说明" +/// info | 说明 - 先安装 `python-multipart`。 +先安装 `python-multipart`。 - 安装命令: `pip install python-multipart`。 +安装命令: `pip install python-multipart`。 - 这是因为 **OAuth2** 使用**表单数据**发送 `username` 与 `password`。 +这是因为 **OAuth2** 使用**表单数据**发送 `username` 与 `password`。 + +/// 用下面的命令运行该示例: @@ -71,19 +54,23 @@ $ uvicorn main:app --reload -!!! check "Authorize 按钮!" +/// check | Authorize 按钮! + +页面右上角出现了一个「**Authorize**」按钮。 - 页面右上角出现了一个「**Authorize**」按钮。 +*路径操作*的右上角也出现了一个可以点击的小锁图标。 - *路径操作*的右上角也出现了一个可以点击的小锁图标。 +/// 点击 **Authorize** 按钮,弹出授权表单,输入 `username` 与 `password` 及其它可选字段: -!!! note "笔记" +/// note | 笔记 - 目前,在表单中输入内容不会有任何反应,后文会介绍相关内容。 +目前,在表单中输入内容不会有任何反应,后文会介绍相关内容。 + +/// 虽然此文档不是给前端最终用户使用的,但这个自动工具非常实用,可在文档中与所有 API 交互。 @@ -125,39 +112,43 @@ OAuth2 的设计目标是为了让后端或 API 独立于服务器验证用户 本例使用 **OAuth2** 的 **Password** 流以及 **Bearer** 令牌(`Token`)。为此要使用 `OAuth2PasswordBearer` 类。 -!!! info "说明" +/// info | 说明 + +`Bearer` 令牌不是唯一的选择。 - `Bearer` 令牌不是唯一的选择。 +但它是最适合这个用例的方案。 - 但它是最适合这个用例的方案。 +甚至可以说,它是适用于绝大多数用例的最佳方案,除非您是 OAuth2 的专家,知道为什么其它方案更合适。 - 甚至可以说,它是适用于绝大多数用例的最佳方案,除非您是 OAuth2 的专家,知道为什么其它方案更合适。 +本例中,**FastAPI** 还提供了构建工具。 - 本例中,**FastAPI** 还提供了构建工具。 +/// 创建 `OAuth2PasswordBearer` 的类实例时,要传递 `tokenUrl` 参数。该参数包含客户端(用户浏览器中运行的前端) 的 URL,用于发送 `username` 与 `password`,并获取令牌。 -```Python hl_lines="6" -{!../../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[6] *} + +/// tip | 提示 -!!! tip "提示" +在此,`tokenUrl="token"` 指向的是暂未创建的相对 URL `token`。这个相对 URL 相当于 `./token`。 - 在此,`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,如果 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 非常重要,可以确保应用在遇到[使用代理](../../advanced/behind-a-proxy.md){.internal-link target=_blank}这样的高级用例时,也能正常运行。 +/// 该参数不会创建端点或*路径操作*,但会声明客户端用来获取令牌的 URL `/token` 。此信息用于 OpenAPI 及 API 文档。 接下来,学习如何创建实际的路径操作。 -!!! info "说明" +/// info | 说明 - 严苛的 **Pythonista** 可能不喜欢用 `tokenUrl` 这种命名风格代替 `token_url`。 +严苛的 **Pythonista** 可能不喜欢用 `tokenUrl` 这种命名风格代替 `token_url`。 - 这种命名方式是因为要使用与 OpenAPI 规范中相同的名字。以便在深入校验安全方案时,能通过复制粘贴查找更多相关信息。 +这种命名方式是因为要使用与 OpenAPI 规范中相同的名字。以便在深入校验安全方案时,能通过复制粘贴查找更多相关信息。 + +/// `oauth2_scheme` 变量是 `OAuth2PasswordBearer` 的实例,也是**可调用项**。 @@ -173,19 +164,19 @@ oauth2_scheme(some, parameters) 接下来,使用 `Depends` 把 `oauth2_scheme` 传入依赖项。 -```Python hl_lines="10" -{!../../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[10] *} 该依赖项使用字符串(`str`)接收*路径操作函数*的参数 `token` 。 **FastAPI** 使用依赖项在 OpenAPI 概图(及 API 文档)中定义**安全方案**。 -!!! info "技术细节" +/// info | 技术细节 + +**FastAPI** 使用(在依赖项中声明的)类 `OAuth2PasswordBearer` 在 OpenAPI 中定义安全方案,这是因为它继承自 `fastapi.security.oauth2.OAuth2`,而该类又是继承自`fastapi.security.base.SecurityBase`。 - **FastAPI** 使用(在依赖项中声明的)类 `OAuth2PasswordBearer` 在 OpenAPI 中定义安全方案,这是因为它继承自 `fastapi.security.oauth2.OAuth2`,而该类又是继承自`fastapi.security.base.SecurityBase`。 +所有与 OpenAPI(及 API 文档)集成的安全工具都继承自 `SecurityBase`, 这就是为什么 **FastAPI** 能把它们集成至 OpenAPI 的原因。 - 所有与 OpenAPI(及 API 文档)集成的安全工具都继承自 `SecurityBase`, 这就是为什么 **FastAPI** 能把它们集成至 OpenAPI 的原因。 +/// ## 实现的操作 diff --git a/docs/zh/docs/tutorial/security/get-current-user.md b/docs/zh/docs/tutorial/security/get-current-user.md index 477baec3a..1f254a103 100644 --- a/docs/zh/docs/tutorial/security/get-current-user.md +++ b/docs/zh/docs/tutorial/security/get-current-user.md @@ -1,114 +1,107 @@ # 获取当前用户 -在上一章节中,(基于依赖项注入系统的)安全系统向*路径操作函数*提供了一个 `str` 类型的 `token`: +上一章中,(基于依赖注入系统的)安全系统向*路径操作函数*传递了 `str` 类型的 `token`: -```Python hl_lines="10" -{!../../../docs_src/security/tutorial001.py!} -``` +{* ../../docs_src/security/tutorial001.py hl[10] *} -但这还不是很实用。 +但这并不实用。 -让我们来使它返回当前用户给我们。 +接下来,我们学习如何返回当前用户。 -## 创建一个用户模型 +## 创建用户模型 -首先,让我们来创建一个用户 Pydantic 模型。 +首先,创建 Pydantic 用户模型。 -与使用 Pydantic 声明请求体的方式相同,我们可以在其他任何地方使用它: +与使用 Pydantic 声明请求体相同,并且可在任何位置使用: -```Python hl_lines="5 12-16" -{!../../../docs_src/security/tutorial002.py!} -``` +{* ../../docs_src/security/tutorial002.py hl[5,12:16] *} -## 创建一个 `get_current_user` 依赖项 +## 创建 `get_current_user` 依赖项 -让我们来创建一个 `get_current_user` 依赖项。 +创建 `get_current_user` 依赖项。 -还记得依赖项可以有子依赖项吗? +还记得依赖项支持子依赖项吗? -`get_current_user` 将具有一个我们之前所创建的同一个 `oauth2_scheme` 作为依赖项。 +`get_current_user` 使用 `oauth2_scheme` 作为依赖项。 -与我们之前直接在路径操作中所做的相同,我们新的依赖项 `get_current_user` 将从子依赖项 `oauth2_scheme` 中接收一个 `str` 类型的 `token`: +与之前直接在路径操作中的做法相同,新的 `get_current_user` 依赖项从子依赖项 `oauth2_scheme` 中接收 `str` 类型的 `token`: -```Python hl_lines="25" -{!../../../docs_src/security/tutorial002.py!} -``` +{* ../../docs_src/security/tutorial002.py hl[25] *} ## 获取用户 -`get_current_user` 将使用我们创建的(伪)工具函数,该函数接收 `str` 类型的令牌并返回我们的 Pydantic `User` 模型: +`get_current_user` 使用创建的(伪)工具函数,该函数接收 `str` 类型的令牌,并返回 Pydantic 的 `User` 模型: -```Python hl_lines="19-22 26-27" -{!../../../docs_src/security/tutorial002.py!} -``` +{* ../../docs_src/security/tutorial002.py hl[19:22,26:27] *} ## 注入当前用户 -因此现在我们可以在*路径操作*中使用 `get_current_user` 作为 `Depends` 了: +在*路径操作* 的 `Depends` 中使用 `get_current_user`: -```Python hl_lines="31" -{!../../../docs_src/security/tutorial002.py!} -``` +{* ../../docs_src/security/tutorial002.py hl[31] *} -注意我们将 `current_user` 的类型声明为 Pydantic 模型 `User`。 +注意,此处把 `current_user` 的类型声明为 Pydantic 的 `User` 模型。 -这将帮助我们在函数内部使用所有的代码补全和类型检查。 +这有助于在函数内部使用代码补全和类型检查。 -!!! tip - 你可能还记得请求体也是使用 Pydantic 模型来声明的。 +/// tip | 提示 - 在这里 **FastAPI** 不会搞混,因为你正在使用的是 `Depends`。 +还记得请求体也是使用 Pydantic 模型声明的吧。 -!!! check - 这种依赖系统的设计方式使我们可以拥有不同的依赖项(不同的「可依赖类型」),并且它们都返回一个 `User` 模型。 +放心,因为使用了 `Depends`,**FastAPI** 不会搞混。 - 我们并未被局限于只能有一个返回该类型数据的依赖项。 +/// +/// check | 检查 -## 其他模型 +依赖系统的这种设计方式可以支持不同的依赖项返回同一个 `User` 模型。 -现在你可以直接在*路径操作函数*中获取当前用户,并使用 `Depends` 在**依赖注入**级别处理安全性机制。 +而不是局限于只能有一个返回该类型数据的依赖项。 -你可以使用任何模型或数据来满足安全性要求(在这个示例中,使用的是 Pydantic 模型 `User`)。 +/// -但是你并未被限制只能使用某些特定的数据模型,类或类型。 +## 其它模型 -你想要在模型中使用 `id` 和 `email` 而不使用任何的 `username`?当然可以。你可以同样地使用这些工具。 +接下来,直接在*路径操作函数*中获取当前用户,并用 `Depends` 在**依赖注入**系统中处理安全机制。 -你只想要一个 `str`?或者仅仅一个 `dict`?还是直接一个数据库模型类的实例?它们的工作方式都是一样的。 +开发者可以使用任何模型或数据满足安全需求(本例中是 Pydantic 的 `User` 模型)。 -实际上你没有用户登录到你的应用程序,而是只拥有访问令牌的机器人,程序或其他系统?再一次,它们的工作方式也是一样的。 +而且,不局限于只能使用特定的数据模型、类或类型。 -尽管去使用你的应用程序所需要的任何模型,任何类,任何数据库。**FastAPI** 通过依赖项注入系统都帮你搞定。 +不想在模型中使用 `username`,而是使用 `id` 和 `email`?当然可以。这些工具也支持。 +只想使用字符串?或字典?甚至是数据库类模型的实例?工作方式都一样。 -## 代码体积 +实际上,就算登录应用的不是用户,而是只拥有访问令牌的机器人、程序或其它系统?工作方式也一样。 -这个示例似乎看起来很冗长。考虑到我们在同一文件中混合了安全性,数据模型工具函数和路径操作等代码。 +尽管使用应用所需的任何模型、类、数据库。**FastAPI** 通过依赖注入系统都能帮您搞定。 -但关键的是。 -安全性和依赖项注入内容只需要编写一次。 +## 代码大小 -你可以根据需要使其变得很复杂。而且只需要在一个地方写一次。但仍然具备所有的灵活性。 +这个示例看起来有些冗长。毕竟这个文件同时包含了安全、数据模型的工具函数,以及路径操作等代码。 -但是,你可以有无数个使用同一安全系统的端点(*路径操作*)。 +但,关键是: -所有(或所需的任何部分)的端点,都可以利用对这些或你创建的其他依赖项进行复用所带来的优势。 +**安全和依赖注入的代码只需要写一次。** -所有的这无数个*路径操作*甚至可以小到只需 3 行代码: +就算写得再复杂,也只是在一个位置写一次就够了。所以,要多复杂就可以写多复杂。 -```Python hl_lines="30-32" -{!../../../docs_src/security/tutorial002.py!} -``` +但是,就算有数千个端点(*路径操作*),它们都可以使用同一个安全系统。 -## 总结 +而且,所有端点(或它们的任何部件)都可以利用这些依赖项或任何其它依赖项。 -现在你可以直接在*路径操作函数*中获取当前用户。 +所有*路径操作*只需 3 行代码就可以了: -我们已经进行到一半了。 +{* ../../docs_src/security/tutorial002.py hl[30:32] *} -我们只需要再为用户/客户端添加一个真正发送 `username` 和 `password` 的*路径操作*。 +## 小结 -这些内容在下一章节。 +现在,我们可以直接在*路径操作函数*中获取当前用户。 + +至此,安全的内容已经讲了一半。 + +只要再为用户或客户端的*路径操作*添加真正发送 `username` 和 `password` 的功能就可以了。 + +下一章见。 diff --git a/docs/zh/docs/tutorial/security/index.md b/docs/zh/docs/tutorial/security/index.md index 0595f5f63..e888a4fe9 100644 --- a/docs/zh/docs/tutorial/security/index.md +++ b/docs/zh/docs/tutorial/security/index.md @@ -32,9 +32,11 @@ OAuth2是一个规范,它定义了几种处理身份认证和授权的方法 OAuth2 没有指定如何加密通信,它期望你为应用程序使用 HTTPS 进行通信。 -!!! tip - 在有关**部署**的章节中,你将了解如何使用 Traefik 和 Let's Encrypt 免费设置 HTTPS。 +/// tip +在有关**部署**的章节中,你将了解如何使用 Traefik 和 Let's Encrypt 免费设置 HTTPS。 + +/// ## OpenID Connect @@ -87,10 +89,13 @@ OpenAPI 定义了以下安全方案: * 此自动发现机制是 OpenID Connect 规范中定义的内容。 -!!! tip - 集成其他身份认证/授权提供者(例如Google,Facebook,Twitter,GitHub等)也是可能的,而且较为容易。 +/// tip + +集成其他身份认证/授权提供者(例如Google,Facebook,Twitter,GitHub等)也是可能的,而且较为容易。 + +最复杂的问题是创建一个像这样的身份认证/授权提供程序,但是 **FastAPI** 为你提供了轻松完成任务的工具,同时为你解决了重活。 - 最复杂的问题是创建一个像这样的身份认证/授权提供程序,但是 **FastAPI** 为你提供了轻松完成任务的工具,同时为你解决了重活。 +/// ## **FastAPI** 实用工具 diff --git a/docs/zh/docs/tutorial/security/oauth2-jwt.md b/docs/zh/docs/tutorial/security/oauth2-jwt.md index 33a4d7fc7..7d338419b 100644 --- a/docs/zh/docs/tutorial/security/oauth2-jwt.md +++ b/docs/zh/docs/tutorial/security/oauth2-jwt.md @@ -26,29 +26,27 @@ JWT 字符串没有加密,任何人都能用它恢复原始信息。 如需深入了解 JWT 令牌,了解它的工作方式,请参阅 https://jwt.io。 -## 安装 `python-jose` +## 安装 `PyJWT` -安装 `python-jose`,在 Python 中生成和校验 JWT 令牌: +安装 `PyJWT`,在 Python 中生成和校验 JWT 令牌:
```console -$ pip install python-jose[cryptography] +$ pip install pyjwt ---> 100% ```
-Python-jose 需要安装配套的加密后端。 +/// info | 说明 -本教程推荐的后端是:pyca/cryptography。 +如果您打算使用类似 RSA 或 ECDSA 的数字签名算法,您应该安装加密库依赖项 `pyjwt[crypto]`。 -!!! tip "提示" +您可以在 PyJWT Installation docs 获得更多信息。 - 本教程以前使用 PyJWT。 - - 但后来换成了 Python-jose,因为 Python-jose 支持 PyJWT 的所有功能,还支持与其它工具集成时可能会用到的一些其它功能。 +/// ## 密码哈希 @@ -62,7 +60,7 @@ $ pip install python-jose[cryptography] 原因很简单,假如数据库被盗,窃贼无法获取用户的明文密码,得到的只是哈希值。 -这样一来,窃贼就无法在其它应用中使用窃取的密码,要知道,很多用户在所有系统中都使用相同的密码,风险超大)。 +这样一来,窃贼就无法在其它应用中使用窃取的密码(要知道,很多用户在所有系统中都使用相同的密码,风险超大)。 ## 安装 `passlib` @@ -84,13 +82,15 @@ $ pip install passlib[bcrypt] -!!! tip "提示" +/// tip | 提示 + +`passlib` 甚至可以读取 Django、Flask 的安全插件等工具创建的密码。 - `passlib` 甚至可以读取 Django、Flask 的安全插件等工具创建的密码。 +例如,把 Django 应用的数据共享给 FastAPI 应用的数据库。或利用同一个数据库,可以逐步把应用从 Django 迁移到 FastAPI。 - 例如,把 Django 应用的数据共享给 FastAPI 应用的数据库。或利用同一个数据库,可以逐步把应用从 Django 迁移到 FastAPI。 +并且,用户可以同时从 Django 应用或 FastAPI 应用登录。 - 并且,用户可以同时从 Django 应用或 FastAPI 应用登录。 +/// ## 密码哈希与校验 @@ -98,13 +98,15 @@ $ pip install passlib[bcrypt] 创建用于密码哈希和身份校验的 PassLib **上下文**。 -!!! tip "提示" +/// tip | 提示 + +PassLib 上下文还支持使用不同哈希算法的功能,包括只能校验的已弃用旧算法等。 - PassLib 上下文还支持使用不同哈希算法的功能,包括只能校验的已弃用旧算法等。 +例如,用它读取和校验其它系统(如 Django)生成的密码,但要使用其它算法,如 Bcrypt,生成新的哈希密码。 - 例如,用它读取和校验其它系统(如 Django)生成的密码,但要使用其它算法,如 Bcrypt,生成新的哈希密码。 +同时,这些功能都是兼容的。 - 同时,这些功能都是兼容的。 +/// 接下来,创建三个工具函数,其中一个函数用于哈希用户的密码。 @@ -112,13 +114,13 @@ $ pip install passlib[bcrypt] 第三个函数用于身份验证,并返回用户。 -```Python hl_lines="7 48 55-56 59-60 69-75" -{!../../../docs_src/security/tutorial004.py!} -``` +{* ../../docs_src/security/tutorial004_an_py310.py hl[8,49,56:57,60:61,70:76] *} + +/// note | 笔记 -!!! note "笔记" +查看新的(伪)数据库 `fake_users_db`,就能看到哈希后的密码:`"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`。 - 查看新的(伪)数据库 `fake_users_db`,就能看到哈希后的密码:`"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`。 +/// ## 处理 JWT 令牌 @@ -148,9 +150,7 @@ $ openssl rand -hex 32 创建生成新的访问令牌的工具函数。 -```Python hl_lines="6 12-14 28-30 78-86" -{!../../../docs_src/security/tutorial004.py!} -``` +{* ../../docs_src/security/tutorial004.py hl[6,12:14,28:30,78:86] *} ## 更新依赖项 @@ -160,9 +160,7 @@ $ openssl rand -hex 32 如果令牌无效,则直接返回 HTTP 错误。 -```Python hl_lines="89-106" -{!../../../docs_src/security/tutorial004.py!} -``` +{* ../../docs_src/security/tutorial004_an_py310.py hl[4,7,13:15,29:31,79:87] *} ## 更新 `/token` *路径操作* @@ -170,9 +168,7 @@ $ openssl rand -hex 32 创建并返回真正的 JWT 访问令牌。 -```Python hl_lines="115-130" -{!../../../docs_src/security/tutorial004.py!} -``` +{* ../../docs_src/security/tutorial004_an_py310.py hl[118:133] *} ### JWT `sub` 的技术细节 @@ -210,9 +206,11 @@ JWT 规范还包括 `sub` 键,值是令牌的主题。 用户名: `johndoe` 密码: `secret` -!!! check "检查" +/// check | 检查 - 注意,代码中没有明文密码**`secret`**,只保存了它的哈希值。 +注意,代码中没有明文密码**`secret`**,只保存了它的哈希值。 + +/// @@ -233,9 +231,11 @@ JWT 规范还包括 `sub` 键,值是令牌的主题。 -!!! note "笔记" +/// note | 笔记 + +注意,请求中 `Authorization` 响应头的值以 `Bearer` 开头。 - 注意,请求中 `Authorization` 响应头的值以 `Bearer` 开头。 +/// ## `scopes` 高级用法 @@ -261,7 +261,7 @@ OAuth2 支持**`scopes`**(作用域)。 开发者可以灵活选择最适合项目的安全机制。 -还可以直接使用 `passlib` 和 `python-jose` 等维护良好、使用广泛的包,这是因为 **FastAPI** 不需要任何复杂机制,就能集成外部的包。 +还可以直接使用 `passlib` 和 `PyJWT` 等维护良好、使用广泛的包,这是因为 **FastAPI** 不需要任何复杂机制,就能集成外部的包。 而且,**FastAPI** 还提供了一些工具,在不影响灵活、稳定和安全的前提下,尽可能地简化安全机制。 diff --git a/docs/zh/docs/tutorial/security/simple-oauth2.md b/docs/zh/docs/tutorial/security/simple-oauth2.md index c7f46177f..f70678df8 100644 --- a/docs/zh/docs/tutorial/security/simple-oauth2.md +++ b/docs/zh/docs/tutorial/security/simple-oauth2.md @@ -32,15 +32,17 @@ OAuth2 还支持客户端发送**`scope`**表单字段。 * 脸书和 Instagram 使用 `instagram_basic` * 谷歌使用 `https://www.googleapis.com/auth/drive` -!!! info "说明" +/// info | 说明 - OAuth2 中,**作用域**只是声明指定权限的字符串。 +OAuth2 中,**作用域**只是声明指定权限的字符串。 - 是否使用冒号 `:` 等符号,或是不是 URL 并不重要。 +是否使用冒号 `:` 等符号,或是不是 URL 并不重要。 - 这些细节只是特定的实现方式。 +这些细节只是特定的实现方式。 - 对 OAuth2 来说,都只是字符串而已。 +对 OAuth2 来说,都只是字符串而已。 + +/// ## 获取 `username` 和 `password` 的代码 @@ -50,9 +52,7 @@ OAuth2 还支持客户端发送**`scope`**表单字段。 首先,导入 `OAuth2PasswordRequestForm`,然后,在 `/token` *路径操作* 中,用 `Depends` 把该类作为依赖项。 -```Python hl_lines="4 76" -{!../../../docs_src/security/tutorial003.py!} -``` +{* ../../docs_src/security/tutorial003.py hl[4,76] *} `OAuth2PasswordRequestForm` 是用以下几项内容声明表单请求体的类依赖项: @@ -61,32 +61,38 @@ OAuth2 还支持客户端发送**`scope`**表单字段。 * 可选的 `scope` 字段,由多个空格分隔的字符串组成的长字符串 * 可选的 `grant_type` -!!! tip "提示" +/// tip | 提示 - 实际上,OAuth2 规范*要求* `grant_type` 字段使用固定值 `password`,但 `OAuth2PasswordRequestForm` 没有作强制约束。 +实际上,OAuth2 规范*要求* `grant_type` 字段使用固定值 `password`,但 `OAuth2PasswordRequestForm` 没有作强制约束。 - 如需强制使用固定值 `password`,则不要用 `OAuth2PasswordRequestForm`,而是用 `OAuth2PasswordRequestFormStrict`。 +如需强制使用固定值 `password`,则不要用 `OAuth2PasswordRequestForm`,而是用 `OAuth2PasswordRequestFormStrict`。 + +/// * 可选的 `client_id`(本例未使用) * 可选的 `client_secret`(本例未使用) -!!! info "说明" +/// info | 说明 + +`OAuth2PasswordRequestForm` 与 `OAuth2PasswordBearer` 一样,都不是 FastAPI 的特殊类。 - `OAuth2PasswordRequestForm` 与 `OAuth2PasswordBearer` 一样,都不是 FastAPI 的特殊类。 +**FastAPI** 把 `OAuth2PasswordBearer` 识别为安全方案。因此,可以通过这种方式把它添加至 OpenAPI。 - **FastAPI** 把 `OAuth2PasswordBearer` 识别为安全方案。因此,可以通过这种方式把它添加至 OpenAPI。 +但 `OAuth2PasswordRequestForm` 只是可以自行编写的类依赖项,也可以直接声明 `Form` 参数。 - 但 `OAuth2PasswordRequestForm` 只是可以自行编写的类依赖项,也可以直接声明 `Form` 参数。 +但由于这种用例很常见,FastAPI 为了简便,就直接提供了对它的支持。 - 但由于这种用例很常见,FastAPI 为了简便,就直接提供了对它的支持。 +/// ### 使用表单数据 -!!! tip "提示" +/// tip | 提示 - `OAuth2PasswordRequestForm` 类依赖项的实例没有以空格分隔的长字符串属性 `scope`,但它支持 `scopes` 属性,由已发送的 scope 字符串列表组成。 +`OAuth2PasswordRequestForm` 类依赖项的实例没有以空格分隔的长字符串属性 `scope`,但它支持 `scopes` 属性,由已发送的 scope 字符串列表组成。 - 本例没有使用 `scopes`,但开发者也可以根据需要使用该属性。 +本例没有使用 `scopes`,但开发者也可以根据需要使用该属性。 + +/// 现在,即可使用表单字段 `username`,从(伪)数据库中获取用户数据。 @@ -94,9 +100,7 @@ OAuth2 还支持客户端发送**`scope`**表单字段。 本例使用 `HTTPException` 异常显示此错误: -```Python hl_lines="3 77-79" -{!../../../docs_src/security/tutorial003.py!} -``` +{* ../../docs_src/security/tutorial003.py hl[3,77:79] *} ### 校验密码 @@ -122,9 +126,7 @@ OAuth2 还支持客户端发送**`scope`**表单字段。 这样一来,窃贼就无法在其它应用中使用窃取的密码,要知道,很多用户在所有系统中都使用相同的密码,风险超大。 -```Python hl_lines="80-83" -{!../../../docs_src/security/tutorial003.py!} -``` +{* ../../docs_src/security/tutorial003.py hl[80:83] *} #### 关于 `**user_dict` @@ -142,9 +144,11 @@ UserInDB( ) ``` -!!! info "说明" +/// info | 说明 - `user_dict` 的说明,详见[**更多模型**一章](../extra-models.md#about-user_indict){.internal-link target=_blank}。 +`user_dict` 的说明,详见[**更多模型**一章](../extra-models.md#user_indict){.internal-link target=_blank}。 + +/// ## 返回 Token @@ -156,25 +160,27 @@ UserInDB( 本例只是简单的演示,返回的 Token 就是 `username`,但这种方式极不安全。 -!!! tip "提示" +/// tip | 提示 - 下一章介绍使用哈希密码和 JWT Token 的真正安全机制。 +下一章介绍使用哈希密码和 JWT Token 的真正安全机制。 - 但现在,仅关注所需的特定细节。 +但现在,仅关注所需的特定细节。 -```Python hl_lines="85" -{!../../../docs_src/security/tutorial003.py!} -``` +/// + +{* ../../docs_src/security/tutorial003.py hl[85] *} -!!! tip "提示" +/// tip | 提示 - 按规范的要求,应像本示例一样,返回带有 `access_token` 和 `token_type` 的 JSON 对象。 +按规范的要求,应像本示例一样,返回带有 `access_token` 和 `token_type` 的 JSON 对象。 - 这是开发者必须在代码中自行完成的工作,并且要确保使用这些 JSON 的键。 +这是开发者必须在代码中自行完成的工作,并且要确保使用这些 JSON 的键。 - 这几乎是唯一需要开发者牢记在心,并按规范要求正确执行的事。 +这几乎是唯一需要开发者牢记在心,并按规范要求正确执行的事。 - **FastAPI** 则负责处理其它的工作。 +**FastAPI** 则负责处理其它的工作。 + +/// ## 更新依赖项 @@ -188,25 +194,25 @@ UserInDB( 因此,在端点中,只有当用户存在、通过身份验证、且状态为激活时,才能获得该用户: -```Python hl_lines="58-67 69-72 90" -{!../../../docs_src/security/tutorial003.py!} -``` +{* ../../docs_src/security/tutorial003.py hl[58:67,69:72,90] *} + +/// info | 说明 -!!! info "说明" +此处返回值为 `Bearer` 的响应头 `WWW-Authenticate` 也是规范的一部分。 - 此处返回值为 `Bearer` 的响应头 `WWW-Authenticate` 也是规范的一部分。 +任何 401**UNAUTHORIZED**HTTP(错误)状态码都应返回 `WWW-Authenticate` 响应头。 - 任何 401**UNAUTHORIZED**HTTP(错误)状态码都应返回 `WWW-Authenticate` 响应头。 +本例中,因为使用的是 Bearer Token,该响应头的值应为 `Bearer`。 - 本例中,因为使用的是 Bearer Token,该响应头的值应为 `Bearer`。 +实际上,忽略这个附加响应头,也不会有什么问题。 - 实际上,忽略这个附加响应头,也不会有什么问题。 +之所以在此提供这个附加响应头,是为了符合规范的要求。 - 之所以在此提供这个附加响应头,是为了符合规范的要求。 +说不定什么时候,就有工具用得上它,而且,开发者或用户也可能用得上。 - 说不定什么时候,就有工具用得上它,而且,开发者或用户也可能用得上。 +这就是遵循标准的好处…… - 这就是遵循标准的好处…… +/// ## 实际效果 diff --git a/docs/zh/docs/tutorial/sql-databases.md b/docs/zh/docs/tutorial/sql-databases.md index c49374971..fbdf3be6c 100644 --- a/docs/zh/docs/tutorial/sql-databases.md +++ b/docs/zh/docs/tutorial/sql-databases.md @@ -1,784 +1,360 @@ -# SQL (关系型) 数据库 +# SQL(关系型)数据库 -**FastAPI**不需要你使用SQL(关系型)数据库。 +**FastAPI** 并不要求您使用 SQL(关系型)数据库。您可以使用**任何**想用的数据库。 -但是您可以使用任何您想要的关系型数据库。 +这里,我们来看一个使用 SQLModel 的示例。 -在这里,让我们看一个使用着[SQLAlchemy](https://www.sqlalchemy.org/)的示例。 +**SQLModel** 是基于 SQLAlchemy 和 Pydantic 构建的。它由 **FastAPI** 的同一作者制作,旨在完美匹配需要使用 **SQL 数据库**的 FastAPI 应用程序。 -您可以很容易地将SQLAlchemy支持任何数据库,像: +/// tip + +您可以使用任何其他您想要的 SQL 或 NoSQL 数据库(在某些情况下称为 “ORM”),FastAPI 不会强迫您使用任何东西。😎 + +/// + +由于 SQLModel 基于 SQLAlchemy,因此您可以轻松使用任何由 SQLAlchemy **支持的数据库**(这也让它们被 SQLModel 支持),例如: * PostgreSQL * MySQL * SQLite * Oracle -* Microsoft SQL Server,等等其它数据库 - -在此示例中,我们将使用**SQLite**,因为它使用单个文件并且 在Python中具有集成支持。因此,您可以复制此示例并按原样来运行它。 - -稍后,对于您的产品级别的应用程序,您可能会要使用像**PostgreSQL**这样的数据库服务器。 - -!!! tip - 这儿有一个**FastAPI**和**PostgreSQL**的官方项目生成器,全部基于**Docker**,包括前端和更多工具:https://github.com/tiangolo/full-stack-fastapi-postgresql - -!!! note - 请注意,大部分代码是`SQLAlchemy`的标准代码,您可以用于任何框架。FastAPI特定的代码和往常一样少。 - -## ORMs(对象关系映射) - -**FastAPI**可与任何数据库在任何样式的库中一起与 数据库进行通信。 - -一种常见的模式是使用“ORM”:对象关系映射。 - -ORM 具有在代码和数据库表(“*关系型”)中的**对象**之间转换(“*映射*”)的工具。 - -使用 ORM,您通常会在 SQL 数据库中创建一个代表映射的类,该类的每个属性代表一个列,具有名称和类型。 +* Microsoft SQL Server 等. -例如,一个类`Pet`可以表示一个 SQL 表`pets`。 +在这个例子中,我们将使用 **SQLite**,因为它使用单个文件,并且 Python 对其有集成支持。因此,您可以直接复制这个例子并运行。 -该类的每个*实例对象都代表数据库中的一行数据。* +之后,对于您的生产应用程序,您可能会想要使用像 PostgreSQL 这样的数据库服务器。 -又例如,一个对象`orion_cat`(`Pet`的一个实例)可以有一个属性`orion_cat.type`, 对标数据库中的`type`列。并且该属性的值可以是其它,例如`"cat"`。 +/// tip -这些 ORM 还具有在表或实体之间建立关系的工具(比如创建多表关系)。 - -这样,您还可以拥有一个属性`orion_cat.owner`,它包含该宠物所有者的数据,这些数据取自另外一个表。 - -因此,`orion_cat.owner.name`可能是该宠物主人的姓名(来自表`owners`中的列`name`)。 - -它可能有一个像`"Arquilian"`(一种业务逻辑)。 - -当您尝试从您的宠物对象访问它时,ORM 将完成所有工作以从相应的表*所有者那里再获取信息。* - -常见的 ORM 例如:Django-ORM(Django 框架的一部分)、SQLAlchemy ORM(SQLAlchemy 的一部分,独立于框架)和 Peewee(独立于框架)等。 - -在这里,我们将看到如何使用**SQLAlchemy ORM**。 - -以类似的方式,您也可以使用任何其他 ORM。 - -!!! tip - 在文档中也有一篇使用 Peewee 的等效的文章。 - -## 文件结构 - -对于这些示例,假设您有一个名为的目录`my_super_project`,其中包含一个名为的子目录`sql_app`,其结构如下: - -``` -. -└── sql_app - ├── __init__.py - ├── crud.py - ├── database.py - ├── main.py - ├── models.py - └── schemas.py -``` +有一个使用 **FastAPI** 和 **PostgreSQL** 的官方的项目生成器,其中包括了前端和更多工具: https://github.com/fastapi/full-stack-fastapi-template -该文件`__init__.py`只是一个空文件,但它告诉 Python 其中`sql_app`的所有模块(Python 文件)都是一个包。 +/// -现在让我们看看每个文件/模块的作用。 +这是一个非常简单和简短的教程。如果您想了解一般的数据库、SQL 或更高级的功能,请查看 SQLModel 文档。 -## 安装 SQLAlchemy +## 安装 `SQLModel` -先下载`SQLAlchemy`所需要的依赖: +首先,确保您创建并激活了[虚拟环境](../virtual-environments.md){.internal-link target=_blank},然后安装了 `sqlmodel` :
```console -$ pip install sqlalchemy - +$ pip install sqlmodel ---> 100% ```
-## 创建 SQLAlchemy 部件 - -让我们转到文件`sql_app/database.py`。 - -### 导入 SQLAlchemy 部件 - -```Python hl_lines="1-3" -{!../../../docs_src/sql_databases/sql_app/database.py!} -``` - -### 为 SQLAlchemy 定义数据库 URL地址 - -```Python hl_lines="5-6" -{!../../../docs_src/sql_databases/sql_app/database.py!} -``` - -在这个例子中,我们正在“连接”到一个 SQLite 数据库(用 SQLite 数据库打开一个文件)。 - -该文件将位于文件中的同一目录中`sql_app.db`。 - -这就是为什么最后一部分是`./sql_app.db`. - -如果您使用的是**PostgreSQL**数据库,则只需取消注释该行: - -```Python -SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" -``` - -...并根据您的数据库数据和相关凭据(也适用于 MySQL、MariaDB 或任何其他)对其进行调整。 - -!!! tip - - 如果您想使用不同的数据库,这是就是您必须修改的地方。 - -### 创建 SQLAlchemy 引擎 - -第一步,创建一个 SQLAlchemy的“引擎”。 - -我们稍后会将这个`engine`在其他地方使用。 - -```Python hl_lines="8-10" -{!../../../docs_src/sql_databases/sql_app/database.py!} -``` - -#### 注意 +## 创建含有单一模型的应用程序 -参数: +我们首先创建应用程序的最简单的第一个版本,只有一个 **SQLModel** 模型。 -```Python -connect_args={"check_same_thread": False} -``` - -...仅用于`SQLite`,在其他数据库不需要它。 - -!!! info "技术细节" - - 默认情况下,SQLite 只允许一个线程与其通信,假设有多个线程的话,也只将处理一个独立的请求。 - - 这是为了防止意外地为不同的事物(不同的请求)共享相同的连接。 - - 但是在 FastAPI 中,普遍使用def函数,多个线程可以为同一个请求与数据库交互,所以我们需要使用`connect_args={"check_same_thread": False}`来让SQLite允许这样。 - - 此外,我们将确保每个请求都在依赖项中获得自己的数据库连接会话,因此不需要该默认机制。 - -### 创建一个`SessionLocal`类 - -每个实例`SessionLocal`都会是一个数据库会话。当然该类本身还不是数据库会话。 - -但是一旦我们创建了一个`SessionLocal`类的实例,这个实例将是实际的数据库会话。 - -我们命名它是`SessionLocal`为了将它与我们从 SQLAlchemy 导入的`Session`区别开来。 - -稍后我们将使用`Session`(从 SQLAlchemy 导入的那个)。 - -要创建`SessionLocal`类,请使用函数`sessionmaker`: - -```Python hl_lines="11" -{!../../../docs_src/sql_databases/sql_app/database.py!} -``` - -### 创建一个`Base`类 - -现在我们将使用`declarative_base()`返回一个类。 - -稍后我们将用这个类继承,来创建每个数据库模型或类(ORM 模型): - -```Python hl_lines="13" -{!../../../docs_src/sql_databases/sql_app/database.py!} -``` - -## 创建数据库模型 - -现在让我们看看文件`sql_app/models.py`。 - -### 用`Base`类来创建 SQLAlchemy 模型 - -我们将使用我们之前创建的`Base`类来创建 SQLAlchemy 模型。 +稍后我们将通过下面的**多个模型**提高其安全性和多功能性。🤓 -!!! tip - SQLAlchemy 使用的“**模型**”这个术语 来指代与数据库交互的这些类和实例。 +### 创建模型 - 而 Pydantic 也使用“模型”这个术语 来指代不同的东西,即数据验证、转换以及文档类和实例。 +导入 `SQLModel` 并创建一个数据库模型: -从`database`(来自上面的`database.py`文件)导入`Base`。 +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[1:11] hl[7:11] *} -创建从它继承的类。 +`Hero` 类与 Pydantic 模型非常相似(实际上,从底层来看,它确实*就是一个 Pydantic 模型*)。 -这些类就是 SQLAlchemy 模型。 +有一些区别: -```Python hl_lines="4 7-8 18-19" -{!../../../docs_src/sql_databases/sql_app/models.py!} -``` - -这个`__tablename__`属性是用来告诉 SQLAlchemy 要在数据库中为每个模型使用的数据库表的名称。 - -### 创建模型属性/列 - -现在创建所有模型(类)属性。 - -这些属性中的每一个都代表其相应数据库表中的一列。 - -我们使用`Column`来表示 SQLAlchemy 中的默认值。 - -我们传递一个 SQLAlchemy “类型”,如`Integer`、`String`和`Boolean`,它定义了数据库中的类型,作为参数。 - -```Python hl_lines="1 10-13 21-24" -{!../../../docs_src/sql_databases/sql_app/models.py!} -``` - -### 创建关系 - -现在创建关系。 - -为此,我们使用SQLAlchemy ORM提供的`relationship`。 +* `table=True` 会告诉 SQLModel 这是一个*表模型*,它应该表示 SQL 数据库中的一个*表*,而不仅仅是一个*数据模型*(就像其他常规的 Pydantic 类一样)。 -这将或多或少会成为一种“神奇”属性,其中表示该表与其他相关的表中的值。 +* `Field(primary_key=True)` 会告诉 SQLModel `id` 是 SQL 数据库中的**主键**(您可以在 SQLModel 文档中了解更多关于 SQL 主键的信息)。 -```Python hl_lines="2 15 26" -{!../../../docs_src/sql_databases/sql_app/models.py!} -``` - -当访问 user 中的属性`items`时,如 中`my_user.items`,它将有一个`Item`SQLAlchemy 模型列表(来自`items`表),这些模型具有指向`users`表中此记录的外键。 - -当您访问`my_user.items`时,SQLAlchemy 实际上会从`items`表中的获取一批记录并在此处填充进去。 - -同样,当访问 Item中的属性`owner`时,它将包含表中的`User`SQLAlchemy 模型`users`。使用`owner_id`属性/列及其外键来了解要从`users`表中获取哪条记录。 - -## 创建 Pydantic 模型 - -现在让我们查看一下文件`sql_app/schemas.py`。 + 把类型设置为 `int | None` ,SQLModel 就能知道该列在 SQL 数据库中应该是 `INTEGER` 类型,并且应该是 `NULLABLE` 。 -!!! tip - 为了避免 SQLAlchemy*模型*和 Pydantic*模型*之间的混淆,我们将有`models.py`(SQLAlchemy 模型的文件)和`schemas.py`( Pydantic 模型的文件)。 +* `Field(index=True)` 会告诉 SQLModel 应该为此列创建一个 **SQL 索引**,这样在读取按此列过滤的数据时,程序能在数据库中进行更快的查找。 - 这些 Pydantic 模型或多或少地定义了一个“schema”(一个有效的数据形状)。 + SQLModel 会知道声明为 `str` 的内容将是类型为 `TEXT` (或 `VARCHAR` ,具体取决于数据库)的 SQL 列。 - 因此,这将帮助我们在使用两者时避免混淆。 +### 创建引擎(Engine) -### 创建初始 Pydantic*模型*/模式 +SQLModel 的引擎 `engine`(实际上它是一个 SQLAlchemy `engine` )是用来与数据库**保持连接**的。 -创建一个`ItemBase`和`UserBase`Pydantic*模型*(或者我们说“schema”)以及在创建或读取数据时具有共同的属性。 +您只需构建**一个 `engine`**,来让您的所有代码连接到同一个数据库。 -`ItemCreate`为 创建一个`UserCreate`继承自它们的所有属性(因此它们将具有相同的属性),以及创建所需的任何其他数据(属性)。 +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[14:18] hl[14:15,17:18] *} -因此在创建时也应当有一个`password`属性。 +使用 `check_same_thread=False` 可以让 FastAPI 在不同线程中使用同一个 SQLite 数据库。这很有必要,因为**单个请求**可能会使用**多个线程**(例如在依赖项中)。 -但是为了安全起见,`password`不会出现在其他同类 Pydantic*模型*中,例如用户请求时不应该从 API 返回响应中包含它。 +不用担心,我们会按照代码结构确保**每个请求使用一个单独的 SQLModel *会话***,这实际上就是 `check_same_thread` 想要实现的。 -=== "Python 3.10+" +### 创建表 - ```Python hl_lines="1 4-6 9-10 21-22 25-26" - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +然后,我们来添加一个函数,使用 `SQLModel.metadata.create_all(engine)` 为所有*表模型***创建表**。 -=== "Python 3.9+" +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[21:22] hl[21:22] *} - ```Python hl_lines="3 6-8 11-12 23-24 27-28" - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +### 创建会话(Session)依赖项 -=== "Python 3.8+" +**`Session`** 会存储**内存中的对象**并跟踪数据中所需更改的内容,然后它**使用 `engine`** 与数据库进行通信。 - ```Python hl_lines="3 6-8 11-12 23-24 27-28" - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +我们会使用 `yield` 创建一个 FastAPI **依赖项**,为每个请求提供一个新的 `Session` 。这确保我们每个请求使用一个单独的会话。🤓 -#### SQLAlchemy 风格和 Pydantic 风格 - -请注意,SQLAlchemy*模型*使用 `=`来定义属性,并将类型作为参数传递给`Column`,例如: - -```Python -name = Column(String) -``` - -虽然 Pydantic*模型*使用`:` 声明类型,但新的类型注释语法/类型提示是: - -```Python -name: str -``` +然后我们创建一个 `Annotated` 的依赖项 `SessionDep` 来简化其他也会用到此依赖的代码。 -请牢记这一点,这样您在使用`:`还是`=`时就不会感到困惑。 +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[25:30] hl[25:27,30] *} -### 创建用于读取/返回的Pydantic*模型/模式* +### 在启动时创建数据库表 -现在创建当从 API 返回数据时、将在读取数据时使用的Pydantic*模型(schemas)。* +我们会在应用程序启动时创建数据库表。 -例如,在创建一个项目之前,我们不知道分配给它的 ID 是什么,但是在读取它时(从 API 返回时)我们已经知道它的 ID。 +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[32:37] hl[35:37] *} -同样,当读取用户时,我们现在可以声明`items`,将包含属于该用户的项目。 +此处,在应用程序启动事件中,我们创建了表。 -不仅是这些项目的 ID,还有我们在 Pydantic*模型*中定义的用于读取项目的所有数据:`Item`. +而对于生产环境,您可能会用一个能够在启动应用程序之前运行的迁移脚本。🤓 -=== "Python 3.10+" +/// tip - ```Python hl_lines="13-15 29-32" - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +SQLModel 将会拥有封装 Alembic 的迁移工具,但目前您可以直接使用 Alembic。 -=== "Python 3.9+" +/// - ```Python hl_lines="15-17 31-34" - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +### 创建 Hero 类 -=== "Python 3.8+" +因为每个 SQLModel 模型同时也是一个 Pydantic 模型,所以您可以在与 Pydantic 模型相同的**类型注释**中使用它。 - ```Python hl_lines="15-17 31-34" - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +例如,如果您声明一个类型为 `Hero` 的参数,它将从 **JSON 主体**中读取数据。 -!!! tip - 请注意,读取用户(从 API 返回)时将使用不包括`password`的`User` Pydantic*模型*。 +同样,您可以将其声明为函数的**返回类型**,然后数据的结构就会显示在自动生成的 API 文档界面中。 -### 使用 Pydantic 的`orm_mode` +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[40:45] hl[40:45] *} -现在,在用于查询的 Pydantic*模型*`Item`中`User`,添加一个内部`Config`类。 + -此类[`Config`](https://pydantic-docs.helpmanual.io/usage/model_config/)用于为 Pydantic 提供配置。 +这里,我们使用 `SessionDep` 依赖项(一个 `Session` )将新的 `Hero` 添加到 `Session` 实例中,提交更改到数据库,刷新 hero 中的数据,并返回它。 -在`Config`类中,设置属性`orm_mode = True`。 +### 读取 Hero 类 -=== "Python 3.10+" +我们可以使用 `select()` 从数据库中**读取** `Hero` 类,并利用 `limit` 和 `offset` 来对结果进行分页。 - ```Python hl_lines="13 17-18 29 34-35" - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[48:55] hl[51:52,54] *} -=== "Python 3.9+" +### 读取单个 Hero - ```Python hl_lines="15 19-20 31 36-37" - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +我们可以**读取**单个 `Hero` 。 -=== "Python 3.8+" +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[58:63] hl[60] *} - ```Python hl_lines="15 19-20 31 36-37" - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +### 删除单个 Hero -!!! tip - 请注意,它使用`=`分配一个值,例如: +我们也可以**删除**单个 `Hero` 。 - `orm_mode = True` +{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[66:73] hl[71] *} - 它不使用之前的`:`来类型声明。 +### 运行应用程序 - 这是设置配置值,而不是声明类型。 +您可以运行这个应用程序: -Pydantic`orm_mode`将告诉 Pydantic*模型*读取数据,即它不是一个`dict`,而是一个 ORM 模型(或任何其他具有属性的任意对象)。 - -这样,而不是仅仅试图从`dict`上 `id` 中获取值,如下所示: - -```Python -id = data["id"] -``` - -尝试从属性中获取它,如: - -```Python -id = data.id -``` - -有了这个,Pydantic*模型*与 ORM 兼容,您只需在*路径操作*`response_model`的参数中声明它即可。 - -您将能够返回一个数据库模型,它将从中读取数据。 - -#### ORM 模式的技术细节 - -SQLAlchemy 和许多其他默认情况下是“延迟加载”。 - -这意味着,例如,除非您尝试访问包含该数据的属性,否则它们不会从数据库中获取关系数据。 - -例如,访问属性`items`: - -```Python -current_user.items -``` - -将使 SQLAlchemy 转到`items`表并获取该用户的项目,在调用`.items`之前不会去查询数据库。 - -没有`orm_mode`,如果您从*路径操作*返回一个 SQLAlchemy 模型,它不会包含关系数据。 - -即使您在 Pydantic 模型中声明了这些关系,也没有用处。 - -但是在 ORM 模式下,由于 Pydantic 本身会尝试从属性访问它需要的数据(而不是假设为 `dict`),你可以声明你想要返回的特定数据,它甚至可以从 ORM 中获取它。 - -## CRUD工具 - -现在让我们看看文件`sql_app/crud.py`。 - -在这个文件中,我们将编写可重用的函数用来与数据库中的数据进行交互。 - -**CRUD**分别为:**增加**、**查询**、**更改**和**删除**,即增删改查。 - -...虽然在这个例子中我们只是新增和查询。 - -### 读取数据 - -从 `sqlalchemy.orm`中导入`Session`,这将允许您声明`db`参数的类型,并在您的函数中进行更好的类型检查和完成。 - -导入之前的`models`(SQLAlchemy 模型)和`schemas`(Pydantic*模型*/模式)。 - -创建一些实用函数来完成: - -* 通过 ID 和电子邮件查询单个用户。 -* 查询多个用户。 -* 查询多个项目。 - -```Python hl_lines="1 3 6-7 10-11 14-15 27-28" -{!../../../docs_src/sql_databases/sql_app/crud.py!} -``` - -!!! tip - 通过创建仅专用于与数据库交互(获取用户或项目)的函数,独立于*路径操作函数*,您可以更轻松地在多个部分中重用它们,并为它们添加单元测试。 - -### 创建数据 - -现在创建实用程序函数来创建数据。 - -它的步骤是: +
-* 使用您的数据创建一个 SQLAlchemy 模型*实例。* -* 使用`add`来将该实例对象添加到您的数据库。 -* 使用`commit`来对数据库的事务提交(以便保存它们)。 -* 使用`refresh`来刷新您的数据库实例(以便它包含来自数据库的任何新数据,例如生成的 ID)。 +```console +$ fastapi dev main.py -```Python hl_lines="18-24 31-36" -{!../../../docs_src/sql_databases/sql_app/crud.py!} +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` -!!! tip - SQLAlchemy 模型`User`包含一个`hashed_password`,它应该是一个包含散列的安全密码。 - - 但由于 API 客户端提供的是原始密码,因此您需要将其提取并在应用程序中生成散列密码。 - - 然后将hashed_password参数与要保存的值一起传递。 - -!!! warning - 此示例不安全,密码未经过哈希处理。 - - 在现实生活中的应用程序中,您需要对密码进行哈希处理,并且永远不要以明文形式保存它们。 - - 有关更多详细信息,请返回教程中的安全部分。 - - 在这里,我们只关注数据库的工具和机制。 - -!!! tip - 这里不是将每个关键字参数传递给Item并从Pydantic模型中读取每个参数,而是先生成一个字典,其中包含Pydantic模型的数据: - - `item.dict()` - - 然后我们将dict的键值对 作为关键字参数传递给 SQLAlchemy `Item`: - - `Item(**item.dict())` - - 然后我们传递 Pydantic模型未提供的额外关键字参数`owner_id`: - - `Item(**item.dict(), owner_id=user_id)` - -## 主**FastAPI**应用程序 - -现在在`sql_app/main.py`文件中 让我们集成和使用我们之前创建的所有其他部分。 - -### 创建数据库表 - -以非常简单的方式创建数据库表: - -=== "Python 3.9+" - - ```Python hl_lines="7" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="9" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` - -#### Alembic 注意 - -通常你可能会使用 Alembic,来进行格式化数据库(创建表等)。 - -而且您还可以将 Alembic 用于“迁移”(这是它的主要工作)。 +
-“迁移”是每当您更改 SQLAlchemy 模型的结构、添加新属性等以在数据库中复制这些更改、添加新列、新表等时所需的一组步骤。 +然后在 `/docs` UI 中,您能够看到 **FastAPI** 会用这些**模型**来**记录** API,并且还会用它们来**序列化**和**验证**数据。 -您可以在[Project Generation - Template](https://fastapi.tiangolo.com/zh/project-generation/)的模板中找到一个 FastAPI 项目中的 Alembic 示例。具体在[`alembic`代码目录中](https://github.com/tiangolo/full-stack-fastapi-postgresql/tree/master/src/backend/app/alembic/)。 +
+ +
-### 创建依赖项 +## 更新应用程序以支持多个模型 -现在使用我们在`sql_app/database.py`文件中创建的`SessionLocal`来创建依赖项。 +现在让我们稍微**重构**一下这个应用,以提高**安全性**和**多功能性**。 -我们需要每个请求有一个独立的数据库会话/连接(`SessionLocal`),在所有请求中使用相同的会话,然后在请求完成后关闭它。 +如果您查看之前的应用程序,您可以在 UI 界面中看到,到目前为止,由客户端决定要创建的 `Hero` 的 `id` 值。😱 -然后将为下一个请求创建一个新会话。 +我们不应该允许这样做,因为他们可能会覆盖我们在数据库中已经分配的 `id` 。决定 `id` 的行为应该由**后端**或**数据库**来完成,**而非客户端**。 -为此,我们将创建一个新的依赖项`yield`,正如前面关于[Dependencies with`yield`](https://fastapi.tiangolo.com/zh/tutorial/dependencies/dependencies-with-yield/)的部分中所解释的那样。 +此外,我们为 hero 创建了一个 `secret_name` ,但到目前为止,我们在各处都返回了它,这就不太**秘密**了……😅 -我们的依赖项将创建一个新的 SQLAlchemy `SessionLocal`,它将在单个请求中使用,然后在请求完成后关闭它。 +我们将通过添加一些**额外的模型**来解决这些问题,而 SQLModel 将在这里大放异彩。✨ -=== "Python 3.9+" +### 创建多个模型 - ```Python hl_lines="13-18" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +在 **SQLModel** 中,任何含有 `table=True` 属性的模型类都是一个**表模型**。 -=== "Python 3.8+" +任何不含有 `table=True` 属性的模型类都是**数据模型**,这些实际上只是 Pydantic 模型(附带一些小的额外功能)。🤓 - ```Python hl_lines="15-20" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +有了 SQLModel,我们就可以利用**继承**来在所有情况下**避免重复**所有字段。 -!!! info - 我们将`SessionLocal()`请求的创建和处理放在一个`try`块中。 +#### `HeroBase` - 基类 - 然后我们在finally块中关闭它。 +我们从一个 `HeroBase` 模型开始,该模型具有所有模型**共享的字段**: - 通过这种方式,我们确保数据库会话在请求后始终关闭。即使在处理请求时出现异常。 +* `name` +* `age` - 但是您不能从退出代码中引发另一个异常(在yield之后)。可以查阅 [Dependencies with yield and HTTPException](https://fastapi.tiangolo.com/zh/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-httpexception) +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:9] hl[7:9] *} -*然后,当在路径操作函数*中使用依赖项时,我们使用`Session`,直接从 SQLAlchemy 导入的类型声明它。 +#### `Hero` - *表模型* -*这将为我们在路径操作函数*中提供更好的编辑器支持,因为编辑器将知道`db`参数的类型`Session`: +接下来,我们创建 `Hero` ,实际的*表模型*,并添加那些不总是在其他模型中的**额外字段**: -=== "Python 3.9+" +* `id` +* `secret_name` - ```Python hl_lines="22 30 36 45 51" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +因为 `Hero` 继承自 HeroBase ,所以它**也**包含了在 `HeroBase` 中声明过的**字段**。因此 `Hero` 的所有字段为: -=== "Python 3.8+" +* `id` +* `name` +* `age` +* `secret_name` - ```Python hl_lines="24 32 38 47 53" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:14] hl[12:14] *} -!!! info "技术细节" - 参数`db`实际上是 type `SessionLocal`,但是这个类(用 创建`sessionmaker()`)是 SQLAlchemy 的“代理” `Session`,所以,编辑器并不真正知道提供了哪些方法。 +#### `HeroPublic` - 公共*数据模型* - 但是通过将类型声明为Session,编辑器现在可以知道可用的方法(.add()、.query()、.commit()等)并且可以提供更好的支持(比如完成)。类型声明不影响实际对象。 +接下来,我们创建一个 `HeroPublic` 模型,这是将**返回**给 API 客户端的模型。 -### 创建您的**FastAPI** *路径操作* +它包含与 `HeroBase` 相同的字段,因此不会包括 `secret_name` 。 -现在,到了最后,编写标准的**FastAPI** *路径操作*代码。 +终于,我们英雄(hero)的身份得到了保护! 🥷 -=== "Python 3.9+" +它还重新声明了 `id: int` 。这样我们便与 API 客户端建立了一种**约定**,使他们始终可以期待 `id` 存在并且是一个整数 `int`(永远不会是 `None` )。 - ```Python hl_lines="21-26 29-32 35-40 43-47 50-53" - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +/// tip -=== "Python 3.8+" +确保返回模型始终提供一个值并且始终是 `int` (而不是 `None` )对 API 客户端非常有用,他们可以在这种确定性下编写更简单的代码。 - ```Python hl_lines="23-28 31-34 37-42 45-49 52-55" - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +此外,**自动生成的客户端**将拥有更简洁的接口,这样与您的 API 交互的开发者就能更轻松地使用您的 API。😎 -我们在依赖项中的每个请求之前利用`yield`创建数据库会话,然后关闭它。 +/// -所以我们就可以在*路径操作函数*中创建需要的依赖,就能直接获取会话。 +`HeroPublic` 中的所有字段都与 `HeroBase` 中的相同,其中 `id` 声明为 `int` (不是 `None` ): -这样,我们就可以直接从*路径操作函数*内部调用`crud.get_user`并使用该会话,来进行对数据库操作。 +* `id` +* `name` +* `age` +* `secret_name` -!!! tip - 请注意,您返回的值是 SQLAlchemy 模型或 SQLAlchemy 模型列表。 +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:18] hl[17:18] *} - 但是由于所有路径操作的response_model都使用 Pydantic模型/使用orm_mode模式,因此您的 Pydantic 模型中声明的数据将从它们中提取并返回给客户端,并进行所有正常的过滤和验证。 +#### `HeroCreate` - 用于创建 hero 的*数据模型* -!!! tip - 另请注意,`response_models`应当是标准 Python 类型,例如`List[schemas.Item]`. +现在我们创建一个 `HeroCreate` 模型,这是用于**验证**客户数据的模型。 - 但是由于它的内容/参数List是一个 使用orm_mode模式的Pydantic模型,所以数据将被正常检索并返回给客户端,所以没有问题。 +它不仅拥有与 `HeroBase` 相同的字段,还有 `secret_name` 。 -### 关于 `def` 对比 `async def` +现在,当客户端**创建一个新的 hero** 时,他们会发送 `secret_name` ,它会被存储到数据库中,但这些 `secret_name` 不会通过 API 返回给客户端。 -*在这里,我们在路径操作函数*和依赖项中都使用着 SQLAlchemy 模型,它将与外部数据库进行通信。 +/// tip -这会需要一些“等待时间”。 +这应当是**密码**被处理的方式:接收密码,但不要通过 API 返回它们。 -但是由于 SQLAlchemy 不具有`await`直接使用的兼容性,因此类似于: +在存储密码之前,您还应该对密码的值进行**哈希**处理,**绝不要以明文形式存储它们**。 -```Python -user = await db.query(User).first() -``` +/// -...相反,我们可以使用: +`HeroCreate` 的字段包括: -```Python -user = db.query(User).first() -``` +* `name` +* `age` +* `secret_name` -然后我们应该声明*路径操作函数*和不带 的依赖关系`async def`,只需使用普通的`def`,如下: +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:22] hl[21:22] *} -```Python hl_lines="2" -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - ... -``` +#### `HeroUpdate` - 用于更新 hero 的*数据模型* -!!! info - 如果您需要异步连接到关系数据库,请参阅[Async SQL (Relational) Databases](https://fastapi.tiangolo.com/zh/advanced/async-sql-databases/) +在之前的应用程序中,我们没有办法**更新 hero**,但现在有了**多个模型**,我们便能做到这一点了。🎉 -!!! note "Very Technical Details" - 如果您很好奇并且拥有深厚的技术知识,您可以在[Async](https://fastapi.tiangolo.com/zh/async/#very-technical-details)文档中查看有关如何处理 `async def`于`def`差别的技术细节。 +`HeroUpdate` *数据模型*有些特殊,它包含创建新 hero 所需的**所有相同字段**,但所有字段都是**可选的**(它们都有默认值)。这样,当您更新一个 hero 时,您可以只发送您想要更新的字段。 -## 迁移 +因为所有**字段实际上**都发生了**变化**(类型现在包括 `None` ,并且它们现在有一个默认值 `None` ),我们需要**重新声明**它们。 -因为我们直接使用 SQLAlchemy,并且我们不需要任何类型的插件来使用**FastAPI**,所以我们可以直接将数据库迁移至[Alembic](https://alembic.sqlalchemy.org/)进行集成。 +我们会重新声明所有字段,因此我们并不是真的需要从 `HeroBase` 继承。我会让它继承只是为了保持一致,但这并不必要。这更多是个人喜好的问题。🤷 -由于与 SQLAlchemy 和 SQLAlchemy 模型相关的代码位于单独的独立文件中,您甚至可以使用 Alembic 执行迁移,而无需安装 FastAPI、Pydantic 或其他任何东西。 +`HeroUpdate` 的字段包括: -同样,您将能够在与**FastAPI**无关的代码的其他部分中使用相同的 SQLAlchemy 模型和实用程序。 +* `name` +* `age` +* `secret_name` -例如,在具有[Celery](https://docs.celeryq.dev/)、[RQ](https://python-rq.org/)或[ARQ](https://arq-docs.helpmanual.io/)的后台任务工作者中。 +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:28] hl[25:28] *} -## 审查所有文件 +### 使用 `HeroCreate` 创建并返回 `HeroPublic` -最后回顾整个案例,您应该有一个名为的目录`my_super_project`,其中包含一个名为`sql_app`。 +既然我们有了**多个模型**,我们就可以对使用它们的应用程序部分进行更新。 -`sql_app`中应该有以下文件: +我们在请求中接收到一个 `HeroCreate` *数据模型*,然后从中创建一个 `Hero` *表模型*。 -* `sql_app/__init__.py`:这是一个空文件。 +这个新的*表模型* `Hero` 会包含客户端发送的字段,以及一个由数据库生成的 `id` 。 -* `sql_app/database.py`: +然后我们将与函数中相同的*表模型* `Hero` 原样返回。但是由于我们使用 `HeroPublic` *数据模型*声明了 `response_model` ,**FastAPI** 会使用 `HeroPublic` 来验证和序列化数据。 -```Python -{!../../../docs_src/sql_databases/sql_app/database.py!} -``` +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[56:62] hl[56:58] *} -* `sql_app/models.py`: +/// tip -```Python -{!../../../docs_src/sql_databases/sql_app/models.py!} -``` +现在我们使用 `response_model=HeroPublic` 来代替**返回类型注释** `-> HeroPublic` ,因为我们返回的值实际上**并不是** `HeroPublic` 类型。 -* `sql_app/schemas.py`: +如果我们声明了 `-> HeroPublic` ,您的编辑器和代码检查工具会抱怨(但也确实理所应当)您返回了一个 `Hero` 而不是一个 `HeroPublic` 。 -=== "Python 3.10+" +通过 `response_model` 的声明,我们让 **FastAPI** 按照它自己的方式处理,而不会干扰类型注解以及编辑器和其他工具提供的帮助。 - ```Python - {!> ../../../docs_src/sql_databases/sql_app_py310/schemas.py!} - ``` +/// -=== "Python 3.9+" +### 用 `HeroPublic` 读取 Hero - ```Python - {!> ../../../docs_src/sql_databases/sql_app_py39/schemas.py!} - ``` +我们可以像之前一样**读取** `Hero` 。同样,使用 `response_model=list[HeroPublic]` 确保正确地验证和序列化数据。 -=== "Python 3.8+" +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[65:72] hl[65] *} - ```Python - {!> ../../../docs_src/sql_databases/sql_app/schemas.py!} - ``` +### 用 `HeroPublic` 读取单个 Hero -* `sql_app/crud.py`: +我们可以**读取**单个 `hero` 。 -```Python -{!../../../docs_src/sql_databases/sql_app/crud.py!} -``` +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[75:80] hl[77] *} -* `sql_app/main.py`: +### 用 `HeroUpdate` 更新单个 Hero -=== "Python 3.9+" +我们可以**更新**单个 `hero` 。为此,我们会使用 HTTP 的 `PATCH` 操作。 - ```Python - {!> ../../../docs_src/sql_databases/sql_app_py39/main.py!} - ``` +在代码中,我们会得到一个 `dict` ,其中包含客户端发送的所有数据,**只有客户端发送的数据**,并排除了任何一个仅仅作为默认值存在的值。为此,我们使用 `exclude_unset=True` 。这是最主要的技巧。🪄 -=== "Python 3.8+" +然后我们会使用 `hero_db.sqlmodel_update(hero_data)` ,来利用 `hero_data` 的数据更新 `hero_db` 。 - ```Python - {!> ../../../docs_src/sql_databases/sql_app/main.py!} - ``` +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[83:93] hl[83:84,88:89] *} -## 执行项目 +### (又一次)删除单个 Hero -您可以复制这些代码并按原样使用它。 +**删除**一个 hero 基本保持不变。 -!!! info +我们不会满足在这一部分中重构一切的愿望。😅 - 事实上,这里的代码只是大多数测试代码的一部分。 +{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[96:103] hl[101] *} -你可以用 Uvicorn 运行它: +### (又一次)运行应用程序 +您可以再运行一次应用程序:
```console -$ uvicorn sql_app.main:app --reload +$ fastapi dev main.py INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ```
-打开浏览器进入 http://127.0.0.1:8000/docs。 - -您将能够与您的**FastAPI**应用程序交互,从真实数据库中读取数据: - - - -## 直接与数据库交互 - -如果您想独立于 FastAPI 直接浏览 SQLite 数据库(文件)以调试其内容、添加表、列、记录、修改数据等,您可以使用[SQLite 的 DB Browser](https://sqlitebrowser.org/) - -它看起来像这样: +您会在 `/docs` API UI 看到它现在已经更新,并且在进行创建 hero 等操作时,它不会再期望从客户端接收 `id` 数据。 +
+
-您还可以使用[SQLite Viewer](https://inloop.github.io/sqlite-viewer/)或[ExtendsClass](https://extendsclass.com/sqlite-browser.html)等在线 SQLite 浏览器。 - -## 中间件替代数据库会话 - -如果你不能使用依赖项`yield`——例如,如果你没有使用**Python 3.7**并且不能安装上面提到的**Python 3.6**的“backports” ——你可以在类似的“中间件”中设置会话方法。 - -“中间件”基本功能是一个为每个请求执行的函数在请求之前进行执行相应的代码,以及在请求执行之后执行相应的代码。 - -### 创建中间件 - -我们将添加中间件(只是一个函数)将为每个请求创建一个新的 SQLAlchemy`SessionLocal`,将其添加到请求中,然后在请求完成后关闭它。 - -=== "Python 3.9+" - - ```Python hl_lines="12-20" - {!> ../../../docs_src/sql_databases/sql_app_py39/alt_main.py!} - ``` - -=== "Python 3.8+" - - ```Python hl_lines="14-22" - {!> ../../../docs_src/sql_databases/sql_app/alt_main.py!} - ``` - -!!! info - 我们将`SessionLocal()`请求的创建和处理放在一个`try`块中。 - - 然后我们在finally块中关闭它。 - - 通过这种方式,我们确保数据库会话在请求后始终关闭,即使在处理请求时出现异常也会关闭。 - -### 关于`request.state` - -`request.state`是每个`Request`对象的属性。它用于存储附加到请求本身的任意对象,例如本例中的数据库会话。您可以在[Starlette 的关于`Request`state](https://www.starlette.io/requests/#other-state)的文档中了解更多信息。 - -对于这种情况下,它帮助我们确保在所有请求中使用单个数据库会话,然后关闭(在中间件中)。 - -### 使用`yield`依赖项与使用中间件的区别 - -在此处添加**中间件**与`yield`的依赖项的作用效果类似,但也有一些区别: - -* 中间件需要更多的代码并且更复杂一些。 -* 中间件必须是一个`async`函数。 - * 如果其中有代码必须“等待”网络,它可能会在那里“阻止”您的应用程序并稍微降低性能。 - * 尽管这里的`SQLAlchemy`工作方式可能不是很成问题。 - * 但是,如果您向等待大量I/O的中间件添加更多代码,则可能会出现问题。 -* *每个*请求都会运行一个中间件。 - * 将为每个请求创建一个连接。 - * 即使处理该请求的*路径操作*不需要数据库。 - -!!! tip - `tyield`当依赖项 足以满足用例时,使用`tyield`依赖项方法会更好。 +## 总结 -!!! info - `yield`的依赖项是最近刚加入**FastAPI**中的。 +您可以使用 **SQLModel** 与 SQL 数据库进行交互,并通过*数据模型*和*表模型*简化代码。 - 所以本教程的先前版本只有带有中间件的示例,并且可能有多个应用程序使用中间件进行数据库会话管理。 +您可以在 SQLModel 的文档中学习到更多内容,其中有一个更详细的关于如何将 SQLModel 与 FastAPI 一起使用的教程。🚀 diff --git a/docs/zh/docs/tutorial/static-files.md b/docs/zh/docs/tutorial/static-files.md index e7c5c3f0a..c19079565 100644 --- a/docs/zh/docs/tutorial/static-files.md +++ b/docs/zh/docs/tutorial/static-files.md @@ -7,14 +7,15 @@ * 导入`StaticFiles`。 * "挂载"(Mount) 一个 `StaticFiles()` 实例到一个指定路径。 -```Python hl_lines="2 6" -{!../../../docs_src/static_files/tutorial001.py!} -``` +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} -!!! note "技术细节" - 你也可以用 `from starlette.staticfiles import StaticFiles`。 +/// note | 技术细节 - **FastAPI** 提供了和 `starlette.staticfiles` 相同的 `fastapi.staticfiles` ,只是为了方便你,开发者。但它确实来自Starlette。 +你也可以用 `from starlette.staticfiles import StaticFiles`。 + +**FastAPI** 提供了和 `starlette.staticfiles` 相同的 `fastapi.staticfiles` ,只是为了方便你,开发者。但它确实来自Starlette。 + +/// ### 什么是"挂载"(Mounting) diff --git a/docs/zh/docs/tutorial/testing.md b/docs/zh/docs/tutorial/testing.md index 77fff7596..3e0c48caf 100644 --- a/docs/zh/docs/tutorial/testing.md +++ b/docs/zh/docs/tutorial/testing.md @@ -8,10 +8,13 @@ ## 使用 `TestClient` -!!! 信息 - 要使用 `TestClient`,先要安装 `httpx`. +/// info | 信息 - 例:`pip install httpx`. +要使用 `TestClient`,先要安装 `httpx`. + +例:`pip install httpx`. + +/// 导入 `TestClient`. @@ -23,24 +26,31 @@ 为你需要检查的地方用标准的Python表达式写个简单的 `assert` 语句(重申,标准的`pytest`)。 -```Python hl_lines="2 12 15-18" -{!../../../docs_src/app_testing/tutorial001.py!} -``` +{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *} + +/// tip | 提示 + +注意测试函数是普通的 `def`,不是 `async def`。 + +还有client的调用也是普通的调用,不是用 `await`。 + +这让你可以直接使用 `pytest` 而不会遇到麻烦。 + +/// + +/// note | 技术细节 -!!! 提示 - 注意测试函数是普通的 `def`,不是 `async def`。 +你也可以用 `from starlette.testclient import TestClient`。 - 还有client的调用也是普通的调用,不是用 `await`。 +**FastAPI** 提供了和 `starlette.testclient` 一样的 `fastapi.testclient`,只是为了方便开发者。但它直接来自Starlette。 - 这让你可以直接使用 `pytest` 而不会遇到麻烦。 +/// -!!! note "技术细节" - 你也可以用 `from starlette.testclient import TestClient`。 +/// tip | 提示 - **FastAPI** 提供了和 `starlette.testclient` 一样的 `fastapi.testclient`,只是为了方便开发者。但它直接来自Starlette。 +除了发送请求之外,如果你还想测试时在FastAPI应用中调用 `async` 函数(例如异步数据库函数), 可以在高级教程中看下 [Async Tests](../advanced/async-tests.md){.internal-link target=_blank} 。 -!!! 提示 - 除了发送请求之外,如果你还想测试时在FastAPI应用中调用 `async` 函数(例如异步数据库函数), 可以在高级教程中看下 [Async Tests](../advanced/async-tests.md){.internal-link target=_blank} 。 +/// ## 分离测试 @@ -50,7 +60,7 @@ ### **FastAPI** app 文件 -假设你有一个像 [更大的应用](./bigger-applications.md){.internal-link target=_blank} 中所描述的文件结构: +假设你有一个像 [更大的应用](bigger-applications.md){.internal-link target=_blank} 中所描述的文件结构: ``` . @@ -62,9 +72,7 @@ 在 `main.py` 文件中你有一个 **FastAPI** app: -```Python -{!../../../docs_src/app_testing/main.py!} -``` +{* ../../docs_src/app_testing/main.py *} ### 测试文件 @@ -80,9 +88,7 @@ 因为这文件在同一个包中,所以你可以通过相对导入从 `main` 模块(`main.py`)导入`app`对象: -```Python hl_lines="3" -{!../../../docs_src/app_testing/test_main.py!} -``` +{* ../../docs_src/app_testing/test_main.py hl[3] *} ...然后测试代码和之前一样的。 @@ -110,50 +116,64 @@ 所有*路径操作* 都需要一个`X-Token` 头。 -=== "Python 3.10+" +//// tab | Python 3.10+ - ```Python - {!> ../../../docs_src/app_testing/app_b_an_py310/main.py!} - ``` +```Python +{!> ../../docs_src/app_testing/app_b_an_py310/main.py!} +``` -=== "Python 3.9+" +//// - ```Python - {!> ../../../docs_src/app_testing/app_b_an_py39/main.py!} - ``` +//// tab | Python 3.9+ -=== "Python 3.8+" +```Python +{!> ../../docs_src/app_testing/app_b_an_py39/main.py!} +``` - ```Python - {!> ../../../docs_src/app_testing/app_b_an/main.py!} - ``` +//// -=== "Python 3.10+ non-Annotated" +//// tab | Python 3.8+ - !!! tip - Prefer to use the `Annotated` version if possible. +```Python +{!> ../../docs_src/app_testing/app_b_an/main.py!} +``` - ```Python - {!> ../../../docs_src/app_testing/app_b_py310/main.py!} - ``` +//// -=== "Python 3.8+ non-Annotated" +//// tab | Python 3.10+ non-Annotated - !!! tip - Prefer to use the `Annotated` version if possible. +/// tip | 提示 - ```Python - {!> ../../../docs_src/app_testing/app_b/main.py!} - ``` +Prefer to use the `Annotated` version if possible. -### 扩展后的测试文件 +/// -然后您可以使用扩展后的测试更新`test_main.py`: +```Python +{!> ../../docs_src/app_testing/app_b_py310/main.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | 提示 + +Prefer to use the `Annotated` version if possible. + +/// ```Python -{!> ../../../docs_src/app_testing/app_b/test_main.py!} +{!> ../../docs_src/app_testing/app_b/main.py!} ``` +//// + +### 扩展后的测试文件 + +然后您可以使用扩展后的测试更新`test_main.py`: + +{* ../../docs_src/app_testing/app_b/test_main.py *} + 每当你需要客户端在请求中传递信息,但你不知道如何传递时,你可以通过搜索(谷歌)如何用 `httpx`做,或者是用 `requests` 做,毕竟HTTPX的设计是基于Requests的设计的。 接着只需在测试中同样操作。 @@ -168,10 +188,13 @@ 关于如何传数据给后端的更多信息 (使用`httpx` 或 `TestClient`),请查阅 HTTPX 文档. -!!! 信息 - 注意 `TestClient` 接收可以被转化为JSON的数据,而不是Pydantic模型。 +/// info | 信息 + +注意 `TestClient` 接收可以被转化为JSON的数据,而不是Pydantic模型。 + +如果你在测试中有一个Pydantic模型,并且你想在测试时发送它的数据给应用,你可以使用在[JSON Compatible Encoder](encoder.md){.internal-link target=_blank}介绍的`jsonable_encoder` 。 - 如果你在测试中有一个Pydantic模型,并且你想在测试时发送它的数据给应用,你可以使用在[JSON Compatible Encoder](encoder.md){.internal-link target=_blank}介绍的`jsonable_encoder` 。 +/// ## 运行起来 diff --git a/docs/zh/docs/virtual-environments.md b/docs/zh/docs/virtual-environments.md new file mode 100644 index 000000000..9b3c0340a --- /dev/null +++ b/docs/zh/docs/virtual-environments.md @@ -0,0 +1,844 @@ +# 虚拟环境 + +当你在 Python 工程中工作时,你可能会有必要用到一个**虚拟环境**(或类似的机制)来隔离你为每个工程安装的包。 + +/// info + +如果你已经了解虚拟环境,知道如何创建和使用它们,你可以考虑跳过这一部分。🤓 + +/// + +/// tip + +**虚拟环境**和**环境变量**是不同的。 + +**环境变量**是系统中的一个变量,可以被程序使用。 + +**虚拟环境**是一个包含一些文件的目录。 + +/// + +/// info + +这个页面将教你如何使用**虚拟环境**以及了解它们的工作原理。 + +如果你计划使用一个**可以为你管理一切的工具**(包括安装 Python),试试 uv。 + +/// + +## 创建一个工程 + +首先,为你的工程创建一个目录。 + +我 (指原作者 —— 译者注) 通常会在我的主目录下创建一个名为 `code` 的目录。 + +在这个目录下,我再为每个工程创建一个目录。 + +
+ +```console +// 进入主目录 +$ cd +// 创建一个用于存放所有代码工程的目录 +$ mkdir code +// 进入 code 目录 +$ cd code +// 创建一个用于存放这个工程的目录 +$ mkdir awesome-project +// 进入这个工程的目录 +$ cd awesome-project +``` + +
+ +## 创建一个虚拟环境 + +在开始一个 Python 工程的**第一时间**,**在你的工程内部**创建一个虚拟环境。 + +/// tip + +你只需要 **在每个工程中操作一次**,而不是每次工作时都操作。 + +/// + +//// tab | `venv` + +你可以使用 Python 自带的 `venv` 模块来创建一个虚拟环境。 + +
+ +```console +$ python -m venv .venv +``` + +
+ +/// details | 上述命令的含义 + +* `python`: 使用名为 `python` 的程序 +* `-m`: 以脚本的方式调用一个模块,我们将告诉它接下来使用哪个模块 +* `venv`: 使用名为 `venv` 的模块,这个模块通常随 Python 一起安装 +* `.venv`: 在新目录 `.venv` 中创建虚拟环境 + +/// + +//// + +//// tab | `uv` + +如果你安装了 `uv`,你也可以使用它来创建一个虚拟环境。 + +
+ +```console +$ uv venv +``` + +
+ +/// tip + +默认情况下,`uv` 会在一个名为 `.venv` 的目录中创建一个虚拟环境。 + +但你可以通过传递一个额外的参数来自定义它,指定目录的名称。 + +/// + +//// + +这个命令会在一个名为 `.venv` 的目录中创建一个新的虚拟环境。 + +/// details | `.venv`,或是其他名称 + +你可以在不同的目录下创建虚拟环境,但通常我们会把它命名为 `.venv`。 + +/// + +## 激活虚拟环境 + +激活新的虚拟环境来确保你运行的任何 Python 命令或安装的包都能使用到它。 + +/// tip + +**每次**开始一个 **新的终端会话** 来工作在这个工程时,你都需要执行这个操作。 + +/// + +//// tab | Linux, macOS + +
+ +```console +$ source .venv/bin/activate +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ .venv\Scripts\Activate.ps1 +``` + +
+ +//// + +//// tab | Windows Bash + +或者,如果你在 Windows 上使用 Bash(例如 Git Bash): + +
+ +```console +$ source .venv/Scripts/activate +``` + +
+ +//// + +/// tip + +每次你在这个环境中安装一个 **新的包** 时,都需要 **重新激活** 这个环境。 + +这么做确保了当你使用一个由这个包安装的 **终端(CLI)程序** 时,你使用的是你的虚拟环境中的程序,而不是全局安装、可能版本不同的程序。 + +/// + +## 检查虚拟环境是否激活 + +检查虚拟环境是否激活 (前面的命令是否生效)。 + +/// tip + +这是 **可选的**,但这是一个很好的方法,可以 **检查** 一切是否按预期工作,以及你是否使用了你打算使用的虚拟环境。 + +/// + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
+ +如果它显示了在你工程 (在这个例子中是 `awesome-project`) 的 `.venv/bin/python` 中的 `python` 二进制文件,那么它就生效了。🎉 + +//// + +//// tab | Windows PowerShell + +
+ +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
+ +如果它显示了在你工程 (在这个例子中是 `awesome-project`) 的 `.venv\Scripts\python` 中的 `python` 二进制文件,那么它就生效了。🎉 + +//// + +## 升级 `pip` + +/// tip + +如果你使用 `uv` 来安装内容,而不是 `pip`,那么你就不需要升级 `pip`。😎 + +/// + +如果你使用 `pip` 来安装包(它是 Python 的默认组件),你应该将它 **升级** 到最新版本。 + +在安装包时出现的许多奇怪的错误都可以通过先升级 `pip` 来解决。 + +/// tip + +通常你只需要在创建虚拟环境后 **执行一次** 这个操作。 + +/// + +确保虚拟环境是激活的 (使用上面的命令),然后运行: + +
+ +```console +$ python -m pip install --upgrade pip + +---> 100% +``` + +
+ +## 添加 `.gitignore` + +如果你使用 **Git** (这是你应该使用的),添加一个 `.gitignore` 文件来排除你的 `.venv` 中的所有内容。 + +/// tip + +如果你使用 `uv` 来创建虚拟环境,它会自动为你完成这个操作,你可以跳过这一步。😎 + +/// + +/// tip + +通常你只需要在创建虚拟环境后 **执行一次** 这个操作。 + +/// + +
+ +```console +$ echo "*" > .venv/.gitignore +``` + +
+ +/// details | 上述命令的含义 + +* `echo "*"`: 将在终端中 "打印" 文本 `*`(接下来的部分会对这个操作进行一些修改) +* `>`: 使左边的命令打印到终端的任何内容实际上都不会被打印,而是会被写入到右边的文件中 +* `.gitignore`: 被写入文本的文件的名称 + +而 `*` 对于 Git 来说意味着 "所有内容"。所以,它会忽略 `.venv` 目录中的所有内容。 + +该命令会创建一个名为 `.gitignore` 的文件,内容如下: + +```gitignore +* +``` + +/// + +## 安装软件包 + +在激活虚拟环境后,你可以在其中安装软件包。 + +/// tip + +当你需要安装或升级软件包时,执行本操作**一次**; + +如果你需要再升级版本或添加新软件包,你可以**再次执行此操作**。 + +/// + +### 直接安装包 + +如果你急于安装,不想使用文件来声明工程的软件包依赖,您可以直接安装它们。 + +/// tip + +将程序所需的软件包及其版本放在文件中(例如 `requirements.txt` 或 `pyproject.toml`)是个好(并且非常好)的主意。 + +/// + +//// tab | `pip` + +
+ +```console +$ pip install "fastapi[standard]" + +---> 100% +``` + +
+ +//// + +//// tab | `uv` + +如果你有 `uv`: + +
+ +```console +$ uv pip install "fastapi[standard]" +---> 100% +``` + +
+ +//// + +### 从 `requirements.txt` 安装 + +如果你有一个 `requirements.txt` 文件,你可以使用它来安装其中的软件包。 + +//// tab | `pip` + +
+ +```console +$ pip install -r requirements.txt +---> 100% +``` + +
+ +//// + +//// tab | `uv` + +如果你有 `uv`: + +
+ +```console +$ uv pip install -r requirements.txt +---> 100% +``` + +
+ +//// + +/// details | 关于 `requirements.txt` + +一个包含一些软件包的 `requirements.txt` 文件看起来应该是这样的: + +```requirements.txt +fastapi[standard]==0.113.0 +pydantic==2.8.0 +``` + +/// + +## 运行程序 + +在你激活虚拟环境后,你可以运行你的程序,它将使用虚拟环境中的 Python 和你在其中安装的软件包。 + +
+ +```console +$ python main.py + +Hello World +``` + +
+ +## 配置编辑器 + +你可能会用到编辑器(即 IDE —— 译者注),请确保配置它使用与你创建的相同的虚拟环境(它可能会自动检测到),以便你可以获得自动补全和内联错误提示。 + +例如: + +* VS Code +* PyCharm + +/// tip + +通常你只需要在创建虚拟环境时执行此操作**一次**。 + +/// + +## 退出虚拟环境 + +当你完成工作后,你可以**退出**虚拟环境。 + +
+ +```console +$ deactivate +``` + +
+ +这样,当你运行 `python` 时,它不会尝试从安装了软件包的虚拟环境中运行。(即,它将不再会尝试从虚拟环境中运行,也不会使用其中安装的软件包。—— 译者注) + +## 开始工作 + +现在你已经准备好开始你的工作了。 + + + +/// tip + +你想要理解上面的所有内容吗? + +继续阅读。👇🤓 + +/// + +## 为什么要使用虚拟环境 + +你需要安装 Python 才能使用 FastAPI。 + +之后,你需要**安装** FastAPI 和你想要使用的任何其他**软件包**。 + +要安装软件包,你通常会使用随 Python 一起提供的 `pip` 命令(或类似的替代方案)。 + +然而,如果你直接使用 `pip`,软件包将被安装在你的**全局 Python 环境**中(即 Python 的全局安装)。 + +### 存在的问题 + +那么,在全局 Python 环境中安装软件包有什么问题呢? + +有些时候,你可能会编写许多不同的程序,这些程序依赖于**不同的软件包**;你所做的一些工程也会依赖于**同一软件包的不同版本**。😱 + +例如,你可能会创建一个名为 `philosophers-stone` 的工程,这个程序依赖于另一个名为 **`harry` 的软件包,使用版本 `1`**。因此,你需要安装 `harry`。 + +```mermaid +flowchart LR + stone(philosophers-stone) -->|需要| harry-1[harry v1] +``` + +然而在此之后,你又创建了另一个名为 `prisoner-of-azkaban` 的工程,这个工程也依赖于 `harry`,但是这个工程需要 **`harry` 版本 `3`**。 + +```mermaid +flowchart LR + azkaban(prisoner-of-azkaban) --> |需要| harry-3[harry v3] +``` + +那么现在的问题是,如果你将软件包安装在全局环境中而不是在本地**虚拟环境**中,你将不得不面临选择安装哪个版本的 `harry` 的问题。 + +如果你想运行 `philosophers-stone`,你需要首先安装 `harry` 版本 `1`,例如: + +
+ +```console +$ pip install "harry==1" +``` + +
+ +然后你将在全局 Python 环境中安装 `harry` 版本 `1`。 + +```mermaid +flowchart LR + subgraph global[全局环境] + harry-1[harry v1] + end + subgraph stone-project[工程 philosophers-stone] + stone(philosophers-stone) -->|需要| harry-1 + end +``` + +但是如果你想运行 `prisoner-of-azkaban`,你需要卸载 `harry` 版本 `1` 并安装 `harry` 版本 `3`(或者说,只要你安装版本 `3` ,版本 `1` 就会自动卸载)。 + +
+ +```console +$ pip install "harry==3" +``` + +
+ +于是,你在你的全局 Python 环境中安装了 `harry` 版本 `3`。 + +如果你再次尝试运行 `philosophers-stone`,有可能它**无法正常工作**,因为它需要 `harry` 版本 `1`。 + +```mermaid +flowchart LR + subgraph global[全局环境] + harry-1[harry v1] + style harry-1 fill:#ccc,stroke-dasharray: 5 5 + harry-3[harry v3] + end + subgraph stone-project[工程 philosophers-stone] + stone(philosophers-stone) -.-x|⛔️| harry-1 + end + subgraph azkaban-project[工程 prisoner-of-azkaban] + azkaban(prisoner-of-azkaban) --> |需要| harry-3 + end +``` + +/// tip + +Python 包在推出**新版本**时通常会尽量**避免破坏性更改**,但最好还是要小心,要想清楚再安装新版本,而且在运行测试以确保一切能正常工作时再安装。 + +/// + +现在,想象一下,如果有**许多**其他**软件包**,它们都是你的**工程所依赖的**。这是非常难以管理的。你可能会发现,有些工程使用了一些**不兼容的软件包版本**,而不知道为什么某些东西无法正常工作。 + +此外,取决于你的操作系统(例如 Linux、Windows、macOS),它可能已经预先安装了 Python。在这种情况下,它可能已经预先安装了一些软件包,这些软件包的特定版本是**系统所需的**。如果你在全局 Python 环境中安装软件包,你可能会**破坏**一些随操作系统一起安装的程序。 + +## 软件包安装在哪里 + +当你安装 Python 时,它会在你的计算机上创建一些目录,并在这些目录中放一些文件。 + +其中一些目录负责存放你安装的所有软件包。 + +当你运行: + +
+ +```console +// 先别去运行这个命令,这只是一个示例 🤓 +$ pip install "fastapi[standard]" +---> 100% +``` + +
+ +这将会从 PyPI 下载一个压缩文件,其中包含 FastAPI 代码。 + +它还会**下载** FastAPI 依赖的其他软件包的文件。 + +然后它会**解压**所有这些文件,并将它们放在你的计算机上的一个目录中。 + +默认情况下,它会将下载并解压的这些文件放在随 Python 安装的目录中,这就是**全局环境**。 + +## 什么是虚拟环境 + +解决软件包都安装在全局环境中的问题的方法是为你所做的每个工程使用一个**虚拟环境**。 + +虚拟环境是一个**目录**,与全局环境非常相似,你可以在其中专为某个工程安装软件包。 + +这样,每个工程都会有自己的虚拟环境(`.venv` 目录),其中包含自己的软件包。 + +```mermaid +flowchart TB + subgraph stone-project[工程 philosophers-stone] + stone(philosophers-stone) --->|需要| harry-1 + subgraph venv1[.venv] + harry-1[harry v1] + end + end + subgraph azkaban-project[工程 prisoner-of-azkaban] + azkaban(prisoner-of-azkaban) --->|需要| harry-3 + subgraph venv2[.venv] + harry-3[harry v3] + end + end + stone-project ~~~ azkaban-project +``` + +## 激活虚拟环境意味着什么 + +当你激活了一个虚拟环境,例如: + +//// tab | Linux, macOS + +
+ +```console +$ source .venv/bin/activate +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ .venv\Scripts\Activate.ps1 +``` + +
+ +//// + +//// tab | Windows Bash + +或者如果你在 Windows 上使用 Bash(例如 Git Bash): + +
+ +```console +$ source .venv/Scripts/activate +``` + +
+ +//// + +这个命令会创建或修改一些[环境变量](environment-variables.md){.internal-link target=_blank},这些环境变量将在接下来的命令中可用。 + +其中之一是 `PATH` 变量。 + +/// tip + +你可以在 [环境变量](environment-variables.md#path-environment-variable){.internal-link target=_blank} 部分了解更多关于 `PATH` 环境变量的内容。 + +/// + +激活虚拟环境会将其路径 `.venv/bin`(在 Linux 和 macOS 上)或 `.venv\Scripts`(在 Windows 上)添加到 `PATH` 环境变量中。 + +假设在激活环境之前,`PATH` 变量看起来像这样: + +//// tab | Linux, macOS + +```plaintext +/usr/bin:/bin:/usr/sbin:/sbin +``` + +这意味着系统会在以下目录中查找程序: + +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Windows\System32 +``` + +这意味着系统会在以下目录中查找程序: + +* `C:\Windows\System32` + +//// + +激活虚拟环境后,`PATH` 变量会变成这样: + +//// tab | Linux, macOS + +```plaintext +/home/user/code/awesome-project/.venv/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +这意味着系统现在会首先在以下目录中查找程序: + +```plaintext +/home/user/code/awesome-project/.venv/bin +``` + +然后再在其他目录中查找。 + +因此,当你在终端中输入 `python` 时,系统会在以下目录中找到 Python 程序: + +```plaintext +/home/user/code/awesome-project/.venv/bin/python +``` + +并使用这个。 + +//// + +//// tab | Windows + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts;C:\Windows\System32 +``` + +这意味着系统现在会首先在以下目录中查找程序: + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts +``` + +然后再在其他目录中查找。 + +因此,当你在终端中输入 `python` 时,系统会在以下目录中找到 Python 程序: + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +并使用这个。 + +//// + +一个重要的细节是,虚拟环境路径会被放在 `PATH` 变量的**开头**。系统会在找到任何其他可用的 Python **之前**找到它。这样,当你运行 `python` 时,它会使用**虚拟环境中**的 Python,而不是任何其他 `python`(例如,全局环境中的 `python`)。 + +激活虚拟环境还会改变其他一些东西,但这是它所做的最重要的事情之一。 + +## 检查虚拟环境 + +当你检查虚拟环境是否激活时,例如: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
+ +//// + +这意味着将使用的 `python` 程序是**在虚拟环境中**的那个。 + +在 Linux 和 macOS 中使用 `which`,在 Windows PowerShell 中使用 `Get-Command`。 + +这个命令的工作方式是,它会在 `PATH` 环境变量中查找,按顺序**逐个路径**查找名为 `python` 的程序。一旦找到,它会**显示该程序的路径**。 + +最重要的部分是,当你调用 `python` 时,将执行的就是这个确切的 "`python`"。 + +因此,你可以确认你是否在正确的虚拟环境中。 + +/// tip + +激活一个虚拟环境,获取一个 Python,然后**转到另一个工程**是一件很容易的事情; + +但如果第二个工程**无法工作**,那是因为你使用了来自另一个工程的虚拟环境的、**不正确的 Python**。 + +因此,会检查正在使用的 `python` 是很有用的。🤓 + +/// + +## 为什么要停用虚拟环境 + +例如,你可能正在一个工程 `philosophers-stone` 上工作,**激活了该虚拟环境**,安装了包并使用了该环境, + +然后你想要在**另一个工程** `prisoner-of-azkaban` 上工作, + +你进入那个工程: + +
+ +```console +$ cd ~/code/prisoner-of-azkaban +``` + +
+ +如果你不去停用 `philosophers-stone` 的虚拟环境,当你在终端中运行 `python` 时,它会尝试使用 `philosophers-stone` 中的 Python。 + +
+ +```console +$ cd ~/code/prisoner-of-azkaban + +$ python main.py + +// 导入 sirius 报错,它没有安装 😱 +Traceback (most recent call last): + File "main.py", line 1, in + import sirius +``` + +
+ +但是如果你停用虚拟环境并激活 `prisoner-of-askaban` 的新虚拟环境,那么当你运行 `python` 时,它会使用 `prisoner-of-askaban` 中的虚拟环境中的 Python。 + +
+ +```console +$ cd ~/code/prisoner-of-azkaban + +// 你不需要在旧目录中操作停用,你可以在任何地方操作停用,甚至在转到另一个工程之后 😎 +$ deactivate + +// 激活 prisoner-of-azkaban/.venv 中的虚拟环境 🚀 +$ source .venv/bin/activate + +// 现在当你运行 python 时,它会在这个虚拟环境中找到安装的 sirius 包 ✨ +$ python main.py + +I solemnly swear 🐺 +``` + +
+ +## 替代方案 + +这是一个简单的指南,可以帮助你入门并教会你如何理解一切**底层**的东西。 + +有许多**替代方案**来管理虚拟环境、包依赖(requirements)、工程。 + +一旦你准备好并想要使用一个工具来**管理整个工程**、包依赖、虚拟环境等,建议你尝试 uv。 + +`uv` 可以做很多事情,它可以: + +* 为你**安装 Python**,包括不同的版本 +* 为你的工程管理**虚拟环境** +* 安装**软件包** +* 为你的工程管理软件包的**依赖和版本** +* 确保你有一个**确切**的软件包和版本集合来安装,包括它们的依赖项,这样你就可以确保在生产中运行你的工程与在开发时在你的计算机上运行的工程完全相同,这被称为**锁定** +* 还有很多其他功能 + +## 结论 + +如果你读过并理解了所有这些,现在**你对虚拟环境的了解比很多开发者都要多**。🤓 + +在未来当你调试看起来复杂的东西时,了解这些细节很可能会有用,你会知道**它是如何在底层工作的**。😎 diff --git a/docs_src/advanced_middleware/tutorial003.py b/docs_src/advanced_middleware/tutorial003.py index b99e3edd1..e2c87e67d 100644 --- a/docs_src/advanced_middleware/tutorial003.py +++ b/docs_src/advanced_middleware/tutorial003.py @@ -3,7 +3,7 @@ from fastapi.middleware.gzip import GZipMiddleware app = FastAPI() -app.add_middleware(GZipMiddleware, minimum_size=1000) +app.add_middleware(GZipMiddleware, minimum_size=1000, compresslevel=5) @app.get("/") diff --git a/docs_src/app_testing/app_b/test_main.py b/docs_src/app_testing/app_b/test_main.py index 4e2b98e23..4e1c51ecc 100644 --- a/docs_src/app_testing/app_b/test_main.py +++ b/docs_src/app_testing/app_b/test_main.py @@ -21,7 +21,7 @@ def test_read_item_bad_token(): assert response.json() == {"detail": "Invalid X-Token header"} -def test_read_inexistent_item(): +def test_read_nonexistent_item(): response = client.get("/items/baz", headers={"X-Token": "coneofsilence"}) assert response.status_code == 404 assert response.json() == {"detail": "Item not found"} diff --git a/docs_src/app_testing/app_b_an/main.py b/docs_src/app_testing/app_b_an/main.py index c63134fc9..c66278fdd 100644 --- a/docs_src/app_testing/app_b_an/main.py +++ b/docs_src/app_testing/app_b_an/main.py @@ -34,6 +34,6 @@ async def create_item(item: Item, x_token: Annotated[str, Header()]): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item.id in fake_db: - raise HTTPException(status_code=400, detail="Item already exists") + raise HTTPException(status_code=409, detail="Item already exists") fake_db[item.id] = item return item diff --git a/docs_src/app_testing/app_b_an/test_main.py b/docs_src/app_testing/app_b_an/test_main.py index d186b8ecb..4e1c51ecc 100644 --- a/docs_src/app_testing/app_b_an/test_main.py +++ b/docs_src/app_testing/app_b_an/test_main.py @@ -21,7 +21,7 @@ def test_read_item_bad_token(): assert response.json() == {"detail": "Invalid X-Token header"} -def test_read_inexistent_item(): +def test_read_nonexistent_item(): response = client.get("/items/baz", headers={"X-Token": "coneofsilence"}) assert response.status_code == 404 assert response.json() == {"detail": "Item not found"} @@ -61,5 +61,5 @@ def test_create_existing_item(): "description": "There goes my stealer", }, ) - assert response.status_code == 400 + assert response.status_code == 409 assert response.json() == {"detail": "Item already exists"} diff --git a/docs_src/app_testing/app_b_an_py310/main.py b/docs_src/app_testing/app_b_an_py310/main.py index 48c27a0b8..c5952be0b 100644 --- a/docs_src/app_testing/app_b_an_py310/main.py +++ b/docs_src/app_testing/app_b_an_py310/main.py @@ -33,6 +33,6 @@ async def create_item(item: Item, x_token: Annotated[str, Header()]): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item.id in fake_db: - raise HTTPException(status_code=400, detail="Item already exists") + raise HTTPException(status_code=409, detail="Item already exists") fake_db[item.id] = item return item diff --git a/docs_src/app_testing/app_b_an_py310/test_main.py b/docs_src/app_testing/app_b_an_py310/test_main.py index d186b8ecb..4e1c51ecc 100644 --- a/docs_src/app_testing/app_b_an_py310/test_main.py +++ b/docs_src/app_testing/app_b_an_py310/test_main.py @@ -21,7 +21,7 @@ def test_read_item_bad_token(): assert response.json() == {"detail": "Invalid X-Token header"} -def test_read_inexistent_item(): +def test_read_nonexistent_item(): response = client.get("/items/baz", headers={"X-Token": "coneofsilence"}) assert response.status_code == 404 assert response.json() == {"detail": "Item not found"} @@ -61,5 +61,5 @@ def test_create_existing_item(): "description": "There goes my stealer", }, ) - assert response.status_code == 400 + assert response.status_code == 409 assert response.json() == {"detail": "Item already exists"} diff --git a/docs_src/app_testing/app_b_an_py39/main.py b/docs_src/app_testing/app_b_an_py39/main.py index 935a510b7..142e23a26 100644 --- a/docs_src/app_testing/app_b_an_py39/main.py +++ b/docs_src/app_testing/app_b_an_py39/main.py @@ -33,6 +33,6 @@ async def create_item(item: Item, x_token: Annotated[str, Header()]): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item.id in fake_db: - raise HTTPException(status_code=400, detail="Item already exists") + raise HTTPException(status_code=409, detail="Item already exists") fake_db[item.id] = item return item diff --git a/docs_src/app_testing/app_b_an_py39/test_main.py b/docs_src/app_testing/app_b_an_py39/test_main.py index d186b8ecb..4e1c51ecc 100644 --- a/docs_src/app_testing/app_b_an_py39/test_main.py +++ b/docs_src/app_testing/app_b_an_py39/test_main.py @@ -21,7 +21,7 @@ def test_read_item_bad_token(): assert response.json() == {"detail": "Invalid X-Token header"} -def test_read_inexistent_item(): +def test_read_nonexistent_item(): response = client.get("/items/baz", headers={"X-Token": "coneofsilence"}) assert response.status_code == 404 assert response.json() == {"detail": "Item not found"} @@ -61,5 +61,5 @@ def test_create_existing_item(): "description": "There goes my stealer", }, ) - assert response.status_code == 400 + assert response.status_code == 409 assert response.json() == {"detail": "Item already exists"} diff --git a/docs_src/app_testing/app_b_py310/test_main.py b/docs_src/app_testing/app_b_py310/test_main.py index 4e2b98e23..4e1c51ecc 100644 --- a/docs_src/app_testing/app_b_py310/test_main.py +++ b/docs_src/app_testing/app_b_py310/test_main.py @@ -21,7 +21,7 @@ def test_read_item_bad_token(): assert response.json() == {"detail": "Invalid X-Token header"} -def test_read_inexistent_item(): +def test_read_nonexistent_item(): response = client.get("/items/baz", headers={"X-Token": "coneofsilence"}) assert response.status_code == 404 assert response.json() == {"detail": "Item not found"} diff --git a/docs_src/async_sql_databases/tutorial001.py b/docs_src/async_sql_databases/tutorial001.py deleted file mode 100644 index cbf43d790..000000000 --- a/docs_src/async_sql_databases/tutorial001.py +++ /dev/null @@ -1,65 +0,0 @@ -from typing import List - -import databases -import sqlalchemy -from fastapi import FastAPI -from pydantic import BaseModel - -# SQLAlchemy specific code, as with any other app -DATABASE_URL = "sqlite:///./test.db" -# DATABASE_URL = "postgresql://user:password@postgresserver/db" - -database = databases.Database(DATABASE_URL) - -metadata = sqlalchemy.MetaData() - -notes = sqlalchemy.Table( - "notes", - metadata, - sqlalchemy.Column("id", sqlalchemy.Integer, primary_key=True), - sqlalchemy.Column("text", sqlalchemy.String), - sqlalchemy.Column("completed", sqlalchemy.Boolean), -) - - -engine = sqlalchemy.create_engine( - DATABASE_URL, connect_args={"check_same_thread": False} -) -metadata.create_all(engine) - - -class NoteIn(BaseModel): - text: str - completed: bool - - -class Note(BaseModel): - id: int - text: str - completed: bool - - -app = FastAPI() - - -@app.on_event("startup") -async def startup(): - await database.connect() - - -@app.on_event("shutdown") -async def shutdown(): - await database.disconnect() - - -@app.get("/notes/", response_model=List[Note]) -async def read_notes(): - query = notes.select() - return await database.fetch_all(query) - - -@app.post("/notes/", response_model=Note) -async def create_note(note: NoteIn): - query = notes.insert().values(text=note.text, completed=note.completed) - last_record_id = await database.execute(query) - return {**note.dict(), "id": last_record_id} diff --git a/docs_src/async_tests/test_main.py b/docs_src/async_tests/test_main.py index 9f1527d5f..a57a31f7d 100644 --- a/docs_src/async_tests/test_main.py +++ b/docs_src/async_tests/test_main.py @@ -1,12 +1,14 @@ import pytest -from httpx import AsyncClient +from httpx import ASGITransport, AsyncClient from .main import app @pytest.mark.anyio async def test_root(): - async with AsyncClient(app=app, base_url="http://test") as ac: + async with AsyncClient( + transport=ASGITransport(app=app), base_url="http://test" + ) as ac: response = await ac.get("/") assert response.status_code == 200 assert response.json() == {"message": "Tomato"} diff --git a/docs_src/body/tutorial002.py b/docs_src/body/tutorial002.py index 7f5183908..5cd86216b 100644 --- a/docs_src/body/tutorial002.py +++ b/docs_src/body/tutorial002.py @@ -17,7 +17,7 @@ app = FastAPI() @app.post("/items/") async def create_item(item: Item): item_dict = item.dict() - if item.tax: + if item.tax is not None: price_with_tax = item.price + item.tax item_dict.update({"price_with_tax": price_with_tax}) return item_dict diff --git a/docs_src/body/tutorial002_py310.py b/docs_src/body/tutorial002_py310.py index 8928b72b8..454c45c88 100644 --- a/docs_src/body/tutorial002_py310.py +++ b/docs_src/body/tutorial002_py310.py @@ -15,7 +15,7 @@ app = FastAPI() @app.post("/items/") async def create_item(item: Item): item_dict = item.dict() - if item.tax: + if item.tax is not None: price_with_tax = item.price + item.tax item_dict.update({"price_with_tax": price_with_tax}) return item_dict diff --git a/docs_src/configure_swagger_ui/tutorial002.py b/docs_src/configure_swagger_ui/tutorial002.py index cc569ce45..cc75c2196 100644 --- a/docs_src/configure_swagger_ui/tutorial002.py +++ b/docs_src/configure_swagger_ui/tutorial002.py @@ -1,6 +1,6 @@ from fastapi import FastAPI -app = FastAPI(swagger_ui_parameters={"syntaxHighlight.theme": "obsidian"}) +app = FastAPI(swagger_ui_parameters={"syntaxHighlight": {"theme": "obsidian"}}) @app.get("/users/{username}") diff --git a/docs_src/cookie_param_models/tutorial001.py b/docs_src/cookie_param_models/tutorial001.py new file mode 100644 index 000000000..cc65c43e1 --- /dev/null +++ b/docs_src/cookie_param_models/tutorial001.py @@ -0,0 +1,17 @@ +from typing import Union + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + session_id: str + fatebook_tracker: Union[str, None] = None + googall_tracker: Union[str, None] = None + + +@app.get("/items/") +async def read_items(cookies: Cookies = Cookie()): + return cookies diff --git a/docs_src/cookie_param_models/tutorial001_an.py b/docs_src/cookie_param_models/tutorial001_an.py new file mode 100644 index 000000000..e5839ffd5 --- /dev/null +++ b/docs_src/cookie_param_models/tutorial001_an.py @@ -0,0 +1,18 @@ +from typing import Union + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel +from typing_extensions import Annotated + +app = FastAPI() + + +class Cookies(BaseModel): + session_id: str + fatebook_tracker: Union[str, None] = None + googall_tracker: Union[str, None] = None + + +@app.get("/items/") +async def read_items(cookies: Annotated[Cookies, Cookie()]): + return cookies diff --git a/docs_src/cookie_param_models/tutorial001_an_py310.py b/docs_src/cookie_param_models/tutorial001_an_py310.py new file mode 100644 index 000000000..24cc889a9 --- /dev/null +++ b/docs_src/cookie_param_models/tutorial001_an_py310.py @@ -0,0 +1,17 @@ +from typing import Annotated + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + session_id: str + fatebook_tracker: str | None = None + googall_tracker: str | None = None + + +@app.get("/items/") +async def read_items(cookies: Annotated[Cookies, Cookie()]): + return cookies diff --git a/docs_src/cookie_param_models/tutorial001_an_py39.py b/docs_src/cookie_param_models/tutorial001_an_py39.py new file mode 100644 index 000000000..3d90c2007 --- /dev/null +++ b/docs_src/cookie_param_models/tutorial001_an_py39.py @@ -0,0 +1,17 @@ +from typing import Annotated, Union + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + session_id: str + fatebook_tracker: Union[str, None] = None + googall_tracker: Union[str, None] = None + + +@app.get("/items/") +async def read_items(cookies: Annotated[Cookies, Cookie()]): + return cookies diff --git a/docs_src/cookie_param_models/tutorial001_py310.py b/docs_src/cookie_param_models/tutorial001_py310.py new file mode 100644 index 000000000..7cdee5a92 --- /dev/null +++ b/docs_src/cookie_param_models/tutorial001_py310.py @@ -0,0 +1,15 @@ +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + session_id: str + fatebook_tracker: str | None = None + googall_tracker: str | None = None + + +@app.get("/items/") +async def read_items(cookies: Cookies = Cookie()): + return cookies diff --git a/docs_src/cookie_param_models/tutorial002.py b/docs_src/cookie_param_models/tutorial002.py new file mode 100644 index 000000000..9679e890f --- /dev/null +++ b/docs_src/cookie_param_models/tutorial002.py @@ -0,0 +1,19 @@ +from typing import Union + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + model_config = {"extra": "forbid"} + + session_id: str + fatebook_tracker: Union[str, None] = None + googall_tracker: Union[str, None] = None + + +@app.get("/items/") +async def read_items(cookies: Cookies = Cookie()): + return cookies diff --git a/docs_src/cookie_param_models/tutorial002_an.py b/docs_src/cookie_param_models/tutorial002_an.py new file mode 100644 index 000000000..ce5644b7b --- /dev/null +++ b/docs_src/cookie_param_models/tutorial002_an.py @@ -0,0 +1,20 @@ +from typing import Union + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel +from typing_extensions import Annotated + +app = FastAPI() + + +class Cookies(BaseModel): + model_config = {"extra": "forbid"} + + session_id: str + fatebook_tracker: Union[str, None] = None + googall_tracker: Union[str, None] = None + + +@app.get("/items/") +async def read_items(cookies: Annotated[Cookies, Cookie()]): + return cookies diff --git a/docs_src/cookie_param_models/tutorial002_an_py310.py b/docs_src/cookie_param_models/tutorial002_an_py310.py new file mode 100644 index 000000000..7fa70fe92 --- /dev/null +++ b/docs_src/cookie_param_models/tutorial002_an_py310.py @@ -0,0 +1,19 @@ +from typing import Annotated + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + model_config = {"extra": "forbid"} + + session_id: str + fatebook_tracker: str | None = None + googall_tracker: str | None = None + + +@app.get("/items/") +async def read_items(cookies: Annotated[Cookies, Cookie()]): + return cookies diff --git a/docs_src/cookie_param_models/tutorial002_an_py39.py b/docs_src/cookie_param_models/tutorial002_an_py39.py new file mode 100644 index 000000000..a906ce6a1 --- /dev/null +++ b/docs_src/cookie_param_models/tutorial002_an_py39.py @@ -0,0 +1,19 @@ +from typing import Annotated, Union + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + model_config = {"extra": "forbid"} + + session_id: str + fatebook_tracker: Union[str, None] = None + googall_tracker: Union[str, None] = None + + +@app.get("/items/") +async def read_items(cookies: Annotated[Cookies, Cookie()]): + return cookies diff --git a/docs_src/cookie_param_models/tutorial002_pv1.py b/docs_src/cookie_param_models/tutorial002_pv1.py new file mode 100644 index 000000000..13f78b850 --- /dev/null +++ b/docs_src/cookie_param_models/tutorial002_pv1.py @@ -0,0 +1,20 @@ +from typing import Union + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + class Config: + extra = "forbid" + + session_id: str + fatebook_tracker: Union[str, None] = None + googall_tracker: Union[str, None] = None + + +@app.get("/items/") +async def read_items(cookies: Cookies = Cookie()): + return cookies diff --git a/docs_src/cookie_param_models/tutorial002_pv1_an.py b/docs_src/cookie_param_models/tutorial002_pv1_an.py new file mode 100644 index 000000000..ddfda9b6f --- /dev/null +++ b/docs_src/cookie_param_models/tutorial002_pv1_an.py @@ -0,0 +1,21 @@ +from typing import Union + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel +from typing_extensions import Annotated + +app = FastAPI() + + +class Cookies(BaseModel): + class Config: + extra = "forbid" + + session_id: str + fatebook_tracker: Union[str, None] = None + googall_tracker: Union[str, None] = None + + +@app.get("/items/") +async def read_items(cookies: Annotated[Cookies, Cookie()]): + return cookies diff --git a/docs_src/cookie_param_models/tutorial002_pv1_an_py310.py b/docs_src/cookie_param_models/tutorial002_pv1_an_py310.py new file mode 100644 index 000000000..ac00360b6 --- /dev/null +++ b/docs_src/cookie_param_models/tutorial002_pv1_an_py310.py @@ -0,0 +1,20 @@ +from typing import Annotated + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + class Config: + extra = "forbid" + + session_id: str + fatebook_tracker: str | None = None + googall_tracker: str | None = None + + +@app.get("/items/") +async def read_items(cookies: Annotated[Cookies, Cookie()]): + return cookies diff --git a/docs_src/cookie_param_models/tutorial002_pv1_an_py39.py b/docs_src/cookie_param_models/tutorial002_pv1_an_py39.py new file mode 100644 index 000000000..573caea4b --- /dev/null +++ b/docs_src/cookie_param_models/tutorial002_pv1_an_py39.py @@ -0,0 +1,20 @@ +from typing import Annotated, Union + +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + class Config: + extra = "forbid" + + session_id: str + fatebook_tracker: Union[str, None] = None + googall_tracker: Union[str, None] = None + + +@app.get("/items/") +async def read_items(cookies: Annotated[Cookies, Cookie()]): + return cookies diff --git a/docs_src/cookie_param_models/tutorial002_pv1_py310.py b/docs_src/cookie_param_models/tutorial002_pv1_py310.py new file mode 100644 index 000000000..2c59aad12 --- /dev/null +++ b/docs_src/cookie_param_models/tutorial002_pv1_py310.py @@ -0,0 +1,18 @@ +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + class Config: + extra = "forbid" + + session_id: str + fatebook_tracker: str | None = None + googall_tracker: str | None = None + + +@app.get("/items/") +async def read_items(cookies: Cookies = Cookie()): + return cookies diff --git a/docs_src/cookie_param_models/tutorial002_py310.py b/docs_src/cookie_param_models/tutorial002_py310.py new file mode 100644 index 000000000..f011aa1af --- /dev/null +++ b/docs_src/cookie_param_models/tutorial002_py310.py @@ -0,0 +1,17 @@ +from fastapi import Cookie, FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Cookies(BaseModel): + model_config = {"extra": "forbid"} + + session_id: str + fatebook_tracker: str | None = None + googall_tracker: str | None = None + + +@app.get("/items/") +async def read_items(cookies: Cookies = Cookie()): + return cookies diff --git a/docs_src/custom_docs_ui/tutorial001.py b/docs_src/custom_docs_ui/tutorial001.py index 4384433e3..f7ceb0c2f 100644 --- a/docs_src/custom_docs_ui/tutorial001.py +++ b/docs_src/custom_docs_ui/tutorial001.py @@ -14,8 +14,8 @@ async def custom_swagger_ui_html(): openapi_url=app.openapi_url, title=app.title + " - Swagger UI", oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url, - swagger_js_url="https://unpkg.com/swagger-ui-dist@5.9.0/swagger-ui-bundle.js", - swagger_css_url="https://unpkg.com/swagger-ui-dist@5.9.0/swagger-ui.css", + swagger_js_url="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js", + swagger_css_url="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css", ) diff --git a/docs_src/custom_response/tutorial006c.py b/docs_src/custom_response/tutorial006c.py index db87a9389..87c720364 100644 --- a/docs_src/custom_response/tutorial006c.py +++ b/docs_src/custom_response/tutorial006c.py @@ -6,4 +6,4 @@ app = FastAPI() @app.get("/pydantic", response_class=RedirectResponse, status_code=302) async def redirect_pydantic(): - return "https://pydantic-docs.helpmanual.io/" + return "https://docs.pydantic.dev/" diff --git a/docs_src/dataclasses/tutorial002.py b/docs_src/dataclasses/tutorial002.py index 08a238080..ece2f150c 100644 --- a/docs_src/dataclasses/tutorial002.py +++ b/docs_src/dataclasses/tutorial002.py @@ -21,6 +21,6 @@ async def read_next_item(): return { "name": "Island In The Moon", "price": 12.99, - "description": "A place to be be playin' and havin' fun", + "description": "A place to be playin' and havin' fun", "tags": ["breater"], } diff --git a/docs_src/dataclasses/tutorial003.py b/docs_src/dataclasses/tutorial003.py index 34ce1199e..c61315513 100644 --- a/docs_src/dataclasses/tutorial003.py +++ b/docs_src/dataclasses/tutorial003.py @@ -33,7 +33,7 @@ def get_authors(): # (8) "items": [ { "name": "Island In The Moon", - "description": "A place to be be playin' and havin' fun", + "description": "A place to be playin' and havin' fun", }, {"name": "Holy Buddies"}, ], diff --git a/docs_src/dependencies/tutorial005_an.py b/docs_src/dependencies/tutorial005_an.py index 6785099da..1d78c17a2 100644 --- a/docs_src/dependencies/tutorial005_an.py +++ b/docs_src/dependencies/tutorial005_an.py @@ -21,6 +21,6 @@ def query_or_cookie_extractor( @app.get("/items/") async def read_query( - query_or_default: Annotated[str, Depends(query_or_cookie_extractor)] + query_or_default: Annotated[str, Depends(query_or_cookie_extractor)], ): return {"q_or_cookie": query_or_default} diff --git a/docs_src/dependencies/tutorial005_an_py310.py b/docs_src/dependencies/tutorial005_an_py310.py index 6c0aa0b36..5ccfc62bd 100644 --- a/docs_src/dependencies/tutorial005_an_py310.py +++ b/docs_src/dependencies/tutorial005_an_py310.py @@ -20,6 +20,6 @@ def query_or_cookie_extractor( @app.get("/items/") async def read_query( - query_or_default: Annotated[str, Depends(query_or_cookie_extractor)] + query_or_default: Annotated[str, Depends(query_or_cookie_extractor)], ): return {"q_or_cookie": query_or_default} diff --git a/docs_src/dependencies/tutorial005_an_py39.py b/docs_src/dependencies/tutorial005_an_py39.py index e8887e162..d5dd8dca9 100644 --- a/docs_src/dependencies/tutorial005_an_py39.py +++ b/docs_src/dependencies/tutorial005_an_py39.py @@ -20,6 +20,6 @@ def query_or_cookie_extractor( @app.get("/items/") async def read_query( - query_or_default: Annotated[str, Depends(query_or_cookie_extractor)] + query_or_default: Annotated[str, Depends(query_or_cookie_extractor)], ): return {"q_or_cookie": query_or_default} diff --git a/docs_src/dependencies/tutorial008c.py b/docs_src/dependencies/tutorial008c.py new file mode 100644 index 000000000..4b99a5a31 --- /dev/null +++ b/docs_src/dependencies/tutorial008c.py @@ -0,0 +1,27 @@ +from fastapi import Depends, FastAPI, HTTPException + +app = FastAPI() + + +class InternalError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except InternalError: + print("Oops, we didn't raise again, Britney 😱") + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: str = Depends(get_username)): + if item_id == "portal-gun": + raise InternalError( + f"The portal gun is too dangerous to be owned by {username}" + ) + if item_id != "plumbus": + raise HTTPException( + status_code=404, detail="Item not found, there's only a plumbus here" + ) + return item_id diff --git a/docs_src/dependencies/tutorial008c_an.py b/docs_src/dependencies/tutorial008c_an.py new file mode 100644 index 000000000..94f59f9aa --- /dev/null +++ b/docs_src/dependencies/tutorial008c_an.py @@ -0,0 +1,28 @@ +from fastapi import Depends, FastAPI, HTTPException +from typing_extensions import Annotated + +app = FastAPI() + + +class InternalError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except InternalError: + print("Oops, we didn't raise again, Britney 😱") + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: Annotated[str, Depends(get_username)]): + if item_id == "portal-gun": + raise InternalError( + f"The portal gun is too dangerous to be owned by {username}" + ) + if item_id != "plumbus": + raise HTTPException( + status_code=404, detail="Item not found, there's only a plumbus here" + ) + return item_id diff --git a/docs_src/dependencies/tutorial008c_an_py39.py b/docs_src/dependencies/tutorial008c_an_py39.py new file mode 100644 index 000000000..da92efa9c --- /dev/null +++ b/docs_src/dependencies/tutorial008c_an_py39.py @@ -0,0 +1,29 @@ +from typing import Annotated + +from fastapi import Depends, FastAPI, HTTPException + +app = FastAPI() + + +class InternalError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except InternalError: + print("Oops, we didn't raise again, Britney 😱") + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: Annotated[str, Depends(get_username)]): + if item_id == "portal-gun": + raise InternalError( + f"The portal gun is too dangerous to be owned by {username}" + ) + if item_id != "plumbus": + raise HTTPException( + status_code=404, detail="Item not found, there's only a plumbus here" + ) + return item_id diff --git a/docs_src/dependencies/tutorial008d.py b/docs_src/dependencies/tutorial008d.py new file mode 100644 index 000000000..93039343d --- /dev/null +++ b/docs_src/dependencies/tutorial008d.py @@ -0,0 +1,28 @@ +from fastapi import Depends, FastAPI, HTTPException + +app = FastAPI() + + +class InternalError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except InternalError: + print("We don't swallow the internal error here, we raise again 😎") + raise + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: str = Depends(get_username)): + if item_id == "portal-gun": + raise InternalError( + f"The portal gun is too dangerous to be owned by {username}" + ) + if item_id != "plumbus": + raise HTTPException( + status_code=404, detail="Item not found, there's only a plumbus here" + ) + return item_id diff --git a/docs_src/dependencies/tutorial008d_an.py b/docs_src/dependencies/tutorial008d_an.py new file mode 100644 index 000000000..c35424574 --- /dev/null +++ b/docs_src/dependencies/tutorial008d_an.py @@ -0,0 +1,29 @@ +from fastapi import Depends, FastAPI, HTTPException +from typing_extensions import Annotated + +app = FastAPI() + + +class InternalError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except InternalError: + print("We don't swallow the internal error here, we raise again 😎") + raise + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: Annotated[str, Depends(get_username)]): + if item_id == "portal-gun": + raise InternalError( + f"The portal gun is too dangerous to be owned by {username}" + ) + if item_id != "plumbus": + raise HTTPException( + status_code=404, detail="Item not found, there's only a plumbus here" + ) + return item_id diff --git a/docs_src/dependencies/tutorial008d_an_py39.py b/docs_src/dependencies/tutorial008d_an_py39.py new file mode 100644 index 000000000..99bd5cb91 --- /dev/null +++ b/docs_src/dependencies/tutorial008d_an_py39.py @@ -0,0 +1,30 @@ +from typing import Annotated + +from fastapi import Depends, FastAPI, HTTPException + +app = FastAPI() + + +class InternalError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except InternalError: + print("We don't swallow the internal error here, we raise again 😎") + raise + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: Annotated[str, Depends(get_username)]): + if item_id == "portal-gun": + raise InternalError( + f"The portal gun is too dangerous to be owned by {username}" + ) + if item_id != "plumbus": + raise HTTPException( + status_code=404, detail="Item not found, there's only a plumbus here" + ) + return item_id diff --git a/docs_src/extra_data_types/tutorial001.py b/docs_src/extra_data_types/tutorial001.py index 8ae8472a7..71de958ff 100644 --- a/docs_src/extra_data_types/tutorial001.py +++ b/docs_src/extra_data_types/tutorial001.py @@ -10,10 +10,10 @@ app = FastAPI() @app.put("/items/{item_id}") async def read_items( item_id: UUID, - start_datetime: Union[datetime, None] = Body(default=None), - end_datetime: Union[datetime, None] = Body(default=None), + start_datetime: datetime = Body(), + end_datetime: datetime = Body(), + process_after: timedelta = Body(), repeat_at: Union[time, None] = Body(default=None), - process_after: Union[timedelta, None] = Body(default=None), ): start_process = start_datetime + process_after duration = end_datetime - start_process @@ -21,8 +21,8 @@ async def read_items( "item_id": item_id, "start_datetime": start_datetime, "end_datetime": end_datetime, - "repeat_at": repeat_at, "process_after": process_after, + "repeat_at": repeat_at, "start_process": start_process, "duration": duration, } diff --git a/docs_src/extra_data_types/tutorial001_an.py b/docs_src/extra_data_types/tutorial001_an.py index a4c074241..257d0c7c8 100644 --- a/docs_src/extra_data_types/tutorial001_an.py +++ b/docs_src/extra_data_types/tutorial001_an.py @@ -11,10 +11,10 @@ app = FastAPI() @app.put("/items/{item_id}") async def read_items( item_id: UUID, - start_datetime: Annotated[Union[datetime, None], Body()] = None, - end_datetime: Annotated[Union[datetime, None], Body()] = None, + start_datetime: Annotated[datetime, Body()], + end_datetime: Annotated[datetime, Body()], + process_after: Annotated[timedelta, Body()], repeat_at: Annotated[Union[time, None], Body()] = None, - process_after: Annotated[Union[timedelta, None], Body()] = None, ): start_process = start_datetime + process_after duration = end_datetime - start_process @@ -22,8 +22,8 @@ async def read_items( "item_id": item_id, "start_datetime": start_datetime, "end_datetime": end_datetime, - "repeat_at": repeat_at, "process_after": process_after, + "repeat_at": repeat_at, "start_process": start_process, "duration": duration, } diff --git a/docs_src/extra_data_types/tutorial001_an_py310.py b/docs_src/extra_data_types/tutorial001_an_py310.py index 4f69c40d9..668bf1909 100644 --- a/docs_src/extra_data_types/tutorial001_an_py310.py +++ b/docs_src/extra_data_types/tutorial001_an_py310.py @@ -10,10 +10,10 @@ app = FastAPI() @app.put("/items/{item_id}") async def read_items( item_id: UUID, - start_datetime: Annotated[datetime | None, Body()] = None, - end_datetime: Annotated[datetime | None, Body()] = None, + start_datetime: Annotated[datetime, Body()], + end_datetime: Annotated[datetime, Body()], + process_after: Annotated[timedelta, Body()], repeat_at: Annotated[time | None, Body()] = None, - process_after: Annotated[timedelta | None, Body()] = None, ): start_process = start_datetime + process_after duration = end_datetime - start_process @@ -21,8 +21,8 @@ async def read_items( "item_id": item_id, "start_datetime": start_datetime, "end_datetime": end_datetime, - "repeat_at": repeat_at, "process_after": process_after, + "repeat_at": repeat_at, "start_process": start_process, "duration": duration, } diff --git a/docs_src/extra_data_types/tutorial001_an_py39.py b/docs_src/extra_data_types/tutorial001_an_py39.py index 630d36ae3..fa3551d66 100644 --- a/docs_src/extra_data_types/tutorial001_an_py39.py +++ b/docs_src/extra_data_types/tutorial001_an_py39.py @@ -10,10 +10,10 @@ app = FastAPI() @app.put("/items/{item_id}") async def read_items( item_id: UUID, - start_datetime: Annotated[Union[datetime, None], Body()] = None, - end_datetime: Annotated[Union[datetime, None], Body()] = None, + start_datetime: Annotated[datetime, Body()], + end_datetime: Annotated[datetime, Body()], + process_after: Annotated[timedelta, Body()], repeat_at: Annotated[Union[time, None], Body()] = None, - process_after: Annotated[Union[timedelta, None], Body()] = None, ): start_process = start_datetime + process_after duration = end_datetime - start_process @@ -21,8 +21,8 @@ async def read_items( "item_id": item_id, "start_datetime": start_datetime, "end_datetime": end_datetime, - "repeat_at": repeat_at, "process_after": process_after, + "repeat_at": repeat_at, "start_process": start_process, "duration": duration, } diff --git a/docs_src/extra_data_types/tutorial001_py310.py b/docs_src/extra_data_types/tutorial001_py310.py index d22f81888..a275a0577 100644 --- a/docs_src/extra_data_types/tutorial001_py310.py +++ b/docs_src/extra_data_types/tutorial001_py310.py @@ -9,10 +9,10 @@ app = FastAPI() @app.put("/items/{item_id}") async def read_items( item_id: UUID, - start_datetime: datetime | None = Body(default=None), - end_datetime: datetime | None = Body(default=None), + start_datetime: datetime = Body(), + end_datetime: datetime = Body(), + process_after: timedelta = Body(), repeat_at: time | None = Body(default=None), - process_after: timedelta | None = Body(default=None), ): start_process = start_datetime + process_after duration = end_datetime - start_process @@ -20,8 +20,8 @@ async def read_items( "item_id": item_id, "start_datetime": start_datetime, "end_datetime": end_datetime, - "repeat_at": repeat_at, "process_after": process_after, + "repeat_at": repeat_at, "start_process": start_process, "duration": duration, } diff --git a/docs_src/generate_clients/tutorial004.js b/docs_src/generate_clients/tutorial004.js index 18dc38267..fa222ba6c 100644 --- a/docs_src/generate_clients/tutorial004.js +++ b/docs_src/generate_clients/tutorial004.js @@ -1,29 +1,36 @@ -import * as fs from "fs"; +import * as fs from 'fs' -const filePath = "./openapi.json"; +async function modifyOpenAPIFile(filePath) { + try { + const data = await fs.promises.readFile(filePath) + const openapiContent = JSON.parse(data) -fs.readFile(filePath, (err, data) => { - const openapiContent = JSON.parse(data); - if (err) throw err; - - const paths = openapiContent.paths; - - Object.keys(paths).forEach((pathKey) => { - const pathData = paths[pathKey]; - Object.keys(pathData).forEach((method) => { - const operation = pathData[method]; - if (operation.tags && operation.tags.length > 0) { - const tag = operation.tags[0]; - const operationId = operation.operationId; - const toRemove = `${tag}-`; - if (operationId.startsWith(toRemove)) { - const newOperationId = operationId.substring(toRemove.length); - operation.operationId = newOperationId; + const paths = openapiContent.paths + for (const pathKey of Object.keys(paths)) { + const pathData = paths[pathKey] + for (const method of Object.keys(pathData)) { + const operation = pathData[method] + if (operation.tags && operation.tags.length > 0) { + const tag = operation.tags[0] + const operationId = operation.operationId + const toRemove = `${tag}-` + if (operationId.startsWith(toRemove)) { + const newOperationId = operationId.substring(toRemove.length) + operation.operationId = newOperationId + } } } - }); - }); - fs.writeFile(filePath, JSON.stringify(openapiContent, null, 2), (err) => { - if (err) throw err; - }); -}); + } + + await fs.promises.writeFile( + filePath, + JSON.stringify(openapiContent, null, 2), + ) + console.log('File successfully modified') + } catch (err) { + console.error('Error:', err) + } +} + +const filePath = './openapi.json' +modifyOpenAPIFile(filePath) diff --git a/docs_src/graphql/tutorial001.py b/docs_src/graphql/tutorial001.py index 3b4ca99cf..e92b2d71c 100644 --- a/docs_src/graphql/tutorial001.py +++ b/docs_src/graphql/tutorial001.py @@ -1,6 +1,6 @@ import strawberry from fastapi import FastAPI -from strawberry.asgi import GraphQL +from strawberry.fastapi import GraphQLRouter @strawberry.type @@ -19,8 +19,7 @@ class Query: schema = strawberry.Schema(query=Query) -graphql_app = GraphQL(schema) +graphql_app = GraphQLRouter(schema) app = FastAPI() -app.add_route("/graphql", graphql_app) -app.add_websocket_route("/graphql", graphql_app) +app.include_router(graphql_app, prefix="/graphql") diff --git a/docs_src/header_param_models/tutorial001.py b/docs_src/header_param_models/tutorial001.py new file mode 100644 index 000000000..4caaba87b --- /dev/null +++ b/docs_src/header_param_models/tutorial001.py @@ -0,0 +1,19 @@ +from typing import List, Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: List[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header()): + return headers diff --git a/docs_src/header_param_models/tutorial001_an.py b/docs_src/header_param_models/tutorial001_an.py new file mode 100644 index 000000000..b55c6b56b --- /dev/null +++ b/docs_src/header_param_models/tutorial001_an.py @@ -0,0 +1,20 @@ +from typing import List, Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel +from typing_extensions import Annotated + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: List[str] = [] + + +@app.get("/items/") +async def read_items(headers: Annotated[CommonHeaders, Header()]): + return headers diff --git a/docs_src/header_param_models/tutorial001_an_py310.py b/docs_src/header_param_models/tutorial001_an_py310.py new file mode 100644 index 000000000..acfb6b9bf --- /dev/null +++ b/docs_src/header_param_models/tutorial001_an_py310.py @@ -0,0 +1,19 @@ +from typing import Annotated + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: str | None = None + traceparent: str | None = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: Annotated[CommonHeaders, Header()]): + return headers diff --git a/docs_src/header_param_models/tutorial001_an_py39.py b/docs_src/header_param_models/tutorial001_an_py39.py new file mode 100644 index 000000000..51a5f94fc --- /dev/null +++ b/docs_src/header_param_models/tutorial001_an_py39.py @@ -0,0 +1,19 @@ +from typing import Annotated, Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: Annotated[CommonHeaders, Header()]): + return headers diff --git a/docs_src/header_param_models/tutorial001_py310.py b/docs_src/header_param_models/tutorial001_py310.py new file mode 100644 index 000000000..7239c64ce --- /dev/null +++ b/docs_src/header_param_models/tutorial001_py310.py @@ -0,0 +1,17 @@ +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: str | None = None + traceparent: str | None = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header()): + return headers diff --git a/docs_src/header_param_models/tutorial001_py39.py b/docs_src/header_param_models/tutorial001_py39.py new file mode 100644 index 000000000..4c1137813 --- /dev/null +++ b/docs_src/header_param_models/tutorial001_py39.py @@ -0,0 +1,19 @@ +from typing import Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header()): + return headers diff --git a/docs_src/header_param_models/tutorial002.py b/docs_src/header_param_models/tutorial002.py new file mode 100644 index 000000000..3f9aac58d --- /dev/null +++ b/docs_src/header_param_models/tutorial002.py @@ -0,0 +1,21 @@ +from typing import List, Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + model_config = {"extra": "forbid"} + + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: List[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header()): + return headers diff --git a/docs_src/header_param_models/tutorial002_an.py b/docs_src/header_param_models/tutorial002_an.py new file mode 100644 index 000000000..771135d77 --- /dev/null +++ b/docs_src/header_param_models/tutorial002_an.py @@ -0,0 +1,22 @@ +from typing import List, Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel +from typing_extensions import Annotated + +app = FastAPI() + + +class CommonHeaders(BaseModel): + model_config = {"extra": "forbid"} + + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: List[str] = [] + + +@app.get("/items/") +async def read_items(headers: Annotated[CommonHeaders, Header()]): + return headers diff --git a/docs_src/header_param_models/tutorial002_an_py310.py b/docs_src/header_param_models/tutorial002_an_py310.py new file mode 100644 index 000000000..e9535f045 --- /dev/null +++ b/docs_src/header_param_models/tutorial002_an_py310.py @@ -0,0 +1,21 @@ +from typing import Annotated + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + model_config = {"extra": "forbid"} + + host: str + save_data: bool + if_modified_since: str | None = None + traceparent: str | None = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: Annotated[CommonHeaders, Header()]): + return headers diff --git a/docs_src/header_param_models/tutorial002_an_py39.py b/docs_src/header_param_models/tutorial002_an_py39.py new file mode 100644 index 000000000..ca5208c9d --- /dev/null +++ b/docs_src/header_param_models/tutorial002_an_py39.py @@ -0,0 +1,21 @@ +from typing import Annotated, Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + model_config = {"extra": "forbid"} + + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: Annotated[CommonHeaders, Header()]): + return headers diff --git a/docs_src/header_param_models/tutorial002_pv1.py b/docs_src/header_param_models/tutorial002_pv1.py new file mode 100644 index 000000000..7e56cd993 --- /dev/null +++ b/docs_src/header_param_models/tutorial002_pv1.py @@ -0,0 +1,22 @@ +from typing import List, Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + class Config: + extra = "forbid" + + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: List[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header()): + return headers diff --git a/docs_src/header_param_models/tutorial002_pv1_an.py b/docs_src/header_param_models/tutorial002_pv1_an.py new file mode 100644 index 000000000..236778231 --- /dev/null +++ b/docs_src/header_param_models/tutorial002_pv1_an.py @@ -0,0 +1,23 @@ +from typing import List, Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel +from typing_extensions import Annotated + +app = FastAPI() + + +class CommonHeaders(BaseModel): + class Config: + extra = "forbid" + + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: List[str] = [] + + +@app.get("/items/") +async def read_items(headers: Annotated[CommonHeaders, Header()]): + return headers diff --git a/docs_src/header_param_models/tutorial002_pv1_an_py310.py b/docs_src/header_param_models/tutorial002_pv1_an_py310.py new file mode 100644 index 000000000..e99e24ea5 --- /dev/null +++ b/docs_src/header_param_models/tutorial002_pv1_an_py310.py @@ -0,0 +1,22 @@ +from typing import Annotated + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + class Config: + extra = "forbid" + + host: str + save_data: bool + if_modified_since: str | None = None + traceparent: str | None = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: Annotated[CommonHeaders, Header()]): + return headers diff --git a/docs_src/header_param_models/tutorial002_pv1_an_py39.py b/docs_src/header_param_models/tutorial002_pv1_an_py39.py new file mode 100644 index 000000000..18398b726 --- /dev/null +++ b/docs_src/header_param_models/tutorial002_pv1_an_py39.py @@ -0,0 +1,22 @@ +from typing import Annotated, Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + class Config: + extra = "forbid" + + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: Annotated[CommonHeaders, Header()]): + return headers diff --git a/docs_src/header_param_models/tutorial002_pv1_py310.py b/docs_src/header_param_models/tutorial002_pv1_py310.py new file mode 100644 index 000000000..3dbff9d7b --- /dev/null +++ b/docs_src/header_param_models/tutorial002_pv1_py310.py @@ -0,0 +1,20 @@ +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + class Config: + extra = "forbid" + + host: str + save_data: bool + if_modified_since: str | None = None + traceparent: str | None = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header()): + return headers diff --git a/docs_src/header_param_models/tutorial002_pv1_py39.py b/docs_src/header_param_models/tutorial002_pv1_py39.py new file mode 100644 index 000000000..86e19be0d --- /dev/null +++ b/docs_src/header_param_models/tutorial002_pv1_py39.py @@ -0,0 +1,22 @@ +from typing import Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + class Config: + extra = "forbid" + + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header()): + return headers diff --git a/docs_src/header_param_models/tutorial002_py310.py b/docs_src/header_param_models/tutorial002_py310.py new file mode 100644 index 000000000..3d2296345 --- /dev/null +++ b/docs_src/header_param_models/tutorial002_py310.py @@ -0,0 +1,19 @@ +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + model_config = {"extra": "forbid"} + + host: str + save_data: bool + if_modified_since: str | None = None + traceparent: str | None = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header()): + return headers diff --git a/docs_src/header_param_models/tutorial002_py39.py b/docs_src/header_param_models/tutorial002_py39.py new file mode 100644 index 000000000..f8ce559a7 --- /dev/null +++ b/docs_src/header_param_models/tutorial002_py39.py @@ -0,0 +1,21 @@ +from typing import Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + model_config = {"extra": "forbid"} + + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header()): + return headers diff --git a/docs_src/header_params/tutorial002.py b/docs_src/header_params/tutorial002.py index 639ab1735..0a34f17cc 100644 --- a/docs_src/header_params/tutorial002.py +++ b/docs_src/header_params/tutorial002.py @@ -7,6 +7,6 @@ app = FastAPI() @app.get("/items/") async def read_items( - strange_header: Union[str, None] = Header(default=None, convert_underscores=False) + strange_header: Union[str, None] = Header(default=None, convert_underscores=False), ): return {"strange_header": strange_header} diff --git a/docs_src/header_params/tutorial002_an_py310.py b/docs_src/header_params/tutorial002_an_py310.py index b340647b6..8a102749f 100644 --- a/docs_src/header_params/tutorial002_an_py310.py +++ b/docs_src/header_params/tutorial002_an_py310.py @@ -7,6 +7,6 @@ app = FastAPI() @app.get("/items/") async def read_items( - strange_header: Annotated[str | None, Header(convert_underscores=False)] = None + strange_header: Annotated[str | None, Header(convert_underscores=False)] = None, ): return {"strange_header": strange_header} diff --git a/docs_src/header_params/tutorial002_py310.py b/docs_src/header_params/tutorial002_py310.py index b7979b542..10d6716c6 100644 --- a/docs_src/header_params/tutorial002_py310.py +++ b/docs_src/header_params/tutorial002_py310.py @@ -5,6 +5,6 @@ app = FastAPI() @app.get("/items/") async def read_items( - strange_header: str | None = Header(default=None, convert_underscores=False) + strange_header: str | None = Header(default=None, convert_underscores=False), ): return {"strange_header": strange_header} diff --git a/docs_src/middleware/tutorial001.py b/docs_src/middleware/tutorial001.py index 6bab3410a..e65a7dade 100644 --- a/docs_src/middleware/tutorial001.py +++ b/docs_src/middleware/tutorial001.py @@ -7,8 +7,8 @@ app = FastAPI() @app.middleware("http") async def add_process_time_header(request: Request, call_next): - start_time = time.time() + start_time = time.perf_counter() response = await call_next(request) - process_time = time.time() - start_time + process_time = time.perf_counter() - start_time response.headers["X-Process-Time"] = str(process_time) return response diff --git a/docs_src/nosql_databases/tutorial001.py b/docs_src/nosql_databases/tutorial001.py deleted file mode 100644 index 91893e528..000000000 --- a/docs_src/nosql_databases/tutorial001.py +++ /dev/null @@ -1,53 +0,0 @@ -from typing import Union - -from couchbase import LOCKMODE_WAIT -from couchbase.bucket import Bucket -from couchbase.cluster import Cluster, PasswordAuthenticator -from fastapi import FastAPI -from pydantic import BaseModel - -USERPROFILE_DOC_TYPE = "userprofile" - - -def get_bucket(): - cluster = Cluster( - "couchbase://couchbasehost:8091?fetch_mutation_tokens=1&operation_timeout=30&n1ql_timeout=300" - ) - authenticator = PasswordAuthenticator("username", "password") - cluster.authenticate(authenticator) - bucket: Bucket = cluster.open_bucket("bucket_name", lockmode=LOCKMODE_WAIT) - bucket.timeout = 30 - bucket.n1ql_timeout = 300 - return bucket - - -class User(BaseModel): - username: str - email: Union[str, None] = None - full_name: Union[str, None] = None - disabled: Union[bool, None] = None - - -class UserInDB(User): - type: str = USERPROFILE_DOC_TYPE - hashed_password: str - - -def get_user(bucket: Bucket, username: str): - doc_id = f"userprofile::{username}" - result = bucket.get(doc_id, quiet=True) - if not result.value: - return None - user = UserInDB(**result.value) - return user - - -# FastAPI specific code -app = FastAPI() - - -@app.get("/users/{username}", response_model=User) -def read_user(username: str): - bucket = get_bucket() - user = get_user(bucket=bucket, username=username) - return user diff --git a/docs_src/path_operation_advanced_configuration/tutorial007.py b/docs_src/path_operation_advanced_configuration/tutorial007.py index 972ddbd2c..54e2e9399 100644 --- a/docs_src/path_operation_advanced_configuration/tutorial007.py +++ b/docs_src/path_operation_advanced_configuration/tutorial007.py @@ -30,5 +30,5 @@ async def create_item(request: Request): try: item = Item.model_validate(data) except ValidationError as e: - raise HTTPException(status_code=422, detail=e.errors()) + raise HTTPException(status_code=422, detail=e.errors(include_url=False)) return item diff --git a/docs_src/path_params_numeric_validations/tutorial006.py b/docs_src/path_params_numeric_validations/tutorial006.py index 0ea32694a..f07629aa0 100644 --- a/docs_src/path_params_numeric_validations/tutorial006.py +++ b/docs_src/path_params_numeric_validations/tutorial006.py @@ -13,4 +13,6 @@ async def read_items( results = {"item_id": item_id} if q: results.update({"q": q}) + if size: + results.update({"size": size}) return results diff --git a/docs_src/path_params_numeric_validations/tutorial006_an.py b/docs_src/path_params_numeric_validations/tutorial006_an.py index 22a143623..ac4732573 100644 --- a/docs_src/path_params_numeric_validations/tutorial006_an.py +++ b/docs_src/path_params_numeric_validations/tutorial006_an.py @@ -14,4 +14,6 @@ async def read_items( results = {"item_id": item_id} if q: results.update({"q": q}) + if size: + results.update({"size": size}) return results diff --git a/docs_src/path_params_numeric_validations/tutorial006_an_py39.py b/docs_src/path_params_numeric_validations/tutorial006_an_py39.py index 804751893..426ec3776 100644 --- a/docs_src/path_params_numeric_validations/tutorial006_an_py39.py +++ b/docs_src/path_params_numeric_validations/tutorial006_an_py39.py @@ -15,4 +15,6 @@ async def read_items( results = {"item_id": item_id} if q: results.update({"q": q}) + if size: + results.update({"size": size}) return results diff --git a/docs_src/query_param_models/tutorial001.py b/docs_src/query_param_models/tutorial001.py new file mode 100644 index 000000000..0c0ab315e --- /dev/null +++ b/docs_src/query_param_models/tutorial001.py @@ -0,0 +1,19 @@ +from typing import List + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: List[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: FilterParams = Query()): + return filter_query diff --git a/docs_src/query_param_models/tutorial001_an.py b/docs_src/query_param_models/tutorial001_an.py new file mode 100644 index 000000000..28375057c --- /dev/null +++ b/docs_src/query_param_models/tutorial001_an.py @@ -0,0 +1,19 @@ +from typing import List + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Annotated, Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: List[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: Annotated[FilterParams, Query()]): + return filter_query diff --git a/docs_src/query_param_models/tutorial001_an_py310.py b/docs_src/query_param_models/tutorial001_an_py310.py new file mode 100644 index 000000000..71427acae --- /dev/null +++ b/docs_src/query_param_models/tutorial001_an_py310.py @@ -0,0 +1,18 @@ +from typing import Annotated, Literal + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field + +app = FastAPI() + + +class FilterParams(BaseModel): + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: Annotated[FilterParams, Query()]): + return filter_query diff --git a/docs_src/query_param_models/tutorial001_an_py39.py b/docs_src/query_param_models/tutorial001_an_py39.py new file mode 100644 index 000000000..ba690d3e3 --- /dev/null +++ b/docs_src/query_param_models/tutorial001_an_py39.py @@ -0,0 +1,17 @@ +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Annotated, Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: Annotated[FilterParams, Query()]): + return filter_query diff --git a/docs_src/query_param_models/tutorial001_py310.py b/docs_src/query_param_models/tutorial001_py310.py new file mode 100644 index 000000000..3ebf9f4d7 --- /dev/null +++ b/docs_src/query_param_models/tutorial001_py310.py @@ -0,0 +1,18 @@ +from typing import Literal + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field + +app = FastAPI() + + +class FilterParams(BaseModel): + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: FilterParams = Query()): + return filter_query diff --git a/docs_src/query_param_models/tutorial001_py39.py b/docs_src/query_param_models/tutorial001_py39.py new file mode 100644 index 000000000..54b52a054 --- /dev/null +++ b/docs_src/query_param_models/tutorial001_py39.py @@ -0,0 +1,17 @@ +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: FilterParams = Query()): + return filter_query diff --git a/docs_src/query_param_models/tutorial002.py b/docs_src/query_param_models/tutorial002.py new file mode 100644 index 000000000..1633bc464 --- /dev/null +++ b/docs_src/query_param_models/tutorial002.py @@ -0,0 +1,21 @@ +from typing import List + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + model_config = {"extra": "forbid"} + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: List[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: FilterParams = Query()): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_an.py b/docs_src/query_param_models/tutorial002_an.py new file mode 100644 index 000000000..69705d4b4 --- /dev/null +++ b/docs_src/query_param_models/tutorial002_an.py @@ -0,0 +1,21 @@ +from typing import List + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Annotated, Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + model_config = {"extra": "forbid"} + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: List[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: Annotated[FilterParams, Query()]): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_an_py310.py b/docs_src/query_param_models/tutorial002_an_py310.py new file mode 100644 index 000000000..975956502 --- /dev/null +++ b/docs_src/query_param_models/tutorial002_an_py310.py @@ -0,0 +1,20 @@ +from typing import Annotated, Literal + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field + +app = FastAPI() + + +class FilterParams(BaseModel): + model_config = {"extra": "forbid"} + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: Annotated[FilterParams, Query()]): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_an_py39.py b/docs_src/query_param_models/tutorial002_an_py39.py new file mode 100644 index 000000000..2d4c1a62b --- /dev/null +++ b/docs_src/query_param_models/tutorial002_an_py39.py @@ -0,0 +1,19 @@ +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Annotated, Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + model_config = {"extra": "forbid"} + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: Annotated[FilterParams, Query()]): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_pv1.py b/docs_src/query_param_models/tutorial002_pv1.py new file mode 100644 index 000000000..71ccd961d --- /dev/null +++ b/docs_src/query_param_models/tutorial002_pv1.py @@ -0,0 +1,22 @@ +from typing import List + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + class Config: + extra = "forbid" + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: List[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: FilterParams = Query()): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_pv1_an.py b/docs_src/query_param_models/tutorial002_pv1_an.py new file mode 100644 index 000000000..1dd29157a --- /dev/null +++ b/docs_src/query_param_models/tutorial002_pv1_an.py @@ -0,0 +1,22 @@ +from typing import List + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Annotated, Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + class Config: + extra = "forbid" + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: List[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: Annotated[FilterParams, Query()]): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_pv1_an_py310.py b/docs_src/query_param_models/tutorial002_pv1_an_py310.py new file mode 100644 index 000000000..d635aae88 --- /dev/null +++ b/docs_src/query_param_models/tutorial002_pv1_an_py310.py @@ -0,0 +1,21 @@ +from typing import Annotated, Literal + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field + +app = FastAPI() + + +class FilterParams(BaseModel): + class Config: + extra = "forbid" + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: Annotated[FilterParams, Query()]): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_pv1_an_py39.py b/docs_src/query_param_models/tutorial002_pv1_an_py39.py new file mode 100644 index 000000000..494fef11f --- /dev/null +++ b/docs_src/query_param_models/tutorial002_pv1_an_py39.py @@ -0,0 +1,20 @@ +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Annotated, Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + class Config: + extra = "forbid" + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: Annotated[FilterParams, Query()]): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_pv1_py310.py b/docs_src/query_param_models/tutorial002_pv1_py310.py new file mode 100644 index 000000000..9ffdeefc0 --- /dev/null +++ b/docs_src/query_param_models/tutorial002_pv1_py310.py @@ -0,0 +1,21 @@ +from typing import Literal + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field + +app = FastAPI() + + +class FilterParams(BaseModel): + class Config: + extra = "forbid" + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: FilterParams = Query()): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_pv1_py39.py b/docs_src/query_param_models/tutorial002_pv1_py39.py new file mode 100644 index 000000000..7fa456a79 --- /dev/null +++ b/docs_src/query_param_models/tutorial002_pv1_py39.py @@ -0,0 +1,20 @@ +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + class Config: + extra = "forbid" + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: FilterParams = Query()): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_py310.py b/docs_src/query_param_models/tutorial002_py310.py new file mode 100644 index 000000000..6ec418499 --- /dev/null +++ b/docs_src/query_param_models/tutorial002_py310.py @@ -0,0 +1,20 @@ +from typing import Literal + +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field + +app = FastAPI() + + +class FilterParams(BaseModel): + model_config = {"extra": "forbid"} + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: FilterParams = Query()): + return filter_query diff --git a/docs_src/query_param_models/tutorial002_py39.py b/docs_src/query_param_models/tutorial002_py39.py new file mode 100644 index 000000000..f9bba028c --- /dev/null +++ b/docs_src/query_param_models/tutorial002_py39.py @@ -0,0 +1,19 @@ +from fastapi import FastAPI, Query +from pydantic import BaseModel, Field +from typing_extensions import Literal + +app = FastAPI() + + +class FilterParams(BaseModel): + model_config = {"extra": "forbid"} + + limit: int = Field(100, gt=0, le=100) + offset: int = Field(0, ge=0) + order_by: Literal["created_at", "updated_at"] = "created_at" + tags: list[str] = [] + + +@app.get("/items/") +async def read_items(filter_query: FilterParams = Query()): + return filter_query diff --git a/docs_src/query_params_str_validations/tutorial003.py b/docs_src/query_params_str_validations/tutorial003.py index 73d2e08c8..7d4917373 100644 --- a/docs_src/query_params_str_validations/tutorial003.py +++ b/docs_src/query_params_str_validations/tutorial003.py @@ -7,7 +7,7 @@ app = FastAPI() @app.get("/items/") async def read_items( - q: Union[str, None] = Query(default=None, min_length=3, max_length=50) + q: Union[str, None] = Query(default=None, min_length=3, max_length=50), ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial003_an.py b/docs_src/query_params_str_validations/tutorial003_an.py index a3665f6a8..0dd14086c 100644 --- a/docs_src/query_params_str_validations/tutorial003_an.py +++ b/docs_src/query_params_str_validations/tutorial003_an.py @@ -8,7 +8,7 @@ app = FastAPI() @app.get("/items/") async def read_items( - q: Annotated[Union[str, None], Query(min_length=3, max_length=50)] = None + q: Annotated[Union[str, None], Query(min_length=3, max_length=50)] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial003_an_py310.py b/docs_src/query_params_str_validations/tutorial003_an_py310.py index 836af04de..79a604b6c 100644 --- a/docs_src/query_params_str_validations/tutorial003_an_py310.py +++ b/docs_src/query_params_str_validations/tutorial003_an_py310.py @@ -7,7 +7,7 @@ app = FastAPI() @app.get("/items/") async def read_items( - q: Annotated[str | None, Query(min_length=3, max_length=50)] = None + q: Annotated[str | None, Query(min_length=3, max_length=50)] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial003_an_py39.py b/docs_src/query_params_str_validations/tutorial003_an_py39.py index 87a426839..3d6697793 100644 --- a/docs_src/query_params_str_validations/tutorial003_an_py39.py +++ b/docs_src/query_params_str_validations/tutorial003_an_py39.py @@ -7,7 +7,7 @@ app = FastAPI() @app.get("/items/") async def read_items( - q: Annotated[Union[str, None], Query(min_length=3, max_length=50)] = None + q: Annotated[Union[str, None], Query(min_length=3, max_length=50)] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial004_an_py310_regex.py b/docs_src/query_params_str_validations/tutorial004_regex_an_py310.py similarity index 100% rename from docs_src/query_params_str_validations/tutorial004_an_py310_regex.py rename to docs_src/query_params_str_validations/tutorial004_regex_an_py310.py diff --git a/docs_src/query_params_str_validations/tutorial006b.py b/docs_src/query_params_str_validations/tutorial006b.py deleted file mode 100644 index a8d69c889..000000000 --- a/docs_src/query_params_str_validations/tutorial006b.py +++ /dev/null @@ -1,11 +0,0 @@ -from fastapi import FastAPI, Query - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: str = Query(default=..., min_length=3)): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial006b_an.py b/docs_src/query_params_str_validations/tutorial006b_an.py deleted file mode 100644 index ea3b02583..000000000 --- a/docs_src/query_params_str_validations/tutorial006b_an.py +++ /dev/null @@ -1,12 +0,0 @@ -from fastapi import FastAPI, Query -from typing_extensions import Annotated - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: Annotated[str, Query(min_length=3)] = ...): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial006b_an_py39.py b/docs_src/query_params_str_validations/tutorial006b_an_py39.py deleted file mode 100644 index 687a9f544..000000000 --- a/docs_src/query_params_str_validations/tutorial006b_an_py39.py +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Annotated - -from fastapi import FastAPI, Query - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: Annotated[str, Query(min_length=3)] = ...): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial006c.py b/docs_src/query_params_str_validations/tutorial006c.py index 2ac148c94..0a0e820da 100644 --- a/docs_src/query_params_str_validations/tutorial006c.py +++ b/docs_src/query_params_str_validations/tutorial006c.py @@ -6,7 +6,7 @@ app = FastAPI() @app.get("/items/") -async def read_items(q: Union[str, None] = Query(default=..., min_length=3)): +async def read_items(q: Union[str, None] = Query(min_length=3)): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/docs_src/query_params_str_validations/tutorial006c_an.py b/docs_src/query_params_str_validations/tutorial006c_an.py index 10bf26a57..55c4f4adc 100644 --- a/docs_src/query_params_str_validations/tutorial006c_an.py +++ b/docs_src/query_params_str_validations/tutorial006c_an.py @@ -7,7 +7,7 @@ app = FastAPI() @app.get("/items/") -async def read_items(q: Annotated[Union[str, None], Query(min_length=3)] = ...): +async def read_items(q: Annotated[Union[str, None], Query(min_length=3)]): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/docs_src/query_params_str_validations/tutorial006c_an_py310.py b/docs_src/query_params_str_validations/tutorial006c_an_py310.py index 1ab0a7d53..2995d9c97 100644 --- a/docs_src/query_params_str_validations/tutorial006c_an_py310.py +++ b/docs_src/query_params_str_validations/tutorial006c_an_py310.py @@ -6,7 +6,7 @@ app = FastAPI() @app.get("/items/") -async def read_items(q: Annotated[str | None, Query(min_length=3)] = ...): +async def read_items(q: Annotated[str | None, Query(min_length=3)]): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/docs_src/query_params_str_validations/tutorial006c_an_py39.py b/docs_src/query_params_str_validations/tutorial006c_an_py39.py index ac1273331..76a1cd49a 100644 --- a/docs_src/query_params_str_validations/tutorial006c_an_py39.py +++ b/docs_src/query_params_str_validations/tutorial006c_an_py39.py @@ -6,7 +6,7 @@ app = FastAPI() @app.get("/items/") -async def read_items(q: Annotated[Union[str, None], Query(min_length=3)] = ...): +async def read_items(q: Annotated[Union[str, None], Query(min_length=3)]): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/docs_src/query_params_str_validations/tutorial006c_py310.py b/docs_src/query_params_str_validations/tutorial006c_py310.py index 82dd9e5d7..88b499c7a 100644 --- a/docs_src/query_params_str_validations/tutorial006c_py310.py +++ b/docs_src/query_params_str_validations/tutorial006c_py310.py @@ -4,7 +4,7 @@ app = FastAPI() @app.get("/items/") -async def read_items(q: str | None = Query(default=..., min_length=3)): +async def read_items(q: str | None = Query(min_length=3)): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/docs_src/query_params_str_validations/tutorial006d.py b/docs_src/query_params_str_validations/tutorial006d.py deleted file mode 100644 index 42c5bf4eb..000000000 --- a/docs_src/query_params_str_validations/tutorial006d.py +++ /dev/null @@ -1,12 +0,0 @@ -from fastapi import FastAPI, Query -from pydantic import Required - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: str = Query(default=Required, min_length=3)): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial006d_an.py b/docs_src/query_params_str_validations/tutorial006d_an.py deleted file mode 100644 index bc8283e15..000000000 --- a/docs_src/query_params_str_validations/tutorial006d_an.py +++ /dev/null @@ -1,13 +0,0 @@ -from fastapi import FastAPI, Query -from pydantic import Required -from typing_extensions import Annotated - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: Annotated[str, Query(min_length=3)] = Required): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial006d_an_py39.py b/docs_src/query_params_str_validations/tutorial006d_an_py39.py deleted file mode 100644 index 035d9e3bd..000000000 --- a/docs_src/query_params_str_validations/tutorial006d_an_py39.py +++ /dev/null @@ -1,14 +0,0 @@ -from typing import Annotated - -from fastapi import FastAPI, Query -from pydantic import Required - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: Annotated[str, Query(min_length=3)] = Required): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial007.py b/docs_src/query_params_str_validations/tutorial007.py index cb836569e..27b649e14 100644 --- a/docs_src/query_params_str_validations/tutorial007.py +++ b/docs_src/query_params_str_validations/tutorial007.py @@ -7,7 +7,7 @@ app = FastAPI() @app.get("/items/") async def read_items( - q: Union[str, None] = Query(default=None, title="Query string", min_length=3) + q: Union[str, None] = Query(default=None, title="Query string", min_length=3), ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial007_an.py b/docs_src/query_params_str_validations/tutorial007_an.py index 3bc85cc0c..4b3c8de4b 100644 --- a/docs_src/query_params_str_validations/tutorial007_an.py +++ b/docs_src/query_params_str_validations/tutorial007_an.py @@ -8,7 +8,7 @@ app = FastAPI() @app.get("/items/") async def read_items( - q: Annotated[Union[str, None], Query(title="Query string", min_length=3)] = None + q: Annotated[Union[str, None], Query(title="Query string", min_length=3)] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial007_an_py310.py b/docs_src/query_params_str_validations/tutorial007_an_py310.py index 5933911fd..ef18e500d 100644 --- a/docs_src/query_params_str_validations/tutorial007_an_py310.py +++ b/docs_src/query_params_str_validations/tutorial007_an_py310.py @@ -7,7 +7,7 @@ app = FastAPI() @app.get("/items/") async def read_items( - q: Annotated[str | None, Query(title="Query string", min_length=3)] = None + q: Annotated[str | None, Query(title="Query string", min_length=3)] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial007_an_py39.py b/docs_src/query_params_str_validations/tutorial007_an_py39.py index dafa1c5c9..8d7a82c46 100644 --- a/docs_src/query_params_str_validations/tutorial007_an_py39.py +++ b/docs_src/query_params_str_validations/tutorial007_an_py39.py @@ -7,7 +7,7 @@ app = FastAPI() @app.get("/items/") async def read_items( - q: Annotated[Union[str, None], Query(title="Query string", min_length=3)] = None + q: Annotated[Union[str, None], Query(title="Query string", min_length=3)] = None, ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial007_py310.py b/docs_src/query_params_str_validations/tutorial007_py310.py index e3e1ef2e0..c283576d5 100644 --- a/docs_src/query_params_str_validations/tutorial007_py310.py +++ b/docs_src/query_params_str_validations/tutorial007_py310.py @@ -5,7 +5,7 @@ app = FastAPI() @app.get("/items/") async def read_items( - q: str | None = Query(default=None, title="Query string", min_length=3) + q: str | None = Query(default=None, title="Query string", min_length=3), ): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: diff --git a/docs_src/query_params_str_validations/tutorial014.py b/docs_src/query_params_str_validations/tutorial014.py index 50e0a6c2b..779db1c80 100644 --- a/docs_src/query_params_str_validations/tutorial014.py +++ b/docs_src/query_params_str_validations/tutorial014.py @@ -7,7 +7,7 @@ app = FastAPI() @app.get("/items/") async def read_items( - hidden_query: Union[str, None] = Query(default=None, include_in_schema=False) + hidden_query: Union[str, None] = Query(default=None, include_in_schema=False), ): if hidden_query: return {"hidden_query": hidden_query} diff --git a/docs_src/query_params_str_validations/tutorial014_an.py b/docs_src/query_params_str_validations/tutorial014_an.py index a9a9c4427..2eaa58540 100644 --- a/docs_src/query_params_str_validations/tutorial014_an.py +++ b/docs_src/query_params_str_validations/tutorial014_an.py @@ -8,7 +8,7 @@ app = FastAPI() @app.get("/items/") async def read_items( - hidden_query: Annotated[Union[str, None], Query(include_in_schema=False)] = None + hidden_query: Annotated[Union[str, None], Query(include_in_schema=False)] = None, ): if hidden_query: return {"hidden_query": hidden_query} diff --git a/docs_src/query_params_str_validations/tutorial014_an_py310.py b/docs_src/query_params_str_validations/tutorial014_an_py310.py index 5fba54150..e728dbdb5 100644 --- a/docs_src/query_params_str_validations/tutorial014_an_py310.py +++ b/docs_src/query_params_str_validations/tutorial014_an_py310.py @@ -7,7 +7,7 @@ app = FastAPI() @app.get("/items/") async def read_items( - hidden_query: Annotated[str | None, Query(include_in_schema=False)] = None + hidden_query: Annotated[str | None, Query(include_in_schema=False)] = None, ): if hidden_query: return {"hidden_query": hidden_query} diff --git a/docs_src/query_params_str_validations/tutorial014_an_py39.py b/docs_src/query_params_str_validations/tutorial014_an_py39.py index b07985210..aaf7703a5 100644 --- a/docs_src/query_params_str_validations/tutorial014_an_py39.py +++ b/docs_src/query_params_str_validations/tutorial014_an_py39.py @@ -7,7 +7,7 @@ app = FastAPI() @app.get("/items/") async def read_items( - hidden_query: Annotated[Union[str, None], Query(include_in_schema=False)] = None + hidden_query: Annotated[Union[str, None], Query(include_in_schema=False)] = None, ): if hidden_query: return {"hidden_query": hidden_query} diff --git a/docs_src/query_params_str_validations/tutorial014_py310.py b/docs_src/query_params_str_validations/tutorial014_py310.py index 1b617efdd..97bb3386e 100644 --- a/docs_src/query_params_str_validations/tutorial014_py310.py +++ b/docs_src/query_params_str_validations/tutorial014_py310.py @@ -5,7 +5,7 @@ app = FastAPI() @app.get("/items/") async def read_items( - hidden_query: str | None = Query(default=None, include_in_schema=False) + hidden_query: str | None = Query(default=None, include_in_schema=False), ): if hidden_query: return {"hidden_query": hidden_query} diff --git a/docs_src/query_params_str_validations/tutorial015_an.py b/docs_src/query_params_str_validations/tutorial015_an.py new file mode 100644 index 000000000..f2ec6db12 --- /dev/null +++ b/docs_src/query_params_str_validations/tutorial015_an.py @@ -0,0 +1,31 @@ +import random +from typing import Union + +from fastapi import FastAPI +from pydantic import AfterValidator +from typing_extensions import Annotated + +app = FastAPI() + +data = { + "isbn-9781529046137": "The Hitchhiker's Guide to the Galaxy", + "imdb-tt0371724": "The Hitchhiker's Guide to the Galaxy", + "isbn-9781439512982": "Isaac Asimov: The Complete Stories, Vol. 2", +} + + +def check_valid_id(id: str): + if not id.startswith(("isbn-", "imdb-")): + raise ValueError('Invalid ID format, it must start with "isbn-" or "imdb-"') + return id + + +@app.get("/items/") +async def read_items( + id: Annotated[Union[str, None], AfterValidator(check_valid_id)] = None, +): + if id: + item = data.get(id) + else: + id, item = random.choice(list(data.items())) + return {"id": id, "name": item} diff --git a/docs_src/query_params_str_validations/tutorial015_an_py310.py b/docs_src/query_params_str_validations/tutorial015_an_py310.py new file mode 100644 index 000000000..35f368094 --- /dev/null +++ b/docs_src/query_params_str_validations/tutorial015_an_py310.py @@ -0,0 +1,30 @@ +import random +from typing import Annotated + +from fastapi import FastAPI +from pydantic import AfterValidator + +app = FastAPI() + +data = { + "isbn-9781529046137": "The Hitchhiker's Guide to the Galaxy", + "imdb-tt0371724": "The Hitchhiker's Guide to the Galaxy", + "isbn-9781439512982": "Isaac Asimov: The Complete Stories, Vol. 2", +} + + +def check_valid_id(id: str): + if not id.startswith(("isbn-", "imdb-")): + raise ValueError('Invalid ID format, it must start with "isbn-" or "imdb-"') + return id + + +@app.get("/items/") +async def read_items( + id: Annotated[str | None, AfterValidator(check_valid_id)] = None, +): + if id: + item = data.get(id) + else: + id, item = random.choice(list(data.items())) + return {"id": id, "name": item} diff --git a/docs_src/query_params_str_validations/tutorial015_an_py39.py b/docs_src/query_params_str_validations/tutorial015_an_py39.py new file mode 100644 index 000000000..989b6d2c2 --- /dev/null +++ b/docs_src/query_params_str_validations/tutorial015_an_py39.py @@ -0,0 +1,30 @@ +import random +from typing import Annotated, Union + +from fastapi import FastAPI +from pydantic import AfterValidator + +app = FastAPI() + +data = { + "isbn-9781529046137": "The Hitchhiker's Guide to the Galaxy", + "imdb-tt0371724": "The Hitchhiker's Guide to the Galaxy", + "isbn-9781439512982": "Isaac Asimov: The Complete Stories, Vol. 2", +} + + +def check_valid_id(id: str): + if not id.startswith(("isbn-", "imdb-")): + raise ValueError('Invalid ID format, it must start with "isbn-" or "imdb-"') + return id + + +@app.get("/items/") +async def read_items( + id: Annotated[Union[str, None], AfterValidator(check_valid_id)] = None, +): + if id: + item = data.get(id) + else: + id, item = random.choice(list(data.items())) + return {"id": id, "name": item} diff --git a/docs_src/request_form_models/tutorial001.py b/docs_src/request_form_models/tutorial001.py new file mode 100644 index 000000000..98feff0b9 --- /dev/null +++ b/docs_src/request_form_models/tutorial001.py @@ -0,0 +1,14 @@ +from fastapi import FastAPI, Form +from pydantic import BaseModel + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + + +@app.post("/login/") +async def login(data: FormData = Form()): + return data diff --git a/docs_src/request_form_models/tutorial001_an.py b/docs_src/request_form_models/tutorial001_an.py new file mode 100644 index 000000000..30483d445 --- /dev/null +++ b/docs_src/request_form_models/tutorial001_an.py @@ -0,0 +1,15 @@ +from fastapi import FastAPI, Form +from pydantic import BaseModel +from typing_extensions import Annotated + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + + +@app.post("/login/") +async def login(data: Annotated[FormData, Form()]): + return data diff --git a/docs_src/request_form_models/tutorial001_an_py39.py b/docs_src/request_form_models/tutorial001_an_py39.py new file mode 100644 index 000000000..7cc81aae9 --- /dev/null +++ b/docs_src/request_form_models/tutorial001_an_py39.py @@ -0,0 +1,16 @@ +from typing import Annotated + +from fastapi import FastAPI, Form +from pydantic import BaseModel + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + + +@app.post("/login/") +async def login(data: Annotated[FormData, Form()]): + return data diff --git a/docs_src/request_form_models/tutorial002.py b/docs_src/request_form_models/tutorial002.py new file mode 100644 index 000000000..59b329e8d --- /dev/null +++ b/docs_src/request_form_models/tutorial002.py @@ -0,0 +1,15 @@ +from fastapi import FastAPI, Form +from pydantic import BaseModel + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + model_config = {"extra": "forbid"} + + +@app.post("/login/") +async def login(data: FormData = Form()): + return data diff --git a/docs_src/request_form_models/tutorial002_an.py b/docs_src/request_form_models/tutorial002_an.py new file mode 100644 index 000000000..bcb022795 --- /dev/null +++ b/docs_src/request_form_models/tutorial002_an.py @@ -0,0 +1,16 @@ +from fastapi import FastAPI, Form +from pydantic import BaseModel +from typing_extensions import Annotated + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + model_config = {"extra": "forbid"} + + +@app.post("/login/") +async def login(data: Annotated[FormData, Form()]): + return data diff --git a/docs_src/request_form_models/tutorial002_an_py39.py b/docs_src/request_form_models/tutorial002_an_py39.py new file mode 100644 index 000000000..3004e0852 --- /dev/null +++ b/docs_src/request_form_models/tutorial002_an_py39.py @@ -0,0 +1,17 @@ +from typing import Annotated + +from fastapi import FastAPI, Form +from pydantic import BaseModel + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + model_config = {"extra": "forbid"} + + +@app.post("/login/") +async def login(data: Annotated[FormData, Form()]): + return data diff --git a/docs_src/request_form_models/tutorial002_pv1.py b/docs_src/request_form_models/tutorial002_pv1.py new file mode 100644 index 000000000..d5f7db2a6 --- /dev/null +++ b/docs_src/request_form_models/tutorial002_pv1.py @@ -0,0 +1,17 @@ +from fastapi import FastAPI, Form +from pydantic import BaseModel + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + + class Config: + extra = "forbid" + + +@app.post("/login/") +async def login(data: FormData = Form()): + return data diff --git a/docs_src/request_form_models/tutorial002_pv1_an.py b/docs_src/request_form_models/tutorial002_pv1_an.py new file mode 100644 index 000000000..fe9dbc344 --- /dev/null +++ b/docs_src/request_form_models/tutorial002_pv1_an.py @@ -0,0 +1,18 @@ +from fastapi import FastAPI, Form +from pydantic import BaseModel +from typing_extensions import Annotated + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + + class Config: + extra = "forbid" + + +@app.post("/login/") +async def login(data: Annotated[FormData, Form()]): + return data diff --git a/docs_src/request_form_models/tutorial002_pv1_an_py39.py b/docs_src/request_form_models/tutorial002_pv1_an_py39.py new file mode 100644 index 000000000..942d5d411 --- /dev/null +++ b/docs_src/request_form_models/tutorial002_pv1_an_py39.py @@ -0,0 +1,19 @@ +from typing import Annotated + +from fastapi import FastAPI, Form +from pydantic import BaseModel + +app = FastAPI() + + +class FormData(BaseModel): + username: str + password: str + + class Config: + extra = "forbid" + + +@app.post("/login/") +async def login(data: Annotated[FormData, Form()]): + return data diff --git a/docs_src/schema_extra_example/tutorial001_py310_pv1.py b/docs_src/schema_extra_example/tutorial001_pv1_py310.py similarity index 100% rename from docs_src/schema_extra_example/tutorial001_py310_pv1.py rename to docs_src/schema_extra_example/tutorial001_pv1_py310.py diff --git a/docs_src/security/tutorial003_an.py b/docs_src/security/tutorial003_an.py index 261cb4857..8fb40dd4a 100644 --- a/docs_src/security/tutorial003_an.py +++ b/docs_src/security/tutorial003_an.py @@ -68,7 +68,7 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): async def get_current_active_user( - current_user: Annotated[User, Depends(get_current_user)] + current_user: Annotated[User, Depends(get_current_user)], ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") @@ -90,6 +90,6 @@ async def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]): @app.get("/users/me") async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return current_user diff --git a/docs_src/security/tutorial003_an_py310.py b/docs_src/security/tutorial003_an_py310.py index a03f4f8bf..ced4a2fbc 100644 --- a/docs_src/security/tutorial003_an_py310.py +++ b/docs_src/security/tutorial003_an_py310.py @@ -67,7 +67,7 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): async def get_current_active_user( - current_user: Annotated[User, Depends(get_current_user)] + current_user: Annotated[User, Depends(get_current_user)], ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") @@ -89,6 +89,6 @@ async def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]): @app.get("/users/me") async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return current_user diff --git a/docs_src/security/tutorial003_an_py39.py b/docs_src/security/tutorial003_an_py39.py index 308dbe798..068a3933e 100644 --- a/docs_src/security/tutorial003_an_py39.py +++ b/docs_src/security/tutorial003_an_py39.py @@ -67,7 +67,7 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): async def get_current_active_user( - current_user: Annotated[User, Depends(get_current_user)] + current_user: Annotated[User, Depends(get_current_user)], ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") @@ -89,6 +89,6 @@ async def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]): @app.get("/users/me") async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return current_user diff --git a/docs_src/security/tutorial004.py b/docs_src/security/tutorial004.py index 044eec700..222589618 100644 --- a/docs_src/security/tutorial004.py +++ b/docs_src/security/tutorial004.py @@ -1,9 +1,10 @@ from datetime import datetime, timedelta, timezone from typing import Union +import jwt from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm -from jose import JWTError, jwt +from jwt.exceptions import InvalidTokenError from passlib.context import CryptContext from pydantic import BaseModel @@ -94,11 +95,11 @@ async def get_current_user(token: str = Depends(oauth2_scheme)): ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - username: str = payload.get("sub") + username = payload.get("sub") if username is None: raise credentials_exception token_data = TokenData(username=username) - except JWTError: + except InvalidTokenError: raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: @@ -114,7 +115,7 @@ async def get_current_active_user(current_user: User = Depends(get_current_user) @app.post("/token") async def login_for_access_token( - form_data: OAuth2PasswordRequestForm = Depends() + form_data: OAuth2PasswordRequestForm = Depends(), ) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: diff --git a/docs_src/security/tutorial004_an.py b/docs_src/security/tutorial004_an.py index c78e8496c..e2221cd39 100644 --- a/docs_src/security/tutorial004_an.py +++ b/docs_src/security/tutorial004_an.py @@ -1,9 +1,10 @@ from datetime import datetime, timedelta, timezone from typing import Union +import jwt from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm -from jose import JWTError, jwt +from jwt.exceptions import InvalidTokenError from passlib.context import CryptContext from pydantic import BaseModel from typing_extensions import Annotated @@ -95,11 +96,11 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - username: str = payload.get("sub") + username = payload.get("sub") if username is None: raise credentials_exception token_data = TokenData(username=username) - except JWTError: + except InvalidTokenError: raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: @@ -108,7 +109,7 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): async def get_current_active_user( - current_user: Annotated[User, Depends(get_current_user)] + current_user: Annotated[User, Depends(get_current_user)], ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") @@ -117,7 +118,7 @@ async def get_current_active_user( @app.post("/token") async def login_for_access_token( - form_data: Annotated[OAuth2PasswordRequestForm, Depends()] + form_data: Annotated[OAuth2PasswordRequestForm, Depends()], ) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: @@ -135,13 +136,13 @@ async def login_for_access_token( @app.get("/users/me/", response_model=User) async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return current_user @app.get("/users/me/items/") async def read_own_items( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return [{"item_id": "Foo", "owner": current_user.username}] diff --git a/docs_src/security/tutorial004_an_py310.py b/docs_src/security/tutorial004_an_py310.py index 36dbc677e..a3f74fc0e 100644 --- a/docs_src/security/tutorial004_an_py310.py +++ b/docs_src/security/tutorial004_an_py310.py @@ -1,9 +1,10 @@ from datetime import datetime, timedelta, timezone from typing import Annotated +import jwt from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm -from jose import JWTError, jwt +from jwt.exceptions import InvalidTokenError from passlib.context import CryptContext from pydantic import BaseModel @@ -94,11 +95,11 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - username: str = payload.get("sub") + username = payload.get("sub") if username is None: raise credentials_exception token_data = TokenData(username=username) - except JWTError: + except InvalidTokenError: raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: @@ -107,7 +108,7 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): async def get_current_active_user( - current_user: Annotated[User, Depends(get_current_user)] + current_user: Annotated[User, Depends(get_current_user)], ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") @@ -116,7 +117,7 @@ async def get_current_active_user( @app.post("/token") async def login_for_access_token( - form_data: Annotated[OAuth2PasswordRequestForm, Depends()] + form_data: Annotated[OAuth2PasswordRequestForm, Depends()], ) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: @@ -134,13 +135,13 @@ async def login_for_access_token( @app.get("/users/me/", response_model=User) async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return current_user @app.get("/users/me/items/") async def read_own_items( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return [{"item_id": "Foo", "owner": current_user.username}] diff --git a/docs_src/security/tutorial004_an_py39.py b/docs_src/security/tutorial004_an_py39.py index 23fc04a72..b33d677ed 100644 --- a/docs_src/security/tutorial004_an_py39.py +++ b/docs_src/security/tutorial004_an_py39.py @@ -1,9 +1,10 @@ from datetime import datetime, timedelta, timezone from typing import Annotated, Union +import jwt from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm -from jose import JWTError, jwt +from jwt.exceptions import InvalidTokenError from passlib.context import CryptContext from pydantic import BaseModel @@ -94,11 +95,11 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - username: str = payload.get("sub") + username = payload.get("sub") if username is None: raise credentials_exception token_data = TokenData(username=username) - except JWTError: + except InvalidTokenError: raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: @@ -107,7 +108,7 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): async def get_current_active_user( - current_user: Annotated[User, Depends(get_current_user)] + current_user: Annotated[User, Depends(get_current_user)], ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") @@ -116,7 +117,7 @@ async def get_current_active_user( @app.post("/token") async def login_for_access_token( - form_data: Annotated[OAuth2PasswordRequestForm, Depends()] + form_data: Annotated[OAuth2PasswordRequestForm, Depends()], ) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: @@ -134,13 +135,13 @@ async def login_for_access_token( @app.get("/users/me/", response_model=User) async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return current_user @app.get("/users/me/items/") async def read_own_items( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return [{"item_id": "Foo", "owner": current_user.username}] diff --git a/docs_src/security/tutorial004_py310.py b/docs_src/security/tutorial004_py310.py index 8363d45ab..d46ce26bf 100644 --- a/docs_src/security/tutorial004_py310.py +++ b/docs_src/security/tutorial004_py310.py @@ -1,8 +1,9 @@ from datetime import datetime, timedelta, timezone +import jwt from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm -from jose import JWTError, jwt +from jwt.exceptions import InvalidTokenError from passlib.context import CryptContext from pydantic import BaseModel @@ -93,11 +94,11 @@ async def get_current_user(token: str = Depends(oauth2_scheme)): ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - username: str = payload.get("sub") + username = payload.get("sub") if username is None: raise credentials_exception token_data = TokenData(username=username) - except JWTError: + except InvalidTokenError: raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: @@ -113,7 +114,7 @@ async def get_current_active_user(current_user: User = Depends(get_current_user) @app.post("/token") async def login_for_access_token( - form_data: OAuth2PasswordRequestForm = Depends() + form_data: OAuth2PasswordRequestForm = Depends(), ) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: diff --git a/docs_src/security/tutorial005.py b/docs_src/security/tutorial005.py index b16bf440a..ccad07969 100644 --- a/docs_src/security/tutorial005.py +++ b/docs_src/security/tutorial005.py @@ -1,13 +1,14 @@ from datetime import datetime, timedelta, timezone from typing import List, Union +import jwt from fastapi import Depends, FastAPI, HTTPException, Security, status from fastapi.security import ( OAuth2PasswordBearer, OAuth2PasswordRequestForm, SecurityScopes, ) -from jose import JWTError, jwt +from jwt.exceptions import InvalidTokenError from passlib.context import CryptContext from pydantic import BaseModel, ValidationError @@ -120,7 +121,7 @@ async def get_current_user( raise credentials_exception token_scopes = payload.get("scopes", []) token_data = TokenData(scopes=token_scopes, username=username) - except (JWTError, ValidationError): + except (InvalidTokenError, ValidationError): raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: @@ -136,7 +137,7 @@ async def get_current_user( async def get_current_active_user( - current_user: User = Security(get_current_user, scopes=["me"]) + current_user: User = Security(get_current_user, scopes=["me"]), ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") @@ -145,7 +146,7 @@ async def get_current_active_user( @app.post("/token") async def login_for_access_token( - form_data: OAuth2PasswordRequestForm = Depends() + form_data: OAuth2PasswordRequestForm = Depends(), ) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: @@ -165,7 +166,7 @@ async def read_users_me(current_user: User = Depends(get_current_active_user)): @app.get("/users/me/items/") async def read_own_items( - current_user: User = Security(get_current_active_user, scopes=["items"]) + current_user: User = Security(get_current_active_user, scopes=["items"]), ): return [{"item_id": "Foo", "owner": current_user.username}] diff --git a/docs_src/security/tutorial005_an.py b/docs_src/security/tutorial005_an.py index 95e406b32..2e8bb3bdb 100644 --- a/docs_src/security/tutorial005_an.py +++ b/docs_src/security/tutorial005_an.py @@ -1,13 +1,14 @@ from datetime import datetime, timedelta, timezone from typing import List, Union +import jwt from fastapi import Depends, FastAPI, HTTPException, Security, status from fastapi.security import ( OAuth2PasswordBearer, OAuth2PasswordRequestForm, SecurityScopes, ) -from jose import JWTError, jwt +from jwt.exceptions import InvalidTokenError from passlib.context import CryptContext from pydantic import BaseModel, ValidationError from typing_extensions import Annotated @@ -116,12 +117,12 @@ async def get_current_user( ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - username: str = payload.get("sub") + username = payload.get("sub") if username is None: raise credentials_exception token_scopes = payload.get("scopes", []) token_data = TokenData(scopes=token_scopes, username=username) - except (JWTError, ValidationError): + except (InvalidTokenError, ValidationError): raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: @@ -137,7 +138,7 @@ async def get_current_user( async def get_current_active_user( - current_user: Annotated[User, Security(get_current_user, scopes=["me"])] + current_user: Annotated[User, Security(get_current_user, scopes=["me"])], ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") @@ -146,7 +147,7 @@ async def get_current_active_user( @app.post("/token") async def login_for_access_token( - form_data: Annotated[OAuth2PasswordRequestForm, Depends()] + form_data: Annotated[OAuth2PasswordRequestForm, Depends()], ) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: @@ -161,14 +162,14 @@ async def login_for_access_token( @app.get("/users/me/", response_model=User) async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return current_user @app.get("/users/me/items/") async def read_own_items( - current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])] + current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])], ): return [{"item_id": "Foo", "owner": current_user.username}] diff --git a/docs_src/security/tutorial005_an_py310.py b/docs_src/security/tutorial005_an_py310.py index c6116a5ed..90781587f 100644 --- a/docs_src/security/tutorial005_an_py310.py +++ b/docs_src/security/tutorial005_an_py310.py @@ -1,13 +1,14 @@ from datetime import datetime, timedelta, timezone from typing import Annotated +import jwt from fastapi import Depends, FastAPI, HTTPException, Security, status from fastapi.security import ( OAuth2PasswordBearer, OAuth2PasswordRequestForm, SecurityScopes, ) -from jose import JWTError, jwt +from jwt.exceptions import InvalidTokenError from passlib.context import CryptContext from pydantic import BaseModel, ValidationError @@ -115,12 +116,12 @@ async def get_current_user( ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - username: str = payload.get("sub") + username = payload.get("sub") if username is None: raise credentials_exception token_scopes = payload.get("scopes", []) token_data = TokenData(scopes=token_scopes, username=username) - except (JWTError, ValidationError): + except (InvalidTokenError, ValidationError): raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: @@ -136,7 +137,7 @@ async def get_current_user( async def get_current_active_user( - current_user: Annotated[User, Security(get_current_user, scopes=["me"])] + current_user: Annotated[User, Security(get_current_user, scopes=["me"])], ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") @@ -145,7 +146,7 @@ async def get_current_active_user( @app.post("/token") async def login_for_access_token( - form_data: Annotated[OAuth2PasswordRequestForm, Depends()] + form_data: Annotated[OAuth2PasswordRequestForm, Depends()], ) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: @@ -160,14 +161,14 @@ async def login_for_access_token( @app.get("/users/me/", response_model=User) async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return current_user @app.get("/users/me/items/") async def read_own_items( - current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])] + current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])], ): return [{"item_id": "Foo", "owner": current_user.username}] diff --git a/docs_src/security/tutorial005_an_py39.py b/docs_src/security/tutorial005_an_py39.py index af51c08b5..a5192d8d6 100644 --- a/docs_src/security/tutorial005_an_py39.py +++ b/docs_src/security/tutorial005_an_py39.py @@ -1,13 +1,14 @@ from datetime import datetime, timedelta, timezone -from typing import Annotated, List, Union +from typing import Annotated, Union +import jwt from fastapi import Depends, FastAPI, HTTPException, Security, status from fastapi.security import ( OAuth2PasswordBearer, OAuth2PasswordRequestForm, SecurityScopes, ) -from jose import JWTError, jwt +from jwt.exceptions import InvalidTokenError from passlib.context import CryptContext from pydantic import BaseModel, ValidationError @@ -43,7 +44,7 @@ class Token(BaseModel): class TokenData(BaseModel): username: Union[str, None] = None - scopes: List[str] = [] + scopes: list[str] = [] class User(BaseModel): @@ -115,12 +116,12 @@ async def get_current_user( ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - username: str = payload.get("sub") + username = payload.get("sub") if username is None: raise credentials_exception token_scopes = payload.get("scopes", []) token_data = TokenData(scopes=token_scopes, username=username) - except (JWTError, ValidationError): + except (InvalidTokenError, ValidationError): raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: @@ -136,7 +137,7 @@ async def get_current_user( async def get_current_active_user( - current_user: Annotated[User, Security(get_current_user, scopes=["me"])] + current_user: Annotated[User, Security(get_current_user, scopes=["me"])], ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") @@ -145,7 +146,7 @@ async def get_current_active_user( @app.post("/token") async def login_for_access_token( - form_data: Annotated[OAuth2PasswordRequestForm, Depends()] + form_data: Annotated[OAuth2PasswordRequestForm, Depends()], ) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: @@ -160,14 +161,14 @@ async def login_for_access_token( @app.get("/users/me/", response_model=User) async def read_users_me( - current_user: Annotated[User, Depends(get_current_active_user)] + current_user: Annotated[User, Depends(get_current_active_user)], ): return current_user @app.get("/users/me/items/") async def read_own_items( - current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])] + current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])], ): return [{"item_id": "Foo", "owner": current_user.username}] diff --git a/docs_src/security/tutorial005_py310.py b/docs_src/security/tutorial005_py310.py index 37a22c709..b244ef08e 100644 --- a/docs_src/security/tutorial005_py310.py +++ b/docs_src/security/tutorial005_py310.py @@ -1,12 +1,13 @@ from datetime import datetime, timedelta, timezone +import jwt from fastapi import Depends, FastAPI, HTTPException, Security, status from fastapi.security import ( OAuth2PasswordBearer, OAuth2PasswordRequestForm, SecurityScopes, ) -from jose import JWTError, jwt +from jwt.exceptions import InvalidTokenError from passlib.context import CryptContext from pydantic import BaseModel, ValidationError @@ -119,7 +120,7 @@ async def get_current_user( raise credentials_exception token_scopes = payload.get("scopes", []) token_data = TokenData(scopes=token_scopes, username=username) - except (JWTError, ValidationError): + except (InvalidTokenError, ValidationError): raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: @@ -135,7 +136,7 @@ async def get_current_user( async def get_current_active_user( - current_user: User = Security(get_current_user, scopes=["me"]) + current_user: User = Security(get_current_user, scopes=["me"]), ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") @@ -144,7 +145,7 @@ async def get_current_active_user( @app.post("/token") async def login_for_access_token( - form_data: OAuth2PasswordRequestForm = Depends() + form_data: OAuth2PasswordRequestForm = Depends(), ) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: @@ -164,7 +165,7 @@ async def read_users_me(current_user: User = Depends(get_current_active_user)): @app.get("/users/me/items/") async def read_own_items( - current_user: User = Security(get_current_active_user, scopes=["items"]) + current_user: User = Security(get_current_active_user, scopes=["items"]), ): return [{"item_id": "Foo", "owner": current_user.username}] diff --git a/docs_src/security/tutorial005_py39.py b/docs_src/security/tutorial005_py39.py index c27580763..8f0e93376 100644 --- a/docs_src/security/tutorial005_py39.py +++ b/docs_src/security/tutorial005_py39.py @@ -1,13 +1,14 @@ from datetime import datetime, timedelta, timezone from typing import Union +import jwt from fastapi import Depends, FastAPI, HTTPException, Security, status from fastapi.security import ( OAuth2PasswordBearer, OAuth2PasswordRequestForm, SecurityScopes, ) -from jose import JWTError, jwt +from jwt.exceptions import InvalidTokenError from passlib.context import CryptContext from pydantic import BaseModel, ValidationError @@ -120,7 +121,7 @@ async def get_current_user( raise credentials_exception token_scopes = payload.get("scopes", []) token_data = TokenData(scopes=token_scopes, username=username) - except (JWTError, ValidationError): + except (InvalidTokenError, ValidationError): raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: @@ -136,7 +137,7 @@ async def get_current_user( async def get_current_active_user( - current_user: User = Security(get_current_user, scopes=["me"]) + current_user: User = Security(get_current_user, scopes=["me"]), ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") @@ -145,7 +146,7 @@ async def get_current_active_user( @app.post("/token") async def login_for_access_token( - form_data: OAuth2PasswordRequestForm = Depends() + form_data: OAuth2PasswordRequestForm = Depends(), ) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: @@ -165,7 +166,7 @@ async def read_users_me(current_user: User = Depends(get_current_active_user)): @app.get("/users/me/items/") async def read_own_items( - current_user: User = Security(get_current_active_user, scopes=["items"]) + current_user: User = Security(get_current_active_user, scopes=["items"]), ): return [{"item_id": "Foo", "owner": current_user.username}] diff --git a/docs_src/security/tutorial007_an.py b/docs_src/security/tutorial007_an.py index 9e9c3cd70..0d211dfde 100644 --- a/docs_src/security/tutorial007_an.py +++ b/docs_src/security/tutorial007_an.py @@ -10,7 +10,7 @@ security = HTTPBasic() def get_current_username( - credentials: Annotated[HTTPBasicCredentials, Depends(security)] + credentials: Annotated[HTTPBasicCredentials, Depends(security)], ): current_username_bytes = credentials.username.encode("utf8") correct_username_bytes = b"stanleyjobson" diff --git a/docs_src/security/tutorial007_an_py39.py b/docs_src/security/tutorial007_an_py39.py index 3d9ea2726..87ef98657 100644 --- a/docs_src/security/tutorial007_an_py39.py +++ b/docs_src/security/tutorial007_an_py39.py @@ -10,7 +10,7 @@ security = HTTPBasic() def get_current_username( - credentials: Annotated[HTTPBasicCredentials, Depends(security)] + credentials: Annotated[HTTPBasicCredentials, Depends(security)], ): current_username_bytes = credentials.username.encode("utf8") correct_username_bytes = b"stanleyjobson" diff --git a/docs_src/sql_databases/sql_app/alt_main.py b/docs_src/sql_databases/sql_app/alt_main.py deleted file mode 100644 index f7206bcb4..000000000 --- a/docs_src/sql_databases/sql_app/alt_main.py +++ /dev/null @@ -1,62 +0,0 @@ -from typing import List - -from fastapi import Depends, FastAPI, HTTPException, Request, Response -from sqlalchemy.orm import Session - -from . import crud, models, schemas -from .database import SessionLocal, engine - -models.Base.metadata.create_all(bind=engine) - -app = FastAPI() - - -@app.middleware("http") -async def db_session_middleware(request: Request, call_next): - response = Response("Internal server error", status_code=500) - try: - request.state.db = SessionLocal() - response = await call_next(request) - finally: - request.state.db.close() - return response - - -# Dependency -def get_db(request: Request): - return request.state.db - - -@app.post("/users/", response_model=schemas.User) -def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): - db_user = crud.get_user_by_email(db, email=user.email) - if db_user: - raise HTTPException(status_code=400, detail="Email already registered") - return crud.create_user(db=db, user=user) - - -@app.get("/users/", response_model=List[schemas.User]) -def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - users = crud.get_users(db, skip=skip, limit=limit) - return users - - -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - if db_user is None: - raise HTTPException(status_code=404, detail="User not found") - return db_user - - -@app.post("/users/{user_id}/items/", response_model=schemas.Item) -def create_item_for_user( - user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) -): - return crud.create_user_item(db=db, item=item, user_id=user_id) - - -@app.get("/items/", response_model=List[schemas.Item]) -def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - items = crud.get_items(db, skip=skip, limit=limit) - return items diff --git a/docs_src/sql_databases/sql_app/crud.py b/docs_src/sql_databases/sql_app/crud.py deleted file mode 100644 index 679acdb5c..000000000 --- a/docs_src/sql_databases/sql_app/crud.py +++ /dev/null @@ -1,36 +0,0 @@ -from sqlalchemy.orm import Session - -from . import models, schemas - - -def get_user(db: Session, user_id: int): - return db.query(models.User).filter(models.User.id == user_id).first() - - -def get_user_by_email(db: Session, email: str): - return db.query(models.User).filter(models.User.email == email).first() - - -def get_users(db: Session, skip: int = 0, limit: int = 100): - return db.query(models.User).offset(skip).limit(limit).all() - - -def create_user(db: Session, user: schemas.UserCreate): - fake_hashed_password = user.password + "notreallyhashed" - db_user = models.User(email=user.email, hashed_password=fake_hashed_password) - db.add(db_user) - db.commit() - db.refresh(db_user) - return db_user - - -def get_items(db: Session, skip: int = 0, limit: int = 100): - return db.query(models.Item).offset(skip).limit(limit).all() - - -def create_user_item(db: Session, item: schemas.ItemCreate, user_id: int): - db_item = models.Item(**item.dict(), owner_id=user_id) - db.add(db_item) - db.commit() - db.refresh(db_item) - return db_item diff --git a/docs_src/sql_databases/sql_app/database.py b/docs_src/sql_databases/sql_app/database.py deleted file mode 100644 index 45a8b9f69..000000000 --- a/docs_src/sql_databases/sql_app/database.py +++ /dev/null @@ -1,13 +0,0 @@ -from sqlalchemy import create_engine -from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.orm import sessionmaker - -SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db" -# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" - -engine = create_engine( - SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} -) -SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) - -Base = declarative_base() diff --git a/docs_src/sql_databases/sql_app/main.py b/docs_src/sql_databases/sql_app/main.py deleted file mode 100644 index e7508c59d..000000000 --- a/docs_src/sql_databases/sql_app/main.py +++ /dev/null @@ -1,55 +0,0 @@ -from typing import List - -from fastapi import Depends, FastAPI, HTTPException -from sqlalchemy.orm import Session - -from . import crud, models, schemas -from .database import SessionLocal, engine - -models.Base.metadata.create_all(bind=engine) - -app = FastAPI() - - -# Dependency -def get_db(): - db = SessionLocal() - try: - yield db - finally: - db.close() - - -@app.post("/users/", response_model=schemas.User) -def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): - db_user = crud.get_user_by_email(db, email=user.email) - if db_user: - raise HTTPException(status_code=400, detail="Email already registered") - return crud.create_user(db=db, user=user) - - -@app.get("/users/", response_model=List[schemas.User]) -def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - users = crud.get_users(db, skip=skip, limit=limit) - return users - - -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - if db_user is None: - raise HTTPException(status_code=404, detail="User not found") - return db_user - - -@app.post("/users/{user_id}/items/", response_model=schemas.Item) -def create_item_for_user( - user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) -): - return crud.create_user_item(db=db, item=item, user_id=user_id) - - -@app.get("/items/", response_model=List[schemas.Item]) -def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - items = crud.get_items(db, skip=skip, limit=limit) - return items diff --git a/docs_src/sql_databases/sql_app/models.py b/docs_src/sql_databases/sql_app/models.py deleted file mode 100644 index 09ae2a807..000000000 --- a/docs_src/sql_databases/sql_app/models.py +++ /dev/null @@ -1,26 +0,0 @@ -from sqlalchemy import Boolean, Column, ForeignKey, Integer, String -from sqlalchemy.orm import relationship - -from .database import Base - - -class User(Base): - __tablename__ = "users" - - id = Column(Integer, primary_key=True) - email = Column(String, unique=True, index=True) - hashed_password = Column(String) - is_active = Column(Boolean, default=True) - - items = relationship("Item", back_populates="owner") - - -class Item(Base): - __tablename__ = "items" - - id = Column(Integer, primary_key=True) - title = Column(String, index=True) - description = Column(String, index=True) - owner_id = Column(Integer, ForeignKey("users.id")) - - owner = relationship("User", back_populates="items") diff --git a/docs_src/sql_databases/sql_app/schemas.py b/docs_src/sql_databases/sql_app/schemas.py deleted file mode 100644 index c49beba88..000000000 --- a/docs_src/sql_databases/sql_app/schemas.py +++ /dev/null @@ -1,37 +0,0 @@ -from typing import List, Union - -from pydantic import BaseModel - - -class ItemBase(BaseModel): - title: str - description: Union[str, None] = None - - -class ItemCreate(ItemBase): - pass - - -class Item(ItemBase): - id: int - owner_id: int - - class Config: - orm_mode = True - - -class UserBase(BaseModel): - email: str - - -class UserCreate(UserBase): - password: str - - -class User(UserBase): - id: int - is_active: bool - items: List[Item] = [] - - class Config: - orm_mode = True diff --git a/docs_src/sql_databases/sql_app/tests/test_sql_app.py b/docs_src/sql_databases/sql_app/tests/test_sql_app.py deleted file mode 100644 index 5f55add0a..000000000 --- a/docs_src/sql_databases/sql_app/tests/test_sql_app.py +++ /dev/null @@ -1,50 +0,0 @@ -from fastapi.testclient import TestClient -from sqlalchemy import create_engine -from sqlalchemy.orm import sessionmaker -from sqlalchemy.pool import StaticPool - -from ..database import Base -from ..main import app, get_db - -SQLALCHEMY_DATABASE_URL = "sqlite://" - -engine = create_engine( - SQLALCHEMY_DATABASE_URL, - connect_args={"check_same_thread": False}, - poolclass=StaticPool, -) -TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) - - -Base.metadata.create_all(bind=engine) - - -def override_get_db(): - try: - db = TestingSessionLocal() - yield db - finally: - db.close() - - -app.dependency_overrides[get_db] = override_get_db - -client = TestClient(app) - - -def test_create_user(): - response = client.post( - "/users/", - json={"email": "deadpool@example.com", "password": "chimichangas4life"}, - ) - assert response.status_code == 200, response.text - data = response.json() - assert data["email"] == "deadpool@example.com" - assert "id" in data - user_id = data["id"] - - response = client.get(f"/users/{user_id}") - assert response.status_code == 200, response.text - data = response.json() - assert data["email"] == "deadpool@example.com" - assert data["id"] == user_id diff --git a/docs_src/sql_databases/sql_app_py310/alt_main.py b/docs_src/sql_databases/sql_app_py310/alt_main.py deleted file mode 100644 index 5de88ec3a..000000000 --- a/docs_src/sql_databases/sql_app_py310/alt_main.py +++ /dev/null @@ -1,60 +0,0 @@ -from fastapi import Depends, FastAPI, HTTPException, Request, Response -from sqlalchemy.orm import Session - -from . import crud, models, schemas -from .database import SessionLocal, engine - -models.Base.metadata.create_all(bind=engine) - -app = FastAPI() - - -@app.middleware("http") -async def db_session_middleware(request: Request, call_next): - response = Response("Internal server error", status_code=500) - try: - request.state.db = SessionLocal() - response = await call_next(request) - finally: - request.state.db.close() - return response - - -# Dependency -def get_db(request: Request): - return request.state.db - - -@app.post("/users/", response_model=schemas.User) -def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): - db_user = crud.get_user_by_email(db, email=user.email) - if db_user: - raise HTTPException(status_code=400, detail="Email already registered") - return crud.create_user(db=db, user=user) - - -@app.get("/users/", response_model=list[schemas.User]) -def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - users = crud.get_users(db, skip=skip, limit=limit) - return users - - -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - if db_user is None: - raise HTTPException(status_code=404, detail="User not found") - return db_user - - -@app.post("/users/{user_id}/items/", response_model=schemas.Item) -def create_item_for_user( - user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) -): - return crud.create_user_item(db=db, item=item, user_id=user_id) - - -@app.get("/items/", response_model=list[schemas.Item]) -def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - items = crud.get_items(db, skip=skip, limit=limit) - return items diff --git a/docs_src/sql_databases/sql_app_py310/crud.py b/docs_src/sql_databases/sql_app_py310/crud.py deleted file mode 100644 index 679acdb5c..000000000 --- a/docs_src/sql_databases/sql_app_py310/crud.py +++ /dev/null @@ -1,36 +0,0 @@ -from sqlalchemy.orm import Session - -from . import models, schemas - - -def get_user(db: Session, user_id: int): - return db.query(models.User).filter(models.User.id == user_id).first() - - -def get_user_by_email(db: Session, email: str): - return db.query(models.User).filter(models.User.email == email).first() - - -def get_users(db: Session, skip: int = 0, limit: int = 100): - return db.query(models.User).offset(skip).limit(limit).all() - - -def create_user(db: Session, user: schemas.UserCreate): - fake_hashed_password = user.password + "notreallyhashed" - db_user = models.User(email=user.email, hashed_password=fake_hashed_password) - db.add(db_user) - db.commit() - db.refresh(db_user) - return db_user - - -def get_items(db: Session, skip: int = 0, limit: int = 100): - return db.query(models.Item).offset(skip).limit(limit).all() - - -def create_user_item(db: Session, item: schemas.ItemCreate, user_id: int): - db_item = models.Item(**item.dict(), owner_id=user_id) - db.add(db_item) - db.commit() - db.refresh(db_item) - return db_item diff --git a/docs_src/sql_databases/sql_app_py310/database.py b/docs_src/sql_databases/sql_app_py310/database.py deleted file mode 100644 index 45a8b9f69..000000000 --- a/docs_src/sql_databases/sql_app_py310/database.py +++ /dev/null @@ -1,13 +0,0 @@ -from sqlalchemy import create_engine -from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.orm import sessionmaker - -SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db" -# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" - -engine = create_engine( - SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} -) -SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) - -Base = declarative_base() diff --git a/docs_src/sql_databases/sql_app_py310/main.py b/docs_src/sql_databases/sql_app_py310/main.py deleted file mode 100644 index a9856d0b6..000000000 --- a/docs_src/sql_databases/sql_app_py310/main.py +++ /dev/null @@ -1,53 +0,0 @@ -from fastapi import Depends, FastAPI, HTTPException -from sqlalchemy.orm import Session - -from . import crud, models, schemas -from .database import SessionLocal, engine - -models.Base.metadata.create_all(bind=engine) - -app = FastAPI() - - -# Dependency -def get_db(): - db = SessionLocal() - try: - yield db - finally: - db.close() - - -@app.post("/users/", response_model=schemas.User) -def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): - db_user = crud.get_user_by_email(db, email=user.email) - if db_user: - raise HTTPException(status_code=400, detail="Email already registered") - return crud.create_user(db=db, user=user) - - -@app.get("/users/", response_model=list[schemas.User]) -def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - users = crud.get_users(db, skip=skip, limit=limit) - return users - - -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - if db_user is None: - raise HTTPException(status_code=404, detail="User not found") - return db_user - - -@app.post("/users/{user_id}/items/", response_model=schemas.Item) -def create_item_for_user( - user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) -): - return crud.create_user_item(db=db, item=item, user_id=user_id) - - -@app.get("/items/", response_model=list[schemas.Item]) -def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - items = crud.get_items(db, skip=skip, limit=limit) - return items diff --git a/docs_src/sql_databases/sql_app_py310/models.py b/docs_src/sql_databases/sql_app_py310/models.py deleted file mode 100644 index 09ae2a807..000000000 --- a/docs_src/sql_databases/sql_app_py310/models.py +++ /dev/null @@ -1,26 +0,0 @@ -from sqlalchemy import Boolean, Column, ForeignKey, Integer, String -from sqlalchemy.orm import relationship - -from .database import Base - - -class User(Base): - __tablename__ = "users" - - id = Column(Integer, primary_key=True) - email = Column(String, unique=True, index=True) - hashed_password = Column(String) - is_active = Column(Boolean, default=True) - - items = relationship("Item", back_populates="owner") - - -class Item(Base): - __tablename__ = "items" - - id = Column(Integer, primary_key=True) - title = Column(String, index=True) - description = Column(String, index=True) - owner_id = Column(Integer, ForeignKey("users.id")) - - owner = relationship("User", back_populates="items") diff --git a/docs_src/sql_databases/sql_app_py310/schemas.py b/docs_src/sql_databases/sql_app_py310/schemas.py deleted file mode 100644 index aea2e3f10..000000000 --- a/docs_src/sql_databases/sql_app_py310/schemas.py +++ /dev/null @@ -1,35 +0,0 @@ -from pydantic import BaseModel - - -class ItemBase(BaseModel): - title: str - description: str | None = None - - -class ItemCreate(ItemBase): - pass - - -class Item(ItemBase): - id: int - owner_id: int - - class Config: - orm_mode = True - - -class UserBase(BaseModel): - email: str - - -class UserCreate(UserBase): - password: str - - -class User(UserBase): - id: int - is_active: bool - items: list[Item] = [] - - class Config: - orm_mode = True diff --git a/docs_src/sql_databases/sql_app_py310/tests/test_sql_app.py b/docs_src/sql_databases/sql_app_py310/tests/test_sql_app.py deleted file mode 100644 index c60c3356f..000000000 --- a/docs_src/sql_databases/sql_app_py310/tests/test_sql_app.py +++ /dev/null @@ -1,47 +0,0 @@ -from fastapi.testclient import TestClient -from sqlalchemy import create_engine -from sqlalchemy.orm import sessionmaker - -from ..database import Base -from ..main import app, get_db - -SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db" - -engine = create_engine( - SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} -) -TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) - - -Base.metadata.create_all(bind=engine) - - -def override_get_db(): - try: - db = TestingSessionLocal() - yield db - finally: - db.close() - - -app.dependency_overrides[get_db] = override_get_db - -client = TestClient(app) - - -def test_create_user(): - response = client.post( - "/users/", - json={"email": "deadpool@example.com", "password": "chimichangas4life"}, - ) - assert response.status_code == 200, response.text - data = response.json() - assert data["email"] == "deadpool@example.com" - assert "id" in data - user_id = data["id"] - - response = client.get(f"/users/{user_id}") - assert response.status_code == 200, response.text - data = response.json() - assert data["email"] == "deadpool@example.com" - assert data["id"] == user_id diff --git a/docs_src/sql_databases/sql_app_py39/__init__.py b/docs_src/sql_databases/sql_app_py39/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/docs_src/sql_databases/sql_app_py39/alt_main.py b/docs_src/sql_databases/sql_app_py39/alt_main.py deleted file mode 100644 index 5de88ec3a..000000000 --- a/docs_src/sql_databases/sql_app_py39/alt_main.py +++ /dev/null @@ -1,60 +0,0 @@ -from fastapi import Depends, FastAPI, HTTPException, Request, Response -from sqlalchemy.orm import Session - -from . import crud, models, schemas -from .database import SessionLocal, engine - -models.Base.metadata.create_all(bind=engine) - -app = FastAPI() - - -@app.middleware("http") -async def db_session_middleware(request: Request, call_next): - response = Response("Internal server error", status_code=500) - try: - request.state.db = SessionLocal() - response = await call_next(request) - finally: - request.state.db.close() - return response - - -# Dependency -def get_db(request: Request): - return request.state.db - - -@app.post("/users/", response_model=schemas.User) -def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): - db_user = crud.get_user_by_email(db, email=user.email) - if db_user: - raise HTTPException(status_code=400, detail="Email already registered") - return crud.create_user(db=db, user=user) - - -@app.get("/users/", response_model=list[schemas.User]) -def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - users = crud.get_users(db, skip=skip, limit=limit) - return users - - -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - if db_user is None: - raise HTTPException(status_code=404, detail="User not found") - return db_user - - -@app.post("/users/{user_id}/items/", response_model=schemas.Item) -def create_item_for_user( - user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) -): - return crud.create_user_item(db=db, item=item, user_id=user_id) - - -@app.get("/items/", response_model=list[schemas.Item]) -def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - items = crud.get_items(db, skip=skip, limit=limit) - return items diff --git a/docs_src/sql_databases/sql_app_py39/crud.py b/docs_src/sql_databases/sql_app_py39/crud.py deleted file mode 100644 index 679acdb5c..000000000 --- a/docs_src/sql_databases/sql_app_py39/crud.py +++ /dev/null @@ -1,36 +0,0 @@ -from sqlalchemy.orm import Session - -from . import models, schemas - - -def get_user(db: Session, user_id: int): - return db.query(models.User).filter(models.User.id == user_id).first() - - -def get_user_by_email(db: Session, email: str): - return db.query(models.User).filter(models.User.email == email).first() - - -def get_users(db: Session, skip: int = 0, limit: int = 100): - return db.query(models.User).offset(skip).limit(limit).all() - - -def create_user(db: Session, user: schemas.UserCreate): - fake_hashed_password = user.password + "notreallyhashed" - db_user = models.User(email=user.email, hashed_password=fake_hashed_password) - db.add(db_user) - db.commit() - db.refresh(db_user) - return db_user - - -def get_items(db: Session, skip: int = 0, limit: int = 100): - return db.query(models.Item).offset(skip).limit(limit).all() - - -def create_user_item(db: Session, item: schemas.ItemCreate, user_id: int): - db_item = models.Item(**item.dict(), owner_id=user_id) - db.add(db_item) - db.commit() - db.refresh(db_item) - return db_item diff --git a/docs_src/sql_databases/sql_app_py39/database.py b/docs_src/sql_databases/sql_app_py39/database.py deleted file mode 100644 index 45a8b9f69..000000000 --- a/docs_src/sql_databases/sql_app_py39/database.py +++ /dev/null @@ -1,13 +0,0 @@ -from sqlalchemy import create_engine -from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.orm import sessionmaker - -SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db" -# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" - -engine = create_engine( - SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} -) -SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) - -Base = declarative_base() diff --git a/docs_src/sql_databases/sql_app_py39/main.py b/docs_src/sql_databases/sql_app_py39/main.py deleted file mode 100644 index a9856d0b6..000000000 --- a/docs_src/sql_databases/sql_app_py39/main.py +++ /dev/null @@ -1,53 +0,0 @@ -from fastapi import Depends, FastAPI, HTTPException -from sqlalchemy.orm import Session - -from . import crud, models, schemas -from .database import SessionLocal, engine - -models.Base.metadata.create_all(bind=engine) - -app = FastAPI() - - -# Dependency -def get_db(): - db = SessionLocal() - try: - yield db - finally: - db.close() - - -@app.post("/users/", response_model=schemas.User) -def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): - db_user = crud.get_user_by_email(db, email=user.email) - if db_user: - raise HTTPException(status_code=400, detail="Email already registered") - return crud.create_user(db=db, user=user) - - -@app.get("/users/", response_model=list[schemas.User]) -def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - users = crud.get_users(db, skip=skip, limit=limit) - return users - - -@app.get("/users/{user_id}", response_model=schemas.User) -def read_user(user_id: int, db: Session = Depends(get_db)): - db_user = crud.get_user(db, user_id=user_id) - if db_user is None: - raise HTTPException(status_code=404, detail="User not found") - return db_user - - -@app.post("/users/{user_id}/items/", response_model=schemas.Item) -def create_item_for_user( - user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) -): - return crud.create_user_item(db=db, item=item, user_id=user_id) - - -@app.get("/items/", response_model=list[schemas.Item]) -def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): - items = crud.get_items(db, skip=skip, limit=limit) - return items diff --git a/docs_src/sql_databases/sql_app_py39/models.py b/docs_src/sql_databases/sql_app_py39/models.py deleted file mode 100644 index 09ae2a807..000000000 --- a/docs_src/sql_databases/sql_app_py39/models.py +++ /dev/null @@ -1,26 +0,0 @@ -from sqlalchemy import Boolean, Column, ForeignKey, Integer, String -from sqlalchemy.orm import relationship - -from .database import Base - - -class User(Base): - __tablename__ = "users" - - id = Column(Integer, primary_key=True) - email = Column(String, unique=True, index=True) - hashed_password = Column(String) - is_active = Column(Boolean, default=True) - - items = relationship("Item", back_populates="owner") - - -class Item(Base): - __tablename__ = "items" - - id = Column(Integer, primary_key=True) - title = Column(String, index=True) - description = Column(String, index=True) - owner_id = Column(Integer, ForeignKey("users.id")) - - owner = relationship("User", back_populates="items") diff --git a/docs_src/sql_databases/sql_app_py39/schemas.py b/docs_src/sql_databases/sql_app_py39/schemas.py deleted file mode 100644 index dadc403d9..000000000 --- a/docs_src/sql_databases/sql_app_py39/schemas.py +++ /dev/null @@ -1,37 +0,0 @@ -from typing import Union - -from pydantic import BaseModel - - -class ItemBase(BaseModel): - title: str - description: Union[str, None] = None - - -class ItemCreate(ItemBase): - pass - - -class Item(ItemBase): - id: int - owner_id: int - - class Config: - orm_mode = True - - -class UserBase(BaseModel): - email: str - - -class UserCreate(UserBase): - password: str - - -class User(UserBase): - id: int - is_active: bool - items: list[Item] = [] - - class Config: - orm_mode = True diff --git a/docs_src/sql_databases/sql_app_py39/tests/__init__.py b/docs_src/sql_databases/sql_app_py39/tests/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/docs_src/sql_databases/sql_app_py39/tests/test_sql_app.py b/docs_src/sql_databases/sql_app_py39/tests/test_sql_app.py deleted file mode 100644 index c60c3356f..000000000 --- a/docs_src/sql_databases/sql_app_py39/tests/test_sql_app.py +++ /dev/null @@ -1,47 +0,0 @@ -from fastapi.testclient import TestClient -from sqlalchemy import create_engine -from sqlalchemy.orm import sessionmaker - -from ..database import Base -from ..main import app, get_db - -SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db" - -engine = create_engine( - SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} -) -TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) - - -Base.metadata.create_all(bind=engine) - - -def override_get_db(): - try: - db = TestingSessionLocal() - yield db - finally: - db.close() - - -app.dependency_overrides[get_db] = override_get_db - -client = TestClient(app) - - -def test_create_user(): - response = client.post( - "/users/", - json={"email": "deadpool@example.com", "password": "chimichangas4life"}, - ) - assert response.status_code == 200, response.text - data = response.json() - assert data["email"] == "deadpool@example.com" - assert "id" in data - user_id = data["id"] - - response = client.get(f"/users/{user_id}") - assert response.status_code == 200, response.text - data = response.json() - assert data["email"] == "deadpool@example.com" - assert data["id"] == user_id diff --git a/docs_src/sql_databases/tutorial001.py b/docs_src/sql_databases/tutorial001.py new file mode 100644 index 000000000..be86ec0ee --- /dev/null +++ b/docs_src/sql_databases/tutorial001.py @@ -0,0 +1,71 @@ +from typing import List, Union + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class Hero(SQLModel, table=True): + id: Union[int, None] = Field(default=None, primary_key=True) + name: str = Field(index=True) + age: Union[int, None] = Field(default=None, index=True) + secret_name: str + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/") +def create_hero(hero: Hero, session: Session = Depends(get_session)) -> Hero: + session.add(hero) + session.commit() + session.refresh(hero) + return hero + + +@app.get("/heroes/") +def read_heroes( + session: Session = Depends(get_session), + offset: int = 0, + limit: int = Query(default=100, le=100), +) -> List[Hero]: + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}") +def read_hero(hero_id: int, session: Session = Depends(get_session)) -> Hero: + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial001_an.py b/docs_src/sql_databases/tutorial001_an.py new file mode 100644 index 000000000..8c000d31c --- /dev/null +++ b/docs_src/sql_databases/tutorial001_an.py @@ -0,0 +1,74 @@ +from typing import List, Union + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select +from typing_extensions import Annotated + + +class Hero(SQLModel, table=True): + id: Union[int, None] = Field(default=None, primary_key=True) + name: str = Field(index=True) + age: Union[int, None] = Field(default=None, index=True) + secret_name: str + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +SessionDep = Annotated[Session, Depends(get_session)] + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/") +def create_hero(hero: Hero, session: SessionDep) -> Hero: + session.add(hero) + session.commit() + session.refresh(hero) + return hero + + +@app.get("/heroes/") +def read_heroes( + session: SessionDep, + offset: int = 0, + limit: Annotated[int, Query(le=100)] = 100, +) -> List[Hero]: + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}") +def read_hero(hero_id: int, session: SessionDep) -> Hero: + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial001_an_py310.py b/docs_src/sql_databases/tutorial001_an_py310.py new file mode 100644 index 000000000..de1fb81fa --- /dev/null +++ b/docs_src/sql_databases/tutorial001_an_py310.py @@ -0,0 +1,73 @@ +from typing import Annotated + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class Hero(SQLModel, table=True): + id: int | None = Field(default=None, primary_key=True) + name: str = Field(index=True) + age: int | None = Field(default=None, index=True) + secret_name: str + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +SessionDep = Annotated[Session, Depends(get_session)] + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/") +def create_hero(hero: Hero, session: SessionDep) -> Hero: + session.add(hero) + session.commit() + session.refresh(hero) + return hero + + +@app.get("/heroes/") +def read_heroes( + session: SessionDep, + offset: int = 0, + limit: Annotated[int, Query(le=100)] = 100, +) -> list[Hero]: + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}") +def read_hero(hero_id: int, session: SessionDep) -> Hero: + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial001_an_py39.py b/docs_src/sql_databases/tutorial001_an_py39.py new file mode 100644 index 000000000..595892746 --- /dev/null +++ b/docs_src/sql_databases/tutorial001_an_py39.py @@ -0,0 +1,73 @@ +from typing import Annotated, Union + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class Hero(SQLModel, table=True): + id: Union[int, None] = Field(default=None, primary_key=True) + name: str = Field(index=True) + age: Union[int, None] = Field(default=None, index=True) + secret_name: str + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +SessionDep = Annotated[Session, Depends(get_session)] + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/") +def create_hero(hero: Hero, session: SessionDep) -> Hero: + session.add(hero) + session.commit() + session.refresh(hero) + return hero + + +@app.get("/heroes/") +def read_heroes( + session: SessionDep, + offset: int = 0, + limit: Annotated[int, Query(le=100)] = 100, +) -> list[Hero]: + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}") +def read_hero(hero_id: int, session: SessionDep) -> Hero: + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial001_py310.py b/docs_src/sql_databases/tutorial001_py310.py new file mode 100644 index 000000000..b58462e6a --- /dev/null +++ b/docs_src/sql_databases/tutorial001_py310.py @@ -0,0 +1,69 @@ +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class Hero(SQLModel, table=True): + id: int | None = Field(default=None, primary_key=True) + name: str = Field(index=True) + age: int | None = Field(default=None, index=True) + secret_name: str + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/") +def create_hero(hero: Hero, session: Session = Depends(get_session)) -> Hero: + session.add(hero) + session.commit() + session.refresh(hero) + return hero + + +@app.get("/heroes/") +def read_heroes( + session: Session = Depends(get_session), + offset: int = 0, + limit: int = Query(default=100, le=100), +) -> list[Hero]: + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}") +def read_hero(hero_id: int, session: Session = Depends(get_session)) -> Hero: + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial001_py39.py b/docs_src/sql_databases/tutorial001_py39.py new file mode 100644 index 000000000..410a52d0c --- /dev/null +++ b/docs_src/sql_databases/tutorial001_py39.py @@ -0,0 +1,71 @@ +from typing import Union + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class Hero(SQLModel, table=True): + id: Union[int, None] = Field(default=None, primary_key=True) + name: str = Field(index=True) + age: Union[int, None] = Field(default=None, index=True) + secret_name: str + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/") +def create_hero(hero: Hero, session: Session = Depends(get_session)) -> Hero: + session.add(hero) + session.commit() + session.refresh(hero) + return hero + + +@app.get("/heroes/") +def read_heroes( + session: Session = Depends(get_session), + offset: int = 0, + limit: int = Query(default=100, le=100), +) -> list[Hero]: + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}") +def read_hero(hero_id: int, session: Session = Depends(get_session)) -> Hero: + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial002.py b/docs_src/sql_databases/tutorial002.py new file mode 100644 index 000000000..4350d19c6 --- /dev/null +++ b/docs_src/sql_databases/tutorial002.py @@ -0,0 +1,104 @@ +from typing import List, Union + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class HeroBase(SQLModel): + name: str = Field(index=True) + age: Union[int, None] = Field(default=None, index=True) + + +class Hero(HeroBase, table=True): + id: Union[int, None] = Field(default=None, primary_key=True) + secret_name: str + + +class HeroPublic(HeroBase): + id: int + + +class HeroCreate(HeroBase): + secret_name: str + + +class HeroUpdate(HeroBase): + name: Union[str, None] = None + age: Union[int, None] = None + secret_name: Union[str, None] = None + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/", response_model=HeroPublic) +def create_hero(hero: HeroCreate, session: Session = Depends(get_session)): + db_hero = Hero.model_validate(hero) + session.add(db_hero) + session.commit() + session.refresh(db_hero) + return db_hero + + +@app.get("/heroes/", response_model=List[HeroPublic]) +def read_heroes( + session: Session = Depends(get_session), + offset: int = 0, + limit: int = Query(default=100, le=100), +): + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}", response_model=HeroPublic) +def read_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.patch("/heroes/{hero_id}", response_model=HeroPublic) +def update_hero( + hero_id: int, hero: HeroUpdate, session: Session = Depends(get_session) +): + hero_db = session.get(Hero, hero_id) + if not hero_db: + raise HTTPException(status_code=404, detail="Hero not found") + hero_data = hero.model_dump(exclude_unset=True) + hero_db.sqlmodel_update(hero_data) + session.add(hero_db) + session.commit() + session.refresh(hero_db) + return hero_db + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial002_an.py b/docs_src/sql_databases/tutorial002_an.py new file mode 100644 index 000000000..15e3d7c3a --- /dev/null +++ b/docs_src/sql_databases/tutorial002_an.py @@ -0,0 +1,104 @@ +from typing import List, Union + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select +from typing_extensions import Annotated + + +class HeroBase(SQLModel): + name: str = Field(index=True) + age: Union[int, None] = Field(default=None, index=True) + + +class Hero(HeroBase, table=True): + id: Union[int, None] = Field(default=None, primary_key=True) + secret_name: str + + +class HeroPublic(HeroBase): + id: int + + +class HeroCreate(HeroBase): + secret_name: str + + +class HeroUpdate(HeroBase): + name: Union[str, None] = None + age: Union[int, None] = None + secret_name: Union[str, None] = None + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +SessionDep = Annotated[Session, Depends(get_session)] +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/", response_model=HeroPublic) +def create_hero(hero: HeroCreate, session: SessionDep): + db_hero = Hero.model_validate(hero) + session.add(db_hero) + session.commit() + session.refresh(db_hero) + return db_hero + + +@app.get("/heroes/", response_model=List[HeroPublic]) +def read_heroes( + session: SessionDep, + offset: int = 0, + limit: Annotated[int, Query(le=100)] = 100, +): + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}", response_model=HeroPublic) +def read_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.patch("/heroes/{hero_id}", response_model=HeroPublic) +def update_hero(hero_id: int, hero: HeroUpdate, session: SessionDep): + hero_db = session.get(Hero, hero_id) + if not hero_db: + raise HTTPException(status_code=404, detail="Hero not found") + hero_data = hero.model_dump(exclude_unset=True) + hero_db.sqlmodel_update(hero_data) + session.add(hero_db) + session.commit() + session.refresh(hero_db) + return hero_db + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial002_an_py310.py b/docs_src/sql_databases/tutorial002_an_py310.py new file mode 100644 index 000000000..64c554b8a --- /dev/null +++ b/docs_src/sql_databases/tutorial002_an_py310.py @@ -0,0 +1,103 @@ +from typing import Annotated + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class HeroBase(SQLModel): + name: str = Field(index=True) + age: int | None = Field(default=None, index=True) + + +class Hero(HeroBase, table=True): + id: int | None = Field(default=None, primary_key=True) + secret_name: str + + +class HeroPublic(HeroBase): + id: int + + +class HeroCreate(HeroBase): + secret_name: str + + +class HeroUpdate(HeroBase): + name: str | None = None + age: int | None = None + secret_name: str | None = None + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +SessionDep = Annotated[Session, Depends(get_session)] +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/", response_model=HeroPublic) +def create_hero(hero: HeroCreate, session: SessionDep): + db_hero = Hero.model_validate(hero) + session.add(db_hero) + session.commit() + session.refresh(db_hero) + return db_hero + + +@app.get("/heroes/", response_model=list[HeroPublic]) +def read_heroes( + session: SessionDep, + offset: int = 0, + limit: Annotated[int, Query(le=100)] = 100, +): + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}", response_model=HeroPublic) +def read_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.patch("/heroes/{hero_id}", response_model=HeroPublic) +def update_hero(hero_id: int, hero: HeroUpdate, session: SessionDep): + hero_db = session.get(Hero, hero_id) + if not hero_db: + raise HTTPException(status_code=404, detail="Hero not found") + hero_data = hero.model_dump(exclude_unset=True) + hero_db.sqlmodel_update(hero_data) + session.add(hero_db) + session.commit() + session.refresh(hero_db) + return hero_db + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial002_an_py39.py b/docs_src/sql_databases/tutorial002_an_py39.py new file mode 100644 index 000000000..a8a0721ff --- /dev/null +++ b/docs_src/sql_databases/tutorial002_an_py39.py @@ -0,0 +1,103 @@ +from typing import Annotated, Union + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class HeroBase(SQLModel): + name: str = Field(index=True) + age: Union[int, None] = Field(default=None, index=True) + + +class Hero(HeroBase, table=True): + id: Union[int, None] = Field(default=None, primary_key=True) + secret_name: str + + +class HeroPublic(HeroBase): + id: int + + +class HeroCreate(HeroBase): + secret_name: str + + +class HeroUpdate(HeroBase): + name: Union[str, None] = None + age: Union[int, None] = None + secret_name: Union[str, None] = None + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +SessionDep = Annotated[Session, Depends(get_session)] +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/", response_model=HeroPublic) +def create_hero(hero: HeroCreate, session: SessionDep): + db_hero = Hero.model_validate(hero) + session.add(db_hero) + session.commit() + session.refresh(db_hero) + return db_hero + + +@app.get("/heroes/", response_model=list[HeroPublic]) +def read_heroes( + session: SessionDep, + offset: int = 0, + limit: Annotated[int, Query(le=100)] = 100, +): + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}", response_model=HeroPublic) +def read_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.patch("/heroes/{hero_id}", response_model=HeroPublic) +def update_hero(hero_id: int, hero: HeroUpdate, session: SessionDep): + hero_db = session.get(Hero, hero_id) + if not hero_db: + raise HTTPException(status_code=404, detail="Hero not found") + hero_data = hero.model_dump(exclude_unset=True) + hero_db.sqlmodel_update(hero_data) + session.add(hero_db) + session.commit() + session.refresh(hero_db) + return hero_db + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: SessionDep): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial002_py310.py b/docs_src/sql_databases/tutorial002_py310.py new file mode 100644 index 000000000..ec3d68db5 --- /dev/null +++ b/docs_src/sql_databases/tutorial002_py310.py @@ -0,0 +1,102 @@ +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class HeroBase(SQLModel): + name: str = Field(index=True) + age: int | None = Field(default=None, index=True) + + +class Hero(HeroBase, table=True): + id: int | None = Field(default=None, primary_key=True) + secret_name: str + + +class HeroPublic(HeroBase): + id: int + + +class HeroCreate(HeroBase): + secret_name: str + + +class HeroUpdate(HeroBase): + name: str | None = None + age: int | None = None + secret_name: str | None = None + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/", response_model=HeroPublic) +def create_hero(hero: HeroCreate, session: Session = Depends(get_session)): + db_hero = Hero.model_validate(hero) + session.add(db_hero) + session.commit() + session.refresh(db_hero) + return db_hero + + +@app.get("/heroes/", response_model=list[HeroPublic]) +def read_heroes( + session: Session = Depends(get_session), + offset: int = 0, + limit: int = Query(default=100, le=100), +): + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}", response_model=HeroPublic) +def read_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.patch("/heroes/{hero_id}", response_model=HeroPublic) +def update_hero( + hero_id: int, hero: HeroUpdate, session: Session = Depends(get_session) +): + hero_db = session.get(Hero, hero_id) + if not hero_db: + raise HTTPException(status_code=404, detail="Hero not found") + hero_data = hero.model_dump(exclude_unset=True) + hero_db.sqlmodel_update(hero_data) + session.add(hero_db) + session.commit() + session.refresh(hero_db) + return hero_db + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases/tutorial002_py39.py b/docs_src/sql_databases/tutorial002_py39.py new file mode 100644 index 000000000..d8f5dd090 --- /dev/null +++ b/docs_src/sql_databases/tutorial002_py39.py @@ -0,0 +1,104 @@ +from typing import Union + +from fastapi import Depends, FastAPI, HTTPException, Query +from sqlmodel import Field, Session, SQLModel, create_engine, select + + +class HeroBase(SQLModel): + name: str = Field(index=True) + age: Union[int, None] = Field(default=None, index=True) + + +class Hero(HeroBase, table=True): + id: Union[int, None] = Field(default=None, primary_key=True) + secret_name: str + + +class HeroPublic(HeroBase): + id: int + + +class HeroCreate(HeroBase): + secret_name: str + + +class HeroUpdate(HeroBase): + name: Union[str, None] = None + age: Union[int, None] = None + secret_name: Union[str, None] = None + + +sqlite_file_name = "database.db" +sqlite_url = f"sqlite:///{sqlite_file_name}" + +connect_args = {"check_same_thread": False} +engine = create_engine(sqlite_url, connect_args=connect_args) + + +def create_db_and_tables(): + SQLModel.metadata.create_all(engine) + + +def get_session(): + with Session(engine) as session: + yield session + + +app = FastAPI() + + +@app.on_event("startup") +def on_startup(): + create_db_and_tables() + + +@app.post("/heroes/", response_model=HeroPublic) +def create_hero(hero: HeroCreate, session: Session = Depends(get_session)): + db_hero = Hero.model_validate(hero) + session.add(db_hero) + session.commit() + session.refresh(db_hero) + return db_hero + + +@app.get("/heroes/", response_model=list[HeroPublic]) +def read_heroes( + session: Session = Depends(get_session), + offset: int = 0, + limit: int = Query(default=100, le=100), +): + heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() + return heroes + + +@app.get("/heroes/{hero_id}", response_model=HeroPublic) +def read_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + return hero + + +@app.patch("/heroes/{hero_id}", response_model=HeroPublic) +def update_hero( + hero_id: int, hero: HeroUpdate, session: Session = Depends(get_session) +): + hero_db = session.get(Hero, hero_id) + if not hero_db: + raise HTTPException(status_code=404, detail="Hero not found") + hero_data = hero.model_dump(exclude_unset=True) + hero_db.sqlmodel_update(hero_data) + session.add(hero_db) + session.commit() + session.refresh(hero_db) + return hero_db + + +@app.delete("/heroes/{hero_id}") +def delete_hero(hero_id: int, session: Session = Depends(get_session)): + hero = session.get(Hero, hero_id) + if not hero: + raise HTTPException(status_code=404, detail="Hero not found") + session.delete(hero) + session.commit() + return {"ok": True} diff --git a/docs_src/sql_databases_peewee/sql_app/__init__.py b/docs_src/sql_databases_peewee/sql_app/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/docs_src/sql_databases_peewee/sql_app/crud.py b/docs_src/sql_databases_peewee/sql_app/crud.py deleted file mode 100644 index 56c587559..000000000 --- a/docs_src/sql_databases_peewee/sql_app/crud.py +++ /dev/null @@ -1,30 +0,0 @@ -from . import models, schemas - - -def get_user(user_id: int): - return models.User.filter(models.User.id == user_id).first() - - -def get_user_by_email(email: str): - return models.User.filter(models.User.email == email).first() - - -def get_users(skip: int = 0, limit: int = 100): - return list(models.User.select().offset(skip).limit(limit)) - - -def create_user(user: schemas.UserCreate): - fake_hashed_password = user.password + "notreallyhashed" - db_user = models.User(email=user.email, hashed_password=fake_hashed_password) - db_user.save() - return db_user - - -def get_items(skip: int = 0, limit: int = 100): - return list(models.Item.select().offset(skip).limit(limit)) - - -def create_user_item(item: schemas.ItemCreate, user_id: int): - db_item = models.Item(**item.dict(), owner_id=user_id) - db_item.save() - return db_item diff --git a/docs_src/sql_databases_peewee/sql_app/database.py b/docs_src/sql_databases_peewee/sql_app/database.py deleted file mode 100644 index 6938fe826..000000000 --- a/docs_src/sql_databases_peewee/sql_app/database.py +++ /dev/null @@ -1,24 +0,0 @@ -from contextvars import ContextVar - -import peewee - -DATABASE_NAME = "test.db" -db_state_default = {"closed": None, "conn": None, "ctx": None, "transactions": None} -db_state = ContextVar("db_state", default=db_state_default.copy()) - - -class PeeweeConnectionState(peewee._ConnectionState): - def __init__(self, **kwargs): - super().__setattr__("_state", db_state) - super().__init__(**kwargs) - - def __setattr__(self, name, value): - self._state.get()[name] = value - - def __getattr__(self, name): - return self._state.get()[name] - - -db = peewee.SqliteDatabase(DATABASE_NAME, check_same_thread=False) - -db._state = PeeweeConnectionState() diff --git a/docs_src/sql_databases_peewee/sql_app/main.py b/docs_src/sql_databases_peewee/sql_app/main.py deleted file mode 100644 index 8fbd2075d..000000000 --- a/docs_src/sql_databases_peewee/sql_app/main.py +++ /dev/null @@ -1,79 +0,0 @@ -import time -from typing import List - -from fastapi import Depends, FastAPI, HTTPException - -from . import crud, database, models, schemas -from .database import db_state_default - -database.db.connect() -database.db.create_tables([models.User, models.Item]) -database.db.close() - -app = FastAPI() - -sleep_time = 10 - - -async def reset_db_state(): - database.db._state._state.set(db_state_default.copy()) - database.db._state.reset() - - -def get_db(db_state=Depends(reset_db_state)): - try: - database.db.connect() - yield - finally: - if not database.db.is_closed(): - database.db.close() - - -@app.post("/users/", response_model=schemas.User, dependencies=[Depends(get_db)]) -def create_user(user: schemas.UserCreate): - db_user = crud.get_user_by_email(email=user.email) - if db_user: - raise HTTPException(status_code=400, detail="Email already registered") - return crud.create_user(user=user) - - -@app.get("/users/", response_model=List[schemas.User], dependencies=[Depends(get_db)]) -def read_users(skip: int = 0, limit: int = 100): - users = crud.get_users(skip=skip, limit=limit) - return users - - -@app.get( - "/users/{user_id}", response_model=schemas.User, dependencies=[Depends(get_db)] -) -def read_user(user_id: int): - db_user = crud.get_user(user_id=user_id) - if db_user is None: - raise HTTPException(status_code=404, detail="User not found") - return db_user - - -@app.post( - "/users/{user_id}/items/", - response_model=schemas.Item, - dependencies=[Depends(get_db)], -) -def create_item_for_user(user_id: int, item: schemas.ItemCreate): - return crud.create_user_item(item=item, user_id=user_id) - - -@app.get("/items/", response_model=List[schemas.Item], dependencies=[Depends(get_db)]) -def read_items(skip: int = 0, limit: int = 100): - items = crud.get_items(skip=skip, limit=limit) - return items - - -@app.get( - "/slowusers/", response_model=List[schemas.User], dependencies=[Depends(get_db)] -) -def read_slow_users(skip: int = 0, limit: int = 100): - global sleep_time - sleep_time = max(0, sleep_time - 1) - time.sleep(sleep_time) # Fake long processing request - users = crud.get_users(skip=skip, limit=limit) - return users diff --git a/docs_src/sql_databases_peewee/sql_app/models.py b/docs_src/sql_databases_peewee/sql_app/models.py deleted file mode 100644 index 46bdcd009..000000000 --- a/docs_src/sql_databases_peewee/sql_app/models.py +++ /dev/null @@ -1,21 +0,0 @@ -import peewee - -from .database import db - - -class User(peewee.Model): - email = peewee.CharField(unique=True, index=True) - hashed_password = peewee.CharField() - is_active = peewee.BooleanField(default=True) - - class Meta: - database = db - - -class Item(peewee.Model): - title = peewee.CharField(index=True) - description = peewee.CharField(index=True) - owner = peewee.ForeignKeyField(User, backref="items") - - class Meta: - database = db diff --git a/docs_src/sql_databases_peewee/sql_app/schemas.py b/docs_src/sql_databases_peewee/sql_app/schemas.py deleted file mode 100644 index d8775cb30..000000000 --- a/docs_src/sql_databases_peewee/sql_app/schemas.py +++ /dev/null @@ -1,49 +0,0 @@ -from typing import Any, List, Union - -import peewee -from pydantic import BaseModel -from pydantic.utils import GetterDict - - -class PeeweeGetterDict(GetterDict): - def get(self, key: Any, default: Any = None): - res = getattr(self._obj, key, default) - if isinstance(res, peewee.ModelSelect): - return list(res) - return res - - -class ItemBase(BaseModel): - title: str - description: Union[str, None] = None - - -class ItemCreate(ItemBase): - pass - - -class Item(ItemBase): - id: int - owner_id: int - - class Config: - orm_mode = True - getter_dict = PeeweeGetterDict - - -class UserBase(BaseModel): - email: str - - -class UserCreate(UserBase): - password: str - - -class User(UserBase): - id: int - is_active: bool - items: List[Item] = [] - - class Config: - orm_mode = True - getter_dict = PeeweeGetterDict diff --git a/fastapi/__init__.py b/fastapi/__init__.py index f457fafd4..757b76106 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.109.0" +__version__ = "0.115.11" from starlette import status as status diff --git a/fastapi/__main__.py b/fastapi/__main__.py new file mode 100644 index 000000000..fc36465f5 --- /dev/null +++ b/fastapi/__main__.py @@ -0,0 +1,3 @@ +from fastapi.cli import main + +main() diff --git a/fastapi/_compat.py b/fastapi/_compat.py index 35d4a8723..c07e4a3b0 100644 --- a/fastapi/_compat.py +++ b/fastapi/_compat.py @@ -2,6 +2,7 @@ from collections import deque from copy import copy from dataclasses import dataclass, is_dataclass from enum import Enum +from functools import lru_cache from typing import ( Any, Callable, @@ -24,7 +25,8 @@ from pydantic.version import VERSION as PYDANTIC_VERSION from starlette.datastructures import UploadFile from typing_extensions import Annotated, Literal, get_args, get_origin -PYDANTIC_V2 = PYDANTIC_VERSION.startswith("2.") +PYDANTIC_VERSION_MINOR_TUPLE = tuple(int(x) for x in PYDANTIC_VERSION.split(".")[:2]) +PYDANTIC_V2 = PYDANTIC_VERSION_MINOR_TUPLE[0] == 2 sequence_annotation_to_type = { @@ -43,6 +45,8 @@ sequence_annotation_to_type = { sequence_types = tuple(sequence_annotation_to_type.keys()) +Url: Type[Any] + if PYDANTIC_V2: from pydantic import PydanticSchemaGenerationError as PydanticSchemaGenerationError from pydantic import TypeAdapter @@ -68,7 +72,7 @@ if PYDANTIC_V2: general_plain_validator_function as with_info_plain_validator_function, # noqa: F401 ) - Required = PydanticUndefined + RequiredParam = PydanticUndefined Undefined = PydanticUndefined UndefinedType = PydanticUndefinedType evaluate_forwardref = eval_type_lenient @@ -127,7 +131,7 @@ if PYDANTIC_V2: ) except ValidationError as exc: return None, _regenerate_error_with_loc( - errors=exc.errors(), loc_prefix=loc + errors=exc.errors(include_url=False), loc_prefix=loc ) def serialize( @@ -266,7 +270,7 @@ if PYDANTIC_V2: def get_missing_field_error(loc: Tuple[str, ...]) -> Dict[str, Any]: error = ValidationError.from_exception_data( "Field required", [{"type": "missing", "loc": loc, "input": {}}] - ).errors()[0] + ).errors(include_url=False)[0] error["input"] = None return error # type: ignore[return-value] @@ -277,6 +281,12 @@ if PYDANTIC_V2: BodyModel: Type[BaseModel] = create_model(model_name, **field_params) # type: ignore[call-overload] return BodyModel + def get_model_fields(model: Type[BaseModel]) -> List[ModelField]: + return [ + ModelField(field_info=field_info, name=name) + for name, field_info in model.model_fields.items() + ] + else: from fastapi.openapi.constants import REF_PREFIX as REF_PREFIX from pydantic import AnyUrl as Url # noqa: F401 @@ -304,9 +314,10 @@ else: from pydantic.fields import ( # type: ignore[no-redef,attr-defined] ModelField as ModelField, # noqa: F401 ) - from pydantic.fields import ( # type: ignore[no-redef,attr-defined] - Required as Required, # noqa: F401 - ) + + # Keeping old "Required" functionality from Pydantic V1, without + # shadowing typing.Required. + RequiredParam: Any = Ellipsis # type: ignore[no-redef] from pydantic.fields import ( # type: ignore[no-redef,attr-defined] Undefined as Undefined, ) @@ -511,6 +522,9 @@ else: BodyModel.__fields__[f.name] = f # type: ignore[index] return BodyModel + def get_model_fields(model: Type[BaseModel]) -> List[ModelField]: + return list(model.__fields__.values()) # type: ignore[attr-defined] + def _regenerate_error_with_loc( *, errors: Sequence[Any], loc_prefix: Tuple[Union[str, int], ...] @@ -530,6 +544,12 @@ def _annotation_is_sequence(annotation: Union[Type[Any], None]) -> bool: def field_annotation_is_sequence(annotation: Union[Type[Any], None]) -> bool: + origin = get_origin(annotation) + if origin is Union or origin is UnionType: + for arg in get_args(annotation): + if field_annotation_is_sequence(arg): + return True + return False return _annotation_is_sequence(annotation) or _annotation_is_sequence( get_origin(annotation) ) @@ -632,3 +652,8 @@ def is_uploadfile_sequence_annotation(annotation: Any) -> bool: is_uploadfile_or_nonable_uploadfile_annotation(sub_annotation) for sub_annotation in get_args(annotation) ) + + +@lru_cache +def get_cached_model_fields(model: Type[BaseModel]) -> List[ModelField]: + return get_model_fields(model) diff --git a/fastapi/applications.py b/fastapi/applications.py index 8493851c6..bd36201a5 100644 --- a/fastapi/applications.py +++ b/fastapi/applications.py @@ -40,7 +40,7 @@ from starlette.requests import Request from starlette.responses import HTMLResponse, JSONResponse, Response from starlette.routing import BaseRoute from starlette.types import ASGIApp, Lifespan, Receive, Scope, Send -from typing_extensions import Annotated, Doc, deprecated # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc, deprecated AppType = TypeVar("AppType", bound="FastAPI") @@ -297,7 +297,7 @@ class FastAPI(Starlette): browser tabs open). Or if you want to leave fixed the possible URLs. If the servers `list` is not provided, or is an empty `list`, the - default value would be a a `dict` with a `url` value of `/`. + default value would be a `dict` with a `url` value of `/`. Each item in the `list` is a `dict` containing: @@ -902,7 +902,7 @@ class FastAPI(Starlette): A state object for the application. This is the same object for the entire application, it doesn't change from request to request. - You normally woudln't use this in FastAPI, for most of the cases you + You normally wouldn't use this in FastAPI, for most of the cases you would instead use FastAPI dependencies. This is simply inherited from Starlette. @@ -1019,7 +1019,7 @@ class FastAPI(Starlette): oauth2_redirect_url = root_path + oauth2_redirect_url return get_swagger_ui_html( openapi_url=openapi_url, - title=self.title + " - Swagger UI", + title=f"{self.title} - Swagger UI", oauth2_redirect_url=oauth2_redirect_url, init_oauth=self.swagger_ui_init_oauth, swagger_ui_parameters=self.swagger_ui_parameters, @@ -1043,7 +1043,7 @@ class FastAPI(Starlette): root_path = req.scope.get("root_path", "").rstrip("/") openapi_url = root_path + self.openapi_url return get_redoc_html( - openapi_url=openapi_url, title=self.title + " - ReDoc" + openapi_url=openapi_url, title=f"{self.title} - ReDoc" ) self.add_route(self.redoc_url, redoc_html, include_in_schema=False) @@ -1056,7 +1056,7 @@ class FastAPI(Starlette): def add_api_route( self, path: str, - endpoint: Callable[..., Coroutine[Any, Any, Response]], + endpoint: Callable[..., Any], *, response_model: Any = Default(None), status_code: Optional[int] = None, diff --git a/fastapi/background.py b/fastapi/background.py index 35ab1b227..203578a41 100644 --- a/fastapi/background.py +++ b/fastapi/background.py @@ -1,7 +1,7 @@ from typing import Any, Callable from starlette.background import BackgroundTasks as StarletteBackgroundTasks -from typing_extensions import Annotated, Doc, ParamSpec # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc, ParamSpec P = ParamSpec("P") diff --git a/fastapi/cli.py b/fastapi/cli.py new file mode 100644 index 000000000..8d3301e9d --- /dev/null +++ b/fastapi/cli.py @@ -0,0 +1,13 @@ +try: + from fastapi_cli.cli import main as cli_main + +except ImportError: # pragma: no cover + cli_main = None # type: ignore + + +def main() -> None: + if not cli_main: # type: ignore[truthy-function] + message = 'To use the fastapi command, please install "fastapi[standard]":\n\n\tpip install "fastapi[standard]"\n' + print(message) + raise RuntimeError(message) # noqa: B904 + cli_main() diff --git a/fastapi/concurrency.py b/fastapi/concurrency.py index 894bd3ed1..3202c7078 100644 --- a/fastapi/concurrency.py +++ b/fastapi/concurrency.py @@ -1,7 +1,7 @@ from contextlib import asynccontextmanager as asynccontextmanager from typing import AsyncGenerator, ContextManager, TypeVar -import anyio +import anyio.to_thread 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 @@ -28,7 +28,7 @@ async def contextmanager_in_threadpool( except Exception as e: ok = bool( await anyio.to_thread.run_sync( - cm.__exit__, type(e), e, None, limiter=exit_limiter + cm.__exit__, type(e), e, e.__traceback__, limiter=exit_limiter ) ) if not ok: diff --git a/fastapi/datastructures.py b/fastapi/datastructures.py index ce03e3ce4..cf8406b0f 100644 --- a/fastapi/datastructures.py +++ b/fastapi/datastructures.py @@ -24,7 +24,7 @@ from starlette.datastructures import Headers as Headers # noqa: F401 from starlette.datastructures import QueryParams as QueryParams # noqa: F401 from starlette.datastructures import State as State # noqa: F401 from starlette.datastructures import UploadFile as StarletteUploadFile -from typing_extensions import Annotated, Doc # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc class UploadFile(StarletteUploadFile): diff --git a/fastapi/dependencies/models.py b/fastapi/dependencies/models.py index 61ef00638..418c11725 100644 --- a/fastapi/dependencies/models.py +++ b/fastapi/dependencies/models.py @@ -1,58 +1,37 @@ -from typing import Any, Callable, List, Optional, Sequence +from dataclasses import dataclass, field +from typing import Any, Callable, List, Optional, Sequence, Tuple from fastapi._compat import ModelField from fastapi.security.base import SecurityBase +@dataclass class SecurityRequirement: - def __init__( - self, security_scheme: SecurityBase, scopes: Optional[Sequence[str]] = None - ): - self.security_scheme = security_scheme - self.scopes = scopes + security_scheme: SecurityBase + scopes: Optional[Sequence[str]] = None +@dataclass class Dependant: - def __init__( - self, - *, - path_params: Optional[List[ModelField]] = None, - query_params: Optional[List[ModelField]] = None, - header_params: Optional[List[ModelField]] = None, - cookie_params: Optional[List[ModelField]] = None, - body_params: Optional[List[ModelField]] = None, - dependencies: Optional[List["Dependant"]] = None, - security_schemes: Optional[List[SecurityRequirement]] = None, - name: Optional[str] = None, - call: Optional[Callable[..., Any]] = None, - request_param_name: Optional[str] = None, - websocket_param_name: Optional[str] = None, - http_connection_param_name: Optional[str] = None, - response_param_name: Optional[str] = None, - background_tasks_param_name: Optional[str] = None, - security_scopes_param_name: Optional[str] = None, - security_scopes: Optional[List[str]] = None, - use_cache: bool = True, - path: Optional[str] = None, - ) -> None: - self.path_params = path_params or [] - self.query_params = query_params or [] - self.header_params = header_params or [] - self.cookie_params = cookie_params or [] - self.body_params = body_params or [] - self.dependencies = dependencies or [] - self.security_requirements = security_schemes or [] - self.request_param_name = request_param_name - self.websocket_param_name = websocket_param_name - self.http_connection_param_name = http_connection_param_name - self.response_param_name = response_param_name - self.background_tasks_param_name = background_tasks_param_name - self.security_scopes = security_scopes - self.security_scopes_param_name = security_scopes_param_name - self.name = name - self.call = call - self.use_cache = use_cache - # Store the path to be able to re-generate a dependable from it in overrides - self.path = path - # Save the cache key at creation to optimize performance + path_params: List[ModelField] = field(default_factory=list) + query_params: List[ModelField] = field(default_factory=list) + header_params: List[ModelField] = field(default_factory=list) + cookie_params: List[ModelField] = field(default_factory=list) + body_params: List[ModelField] = field(default_factory=list) + dependencies: List["Dependant"] = field(default_factory=list) + security_requirements: List[SecurityRequirement] = field(default_factory=list) + name: Optional[str] = None + call: Optional[Callable[..., Any]] = None + request_param_name: Optional[str] = None + websocket_param_name: Optional[str] = None + http_connection_param_name: Optional[str] = None + response_param_name: Optional[str] = None + background_tasks_param_name: Optional[str] = None + security_scopes_param_name: Optional[str] = None + security_scopes: Optional[List[str]] = None + use_cache: bool = True + path: Optional[str] = None + cache_key: Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] = field(init=False) + + def __post_init__(self) -> None: self.cache_key = (self.call, tuple(sorted(set(self.security_scopes or [])))) diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index b73473484..e2866b488 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -1,6 +1,7 @@ import inspect from contextlib import AsyncExitStack, contextmanager -from copy import deepcopy +from copy import copy, deepcopy +from dataclasses import dataclass from typing import ( Any, Callable, @@ -23,7 +24,7 @@ from fastapi._compat import ( PYDANTIC_V2, ErrorWrapper, ModelField, - Required, + RequiredParam, Undefined, _regenerate_error_with_loc, copy_field_info, @@ -31,6 +32,7 @@ from fastapi._compat import ( evaluate_forwardref, field_annotation_is_scalar, get_annotation_from_field_info, + get_cached_model_fields, get_missing_field_error, is_bytes_field, is_bytes_sequence_field, @@ -54,11 +56,18 @@ from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect -from fastapi.utils import create_response_field, get_path_param_names +from fastapi.utils import create_model_field, get_path_param_names +from pydantic import BaseModel from pydantic.fields import FieldInfo from starlette.background import BackgroundTasks as StarletteBackgroundTasks from starlette.concurrency import run_in_threadpool -from starlette.datastructures import FormData, Headers, QueryParams, UploadFile +from starlette.datastructures import ( + FormData, + Headers, + ImmutableMultiDict, + QueryParams, + UploadFile, +) from starlette.requests import HTTPConnection, Request from starlette.responses import Response from starlette.websockets import WebSocket @@ -79,17 +88,23 @@ multipart_incorrect_install_error = ( ) -def check_file_field(field: ModelField) -> None: - field_info = field.field_info - if isinstance(field_info, params.Form): +def ensure_multipart_is_installed() -> None: + try: + from python_multipart import __version__ + + # Import an attribute that can be mocked/deleted in testing + assert __version__ > "0.0.12" + except (ImportError, AssertionError): try: # __version__ is available in both multiparts, and can be mocked - from multipart import __version__ # type: ignore + from multipart import __version__ # type: ignore[no-redef,import-untyped] assert __version__ try: # parse_options_header is only available in the right multipart - from multipart.multipart import parse_options_header # type: ignore + from multipart.multipart import ( # type: ignore[import-untyped] + parse_options_header, + ) assert parse_options_header except ImportError: @@ -175,7 +190,7 @@ def get_flat_dependant( header_params=dependant.header_params.copy(), cookie_params=dependant.cookie_params.copy(), body_params=dependant.body_params.copy(), - security_schemes=dependant.security_requirements.copy(), + security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) @@ -194,14 +209,23 @@ def get_flat_dependant( return flat_dependant +def _get_flat_fields_from_params(fields: List[ModelField]) -> List[ModelField]: + if not fields: + return fields + first_field = fields[0] + if len(fields) == 1 and lenient_issubclass(first_field.type_, BaseModel): + fields_to_extract = get_cached_model_fields(first_field.type_) + return fields_to_extract + return fields + + def get_flat_params(dependant: Dependant) -> List[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) - return ( - flat_dependant.path_params - + flat_dependant.query_params - + flat_dependant.header_params - + flat_dependant.cookie_params - ) + path_params = _get_flat_fields_from_params(flat_dependant.path_params) + query_params = _get_flat_fields_from_params(flat_dependant.query_params) + header_params = _get_flat_fields_from_params(flat_dependant.header_params) + cookie_params = _get_flat_fields_from_params(flat_dependant.cookie_params) + return path_params + query_params + header_params + cookie_params def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: @@ -258,16 +282,16 @@ def get_dependant( ) for param_name, param in signature_params.items(): is_path_param = param_name in path_param_names - type_annotation, depends, param_field = analyze_param( + param_details = analyze_param( param_name=param_name, annotation=param.annotation, value=param.default, is_path_param=is_path_param, ) - if depends is not None: + if param_details.depends is not None: sub_dependant = get_param_sub_dependant( param_name=param_name, - depends=depends, + depends=param_details.depends, path=path, security_scopes=security_scopes, ) @@ -275,18 +299,18 @@ def get_dependant( continue if add_non_field_param_to_dependency( param_name=param_name, - type_annotation=type_annotation, + type_annotation=param_details.type_annotation, dependant=dependant, ): assert ( - param_field is None + param_details.field is None ), f"Cannot specify multiple FastAPI annotations for {param_name!r}" continue - assert param_field is not None - if is_body_param(param_field=param_field, is_path_param=is_path_param): - dependant.body_params.append(param_field) + assert param_details.field is not None + if isinstance(param_details.field.field_info, params.Body): + dependant.body_params.append(param_details.field) else: - add_param_to_fields(field=param_field, dependant=dependant) + add_param_to_fields(field=param_details.field, dependant=dependant) return dependant @@ -314,13 +338,20 @@ def add_non_field_param_to_dependency( return None +@dataclass +class ParamDetails: + type_annotation: Any + depends: Optional[params.Depends] + field: Optional[ModelField] + + def analyze_param( *, param_name: str, annotation: Any, value: Any, is_path_param: bool, -) -> Tuple[Any, Optional[params.Depends], Optional[ModelField]]: +) -> ParamDetails: field_info = None depends = None type_annotation: Any = Any @@ -328,6 +359,7 @@ def analyze_param( if annotation is not inspect.Signature.empty: use_annotation = annotation type_annotation = annotation + # Extract Annotated info if get_origin(use_annotation) is Annotated: annotated_args = get_args(annotation) type_annotation = annotated_args[0] @@ -342,17 +374,20 @@ def analyze_param( if isinstance(arg, (params.Param, params.Body, params.Depends)) ] if fastapi_specific_annotations: - fastapi_annotation: Union[ - FieldInfo, params.Depends, None - ] = fastapi_specific_annotations[-1] + fastapi_annotation: Union[FieldInfo, params.Depends, None] = ( + fastapi_specific_annotations[-1] + ) else: fastapi_annotation = None + # Set default for Annotated FieldInfo if isinstance(fastapi_annotation, FieldInfo): # Copy `field_info` because we mutate `field_info.default` below. field_info = copy_field_info( field_info=fastapi_annotation, annotation=use_annotation ) - assert field_info.default is Undefined or field_info.default is Required, ( + assert ( + field_info.default is Undefined or field_info.default is RequiredParam + ), ( f"`{field_info.__class__.__name__}` default value cannot be set in" f" `Annotated` for {param_name!r}. Set the default value with `=` instead." ) @@ -360,10 +395,11 @@ def analyze_param( assert not is_path_param, "Path parameters cannot have default values" field_info.default = value else: - field_info.default = Required + field_info.default = RequiredParam + # Get Annotated Depends elif isinstance(fastapi_annotation, params.Depends): depends = fastapi_annotation - + # Get Depends from default value if isinstance(value, params.Depends): assert depends is None, ( "Cannot specify `Depends` in `Annotated` and default value" @@ -374,6 +410,7 @@ def analyze_param( f" default value together for {param_name!r}" ) depends = value + # Get FieldInfo from default value elif isinstance(value, FieldInfo): assert field_info is None, ( "Cannot specify FastAPI annotations in `Annotated` and default value" @@ -383,9 +420,13 @@ def analyze_param( if PYDANTIC_V2: field_info.annotation = type_annotation + # Get Depends from type annotation if depends is not None and depends.dependency is None: + # Copy `depends` before mutating it + depends = copy(depends) depends.dependency = type_annotation + # Handle non-param type annotations like Request if lenient_issubclass( type_annotation, ( @@ -401,10 +442,11 @@ def analyze_param( assert ( field_info is None ), f"Cannot specify FastAPI annotation for type {type_annotation!r}" + # Handle default assignations, neither field_info nor depends was not found in Annotated nor default value elif field_info is None and depends is None: - default_value = value if value is not inspect.Signature.empty else Required + default_value = value if value is not inspect.Signature.empty else RequiredParam if is_path_param: - # We might check here that `default_value is Required`, but the fact is that the same + # We might check here that `default_value is RequiredParam`, but the fact is that the same # parameter might sometimes be a path parameter and sometimes not. See # `tests/test_infer_param_optionality.py` for an example. field_info = params.Path(annotation=use_annotation) @@ -418,7 +460,9 @@ def analyze_param( field_info = params.Query(annotation=use_annotation, default=default_value) field = None + # It's a field_info, not a dependency if field_info is not None: + # Handle field_info.in_ if is_path_param: assert isinstance(field_info, params.Path), ( f"Cannot use `{field_info.__class__.__name__}` for path param" @@ -434,40 +478,37 @@ def analyze_param( field_info, param_name, ) + if isinstance(field_info, params.Form): + ensure_multipart_is_installed() if not field_info.alias and getattr(field_info, "convert_underscores", None): alias = param_name.replace("_", "-") else: alias = field_info.alias or param_name field_info.alias = alias - field = create_response_field( + field = create_model_field( name=param_name, type_=use_annotation_from_field_info, default=field_info.default, alias=alias, - required=field_info.default in (Required, Undefined), + required=field_info.default in (RequiredParam, Undefined), field_info=field_info, ) + if is_path_param: + assert is_scalar_field( + field=field + ), "Path params must be of one of the supported types" + elif isinstance(field_info, params.Query): + assert ( + is_scalar_field(field) + or is_scalar_sequence_field(field) + or ( + lenient_issubclass(field.type_, BaseModel) + # For Pydantic v1 + and getattr(field, "shape", 1) == 1 + ) + ) - return type_annotation, depends, field - - -def is_body_param(*, param_field: ModelField, is_path_param: bool) -> bool: - if is_path_param: - assert is_scalar_field( - field=param_field - ), "Path params must be of one of the supported types" - return False - elif is_scalar_field(field=param_field): - return False - elif isinstance( - param_field.field_info, (params.Query, params.Header) - ) and is_scalar_sequence_field(param_field): - return False - else: - assert isinstance( - param_field.field_info, params.Body - ), f"Param: {param_field.name} can only be a request body, using Body()" - return True + return ParamDetails(type_annotation=type_annotation, depends=depends, field=field) def add_param_to_fields(*, field: ModelField, dependant: Dependant) -> None: @@ -519,6 +560,15 @@ async def solve_generator( return await stack.enter_async_context(cm) +@dataclass +class SolvedDependency: + values: Dict[str, Any] + errors: List[Any] + background_tasks: Optional[StarletteBackgroundTasks] + response: Response + dependency_cache: Dict[Tuple[Callable[..., Any], Tuple[str]], Any] + + async def solve_dependencies( *, request: Union[Request, WebSocket], @@ -529,13 +579,8 @@ async def solve_dependencies( dependency_overrides_provider: Optional[Any] = None, dependency_cache: Optional[Dict[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, -) -> Tuple[ - Dict[str, Any], - List[Any], - Optional[StarletteBackgroundTasks], - Response, - Dict[Tuple[Callable[..., Any], Tuple[str]], Any], -]: + embed_body_fields: bool, +) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: @@ -576,28 +621,23 @@ async def solve_dependencies( dependency_overrides_provider=dependency_overrides_provider, dependency_cache=dependency_cache, async_exit_stack=async_exit_stack, + embed_body_fields=embed_body_fields, ) - ( - sub_values, - sub_errors, - background_tasks, - _, # the subdependency returns the same response we have - sub_dependency_cache, - ) = solved_result - dependency_cache.update(sub_dependency_cache) - if sub_errors: - errors.extend(sub_errors) + background_tasks = solved_result.background_tasks + dependency_cache.update(solved_result.dependency_cache) + if solved_result.errors: + errors.extend(solved_result.errors) continue if sub_dependant.use_cache and sub_dependant.cache_key in dependency_cache: solved = dependency_cache[sub_dependant.cache_key] elif is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( - call=call, stack=async_exit_stack, sub_values=sub_values + call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): - solved = await call(**sub_values) + solved = await call(**solved_result.values) else: - solved = await run_in_threadpool(call, **sub_values) + solved = await run_in_threadpool(call, **solved_result.values) if sub_dependant.name is not None: values[sub_dependant.name] = solved if sub_dependant.cache_key not in dependency_cache: @@ -624,7 +664,9 @@ async def solve_dependencies( body_values, body_errors, ) = await request_body_to_args( # body_params checked above - required_params=dependant.body_params, received_body=body + body_fields=dependant.body_params, + received_body=body, + embed_body_fields=embed_body_fields, ) values.update(body_values) errors.extend(body_errors) @@ -644,142 +686,257 @@ async def solve_dependencies( values[dependant.security_scopes_param_name] = SecurityScopes( scopes=dependant.security_scopes ) - return values, errors, background_tasks, response, dependency_cache + return SolvedDependency( + values=values, + errors=errors, + background_tasks=background_tasks, + response=response, + dependency_cache=dependency_cache, + ) + + +def _validate_value_with_model_field( + *, field: ModelField, value: Any, values: Dict[str, Any], loc: Tuple[str, ...] +) -> Tuple[Any, List[Any]]: + if value is None: + if field.required: + return None, [get_missing_field_error(loc=loc)] + else: + return deepcopy(field.default), [] + v_, errors_ = field.validate(value, values, loc=loc) + if isinstance(errors_, ErrorWrapper): + return None, [errors_] + elif isinstance(errors_, list): + new_errors = _regenerate_error_with_loc(errors=errors_, loc_prefix=()) + return None, new_errors + else: + return v_, [] + + +def _get_multidict_value( + field: ModelField, values: Mapping[str, Any], alias: Union[str, None] = None +) -> Any: + alias = alias or field.alias + if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): + value = values.getlist(alias) + else: + value = values.get(alias, None) + if ( + value is None + or ( + isinstance(field.field_info, params.Form) + and isinstance(value, str) # For type checks + and value == "" + ) + or (is_sequence_field(field) and len(value) == 0) + ): + if field.required: + return + else: + return deepcopy(field.default) + return value def request_params_to_args( - required_params: Sequence[ModelField], + fields: Sequence[ModelField], received_params: Union[Mapping[str, Any], QueryParams, Headers], ) -> Tuple[Dict[str, Any], List[Any]]: - values = {} - errors = [] - for field in required_params: - if is_scalar_sequence_field(field) and isinstance( - received_params, (QueryParams, Headers) - ): - value = received_params.getlist(field.alias) or field.default - else: - value = received_params.get(field.alias) + values: Dict[str, Any] = {} + errors: List[Dict[str, Any]] = [] + + if not fields: + return values, errors + + first_field = fields[0] + fields_to_extract = fields + single_not_embedded_field = False + if len(fields) == 1 and lenient_issubclass(first_field.type_, BaseModel): + fields_to_extract = get_cached_model_fields(first_field.type_) + single_not_embedded_field = True + + params_to_process: Dict[str, Any] = {} + + processed_keys = set() + + for field in fields_to_extract: + alias = None + if isinstance(received_params, Headers): + # Handle fields extracted from a Pydantic Model for a header, each field + # doesn't have a FieldInfo of type Header with the default convert_underscores=True + convert_underscores = getattr(field.field_info, "convert_underscores", True) + if convert_underscores: + alias = ( + field.alias + if field.alias != field.name + else field.name.replace("_", "-") + ) + value = _get_multidict_value(field, received_params, alias=alias) + if value is not None: + params_to_process[field.name] = value + processed_keys.add(alias or field.alias) + processed_keys.add(field.name) + + for key, value in received_params.items(): + if key not in processed_keys: + params_to_process[key] = value + + if single_not_embedded_field: + field_info = first_field.field_info + assert isinstance( + field_info, params.Param + ), "Params must be subclasses of Param" + loc: Tuple[str, ...] = (field_info.in_.value,) + v_, errors_ = _validate_value_with_model_field( + field=first_field, value=params_to_process, values=values, loc=loc + ) + return {first_field.name: v_}, errors_ + + for field in fields: + value = _get_multidict_value(field, received_params) field_info = field.field_info assert isinstance( field_info, params.Param ), "Params must be subclasses of Param" loc = (field_info.in_.value, field.alias) - if value is None: - if field.required: - errors.append(get_missing_field_error(loc=loc)) - else: - values[field.name] = deepcopy(field.default) - continue - v_, errors_ = field.validate(value, values, loc=loc) - if isinstance(errors_, ErrorWrapper): - errors.append(errors_) - elif isinstance(errors_, list): - new_errors = _regenerate_error_with_loc(errors=errors_, loc_prefix=()) - errors.extend(new_errors) + v_, errors_ = _validate_value_with_model_field( + field=field, value=value, values=values, loc=loc + ) + if errors_: + errors.extend(errors_) else: values[field.name] = v_ return values, errors +def _should_embed_body_fields(fields: List[ModelField]) -> bool: + if not fields: + return False + # More than one dependency could have the same field, it would show up as multiple + # fields but it's the same one, so count them by name + body_param_names_set = {field.name for field in fields} + # A top level field has to be a single field, not multiple + if len(body_param_names_set) > 1: + return True + first_field = fields[0] + # If it explicitly specifies it is embedded, it has to be embedded + if getattr(first_field.field_info, "embed", None): + return True + # If it's a Form (or File) field, it has to be a BaseModel to be top level + # otherwise it has to be embedded, so that the key value pair can be extracted + if isinstance(first_field.field_info, params.Form) and not lenient_issubclass( + first_field.type_, BaseModel + ): + return True + return False + + +async def _extract_form_body( + body_fields: List[ModelField], + received_body: FormData, +) -> Dict[str, Any]: + values = {} + first_field = body_fields[0] + first_field_info = first_field.field_info + + for field in body_fields: + value = _get_multidict_value(field, received_body) + if ( + isinstance(first_field_info, params.File) + and is_bytes_field(field) + and isinstance(value, UploadFile) + ): + value = await value.read() + elif ( + is_bytes_sequence_field(field) + and isinstance(first_field_info, params.File) + and value_is_sequence(value) + ): + # For types + assert isinstance(value, sequence_types) # type: ignore[arg-type] + results: List[Union[bytes, str]] = [] + + async def process_fn( + fn: Callable[[], Coroutine[Any, Any, Any]], + ) -> None: + result = await fn() + results.append(result) # noqa: B023 + + async with anyio.create_task_group() as tg: + for sub_value in value: + tg.start_soon(process_fn, sub_value.read) + value = serialize_sequence_value(field=field, value=results) + if value is not None: + values[field.alias] = value + for key, value in received_body.items(): + if key not in values: + values[key] = value + return values + + async def request_body_to_args( - required_params: List[ModelField], + body_fields: List[ModelField], received_body: Optional[Union[Dict[str, Any], FormData]], + embed_body_fields: bool, ) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]: - values = {} + values: Dict[str, Any] = {} errors: List[Dict[str, Any]] = [] - if required_params: - field = required_params[0] - field_info = field.field_info - embed = getattr(field_info, "embed", None) - field_alias_omitted = len(required_params) == 1 and not embed - if field_alias_omitted: - received_body = {field.alias: received_body} - - for field in required_params: - loc: Tuple[str, ...] - if field_alias_omitted: - loc = ("body",) - else: - loc = ("body", field.alias) - - value: Optional[Any] = None - if received_body is not None: - if (is_sequence_field(field)) and isinstance(received_body, FormData): - value = received_body.getlist(field.alias) - else: - try: - value = received_body.get(field.alias) - except AttributeError: - errors.append(get_missing_field_error(loc)) - continue - if ( - value is None - or (isinstance(field_info, params.Form) and value == "") - or ( - isinstance(field_info, params.Form) - and is_sequence_field(field) - and len(value) == 0 - ) - ): - if field.required: - errors.append(get_missing_field_error(loc)) - else: - values[field.name] = deepcopy(field.default) + assert body_fields, "request_body_to_args() should be called with fields" + single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields + first_field = body_fields[0] + body_to_process = received_body + + fields_to_extract: List[ModelField] = body_fields + + if single_not_embedded_field and lenient_issubclass(first_field.type_, BaseModel): + fields_to_extract = get_cached_model_fields(first_field.type_) + + if isinstance(received_body, FormData): + body_to_process = await _extract_form_body(fields_to_extract, received_body) + + if single_not_embedded_field: + loc: Tuple[str, ...] = ("body",) + v_, errors_ = _validate_value_with_model_field( + field=first_field, value=body_to_process, values=values, loc=loc + ) + return {first_field.name: v_}, errors_ + for field in body_fields: + loc = ("body", field.alias) + value: Optional[Any] = None + if body_to_process is not None: + try: + value = body_to_process.get(field.alias) + # If the received body is a list, not a dict + except AttributeError: + errors.append(get_missing_field_error(loc)) continue - if ( - isinstance(field_info, params.File) - and is_bytes_field(field) - and isinstance(value, UploadFile) - ): - value = await value.read() - elif ( - is_bytes_sequence_field(field) - and isinstance(field_info, params.File) - and value_is_sequence(value) - ): - # For types - assert isinstance(value, sequence_types) # type: ignore[arg-type] - results: List[Union[bytes, str]] = [] - - async def process_fn( - fn: Callable[[], Coroutine[Any, Any, Any]] - ) -> None: - result = await fn() - results.append(result) # noqa: B023 - - async with anyio.create_task_group() as tg: - for sub_value in value: - tg.start_soon(process_fn, sub_value.read) - value = serialize_sequence_value(field=field, value=results) - - v_, errors_ = field.validate(value, values, loc=loc) - - if isinstance(errors_, list): - errors.extend(errors_) - elif errors_: - errors.append(errors_) - else: - values[field.name] = v_ + v_, errors_ = _validate_value_with_model_field( + field=field, value=value, values=values, loc=loc + ) + if errors_: + errors.extend(errors_) + else: + values[field.name] = v_ return values, errors -def get_body_field(*, dependant: Dependant, name: str) -> Optional[ModelField]: - flat_dependant = get_flat_dependant(dependant) +def get_body_field( + *, flat_dependant: Dependant, name: str, embed_body_fields: bool +) -> Optional[ModelField]: + """ + Get a ModelField representing the request body for a path operation, combining + all body parameters into a single field if necessary. + + Used to check if it's form data (with `isinstance(body_field, params.Form)`) + or JSON and to generate the JSON Schema for a request body. + + This is **not** used to validate/parse the request body, that's done with each + individual body parameter. + """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] - field_info = first_param.field_info - embed = getattr(field_info, "embed", None) - body_param_names_set = {param.name for param in flat_dependant.body_params} - if len(body_param_names_set) == 1 and not embed: - check_file_field(first_param) + if not embed_body_fields: return first_param - # If one field requires to embed, all have to be embedded - # in case a sub-dependency is evaluated with a single unique body field - # That is combined (embedded) with other body fields - for param in flat_dependant.body_params: - setattr(param.field_info, "embed", True) # noqa: B010 model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name @@ -805,12 +962,11 @@ def get_body_field(*, dependant: Dependant, name: str) -> Optional[ModelField]: ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] - final_field = create_response_field( + final_field = create_model_field( name="body", type_=BodyModel, required=required, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) - check_file_field(final_field) return final_field diff --git a/fastapi/encoders.py b/fastapi/encoders.py index e50171393..451ea0760 100644 --- a/fastapi/encoders.py +++ b/fastapi/encoders.py @@ -22,9 +22,9 @@ from pydantic import BaseModel from pydantic.color import Color from pydantic.networks import AnyUrl, NameEmail from pydantic.types import SecretBytes, SecretStr -from typing_extensions import Annotated, Doc # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc -from ._compat import PYDANTIC_V2, Url, _model_dump +from ._compat import PYDANTIC_V2, UndefinedType, Url, _model_dump # Taken from Pydantic v1 as is @@ -86,7 +86,7 @@ ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = { def generate_encoders_by_class_tuples( - type_encoder_map: Dict[Any, Callable[[Any], Any]] + type_encoder_map: Dict[Any, Callable[[Any], Any]], ) -> Dict[Callable[[Any], Any], Tuple[Any, ...]]: encoders_by_class_tuples: Dict[Callable[[Any], Any], Tuple[Any, ...]] = defaultdict( tuple @@ -259,6 +259,8 @@ def jsonable_encoder( return str(obj) if isinstance(obj, (str, int, float, type(None))): return obj + if isinstance(obj, UndefinedType): + return None if isinstance(obj, dict): encoded_dict = {} allowed_keys = set(obj.keys()) diff --git a/fastapi/exceptions.py b/fastapi/exceptions.py index 680d288e4..44d4ada86 100644 --- a/fastapi/exceptions.py +++ b/fastapi/exceptions.py @@ -3,7 +3,7 @@ from typing import Any, Dict, Optional, Sequence, Type, Union from pydantic import BaseModel, create_model from starlette.exceptions import HTTPException as StarletteHTTPException from starlette.exceptions import WebSocketException as StarletteWebSocketException -from typing_extensions import Annotated, Doc # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc class HTTPException(StarletteHTTPException): diff --git a/fastapi/openapi/docs.py b/fastapi/openapi/docs.py index 69473d19c..c2ec358d2 100644 --- a/fastapi/openapi/docs.py +++ b/fastapi/openapi/docs.py @@ -3,7 +3,7 @@ from typing import Any, Dict, Optional from fastapi.encoders import jsonable_encoder from starlette.responses import HTMLResponse -from typing_extensions import Annotated, Doc # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc swagger_ui_default_parameters: Annotated[ Dict[str, Any], @@ -53,7 +53,7 @@ def get_swagger_ui_html( It is normally set to a CDN URL. """ ), - ] = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.9.0/swagger-ui-bundle.js", + ] = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js", swagger_css_url: Annotated[ str, Doc( @@ -63,7 +63,7 @@ def get_swagger_ui_html( It is normally set to a CDN URL. """ ), - ] = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.9.0/swagger-ui.css", + ] = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css", swagger_favicon_url: Annotated[ str, Doc( diff --git a/fastapi/openapi/models.py b/fastapi/openapi/models.py index 5f3bdbb20..ed07b40f5 100644 --- a/fastapi/openapi/models.py +++ b/fastapi/openapi/models.py @@ -55,11 +55,7 @@ except ImportError: # pragma: no cover return with_info_plain_validator_function(cls._validate) -class Contact(BaseModel): - name: Optional[str] = None - url: Optional[AnyUrl] = None - email: Optional[EmailStr] = None - +class BaseModelWithConfig(BaseModel): if PYDANTIC_V2: model_config = {"extra": "allow"} @@ -69,21 +65,19 @@ class Contact(BaseModel): extra = "allow" -class License(BaseModel): - name: str - identifier: Optional[str] = None +class Contact(BaseModelWithConfig): + name: Optional[str] = None url: Optional[AnyUrl] = None + email: Optional[EmailStr] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - class Config: - extra = "allow" +class License(BaseModelWithConfig): + name: str + identifier: Optional[str] = None + url: Optional[AnyUrl] = None -class Info(BaseModel): +class Info(BaseModelWithConfig): title: str summary: Optional[str] = None description: Optional[str] = None @@ -92,42 +86,18 @@ class Info(BaseModel): license: Optional[License] = None version: str - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - class Config: - extra = "allow" - - -class ServerVariable(BaseModel): +class ServerVariable(BaseModelWithConfig): enum: Annotated[Optional[List[str]], Field(min_length=1)] = None default: str description: Optional[str] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - class Config: - extra = "allow" - - -class Server(BaseModel): +class Server(BaseModelWithConfig): url: Union[AnyUrl, str] description: Optional[str] = None variables: Optional[Dict[str, ServerVariable]] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - class Reference(BaseModel): ref: str = Field(alias="$ref") @@ -138,36 +108,20 @@ class Discriminator(BaseModel): mapping: Optional[Dict[str, str]] = None -class XML(BaseModel): +class XML(BaseModelWithConfig): name: Optional[str] = None namespace: Optional[str] = None prefix: Optional[str] = None attribute: Optional[bool] = None wrapped: Optional[bool] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - class Config: - extra = "allow" - - -class ExternalDocumentation(BaseModel): +class ExternalDocumentation(BaseModelWithConfig): description: Optional[str] = None url: AnyUrl - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - -class Schema(BaseModel): +class Schema(BaseModelWithConfig): # Ref: JSON Schema 2020-12: https://json-schema.org/draft/2020-12/json-schema-core.html#name-the-json-schema-core-vocabu # Core Vocabulary schema_: Optional[str] = Field(default=None, alias="$schema") @@ -253,14 +207,6 @@ class Schema(BaseModel): ), ] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - # Ref: https://json-schema.org/draft/2020-12/json-schema-core.html#name-json-schema-documents # A JSON Schema MUST be an object or a boolean. @@ -289,38 +235,22 @@ class ParameterInType(Enum): cookie = "cookie" -class Encoding(BaseModel): +class Encoding(BaseModelWithConfig): contentType: Optional[str] = None headers: Optional[Dict[str, Union["Header", Reference]]] = None style: Optional[str] = None explode: Optional[bool] = None allowReserved: Optional[bool] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - -class MediaType(BaseModel): +class MediaType(BaseModelWithConfig): schema_: Optional[Union[Schema, Reference]] = Field(default=None, alias="schema") example: Optional[Any] = None examples: Optional[Dict[str, Union[Example, Reference]]] = None encoding: Optional[Dict[str, Encoding]] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - -class ParameterBase(BaseModel): +class ParameterBase(BaseModelWithConfig): description: Optional[str] = None required: Optional[bool] = None deprecated: Optional[bool] = None @@ -334,14 +264,6 @@ class ParameterBase(BaseModel): # Serialization rules for more complex scenarios content: Optional[Dict[str, MediaType]] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - class Parameter(ParameterBase): name: str @@ -352,21 +274,13 @@ class Header(ParameterBase): pass -class RequestBody(BaseModel): +class RequestBody(BaseModelWithConfig): description: Optional[str] = None content: Dict[str, MediaType] required: Optional[bool] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - class Config: - extra = "allow" - - -class Link(BaseModel): +class Link(BaseModelWithConfig): operationRef: Optional[str] = None operationId: Optional[str] = None parameters: Optional[Dict[str, Union[Any, str]]] = None @@ -374,31 +288,15 @@ class Link(BaseModel): description: Optional[str] = None server: Optional[Server] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - -class Response(BaseModel): +class Response(BaseModelWithConfig): description: str headers: Optional[Dict[str, Union[Header, Reference]]] = None content: Optional[Dict[str, MediaType]] = None links: Optional[Dict[str, Union[Link, Reference]]] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - -class Operation(BaseModel): +class Operation(BaseModelWithConfig): tags: Optional[List[str]] = None summary: Optional[str] = None description: Optional[str] = None @@ -413,16 +311,8 @@ class Operation(BaseModel): security: Optional[List[Dict[str, List[str]]]] = None servers: Optional[List[Server]] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - class Config: - extra = "allow" - - -class PathItem(BaseModel): +class PathItem(BaseModelWithConfig): ref: Optional[str] = Field(default=None, alias="$ref") summary: Optional[str] = None description: Optional[str] = None @@ -437,14 +327,6 @@ class PathItem(BaseModel): servers: Optional[List[Server]] = None parameters: Optional[List[Union[Parameter, Reference]]] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - class SecuritySchemeType(Enum): apiKey = "apiKey" @@ -453,18 +335,10 @@ class SecuritySchemeType(Enum): openIdConnect = "openIdConnect" -class SecurityBase(BaseModel): +class SecurityBase(BaseModelWithConfig): type_: SecuritySchemeType = Field(alias="type") description: Optional[str] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - class APIKeyIn(Enum): query = "query" @@ -488,18 +362,10 @@ class HTTPBearer(HTTPBase): bearerFormat: Optional[str] = None -class OAuthFlow(BaseModel): +class OAuthFlow(BaseModelWithConfig): refreshUrl: Optional[str] = None scopes: Dict[str, str] = {} - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - class OAuthFlowImplicit(OAuthFlow): authorizationUrl: str @@ -518,20 +384,12 @@ class OAuthFlowAuthorizationCode(OAuthFlow): tokenUrl: str -class OAuthFlows(BaseModel): +class OAuthFlows(BaseModelWithConfig): implicit: Optional[OAuthFlowImplicit] = None password: Optional[OAuthFlowPassword] = None clientCredentials: Optional[OAuthFlowClientCredentials] = None authorizationCode: Optional[OAuthFlowAuthorizationCode] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - class OAuth2(SecurityBase): type_: SecuritySchemeType = Field(default=SecuritySchemeType.oauth2, alias="type") @@ -548,7 +406,7 @@ class OpenIdConnect(SecurityBase): SecurityScheme = Union[APIKey, HTTPBase, OAuth2, OpenIdConnect, HTTPBearer] -class Components(BaseModel): +class Components(BaseModelWithConfig): schemas: Optional[Dict[str, Union[Schema, Reference]]] = None responses: Optional[Dict[str, Union[Response, Reference]]] = None parameters: Optional[Dict[str, Union[Parameter, Reference]]] = None @@ -561,30 +419,14 @@ class Components(BaseModel): callbacks: Optional[Dict[str, Union[Dict[str, PathItem], Reference, Any]]] = None pathItems: Optional[Dict[str, Union[PathItem, Reference]]] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - -class Tag(BaseModel): +class Tag(BaseModelWithConfig): name: str description: Optional[str] = None externalDocs: Optional[ExternalDocumentation] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - -class OpenAPI(BaseModel): +class OpenAPI(BaseModelWithConfig): openapi: str info: Info jsonSchemaDialect: Optional[str] = None @@ -597,14 +439,6 @@ class OpenAPI(BaseModel): tags: Optional[List[Tag]] = None externalDocs: Optional[ExternalDocumentation] = None - if PYDANTIC_V2: - model_config = {"extra": "allow"} - - else: - - class Config: - extra = "allow" - _model_rebuild(Schema) _model_rebuild(Operation) diff --git a/fastapi/openapi/utils.py b/fastapi/openapi/utils.py index 5bfb5acef..947eca948 100644 --- a/fastapi/openapi/utils.py +++ b/fastapi/openapi/utils.py @@ -16,11 +16,15 @@ from fastapi._compat import ( ) from fastapi.datastructures import DefaultPlaceholder from fastapi.dependencies.models import Dependant -from fastapi.dependencies.utils import get_flat_dependant, get_flat_params +from fastapi.dependencies.utils import ( + _get_flat_fields_from_params, + get_flat_dependant, + get_flat_params, +) from fastapi.encoders import jsonable_encoder from fastapi.openapi.constants import METHODS_WITH_BODY, REF_PREFIX, REF_TEMPLATE from fastapi.openapi.models import OpenAPI -from fastapi.params import Body, Param +from fastapi.params import Body, ParamTypes from fastapi.responses import Response from fastapi.types import ModelNameMap from fastapi.utils import ( @@ -87,9 +91,9 @@ def get_openapi_security_definitions( return security_definitions, operation_security -def get_openapi_operation_parameters( +def _get_openapi_operation_parameters( *, - all_route_params: Sequence[ModelField], + dependant: Dependant, schema_generator: GenerateJsonSchema, model_name_map: ModelNameMap, field_mapping: Dict[ @@ -98,33 +102,47 @@ def get_openapi_operation_parameters( separate_input_output_schemas: bool = True, ) -> List[Dict[str, Any]]: parameters = [] - for param in all_route_params: - field_info = param.field_info - field_info = cast(Param, field_info) - if not field_info.include_in_schema: - continue - param_schema = get_schema_from_model_field( - field=param, - schema_generator=schema_generator, - model_name_map=model_name_map, - field_mapping=field_mapping, - separate_input_output_schemas=separate_input_output_schemas, - ) - parameter = { - "name": param.alias, - "in": field_info.in_.value, - "required": param.required, - "schema": param_schema, - } - if field_info.description: - parameter["description"] = field_info.description - if field_info.openapi_examples: - parameter["examples"] = jsonable_encoder(field_info.openapi_examples) - elif field_info.example != Undefined: - parameter["example"] = jsonable_encoder(field_info.example) - if field_info.deprecated: - parameter["deprecated"] = field_info.deprecated - parameters.append(parameter) + flat_dependant = get_flat_dependant(dependant, skip_repeats=True) + path_params = _get_flat_fields_from_params(flat_dependant.path_params) + query_params = _get_flat_fields_from_params(flat_dependant.query_params) + header_params = _get_flat_fields_from_params(flat_dependant.header_params) + cookie_params = _get_flat_fields_from_params(flat_dependant.cookie_params) + parameter_groups = [ + (ParamTypes.path, path_params), + (ParamTypes.query, query_params), + (ParamTypes.header, header_params), + (ParamTypes.cookie, cookie_params), + ] + for param_type, param_group in parameter_groups: + for param in param_group: + field_info = param.field_info + # field_info = cast(Param, field_info) + if not getattr(field_info, "include_in_schema", True): + continue + param_schema = get_schema_from_model_field( + field=param, + schema_generator=schema_generator, + model_name_map=model_name_map, + field_mapping=field_mapping, + separate_input_output_schemas=separate_input_output_schemas, + ) + parameter = { + "name": param.alias, + "in": param_type.value, + "required": param.required, + "schema": param_schema, + } + if field_info.description: + parameter["description"] = field_info.description + openapi_examples = getattr(field_info, "openapi_examples", None) + example = getattr(field_info, "example", None) + if openapi_examples: + parameter["examples"] = jsonable_encoder(openapi_examples) + elif example != Undefined: + parameter["example"] = jsonable_encoder(example) + if getattr(field_info, "deprecated", None): + parameter["deprecated"] = True + parameters.append(parameter) return parameters @@ -247,9 +265,8 @@ def get_openapi_path( operation.setdefault("security", []).extend(operation_security) if security_definitions: security_schemes.update(security_definitions) - all_route_params = get_flat_params(route.dependant) - operation_parameters = get_openapi_operation_parameters( - all_route_params=all_route_params, + operation_parameters = _get_openapi_operation_parameters( + dependant=route.dependant, schema_generator=schema_generator, model_name_map=model_name_map, field_mapping=field_mapping, @@ -379,6 +396,7 @@ def get_openapi_path( deep_dict_update(openapi_response, process_response) openapi_response["description"] = description http422 = str(HTTP_422_UNPROCESSABLE_ENTITY) + all_route_params = get_flat_params(route.dependant) if (all_route_params or route.body_field) and not any( status in operation["responses"] for status in [http422, "4XX", "default"] diff --git a/fastapi/param_functions.py b/fastapi/param_functions.py index 3f6dbc959..b3621626c 100644 --- a/fastapi/param_functions.py +++ b/fastapi/param_functions.py @@ -3,7 +3,7 @@ from typing import Any, Callable, Dict, List, Optional, Sequence, Union from fastapi import params from fastapi._compat import Undefined from fastapi.openapi.models import Example -from typing_extensions import Annotated, Doc, deprecated # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc, deprecated _Unset: Any = Undefined @@ -240,7 +240,7 @@ def Path( # noqa: N802 ), ] = None, deprecated: Annotated[ - Optional[bool], + Union[deprecated, str, bool, None], Doc( """ Mark this parameter field as deprecated. @@ -565,7 +565,7 @@ def Query( # noqa: N802 ), ] = None, deprecated: Annotated[ - Optional[bool], + Union[deprecated, str, bool, None], Doc( """ Mark this parameter field as deprecated. @@ -880,7 +880,7 @@ def Header( # noqa: N802 ), ] = None, deprecated: Annotated[ - Optional[bool], + Union[deprecated, str, bool, None], Doc( """ Mark this parameter field as deprecated. @@ -1185,7 +1185,7 @@ def Cookie( # noqa: N802 ), ] = None, deprecated: Annotated[ - Optional[bool], + Union[deprecated, str, bool, None], Doc( """ Mark this parameter field as deprecated. @@ -1282,7 +1282,7 @@ def Body( # noqa: N802 ), ] = _Unset, embed: Annotated[ - bool, + Union[bool, None], Doc( """ When `embed` is `True`, the parameter will be expected in a JSON body as a @@ -1294,7 +1294,7 @@ def Body( # noqa: N802 [FastAPI docs for Body - Multiple Parameters](https://fastapi.tiangolo.com/tutorial/body-multiple-params/#embed-a-single-body-parameter). """ ), - ] = False, + ] = None, media_type: Annotated[ str, Doc( @@ -1512,7 +1512,7 @@ def Body( # noqa: N802 ), ] = None, deprecated: Annotated[ - Optional[bool], + Union[deprecated, str, bool, None], Doc( """ Mark this parameter field as deprecated. @@ -1827,7 +1827,7 @@ def Form( # noqa: N802 ), ] = None, deprecated: Annotated[ - Optional[bool], + Union[deprecated, str, bool, None], Doc( """ Mark this parameter field as deprecated. @@ -2141,7 +2141,7 @@ def File( # noqa: N802 ), ] = None, deprecated: Annotated[ - Optional[bool], + Union[deprecated, str, bool, None], Doc( """ Mark this parameter field as deprecated. @@ -2298,7 +2298,7 @@ def Security( # noqa: N802 dependency. The term "scope" comes from the OAuth2 specification, it seems to be - intentionaly vague and interpretable. It normally refers to permissions, + intentionally vague and interpretable. It normally refers to permissions, in cases to roles. These scopes are integrated with OpenAPI (and the API docs at `/docs`). @@ -2343,7 +2343,7 @@ def Security( # noqa: N802 ```python from typing import Annotated - from fastapi import Depends, FastAPI + from fastapi import Security, FastAPI from .db import User from .security import get_current_active_user diff --git a/fastapi/params.py b/fastapi/params.py index b40944dba..8f5601dd3 100644 --- a/fastapi/params.py +++ b/fastapi/params.py @@ -6,7 +6,11 @@ from fastapi.openapi.models import Example from pydantic.fields import FieldInfo from typing_extensions import Annotated, deprecated -from ._compat import PYDANTIC_V2, Undefined +from ._compat import ( + PYDANTIC_V2, + PYDANTIC_VERSION_MINOR_TUPLE, + Undefined, +) _Unset: Any = Undefined @@ -63,12 +67,11 @@ class Param(FieldInfo): ), ] = _Unset, openapi_examples: Optional[Dict[str, Example]] = None, - deprecated: Optional[bool] = None, + deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, ): - self.deprecated = deprecated if example is not _Unset: warnings.warn( "`example` has been deprecated, please use `examples` instead", @@ -92,7 +95,7 @@ class Param(FieldInfo): max_length=max_length, discriminator=discriminator, multiple_of=multiple_of, - allow_nan=allow_inf_nan, + allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, **extra, @@ -106,6 +109,10 @@ class Param(FieldInfo): stacklevel=4, ) current_json_schema_extra = json_schema_extra or extra + if PYDANTIC_VERSION_MINOR_TUPLE < (2, 7): + self.deprecated = deprecated + else: + kwargs["deprecated"] = deprecated if PYDANTIC_V2: kwargs.update( { @@ -174,7 +181,7 @@ class Path(Param): ), ] = _Unset, openapi_examples: Optional[Dict[str, Example]] = None, - deprecated: Optional[bool] = None, + deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, @@ -260,7 +267,7 @@ class Query(Param): ), ] = _Unset, openapi_examples: Optional[Dict[str, Example]] = None, - deprecated: Optional[bool] = None, + deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, @@ -345,7 +352,7 @@ class Header(Param): ), ] = _Unset, openapi_examples: Optional[Dict[str, Example]] = None, - deprecated: Optional[bool] = None, + deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, @@ -430,7 +437,7 @@ class Cookie(Param): ), ] = _Unset, openapi_examples: Optional[Dict[str, Example]] = None, - deprecated: Optional[bool] = None, + deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, @@ -476,7 +483,7 @@ class Body(FieldInfo): *, default_factory: Union[Callable[[], Any], None] = _Unset, annotation: Optional[Any] = None, - embed: bool = False, + embed: Union[bool, None] = None, media_type: str = "application/json", alias: Optional[str] = None, alias_priority: Union[int, None] = _Unset, @@ -514,14 +521,13 @@ class Body(FieldInfo): ), ] = _Unset, openapi_examples: Optional[Dict[str, Example]] = None, - deprecated: Optional[bool] = None, + deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, ): self.embed = embed self.media_type = media_type - self.deprecated = deprecated if example is not _Unset: warnings.warn( "`example` has been deprecated, please use `examples` instead", @@ -545,7 +551,7 @@ class Body(FieldInfo): max_length=max_length, discriminator=discriminator, multiple_of=multiple_of, - allow_nan=allow_inf_nan, + allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, **extra, @@ -554,11 +560,15 @@ class Body(FieldInfo): kwargs["examples"] = examples if regex is not None: warnings.warn( - "`regex` has been depreacated, please use `pattern` instead", + "`regex` has been deprecated, please use `pattern` instead", category=DeprecationWarning, stacklevel=4, ) current_json_schema_extra = json_schema_extra or extra + if PYDANTIC_VERSION_MINOR_TUPLE < (2, 7): + self.deprecated = deprecated + else: + kwargs["deprecated"] = deprecated if PYDANTIC_V2: kwargs.update( { @@ -627,7 +637,7 @@ class Form(Body): ), ] = _Unset, openapi_examples: Optional[Dict[str, Example]] = None, - deprecated: Optional[bool] = None, + deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, @@ -636,7 +646,6 @@ class Form(Body): default=default, default_factory=default_factory, annotation=annotation, - embed=True, media_type=media_type, alias=alias, alias_priority=alias_priority, @@ -712,7 +721,7 @@ class File(Form): ), ] = _Unset, openapi_examples: Optional[Dict[str, Example]] = None, - deprecated: Optional[bool] = None, + deprecated: Union[deprecated, str, bool, None] = None, include_in_schema: bool = True, json_schema_extra: Union[Dict[str, Any], None] = None, **extra: Any, diff --git a/fastapi/routing.py b/fastapi/routing.py index e52b633a1..6469ef3ce 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -3,14 +3,16 @@ import dataclasses import email.message import inspect import json -from contextlib import AsyncExitStack +from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, + AsyncIterator, Callable, Coroutine, Dict, List, + Mapping, Optional, Sequence, Set, @@ -31,8 +33,10 @@ from fastapi._compat import ( from fastapi.datastructures import Default, DefaultPlaceholder from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( + _should_embed_body_fields, get_body_field, get_dependant, + get_flat_dependant, get_parameterless_sub_dependant, get_typed_return_annotation, solve_dependencies, @@ -47,7 +51,7 @@ from fastapi.exceptions import ( from fastapi.types import DecoratedCallable, IncEx from fastapi.utils import ( create_cloned_field, - create_response_field, + create_model_field, generate_unique_id, get_value_or_default, is_body_allowed_for_status_code, @@ -67,9 +71,9 @@ from starlette.routing import ( websocket_session, ) from starlette.routing import Mount as Mount # noqa -from starlette.types import ASGIApp, Lifespan, Scope +from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket -from typing_extensions import Annotated, Doc, deprecated # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc, deprecated def _prepare_response_content( @@ -119,6 +123,23 @@ def _prepare_response_content( return res +def _merge_lifespan_context( + original_context: Lifespan[Any], nested_context: Lifespan[Any] +) -> Lifespan[Any]: + @asynccontextmanager + async def merged_lifespan( + app: AppType, + ) -> AsyncIterator[Optional[Mapping[str, Any]]]: + async with original_context(app) as maybe_original_state: + async with nested_context(app) as maybe_nested_state: + if maybe_nested_state is None and maybe_original_state is None: + yield None # old ASGI compatibility + else: + yield {**(maybe_nested_state or {}), **(maybe_original_state or {})} + + return merged_lifespan # type: ignore[return-value] + + async def serialize_response( *, field: Optional[ModelField] = None, @@ -206,6 +227,7 @@ def get_request_handler( response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, dependency_overrides_provider: Optional[Any] = None, + embed_body_fields: bool = False, ) -> Callable[[Request], Coroutine[Any, Any, Response]]: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = asyncio.iscoroutinefunction(dependant.call) @@ -216,19 +238,14 @@ def get_request_handler( actual_response_class = response_class async def app(request: Request) -> Response: - exception_to_reraise: Optional[Exception] = None response: Union[Response, None] = None - async with AsyncExitStack() as async_exit_stack: - # TODO: remove this scope later, after a few releases - # This scope fastapi_astack is no longer used by FastAPI, kept for - # compatibility, just in case - request.scope["fastapi_astack"] = async_exit_stack + async with AsyncExitStack() as file_stack: try: body: Any = None if body_field: if is_body_form: body = await request.form() - async_exit_stack.push_async_callback(body.close) + file_stack.push_async_callback(body.close) else: body_bytes = await request.body() if body_bytes: @@ -260,86 +277,90 @@ def get_request_handler( ], body=e.doc, ) - exception_to_reraise = validation_error raise validation_error from e - except HTTPException as e: - exception_to_reraise = e + except HTTPException: + # If a middleware raises an HTTPException, it should be raised again raise except Exception as e: http_error = HTTPException( status_code=400, detail="There was an error parsing the body" ) - exception_to_reraise = http_error raise http_error from e - try: + errors: List[Any] = [] + async with AsyncExitStack() as async_exit_stack: solved_result = await solve_dependencies( request=request, dependant=dependant, body=body, dependency_overrides_provider=dependency_overrides_provider, async_exit_stack=async_exit_stack, + embed_body_fields=embed_body_fields, ) - values, errors, background_tasks, sub_response, _ = solved_result - except Exception as e: - exception_to_reraise = e - raise e + errors = solved_result.errors + if not errors: + raw_response = await run_endpoint_function( + dependant=dependant, + values=solved_result.values, + is_coroutine=is_coroutine, + ) + if isinstance(raw_response, Response): + if raw_response.background is None: + raw_response.background = solved_result.background_tasks + response = raw_response + else: + response_args: Dict[str, Any] = { + "background": solved_result.background_tasks + } + # If status_code was set, use it, otherwise use the default from the + # response class, in the case of redirect it's 307 + current_status_code = ( + status_code + if status_code + else solved_result.response.status_code + ) + if current_status_code is not None: + response_args["status_code"] = current_status_code + if solved_result.response.status_code: + response_args["status_code"] = ( + solved_result.response.status_code + ) + content = await serialize_response( + field=response_field, + response_content=raw_response, + include=response_model_include, + exclude=response_model_exclude, + by_alias=response_model_by_alias, + exclude_unset=response_model_exclude_unset, + exclude_defaults=response_model_exclude_defaults, + exclude_none=response_model_exclude_none, + is_coroutine=is_coroutine, + ) + response = actual_response_class(content, **response_args) + if not is_body_allowed_for_status_code(response.status_code): + response.body = b"" + response.headers.raw.extend(solved_result.response.headers.raw) if errors: validation_error = RequestValidationError( _normalize_errors(errors), body=body ) - exception_to_reraise = validation_error raise validation_error - else: - try: - raw_response = await run_endpoint_function( - dependant=dependant, values=values, is_coroutine=is_coroutine - ) - except Exception as e: - exception_to_reraise = e - raise e - if isinstance(raw_response, Response): - if raw_response.background is None: - raw_response.background = background_tasks - response = raw_response - else: - response_args: Dict[str, Any] = {"background": background_tasks} - # If status_code was set, use it, otherwise use the default from the - # response class, in the case of redirect it's 307 - current_status_code = ( - status_code if status_code else sub_response.status_code - ) - if current_status_code is not None: - response_args["status_code"] = current_status_code - if sub_response.status_code: - response_args["status_code"] = sub_response.status_code - content = await serialize_response( - field=response_field, - response_content=raw_response, - include=response_model_include, - exclude=response_model_exclude, - by_alias=response_model_by_alias, - exclude_unset=response_model_exclude_unset, - exclude_defaults=response_model_exclude_defaults, - exclude_none=response_model_exclude_none, - is_coroutine=is_coroutine, - ) - response = actual_response_class(content, **response_args) - if not is_body_allowed_for_status_code(response.status_code): - response.body = b"" - response.headers.raw.extend(sub_response.headers.raw) - # This exception was possibly handled by the dependency but it should - # still bubble up so that the ServerErrorMiddleware can return a 500 - # or the ExceptionMiddleware can catch and handle any other exceptions - if exception_to_reraise: - raise exception_to_reraise - assert response is not None, "An error occurred while generating the request" + if response is None: + raise FastAPIError( + "No response object was returned. There's a high chance that the " + "application code is raising an exception and a dependency with yield " + "has a block with a bare except, or a block with except Exception, " + "and is not raising the exception again. Read more about it in the " + "docs: https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-except" + ) return response return app def get_websocket_app( - dependant: Dependant, dependency_overrides_provider: Optional[Any] = None + dependant: Dependant, + dependency_overrides_provider: Optional[Any] = None, + embed_body_fields: bool = False, ) -> Callable[[WebSocket], Coroutine[Any, Any, Any]]: async def app(websocket: WebSocket) -> None: async with AsyncExitStack() as async_exit_stack: @@ -352,12 +373,14 @@ def get_websocket_app( dependant=dependant, dependency_overrides_provider=dependency_overrides_provider, async_exit_stack=async_exit_stack, + embed_body_fields=embed_body_fields, ) - values, errors, _, _2, _3 = solved_result - if errors: - raise WebSocketRequestValidationError(_normalize_errors(errors)) + if solved_result.errors: + raise WebSocketRequestValidationError( + _normalize_errors(solved_result.errors) + ) assert dependant.call is not None, "dependant.call must be a function" - await dependant.call(**values) + await dependant.call(**solved_result.values) return app @@ -383,11 +406,15 @@ class APIWebSocketRoute(routing.WebSocketRoute): 0, get_parameterless_sub_dependant(depends=depends, path=self.path_format), ) - + self._flat_dependant = get_flat_dependant(self.dependant) + self._embed_body_fields = _should_embed_body_fields( + self._flat_dependant.body_params + ) self.app = websocket_session( get_websocket_app( dependant=self.dependant, dependency_overrides_provider=dependency_overrides_provider, + embed_body_fields=self._embed_body_fields, ) ) @@ -467,9 +494,9 @@ class APIRoute(routing.Route): methods = ["GET"] self.methods: Set[str] = {method.upper() for method in methods} if isinstance(generate_unique_id_function, DefaultPlaceholder): - current_generate_unique_id: Callable[ - ["APIRoute"], str - ] = generate_unique_id_function.value + current_generate_unique_id: Callable[[APIRoute], str] = ( + generate_unique_id_function.value + ) else: current_generate_unique_id = generate_unique_id_function self.unique_id = self.operation_id or current_generate_unique_id(self) @@ -482,7 +509,7 @@ class APIRoute(routing.Route): status_code ), f"Status code {status_code} must not have a response body" response_name = "Response_" + self.unique_id - self.response_field = create_response_field( + self.response_field = create_model_field( name=response_name, type_=self.response_model, mode="serialization", @@ -495,9 +522,9 @@ class APIRoute(routing.Route): # By being a new field, no inheritance will be passed as is. A new model # will always be created. # TODO: remove when deprecating Pydantic v1 - self.secure_cloned_response_field: Optional[ - ModelField - ] = create_cloned_field(self.response_field) + self.secure_cloned_response_field: Optional[ModelField] = ( + create_cloned_field(self.response_field) + ) else: self.response_field = None # type: ignore self.secure_cloned_response_field = None @@ -515,7 +542,9 @@ class APIRoute(routing.Route): additional_status_code ), f"Status code {additional_status_code} must not have a response body" response_name = f"Response_{additional_status_code}_{self.unique_id}" - response_field = create_response_field(name=response_name, type_=model) + response_field = create_model_field( + name=response_name, type_=model, mode="serialization" + ) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], ModelField] = response_fields @@ -529,7 +558,15 @@ class APIRoute(routing.Route): 0, get_parameterless_sub_dependant(depends=depends, path=self.path_format), ) - self.body_field = get_body_field(dependant=self.dependant, name=self.unique_id) + self._flat_dependant = get_flat_dependant(self.dependant) + self._embed_body_fields = _should_embed_body_fields( + self._flat_dependant.body_params + ) + self.body_field = get_body_field( + flat_dependant=self._flat_dependant, + name=self.unique_id, + embed_body_fields=self._embed_body_fields, + ) self.app = request_response(self.get_route_handler()) self.is_auto_options = is_auto_options @@ -547,6 +584,7 @@ class APIRoute(routing.Route): response_model_exclude_defaults=self.response_model_exclude_defaults, response_model_exclude_none=self.response_model_exclude_none, dependency_overrides_provider=self.dependency_overrides_provider, + embed_body_fields=self._embed_body_fields, ) def matches(self, scope: Scope) -> Tuple[Match, Scope]: @@ -1356,6 +1394,10 @@ class APIRouter(routing.Router): self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) + self.lifespan_context = _merge_lifespan_context( + self.lifespan_context, + router.lifespan_context, + ) def get( self, diff --git a/fastapi/security/api_key.py b/fastapi/security/api_key.py index b1a6b4f94..70c2dca8a 100644 --- a/fastapi/security/api_key.py +++ b/fastapi/security/api_key.py @@ -5,11 +5,19 @@ from fastapi.security.base import SecurityBase from starlette.exceptions import HTTPException from starlette.requests import Request from starlette.status import HTTP_403_FORBIDDEN -from typing_extensions import Annotated, Doc # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc class APIKeyBase(SecurityBase): - pass + @staticmethod + def check_api_key(api_key: Optional[str], auto_error: bool) -> Optional[str]: + if not api_key: + if auto_error: + raise HTTPException( + status_code=HTTP_403_FORBIDDEN, detail="Not authenticated" + ) + return None + return api_key class APIKeyQuery(APIKeyBase): @@ -76,7 +84,7 @@ class APIKeyQuery(APIKeyBase): Doc( """ By default, if the query parameter is not provided, `APIKeyQuery` will - automatically cancel the request and sebd the client an error. + automatically cancel the request and send the client an error. If `auto_error` is set to `False`, when the query parameter is not available, instead of erroring out, the dependency result will be @@ -101,14 +109,7 @@ class APIKeyQuery(APIKeyBase): async def __call__(self, request: Request) -> Optional[str]: api_key = request.query_params.get(self.model.name) - if not api_key: - if self.auto_error: - raise HTTPException( - status_code=HTTP_403_FORBIDDEN, detail="Not authenticated" - ) - else: - return None - return api_key + return self.check_api_key(api_key, self.auto_error) class APIKeyHeader(APIKeyBase): @@ -196,14 +197,7 @@ class APIKeyHeader(APIKeyBase): async def __call__(self, request: Request) -> Optional[str]: api_key = request.headers.get(self.model.name) - if not api_key: - if self.auto_error: - raise HTTPException( - status_code=HTTP_403_FORBIDDEN, detail="Not authenticated" - ) - else: - return None - return api_key + return self.check_api_key(api_key, self.auto_error) class APIKeyCookie(APIKeyBase): @@ -291,11 +285,4 @@ class APIKeyCookie(APIKeyBase): async def __call__(self, request: Request) -> Optional[str]: api_key = request.cookies.get(self.model.name) - if not api_key: - if self.auto_error: - raise HTTPException( - status_code=HTTP_403_FORBIDDEN, detail="Not authenticated" - ) - else: - return None - return api_key + return self.check_api_key(api_key, self.auto_error) diff --git a/fastapi/security/http.py b/fastapi/security/http.py index 738455de3..9ab2df3c9 100644 --- a/fastapi/security/http.py +++ b/fastapi/security/http.py @@ -10,12 +10,12 @@ from fastapi.security.utils import get_authorization_scheme_param from pydantic import BaseModel from starlette.requests import Request from starlette.status import HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN -from typing_extensions import Annotated, Doc # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc class HTTPBasicCredentials(BaseModel): """ - The HTTP Basic credendials given as the result of using `HTTPBasic` in a + The HTTP Basic credentials given as the result of using `HTTPBasic` in a dependency. Read more about it in the @@ -277,7 +277,7 @@ class HTTPBearer(HTTPBase): bool, Doc( """ - By default, if the HTTP Bearer token not provided (in an + By default, if the HTTP Bearer token is not provided (in an `Authorization` header), `HTTPBearer` will automatically cancel the request and send the client an error. @@ -380,7 +380,7 @@ class HTTPDigest(HTTPBase): bool, Doc( """ - By default, if the HTTP Digest not provided, `HTTPDigest` will + By default, if the HTTP Digest is not provided, `HTTPDigest` will automatically cancel the request and send the client an error. If `auto_error` is set to `False`, when the HTTP Digest is not @@ -413,8 +413,11 @@ class HTTPDigest(HTTPBase): else: return None if scheme.lower() != "digest": - raise HTTPException( - status_code=HTTP_403_FORBIDDEN, - detail="Invalid authentication credentials", - ) + if self.auto_error: + raise HTTPException( + status_code=HTTP_403_FORBIDDEN, + detail="Invalid authentication credentials", + ) + else: + return None return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials) diff --git a/fastapi/security/oauth2.py b/fastapi/security/oauth2.py index 9281dfb64..5ffad5986 100644 --- a/fastapi/security/oauth2.py +++ b/fastapi/security/oauth2.py @@ -10,7 +10,7 @@ from starlette.requests import Request from starlette.status import HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN # TODO: import from typing when deprecating Python 3.9 -from typing_extensions import Annotated, Doc # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc class OAuth2PasswordRequestForm: @@ -52,9 +52,9 @@ class OAuth2PasswordRequestForm: ``` Note that for OAuth2 the scope `items:read` is a single scope in an opaque string. - You could have custom internal logic to separate it by colon caracters (`:`) or + You could have custom internal logic to separate it by colon characters (`:`) or similar, and get the two parts `items` and `read`. Many applications do that to - group and organize permisions, you could do it as well in your application, just + group and organize permissions, you could do it as well in your application, just know that that it is application specific, it's not part of the specification. """ @@ -63,7 +63,7 @@ class OAuth2PasswordRequestForm: *, grant_type: Annotated[ Union[str, None], - Form(pattern="password"), + Form(pattern="^password$"), Doc( """ The OAuth2 spec says it is required and MUST be the fixed string @@ -194,9 +194,9 @@ class OAuth2PasswordRequestFormStrict(OAuth2PasswordRequestForm): ``` Note that for OAuth2 the scope `items:read` is a single scope in an opaque string. - You could have custom internal logic to separate it by colon caracters (`:`) or + You could have custom internal logic to separate it by colon characters (`:`) or similar, and get the two parts `items` and `read`. Many applications do that to - group and organize permisions, you could do it as well in your application, just + group and organize permissions, you could do it as well in your application, just know that that it is application specific, it's not part of the specification. @@ -217,7 +217,7 @@ class OAuth2PasswordRequestFormStrict(OAuth2PasswordRequestForm): self, grant_type: Annotated[ str, - Form(pattern="password"), + Form(pattern="^password$"), Doc( """ The OAuth2 spec says it is required and MUST be the fixed string @@ -353,7 +353,7 @@ class OAuth2(SecurityBase): bool, Doc( """ - By default, if no HTTP Auhtorization header is provided, required for + By default, if no HTTP Authorization header is provided, required for OAuth2 authentication, it will automatically cancel the request and send the client an error. @@ -441,7 +441,7 @@ class OAuth2PasswordBearer(OAuth2): bool, Doc( """ - By default, if no HTTP Auhtorization header is provided, required for + By default, if no HTTP Authorization header is provided, required for OAuth2 authentication, it will automatically cancel the request and send the client an error. @@ -543,7 +543,7 @@ class OAuth2AuthorizationCodeBearer(OAuth2): bool, Doc( """ - By default, if no HTTP Auhtorization header is provided, required for + By default, if no HTTP Authorization header is provided, required for OAuth2 authentication, it will automatically cancel the request and send the client an error. diff --git a/fastapi/security/open_id_connect_url.py b/fastapi/security/open_id_connect_url.py index c612b475d..c8cceb911 100644 --- a/fastapi/security/open_id_connect_url.py +++ b/fastapi/security/open_id_connect_url.py @@ -5,7 +5,7 @@ from fastapi.security.base import SecurityBase from starlette.exceptions import HTTPException from starlette.requests import Request from starlette.status import HTTP_403_FORBIDDEN -from typing_extensions import Annotated, Doc # type: ignore [attr-defined] +from typing_extensions import Annotated, Doc class OpenIdConnect(SecurityBase): @@ -49,7 +49,7 @@ class OpenIdConnect(SecurityBase): bool, Doc( """ - By default, if no HTTP Auhtorization header is provided, required for + By default, if no HTTP Authorization header is provided, required for OpenID Connect authentication, it will automatically cancel the request and send the client an error. diff --git a/fastapi/utils.py b/fastapi/utils.py index 0019c2153..4c7350fea 100644 --- a/fastapi/utils.py +++ b/fastapi/utils.py @@ -34,9 +34,9 @@ if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute # Cache for `create_cloned_field` -_CLONED_TYPES_CACHE: MutableMapping[ - Type[BaseModel], Type[BaseModel] -] = WeakKeyDictionary() +_CLONED_TYPES_CACHE: MutableMapping[Type[BaseModel], Type[BaseModel]] = ( + WeakKeyDictionary() +) def is_body_allowed_for_status_code(status_code: Union[int, str, None]) -> bool: @@ -53,16 +53,16 @@ def is_body_allowed_for_status_code(status_code: Union[int, str, None]) -> bool: }: return True current_status_code = int(status_code) - return not (current_status_code < 200 or current_status_code in {204, 304}) + return not (current_status_code < 200 or current_status_code in {204, 205, 304}) def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) -def create_response_field( +def create_model_field( name: str, - type_: Type[Any], + type_: Any, class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = Undefined, required: Union[bool, UndefinedType] = Undefined, @@ -71,9 +71,6 @@ def create_response_field( alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: - """ - Create a new response field. Raises if type_ is invalid. - """ class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( @@ -135,7 +132,7 @@ def create_cloned_field( use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) - new_field = create_response_field(name=field.name, type_=use_type) + new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] @@ -221,9 +218,3 @@ def get_value_or_default( if not isinstance(item, DefaultPlaceholder): return item return first_item - - -def match_pydantic_error_url(error_type: str) -> Any: - from dirty_equals import IsStr - - return IsStr(regex=rf"^https://errors\.pydantic\.dev/.*/v/{error_type}") diff --git a/pdm_build.py b/pdm_build.py new file mode 100644 index 000000000..c83222b33 --- /dev/null +++ b/pdm_build.py @@ -0,0 +1,20 @@ +import os +from typing import Any, Dict + +from pdm.backend.hooks import Context + +TIANGOLO_BUILD_PACKAGE = os.getenv("TIANGOLO_BUILD_PACKAGE", "fastapi") + + +def pdm_build_initialize(context: Context) -> None: + metadata = context.config.metadata + # Get custom config for the current package, from the env var + config: Dict[str, Any] = context.config.data["tool"]["tiangolo"][ + "_internal-slim-build" + ]["packages"].get(TIANGOLO_BUILD_PACKAGE) + if not config: + return + project_config: Dict[str, Any] = config["project"] + # Override main [project] configs with custom configs for this package + for key, value in project_config.items(): + metadata[key] = value diff --git a/pyproject.toml b/pyproject.toml index 3e43f35e1..1c540e2f6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,13 +1,13 @@ [build-system] -requires = ["hatchling >= 1.13.0"] -build-backend = "hatchling.build" +requires = ["pdm-backend"] +build-backend = "pdm.backend" [project] name = "fastapi" +dynamic = ["version"] description = "FastAPI framework, high performance, easy to learn, fast to code, ready for production" readme = "README.md" requires-python = ">=3.8" -license = "MIT" authors = [ { name = "Sebastián Ramírez", email = "tiangolo@gmail.com" }, ] @@ -29,6 +29,7 @@ classifiers = [ "Framework :: FastAPI", "Framework :: Pydantic", "Framework :: Pydantic :: 1", + "Framework :: Pydantic :: 2", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3 :: Only", @@ -37,38 +38,89 @@ classifiers = [ "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", "Topic :: Internet :: WWW/HTTP :: HTTP Servers", "Topic :: Internet :: WWW/HTTP", ] dependencies = [ - "starlette>=0.35.0,<0.36.0", + "starlette>=0.40.0,<0.47.0", "pydantic>=1.7.4,!=1.8,!=1.8.1,!=2.0.0,!=2.0.1,!=2.1.0,<3.0.0", "typing-extensions>=4.8.0", ] -dynamic = ["version"] [project.urls] -Homepage = "https://github.com/tiangolo/fastapi" +Homepage = "https://github.com/fastapi/fastapi" Documentation = "https://fastapi.tiangolo.com/" -Repository = "https://github.com/tiangolo/fastapi" +Repository = "https://github.com/fastapi/fastapi" +Issues = "https://github.com/fastapi/fastapi/issues" +Changelog = "https://fastapi.tiangolo.com/release-notes/" [project.optional-dependencies] + +standard = [ + "fastapi-cli[standard] >=0.0.5", + # For the test client + "httpx >=0.23.0", + # For templates + "jinja2 >=3.1.5", + # For forms and file uploads + "python-multipart >=0.0.18", + # To validate email fields + "email-validator >=2.0.0", + # Uvicorn with uvloop + "uvicorn[standard] >=0.12.0", + # TODO: this should be part of some pydantic optional extra dependencies + # # Settings management + # "pydantic-settings >=2.0.0", + # # Extra Pydantic data types + # "pydantic-extra-types >=2.0.0", +] + all = [ + "fastapi-cli[standard] >=0.0.5", + # # For the test client "httpx >=0.23.0", - "jinja2 >=2.11.2", - "python-multipart >=0.0.5", + # For templates + "jinja2 >=3.1.5", + # For forms and file uploads + "python-multipart >=0.0.18", + # For Starlette's SessionMiddleware, not commonly used with FastAPI "itsdangerous >=1.1.0", + # For Starlette's schema generation, would not be used with FastAPI "pyyaml >=5.3.1", + # For UJSONResponse "ujson >=4.0.1,!=4.0.2,!=4.1.0,!=4.2.0,!=4.3.0,!=5.0.0,!=5.1.0", + # For ORJSONResponse "orjson >=3.2.1", - "email_validator >=2.0.0", + # To validate email fields + "email-validator >=2.0.0", + # Uvicorn with uvloop "uvicorn[standard] >=0.12.0", + # Settings management "pydantic-settings >=2.0.0", + # Extra Pydantic data types "pydantic-extra-types >=2.0.0", ] -[tool.hatch.version] -path = "fastapi/__init__.py" +[project.scripts] +fastapi = "fastapi.cli:main" + +[tool.pdm] +version = { source = "file", path = "fastapi/__init__.py" } +distribution = true + +[tool.pdm.build] +source-includes = [ + "tests/", + "docs_src/", + "requirements*.txt", + "scripts/", + # For a test + "docs/en/docs/img/favicon.png", + ] + +[tool.tiangolo._internal-slim-build.packages.fastapi-slim.project] +name = "fastapi-slim" [tool.mypy] strict = true @@ -99,47 +151,45 @@ xfail_strict = true junit_family = "xunit2" filterwarnings = [ "error", - # TODO: needed by asyncio in Python 3.9.7 https://bugs.python.org/issue45097, try to remove on 3.9.8 - 'ignore:The loop argument is deprecated since Python 3\.8, and scheduled for removal in Python 3\.10:DeprecationWarning:asyncio', 'ignore:starlette.middleware.wsgi is deprecated and will be removed in a future release\..*:DeprecationWarning:starlette', - # TODO: remove after upgrading HTTPX to a version newer than 0.23.0 - # Including PR: https://github.com/encode/httpx/pull/2309 - "ignore:'cgi' is deprecated:DeprecationWarning", # For passlib "ignore:'crypt' is deprecated and slated for removal in Python 3.13:DeprecationWarning", # see https://trio.readthedocs.io/en/stable/history.html#trio-0-22-0-2022-09-28 "ignore:You seem to already have a custom.*:RuntimeWarning:trio", - "ignore::trio.TrioDeprecationWarning", - # TODO remove pytest-cov - 'ignore::pytest.PytestDeprecationWarning:pytest_cov', # TODO: remove after upgrading SQLAlchemy to a version that includes the following changes # https://github.com/sqlalchemy/sqlalchemy/commit/59521abcc0676e936b31a523bd968fc157fef0c2 'ignore:datetime\.datetime\.utcfromtimestamp\(\) is deprecated and scheduled for removal in a future version\..*:DeprecationWarning:sqlalchemy', - # TODO: remove after upgrading python-jose to a version that explicitly supports Python 3.12 - # also, if it won't receive an update, consider replacing python-jose with some alternative - # related issues: - # - https://github.com/mpdavis/python-jose/issues/332 - # - https://github.com/mpdavis/python-jose/issues/334 - 'ignore:datetime\.datetime\.utcnow\(\) is deprecated and scheduled for removal in a future version\..*:DeprecationWarning:jose', - # TODO: remove after upgrading Starlette to a version including https://github.com/encode/starlette/pull/2406 - # Probably Starlette 0.36.0 - "ignore: The 'method' parameter is not used, and it will be removed.:DeprecationWarning:starlette", + # Trio 24.1.0 raises a warning from attrs + # Ref: https://github.com/python-trio/trio/pull/3054 + # Remove once there's a new version of Trio + 'ignore:The `hash` argument is deprecated*:DeprecationWarning:trio', + # Ignore flaky coverage / pytest warning about SQLite connection, only applies to Python 3.13 and Pydantic v1 + 'ignore:Exception ignored in. =0.23.0,<0.25.0 +httpx >=0.23.0,<0.28.0 +# For linting and generating docs versions +ruff ==0.6.4 diff --git a/requirements-docs.txt b/requirements-docs.txt index 28408a9f1..cd2e4e58e 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -1,19 +1,19 @@ -e . -r requirements-docs-tests.txt -mkdocs-material==9.4.7 +mkdocs-material==9.6.1 mdx-include >=1.4.1,<2.0.0 -mkdocs-markdownextradata-plugin >=0.1.7,<0.3.0 mkdocs-redirects>=1.2.1,<1.3.0 -typer-cli >=0.0.13,<0.0.14 -typer[all] >=0.6.1,<0.8.0 +typer == 0.12.5 pyyaml >=5.3.1,<7.0.0 # For Material for MkDocs, Chinese search jieba==0.42.1 # For image processing by Material for MkDocs -pillow==10.1.0 +pillow==11.1.0 # For image processing by Material for MkDocs -cairosvg==2.7.0 -mkdocstrings[python]==0.23.0 -griffe-typingdoc==0.2.2 +cairosvg==2.7.1 +mkdocstrings[python]==0.26.1 +griffe-typingdoc==0.2.7 # For griffe, it formats with black -black==23.3.0 +black==24.10.0 +mkdocs-macros-plugin==1.3.7 +markdown-include-variants==0.0.4 diff --git a/requirements-github-actions.txt b/requirements-github-actions.txt new file mode 100644 index 000000000..920aefea6 --- /dev/null +++ b/requirements-github-actions.txt @@ -0,0 +1,6 @@ +PyGithub>=2.3.0,<3.0.0 +pydantic>=2.5.3,<3.0.0 +pydantic-settings>=2.1.0,<3.0.0 +httpx>=0.27.0,<0.28.0 +pyyaml >=5.3.1,<7.0.0 +smokeshow diff --git a/requirements-tests.txt b/requirements-tests.txt index e1a976c13..4a15844e4 100644 --- a/requirements-tests.txt +++ b/requirements-tests.txt @@ -1,25 +1,16 @@ --e . +-e .[all] -r requirements-docs-tests.txt -pydantic-settings >=2.0.0 -pytest >=7.1.3,<8.0.0 +pytest >=7.1.3,<9.0.0 coverage[toml] >= 6.5.0,< 8.0 -mypy ==1.4.1 -ruff ==0.1.2 -email_validator >=1.1.1,<3.0.0 -dirty-equals ==0.6.0 -# TODO: once removing databases from tutorial, upgrade SQLAlchemy -# probably when including SQLModel -sqlalchemy >=1.3.18,<1.4.43 -databases[sqlite] >=0.3.2,<0.7.0 -orjson >=3.2.1,<4.0.0 -ujson >=4.0.1,!=4.0.2,!=4.1.0,!=4.2.0,!=4.3.0,!=5.0.0,!=5.1.0,<6.0.0 -python-multipart >=0.0.5,<0.0.7 -flask >=1.1.2,<3.0.0 -anyio[trio] >=3.2.1,<4.0.0 -python-jose[cryptography] >=3.3.0,<4.0.0 +mypy ==1.8.0 +dirty-equals ==0.8.0 +sqlmodel==0.0.22 +flask >=1.1.2,<4.0.0 +anyio[trio] >=3.2.1,<5.0.0 +PyJWT==2.8.0 pyyaml >=5.3.1,<7.0.0 passlib[bcrypt] >=1.7.2,<2.0.0 - +inline-snapshot==0.19.3 # types -types-ujson ==5.7.0.1 +types-ujson ==5.10.0.20240515 types-orjson ==3.6.2 diff --git a/requirements-translations.txt b/requirements-translations.txt new file mode 100644 index 000000000..a8f8a02d7 --- /dev/null +++ b/requirements-translations.txt @@ -0,0 +1 @@ +pydantic-ai==0.0.15 diff --git a/requirements.txt b/requirements.txt index ef25ec483..9180bf1be 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,7 +1,6 @@ -e .[all] -r requirements-tests.txt -r requirements-docs.txt -uvicorn[standard] >=0.12.0,<0.23.0 -pre-commit >=2.17.0,<4.0.0 +pre-commit >=2.17.0,<5.0.0 # For generating screenshots playwright diff --git a/scripts/build-docs.sh b/scripts/build-docs.sh deleted file mode 100755 index ebf864afa..000000000 --- a/scripts/build-docs.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env bash - -set -e -set -x - -# Check README.md is up to date -python ./scripts/docs.py verify-readme -python ./scripts/docs.py build-all diff --git a/scripts/clean.sh b/scripts/clean.sh deleted file mode 100755 index d5a4b790a..000000000 --- a/scripts/clean.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/bin/sh -e - -if [ -d 'dist' ] ; then - rm -r dist -fi -if [ -d 'site' ] ; then - rm -r site -fi diff --git a/scripts/contributors.py b/scripts/contributors.py new file mode 100644 index 000000000..251558de7 --- /dev/null +++ b/scripts/contributors.py @@ -0,0 +1,315 @@ +import logging +import secrets +import subprocess +from collections import Counter +from datetime import datetime +from pathlib import Path +from typing import Any + +import httpx +import yaml +from github import Github +from pydantic import BaseModel, SecretStr +from pydantic_settings import BaseSettings + +github_graphql_url = "https://api.github.com/graphql" + + +prs_query = """ +query Q($after: String) { + repository(name: "fastapi", owner: "fastapi") { + pullRequests(first: 100, after: $after) { + edges { + cursor + node { + number + labels(first: 100) { + nodes { + name + } + } + author { + login + avatarUrl + url + } + title + createdAt + lastEditedAt + updatedAt + state + reviews(first:100) { + nodes { + author { + login + avatarUrl + url + } + state + } + } + } + } + } + } +} +""" + + +class Author(BaseModel): + login: str + avatarUrl: str + url: str + + +class LabelNode(BaseModel): + name: str + + +class Labels(BaseModel): + nodes: list[LabelNode] + + +class ReviewNode(BaseModel): + author: Author | None = None + state: str + + +class Reviews(BaseModel): + nodes: list[ReviewNode] + + +class PullRequestNode(BaseModel): + number: int + labels: Labels + author: Author | None = None + title: str + createdAt: datetime + lastEditedAt: datetime | None = None + updatedAt: datetime | None = None + state: str + reviews: Reviews + + +class PullRequestEdge(BaseModel): + cursor: str + node: PullRequestNode + + +class PullRequests(BaseModel): + edges: list[PullRequestEdge] + + +class PRsRepository(BaseModel): + pullRequests: PullRequests + + +class PRsResponseData(BaseModel): + repository: PRsRepository + + +class PRsResponse(BaseModel): + data: PRsResponseData + + +class Settings(BaseSettings): + github_token: SecretStr + github_repository: str + httpx_timeout: int = 30 + + +def get_graphql_response( + *, + settings: Settings, + query: str, + after: str | None = None, +) -> dict[str, Any]: + headers = {"Authorization": f"token {settings.github_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 response.status_code != 200: + logging.error(f"Response was not 200, after: {after}") + logging.error(response.text) + raise RuntimeError(response.text) + data = response.json() + if "errors" in data: + logging.error(f"Errors in response, after: {after}") + logging.error(data["errors"]) + logging.error(response.text) + raise RuntimeError(response.text) + return data + + +def get_graphql_pr_edges( + *, settings: Settings, after: str | None = None +) -> list[PullRequestEdge]: + data = get_graphql_response(settings=settings, query=prs_query, after=after) + graphql_response = PRsResponse.model_validate(data) + return graphql_response.data.repository.pullRequests.edges + + +def get_pr_nodes(settings: Settings) -> list[PullRequestNode]: + pr_nodes: list[PullRequestNode] = [] + pr_edges = get_graphql_pr_edges(settings=settings) + + while pr_edges: + for edge in pr_edges: + pr_nodes.append(edge.node) + last_edge = pr_edges[-1] + pr_edges = get_graphql_pr_edges(settings=settings, after=last_edge.cursor) + return pr_nodes + + +class ContributorsResults(BaseModel): + contributors: Counter[str] + translation_reviewers: Counter[str] + translators: Counter[str] + authors: dict[str, Author] + + +def get_contributors(pr_nodes: list[PullRequestNode]) -> ContributorsResults: + contributors = Counter[str]() + translation_reviewers = Counter[str]() + translators = Counter[str]() + authors: dict[str, Author] = {} + + for pr in pr_nodes: + if pr.author: + authors[pr.author.login] = pr.author + is_lang = False + for label in pr.labels.nodes: + if label.name == "lang-all": + is_lang = True + break + for review in pr.reviews.nodes: + if review.author: + authors[review.author.login] = review.author + if is_lang: + translation_reviewers[review.author.login] += 1 + if pr.state == "MERGED" and pr.author: + if is_lang: + translators[pr.author.login] += 1 + else: + contributors[pr.author.login] += 1 + return ContributorsResults( + contributors=contributors, + translation_reviewers=translation_reviewers, + translators=translators, + authors=authors, + ) + + +def get_users_to_write( + *, + counter: Counter[str], + authors: dict[str, Author], + min_count: int = 2, +) -> dict[str, Any]: + users: dict[str, Any] = {} + for user, count in counter.most_common(): + if count >= min_count: + author = authors[user] + users[user] = { + "login": user, + "count": count, + "avatarUrl": author.avatarUrl, + "url": author.url, + } + return users + + +def update_content(*, content_path: Path, new_content: Any) -> bool: + old_content = content_path.read_text(encoding="utf-8") + + new_content = yaml.dump(new_content, sort_keys=False, width=200, allow_unicode=True) + if old_content == new_content: + logging.info(f"The content hasn't changed for {content_path}") + return False + content_path.write_text(new_content, encoding="utf-8") + logging.info(f"Updated {content_path}") + return True + + +def main() -> None: + logging.basicConfig(level=logging.INFO) + settings = Settings() + logging.info(f"Using config: {settings.model_dump_json()}") + g = Github(settings.github_token.get_secret_value()) + repo = g.get_repo(settings.github_repository) + + pr_nodes = get_pr_nodes(settings=settings) + contributors_results = get_contributors(pr_nodes=pr_nodes) + authors = contributors_results.authors + + top_contributors = get_users_to_write( + counter=contributors_results.contributors, + authors=authors, + ) + + top_translators = get_users_to_write( + counter=contributors_results.translators, + authors=authors, + ) + top_translations_reviewers = get_users_to_write( + counter=contributors_results.translation_reviewers, + authors=authors, + ) + + # For local development + # contributors_path = Path("../docs/en/data/contributors.yml") + contributors_path = Path("./docs/en/data/contributors.yml") + # translators_path = Path("../docs/en/data/translators.yml") + translators_path = Path("./docs/en/data/translators.yml") + # translation_reviewers_path = Path("../docs/en/data/translation_reviewers.yml") + translation_reviewers_path = Path("./docs/en/data/translation_reviewers.yml") + + updated = [ + update_content(content_path=contributors_path, new_content=top_contributors), + update_content(content_path=translators_path, new_content=top_translators), + update_content( + content_path=translation_reviewers_path, + new_content=top_translations_reviewers, + ), + ] + + if not any(updated): + logging.info("The data hasn't changed, finishing.") + return + + logging.info("Setting up GitHub Actions git user") + subprocess.run(["git", "config", "user.name", "github-actions"], check=True) + subprocess.run( + ["git", "config", "user.email", "github-actions@github.com"], check=True + ) + branch_name = f"fastapi-people-contributors-{secrets.token_hex(4)}" + logging.info(f"Creating a new branch {branch_name}") + subprocess.run(["git", "checkout", "-b", branch_name], check=True) + logging.info("Adding updated file") + subprocess.run( + [ + "git", + "add", + str(contributors_path), + str(translators_path), + str(translation_reviewers_path), + ], + check=True, + ) + logging.info("Committing updated file") + message = "👥 Update FastAPI People - Contributors and Translators" + subprocess.run(["git", "commit", "-m", message], check=True) + logging.info("Pushing branch") + subprocess.run(["git", "push", "origin", branch_name], check=True) + logging.info("Creating PR") + pr = repo.create_pull(title=message, body=message, base="master", head=branch_name) + logging.info(f"Created PR: {pr.number}") + logging.info("Finished") + + +if __name__ == "__main__": + main() diff --git a/scripts/deploy_docs_status.py b/scripts/deploy_docs_status.py new file mode 100644 index 000000000..c652cdb6e --- /dev/null +++ b/scripts/deploy_docs_status.py @@ -0,0 +1,125 @@ +import logging +import re + +from github import Github +from pydantic import BaseModel, SecretStr +from pydantic_settings import BaseSettings + + +class Settings(BaseSettings): + github_repository: str + github_token: SecretStr + deploy_url: str | None = None + commit_sha: str + run_id: int + is_done: bool = False + + +class LinkData(BaseModel): + previous_link: str + preview_link: str + en_link: str | None = None + + +def main() -> None: + logging.basicConfig(level=logging.INFO) + settings = Settings() + + logging.info(f"Using config: {settings.model_dump_json()}") + g = Github(settings.github_token.get_secret_value()) + repo = g.get_repo(settings.github_repository) + use_pr = next( + (pr for pr in repo.get_pulls() if pr.head.sha == settings.commit_sha), None + ) + if not use_pr: + logging.error(f"No PR found for hash: {settings.commit_sha}") + return + commits = list(use_pr.get_commits()) + current_commit = [c for c in commits if c.sha == settings.commit_sha][0] + run_url = f"https://github.com/{settings.github_repository}/actions/runs/{settings.run_id}" + if settings.is_done and not settings.deploy_url: + current_commit.create_status( + state="success", + description="No Docs Changes", + context="deploy-docs", + target_url=run_url, + ) + logging.info("No docs changes found") + return + if not settings.deploy_url: + current_commit.create_status( + state="pending", + description="Deploying Docs", + context="deploy-docs", + target_url=run_url, + ) + logging.info("No deploy URL available yet") + return + current_commit.create_status( + state="success", + description="Docs Deployed", + context="deploy-docs", + target_url=run_url, + ) + + files = list(use_pr.get_files()) + docs_files = [f for f in files if f.filename.startswith("docs/")] + + deploy_url = settings.deploy_url.rstrip("/") + lang_links: dict[str, list[LinkData]] = {} + for f in docs_files: + match = re.match(r"docs/([^/]+)/docs/(.*)", f.filename) + if not match: + continue + lang = match.group(1) + path = match.group(2) + if path.endswith("index.md"): + path = path.replace("index.md", "") + else: + path = path.replace(".md", "/") + en_path = path + if lang == "en": + use_path = en_path + else: + use_path = f"{lang}/{path}" + link = LinkData( + previous_link=f"https://fastapi.tiangolo.com/{use_path}", + preview_link=f"{deploy_url}/{use_path}", + ) + if lang != "en": + link.en_link = f"https://fastapi.tiangolo.com/{en_path}" + lang_links.setdefault(lang, []).append(link) + + links: list[LinkData] = [] + en_links = lang_links.get("en", []) + en_links.sort(key=lambda x: x.preview_link) + links.extend(en_links) + + langs = list(lang_links.keys()) + langs.sort() + for lang in langs: + if lang == "en": + continue + current_lang_links = lang_links[lang] + current_lang_links.sort(key=lambda x: x.preview_link) + links.extend(current_lang_links) + + message = f"📝 Docs preview for commit {settings.commit_sha} at: {deploy_url}" + + if links: + message += "\n\n### Modified Pages\n\n" + for link in links: + message += f"* {link.preview_link}" + message += f" - ([before]({link.previous_link}))" + if link.en_link: + message += f" - ([English]({link.en_link}))" + message += "\n" + + print(message) + use_pr.as_issue().create_comment(message) + + logging.info("Finished") + + +if __name__ == "__main__": + main() diff --git a/scripts/docs-live.sh b/scripts/docs-live.sh deleted file mode 100755 index 30637a528..000000000 --- a/scripts/docs-live.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/usr/bin/env bash - -set -e - -mkdocs serve --dev-addr 0.0.0.0:8008 diff --git a/scripts/docs.py b/scripts/docs.py index 37a7a3477..8462e2bc1 100644 --- a/scripts/docs.py +++ b/scripts/docs.py @@ -11,13 +11,11 @@ from multiprocessing import Pool from pathlib import Path from typing import Any, Dict, List, Optional, Union -import mkdocs.commands.build -import mkdocs.commands.serve -import mkdocs.config import mkdocs.utils import typer import yaml from jinja2 import Template +from ruff.__main__ import find_ruff_bin logging.basicConfig(level=logging.INFO) @@ -26,9 +24,20 @@ app = typer.Typer() mkdocs_name = "mkdocs.yml" missing_translation_snippet = """ -{!../../../docs/missing-translation.md!} +{!../../docs/missing-translation.md!} """ +non_translated_sections = [ + "reference/", + "release-notes.md", + "fastapi-people.md", + "external-links.md", + "newsletter.md", + "management-tasks.md", + "management.md", + "contributing.md", +] + docs_path = Path("docs") en_docs_path = Path("docs/en") en_config_path: Path = en_docs_path / mkdocs_name @@ -76,8 +85,6 @@ def callback() -> None: def new_lang(lang: str = typer.Argument(..., callback=lang_callback)): """ Generate a new docs translation directory for the language LANG. - - LANG should be a 2-letter language code, like: en, es, de, pt, etc. """ new_path: Path = Path("docs") / lang if new_path.exists(): @@ -167,6 +174,13 @@ def generate_readme_content() -> str: pre_content = content[frontmatter_end:pre_end] post_content = content[post_start:] new_content = pre_content + message + post_content + # Remove content between and + new_content = re.sub( + r".*?", + "", + new_content, + flags=re.DOTALL, + ) return new_content @@ -249,6 +263,7 @@ def live( lang: str = typer.Argument( None, callback=lang_callback, autocompletion=complete_existing_lang ), + dirty: bool = False, ) -> None: """ Serve with livereload a docs site for a specific language. @@ -260,15 +275,19 @@ def live( en. """ # Enable line numbers during local development to make it easier to highlight - os.environ["LINENUMS"] = "true" if lang is None: lang = "en" lang_path: Path = docs_path / lang - os.chdir(lang_path) - mkdocs.commands.serve.serve(dev_addr="127.0.0.1:8008") + # Enable line numbers during local development to make it easier to highlight + args = ["mkdocs", "serve", "--dev-addr", "127.0.0.1:8008"] + if dirty: + args.append("--dirty") + subprocess.run( + args, env={**os.environ, "LINENUMS": "true"}, cwd=lang_path, check=True + ) -def update_config() -> None: +def get_updated_config_content() -> Dict[str, Any]: config = get_en_config() languages = [{"en": "/"}] new_alternate: List[Dict[str, str]] = [] @@ -296,12 +315,66 @@ def update_config() -> None: new_alternate.append({"link": url, "name": use_name}) new_alternate.append({"link": "/em/", "name": "😉"}) config["extra"]["alternate"] = new_alternate + return config + + +def update_config() -> None: + config = get_updated_config_content() en_config_path.write_text( yaml.dump(config, sort_keys=False, width=200, allow_unicode=True), encoding="utf-8", ) +@app.command() +def verify_config() -> None: + """ + Verify main mkdocs.yml content to make sure it uses the latest language names. + """ + typer.echo("Verifying mkdocs.yml") + config = get_en_config() + updated_config = get_updated_config_content() + if config != updated_config: + typer.secho( + "docs/en/mkdocs.yml outdated from docs/language_names.yml, " + "update language_names.yml and run " + "python ./scripts/docs.py update-languages", + color=typer.colors.RED, + ) + raise typer.Abort() + typer.echo("Valid mkdocs.yml ✅") + + +@app.command() +def verify_non_translated() -> None: + """ + Verify there are no files in the non translatable pages. + """ + print("Verifying non translated pages") + lang_paths = get_lang_paths() + error_paths = [] + for lang in lang_paths: + if lang.name == "en": + continue + for non_translatable in non_translated_sections: + non_translatable_path = lang / "docs" / non_translatable + if non_translatable_path.exists(): + error_paths.append(non_translatable_path) + if error_paths: + print("Non-translated pages found, remove them:") + for error_path in error_paths: + print(error_path) + raise typer.Abort() + print("No non-translated pages found ✅") + + +@app.command() +def verify_docs(): + verify_readme() + verify_config() + verify_non_translated() + + @app.command() def langs_json(): langs = [] @@ -311,5 +384,41 @@ def langs_json(): print(json.dumps(langs)) +@app.command() +def generate_docs_src_versions_for_file(file_path: Path) -> None: + target_versions = ["py39", "py310"] + base_content = file_path.read_text(encoding="utf-8") + previous_content = {base_content} + for target_version in target_versions: + version_result = subprocess.run( + [ + find_ruff_bin(), + "check", + "--target-version", + target_version, + "--fix", + "--unsafe-fixes", + "-", + ], + input=base_content.encode("utf-8"), + capture_output=True, + ) + content_target = version_result.stdout.decode("utf-8") + format_result = subprocess.run( + [find_ruff_bin(), "format", "-"], + input=content_target.encode("utf-8"), + capture_output=True, + ) + content_format = format_result.stdout.decode("utf-8") + if content_format in previous_content: + continue + previous_content.add(content_format) + version_file = file_path.with_name( + file_path.name.replace(".py", f"_{target_version}.py") + ) + logging.info(f"Writing to {version_file}") + version_file.write_text(content_format, encoding="utf-8") + + if __name__ == "__main__": app() diff --git a/scripts/format.sh b/scripts/format.sh index 11f25f1ce..bf70f42e5 100755 --- a/scripts/format.sh +++ b/scripts/format.sh @@ -1,5 +1,5 @@ -#!/bin/sh -e +#!/usr/bin/env bash set -x -ruff fastapi tests docs_src scripts --fix +ruff check fastapi tests docs_src scripts --fix ruff format fastapi tests docs_src scripts diff --git a/scripts/label_approved.py b/scripts/label_approved.py new file mode 100644 index 000000000..271444504 --- /dev/null +++ b/scripts/label_approved.py @@ -0,0 +1,60 @@ +import logging +from typing import Literal + +from github import Github +from github.PullRequestReview import PullRequestReview +from pydantic import BaseModel, SecretStr +from pydantic_settings import BaseSettings + + +class LabelSettings(BaseModel): + await_label: str | None = None + number: int + + +default_config = {"approved-2": LabelSettings(await_label="awaiting-review", number=2)} + + +class Settings(BaseSettings): + github_repository: str + token: SecretStr + debug: bool | None = False + config: dict[str, LabelSettings] | Literal[""] = default_config + + +settings = Settings() +if settings.debug: + logging.basicConfig(level=logging.DEBUG) +else: + logging.basicConfig(level=logging.INFO) +logging.debug(f"Using config: {settings.json()}") +g = Github(settings.token.get_secret_value()) +repo = g.get_repo(settings.github_repository) +for pr in repo.get_pulls(state="open"): + logging.info(f"Checking PR: #{pr.number}") + pr_labels = list(pr.get_labels()) + pr_label_by_name = {label.name: label for label in pr_labels} + reviews = list(pr.get_reviews()) + review_by_user: dict[str, PullRequestReview] = {} + for review in reviews: + if review.user.login in review_by_user: + stored_review = review_by_user[review.user.login] + if review.submitted_at >= stored_review.submitted_at: + review_by_user[review.user.login] = review + else: + review_by_user[review.user.login] = review + approved_reviews = [ + review for review in review_by_user.values() if review.state == "APPROVED" + ] + config = settings.config or default_config + for approved_label, conf in config.items(): + logging.debug(f"Processing config: {conf.json()}") + if conf.await_label is None or (conf.await_label in pr_label_by_name): + logging.debug(f"Processable PR: {pr.number}") + if len(approved_reviews) >= conf.number: + logging.info(f"Adding label to PR: {pr.number}") + pr.add_to_labels(approved_label) + if conf.await_label: + logging.info(f"Removing label from PR: {pr.number}") + pr.remove_from_labels(conf.await_label) +logging.info("Finished") diff --git a/scripts/lint.sh b/scripts/lint.sh index c0e24db9f..18cf52a84 100755 --- a/scripts/lint.sh +++ b/scripts/lint.sh @@ -4,5 +4,5 @@ set -e set -x mypy fastapi -ruff fastapi tests docs_src scripts +ruff check fastapi tests docs_src scripts ruff format fastapi tests --check diff --git a/scripts/mkdocs_hooks.py b/scripts/mkdocs_hooks.py index 8335a13f6..0bc4929a4 100644 --- a/scripts/mkdocs_hooks.py +++ b/scripts/mkdocs_hooks.py @@ -8,9 +8,14 @@ from mkdocs.structure.files import File, Files from mkdocs.structure.nav import Link, Navigation, Section from mkdocs.structure.pages import Page -non_traslated_sections = [ +non_translated_sections = [ "reference/", "release-notes.md", + "fastapi-people.md", + "external-links.md", + "newsletter.md", + "management-tasks.md", + "management.md", ] @@ -39,7 +44,7 @@ def on_config(config: MkDocsConfig, **kwargs: Any) -> MkDocsConfig: lang = dir_path.parent.name if lang in available_langs: config.theme["language"] = lang - if not (config.site_url or "").endswith(f"{lang}/") and not lang == "en": + if not (config.site_url or "").endswith(f"{lang}/") and lang != "en": config.site_url = f"{config.site_url}{lang}/" return config @@ -128,7 +133,7 @@ def on_page_markdown( markdown: str, *, page: Page, config: MkDocsConfig, files: Files ) -> str: if isinstance(page.file, EnFile): - for excluded_section in non_traslated_sections: + for excluded_section in non_translated_sections: if page.file.src_path.startswith(excluded_section): return markdown missing_translation_content = get_missing_translation_content(config.docs_dir) diff --git a/scripts/netlify-docs.sh b/scripts/netlify-docs.sh deleted file mode 100755 index 8f9065e23..000000000 --- a/scripts/netlify-docs.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/env bash -set -x -set -e -# Install pip -cd /tmp -curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py -python3.6 get-pip.py --user -cd - -# Install Flit to be able to install all -python3.6 -m pip install --user flit -# Install with Flit -python3.6 -m flit install --user --extras doc -# Finally, run mkdocs -python3.6 -m mkdocs build diff --git a/scripts/notify_translations.py b/scripts/notify_translations.py new file mode 100644 index 000000000..c300624db --- /dev/null +++ b/scripts/notify_translations.py @@ -0,0 +1,432 @@ +import logging +import random +import sys +import time +from pathlib import Path +from typing import Any, Dict, List, Union, cast + +import httpx +from github import Github +from pydantic import BaseModel, SecretStr +from pydantic_settings import BaseSettings + +awaiting_label = "awaiting-review" +lang_all_label = "lang-all" +approved_label = "approved-1" + + +github_graphql_url = "https://api.github.com/graphql" +questions_translations_category_id = "DIC_kwDOCZduT84CT5P9" + +all_discussions_query = """ +query Q($category_id: ID) { + repository(name: "fastapi", owner: "fastapi") { + discussions(categoryId: $category_id, first: 100) { + nodes { + title + id + number + labels(first: 10) { + edges { + node { + id + name + } + } + } + } + } + } +} +""" + +translation_discussion_query = """ +query Q($after: String, $discussion_number: Int!) { + repository(name: "fastapi", owner: "fastapi") { + discussion(number: $discussion_number) { + comments(first: 100, after: $after) { + edges { + cursor + node { + id + url + body + } + } + } + } + } +} +""" + +add_comment_mutation = """ +mutation Q($discussion_id: ID!, $body: String!) { + addDiscussionComment(input: {discussionId: $discussion_id, body: $body}) { + comment { + id + url + body + } + } +} +""" + +update_comment_mutation = """ +mutation Q($comment_id: ID!, $body: String!) { + updateDiscussionComment(input: {commentId: $comment_id, body: $body}) { + comment { + id + url + body + } + } +} +""" + + +class Comment(BaseModel): + id: str + url: str + body: str + + +class UpdateDiscussionComment(BaseModel): + comment: Comment + + +class UpdateCommentData(BaseModel): + updateDiscussionComment: UpdateDiscussionComment + + +class UpdateCommentResponse(BaseModel): + data: UpdateCommentData + + +class AddDiscussionComment(BaseModel): + comment: Comment + + +class AddCommentData(BaseModel): + addDiscussionComment: AddDiscussionComment + + +class AddCommentResponse(BaseModel): + data: AddCommentData + + +class CommentsEdge(BaseModel): + node: Comment + cursor: str + + +class Comments(BaseModel): + edges: List[CommentsEdge] + + +class CommentsDiscussion(BaseModel): + comments: Comments + + +class CommentsRepository(BaseModel): + discussion: CommentsDiscussion + + +class CommentsData(BaseModel): + repository: CommentsRepository + + +class CommentsResponse(BaseModel): + data: CommentsData + + +class AllDiscussionsLabelNode(BaseModel): + id: str + name: str + + +class AllDiscussionsLabelsEdge(BaseModel): + node: AllDiscussionsLabelNode + + +class AllDiscussionsDiscussionLabels(BaseModel): + edges: List[AllDiscussionsLabelsEdge] + + +class AllDiscussionsDiscussionNode(BaseModel): + title: str + id: str + number: int + labels: AllDiscussionsDiscussionLabels + + +class AllDiscussionsDiscussions(BaseModel): + nodes: List[AllDiscussionsDiscussionNode] + + +class AllDiscussionsRepository(BaseModel): + discussions: AllDiscussionsDiscussions + + +class AllDiscussionsData(BaseModel): + repository: AllDiscussionsRepository + + +class AllDiscussionsResponse(BaseModel): + data: AllDiscussionsData + + +class Settings(BaseSettings): + model_config = {"env_ignore_empty": True} + + github_repository: str + github_token: SecretStr + github_event_path: Path + github_event_name: Union[str, None] = None + httpx_timeout: int = 30 + debug: Union[bool, None] = False + number: int | None = None + + +class PartialGitHubEventIssue(BaseModel): + number: int | None = None + + +class PartialGitHubEvent(BaseModel): + pull_request: PartialGitHubEventIssue | None = None + + +def get_graphql_response( + *, + settings: Settings, + query: str, + after: Union[str, None] = None, + category_id: Union[str, None] = None, + discussion_number: Union[int, None] = None, + discussion_id: Union[str, None] = None, + comment_id: Union[str, None] = None, + body: Union[str, None] = None, +) -> Dict[str, Any]: + headers = {"Authorization": f"token {settings.github_token.get_secret_value()}"} + variables = { + "after": after, + "category_id": category_id, + "discussion_number": discussion_number, + "discussion_id": discussion_id, + "comment_id": comment_id, + "body": body, + } + response = httpx.post( + github_graphql_url, + headers=headers, + timeout=settings.httpx_timeout, + json={"query": query, "variables": variables, "operationName": "Q"}, + ) + if response.status_code != 200: + logging.error( + f"Response was not 200, after: {after}, category_id: {category_id}" + ) + logging.error(response.text) + raise RuntimeError(response.text) + data = response.json() + if "errors" in data: + logging.error(f"Errors in response, after: {after}, category_id: {category_id}") + logging.error(data["errors"]) + logging.error(response.text) + raise RuntimeError(response.text) + return cast(Dict[str, Any], data) + + +def get_graphql_translation_discussions( + *, settings: Settings +) -> List[AllDiscussionsDiscussionNode]: + data = get_graphql_response( + settings=settings, + query=all_discussions_query, + category_id=questions_translations_category_id, + ) + graphql_response = AllDiscussionsResponse.model_validate(data) + return graphql_response.data.repository.discussions.nodes + + +def get_graphql_translation_discussion_comments_edges( + *, settings: Settings, discussion_number: int, after: Union[str, None] = None +) -> List[CommentsEdge]: + data = get_graphql_response( + settings=settings, + query=translation_discussion_query, + discussion_number=discussion_number, + after=after, + ) + graphql_response = CommentsResponse.model_validate(data) + return graphql_response.data.repository.discussion.comments.edges + + +def get_graphql_translation_discussion_comments( + *, settings: Settings, discussion_number: int +) -> list[Comment]: + comment_nodes: List[Comment] = [] + discussion_edges = get_graphql_translation_discussion_comments_edges( + settings=settings, discussion_number=discussion_number + ) + + while discussion_edges: + for discussion_edge in discussion_edges: + comment_nodes.append(discussion_edge.node) + last_edge = discussion_edges[-1] + discussion_edges = get_graphql_translation_discussion_comments_edges( + settings=settings, + discussion_number=discussion_number, + after=last_edge.cursor, + ) + return comment_nodes + + +def create_comment(*, settings: Settings, discussion_id: str, body: str) -> Comment: + data = get_graphql_response( + settings=settings, + query=add_comment_mutation, + discussion_id=discussion_id, + body=body, + ) + response = AddCommentResponse.model_validate(data) + return response.data.addDiscussionComment.comment + + +def update_comment(*, settings: Settings, comment_id: str, body: str) -> Comment: + data = get_graphql_response( + settings=settings, + query=update_comment_mutation, + comment_id=comment_id, + body=body, + ) + response = UpdateCommentResponse.model_validate(data) + return response.data.updateDiscussionComment.comment + + +def main() -> None: + settings = Settings() + if settings.debug: + logging.basicConfig(level=logging.DEBUG) + else: + logging.basicConfig(level=logging.INFO) + logging.debug(f"Using config: {settings.model_dump_json()}") + g = Github(settings.github_token.get_secret_value()) + repo = g.get_repo(settings.github_repository) + if not settings.github_event_path.is_file(): + raise RuntimeError( + f"No github event file available at: {settings.github_event_path}" + ) + contents = settings.github_event_path.read_text() + github_event = PartialGitHubEvent.model_validate_json(contents) + logging.info(f"Using GitHub event: {github_event}") + number = ( + github_event.pull_request and github_event.pull_request.number + ) or settings.number + if number is None: + raise RuntimeError("No PR number available") + + # Avoid race conditions with multiple labels + sleep_time = random.random() * 10 # random number between 0 and 10 seconds + logging.info( + f"Sleeping for {sleep_time} seconds to avoid " + "race conditions and multiple comments" + ) + time.sleep(sleep_time) + + # Get PR + logging.debug(f"Processing PR: #{number}") + pr = repo.get_pull(number) + label_strs = {label.name for label in pr.get_labels()} + langs = [] + for label in label_strs: + if label.startswith("lang-") and not label == lang_all_label: + langs.append(label[5:]) + logging.info(f"PR #{pr.number} has labels: {label_strs}") + if not langs or lang_all_label not in label_strs: + logging.info(f"PR #{pr.number} doesn't seem to be a translation PR, skipping") + sys.exit(0) + + # Generate translation map, lang ID to discussion + discussions = get_graphql_translation_discussions(settings=settings) + lang_to_discussion_map: Dict[str, AllDiscussionsDiscussionNode] = {} + for discussion in discussions: + for edge in discussion.labels.edges: + label = edge.node.name + if label.startswith("lang-") and not label == lang_all_label: + lang = label[5:] + lang_to_discussion_map[lang] = discussion + logging.debug(f"Using translations map: {lang_to_discussion_map}") + + # Messages to create or check + new_translation_message = f"Good news everyone! 😉 There's a new translation PR to be reviewed: #{pr.number} by @{pr.user.login}. 🎉 This requires 2 approvals from native speakers to be merged. 🤓" + done_translation_message = f"~There's a new translation PR to be reviewed: #{pr.number} by @{pr.user.login}~ Good job! This is done. 🍰☕" + + # Normally only one language, but still + for lang in langs: + if lang not in lang_to_discussion_map: + log_message = f"Could not find discussion for language: {lang}" + logging.error(log_message) + raise RuntimeError(log_message) + discussion = lang_to_discussion_map[lang] + logging.info( + f"Found a translation discussion for language: {lang} in discussion: #{discussion.number}" + ) + + already_notified_comment: Union[Comment, None] = None + already_done_comment: Union[Comment, None] = None + + logging.info( + f"Checking current comments in discussion: #{discussion.number} to see if already notified about this PR: #{pr.number}" + ) + comments = get_graphql_translation_discussion_comments( + settings=settings, discussion_number=discussion.number + ) + for comment in comments: + if new_translation_message in comment.body: + already_notified_comment = comment + elif done_translation_message in comment.body: + already_done_comment = comment + logging.info( + f"Already notified comment: {already_notified_comment}, already done comment: {already_done_comment}" + ) + + if pr.state == "open" and awaiting_label in label_strs: + logging.info( + f"This PR seems to be a language translation and awaiting reviews: #{pr.number}" + ) + if already_notified_comment: + logging.info( + f"This PR #{pr.number} was already notified in comment: {already_notified_comment.url}" + ) + else: + logging.info( + f"Writing notification comment about PR #{pr.number} in Discussion: #{discussion.number}" + ) + comment = create_comment( + settings=settings, + discussion_id=discussion.id, + body=new_translation_message, + ) + logging.info(f"Notified in comment: {comment.url}") + elif pr.state == "closed" or approved_label in label_strs: + logging.info(f"Already approved or closed PR #{pr.number}") + if already_done_comment: + logging.info( + f"This PR #{pr.number} was already marked as done in comment: {already_done_comment.url}" + ) + elif already_notified_comment: + updated_comment = update_comment( + settings=settings, + comment_id=already_notified_comment.id, + body=done_translation_message, + ) + logging.info(f"Marked as done in comment: {updated_comment.url}") + else: + logging.info( + f"There doesn't seem to be anything to be done about PR #{pr.number}" + ) + logging.info("Finished") + + +if __name__ == "__main__": + main() diff --git a/scripts/people.py b/scripts/people.py new file mode 100644 index 000000000..f61fd31c9 --- /dev/null +++ b/scripts/people.py @@ -0,0 +1,401 @@ +import logging +import secrets +import subprocess +import time +from collections import Counter +from datetime import datetime, timedelta, timezone +from pathlib import Path +from typing import Any, Container, Union + +import httpx +import yaml +from github import Github +from pydantic import BaseModel, SecretStr +from pydantic_settings import BaseSettings + +github_graphql_url = "https://api.github.com/graphql" +questions_category_id = "MDE4OkRpc2N1c3Npb25DYXRlZ29yeTMyMDAxNDM0" + +discussions_query = """ +query Q($after: String, $category_id: ID) { + repository(name: "fastapi", owner: "fastapi") { + discussions(first: 100, after: $after, categoryId: $category_id) { + edges { + cursor + node { + number + author { + login + avatarUrl + url + } + createdAt + comments(first: 50) { + totalCount + nodes { + createdAt + author { + login + avatarUrl + url + } + isAnswer + replies(first: 10) { + totalCount + nodes { + createdAt + author { + login + avatarUrl + url + } + } + } + } + } + } + } + } + } +} +""" + + +class Author(BaseModel): + login: str + avatarUrl: str | None = None + url: str | None = None + + +class CommentsNode(BaseModel): + createdAt: datetime + author: Union[Author, None] = None + + +class Replies(BaseModel): + totalCount: int + nodes: list[CommentsNode] + + +class DiscussionsCommentsNode(CommentsNode): + replies: Replies + + +class DiscussionsComments(BaseModel): + totalCount: int + nodes: list[DiscussionsCommentsNode] + + +class DiscussionsNode(BaseModel): + number: int + author: Union[Author, None] = None + title: str | None = None + createdAt: datetime + comments: DiscussionsComments + + +class DiscussionsEdge(BaseModel): + cursor: str + node: DiscussionsNode + + +class Discussions(BaseModel): + edges: list[DiscussionsEdge] + + +class DiscussionsRepository(BaseModel): + discussions: Discussions + + +class DiscussionsResponseData(BaseModel): + repository: DiscussionsRepository + + +class DiscussionsResponse(BaseModel): + data: DiscussionsResponseData + + +class Settings(BaseSettings): + github_token: SecretStr + github_repository: str + httpx_timeout: int = 30 + + +def get_graphql_response( + *, + settings: Settings, + query: str, + after: Union[str, None] = None, + category_id: Union[str, None] = None, +) -> dict[str, Any]: + headers = {"Authorization": f"token {settings.github_token.get_secret_value()}"} + variables = {"after": after, "category_id": category_id} + response = httpx.post( + github_graphql_url, + headers=headers, + timeout=settings.httpx_timeout, + json={"query": query, "variables": variables, "operationName": "Q"}, + ) + if response.status_code != 200: + logging.error( + f"Response was not 200, after: {after}, category_id: {category_id}" + ) + logging.error(response.text) + raise RuntimeError(response.text) + data = response.json() + if "errors" in data: + logging.error(f"Errors in response, after: {after}, category_id: {category_id}") + logging.error(data["errors"]) + logging.error(response.text) + raise RuntimeError(response.text) + return data + + +def get_graphql_question_discussion_edges( + *, + settings: Settings, + after: Union[str, None] = None, +) -> list[DiscussionsEdge]: + data = get_graphql_response( + settings=settings, + query=discussions_query, + after=after, + category_id=questions_category_id, + ) + graphql_response = DiscussionsResponse.model_validate(data) + return graphql_response.data.repository.discussions.edges + + +class DiscussionExpertsResults(BaseModel): + commenters: Counter[str] + last_month_commenters: Counter[str] + three_months_commenters: Counter[str] + six_months_commenters: Counter[str] + one_year_commenters: Counter[str] + authors: dict[str, Author] + + +def get_discussion_nodes(settings: Settings) -> list[DiscussionsNode]: + discussion_nodes: list[DiscussionsNode] = [] + discussion_edges = get_graphql_question_discussion_edges(settings=settings) + + while discussion_edges: + for discussion_edge in discussion_edges: + discussion_nodes.append(discussion_edge.node) + last_edge = discussion_edges[-1] + # Handle GitHub secondary rate limits, requests per minute + time.sleep(5) + discussion_edges = get_graphql_question_discussion_edges( + settings=settings, after=last_edge.cursor + ) + return discussion_nodes + + +def get_discussions_experts( + discussion_nodes: list[DiscussionsNode], +) -> DiscussionExpertsResults: + commenters = Counter[str]() + last_month_commenters = Counter[str]() + three_months_commenters = Counter[str]() + six_months_commenters = Counter[str]() + one_year_commenters = Counter[str]() + authors: dict[str, Author] = {} + + now = datetime.now(tz=timezone.utc) + one_month_ago = now - timedelta(days=30) + three_months_ago = now - timedelta(days=90) + six_months_ago = now - timedelta(days=180) + one_year_ago = now - timedelta(days=365) + + for discussion in discussion_nodes: + discussion_author_name = None + if discussion.author: + authors[discussion.author.login] = discussion.author + discussion_author_name = discussion.author.login + discussion_commentors: dict[str, datetime] = {} + for comment in discussion.comments.nodes: + if comment.author: + authors[comment.author.login] = comment.author + if comment.author.login != discussion_author_name: + author_time = discussion_commentors.get( + comment.author.login, comment.createdAt + ) + discussion_commentors[comment.author.login] = max( + author_time, comment.createdAt + ) + for reply in comment.replies.nodes: + if reply.author: + authors[reply.author.login] = reply.author + if reply.author.login != discussion_author_name: + author_time = discussion_commentors.get( + reply.author.login, reply.createdAt + ) + discussion_commentors[reply.author.login] = max( + author_time, reply.createdAt + ) + for author_name, author_time in discussion_commentors.items(): + commenters[author_name] += 1 + if author_time > one_month_ago: + last_month_commenters[author_name] += 1 + if author_time > three_months_ago: + three_months_commenters[author_name] += 1 + if author_time > six_months_ago: + six_months_commenters[author_name] += 1 + if author_time > one_year_ago: + one_year_commenters[author_name] += 1 + discussion_experts_results = DiscussionExpertsResults( + authors=authors, + commenters=commenters, + last_month_commenters=last_month_commenters, + three_months_commenters=three_months_commenters, + six_months_commenters=six_months_commenters, + one_year_commenters=one_year_commenters, + ) + return discussion_experts_results + + +def get_top_users( + *, + counter: Counter[str], + authors: dict[str, Author], + skip_users: Container[str], + min_count: int = 2, +) -> list[dict[str, Any]]: + users: list[dict[str, Any]] = [] + for commenter, count in counter.most_common(50): + if commenter in skip_users: + continue + if count >= min_count: + author = authors[commenter] + users.append( + { + "login": commenter, + "count": count, + "avatarUrl": author.avatarUrl, + "url": author.url, + } + ) + return users + + +def get_users_to_write( + *, + counter: Counter[str], + authors: dict[str, Author], + min_count: int = 2, +) -> list[dict[str, Any]]: + users: dict[str, Any] = {} + users_list: list[dict[str, Any]] = [] + for user, count in counter.most_common(60): + if count >= min_count: + author = authors[user] + user_data = { + "login": user, + "count": count, + "avatarUrl": author.avatarUrl, + "url": author.url, + } + users[user] = user_data + users_list.append(user_data) + return users_list + + +def update_content(*, content_path: Path, new_content: Any) -> bool: + old_content = content_path.read_text(encoding="utf-8") + + new_content = yaml.dump(new_content, sort_keys=False, width=200, allow_unicode=True) + if old_content == new_content: + logging.info(f"The content hasn't changed for {content_path}") + return False + content_path.write_text(new_content, encoding="utf-8") + logging.info(f"Updated {content_path}") + return True + + +def main() -> None: + logging.basicConfig(level=logging.INFO) + settings = Settings() + logging.info(f"Using config: {settings.model_dump_json()}") + g = Github(settings.github_token.get_secret_value()) + repo = g.get_repo(settings.github_repository) + + discussion_nodes = get_discussion_nodes(settings=settings) + experts_results = get_discussions_experts(discussion_nodes=discussion_nodes) + + authors = experts_results.authors + maintainers_logins = {"tiangolo"} + maintainers = [] + for login in maintainers_logins: + user = authors[login] + maintainers.append( + { + "login": login, + "answers": experts_results.commenters[login], + "avatarUrl": user.avatarUrl, + "url": user.url, + } + ) + + experts = get_users_to_write( + counter=experts_results.commenters, + authors=authors, + ) + last_month_experts = get_users_to_write( + counter=experts_results.last_month_commenters, + authors=authors, + ) + three_months_experts = get_users_to_write( + counter=experts_results.three_months_commenters, + authors=authors, + ) + six_months_experts = get_users_to_write( + counter=experts_results.six_months_commenters, + authors=authors, + ) + one_year_experts = get_users_to_write( + counter=experts_results.one_year_commenters, + authors=authors, + ) + + people = { + "maintainers": maintainers, + "experts": experts, + "last_month_experts": last_month_experts, + "three_months_experts": three_months_experts, + "six_months_experts": six_months_experts, + "one_year_experts": one_year_experts, + } + + # For local development + # people_path = Path("../docs/en/data/people.yml") + people_path = Path("./docs/en/data/people.yml") + + updated = update_content(content_path=people_path, new_content=people) + + if not updated: + logging.info("The data hasn't changed, finishing.") + return + + logging.info("Setting up GitHub Actions git user") + subprocess.run(["git", "config", "user.name", "github-actions"], check=True) + subprocess.run( + ["git", "config", "user.email", "github-actions@github.com"], check=True + ) + branch_name = f"fastapi-people-experts-{secrets.token_hex(4)}" + logging.info(f"Creating a new branch {branch_name}") + subprocess.run(["git", "checkout", "-b", branch_name], check=True) + logging.info("Adding updated file") + subprocess.run(["git", "add", str(people_path)], check=True) + logging.info("Committing updated file") + message = "👥 Update FastAPI People - Experts" + subprocess.run(["git", "commit", "-m", message], check=True) + logging.info("Pushing branch") + subprocess.run(["git", "push", "origin", branch_name], check=True) + logging.info("Creating PR") + pr = repo.create_pull(title=message, body=message, base="master", head=branch_name) + logging.info(f"Created PR: {pr.number}") + logging.info("Finished") + + +if __name__ == "__main__": + main() diff --git a/scripts/playwright/cookie_param_models/image01.py b/scripts/playwright/cookie_param_models/image01.py new file mode 100644 index 000000000..77c91bfe2 --- /dev/null +++ b/scripts/playwright/cookie_param_models/image01.py @@ -0,0 +1,39 @@ +import subprocess +import time + +import httpx +from playwright.sync_api import Playwright, sync_playwright + + +# Run playwright codegen to generate the code below, copy paste the sections in run() +def run(playwright: Playwright) -> None: + browser = playwright.chromium.launch(headless=False) + # Update the viewport manually + context = browser.new_context(viewport={"width": 960, "height": 1080}) + browser = playwright.chromium.launch(headless=False) + context = browser.new_context() + page = context.new_page() + page.goto("http://localhost:8000/docs") + page.get_by_role("link", name="/items/").click() + # Manually add the screenshot + page.screenshot(path="docs/en/docs/img/tutorial/cookie-param-models/image01.png") + + # --------------------- + context.close() + browser.close() + + +process = subprocess.Popen( + ["fastapi", "run", "docs_src/cookie_param_models/tutorial001.py"] +) +try: + for _ in range(3): + try: + response = httpx.get("http://localhost:8000/docs") + except httpx.ConnectError: + time.sleep(1) + break + with sync_playwright() as playwright: + run(playwright) +finally: + process.terminate() diff --git a/scripts/playwright/header_param_models/image01.py b/scripts/playwright/header_param_models/image01.py new file mode 100644 index 000000000..53914251e --- /dev/null +++ b/scripts/playwright/header_param_models/image01.py @@ -0,0 +1,38 @@ +import subprocess +import time + +import httpx +from playwright.sync_api import Playwright, sync_playwright + + +# Run playwright codegen to generate the code below, copy paste the sections in run() +def run(playwright: Playwright) -> None: + browser = playwright.chromium.launch(headless=False) + # Update the viewport manually + context = browser.new_context(viewport={"width": 960, "height": 1080}) + page = context.new_page() + page.goto("http://localhost:8000/docs") + page.get_by_role("button", name="GET /items/ Read Items").click() + page.get_by_role("button", name="Try it out").click() + # Manually add the screenshot + page.screenshot(path="docs/en/docs/img/tutorial/header-param-models/image01.png") + + # --------------------- + context.close() + browser.close() + + +process = subprocess.Popen( + ["fastapi", "run", "docs_src/header_param_models/tutorial001.py"] +) +try: + for _ in range(3): + try: + response = httpx.get("http://localhost:8000/docs") + except httpx.ConnectError: + time.sleep(1) + break + with sync_playwright() as playwright: + run(playwright) +finally: + process.terminate() diff --git a/scripts/playwright/query_param_models/image01.py b/scripts/playwright/query_param_models/image01.py new file mode 100644 index 000000000..0ea1d0df4 --- /dev/null +++ b/scripts/playwright/query_param_models/image01.py @@ -0,0 +1,41 @@ +import subprocess +import time + +import httpx +from playwright.sync_api import Playwright, sync_playwright + + +# Run playwright codegen to generate the code below, copy paste the sections in run() +def run(playwright: Playwright) -> None: + browser = playwright.chromium.launch(headless=False) + # Update the viewport manually + context = browser.new_context(viewport={"width": 960, "height": 1080}) + browser = playwright.chromium.launch(headless=False) + context = browser.new_context() + page = context.new_page() + page.goto("http://localhost:8000/docs") + page.get_by_role("button", name="GET /items/ Read Items").click() + page.get_by_role("button", name="Try it out").click() + page.get_by_role("heading", name="Servers").click() + # Manually add the screenshot + page.screenshot(path="docs/en/docs/img/tutorial/query-param-models/image01.png") + + # --------------------- + context.close() + browser.close() + + +process = subprocess.Popen( + ["fastapi", "run", "docs_src/query_param_models/tutorial001.py"] +) +try: + for _ in range(3): + try: + response = httpx.get("http://localhost:8000/docs") + except httpx.ConnectError: + time.sleep(1) + break + with sync_playwright() as playwright: + run(playwright) +finally: + process.terminate() diff --git a/scripts/playwright/request_form_models/image01.py b/scripts/playwright/request_form_models/image01.py new file mode 100644 index 000000000..fe4da32fc --- /dev/null +++ b/scripts/playwright/request_form_models/image01.py @@ -0,0 +1,38 @@ +import subprocess +import time + +import httpx +from playwright.sync_api import Playwright, sync_playwright + + +# Run playwright codegen to generate the code below, copy paste the sections in run() +def run(playwright: Playwright) -> None: + browser = playwright.chromium.launch(headless=False) + # Update the viewport manually + context = browser.new_context(viewport={"width": 960, "height": 1080}) + page = context.new_page() + page.goto("http://localhost:8000/docs") + page.get_by_role("button", name="POST /login/ Login").click() + page.get_by_role("button", name="Try it out").click() + # Manually add the screenshot + page.screenshot(path="docs/en/docs/img/tutorial/request-form-models/image01.png") + + # --------------------- + context.close() + browser.close() + + +process = subprocess.Popen( + ["fastapi", "run", "docs_src/request_form_models/tutorial001.py"] +) +try: + for _ in range(3): + try: + response = httpx.get("http://localhost:8000/docs") + except httpx.ConnectError: + time.sleep(1) + break + with sync_playwright() as playwright: + run(playwright) +finally: + process.terminate() diff --git a/scripts/playwright/separate_openapi_schemas/image01.py b/scripts/playwright/separate_openapi_schemas/image01.py index 0b40f3bbc..0eb55fb73 100644 --- a/scripts/playwright/separate_openapi_schemas/image01.py +++ b/scripts/playwright/separate_openapi_schemas/image01.py @@ -3,13 +3,16 @@ import subprocess from playwright.sync_api import Playwright, sync_playwright +# Run playwright codegen to generate the code below, copy paste the sections in run() def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) + # Update the viewport manually context = browser.new_context(viewport={"width": 960, "height": 1080}) page = context.new_page() page.goto("http://localhost:8000/docs") page.get_by_text("POST/items/Create Item").click() page.get_by_role("tab", name="Schema").first.click() + # Manually add the screenshot page.screenshot( path="docs/en/docs/img/tutorial/separate-openapi-schemas/image01.png" ) diff --git a/scripts/playwright/separate_openapi_schemas/image02.py b/scripts/playwright/separate_openapi_schemas/image02.py index f76af7ee2..0eb6c3c79 100644 --- a/scripts/playwright/separate_openapi_schemas/image02.py +++ b/scripts/playwright/separate_openapi_schemas/image02.py @@ -3,14 +3,17 @@ import subprocess from playwright.sync_api import Playwright, sync_playwright +# Run playwright codegen to generate the code below, copy paste the sections in run() def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) + # Update the viewport manually context = browser.new_context(viewport={"width": 960, "height": 1080}) page = context.new_page() page.goto("http://localhost:8000/docs") page.get_by_text("GET/items/Read Items").click() page.get_by_role("button", name="Try it out").click() page.get_by_role("button", name="Execute").click() + # Manually add the screenshot page.screenshot( path="docs/en/docs/img/tutorial/separate-openapi-schemas/image02.png" ) diff --git a/scripts/playwright/separate_openapi_schemas/image03.py b/scripts/playwright/separate_openapi_schemas/image03.py index 127f5c428..b68e9d7db 100644 --- a/scripts/playwright/separate_openapi_schemas/image03.py +++ b/scripts/playwright/separate_openapi_schemas/image03.py @@ -3,14 +3,17 @@ import subprocess from playwright.sync_api import Playwright, sync_playwright +# Run playwright codegen to generate the code below, copy paste the sections in run() def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) + # Update the viewport manually context = browser.new_context(viewport={"width": 960, "height": 1080}) page = context.new_page() page.goto("http://localhost:8000/docs") page.get_by_text("GET/items/Read Items").click() page.get_by_role("tab", name="Schema").click() page.get_by_label("Schema").get_by_role("button", name="Expand all").click() + # Manually add the screenshot page.screenshot( path="docs/en/docs/img/tutorial/separate-openapi-schemas/image03.png" ) diff --git a/scripts/playwright/separate_openapi_schemas/image04.py b/scripts/playwright/separate_openapi_schemas/image04.py index 208eaf8a0..a36c2f6b2 100644 --- a/scripts/playwright/separate_openapi_schemas/image04.py +++ b/scripts/playwright/separate_openapi_schemas/image04.py @@ -3,14 +3,17 @@ import subprocess from playwright.sync_api import Playwright, sync_playwright +# Run playwright codegen to generate the code below, copy paste the sections in run() def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) + # Update the viewport manually context = browser.new_context(viewport={"width": 960, "height": 1080}) page = context.new_page() page.goto("http://localhost:8000/docs") page.get_by_role("button", name="Item-Input").click() page.get_by_role("button", name="Item-Output").click() page.set_viewport_size({"width": 960, "height": 820}) + # Manually add the screenshot page.screenshot( path="docs/en/docs/img/tutorial/separate-openapi-schemas/image04.png" ) diff --git a/scripts/playwright/separate_openapi_schemas/image05.py b/scripts/playwright/separate_openapi_schemas/image05.py index 83966b449..0da5db0cf 100644 --- a/scripts/playwright/separate_openapi_schemas/image05.py +++ b/scripts/playwright/separate_openapi_schemas/image05.py @@ -3,13 +3,16 @@ import subprocess from playwright.sync_api import Playwright, sync_playwright +# Run playwright codegen to generate the code below, copy paste the sections in run() def run(playwright: Playwright) -> None: browser = playwright.chromium.launch(headless=False) + # Update the viewport manually context = browser.new_context(viewport={"width": 960, "height": 1080}) page = context.new_page() page.goto("http://localhost:8000/docs") page.get_by_role("button", name="Item", exact=True).click() page.set_viewport_size({"width": 960, "height": 700}) + # Manually add the screenshot page.screenshot( path="docs/en/docs/img/tutorial/separate-openapi-schemas/image05.png" ) diff --git a/scripts/playwright/sql_databases/image01.py b/scripts/playwright/sql_databases/image01.py new file mode 100644 index 000000000..0dd6f2514 --- /dev/null +++ b/scripts/playwright/sql_databases/image01.py @@ -0,0 +1,37 @@ +import subprocess +import time + +import httpx +from playwright.sync_api import Playwright, sync_playwright + + +# Run playwright codegen to generate the code below, copy paste the sections in run() +def run(playwright: Playwright) -> None: + browser = playwright.chromium.launch(headless=False) + # Update the viewport manually + context = browser.new_context(viewport={"width": 960, "height": 1080}) + page = context.new_page() + page.goto("http://localhost:8000/docs") + page.get_by_label("post /heroes/").click() + # Manually add the screenshot + page.screenshot(path="docs/en/docs/img/tutorial/sql-databases/image01.png") + + # --------------------- + context.close() + browser.close() + + +process = subprocess.Popen( + ["fastapi", "run", "docs_src/sql_databases/tutorial001.py"], +) +try: + for _ in range(3): + try: + response = httpx.get("http://localhost:8000/docs") + except httpx.ConnectError: + time.sleep(1) + break + with sync_playwright() as playwright: + run(playwright) +finally: + process.terminate() diff --git a/scripts/playwright/sql_databases/image02.py b/scripts/playwright/sql_databases/image02.py new file mode 100644 index 000000000..6c4f685e8 --- /dev/null +++ b/scripts/playwright/sql_databases/image02.py @@ -0,0 +1,37 @@ +import subprocess +import time + +import httpx +from playwright.sync_api import Playwright, sync_playwright + + +# Run playwright codegen to generate the code below, copy paste the sections in run() +def run(playwright: Playwright) -> None: + browser = playwright.chromium.launch(headless=False) + # Update the viewport manually + context = browser.new_context(viewport={"width": 960, "height": 1080}) + page = context.new_page() + page.goto("http://localhost:8000/docs") + page.get_by_label("post /heroes/").click() + # Manually add the screenshot + page.screenshot(path="docs/en/docs/img/tutorial/sql-databases/image02.png") + + # --------------------- + context.close() + browser.close() + + +process = subprocess.Popen( + ["fastapi", "run", "docs_src/sql_databases/tutorial002.py"], +) +try: + for _ in range(3): + try: + response = httpx.get("http://localhost:8000/docs") + except httpx.ConnectError: + time.sleep(1) + break + with sync_playwright() as playwright: + run(playwright) +finally: + process.terminate() diff --git a/scripts/publish.sh b/scripts/publish.sh deleted file mode 100755 index 122728a60..000000000 --- a/scripts/publish.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/usr/bin/env bash - -set -e - -flit publish diff --git a/scripts/sponsors.py b/scripts/sponsors.py new file mode 100644 index 000000000..45e02bd62 --- /dev/null +++ b/scripts/sponsors.py @@ -0,0 +1,221 @@ +import logging +import secrets +import subprocess +from collections import defaultdict +from pathlib import Path +from typing import Any + +import httpx +import yaml +from github import Github +from pydantic import BaseModel, SecretStr +from pydantic_settings import BaseSettings + +github_graphql_url = "https://api.github.com/graphql" + + +sponsors_query = """ +query Q($after: String) { + user(login: "tiangolo") { + sponsorshipsAsMaintainer(first: 100, after: $after) { + edges { + cursor + node { + sponsorEntity { + ... on Organization { + login + avatarUrl + url + } + ... on User { + login + avatarUrl + url + } + } + tier { + name + monthlyPriceInDollars + } + } + } + } + } +} +""" + + +class SponsorEntity(BaseModel): + login: str + avatarUrl: str + url: str + + +class Tier(BaseModel): + name: str + monthlyPriceInDollars: float + + +class SponsorshipAsMaintainerNode(BaseModel): + sponsorEntity: SponsorEntity + tier: Tier + + +class SponsorshipAsMaintainerEdge(BaseModel): + cursor: str + node: SponsorshipAsMaintainerNode + + +class SponsorshipAsMaintainer(BaseModel): + edges: list[SponsorshipAsMaintainerEdge] + + +class SponsorsUser(BaseModel): + sponsorshipsAsMaintainer: SponsorshipAsMaintainer + + +class SponsorsResponseData(BaseModel): + user: SponsorsUser + + +class SponsorsResponse(BaseModel): + data: SponsorsResponseData + + +class Settings(BaseSettings): + sponsors_token: SecretStr + pr_token: SecretStr + github_repository: str + httpx_timeout: int = 30 + + +def get_graphql_response( + *, + settings: Settings, + query: str, + after: str | None = None, +) -> dict[str, Any]: + headers = {"Authorization": f"token {settings.sponsors_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 response.status_code != 200: + logging.error(f"Response was not 200, after: {after}") + logging.error(response.text) + raise RuntimeError(response.text) + data = response.json() + if "errors" in data: + logging.error(f"Errors in response, after: {after}") + logging.error(data["errors"]) + logging.error(response.text) + raise RuntimeError(response.text) + return data + + +def get_graphql_sponsor_edges( + *, settings: Settings, after: str | None = None +) -> list[SponsorshipAsMaintainerEdge]: + data = get_graphql_response(settings=settings, query=sponsors_query, after=after) + graphql_response = SponsorsResponse.model_validate(data) + return graphql_response.data.user.sponsorshipsAsMaintainer.edges + + +def get_individual_sponsors( + settings: Settings, +) -> defaultdict[float, dict[str, SponsorEntity]]: + nodes: list[SponsorshipAsMaintainerNode] = [] + edges = get_graphql_sponsor_edges(settings=settings) + + while edges: + for edge in edges: + nodes.append(edge.node) + last_edge = edges[-1] + edges = get_graphql_sponsor_edges(settings=settings, after=last_edge.cursor) + + tiers: defaultdict[float, dict[str, SponsorEntity]] = defaultdict(dict) + for node in nodes: + tiers[node.tier.monthlyPriceInDollars][node.sponsorEntity.login] = ( + node.sponsorEntity + ) + return tiers + + +def update_content(*, content_path: Path, new_content: Any) -> bool: + old_content = content_path.read_text(encoding="utf-8") + + new_content = yaml.dump(new_content, sort_keys=False, width=200, allow_unicode=True) + if old_content == new_content: + logging.info(f"The content hasn't changed for {content_path}") + return False + content_path.write_text(new_content, encoding="utf-8") + logging.info(f"Updated {content_path}") + return True + + +def main() -> None: + logging.basicConfig(level=logging.INFO) + settings = Settings() + logging.info(f"Using config: {settings.model_dump_json()}") + g = Github(settings.pr_token.get_secret_value()) + repo = g.get_repo(settings.github_repository) + + tiers = get_individual_sponsors(settings=settings) + keys = list(tiers.keys()) + keys.sort(reverse=True) + sponsors = [] + for key in keys: + sponsor_group = [] + for login, sponsor in tiers[key].items(): + sponsor_group.append( + {"login": login, "avatarUrl": sponsor.avatarUrl, "url": sponsor.url} + ) + sponsors.append(sponsor_group) + github_sponsors = { + "sponsors": sponsors, + } + + # For local development + # github_sponsors_path = Path("../docs/en/data/github_sponsors.yml") + github_sponsors_path = Path("./docs/en/data/github_sponsors.yml") + updated = update_content( + content_path=github_sponsors_path, new_content=github_sponsors + ) + + if not updated: + logging.info("The data hasn't changed, finishing.") + return + + logging.info("Setting up GitHub Actions git user") + subprocess.run(["git", "config", "user.name", "github-actions"], check=True) + subprocess.run( + ["git", "config", "user.email", "github-actions@github.com"], check=True + ) + branch_name = f"fastapi-people-sponsors-{secrets.token_hex(4)}" + logging.info(f"Creating a new branch {branch_name}") + subprocess.run(["git", "checkout", "-b", branch_name], check=True) + logging.info("Adding updated file") + subprocess.run( + [ + "git", + "add", + str(github_sponsors_path), + ], + check=True, + ) + logging.info("Committing updated file") + message = "👥 Update FastAPI People - Sponsors" + subprocess.run(["git", "commit", "-m", message], check=True) + logging.info("Pushing branch") + subprocess.run(["git", "push", "origin", branch_name], check=True) + logging.info("Creating PR") + pr = repo.create_pull(title=message, body=message, base="master", head=branch_name) + logging.info(f"Created PR: {pr.number}") + logging.info("Finished") + + +if __name__ == "__main__": + main() diff --git a/scripts/test-cov-html.sh b/scripts/test-cov-html.sh index d1bdfced2..517ac6422 100755 --- a/scripts/test-cov-html.sh +++ b/scripts/test-cov-html.sh @@ -5,5 +5,5 @@ set -x bash scripts/test.sh ${@} coverage combine -coverage report --show-missing +coverage report coverage html diff --git a/scripts/topic_repos.py b/scripts/topic_repos.py new file mode 100644 index 000000000..bc1497751 --- /dev/null +++ b/scripts/topic_repos.py @@ -0,0 +1,80 @@ +import logging +import secrets +import subprocess +from pathlib import Path + +import yaml +from github import Github +from pydantic import BaseModel, SecretStr +from pydantic_settings import BaseSettings + + +class Settings(BaseSettings): + github_repository: str + github_token: SecretStr + + +class Repo(BaseModel): + name: str + html_url: str + stars: int + owner_login: str + owner_html_url: str + + +def main() -> None: + logging.basicConfig(level=logging.INFO) + settings = Settings() + + logging.info(f"Using config: {settings.model_dump_json()}") + g = Github(settings.github_token.get_secret_value(), per_page=100) + r = g.get_repo(settings.github_repository) + repos = g.search_repositories(query="topic:fastapi") + repos_list = list(repos) + final_repos: list[Repo] = [] + for repo in repos_list[:100]: + if repo.full_name == settings.github_repository: + continue + final_repos.append( + Repo( + name=repo.name, + html_url=repo.html_url, + stars=repo.stargazers_count, + owner_login=repo.owner.login, + owner_html_url=repo.owner.html_url, + ) + ) + data = [repo.model_dump() for repo in final_repos] + + # Local development + # repos_path = Path("../docs/en/data/topic_repos.yml") + repos_path = Path("./docs/en/data/topic_repos.yml") + repos_old_content = repos_path.read_text(encoding="utf-8") + new_repos_content = yaml.dump(data, sort_keys=False, width=200, allow_unicode=True) + if repos_old_content == new_repos_content: + logging.info("The data hasn't changed. Finishing.") + return + repos_path.write_text(new_repos_content, encoding="utf-8") + logging.info("Setting up GitHub Actions git user") + subprocess.run(["git", "config", "user.name", "github-actions"], check=True) + subprocess.run( + ["git", "config", "user.email", "github-actions@github.com"], check=True + ) + branch_name = f"fastapi-topic-repos-{secrets.token_hex(4)}" + logging.info(f"Creating a new branch {branch_name}") + subprocess.run(["git", "checkout", "-b", branch_name], check=True) + logging.info("Adding updated file") + subprocess.run(["git", "add", str(repos_path)], check=True) + logging.info("Committing updated file") + message = "👥 Update FastAPI GitHub topic repositories" + subprocess.run(["git", "commit", "-m", message], check=True) + logging.info("Pushing branch") + subprocess.run(["git", "push", "origin", branch_name], check=True) + logging.info("Creating PR") + pr = r.create_pull(title=message, body=message, base="master", head=branch_name) + logging.info(f"Created PR: {pr.number}") + logging.info("Finished") + + +if __name__ == "__main__": + main() diff --git a/scripts/translate.py b/scripts/translate.py new file mode 100644 index 000000000..ce11b3877 --- /dev/null +++ b/scripts/translate.py @@ -0,0 +1,162 @@ +from functools import lru_cache +from pathlib import Path +from typing import Iterable + +import typer +import yaml +from pydantic_ai import Agent + +non_translated_sections = ( + "reference/", + "release-notes.md", + "fastapi-people.md", + "external-links.md", + "newsletter.md", + "management-tasks.md", + "management.md", + "contributing.md", +) + + +general_prompt = """ +For technical terms in English that don't have a common translation term use the original term in English. + +For code snippets or fragments, surrounded by backticks (`), don't translate the content, keep the original in English. For example, `list`, `dict`, keep them as is. + +The content is written in markdown, write the translation in markdown as well. Don't add triple backticks (`) around the generated translation content. + +When there's an example of code, the console or a terminal, normally surrounded by triple backticks and a keyword like "console" or "bash" (e.g. ```console), do not translate the content, keep the original in English. + +The original content will be surrounded by triple percentage signs (%) and you should translate it to the target language. Do not include the triple percentage signs in the translation. +""" + + +@lru_cache +def get_langs() -> dict[str, str]: + return yaml.safe_load(Path("docs/language_names.yml").read_text()) + + +def generate_lang_path(*, lang: str, path: Path) -> Path: + en_docs_path = Path("docs/en/docs") + assert str(path).startswith( + str(en_docs_path) + ), f"Path must be inside {en_docs_path}" + lang_docs_path = Path(f"docs/{lang}/docs") + out_path = Path(str(path).replace(str(en_docs_path), str(lang_docs_path))) + return out_path + + +def translate_page(*, lang: str, path: Path) -> None: + langs = get_langs() + language = langs[lang] + lang_path = Path(f"docs/{lang}") + lang_path.mkdir(exist_ok=True) + lang_prompt_path = lang_path / "llm-prompt.md" + assert lang_prompt_path.exists(), f"Prompt file not found: {lang_prompt_path}" + lang_prompt_content = lang_prompt_path.read_text() + + en_docs_path = Path("docs/en/docs") + assert str(path).startswith( + str(en_docs_path) + ), f"Path must be inside {en_docs_path}" + out_path = generate_lang_path(lang=lang, path=path) + out_path.parent.mkdir(parents=True, exist_ok=True) + original_content = path.read_text() + old_translation: str | None = None + if out_path.exists(): + old_translation = out_path.read_text() + agent = Agent("openai:gpt-4o") + + prompt_segments = [ + lang_prompt_content, + general_prompt, + ] + if old_translation: + prompt_segments.extend( + [ + "There's an existing previous translation for this content that is probably outdated with old content or old instructions.", + "Update the translation given your current instructions and the original content.", + "If you have instructions to translate specific terms or phrases in a specific way, please follow those instructions instead of keeping the old and outdated content.", + "Previous translation:", + f"%%%\n{old_translation}%%%", + ] + ) + prompt_segments.extend( + [ + f"Translate to {language} ({lang}).", + "Original content:", + f"%%%\n{original_content}%%%", + ] + ) + prompt = "\n\n".join(prompt_segments) + + result = agent.run_sync(prompt) + out_content = f"{result.data.strip()}\n" + out_path.write_text(out_content) + + +def iter_paths_to_translate() -> Iterable[Path]: + """ + Iterate on the markdown files to translate in order of priority. + """ + first_dirs = [ + Path("docs/en/docs/learn"), + Path("docs/en/docs/tutorial"), + Path("docs/en/docs/advanced"), + Path("docs/en/docs/about"), + Path("docs/en/docs/how-to"), + ] + first_parent = Path("docs/en/docs") + yield from first_parent.glob("*.md") + for dir_path in first_dirs: + yield from dir_path.rglob("*.md") + first_dirs_str = tuple(str(d) for d in first_dirs) + for path in Path("docs/en/docs").rglob("*.md"): + if str(path).startswith(first_dirs_str): + continue + if path.parent == first_parent: + continue + yield path + + +def translate_all(lang: str) -> None: + paths_to_process: list[Path] = [] + for path in iter_paths_to_translate(): + if str(path).replace("docs/en/docs/", "").startswith(non_translated_sections): + continue + paths_to_process.append(path) + print("Original paths:") + for p in paths_to_process: + print(f" - {p}") + print(f"Total original paths: {len(paths_to_process)}") + missing_paths: list[Path] = [] + skipped_paths: list[Path] = [] + for p in paths_to_process: + lang_path = generate_lang_path(lang=lang, path=p) + if lang_path.exists(): + skipped_paths.append(p) + continue + missing_paths.append(p) + print("Paths to skip:") + for p in skipped_paths: + print(f" - {p}") + print(f"Total paths to skip: {len(skipped_paths)}") + print("Paths to process:") + for p in missing_paths: + print(f" - {p}") + print(f"Total paths to process: {len(missing_paths)}") + for p in missing_paths: + print(f"Translating: {p}") + translate_page(lang="es", path=p) + print(f"Done translating: {p}") + + +def main(*, lang: str, path: Path = None) -> None: + if path: + translate_page(lang=lang, path=path) + else: + translate_all(lang=lang) + + +if __name__ == "__main__": + typer.run(main) diff --git a/tests/main.py b/tests/main.py index 15760c039..6927eab61 100644 --- a/tests/main.py +++ b/tests/main.py @@ -1,5 +1,5 @@ import http -from typing import FrozenSet, Optional +from typing import FrozenSet, List, Optional from fastapi import FastAPI, Path, Query @@ -192,3 +192,13 @@ def get_enum_status_code(): @app.get("/query/frozenset") def get_query_type_frozenset(query: FrozenSet[int] = Query(...)): return ",".join(map(str, sorted(query))) + + +@app.get("/query/list") +def get_query_list(device_ids: List[int] = Query()) -> List[int]: + return device_ids + + +@app.get("/query/list-default") +def get_query_list_default(device_ids: List[int] = Query(default=[])) -> List[int]: + return device_ids diff --git a/tests/test_allow_inf_nan_in_enforcing.py b/tests/test_allow_inf_nan_in_enforcing.py new file mode 100644 index 000000000..9e855fdf8 --- /dev/null +++ b/tests/test_allow_inf_nan_in_enforcing.py @@ -0,0 +1,83 @@ +import pytest +from fastapi import Body, FastAPI, Query +from fastapi.testclient import TestClient +from typing_extensions import Annotated + +app = FastAPI() + + +@app.post("/") +async def get( + x: Annotated[float, Query(allow_inf_nan=True)] = 0, + y: Annotated[float, Query(allow_inf_nan=False)] = 0, + z: Annotated[float, Query()] = 0, + b: Annotated[float, Body(allow_inf_nan=False)] = 0, +) -> str: + return "OK" + + +client = TestClient(app) + + +@pytest.mark.parametrize( + "value,code", + [ + ("-1", 200), + ("inf", 200), + ("-inf", 200), + ("nan", 200), + ("0", 200), + ("342", 200), + ], +) +def test_allow_inf_nan_param_true(value: str, code: int): + response = client.post(f"/?x={value}") + assert response.status_code == code, response.text + + +@pytest.mark.parametrize( + "value,code", + [ + ("-1", 200), + ("inf", 422), + ("-inf", 422), + ("nan", 422), + ("0", 200), + ("342", 200), + ], +) +def test_allow_inf_nan_param_false(value: str, code: int): + response = client.post(f"/?y={value}") + assert response.status_code == code, response.text + + +@pytest.mark.parametrize( + "value,code", + [ + ("-1", 200), + ("inf", 200), + ("-inf", 200), + ("nan", 200), + ("0", 200), + ("342", 200), + ], +) +def test_allow_inf_nan_param_default(value: str, code: int): + response = client.post(f"/?z={value}") + assert response.status_code == code, response.text + + +@pytest.mark.parametrize( + "value,code", + [ + ("-1", 200), + ("inf", 422), + ("-inf", 422), + ("nan", 422), + ("0", 200), + ("342", 200), + ], +) +def test_allow_inf_nan_body(value: str, code: int): + response = client.post("/", json=value) + assert response.status_code == code, response.text diff --git a/tests/test_annotated.py b/tests/test_annotated.py index 2222be978..473d33e52 100644 --- a/tests/test_annotated.py +++ b/tests/test_annotated.py @@ -2,7 +2,6 @@ import pytest from dirty_equals import IsDict from fastapi import APIRouter, FastAPI, Query from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from typing_extensions import Annotated app = FastAPI() @@ -38,7 +37,6 @@ foo_is_missing = { "msg": "Field required", "type": "missing", "input": None, - "url": match_pydantic_error_url("missing"), } ) # TODO: remove when deprecating Pydantic v1 @@ -60,7 +58,6 @@ foo_is_short = { "msg": "String should have at least 1 character", "type": "string_too_short", "input": "", - "url": match_pydantic_error_url("string_too_short"), } ) # TODO: remove when deprecating Pydantic v1 diff --git a/tests/test_application.py b/tests/test_application.py index ea7a80128..5c62f5f6e 100644 --- a/tests/test_application.py +++ b/tests/test_application.py @@ -1163,6 +1163,91 @@ def test_openapi_schema(): }, } }, + "/query/list": { + "get": { + "summary": "Get Query List", + "operationId": "get_query_list_query_list_get", + "parameters": [ + { + "name": "device_ids", + "in": "query", + "required": True, + "schema": { + "type": "array", + "items": {"type": "integer"}, + "title": "Device Ids", + }, + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": {"type": "integer"}, + "title": "Response Get Query List Query List Get", + } + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + }, + "/query/list-default": { + "get": { + "summary": "Get Query List Default", + "operationId": "get_query_list_default_query_list_default_get", + "parameters": [ + { + "name": "device_ids", + "in": "query", + "required": False, + "schema": { + "type": "array", + "items": {"type": "integer"}, + "default": [], + "title": "Device Ids", + }, + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": {"type": "integer"}, + "title": "Response Get Query List Default Query List Default Get", + } + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + }, }, "components": { "schemas": { diff --git a/tests/test_compat.py b/tests/test_compat.py index bf268b860..f4a3093c5 100644 --- a/tests/test_compat.py +++ b/tests/test_compat.py @@ -1,11 +1,14 @@ -from typing import List, Union +from typing import Any, Dict, List, Union from fastapi import FastAPI, UploadFile from fastapi._compat import ( ModelField, Undefined, _get_model_config, + get_cached_model_fields, + get_model_fields, is_bytes_sequence_annotation, + is_scalar_field, is_uploadfile_sequence_annotation, ) from fastapi.testclient import TestClient @@ -91,3 +94,27 @@ def test_is_uploadfile_sequence_annotation(): # and other types, but I'm not even sure it's a good idea to support it as a first # class "feature" assert is_uploadfile_sequence_annotation(Union[List[str], List[UploadFile]]) + + +def test_is_pv1_scalar_field(): + # For coverage + class Model(BaseModel): + foo: Union[str, Dict[str, Any]] + + fields = get_model_fields(Model) + assert not is_scalar_field(fields[0]) + + +def test_get_model_fields_cached(): + class Model(BaseModel): + foo: str + + non_cached_fields = get_model_fields(Model) + non_cached_fields2 = get_model_fields(Model) + cached_fields = get_cached_model_fields(Model) + cached_fields2 = get_cached_model_fields(Model) + for f1, f2 in zip(cached_fields, cached_fields2): + assert f1 is f2 + + assert non_cached_fields is not non_cached_fields2 + assert cached_fields is cached_fields2 diff --git a/tests/test_computed_fields.py b/tests/test_computed_fields.py index 5286507b2..a1b412168 100644 --- a/tests/test_computed_fields.py +++ b/tests/test_computed_fields.py @@ -24,13 +24,18 @@ def get_client(): def read_root() -> Rectangle: return Rectangle(width=3, length=4) + @app.get("/responses", responses={200: {"model": Rectangle}}) + def read_responses() -> Rectangle: + return Rectangle(width=3, length=4) + client = TestClient(app) return client +@pytest.mark.parametrize("path", ["/", "/responses"]) @needs_pydanticv2 -def test_get(client: TestClient): - response = client.get("/") +def test_get(client: TestClient, path: str): + response = client.get(path) assert response.status_code == 200, response.text assert response.json() == {"width": 3, "length": 4, "area": 12} @@ -58,7 +63,23 @@ def test_openapi_schema(client: TestClient): } }, } - } + }, + "/responses": { + "get": { + "summary": "Read Responses", + "operationId": "read_responses_responses_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Rectangle"} + } + }, + } + }, + } + }, }, "components": { "schemas": { diff --git a/tests/test_dependency_contextmanager.py b/tests/test_dependency_contextmanager.py index b07f9aa5b..039c423b9 100644 --- a/tests/test_dependency_contextmanager.py +++ b/tests/test_dependency_contextmanager.py @@ -55,6 +55,7 @@ async def asyncgen_state_try(state: Dict[str, str] = Depends(get_state)): yield state["/async_raise"] except AsyncDependencyError: errors.append("/async_raise") + raise finally: state["/async_raise"] = "asyncgen raise finalized" @@ -65,6 +66,7 @@ def generator_state_try(state: Dict[str, str] = Depends(get_state)): yield state["/sync_raise"] except SyncDependencyError: errors.append("/sync_raise") + raise finally: state["/sync_raise"] = "generator raise finalized" @@ -194,9 +196,9 @@ async def get_sync_context_b_bg( tasks: BackgroundTasks, state: dict = Depends(context_b) ): async def bg(state: dict): - state[ - "sync_bg" - ] = f"sync_bg set - b: {state['context_b']} - a: {state['context_a']}" + state["sync_bg"] = ( + f"sync_bg set - b: {state['context_b']} - a: {state['context_a']}" + ) tasks.add_task(bg, state) return state diff --git a/tests/test_dependency_duplicates.py b/tests/test_dependency_duplicates.py index 0882cc41d..8e8d07c2d 100644 --- a/tests/test_dependency_duplicates.py +++ b/tests/test_dependency_duplicates.py @@ -3,7 +3,6 @@ from typing import List from dirty_equals import IsDict from fastapi import Depends, FastAPI from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from pydantic import BaseModel app = FastAPI() @@ -57,7 +56,6 @@ def test_no_duplicates_invalid(): "loc": ["body", "item2"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } diff --git a/tests/test_dependency_normal_exceptions.py b/tests/test_dependency_normal_exceptions.py index 23c366d5d..326f8fd88 100644 --- a/tests/test_dependency_normal_exceptions.py +++ b/tests/test_dependency_normal_exceptions.py @@ -20,6 +20,7 @@ async def get_database(): fake_database.update(temp_database) except HTTPException: state["except"] = True + raise finally: state["finally"] = True diff --git a/tests/test_dependency_overrides.py b/tests/test_dependency_overrides.py index 21cff998d..154937fa0 100644 --- a/tests/test_dependency_overrides.py +++ b/tests/test_dependency_overrides.py @@ -4,7 +4,6 @@ import pytest from dirty_equals import IsDict from fastapi import APIRouter, Depends, FastAPI from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url app = FastAPI() @@ -63,7 +62,6 @@ def test_main_depends(): "loc": ["query", "q"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -110,7 +108,6 @@ def test_decorator_depends(): "loc": ["query", "q"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -151,7 +148,6 @@ def test_router_depends(): "loc": ["query", "q"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -198,7 +194,6 @@ def test_router_decorator_depends(): "loc": ["query", "q"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -285,7 +280,6 @@ def test_override_with_sub_main_depends(): "loc": ["query", "k"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -316,7 +310,6 @@ def test_override_with_sub__main_depends_q_foo(): "loc": ["query", "k"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -355,7 +348,6 @@ def test_override_with_sub_decorator_depends(): "loc": ["query", "k"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -386,7 +378,6 @@ def test_override_with_sub_decorator_depends_q_foo(): "loc": ["query", "k"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -425,7 +416,6 @@ def test_override_with_sub_router_depends(): "loc": ["query", "k"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -456,7 +446,6 @@ def test_override_with_sub_router_depends_q_foo(): "loc": ["query", "k"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -495,7 +484,6 @@ def test_override_with_sub_router_decorator_depends(): "loc": ["query", "k"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -526,7 +514,6 @@ def test_override_with_sub_router_decorator_depends_q_foo(): "loc": ["query", "k"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } diff --git a/tests/test_exception_handlers.py b/tests/test_exception_handlers.py index 67a4becec..6a3cbd830 100644 --- a/tests/test_exception_handlers.py +++ b/tests/test_exception_handlers.py @@ -1,5 +1,5 @@ import pytest -from fastapi import FastAPI, HTTPException +from fastapi import Depends, FastAPI, HTTPException from fastapi.exceptions import RequestValidationError from fastapi.testclient import TestClient from starlette.responses import JSONResponse @@ -28,6 +28,18 @@ app = FastAPI( client = TestClient(app) +def raise_value_error(): + raise ValueError() + + +def dependency_with_yield(): + yield raise_value_error() + + +@app.get("/dependency-with-yield", dependencies=[Depends(dependency_with_yield)]) +def with_yield(): ... + + @app.get("/http-exception") def route_with_http_exception(): raise HTTPException(status_code=400) @@ -65,3 +77,12 @@ def test_override_server_error_exception_response(): response = client.get("/server-error") assert response.status_code == 500 assert response.json() == {"exception": "server-error"} + + +def test_traceback_for_dependency_with_yield(): + client = TestClient(app, raise_server_exceptions=True) + with pytest.raises(ValueError) as exc_info: + client.get("/dependency-with-yield") + last_frame = exc_info.traceback[-1] + assert str(last_frame.path) == __file__ + assert last_frame.lineno == raise_value_error.__code__.co_firstlineno diff --git a/tests/test_fastapi_cli.py b/tests/test_fastapi_cli.py new file mode 100644 index 000000000..a5c10778a --- /dev/null +++ b/tests/test_fastapi_cli.py @@ -0,0 +1,32 @@ +import subprocess +import sys +from unittest.mock import patch + +import fastapi.cli +import pytest + + +def test_fastapi_cli(): + result = subprocess.run( + [ + sys.executable, + "-m", + "coverage", + "run", + "-m", + "fastapi", + "dev", + "non_existent_file.py", + ], + capture_output=True, + encoding="utf-8", + ) + assert result.returncode == 1, result.stdout + assert "Path does not exist non_existent_file.py" in result.stdout + + +def test_fastapi_cli_not_installed(): + with patch.object(fastapi.cli, "cli_main", None): + with pytest.raises(RuntimeError) as exc_info: + fastapi.cli.main() + assert "To use the fastapi command, please install" in str(exc_info.value) diff --git a/tests/test_filter_pydantic_sub_model_pv2.py b/tests/test_filter_pydantic_sub_model_pv2.py index 9097d2ce5..2e2c26ddc 100644 --- a/tests/test_filter_pydantic_sub_model_pv2.py +++ b/tests/test_filter_pydantic_sub_model_pv2.py @@ -5,7 +5,6 @@ from dirty_equals import HasRepr, IsDict, IsOneOf from fastapi import Depends, FastAPI from fastapi.exceptions import ResponseValidationError from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from .utils import needs_pydanticv2 @@ -67,7 +66,6 @@ def test_validator_is_cloned(client: TestClient): "msg": "Value error, name must end in A", "input": "modelX", "ctx": {"error": HasRepr("ValueError('name must end in A')")}, - "url": match_pydantic_error_url("value_error"), } ) | IsDict( diff --git a/tests/test_forms_single_model.py b/tests/test_forms_single_model.py new file mode 100644 index 000000000..880ab3820 --- /dev/null +++ b/tests/test_forms_single_model.py @@ -0,0 +1,133 @@ +from typing import List, Optional + +from dirty_equals import IsDict +from fastapi import FastAPI, Form +from fastapi.testclient import TestClient +from pydantic import BaseModel, Field +from typing_extensions import Annotated + +app = FastAPI() + + +class FormModel(BaseModel): + username: str + lastname: str + age: Optional[int] = None + tags: List[str] = ["foo", "bar"] + alias_with: str = Field(alias="with", default="nothing") + + +@app.post("/form/") +def post_form(user: Annotated[FormModel, Form()]): + return user + + +client = TestClient(app) + + +def test_send_all_data(): + response = client.post( + "/form/", + data={ + "username": "Rick", + "lastname": "Sanchez", + "age": "70", + "tags": ["plumbus", "citadel"], + "with": "something", + }, + ) + assert response.status_code == 200, response.text + assert response.json() == { + "username": "Rick", + "lastname": "Sanchez", + "age": 70, + "tags": ["plumbus", "citadel"], + "with": "something", + } + + +def test_defaults(): + response = client.post("/form/", data={"username": "Rick", "lastname": "Sanchez"}) + assert response.status_code == 200, response.text + assert response.json() == { + "username": "Rick", + "lastname": "Sanchez", + "age": None, + "tags": ["foo", "bar"], + "with": "nothing", + } + + +def test_invalid_data(): + response = client.post( + "/form/", + data={ + "username": "Rick", + "lastname": "Sanchez", + "age": "seventy", + "tags": ["plumbus", "citadel"], + }, + ) + assert response.status_code == 422, response.text + assert response.json() == IsDict( + { + "detail": [ + { + "type": "int_parsing", + "loc": ["body", "age"], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "seventy", + } + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "age"], + "msg": "value is not a valid integer", + "type": "type_error.integer", + } + ] + } + ) + + +def test_no_data(): + response = client.post("/form/") + assert response.status_code == 422, response.text + assert response.json() == IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["body", "username"], + "msg": "Field required", + "input": {"tags": ["foo", "bar"], "with": "nothing"}, + }, + { + "type": "missing", + "loc": ["body", "lastname"], + "msg": "Field required", + "input": {"tags": ["foo", "bar"], "with": "nothing"}, + }, + ] + } + ) | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "loc": ["body", "username"], + "msg": "field required", + "type": "value_error.missing", + }, + { + "loc": ["body", "lastname"], + "msg": "field required", + "type": "value_error.missing", + }, + ] + } + ) diff --git a/tests/test_forms_single_param.py b/tests/test_forms_single_param.py new file mode 100644 index 000000000..3bb951441 --- /dev/null +++ b/tests/test_forms_single_param.py @@ -0,0 +1,99 @@ +from fastapi import FastAPI, Form +from fastapi.testclient import TestClient +from typing_extensions import Annotated + +app = FastAPI() + + +@app.post("/form/") +def post_form(username: Annotated[str, Form()]): + return username + + +client = TestClient(app) + + +def test_single_form_field(): + response = client.post("/form/", data={"username": "Rick"}) + assert response.status_code == 200, response.text + assert response.json() == "Rick" + + +def test_openapi_schema(): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/form/": { + "post": { + "summary": "Post Form", + "operationId": "post_form_form__post", + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": { + "$ref": "#/components/schemas/Body_post_form_form__post" + } + } + }, + "required": True, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "Body_post_form_form__post": { + "properties": {"username": {"type": "string", "title": "Username"}}, + "type": "object", + "required": ["username"], + "title": "Body_post_form_form__post", + }, + "HTTPValidationError": { + "properties": { + "detail": { + "items": {"$ref": "#/components/schemas/ValidationError"}, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } diff --git a/tests/test_generic_parameterless_depends.py b/tests/test_generic_parameterless_depends.py new file mode 100644 index 000000000..fe13ff89b --- /dev/null +++ b/tests/test_generic_parameterless_depends.py @@ -0,0 +1,77 @@ +from typing import TypeVar + +from fastapi import Depends, FastAPI +from fastapi.testclient import TestClient +from typing_extensions import Annotated + +app = FastAPI() + +T = TypeVar("T") + +Dep = Annotated[T, Depends()] + + +class A: + pass + + +class B: + pass + + +@app.get("/a") +async def a(dep: Dep[A]): + return {"cls": dep.__class__.__name__} + + +@app.get("/b") +async def b(dep: Dep[B]): + return {"cls": dep.__class__.__name__} + + +client = TestClient(app) + + +def test_generic_parameterless_depends(): + response = client.get("/a") + assert response.status_code == 200, response.text + assert response.json() == {"cls": "A"} + + response = client.get("/b") + assert response.status_code == 200, response.text + assert response.json() == {"cls": "B"} + + +def test_openapi_schema(): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == { + "info": {"title": "FastAPI", "version": "0.1.0"}, + "openapi": "3.1.0", + "paths": { + "/a": { + "get": { + "operationId": "a_a_get", + "responses": { + "200": { + "content": {"application/json": {"schema": {}}}, + "description": "Successful " "Response", + } + }, + "summary": "A", + } + }, + "/b": { + "get": { + "operationId": "b_b_get", + "responses": { + "200": { + "content": {"application/json": {"schema": {}}}, + "description": "Successful " "Response", + } + }, + "summary": "B", + } + }, + }, + } diff --git a/tests/test_inherited_custom_class.py b/tests/test_inherited_custom_class.py index 42b249211..fe9350f4e 100644 --- a/tests/test_inherited_custom_class.py +++ b/tests/test_inherited_custom_class.py @@ -36,7 +36,7 @@ def test_pydanticv2(): def return_fast_uuid(): asyncpg_uuid = MyUuid("a10ff360-3b1e-4984-a26f-d3ab460bdb51") assert isinstance(asyncpg_uuid, uuid.UUID) - assert type(asyncpg_uuid) != uuid.UUID + assert type(asyncpg_uuid) is not uuid.UUID with pytest.raises(TypeError): vars(asyncpg_uuid) return {"fast_uuid": asyncpg_uuid} @@ -79,7 +79,7 @@ def test_pydanticv1(): def return_fast_uuid(): asyncpg_uuid = MyUuid("a10ff360-3b1e-4984-a26f-d3ab460bdb51") assert isinstance(asyncpg_uuid, uuid.UUID) - assert type(asyncpg_uuid) != uuid.UUID + assert type(asyncpg_uuid) is not uuid.UUID with pytest.raises(TypeError): vars(asyncpg_uuid) return {"fast_uuid": asyncpg_uuid} diff --git a/tests/test_jsonable_encoder.py b/tests/test_jsonable_encoder.py index 7c8338ff3..1906d6bf1 100644 --- a/tests/test_jsonable_encoder.py +++ b/tests/test_jsonable_encoder.py @@ -7,7 +7,7 @@ from pathlib import PurePath, PurePosixPath, PureWindowsPath from typing import Optional import pytest -from fastapi._compat import PYDANTIC_V2 +from fastapi._compat import PYDANTIC_V2, Undefined from fastapi.encoders import jsonable_encoder from pydantic import BaseModel, Field, ValidationError @@ -310,3 +310,9 @@ def test_encode_deque_encodes_child_models(): dq = deque([Model(test="test")]) assert jsonable_encoder(dq)[0]["test"] == "test" + + +@needs_pydanticv2 +def test_encode_pydantic_undefined(): + data = {"value": Undefined} + assert jsonable_encoder(data) == {"value": None} diff --git a/tests/test_modules_same_name_body/test_main.py b/tests/test_modules_same_name_body/test_main.py index cc165bdca..263d87df2 100644 --- a/tests/test_modules_same_name_body/test_main.py +++ b/tests/test_modules_same_name_body/test_main.py @@ -1,3 +1,4 @@ +import pytest from fastapi.testclient import TestClient from .app.main import app @@ -5,29 +6,22 @@ from .app.main import app client = TestClient(app) -def test_post_a(): +@pytest.mark.parametrize( + "path", ["/a/compute", "/a/compute/", "/b/compute", "/b/compute/"] +) +def test_post(path): data = {"a": 2, "b": "foo"} - response = client.post("/a/compute", json=data) + response = client.post(path, json=data) assert response.status_code == 200, response.text - data = response.json() + assert data == response.json() -def test_post_a_invalid(): +@pytest.mark.parametrize( + "path", ["/a/compute", "/a/compute/", "/b/compute", "/b/compute/"] +) +def test_post_invalid(path): data = {"a": "bar", "b": "foo"} - response = client.post("/a/compute", json=data) - assert response.status_code == 422, response.text - - -def test_post_b(): - data = {"a": 2, "b": "foo"} - response = client.post("/b/compute/", json=data) - assert response.status_code == 200, response.text - data = response.json() - - -def test_post_b_invalid(): - data = {"a": "bar", "b": "foo"} - response = client.post("/b/compute/", json=data) + response = client.post(path, json=data) assert response.status_code == 422, response.text diff --git a/tests/test_multi_body_errors.py b/tests/test_multi_body_errors.py index a51ca7253..0102f0f1a 100644 --- a/tests/test_multi_body_errors.py +++ b/tests/test_multi_body_errors.py @@ -4,7 +4,6 @@ from typing import List from dirty_equals import IsDict, IsOneOf from fastapi import FastAPI from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from pydantic import BaseModel, condecimal app = FastAPI() @@ -52,7 +51,6 @@ def test_jsonable_encoder_requiring_error(): "msg": "Input should be greater than 0", "input": -1.0, "ctx": {"gt": 0}, - "url": match_pydantic_error_url("greater_than"), } ] } @@ -82,28 +80,24 @@ def test_put_incorrect_body_multiple(): "loc": ["body", 0, "name"], "msg": "Field required", "input": {"age": "five"}, - "url": match_pydantic_error_url("missing"), }, { "type": "decimal_parsing", "loc": ["body", 0, "age"], "msg": "Input should be a valid decimal", "input": "five", - "url": match_pydantic_error_url("decimal_parsing"), }, { "type": "missing", "loc": ["body", 1, "name"], "msg": "Field required", "input": {"age": "six"}, - "url": match_pydantic_error_url("missing"), }, { "type": "decimal_parsing", "loc": ["body", 1, "age"], "msg": "Input should be a valid decimal", "input": "six", - "url": match_pydantic_error_url("decimal_parsing"), }, ] } diff --git a/tests/test_multi_query_errors.py b/tests/test_multi_query_errors.py index 470a35808..8162d986c 100644 --- a/tests/test_multi_query_errors.py +++ b/tests/test_multi_query_errors.py @@ -3,7 +3,6 @@ from typing import List from dirty_equals import IsDict from fastapi import FastAPI, Query from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url app = FastAPI() @@ -33,14 +32,12 @@ def test_multi_query_incorrect(): "loc": ["query", "q", 0], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "five", - "url": match_pydantic_error_url("int_parsing"), }, { "type": "int_parsing", "loc": ["query", "q", 1], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "six", - "url": match_pydantic_error_url("int_parsing"), }, ] } diff --git a/tests/test_multipart_installation.py b/tests/test_multipart_installation.py index 788d9ef5a..9c3e47c49 100644 --- a/tests/test_multipart_installation.py +++ b/tests/test_multipart_installation.py @@ -1,3 +1,5 @@ +import warnings + import pytest from fastapi import FastAPI, File, Form, UploadFile from fastapi.dependencies.utils import ( @@ -7,7 +9,10 @@ from fastapi.dependencies.utils import ( def test_incorrect_multipart_installed_form(monkeypatch): - monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) + monkeypatch.setattr("python_multipart.__version__", "0.0.12") + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) with pytest.raises(RuntimeError, match=multipart_incorrect_install_error): app = FastAPI() @@ -17,7 +22,10 @@ def test_incorrect_multipart_installed_form(monkeypatch): def test_incorrect_multipart_installed_file_upload(monkeypatch): - monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) + monkeypatch.setattr("python_multipart.__version__", "0.0.12") + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) with pytest.raises(RuntimeError, match=multipart_incorrect_install_error): app = FastAPI() @@ -27,7 +35,10 @@ def test_incorrect_multipart_installed_file_upload(monkeypatch): def test_incorrect_multipart_installed_file_bytes(monkeypatch): - monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) + monkeypatch.setattr("python_multipart.__version__", "0.0.12") + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) with pytest.raises(RuntimeError, match=multipart_incorrect_install_error): app = FastAPI() @@ -37,7 +48,10 @@ def test_incorrect_multipart_installed_file_bytes(monkeypatch): def test_incorrect_multipart_installed_multi_form(monkeypatch): - monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) + monkeypatch.setattr("python_multipart.__version__", "0.0.12") + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) with pytest.raises(RuntimeError, match=multipart_incorrect_install_error): app = FastAPI() @@ -47,7 +61,10 @@ def test_incorrect_multipart_installed_multi_form(monkeypatch): def test_incorrect_multipart_installed_form_file(monkeypatch): - monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) + monkeypatch.setattr("python_multipart.__version__", "0.0.12") + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + monkeypatch.delattr("multipart.multipart.parse_options_header", raising=False) with pytest.raises(RuntimeError, match=multipart_incorrect_install_error): app = FastAPI() @@ -57,50 +74,76 @@ def test_incorrect_multipart_installed_form_file(monkeypatch): def test_no_multipart_installed(monkeypatch): - monkeypatch.delattr("multipart.__version__", raising=False) - with pytest.raises(RuntimeError, match=multipart_not_installed_error): - app = FastAPI() + monkeypatch.setattr("python_multipart.__version__", "0.0.12") + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + monkeypatch.delattr("multipart.__version__", raising=False) + with pytest.raises(RuntimeError, match=multipart_not_installed_error): + app = FastAPI() - @app.post("/") - async def root(username: str = Form()): - return username # pragma: nocover + @app.post("/") + async def root(username: str = Form()): + return username # pragma: nocover def test_no_multipart_installed_file(monkeypatch): - monkeypatch.delattr("multipart.__version__", raising=False) - with pytest.raises(RuntimeError, match=multipart_not_installed_error): - app = FastAPI() + monkeypatch.setattr("python_multipart.__version__", "0.0.12") + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + monkeypatch.delattr("multipart.__version__", raising=False) + with pytest.raises(RuntimeError, match=multipart_not_installed_error): + app = FastAPI() - @app.post("/") - async def root(f: UploadFile = File()): - return f # pragma: nocover + @app.post("/") + async def root(f: UploadFile = File()): + return f # pragma: nocover def test_no_multipart_installed_file_bytes(monkeypatch): - monkeypatch.delattr("multipart.__version__", raising=False) - with pytest.raises(RuntimeError, match=multipart_not_installed_error): - app = FastAPI() + monkeypatch.setattr("python_multipart.__version__", "0.0.12") + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + monkeypatch.delattr("multipart.__version__", raising=False) + with pytest.raises(RuntimeError, match=multipart_not_installed_error): + app = FastAPI() - @app.post("/") - async def root(f: bytes = File()): - return f # pragma: nocover + @app.post("/") + async def root(f: bytes = File()): + return f # pragma: nocover def test_no_multipart_installed_multi_form(monkeypatch): - monkeypatch.delattr("multipart.__version__", raising=False) - with pytest.raises(RuntimeError, match=multipart_not_installed_error): - app = FastAPI() + monkeypatch.setattr("python_multipart.__version__", "0.0.12") + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + monkeypatch.delattr("multipart.__version__", raising=False) + with pytest.raises(RuntimeError, match=multipart_not_installed_error): + app = FastAPI() - @app.post("/") - async def root(username: str = Form(), password: str = Form()): - return username # pragma: nocover + @app.post("/") + async def root(username: str = Form(), password: str = Form()): + return username # pragma: nocover def test_no_multipart_installed_form_file(monkeypatch): - monkeypatch.delattr("multipart.__version__", raising=False) - with pytest.raises(RuntimeError, match=multipart_not_installed_error): + monkeypatch.setattr("python_multipart.__version__", "0.0.12") + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + monkeypatch.delattr("multipart.__version__", raising=False) + with pytest.raises(RuntimeError, match=multipart_not_installed_error): + app = FastAPI() + + @app.post("/") + async def root(username: str = Form(), f: UploadFile = File()): + return username # pragma: nocover + + +def test_old_multipart_installed(monkeypatch): + monkeypatch.setattr("python_multipart.__version__", "0.0.12") + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") app = FastAPI() @app.post("/") - async def root(username: str = Form(), f: UploadFile = File()): + async def root(username: str = Form()): return username # pragma: nocover diff --git a/tests/test_openapi_examples.py b/tests/test_openapi_examples.py index 6597e5058..b3f83ae23 100644 --- a/tests/test_openapi_examples.py +++ b/tests/test_openapi_examples.py @@ -155,13 +155,26 @@ def test_openapi_schema(): "requestBody": { "content": { "application/json": { - "schema": { - "allOf": [{"$ref": "#/components/schemas/Item"}], - "title": "Item", - "examples": [ - {"data": "Data in Body examples, example1"} - ], - }, + "schema": IsDict( + { + "$ref": "#/components/schemas/Item", + "examples": [ + {"data": "Data in Body examples, example1"} + ], + } + ) + | IsDict( + { + # TODO: remove when deprecating Pydantic v1 + "allOf": [ + {"$ref": "#/components/schemas/Item"} + ], + "title": "Item", + "examples": [ + {"data": "Data in Body examples, example1"} + ], + } + ), "examples": { "Example One": { "summary": "Example One Summary", diff --git a/tests/test_openapi_separate_input_output_schemas.py b/tests/test_openapi_separate_input_output_schemas.py index aeb85f735..f7e045259 100644 --- a/tests/test_openapi_separate_input_output_schemas.py +++ b/tests/test_openapi_separate_input_output_schemas.py @@ -26,8 +26,8 @@ class Item(BaseModel): def get_app_client(separate_input_output_schemas: bool = True) -> TestClient: app = FastAPI(separate_input_output_schemas=separate_input_output_schemas) - @app.post("/items/") - def create_item(item: Item): + @app.post("/items/", responses={402: {"model": Item}}) + def create_item(item: Item) -> Item: return item @app.post("/items-list/") @@ -174,7 +174,23 @@ def test_openapi_schema(): "responses": { "200": { "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Item-Output" + } + } + }, + }, + "402": { + "description": "Payment Required", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Item-Output" + } + } + }, }, "422": { "description": "Validation Error", @@ -374,7 +390,19 @@ def test_openapi_schema_no_separate(): "responses": { "200": { "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, + }, + "402": { + "description": "Payment Required", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Item"} + } + }, }, "422": { "description": "Validation Error", diff --git a/tests/test_param_include_in_schema.py b/tests/test_param_include_in_schema.py index 26201e9e2..f461947c9 100644 --- a/tests/test_param_include_in_schema.py +++ b/tests/test_param_include_in_schema.py @@ -9,14 +9,14 @@ app = FastAPI() @app.get("/hidden_cookie") async def hidden_cookie( - hidden_cookie: Optional[str] = Cookie(default=None, include_in_schema=False) + hidden_cookie: Optional[str] = Cookie(default=None, include_in_schema=False), ): return {"hidden_cookie": hidden_cookie} @app.get("/hidden_header") async def hidden_header( - hidden_header: Optional[str] = Header(default=None, include_in_schema=False) + hidden_header: Optional[str] = Header(default=None, include_in_schema=False), ): return {"hidden_header": hidden_header} @@ -28,7 +28,7 @@ async def hidden_path(hidden_path: str = Path(include_in_schema=False)): @app.get("/hidden_query") async def hidden_query( - hidden_query: Optional[str] = Query(default=None, include_in_schema=False) + hidden_query: Optional[str] = Query(default=None, include_in_schema=False), ): return {"hidden_query": hidden_query} diff --git a/tests/test_path.py b/tests/test_path.py index 848b245e2..09c1f13fb 100644 --- a/tests/test_path.py +++ b/tests/test_path.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from .main import app @@ -54,7 +53,6 @@ def test_path_int_foobar(): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "foobar", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -83,7 +81,6 @@ def test_path_int_True(): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "True", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -118,7 +115,6 @@ def test_path_int_42_5(): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "42.5", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -147,7 +143,6 @@ def test_path_float_foobar(): "loc": ["path", "item_id"], "msg": "Input should be a valid number, unable to parse string as a number", "input": "foobar", - "url": match_pydantic_error_url("float_parsing"), } ] } @@ -176,7 +171,6 @@ def test_path_float_True(): "loc": ["path", "item_id"], "msg": "Input should be a valid number, unable to parse string as a number", "input": "True", - "url": match_pydantic_error_url("float_parsing"), } ] } @@ -217,7 +211,6 @@ def test_path_bool_foobar(): "loc": ["path", "item_id"], "msg": "Input should be a valid boolean, unable to interpret input", "input": "foobar", - "url": match_pydantic_error_url("bool_parsing"), } ] } @@ -252,7 +245,6 @@ def test_path_bool_42(): "loc": ["path", "item_id"], "msg": "Input should be a valid boolean, unable to interpret input", "input": "42", - "url": match_pydantic_error_url("bool_parsing"), } ] } @@ -281,7 +273,6 @@ def test_path_bool_42_5(): "loc": ["path", "item_id"], "msg": "Input should be a valid boolean, unable to interpret input", "input": "42.5", - "url": match_pydantic_error_url("bool_parsing"), } ] } @@ -353,7 +344,6 @@ def test_path_param_minlength_fo(): "msg": "String should have at least 3 characters", "input": "fo", "ctx": {"min_length": 3}, - "url": match_pydantic_error_url("string_too_short"), } ] } @@ -390,7 +380,6 @@ def test_path_param_maxlength_foobar(): "msg": "String should have at most 3 characters", "input": "foobar", "ctx": {"max_length": 3}, - "url": match_pydantic_error_url("string_too_long"), } ] } @@ -427,7 +416,6 @@ def test_path_param_min_maxlength_foobar(): "msg": "String should have at most 3 characters", "input": "foobar", "ctx": {"max_length": 3}, - "url": match_pydantic_error_url("string_too_long"), } ] } @@ -458,7 +446,6 @@ def test_path_param_min_maxlength_f(): "msg": "String should have at least 2 characters", "input": "f", "ctx": {"min_length": 2}, - "url": match_pydantic_error_url("string_too_short"), } ] } @@ -494,7 +481,6 @@ def test_path_param_gt_2(): "msg": "Input should be greater than 3", "input": "2", "ctx": {"gt": 3.0}, - "url": match_pydantic_error_url("greater_than"), } ] } @@ -531,7 +517,6 @@ def test_path_param_gt0_0(): "msg": "Input should be greater than 0", "input": "0", "ctx": {"gt": 0.0}, - "url": match_pydantic_error_url("greater_than"), } ] } @@ -574,7 +559,6 @@ def test_path_param_ge_2(): "msg": "Input should be greater than or equal to 3", "input": "2", "ctx": {"ge": 3.0}, - "url": match_pydantic_error_url("greater_than_equal"), } ] } @@ -605,7 +589,6 @@ def test_path_param_lt_42(): "msg": "Input should be less than 3", "input": "42", "ctx": {"lt": 3.0}, - "url": match_pydantic_error_url("less_than"), } ] } @@ -648,7 +631,6 @@ def test_path_param_lt0_0(): "msg": "Input should be less than 0", "input": "0", "ctx": {"lt": 0.0}, - "url": match_pydantic_error_url("less_than"), } ] } @@ -679,7 +661,6 @@ def test_path_param_le_42(): "msg": "Input should be less than or equal to 3", "input": "42", "ctx": {"le": 3.0}, - "url": match_pydantic_error_url("less_than_equal"), } ] } @@ -728,7 +709,6 @@ def test_path_param_lt_gt_4(): "msg": "Input should be less than 3", "input": "4", "ctx": {"lt": 3.0}, - "url": match_pydantic_error_url("less_than"), } ] } @@ -759,7 +739,6 @@ def test_path_param_lt_gt_0(): "msg": "Input should be greater than 1", "input": "0", "ctx": {"gt": 1.0}, - "url": match_pydantic_error_url("greater_than"), } ] } @@ -807,7 +786,6 @@ def test_path_param_le_ge_4(): "msg": "Input should be less than or equal to 3", "input": "4", "ctx": {"le": 3.0}, - "url": match_pydantic_error_url("less_than_equal"), } ] } @@ -844,7 +822,6 @@ def test_path_param_lt_int_42(): "msg": "Input should be less than 3", "input": "42", "ctx": {"lt": 3}, - "url": match_pydantic_error_url("less_than"), } ] } @@ -874,7 +851,6 @@ def test_path_param_lt_int_2_7(): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "2.7", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -910,7 +886,6 @@ def test_path_param_gt_int_2(): "msg": "Input should be greater than 3", "input": "2", "ctx": {"gt": 3}, - "url": match_pydantic_error_url("greater_than"), } ] } @@ -940,7 +915,6 @@ def test_path_param_gt_int_2_7(): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "2.7", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -970,7 +944,6 @@ def test_path_param_le_int_42(): "msg": "Input should be less than or equal to 3", "input": "42", "ctx": {"le": 3}, - "url": match_pydantic_error_url("less_than_equal"), } ] } @@ -1012,7 +985,6 @@ def test_path_param_le_int_2_7(): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "2.7", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -1054,7 +1026,6 @@ def test_path_param_ge_int_2(): "msg": "Input should be greater than or equal to 3", "input": "2", "ctx": {"ge": 3}, - "url": match_pydantic_error_url("greater_than_equal"), } ] } @@ -1084,7 +1055,6 @@ def test_path_param_ge_int_2_7(): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "2.7", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -1120,7 +1090,6 @@ def test_path_param_lt_gt_int_4(): "msg": "Input should be less than 3", "input": "4", "ctx": {"lt": 3}, - "url": match_pydantic_error_url("less_than"), } ] } @@ -1151,7 +1120,6 @@ def test_path_param_lt_gt_int_0(): "msg": "Input should be greater than 1", "input": "0", "ctx": {"gt": 1}, - "url": match_pydantic_error_url("greater_than"), } ] } @@ -1181,7 +1149,6 @@ def test_path_param_lt_gt_int_2_7(): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "2.7", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -1229,7 +1196,6 @@ def test_path_param_le_ge_int_4(): "msg": "Input should be less than or equal to 3", "input": "4", "ctx": {"le": 3}, - "url": match_pydantic_error_url("less_than_equal"), } ] } @@ -1259,7 +1225,6 @@ def test_path_param_le_ge_int_2_7(): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "2.7", - "url": match_pydantic_error_url("int_parsing"), } ] } diff --git a/tests/test_query.py b/tests/test_query.py index 5bb9995d6..57f551d2a 100644 --- a/tests/test_query.py +++ b/tests/test_query.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from .main import app @@ -18,7 +17,6 @@ def test_query(): "loc": ["query", "query"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -53,7 +51,6 @@ def test_query_not_declared_baz(): "loc": ["query", "query"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -100,7 +97,6 @@ def test_query_int(): "loc": ["query", "query"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -135,7 +131,6 @@ def test_query_int_query_42_5(): "loc": ["query", "query"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "42.5", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -164,7 +159,6 @@ def test_query_int_query_baz(): "loc": ["query", "query"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "baz", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -193,7 +187,6 @@ def test_query_int_not_declared_baz(): "loc": ["query", "query"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -234,7 +227,6 @@ def test_query_int_optional_query_foo(): "loc": ["query", "query"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "foo", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -275,7 +267,6 @@ def test_query_int_default_query_foo(): "loc": ["query", "query"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "foo", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -316,7 +307,6 @@ def test_query_param_required(): "loc": ["query", "query"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -351,7 +341,6 @@ def test_query_param_required_int(): "loc": ["query", "query"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -386,7 +375,6 @@ def test_query_param_required_int_query_foo(): "loc": ["query", "query"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "foo", - "url": match_pydantic_error_url("int_parsing"), } ] } @@ -408,3 +396,26 @@ def test_query_frozenset_query_1_query_1_query_2(): response = client.get("/query/frozenset/?query=1&query=1&query=2") assert response.status_code == 200 assert response.json() == "1,2" + + +def test_query_list(): + response = client.get("/query/list/?device_ids=1&device_ids=2") + assert response.status_code == 200 + assert response.json() == [1, 2] + + +def test_query_list_empty(): + response = client.get("/query/list/") + assert response.status_code == 422 + + +def test_query_list_default(): + response = client.get("/query/list-default/?device_ids=1&device_ids=2") + assert response.status_code == 200 + assert response.json() == [1, 2] + + +def test_query_list_default_empty(): + response = client.get("/query/list-default/") + assert response.status_code == 200 + assert response.json() == [] diff --git a/tests/test_regex_deprecated_body.py b/tests/test_regex_deprecated_body.py index ca1ab514c..74654ff3c 100644 --- a/tests/test_regex_deprecated_body.py +++ b/tests/test_regex_deprecated_body.py @@ -2,7 +2,6 @@ import pytest from dirty_equals import IsDict from fastapi import FastAPI, Form from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from typing_extensions import Annotated from .utils import needs_py310 @@ -14,7 +13,7 @@ def get_client(): @app.post("/items/") async def read_items( - q: Annotated[str | None, Form(regex="^fixedquery$")] = None + q: Annotated[str | None, Form(regex="^fixedquery$")] = None, ): if q: return f"Hello {q}" @@ -55,7 +54,6 @@ def test_query_nonregexquery(): "msg": "String should match pattern '^fixedquery$'", "input": "nonregexquery", "ctx": {"pattern": "^fixedquery$"}, - "url": match_pydantic_error_url("string_pattern_mismatch"), } ] } diff --git a/tests/test_regex_deprecated_params.py b/tests/test_regex_deprecated_params.py index 79a653353..2ce64c686 100644 --- a/tests/test_regex_deprecated_params.py +++ b/tests/test_regex_deprecated_params.py @@ -2,7 +2,6 @@ import pytest from dirty_equals import IsDict from fastapi import FastAPI, Query from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from typing_extensions import Annotated from .utils import needs_py310 @@ -14,7 +13,7 @@ def get_client(): @app.get("/items/") async def read_items( - q: Annotated[str | None, Query(regex="^fixedquery$")] = None + q: Annotated[str | None, Query(regex="^fixedquery$")] = None, ): if q: return f"Hello {q}" @@ -55,7 +54,6 @@ def test_query_params_str_validations_item_query_nonregexquery(): "msg": "String should match pattern '^fixedquery$'", "input": "nonregexquery", "ctx": {"pattern": "^fixedquery$"}, - "url": match_pydantic_error_url("string_pattern_mismatch"), } ] } diff --git a/tests/test_router_events.py b/tests/test_router_events.py index 1b9de18ae..dd7ff3314 100644 --- a/tests/test_router_events.py +++ b/tests/test_router_events.py @@ -1,8 +1,8 @@ from contextlib import asynccontextmanager -from typing import AsyncGenerator, Dict +from typing import AsyncGenerator, Dict, Union import pytest -from fastapi import APIRouter, FastAPI +from fastapi import APIRouter, FastAPI, Request from fastapi.testclient import TestClient from pydantic import BaseModel @@ -109,3 +109,134 @@ def test_app_lifespan_state(state: State) -> None: assert response.json() == {"message": "Hello World"} assert state.app_startup is True assert state.app_shutdown is True + + +def test_router_nested_lifespan_state(state: State) -> None: + @asynccontextmanager + async def lifespan(app: FastAPI) -> AsyncGenerator[Dict[str, bool], None]: + state.app_startup = True + yield {"app": True} + state.app_shutdown = True + + @asynccontextmanager + async def router_lifespan(app: FastAPI) -> AsyncGenerator[Dict[str, bool], None]: + state.router_startup = True + yield {"router": True} + state.router_shutdown = True + + @asynccontextmanager + async def subrouter_lifespan(app: FastAPI) -> AsyncGenerator[Dict[str, bool], None]: + state.sub_router_startup = True + yield {"sub_router": True} + state.sub_router_shutdown = True + + sub_router = APIRouter(lifespan=subrouter_lifespan) + + router = APIRouter(lifespan=router_lifespan) + router.include_router(sub_router) + + app = FastAPI(lifespan=lifespan) + app.include_router(router) + + @app.get("/") + def main(request: Request) -> Dict[str, str]: + assert request.state.app + assert request.state.router + assert request.state.sub_router + return {"message": "Hello World"} + + assert state.app_startup is False + assert state.router_startup is False + assert state.sub_router_startup is False + assert state.app_shutdown is False + assert state.router_shutdown is False + assert state.sub_router_shutdown is False + + with TestClient(app) as client: + assert state.app_startup is True + assert state.router_startup is True + assert state.sub_router_startup is True + assert state.app_shutdown is False + assert state.router_shutdown is False + assert state.sub_router_shutdown is False + response = client.get("/") + assert response.status_code == 200, response.text + assert response.json() == {"message": "Hello World"} + + assert state.app_startup is True + assert state.router_startup is True + assert state.sub_router_startup is True + assert state.app_shutdown is True + assert state.router_shutdown is True + assert state.sub_router_shutdown is True + + +def test_router_nested_lifespan_state_overriding_by_parent() -> None: + @asynccontextmanager + async def lifespan( + app: FastAPI, + ) -> AsyncGenerator[Dict[str, Union[str, bool]], None]: + yield { + "app_specific": True, + "overridden": "app", + } + + @asynccontextmanager + async def router_lifespan( + app: FastAPI, + ) -> AsyncGenerator[Dict[str, Union[str, bool]], None]: + yield { + "router_specific": True, + "overridden": "router", # should override parent + } + + router = APIRouter(lifespan=router_lifespan) + app = FastAPI(lifespan=lifespan) + app.include_router(router) + + with TestClient(app) as client: + assert client.app_state == { + "app_specific": True, + "router_specific": True, + "overridden": "app", + } + + +def test_merged_no_return_lifespans_return_none() -> None: + @asynccontextmanager + async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]: + yield + + @asynccontextmanager + async def router_lifespan(app: FastAPI) -> AsyncGenerator[None, None]: + yield + + router = APIRouter(lifespan=router_lifespan) + app = FastAPI(lifespan=lifespan) + app.include_router(router) + + with TestClient(app) as client: + assert not client.app_state + + +def test_merged_mixed_state_lifespans() -> None: + @asynccontextmanager + async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]: + yield + + @asynccontextmanager + async def router_lifespan(app: FastAPI) -> AsyncGenerator[Dict[str, bool], None]: + yield {"router": True} + + @asynccontextmanager + async def sub_router_lifespan(app: FastAPI) -> AsyncGenerator[None, None]: + yield + + sub_router = APIRouter(lifespan=sub_router_lifespan) + router = APIRouter(lifespan=router_lifespan) + app = FastAPI(lifespan=lifespan) + router.include_router(sub_router) + app.include_router(router) + + with TestClient(app) as client: + assert client.app_state == {"router": True} diff --git a/tests/test_security_http_digest_optional.py b/tests/test_security_http_digest_optional.py index 1e6eb8bd7..0d66f9c72 100644 --- a/tests/test_security_http_digest_optional.py +++ b/tests/test_security_http_digest_optional.py @@ -37,8 +37,8 @@ def test_security_http_digest_incorrect_scheme_credentials(): response = client.get( "/users/me", headers={"Authorization": "Other invalidauthorization"} ) - assert response.status_code == 403, response.text - assert response.json() == {"detail": "Invalid authentication credentials"} + assert response.status_code == 200, response.text + assert response.json() == {"msg": "Create an account first"} def test_openapi_schema(): diff --git a/tests/test_security_oauth2.py b/tests/test_security_oauth2.py index e98f80ebf..2b7e3457a 100644 --- a/tests/test_security_oauth2.py +++ b/tests/test_security_oauth2.py @@ -1,8 +1,8 @@ +import pytest from dirty_equals import IsDict from fastapi import Depends, FastAPI, Security from fastapi.security import OAuth2, OAuth2PasswordRequestFormStrict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from pydantic import BaseModel app = FastAPI() @@ -71,21 +71,18 @@ def test_strict_login_no_data(): "loc": ["body", "grant_type"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "username"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "password"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -124,7 +121,6 @@ def test_strict_login_no_grant_type(): "loc": ["body", "grant_type"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -142,10 +138,18 @@ def test_strict_login_no_grant_type(): ) -def test_strict_login_incorrect_grant_type(): +@pytest.mark.parametrize( + argnames=["grant_type"], + argvalues=[ + pytest.param("incorrect", id="incorrect value"), + pytest.param("passwordblah", id="password with suffix"), + pytest.param("blahpassword", id="password with prefix"), + ], +) +def test_strict_login_incorrect_grant_type(grant_type: str): response = client.post( "/login", - data={"username": "johndoe", "password": "secret", "grant_type": "incorrect"}, + data={"username": "johndoe", "password": "secret", "grant_type": grant_type}, ) assert response.status_code == 422 assert response.json() == IsDict( @@ -154,10 +158,9 @@ def test_strict_login_incorrect_grant_type(): { "type": "string_pattern_mismatch", "loc": ["body", "grant_type"], - "msg": "String should match pattern 'password'", - "input": "incorrect", - "ctx": {"pattern": "password"}, - "url": match_pydantic_error_url("string_pattern_mismatch"), + "msg": "String should match pattern '^password$'", + "input": grant_type, + "ctx": {"pattern": "^password$"}, } ] } @@ -167,9 +170,9 @@ def test_strict_login_incorrect_grant_type(): "detail": [ { "loc": ["body", "grant_type"], - "msg": 'string does not match regex "password"', + "msg": 'string does not match regex "^password$"', "type": "value_error.str.regex", - "ctx": {"pattern": "password"}, + "ctx": {"pattern": "^password$"}, } ] } @@ -254,7 +257,7 @@ def test_openapi_schema(): "properties": { "grant_type": { "title": "Grant Type", - "pattern": "password", + "pattern": "^password$", "type": "string", }, "username": {"title": "Username", "type": "string"}, diff --git a/tests/test_security_oauth2_optional.py b/tests/test_security_oauth2_optional.py index d06c01bba..046ac5763 100644 --- a/tests/test_security_oauth2_optional.py +++ b/tests/test_security_oauth2_optional.py @@ -1,10 +1,10 @@ from typing import Optional +import pytest from dirty_equals import IsDict from fastapi import Depends, FastAPI, Security from fastapi.security import OAuth2, OAuth2PasswordRequestFormStrict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from pydantic import BaseModel app = FastAPI() @@ -75,21 +75,18 @@ def test_strict_login_no_data(): "loc": ["body", "grant_type"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "username"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "password"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -128,7 +125,6 @@ def test_strict_login_no_grant_type(): "loc": ["body", "grant_type"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -146,10 +142,18 @@ def test_strict_login_no_grant_type(): ) -def test_strict_login_incorrect_grant_type(): +@pytest.mark.parametrize( + argnames=["grant_type"], + argvalues=[ + pytest.param("incorrect", id="incorrect value"), + pytest.param("passwordblah", id="password with suffix"), + pytest.param("blahpassword", id="password with prefix"), + ], +) +def test_strict_login_incorrect_grant_type(grant_type: str): response = client.post( "/login", - data={"username": "johndoe", "password": "secret", "grant_type": "incorrect"}, + data={"username": "johndoe", "password": "secret", "grant_type": grant_type}, ) assert response.status_code == 422 assert response.json() == IsDict( @@ -158,10 +162,9 @@ def test_strict_login_incorrect_grant_type(): { "type": "string_pattern_mismatch", "loc": ["body", "grant_type"], - "msg": "String should match pattern 'password'", - "input": "incorrect", - "ctx": {"pattern": "password"}, - "url": match_pydantic_error_url("string_pattern_mismatch"), + "msg": "String should match pattern '^password$'", + "input": grant_type, + "ctx": {"pattern": "^password$"}, } ] } @@ -171,9 +174,9 @@ def test_strict_login_incorrect_grant_type(): "detail": [ { "loc": ["body", "grant_type"], - "msg": 'string does not match regex "password"', + "msg": 'string does not match regex "^password$"', "type": "value_error.str.regex", - "ctx": {"pattern": "password"}, + "ctx": {"pattern": "^password$"}, } ] } @@ -258,7 +261,7 @@ def test_openapi_schema(): "properties": { "grant_type": { "title": "Grant Type", - "pattern": "password", + "pattern": "^password$", "type": "string", }, "username": {"title": "Username", "type": "string"}, diff --git a/tests/test_security_oauth2_optional_description.py b/tests/test_security_oauth2_optional_description.py index 9287e4366..629cddca2 100644 --- a/tests/test_security_oauth2_optional_description.py +++ b/tests/test_security_oauth2_optional_description.py @@ -1,10 +1,10 @@ from typing import Optional +import pytest from dirty_equals import IsDict from fastapi import Depends, FastAPI, Security from fastapi.security import OAuth2, OAuth2PasswordRequestFormStrict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from pydantic import BaseModel app = FastAPI() @@ -76,21 +76,18 @@ def test_strict_login_None(): "loc": ["body", "grant_type"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "username"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "password"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -129,7 +126,6 @@ def test_strict_login_no_grant_type(): "loc": ["body", "grant_type"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -147,10 +143,18 @@ def test_strict_login_no_grant_type(): ) -def test_strict_login_incorrect_grant_type(): +@pytest.mark.parametrize( + argnames=["grant_type"], + argvalues=[ + pytest.param("incorrect", id="incorrect value"), + pytest.param("passwordblah", id="password with suffix"), + pytest.param("blahpassword", id="password with prefix"), + ], +) +def test_strict_login_incorrect_grant_type(grant_type: str): response = client.post( "/login", - data={"username": "johndoe", "password": "secret", "grant_type": "incorrect"}, + data={"username": "johndoe", "password": "secret", "grant_type": grant_type}, ) assert response.status_code == 422 assert response.json() == IsDict( @@ -159,10 +163,9 @@ def test_strict_login_incorrect_grant_type(): { "type": "string_pattern_mismatch", "loc": ["body", "grant_type"], - "msg": "String should match pattern 'password'", - "input": "incorrect", - "ctx": {"pattern": "password"}, - "url": match_pydantic_error_url("string_pattern_mismatch"), + "msg": "String should match pattern '^password$'", + "input": grant_type, + "ctx": {"pattern": "^password$"}, } ] } @@ -172,9 +175,9 @@ def test_strict_login_incorrect_grant_type(): "detail": [ { "loc": ["body", "grant_type"], - "msg": 'string does not match regex "password"', + "msg": 'string does not match regex "^password$"', "type": "value_error.str.regex", - "ctx": {"pattern": "password"}, + "ctx": {"pattern": "^password$"}, } ] } @@ -259,7 +262,7 @@ def test_openapi_schema(): "properties": { "grant_type": { "title": "Grant Type", - "pattern": "password", + "pattern": "^password$", "type": "string", }, "username": {"title": "Username", "type": "string"}, diff --git a/tests/test_tutorial/test_additional_status_codes/test_tutorial001.py b/tests/test_tutorial/test_additional_status_codes/test_tutorial001.py index c382cb5fe..b304f7015 100644 --- a/tests/test_tutorial/test_additional_status_codes/test_tutorial001.py +++ b/tests/test_tutorial/test_additional_status_codes/test_tutorial001.py @@ -1,17 +1,35 @@ +import importlib + +import pytest from fastapi.testclient import TestClient -from docs_src.additional_status_codes.tutorial001 import app +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py310", marks=needs_py310), + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + pytest.param("tutorial001_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.additional_status_codes.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_update(): +def test_update(client: TestClient): response = client.put("/items/foo", json={"name": "Wrestlers"}) assert response.status_code == 200, response.text assert response.json() == {"name": "Wrestlers", "size": None} -def test_create(): +def test_create(client: TestClient): response = client.put("/items/red", json={"name": "Chillies"}) assert response.status_code == 201, response.text assert response.json() == {"name": "Chillies", "size": None} diff --git a/tests/test_tutorial/test_additional_status_codes/test_tutorial001_an.py b/tests/test_tutorial/test_additional_status_codes/test_tutorial001_an.py deleted file mode 100644 index 2cb2bb993..000000000 --- a/tests/test_tutorial/test_additional_status_codes/test_tutorial001_an.py +++ /dev/null @@ -1,17 +0,0 @@ -from fastapi.testclient import TestClient - -from docs_src.additional_status_codes.tutorial001_an import app - -client = TestClient(app) - - -def test_update(): - response = client.put("/items/foo", json={"name": "Wrestlers"}) - assert response.status_code == 200, response.text - assert response.json() == {"name": "Wrestlers", "size": None} - - -def test_create(): - response = client.put("/items/red", json={"name": "Chillies"}) - assert response.status_code == 201, response.text - assert response.json() == {"name": "Chillies", "size": None} diff --git a/tests/test_tutorial/test_additional_status_codes/test_tutorial001_an_py310.py b/tests/test_tutorial/test_additional_status_codes/test_tutorial001_an_py310.py deleted file mode 100644 index c7660a392..000000000 --- a/tests/test_tutorial/test_additional_status_codes/test_tutorial001_an_py310.py +++ /dev/null @@ -1,26 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.additional_status_codes.tutorial001_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_update(client: TestClient): - response = client.put("/items/foo", json={"name": "Wrestlers"}) - assert response.status_code == 200, response.text - assert response.json() == {"name": "Wrestlers", "size": None} - - -@needs_py310 -def test_create(client: TestClient): - response = client.put("/items/red", json={"name": "Chillies"}) - assert response.status_code == 201, response.text - assert response.json() == {"name": "Chillies", "size": None} diff --git a/tests/test_tutorial/test_additional_status_codes/test_tutorial001_an_py39.py b/tests/test_tutorial/test_additional_status_codes/test_tutorial001_an_py39.py deleted file mode 100644 index 303c5dbae..000000000 --- a/tests/test_tutorial/test_additional_status_codes/test_tutorial001_an_py39.py +++ /dev/null @@ -1,26 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.additional_status_codes.tutorial001_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_update(client: TestClient): - response = client.put("/items/foo", json={"name": "Wrestlers"}) - assert response.status_code == 200, response.text - assert response.json() == {"name": "Wrestlers", "size": None} - - -@needs_py39 -def test_create(client: TestClient): - response = client.put("/items/red", json={"name": "Chillies"}) - assert response.status_code == 201, response.text - assert response.json() == {"name": "Chillies", "size": None} diff --git a/tests/test_tutorial/test_additional_status_codes/test_tutorial001_py310.py b/tests/test_tutorial/test_additional_status_codes/test_tutorial001_py310.py deleted file mode 100644 index 02f2e188c..000000000 --- a/tests/test_tutorial/test_additional_status_codes/test_tutorial001_py310.py +++ /dev/null @@ -1,26 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.additional_status_codes.tutorial001_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_update(client: TestClient): - response = client.put("/items/foo", json={"name": "Wrestlers"}) - assert response.status_code == 200, response.text - assert response.json() == {"name": "Wrestlers", "size": None} - - -@needs_py310 -def test_create(client: TestClient): - response = client.put("/items/red", json={"name": "Chillies"}) - assert response.status_code == 201, response.text - assert response.json() == {"name": "Chillies", "size": None} diff --git a/tests/test_tutorial/test_async_sql_databases/__init__.py b/tests/test_tutorial/test_async_sql_databases/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/tests/test_tutorial/test_async_sql_databases/test_tutorial001.py b/tests/test_tutorial/test_async_sql_databases/test_tutorial001.py deleted file mode 100644 index 13568a532..000000000 --- a/tests/test_tutorial/test_async_sql_databases/test_tutorial001.py +++ /dev/null @@ -1,146 +0,0 @@ -import pytest -from fastapi import FastAPI -from fastapi.testclient import TestClient - -from ...utils import needs_pydanticv1 - - -@pytest.fixture(name="app", scope="module") -def get_app(): - with pytest.warns(DeprecationWarning): - from docs_src.async_sql_databases.tutorial001 import app - yield app - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_create_read(app: FastAPI): - with TestClient(app) as client: - note = {"text": "Foo bar", "completed": False} - response = client.post("/notes/", json=note) - assert response.status_code == 200, response.text - data = response.json() - assert data["text"] == note["text"] - assert data["completed"] == note["completed"] - assert "id" in data - response = client.get("/notes/") - assert response.status_code == 200, response.text - assert data in response.json() - - -def test_openapi_schema(app: FastAPI): - with TestClient(app) as client: - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/notes/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Notes Notes Get", - "type": "array", - "items": { - "$ref": "#/components/schemas/Note" - }, - } - } - }, - } - }, - "summary": "Read Notes", - "operationId": "read_notes_notes__get", - }, - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Note"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Note", - "operationId": "create_note_notes__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/NoteIn"} - } - }, - "required": True, - }, - }, - } - }, - "components": { - "schemas": { - "NoteIn": { - "title": "NoteIn", - "required": ["text", "completed"], - "type": "object", - "properties": { - "text": {"title": "Text", "type": "string"}, - "completed": {"title": "Completed", "type": "boolean"}, - }, - }, - "Note": { - "title": "Note", - "required": ["id", "text", "completed"], - "type": "object", - "properties": { - "id": {"title": "Id", "type": "integer"}, - "text": {"title": "Text", "type": "string"}, - "completed": {"title": "Completed", "type": "boolean"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": { - "$ref": "#/components/schemas/ValidationError" - }, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_background_tasks/test_tutorial002.py b/tests/test_tutorial/test_background_tasks/test_tutorial002.py index 74de1314b..d5ef51ee2 100644 --- a/tests/test_tutorial/test_background_tasks/test_tutorial002.py +++ b/tests/test_tutorial/test_background_tasks/test_tutorial002.py @@ -1,14 +1,31 @@ +import importlib import os from pathlib import Path +import pytest from fastapi.testclient import TestClient -from docs_src.background_tasks.tutorial002 import app +from ...utils import needs_py39, needs_py310 -client = TestClient(app) +@pytest.fixture( + name="client", + params=[ + "tutorial002", + pytest.param("tutorial002_py310", marks=needs_py310), + "tutorial002_an", + pytest.param("tutorial002_an_py39", marks=needs_py39), + pytest.param("tutorial002_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.background_tasks.{request.param}") -def test(): + client = TestClient(mod.app) + return client + + +def test(client: TestClient): log = Path("log.txt") if log.is_file(): os.remove(log) # pragma: no cover diff --git a/tests/test_tutorial/test_background_tasks/test_tutorial002_an.py b/tests/test_tutorial/test_background_tasks/test_tutorial002_an.py deleted file mode 100644 index af682ecff..000000000 --- a/tests/test_tutorial/test_background_tasks/test_tutorial002_an.py +++ /dev/null @@ -1,19 +0,0 @@ -import os -from pathlib import Path - -from fastapi.testclient import TestClient - -from docs_src.background_tasks.tutorial002_an import app - -client = TestClient(app) - - -def test(): - log = Path("log.txt") - if log.is_file(): - os.remove(log) # pragma: no cover - response = client.post("/send-notification/foo@example.com?q=some-query") - assert response.status_code == 200, response.text - assert response.json() == {"message": "Message sent"} - with open("./log.txt") as f: - assert "found query: some-query\nmessage to foo@example.com" in f.read() diff --git a/tests/test_tutorial/test_background_tasks/test_tutorial002_an_py310.py b/tests/test_tutorial/test_background_tasks/test_tutorial002_an_py310.py deleted file mode 100644 index 067b2787e..000000000 --- a/tests/test_tutorial/test_background_tasks/test_tutorial002_an_py310.py +++ /dev/null @@ -1,21 +0,0 @@ -import os -from pathlib import Path - -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@needs_py310 -def test(): - from docs_src.background_tasks.tutorial002_an_py310 import app - - client = TestClient(app) - log = Path("log.txt") - if log.is_file(): - os.remove(log) # pragma: no cover - response = client.post("/send-notification/foo@example.com?q=some-query") - assert response.status_code == 200, response.text - assert response.json() == {"message": "Message sent"} - with open("./log.txt") as f: - assert "found query: some-query\nmessage to foo@example.com" in f.read() diff --git a/tests/test_tutorial/test_background_tasks/test_tutorial002_an_py39.py b/tests/test_tutorial/test_background_tasks/test_tutorial002_an_py39.py deleted file mode 100644 index 06b5a2f57..000000000 --- a/tests/test_tutorial/test_background_tasks/test_tutorial002_an_py39.py +++ /dev/null @@ -1,21 +0,0 @@ -import os -from pathlib import Path - -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@needs_py39 -def test(): - from docs_src.background_tasks.tutorial002_an_py39 import app - - client = TestClient(app) - log = Path("log.txt") - if log.is_file(): - os.remove(log) # pragma: no cover - response = client.post("/send-notification/foo@example.com?q=some-query") - assert response.status_code == 200, response.text - assert response.json() == {"message": "Message sent"} - with open("./log.txt") as f: - assert "found query: some-query\nmessage to foo@example.com" in f.read() diff --git a/tests/test_tutorial/test_background_tasks/test_tutorial002_py310.py b/tests/test_tutorial/test_background_tasks/test_tutorial002_py310.py deleted file mode 100644 index 6937c8fab..000000000 --- a/tests/test_tutorial/test_background_tasks/test_tutorial002_py310.py +++ /dev/null @@ -1,21 +0,0 @@ -import os -from pathlib import Path - -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@needs_py310 -def test(): - from docs_src.background_tasks.tutorial002_py310 import app - - client = TestClient(app) - log = Path("log.txt") - if log.is_file(): - os.remove(log) # pragma: no cover - response = client.post("/send-notification/foo@example.com?q=some-query") - assert response.status_code == 200, response.text - assert response.json() == {"message": "Message sent"} - with open("./log.txt") as f: - assert "found query: some-query\nmessage to foo@example.com" in f.read() diff --git a/tests/test_tutorial/test_bigger_applications/test_main.py b/tests/test_tutorial/test_bigger_applications/test_main.py index 526e265a6..fe40fad7d 100644 --- a/tests/test_tutorial/test_bigger_applications/test_main.py +++ b/tests/test_tutorial/test_bigger_applications/test_main.py @@ -1,14 +1,24 @@ +import importlib + import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url + +from ...utils import needs_py39 -@pytest.fixture(name="client") -def get_client(): - from docs_src.bigger_applications.app.main import app +@pytest.fixture( + name="client", + params=[ + "app_an.main", + pytest.param("app_an_py39.main", marks=needs_py39), + "app.main", + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.bigger_applications.{request.param}") - client = TestClient(app) + client = TestClient(mod.app) return client @@ -29,7 +39,6 @@ def test_users_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -64,7 +73,6 @@ def test_users_foo_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -99,7 +107,6 @@ def test_users_me_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -145,7 +152,6 @@ def test_items_with_no_token_jessica(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -192,7 +198,6 @@ def test_items_plumbus_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -233,7 +238,6 @@ def test_items_with_missing_x_token_header(client: TestClient): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -262,7 +266,6 @@ def test_items_plumbus_with_missing_x_token_header(client: TestClient): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -297,7 +300,6 @@ def test_root_with_no_token(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -326,14 +328,12 @@ def test_put_no_header(client: TestClient): "loc": ["query", "token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_bigger_applications/test_main_an.py b/tests/test_tutorial/test_bigger_applications/test_main_an.py deleted file mode 100644 index c0b77d4a7..000000000 --- a/tests/test_tutorial/test_bigger_applications/test_main_an.py +++ /dev/null @@ -1,726 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.bigger_applications.app_an.main import app - - client = TestClient(app) - return client - - -def test_users_token_jessica(client: TestClient): - response = client.get("/users?token=jessica") - assert response.status_code == 200 - assert response.json() == [{"username": "Rick"}, {"username": "Morty"}] - - -def test_users_with_no_token(client: TestClient): - response = client.get("/users") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["query", "token"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["query", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_users_foo_token_jessica(client: TestClient): - response = client.get("/users/foo?token=jessica") - assert response.status_code == 200 - assert response.json() == {"username": "foo"} - - -def test_users_foo_with_no_token(client: TestClient): - response = client.get("/users/foo") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["query", "token"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["query", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_users_me_token_jessica(client: TestClient): - response = client.get("/users/me?token=jessica") - assert response.status_code == 200 - assert response.json() == {"username": "fakecurrentuser"} - - -def test_users_me_with_no_token(client: TestClient): - response = client.get("/users/me") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["query", "token"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["query", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_users_token_monica_with_no_jessica(client: TestClient): - response = client.get("/users?token=monica") - assert response.status_code == 400 - assert response.json() == {"detail": "No Jessica token provided"} - - -def test_items_token_jessica(client: TestClient): - response = client.get( - "/items?token=jessica", headers={"X-Token": "fake-super-secret-token"} - ) - assert response.status_code == 200 - assert response.json() == { - "plumbus": {"name": "Plumbus"}, - "gun": {"name": "Portal Gun"}, - } - - -def test_items_with_no_token_jessica(client: TestClient): - response = client.get("/items", headers={"X-Token": "fake-super-secret-token"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["query", "token"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["query", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_items_plumbus_token_jessica(client: TestClient): - response = client.get( - "/items/plumbus?token=jessica", headers={"X-Token": "fake-super-secret-token"} - ) - assert response.status_code == 200 - assert response.json() == {"name": "Plumbus", "item_id": "plumbus"} - - -def test_items_bar_token_jessica(client: TestClient): - response = client.get( - "/items/bar?token=jessica", headers={"X-Token": "fake-super-secret-token"} - ) - assert response.status_code == 404 - assert response.json() == {"detail": "Item not found"} - - -def test_items_plumbus_with_no_token(client: TestClient): - response = client.get( - "/items/plumbus", headers={"X-Token": "fake-super-secret-token"} - ) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["query", "token"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["query", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_items_with_invalid_token(client: TestClient): - response = client.get("/items?token=jessica", headers={"X-Token": "invalid"}) - assert response.status_code == 400 - assert response.json() == {"detail": "X-Token header invalid"} - - -def test_items_bar_with_invalid_token(client: TestClient): - response = client.get("/items/bar?token=jessica", headers={"X-Token": "invalid"}) - assert response.status_code == 400 - assert response.json() == {"detail": "X-Token header invalid"} - - -def test_items_with_missing_x_token_header(client: TestClient): - response = client.get("/items?token=jessica") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["header", "x-token"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -def test_items_plumbus_with_missing_x_token_header(client: TestClient): - response = client.get("/items/plumbus?token=jessica") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["header", "x-token"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -def test_root_token_jessica(client: TestClient): - response = client.get("/?token=jessica") - assert response.status_code == 200 - assert response.json() == {"message": "Hello Bigger Applications!"} - - -def test_root_with_no_token(client: TestClient): - response = client.get("/") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["query", "token"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["query", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_put_no_header(client: TestClient): - response = client.put("/items/foo") - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["query", "token"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - { - "type": "missing", - "loc": ["header", "x-token"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["query", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_put_invalid_header(client: TestClient): - response = client.put("/items/foo", headers={"X-Token": "invalid"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "X-Token header invalid"} - - -def test_put(client: TestClient): - response = client.put( - "/items/plumbus?token=jessica", headers={"X-Token": "fake-super-secret-token"} - ) - assert response.status_code == 200, response.text - assert response.json() == {"item_id": "plumbus", "name": "The great Plumbus"} - - -def test_put_forbidden(client: TestClient): - response = client.put( - "/items/bar?token=jessica", headers={"X-Token": "fake-super-secret-token"} - ) - assert response.status_code == 403, response.text - assert response.json() == {"detail": "You can only update the item: plumbus"} - - -def test_admin(client: TestClient): - response = client.post( - "/admin/?token=jessica", headers={"X-Token": "fake-super-secret-token"} - ) - assert response.status_code == 200, response.text - assert response.json() == {"message": "Admin getting schwifty"} - - -def test_admin_invalid_header(client: TestClient): - response = client.post("/admin/", headers={"X-Token": "invalid"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "X-Token header invalid"} - - -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/": { - "get": { - "tags": ["users"], - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Token", "type": "string"}, - "name": "token", - "in": "query", - } - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/users/me": { - "get": { - "tags": ["users"], - "summary": "Read User Me", - "operationId": "read_user_me_users_me_get", - "parameters": [ - { - "required": True, - "schema": {"title": "Token", "type": "string"}, - "name": "token", - "in": "query", - } - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/users/{username}": { - "get": { - "tags": ["users"], - "summary": "Read User", - "operationId": "read_user_users__username__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Username", "type": "string"}, - "name": "username", - "in": "path", - }, - { - "required": True, - "schema": {"title": "Token", "type": "string"}, - "name": "token", - "in": "query", - }, - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/items/": { - "get": { - "tags": ["items"], - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Token", "type": "string"}, - "name": "token", - "in": "query", - }, - { - "required": True, - "schema": {"title": "X-Token", "type": "string"}, - "name": "x-token", - "in": "header", - }, - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "404": {"description": "Not found"}, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/items/{item_id}": { - "get": { - "tags": ["items"], - "summary": "Read Item", - "operationId": "read_item_items__item_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - }, - { - "required": True, - "schema": {"title": "Token", "type": "string"}, - "name": "token", - "in": "query", - }, - { - "required": True, - "schema": {"title": "X-Token", "type": "string"}, - "name": "x-token", - "in": "header", - }, - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "404": {"description": "Not found"}, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - }, - "put": { - "tags": ["items", "custom"], - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - }, - { - "required": True, - "schema": {"title": "Token", "type": "string"}, - "name": "token", - "in": "query", - }, - { - "required": True, - "schema": {"title": "X-Token", "type": "string"}, - "name": "x-token", - "in": "header", - }, - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "404": {"description": "Not found"}, - "403": {"description": "Operation forbidden"}, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - }, - }, - "/admin/": { - "post": { - "tags": ["admin"], - "summary": "Update Admin", - "operationId": "update_admin_admin__post", - "parameters": [ - { - "required": True, - "schema": {"title": "Token", "type": "string"}, - "name": "token", - "in": "query", - }, - { - "required": True, - "schema": {"title": "X-Token", "type": "string"}, - "name": "x-token", - "in": "header", - }, - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "418": {"description": "I'm a teapot"}, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/": { - "get": { - "summary": "Root", - "operationId": "root__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Token", "type": "string"}, - "name": "token", - "in": "query", - } - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_bigger_applications/test_main_an_py39.py b/tests/test_tutorial/test_bigger_applications/test_main_an_py39.py deleted file mode 100644 index 948331b5d..000000000 --- a/tests/test_tutorial/test_bigger_applications/test_main_an_py39.py +++ /dev/null @@ -1,753 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.bigger_applications.app_an_py39.main import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_users_token_jessica(client: TestClient): - response = client.get("/users?token=jessica") - assert response.status_code == 200 - assert response.json() == [{"username": "Rick"}, {"username": "Morty"}] - - -@needs_py39 -def test_users_with_no_token(client: TestClient): - response = client.get("/users") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["query", "token"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["query", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_users_foo_token_jessica(client: TestClient): - response = client.get("/users/foo?token=jessica") - assert response.status_code == 200 - assert response.json() == {"username": "foo"} - - -@needs_py39 -def test_users_foo_with_no_token(client: TestClient): - response = client.get("/users/foo") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["query", "token"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["query", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_users_me_token_jessica(client: TestClient): - response = client.get("/users/me?token=jessica") - assert response.status_code == 200 - assert response.json() == {"username": "fakecurrentuser"} - - -@needs_py39 -def test_users_me_with_no_token(client: TestClient): - response = client.get("/users/me") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["query", "token"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["query", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_users_token_monica_with_no_jessica(client: TestClient): - response = client.get("/users?token=monica") - assert response.status_code == 400 - assert response.json() == {"detail": "No Jessica token provided"} - - -@needs_py39 -def test_items_token_jessica(client: TestClient): - response = client.get( - "/items?token=jessica", headers={"X-Token": "fake-super-secret-token"} - ) - assert response.status_code == 200 - assert response.json() == { - "plumbus": {"name": "Plumbus"}, - "gun": {"name": "Portal Gun"}, - } - - -@needs_py39 -def test_items_with_no_token_jessica(client: TestClient): - response = client.get("/items", headers={"X-Token": "fake-super-secret-token"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["query", "token"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["query", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_items_plumbus_token_jessica(client: TestClient): - response = client.get( - "/items/plumbus?token=jessica", headers={"X-Token": "fake-super-secret-token"} - ) - assert response.status_code == 200 - assert response.json() == {"name": "Plumbus", "item_id": "plumbus"} - - -@needs_py39 -def test_items_bar_token_jessica(client: TestClient): - response = client.get( - "/items/bar?token=jessica", headers={"X-Token": "fake-super-secret-token"} - ) - assert response.status_code == 404 - assert response.json() == {"detail": "Item not found"} - - -@needs_py39 -def test_items_plumbus_with_no_token(client: TestClient): - response = client.get( - "/items/plumbus", headers={"X-Token": "fake-super-secret-token"} - ) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["query", "token"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["query", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_items_with_invalid_token(client: TestClient): - response = client.get("/items?token=jessica", headers={"X-Token": "invalid"}) - assert response.status_code == 400 - assert response.json() == {"detail": "X-Token header invalid"} - - -@needs_py39 -def test_items_bar_with_invalid_token(client: TestClient): - response = client.get("/items/bar?token=jessica", headers={"X-Token": "invalid"}) - assert response.status_code == 400 - assert response.json() == {"detail": "X-Token header invalid"} - - -@needs_py39 -def test_items_with_missing_x_token_header(client: TestClient): - response = client.get("/items?token=jessica") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["header", "x-token"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -@needs_py39 -def test_items_plumbus_with_missing_x_token_header(client: TestClient): - response = client.get("/items/plumbus?token=jessica") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["header", "x-token"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -@needs_py39 -def test_root_token_jessica(client: TestClient): - response = client.get("/?token=jessica") - assert response.status_code == 200 - assert response.json() == {"message": "Hello Bigger Applications!"} - - -@needs_py39 -def test_root_with_no_token(client: TestClient): - response = client.get("/") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["query", "token"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["query", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_put_no_header(client: TestClient): - response = client.put("/items/foo") - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["query", "token"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - { - "type": "missing", - "loc": ["header", "x-token"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["query", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_put_invalid_header(client: TestClient): - response = client.put("/items/foo", headers={"X-Token": "invalid"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "X-Token header invalid"} - - -@needs_py39 -def test_put(client: TestClient): - response = client.put( - "/items/plumbus?token=jessica", headers={"X-Token": "fake-super-secret-token"} - ) - assert response.status_code == 200, response.text - assert response.json() == {"item_id": "plumbus", "name": "The great Plumbus"} - - -@needs_py39 -def test_put_forbidden(client: TestClient): - response = client.put( - "/items/bar?token=jessica", headers={"X-Token": "fake-super-secret-token"} - ) - assert response.status_code == 403, response.text - assert response.json() == {"detail": "You can only update the item: plumbus"} - - -@needs_py39 -def test_admin(client: TestClient): - response = client.post( - "/admin/?token=jessica", headers={"X-Token": "fake-super-secret-token"} - ) - assert response.status_code == 200, response.text - assert response.json() == {"message": "Admin getting schwifty"} - - -@needs_py39 -def test_admin_invalid_header(client: TestClient): - response = client.post("/admin/", headers={"X-Token": "invalid"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "X-Token header invalid"} - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/": { - "get": { - "tags": ["users"], - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Token", "type": "string"}, - "name": "token", - "in": "query", - } - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/users/me": { - "get": { - "tags": ["users"], - "summary": "Read User Me", - "operationId": "read_user_me_users_me_get", - "parameters": [ - { - "required": True, - "schema": {"title": "Token", "type": "string"}, - "name": "token", - "in": "query", - } - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/users/{username}": { - "get": { - "tags": ["users"], - "summary": "Read User", - "operationId": "read_user_users__username__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Username", "type": "string"}, - "name": "username", - "in": "path", - }, - { - "required": True, - "schema": {"title": "Token", "type": "string"}, - "name": "token", - "in": "query", - }, - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/items/": { - "get": { - "tags": ["items"], - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Token", "type": "string"}, - "name": "token", - "in": "query", - }, - { - "required": True, - "schema": {"title": "X-Token", "type": "string"}, - "name": "x-token", - "in": "header", - }, - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "404": {"description": "Not found"}, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/items/{item_id}": { - "get": { - "tags": ["items"], - "summary": "Read Item", - "operationId": "read_item_items__item_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - }, - { - "required": True, - "schema": {"title": "Token", "type": "string"}, - "name": "token", - "in": "query", - }, - { - "required": True, - "schema": {"title": "X-Token", "type": "string"}, - "name": "x-token", - "in": "header", - }, - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "404": {"description": "Not found"}, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - }, - "put": { - "tags": ["items", "custom"], - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - }, - { - "required": True, - "schema": {"title": "Token", "type": "string"}, - "name": "token", - "in": "query", - }, - { - "required": True, - "schema": {"title": "X-Token", "type": "string"}, - "name": "x-token", - "in": "header", - }, - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "404": {"description": "Not found"}, - "403": {"description": "Operation forbidden"}, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - }, - }, - "/admin/": { - "post": { - "tags": ["admin"], - "summary": "Update Admin", - "operationId": "update_admin_admin__post", - "parameters": [ - { - "required": True, - "schema": {"title": "Token", "type": "string"}, - "name": "token", - "in": "query", - }, - { - "required": True, - "schema": {"title": "X-Token", "type": "string"}, - "name": "x-token", - "in": "header", - }, - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "418": {"description": "I'm a teapot"}, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/": { - "get": { - "summary": "Root", - "operationId": "root__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Token", "type": "string"}, - "name": "token", - "in": "query", - } - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_body/test_tutorial001.py b/tests/test_tutorial/test_body/test_tutorial001.py index 2476b773f..f8b5aee8d 100644 --- a/tests/test_tutorial/test_body/test_tutorial001.py +++ b/tests/test_tutorial/test_body/test_tutorial001.py @@ -1,16 +1,24 @@ +import importlib from unittest.mock import patch import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url +from ...utils import needs_py310 -@pytest.fixture -def client(): - from docs_src.body.tutorial001 import app - client = TestClient(app) +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.body.{request.param}") + + client = TestClient(mod.app) return client @@ -74,7 +82,6 @@ def test_post_with_only_name(client: TestClient): "loc": ["body", "price"], "msg": "Field required", "input": {"name": "Foo"}, - "url": match_pydantic_error_url("missing"), } ] } @@ -103,7 +110,6 @@ def test_post_with_only_name_price(client: TestClient): "loc": ["body", "price"], "msg": "Input should be a valid number, unable to parse string as a number", "input": "twenty", - "url": match_pydantic_error_url("float_parsing"), } ] } @@ -132,14 +138,12 @@ def test_post_with_no_data(client: TestClient): "loc": ["body", "name"], "msg": "Field required", "input": {}, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "price"], "msg": "Field required", "input": {}, - "url": match_pydantic_error_url("missing"), }, ] } @@ -173,7 +177,6 @@ def test_post_with_none(client: TestClient): "loc": ["body"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -244,7 +247,6 @@ def test_post_form_for_json(client: TestClient): "loc": ["body"], "msg": "Input should be a valid dictionary or object to extract fields from", "input": "name=Foo&price=50.5", - "url": match_pydantic_error_url("model_attributes_type"), } ] } @@ -308,9 +310,6 @@ def test_wrong_headers(client: TestClient): "loc": ["body"], "msg": "Input should be a valid dictionary or object to extract fields from", "input": '{"name": "Foo", "price": 50.5}', - "url": match_pydantic_error_url( - "model_attributes_type" - ), # "https://errors.pydantic.dev/0.38.0/v/dict_attributes_type", } ] } @@ -339,7 +338,6 @@ def test_wrong_headers(client: TestClient): "loc": ["body"], "msg": "Input should be a valid dictionary or object to extract fields from", "input": '{"name": "Foo", "price": 50.5}', - "url": match_pydantic_error_url("model_attributes_type"), } ] } @@ -367,7 +365,6 @@ def test_wrong_headers(client: TestClient): "loc": ["body"], "msg": "Input should be a valid dictionary or object to extract fields from", "input": '{"name": "Foo", "price": 50.5}', - "url": match_pydantic_error_url("model_attributes_type"), } ] } diff --git a/tests/test_tutorial/test_body/test_tutorial001_py310.py b/tests/test_tutorial/test_body/test_tutorial001_py310.py deleted file mode 100644 index b64d86005..000000000 --- a/tests/test_tutorial/test_body/test_tutorial001_py310.py +++ /dev/null @@ -1,508 +0,0 @@ -from unittest.mock import patch - -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url - -from ...utils import needs_py310 - - -@pytest.fixture -def client(): - from docs_src.body.tutorial001_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_body_float(client: TestClient): - response = client.post("/items/", json={"name": "Foo", "price": 50.5}) - assert response.status_code == 200 - assert response.json() == { - "name": "Foo", - "price": 50.5, - "description": None, - "tax": None, - } - - -@needs_py310 -def test_post_with_str_float(client: TestClient): - response = client.post("/items/", json={"name": "Foo", "price": "50.5"}) - assert response.status_code == 200 - assert response.json() == { - "name": "Foo", - "price": 50.5, - "description": None, - "tax": None, - } - - -@needs_py310 -def test_post_with_str_float_description(client: TestClient): - response = client.post( - "/items/", json={"name": "Foo", "price": "50.5", "description": "Some Foo"} - ) - assert response.status_code == 200 - assert response.json() == { - "name": "Foo", - "price": 50.5, - "description": "Some Foo", - "tax": None, - } - - -@needs_py310 -def test_post_with_str_float_description_tax(client: TestClient): - response = client.post( - "/items/", - json={"name": "Foo", "price": "50.5", "description": "Some Foo", "tax": 0.3}, - ) - assert response.status_code == 200 - assert response.json() == { - "name": "Foo", - "price": 50.5, - "description": "Some Foo", - "tax": 0.3, - } - - -@needs_py310 -def test_post_with_only_name(client: TestClient): - response = client.post("/items/", json={"name": "Foo"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "price"], - "msg": "Field required", - "input": {"name": "Foo"}, - "url": match_pydantic_error_url("missing"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "price"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -@needs_py310 -def test_post_with_only_name_price(client: TestClient): - response = client.post("/items/", json={"name": "Foo", "price": "twenty"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "float_parsing", - "loc": ["body", "price"], - "msg": "Input should be a valid number, unable to parse string as a number", - "input": "twenty", - "url": match_pydantic_error_url("float_parsing"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "price"], - "msg": "value is not a valid float", - "type": "type_error.float", - } - ] - } - ) - - -@needs_py310 -def test_post_with_no_data(client: TestClient): - response = client.post("/items/", json={}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "name"], - "msg": "Field required", - "input": {}, - "url": match_pydantic_error_url("missing"), - }, - { - "type": "missing", - "loc": ["body", "price"], - "msg": "Field required", - "input": {}, - "url": match_pydantic_error_url("missing"), - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "name"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "price"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py310 -def test_post_with_none(client: TestClient): - response = client.post("/items/", json=None) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -@needs_py310 -def test_post_broken_body(client: TestClient): - response = client.post( - "/items/", - headers={"content-type": "application/json"}, - content="{some broken json}", - ) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "json_invalid", - "loc": ["body", 1], - "msg": "JSON decode error", - "input": {}, - "ctx": { - "error": "Expecting property name enclosed in double quotes" - }, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", 1], - "msg": "Expecting property name enclosed in double quotes: line 1 column 2 (char 1)", - "type": "value_error.jsondecode", - "ctx": { - "msg": "Expecting property name enclosed in double quotes", - "doc": "{some broken json}", - "pos": 1, - "lineno": 1, - "colno": 2, - }, - } - ] - } - ) - - -@needs_py310 -def test_post_form_for_json(client: TestClient): - response = client.post("/items/", data={"name": "Foo", "price": 50.5}) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "model_attributes_type", - "loc": ["body"], - "msg": "Input should be a valid dictionary or object to extract fields from", - "input": "name=Foo&price=50.5", - "url": match_pydantic_error_url("model_attributes_type"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body"], - "msg": "value is not a valid dict", - "type": "type_error.dict", - } - ] - } - ) - - -@needs_py310 -def test_explicit_content_type(client: TestClient): - response = client.post( - "/items/", - content='{"name": "Foo", "price": 50.5}', - headers={"Content-Type": "application/json"}, - ) - assert response.status_code == 200, response.text - - -@needs_py310 -def test_geo_json(client: TestClient): - response = client.post( - "/items/", - content='{"name": "Foo", "price": 50.5}', - headers={"Content-Type": "application/geo+json"}, - ) - assert response.status_code == 200, response.text - - -@needs_py310 -def test_no_content_type_is_json(client: TestClient): - response = client.post( - "/items/", - content='{"name": "Foo", "price": 50.5}', - ) - assert response.status_code == 200, response.text - assert response.json() == { - "name": "Foo", - "description": None, - "price": 50.5, - "tax": None, - } - - -@needs_py310 -def test_wrong_headers(client: TestClient): - data = '{"name": "Foo", "price": 50.5}' - response = client.post( - "/items/", content=data, headers={"Content-Type": "text/plain"} - ) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "model_attributes_type", - "loc": ["body"], - "msg": "Input should be a valid dictionary or object to extract fields from", - "input": '{"name": "Foo", "price": 50.5}', - "url": match_pydantic_error_url("model_attributes_type"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body"], - "msg": "value is not a valid dict", - "type": "type_error.dict", - } - ] - } - ) - - response = client.post( - "/items/", content=data, headers={"Content-Type": "application/geo+json-seq"} - ) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "model_attributes_type", - "loc": ["body"], - "msg": "Input should be a valid dictionary or object to extract fields from", - "input": '{"name": "Foo", "price": 50.5}', - "url": match_pydantic_error_url("model_attributes_type"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body"], - "msg": "value is not a valid dict", - "type": "type_error.dict", - } - ] - } - ) - response = client.post( - "/items/", content=data, headers={"Content-Type": "application/not-really-json"} - ) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "model_attributes_type", - "loc": ["body"], - "msg": "Input should be a valid dictionary or object to extract fields from", - "input": '{"name": "Foo", "price": 50.5}', - "url": match_pydantic_error_url("model_attributes_type"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body"], - "msg": "value is not a valid dict", - "type": "type_error.dict", - } - ] - } - ) - - -@needs_py310 -def test_other_exceptions(client: TestClient): - with patch("json.loads", side_effect=Exception): - response = client.post("/items/", json={"test": "test2"}) - assert response.status_code == 400, response.text - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Item", - "operationId": "create_item_items__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "price": {"title": "Price", "type": "number"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_body_fields/test_tutorial001.py b/tests/test_tutorial/test_body_fields/test_tutorial001.py index 1ff2d9576..fb68f2868 100644 --- a/tests/test_tutorial/test_body_fields/test_tutorial001.py +++ b/tests/test_tutorial/test_body_fields/test_tutorial001.py @@ -1,14 +1,26 @@ +import importlib + import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url + +from ...utils import needs_py39, needs_py310 -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_fields.tutorial001 import app +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py310", marks=needs_py310), + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + pytest.param("tutorial001_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.body_fields.{request.param}") - client = TestClient(app) + client = TestClient(mod.app) return client @@ -57,7 +69,6 @@ def test_invalid_price(client: TestClient): "msg": "Input should be greater than 0", "input": -3.0, "ctx": {"gt": 0.0}, - "url": match_pydantic_error_url("greater_than"), } ] } diff --git a/tests/test_tutorial/test_body_fields/test_tutorial001_an.py b/tests/test_tutorial/test_body_fields/test_tutorial001_an.py deleted file mode 100644 index 907d6842a..000000000 --- a/tests/test_tutorial/test_body_fields/test_tutorial001_an.py +++ /dev/null @@ -1,205 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_fields.tutorial001_an import app - - client = TestClient(app) - return client - - -def test_items_5(client: TestClient): - response = client.put("/items/5", json={"item": {"name": "Foo", "price": 3.0}}) - assert response.status_code == 200 - assert response.json() == { - "item_id": 5, - "item": {"name": "Foo", "price": 3.0, "description": None, "tax": None}, - } - - -def test_items_6(client: TestClient): - response = client.put( - "/items/6", - json={ - "item": { - "name": "Bar", - "price": 0.2, - "description": "Some bar", - "tax": "5.4", - } - }, - ) - assert response.status_code == 200 - assert response.json() == { - "item_id": 6, - "item": { - "name": "Bar", - "price": 0.2, - "description": "Some bar", - "tax": 5.4, - }, - } - - -def test_invalid_price(client: TestClient): - response = client.put("/items/5", json={"item": {"name": "Foo", "price": -3.0}}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "greater_than", - "loc": ["body", "item", "price"], - "msg": "Input should be greater than 0", - "input": -3.0, - "ctx": {"gt": 0.0}, - "url": match_pydantic_error_url("greater_than"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "ctx": {"limit_value": 0}, - "loc": ["body", "item", "price"], - "msg": "ensure this value is greater than 0", - "type": "value_error.number.not_gt", - } - ] - } - ) - - -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Body_update_item_items__item_id__put" - } - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "The description of the item", - "anyOf": [ - {"maxLength": 300, "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "The description of the item", - "maxLength": 300, - "type": "string", - } - ), - "price": { - "title": "Price", - "exclusiveMinimum": 0.0, - "type": "number", - "description": "The price must be greater than zero", - }, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "Body_update_item_items__item_id__put": { - "title": "Body_update_item_items__item_id__put", - "required": ["item"], - "type": "object", - "properties": {"item": {"$ref": "#/components/schemas/Item"}}, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_body_fields/test_tutorial001_an_py310.py b/tests/test_tutorial/test_body_fields/test_tutorial001_an_py310.py deleted file mode 100644 index 431d2d181..000000000 --- a/tests/test_tutorial/test_body_fields/test_tutorial001_an_py310.py +++ /dev/null @@ -1,211 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_fields.tutorial001_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_items_5(client: TestClient): - response = client.put("/items/5", json={"item": {"name": "Foo", "price": 3.0}}) - assert response.status_code == 200 - assert response.json() == { - "item_id": 5, - "item": {"name": "Foo", "price": 3.0, "description": None, "tax": None}, - } - - -@needs_py310 -def test_items_6(client: TestClient): - response = client.put( - "/items/6", - json={ - "item": { - "name": "Bar", - "price": 0.2, - "description": "Some bar", - "tax": "5.4", - } - }, - ) - assert response.status_code == 200 - assert response.json() == { - "item_id": 6, - "item": { - "name": "Bar", - "price": 0.2, - "description": "Some bar", - "tax": 5.4, - }, - } - - -@needs_py310 -def test_invalid_price(client: TestClient): - response = client.put("/items/5", json={"item": {"name": "Foo", "price": -3.0}}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "greater_than", - "loc": ["body", "item", "price"], - "msg": "Input should be greater than 0", - "input": -3.0, - "ctx": {"gt": 0.0}, - "url": match_pydantic_error_url("greater_than"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "ctx": {"limit_value": 0}, - "loc": ["body", "item", "price"], - "msg": "ensure this value is greater than 0", - "type": "value_error.number.not_gt", - } - ] - } - ) - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Body_update_item_items__item_id__put" - } - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "The description of the item", - "anyOf": [ - {"maxLength": 300, "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "The description of the item", - "maxLength": 300, - "type": "string", - } - ), - "price": { - "title": "Price", - "exclusiveMinimum": 0.0, - "type": "number", - "description": "The price must be greater than zero", - }, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "Body_update_item_items__item_id__put": { - "title": "Body_update_item_items__item_id__put", - "required": ["item"], - "type": "object", - "properties": {"item": {"$ref": "#/components/schemas/Item"}}, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_body_fields/test_tutorial001_an_py39.py b/tests/test_tutorial/test_body_fields/test_tutorial001_an_py39.py deleted file mode 100644 index 8cef6c154..000000000 --- a/tests/test_tutorial/test_body_fields/test_tutorial001_an_py39.py +++ /dev/null @@ -1,211 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_fields.tutorial001_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_items_5(client: TestClient): - response = client.put("/items/5", json={"item": {"name": "Foo", "price": 3.0}}) - assert response.status_code == 200 - assert response.json() == { - "item_id": 5, - "item": {"name": "Foo", "price": 3.0, "description": None, "tax": None}, - } - - -@needs_py39 -def test_items_6(client: TestClient): - response = client.put( - "/items/6", - json={ - "item": { - "name": "Bar", - "price": 0.2, - "description": "Some bar", - "tax": "5.4", - } - }, - ) - assert response.status_code == 200 - assert response.json() == { - "item_id": 6, - "item": { - "name": "Bar", - "price": 0.2, - "description": "Some bar", - "tax": 5.4, - }, - } - - -@needs_py39 -def test_invalid_price(client: TestClient): - response = client.put("/items/5", json={"item": {"name": "Foo", "price": -3.0}}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "greater_than", - "loc": ["body", "item", "price"], - "msg": "Input should be greater than 0", - "input": -3.0, - "ctx": {"gt": 0.0}, - "url": match_pydantic_error_url("greater_than"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "ctx": {"limit_value": 0}, - "loc": ["body", "item", "price"], - "msg": "ensure this value is greater than 0", - "type": "value_error.number.not_gt", - } - ] - } - ) - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Body_update_item_items__item_id__put" - } - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "The description of the item", - "anyOf": [ - {"maxLength": 300, "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "The description of the item", - "maxLength": 300, - "type": "string", - } - ), - "price": { - "title": "Price", - "exclusiveMinimum": 0.0, - "type": "number", - "description": "The price must be greater than zero", - }, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "Body_update_item_items__item_id__put": { - "title": "Body_update_item_items__item_id__put", - "required": ["item"], - "type": "object", - "properties": {"item": {"$ref": "#/components/schemas/Item"}}, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_body_fields/test_tutorial001_py310.py b/tests/test_tutorial/test_body_fields/test_tutorial001_py310.py deleted file mode 100644 index b48cd9ec2..000000000 --- a/tests/test_tutorial/test_body_fields/test_tutorial001_py310.py +++ /dev/null @@ -1,211 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_fields.tutorial001_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_items_5(client: TestClient): - response = client.put("/items/5", json={"item": {"name": "Foo", "price": 3.0}}) - assert response.status_code == 200 - assert response.json() == { - "item_id": 5, - "item": {"name": "Foo", "price": 3.0, "description": None, "tax": None}, - } - - -@needs_py310 -def test_items_6(client: TestClient): - response = client.put( - "/items/6", - json={ - "item": { - "name": "Bar", - "price": 0.2, - "description": "Some bar", - "tax": "5.4", - } - }, - ) - assert response.status_code == 200 - assert response.json() == { - "item_id": 6, - "item": { - "name": "Bar", - "price": 0.2, - "description": "Some bar", - "tax": 5.4, - }, - } - - -@needs_py310 -def test_invalid_price(client: TestClient): - response = client.put("/items/5", json={"item": {"name": "Foo", "price": -3.0}}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "greater_than", - "loc": ["body", "item", "price"], - "msg": "Input should be greater than 0", - "input": -3.0, - "ctx": {"gt": 0.0}, - "url": match_pydantic_error_url("greater_than"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "ctx": {"limit_value": 0}, - "loc": ["body", "item", "price"], - "msg": "ensure this value is greater than 0", - "type": "value_error.number.not_gt", - } - ] - } - ) - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Body_update_item_items__item_id__put" - } - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "The description of the item", - "anyOf": [ - {"maxLength": 300, "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "The description of the item", - "maxLength": 300, - "type": "string", - } - ), - "price": { - "title": "Price", - "exclusiveMinimum": 0.0, - "type": "number", - "description": "The price must be greater than zero", - }, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "Body_update_item_items__item_id__put": { - "title": "Body_update_item_items__item_id__put", - "required": ["item"], - "type": "object", - "properties": {"item": {"$ref": "#/components/schemas/Item"}}, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py index e5dc13b26..142405595 100644 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py +++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial001.py @@ -1,14 +1,26 @@ +import importlib + import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url + +from ...utils import needs_py39, needs_py310 -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_multiple_params.tutorial001 import app +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py310", marks=needs_py310), + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + pytest.param("tutorial001_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.body_multiple_params.{request.param}") - client = TestClient(app) + client = TestClient(mod.app) return client @@ -50,7 +62,6 @@ def test_post_id_foo(client: TestClient): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "foo", - "url": match_pydantic_error_url("int_parsing"), } ] } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an.py deleted file mode 100644 index 51e8e3a4e..000000000 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an.py +++ /dev/null @@ -1,208 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_multiple_params.tutorial001_an import app - - client = TestClient(app) - return client - - -def test_post_body_q_bar_content(client: TestClient): - response = client.put("/items/5?q=bar", json={"name": "Foo", "price": 50.5}) - assert response.status_code == 200 - assert response.json() == { - "item_id": 5, - "item": { - "name": "Foo", - "price": 50.5, - "description": None, - "tax": None, - }, - "q": "bar", - } - - -def test_post_no_body_q_bar(client: TestClient): - response = client.put("/items/5?q=bar", json=None) - assert response.status_code == 200 - assert response.json() == {"item_id": 5, "q": "bar"} - - -def test_post_no_body(client: TestClient): - response = client.put("/items/5", json=None) - assert response.status_code == 200 - assert response.json() == {"item_id": 5} - - -def test_post_id_foo(client: TestClient): - response = client.put("/items/foo", json=None) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "int_parsing", - "loc": ["path", "item_id"], - "msg": "Input should be a valid integer, unable to parse string as an integer", - "input": "foo", - "url": match_pydantic_error_url("int_parsing"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["path", "item_id"], - "msg": "value is not a valid integer", - "type": "type_error.integer", - } - ] - } - ) - - -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": { - "title": "The ID of the item to get", - "maximum": 1000.0, - "minimum": 0.0, - "type": "integer", - }, - "name": "item_id", - "in": "path", - }, - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Q", "type": "string"} - ), - "name": "q", - "in": "query", - }, - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict( - { - "anyOf": [ - {"$ref": "#/components/schemas/Item"}, - {"type": "null"}, - ], - "title": "Item", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"$ref": "#/components/schemas/Item"} - ) - } - } - }, - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py310.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py310.py deleted file mode 100644 index 8ac1f7261..000000000 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py310.py +++ /dev/null @@ -1,215 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_multiple_params.tutorial001_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_post_body_q_bar_content(client: TestClient): - response = client.put("/items/5?q=bar", json={"name": "Foo", "price": 50.5}) - assert response.status_code == 200 - assert response.json() == { - "item_id": 5, - "item": { - "name": "Foo", - "price": 50.5, - "description": None, - "tax": None, - }, - "q": "bar", - } - - -@needs_py310 -def test_post_no_body_q_bar(client: TestClient): - response = client.put("/items/5?q=bar", json=None) - assert response.status_code == 200 - assert response.json() == {"item_id": 5, "q": "bar"} - - -@needs_py310 -def test_post_no_body(client: TestClient): - response = client.put("/items/5", json=None) - assert response.status_code == 200 - assert response.json() == {"item_id": 5} - - -@needs_py310 -def test_post_id_foo(client: TestClient): - response = client.put("/items/foo", json=None) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "int_parsing", - "loc": ["path", "item_id"], - "msg": "Input should be a valid integer, unable to parse string as an integer", - "input": "foo", - "url": match_pydantic_error_url("int_parsing"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["path", "item_id"], - "msg": "value is not a valid integer", - "type": "type_error.integer", - } - ] - } - ) - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": { - "title": "The ID of the item to get", - "maximum": 1000.0, - "minimum": 0.0, - "type": "integer", - }, - "name": "item_id", - "in": "path", - }, - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Q", "type": "string"} - ), - "name": "q", - "in": "query", - }, - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict( - { - "anyOf": [ - {"$ref": "#/components/schemas/Item"}, - {"type": "null"}, - ], - "title": "Item", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"$ref": "#/components/schemas/Item"} - ) - } - } - }, - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py39.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py39.py deleted file mode 100644 index 7ada42c52..000000000 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_an_py39.py +++ /dev/null @@ -1,215 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_multiple_params.tutorial001_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_post_body_q_bar_content(client: TestClient): - response = client.put("/items/5?q=bar", json={"name": "Foo", "price": 50.5}) - assert response.status_code == 200 - assert response.json() == { - "item_id": 5, - "item": { - "name": "Foo", - "price": 50.5, - "description": None, - "tax": None, - }, - "q": "bar", - } - - -@needs_py39 -def test_post_no_body_q_bar(client: TestClient): - response = client.put("/items/5?q=bar", json=None) - assert response.status_code == 200 - assert response.json() == {"item_id": 5, "q": "bar"} - - -@needs_py39 -def test_post_no_body(client: TestClient): - response = client.put("/items/5", json=None) - assert response.status_code == 200 - assert response.json() == {"item_id": 5} - - -@needs_py39 -def test_post_id_foo(client: TestClient): - response = client.put("/items/foo", json=None) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "int_parsing", - "loc": ["path", "item_id"], - "msg": "Input should be a valid integer, unable to parse string as an integer", - "input": "foo", - "url": match_pydantic_error_url("int_parsing"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["path", "item_id"], - "msg": "value is not a valid integer", - "type": "type_error.integer", - } - ] - } - ) - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": { - "title": "The ID of the item to get", - "maximum": 1000.0, - "minimum": 0.0, - "type": "integer", - }, - "name": "item_id", - "in": "path", - }, - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Q", "type": "string"} - ), - "name": "q", - "in": "query", - }, - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict( - { - "anyOf": [ - {"$ref": "#/components/schemas/Item"}, - {"type": "null"}, - ], - "title": "Item", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"$ref": "#/components/schemas/Item"} - ) - } - } - }, - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_py310.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial001_py310.py deleted file mode 100644 index 0a832eaf6..000000000 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial001_py310.py +++ /dev/null @@ -1,215 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_multiple_params.tutorial001_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_post_body_q_bar_content(client: TestClient): - response = client.put("/items/5?q=bar", json={"name": "Foo", "price": 50.5}) - assert response.status_code == 200 - assert response.json() == { - "item_id": 5, - "item": { - "name": "Foo", - "price": 50.5, - "description": None, - "tax": None, - }, - "q": "bar", - } - - -@needs_py310 -def test_post_no_body_q_bar(client: TestClient): - response = client.put("/items/5?q=bar", json=None) - assert response.status_code == 200 - assert response.json() == {"item_id": 5, "q": "bar"} - - -@needs_py310 -def test_post_no_body(client: TestClient): - response = client.put("/items/5", json=None) - assert response.status_code == 200 - assert response.json() == {"item_id": 5} - - -@needs_py310 -def test_post_id_foo(client: TestClient): - response = client.put("/items/foo", json=None) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "int_parsing", - "loc": ["path", "item_id"], - "msg": "Input should be a valid integer, unable to parse string as an integer", - "input": "foo", - "url": match_pydantic_error_url("int_parsing"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["path", "item_id"], - "msg": "value is not a valid integer", - "type": "type_error.integer", - } - ] - } - ) - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": { - "title": "The ID of the item to get", - "maximum": 1000.0, - "minimum": 0.0, - "type": "integer", - }, - "name": "item_id", - "in": "path", - }, - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Q", "type": "string"} - ), - "name": "q", - "in": "query", - }, - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict( - { - "anyOf": [ - {"$ref": "#/components/schemas/Item"}, - {"type": "null"}, - ], - "title": "Item", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"$ref": "#/components/schemas/Item"} - ) - } - } - }, - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial003.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial003.py index 2046579a9..d18ceae48 100644 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial003.py +++ b/tests/test_tutorial/test_body_multiple_params/test_tutorial003.py @@ -1,14 +1,26 @@ +import importlib + import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url + +from ...utils import needs_py39, needs_py310 -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_multiple_params.tutorial003 import app +@pytest.fixture( + name="client", + params=[ + "tutorial003", + pytest.param("tutorial003_py310", marks=needs_py310), + "tutorial003_an", + pytest.param("tutorial003_an_py39", marks=needs_py39), + pytest.param("tutorial003_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.body_multiple_params.{request.param}") - client = TestClient(app) + client = TestClient(mod.app) return client @@ -46,21 +58,18 @@ def test_post_body_no_data(client: TestClient): "loc": ["body", "item"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "user"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "importance"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -99,21 +108,18 @@ def test_post_body_empty_list(client: TestClient): "loc": ["body", "item"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "user"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["body", "importance"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an.py deleted file mode 100644 index 1282483e0..000000000 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an.py +++ /dev/null @@ -1,280 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_multiple_params.tutorial003_an import app - - client = TestClient(app) - return client - - -def test_post_body_valid(client: TestClient): - response = client.put( - "/items/5", - json={ - "importance": 2, - "item": {"name": "Foo", "price": 50.5}, - "user": {"username": "Dave"}, - }, - ) - assert response.status_code == 200 - assert response.json() == { - "item_id": 5, - "importance": 2, - "item": { - "name": "Foo", - "price": 50.5, - "description": None, - "tax": None, - }, - "user": {"username": "Dave", "full_name": None}, - } - - -def test_post_body_no_data(client: TestClient): - response = client.put("/items/5", json=None) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "item"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - { - "type": "missing", - "loc": ["body", "user"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - { - "type": "missing", - "loc": ["body", "importance"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "item"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "user"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "importance"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_post_body_empty_list(client: TestClient): - response = client.put("/items/5", json=[]) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "item"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - { - "type": "missing", - "loc": ["body", "user"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - { - "type": "missing", - "loc": ["body", "importance"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "item"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "user"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "importance"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Body_update_item_items__item_id__put" - } - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "User": { - "title": "User", - "required": ["username"], - "type": "object", - "properties": { - "username": {"title": "Username", "type": "string"}, - "full_name": IsDict( - { - "title": "Full Name", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Full Name", "type": "string"} - ), - }, - }, - "Body_update_item_items__item_id__put": { - "title": "Body_update_item_items__item_id__put", - "required": ["item", "user", "importance"], - "type": "object", - "properties": { - "item": {"$ref": "#/components/schemas/Item"}, - "user": {"$ref": "#/components/schemas/User"}, - "importance": {"title": "Importance", "type": "integer"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py310.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py310.py deleted file mode 100644 index 577c079d0..000000000 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py310.py +++ /dev/null @@ -1,286 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_multiple_params.tutorial003_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_post_body_valid(client: TestClient): - response = client.put( - "/items/5", - json={ - "importance": 2, - "item": {"name": "Foo", "price": 50.5}, - "user": {"username": "Dave"}, - }, - ) - assert response.status_code == 200 - assert response.json() == { - "item_id": 5, - "importance": 2, - "item": { - "name": "Foo", - "price": 50.5, - "description": None, - "tax": None, - }, - "user": {"username": "Dave", "full_name": None}, - } - - -@needs_py310 -def test_post_body_no_data(client: TestClient): - response = client.put("/items/5", json=None) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "item"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - { - "type": "missing", - "loc": ["body", "user"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - { - "type": "missing", - "loc": ["body", "importance"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "item"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "user"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "importance"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py310 -def test_post_body_empty_list(client: TestClient): - response = client.put("/items/5", json=[]) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "item"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - { - "type": "missing", - "loc": ["body", "user"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - { - "type": "missing", - "loc": ["body", "importance"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "item"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "user"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "importance"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Body_update_item_items__item_id__put" - } - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "User": { - "title": "User", - "required": ["username"], - "type": "object", - "properties": { - "username": {"title": "Username", "type": "string"}, - "full_name": IsDict( - { - "title": "Full Name", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Full Name", "type": "string"} - ), - }, - }, - "Body_update_item_items__item_id__put": { - "title": "Body_update_item_items__item_id__put", - "required": ["item", "user", "importance"], - "type": "object", - "properties": { - "item": {"$ref": "#/components/schemas/Item"}, - "user": {"$ref": "#/components/schemas/User"}, - "importance": {"title": "Importance", "type": "integer"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py39.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py39.py deleted file mode 100644 index 0ec04151c..000000000 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_an_py39.py +++ /dev/null @@ -1,286 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_multiple_params.tutorial003_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_post_body_valid(client: TestClient): - response = client.put( - "/items/5", - json={ - "importance": 2, - "item": {"name": "Foo", "price": 50.5}, - "user": {"username": "Dave"}, - }, - ) - assert response.status_code == 200 - assert response.json() == { - "item_id": 5, - "importance": 2, - "item": { - "name": "Foo", - "price": 50.5, - "description": None, - "tax": None, - }, - "user": {"username": "Dave", "full_name": None}, - } - - -@needs_py39 -def test_post_body_no_data(client: TestClient): - response = client.put("/items/5", json=None) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "item"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - { - "type": "missing", - "loc": ["body", "user"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - { - "type": "missing", - "loc": ["body", "importance"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "item"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "user"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "importance"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_post_body_empty_list(client: TestClient): - response = client.put("/items/5", json=[]) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "item"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - { - "type": "missing", - "loc": ["body", "user"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - { - "type": "missing", - "loc": ["body", "importance"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "item"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "user"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "importance"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Body_update_item_items__item_id__put" - } - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "User": { - "title": "User", - "required": ["username"], - "type": "object", - "properties": { - "username": {"title": "Username", "type": "string"}, - "full_name": IsDict( - { - "title": "Full Name", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Full Name", "type": "string"} - ), - }, - }, - "Body_update_item_items__item_id__put": { - "title": "Body_update_item_items__item_id__put", - "required": ["item", "user", "importance"], - "type": "object", - "properties": { - "item": {"$ref": "#/components/schemas/Item"}, - "user": {"$ref": "#/components/schemas/User"}, - "importance": {"title": "Importance", "type": "integer"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_py310.py b/tests/test_tutorial/test_body_multiple_params/test_tutorial003_py310.py deleted file mode 100644 index 9caf5fe6c..000000000 --- a/tests/test_tutorial/test_body_multiple_params/test_tutorial003_py310.py +++ /dev/null @@ -1,286 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_multiple_params.tutorial003_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_post_body_valid(client: TestClient): - response = client.put( - "/items/5", - json={ - "importance": 2, - "item": {"name": "Foo", "price": 50.5}, - "user": {"username": "Dave"}, - }, - ) - assert response.status_code == 200 - assert response.json() == { - "item_id": 5, - "importance": 2, - "item": { - "name": "Foo", - "price": 50.5, - "description": None, - "tax": None, - }, - "user": {"username": "Dave", "full_name": None}, - } - - -@needs_py310 -def test_post_body_no_data(client: TestClient): - response = client.put("/items/5", json=None) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "item"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - { - "type": "missing", - "loc": ["body", "user"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - { - "type": "missing", - "loc": ["body", "importance"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "item"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "user"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "importance"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py310 -def test_post_body_empty_list(client: TestClient): - response = client.put("/items/5", json=[]) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "item"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - { - "type": "missing", - "loc": ["body", "user"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - { - "type": "missing", - "loc": ["body", "importance"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "item"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "user"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "importance"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Body_update_item_items__item_id__put" - } - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "User": { - "title": "User", - "required": ["username"], - "type": "object", - "properties": { - "username": {"title": "Username", "type": "string"}, - "full_name": IsDict( - { - "title": "Full Name", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Full Name", "type": "string"} - ), - }, - }, - "Body_update_item_items__item_id__put": { - "title": "Body_update_item_items__item_id__put", - "required": ["item", "user", "importance"], - "type": "object", - "properties": { - "item": {"$ref": "#/components/schemas/Item"}, - "user": {"$ref": "#/components/schemas/User"}, - "importance": {"title": "Importance", "type": "integer"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_body_nested_models/test_tutorial009.py b/tests/test_tutorial/test_body_nested_models/test_tutorial009.py index f4a76be44..38ba3c887 100644 --- a/tests/test_tutorial/test_body_nested_models/test_tutorial009.py +++ b/tests/test_tutorial/test_body_nested_models/test_tutorial009.py @@ -1,14 +1,23 @@ +import importlib + import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url + +from ...utils import needs_py39 -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_nested_models.tutorial009 import app +@pytest.fixture( + name="client", + params=[ + "tutorial009", + pytest.param("tutorial009_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.body_nested_models.{request.param}") - client = TestClient(app) + client = TestClient(mod.app) return client @@ -31,7 +40,6 @@ def test_post_invalid_body(client: TestClient): "loc": ["body", "foo", "[key]"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "foo", - "url": match_pydantic_error_url("int_parsing"), } ] } diff --git a/tests/test_tutorial/test_body_nested_models/test_tutorial009_py39.py b/tests/test_tutorial/test_body_nested_models/test_tutorial009_py39.py deleted file mode 100644 index 8ab9bcac8..000000000 --- a/tests/test_tutorial/test_body_nested_models/test_tutorial009_py39.py +++ /dev/null @@ -1,130 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_nested_models.tutorial009_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_post_body(client: TestClient): - data = {"2": 2.2, "3": 3.3} - response = client.post("/index-weights/", json=data) - assert response.status_code == 200, response.text - assert response.json() == data - - -@needs_py39 -def test_post_invalid_body(client: TestClient): - data = {"foo": 2.2, "3": 3.3} - response = client.post("/index-weights/", json=data) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "int_parsing", - "loc": ["body", "foo", "[key]"], - "msg": "Input should be a valid integer, unable to parse string as an integer", - "input": "foo", - "url": match_pydantic_error_url("int_parsing"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "__key__"], - "msg": "value is not a valid integer", - "type": "type_error.integer", - } - ] - } - ) - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/index-weights/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Index Weights", - "operationId": "create_index_weights_index_weights__post", - "requestBody": { - "content": { - "application/json": { - "schema": { - "title": "Weights", - "type": "object", - "additionalProperties": {"type": "number"}, - } - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_body_updates/test_tutorial001.py b/tests/test_tutorial/test_body_updates/test_tutorial001.py index e586534a0..f874dc9bd 100644 --- a/tests/test_tutorial/test_body_updates/test_tutorial001.py +++ b/tests/test_tutorial/test_body_updates/test_tutorial001.py @@ -1,14 +1,23 @@ +import importlib + import pytest from fastapi.testclient import TestClient -from ...utils import needs_pydanticv1, needs_pydanticv2 +from ...utils import needs_py39, needs_py310, needs_pydanticv1, needs_pydanticv2 -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_updates.tutorial001 import app +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py310", marks=needs_py310), + pytest.param("tutorial001_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.body_updates.{request.param}") - client = TestClient(app) + client = TestClient(mod.app) return client diff --git a/tests/test_tutorial/test_body_updates/test_tutorial001_py310.py b/tests/test_tutorial/test_body_updates/test_tutorial001_py310.py deleted file mode 100644 index 6bc969d43..000000000 --- a/tests/test_tutorial/test_body_updates/test_tutorial001_py310.py +++ /dev/null @@ -1,317 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py310, needs_pydanticv1, needs_pydanticv2 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_updates.tutorial001_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_get(client: TestClient): - response = client.get("/items/baz") - assert response.status_code == 200, response.text - assert response.json() == { - "name": "Baz", - "description": None, - "price": 50.2, - "tax": 10.5, - "tags": [], - } - - -@needs_py310 -def test_put(client: TestClient): - response = client.put( - "/items/bar", json={"name": "Barz", "price": 3, "description": None} - ) - assert response.json() == { - "name": "Barz", - "description": None, - "price": 3, - "tax": 10.5, - "tags": [], - } - - -@needs_py310 -@needs_pydanticv2 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Item", - "operationId": "read_item_items__item_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - } - ], - }, - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - "required": True, - }, - }, - } - }, - "components": { - "schemas": { - "Item": { - "type": "object", - "title": "Item", - "properties": { - "name": { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Name", - }, - "description": { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Description", - }, - "price": { - "anyOf": [{"type": "number"}, {"type": "null"}], - "title": "Price", - }, - "tax": {"title": "Tax", "type": "number", "default": 10.5}, - "tags": { - "title": "Tags", - "type": "array", - "items": {"type": "string"}, - "default": [], - }, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } - - -# TODO: remove when deprecating Pydantic v1 -@needs_py310 -@needs_pydanticv1 -def test_openapi_schema_pv1(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Item", - "operationId": "read_item_items__item_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - } - ], - }, - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - "required": True, - }, - }, - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": {"title": "Description", "type": "string"}, - "price": {"title": "Price", "type": "number"}, - "tax": {"title": "Tax", "type": "number", "default": 10.5}, - "tags": { - "title": "Tags", - "type": "array", - "items": {"type": "string"}, - "default": [], - }, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_body_updates/test_tutorial001_py39.py b/tests/test_tutorial/test_body_updates/test_tutorial001_py39.py deleted file mode 100644 index a1edb3370..000000000 --- a/tests/test_tutorial/test_body_updates/test_tutorial001_py39.py +++ /dev/null @@ -1,317 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39, needs_pydanticv1, needs_pydanticv2 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.body_updates.tutorial001_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_get(client: TestClient): - response = client.get("/items/baz") - assert response.status_code == 200, response.text - assert response.json() == { - "name": "Baz", - "description": None, - "price": 50.2, - "tax": 10.5, - "tags": [], - } - - -@needs_py39 -def test_put(client: TestClient): - response = client.put( - "/items/bar", json={"name": "Barz", "price": 3, "description": None} - ) - assert response.json() == { - "name": "Barz", - "description": None, - "price": 3, - "tax": 10.5, - "tags": [], - } - - -@needs_py39 -@needs_pydanticv2 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Item", - "operationId": "read_item_items__item_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - } - ], - }, - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - "required": True, - }, - }, - } - }, - "components": { - "schemas": { - "Item": { - "type": "object", - "title": "Item", - "properties": { - "name": { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Name", - }, - "description": { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Description", - }, - "price": { - "anyOf": [{"type": "number"}, {"type": "null"}], - "title": "Price", - }, - "tax": {"title": "Tax", "type": "number", "default": 10.5}, - "tags": { - "title": "Tags", - "type": "array", - "items": {"type": "string"}, - "default": [], - }, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } - - -# TODO: remove when deprecating Pydantic v1 -@needs_py39 -@needs_pydanticv1 -def test_openapi_schema_pv1(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Item", - "operationId": "read_item_items__item_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - } - ], - }, - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - "required": True, - }, - }, - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": {"title": "Description", "type": "string"}, - "price": {"title": "Price", "type": "number"}, - "tax": {"title": "Tax", "type": "number", "default": 10.5}, - "tags": { - "title": "Tags", - "type": "array", - "items": {"type": "string"}, - "default": [], - }, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_configure_swagger_ui/test_tutorial002.py b/tests/test_tutorial/test_configure_swagger_ui/test_tutorial002.py index 166901188..d06a385b5 100644 --- a/tests/test_tutorial/test_configure_swagger_ui/test_tutorial002.py +++ b/tests/test_tutorial/test_configure_swagger_ui/test_tutorial002.py @@ -12,7 +12,7 @@ def test_swagger_ui(): '"syntaxHighlight": false' not in response.text ), "not used parameters should not be included" assert ( - '"syntaxHighlight.theme": "obsidian"' in response.text + '"syntaxHighlight": {"theme": "obsidian"}' in response.text ), "parameters with middle dots should be included in a JSON compatible way" assert ( '"dom_id": "#swagger-ui"' in response.text diff --git a/docs_src/sql_databases/sql_app/__init__.py b/tests/test_tutorial/test_cookie_param_models/__init__.py similarity index 100% rename from docs_src/sql_databases/sql_app/__init__.py rename to tests/test_tutorial/test_cookie_param_models/__init__.py diff --git a/tests/test_tutorial/test_cookie_param_models/test_tutorial001.py b/tests/test_tutorial/test_cookie_param_models/test_tutorial001.py new file mode 100644 index 000000000..60643185a --- /dev/null +++ b/tests/test_tutorial/test_cookie_param_models/test_tutorial001.py @@ -0,0 +1,205 @@ +import importlib + +import pytest +from dirty_equals import IsDict +from fastapi.testclient import TestClient +from inline_snapshot import snapshot + +from tests.utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py310", marks=needs_py310), + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + pytest.param("tutorial001_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.cookie_param_models.{request.param}") + + client = TestClient(mod.app) + return client + + +def test_cookie_param_model(client: TestClient): + with client as c: + c.cookies.set("session_id", "123") + c.cookies.set("fatebook_tracker", "456") + c.cookies.set("googall_tracker", "789") + response = c.get("/items/") + assert response.status_code == 200 + assert response.json() == { + "session_id": "123", + "fatebook_tracker": "456", + "googall_tracker": "789", + } + + +def test_cookie_param_model_defaults(client: TestClient): + with client as c: + c.cookies.set("session_id", "123") + response = c.get("/items/") + assert response.status_code == 200 + assert response.json() == { + "session_id": "123", + "fatebook_tracker": None, + "googall_tracker": None, + } + + +def test_cookie_param_model_invalid(client: TestClient): + response = client.get("/items/") + assert response.status_code == 422 + assert response.json() == snapshot( + IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["cookie", "session_id"], + "msg": "Field required", + "input": {}, + } + ] + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "type": "value_error.missing", + "loc": ["cookie", "session_id"], + "msg": "field required", + } + ] + } + ) + ) + + +def test_cookie_param_model_extra(client: TestClient): + with client as c: + c.cookies.set("session_id", "123") + c.cookies.set("extra", "track-me-here-too") + response = c.get("/items/") + assert response.status_code == 200 + assert response.json() == snapshot( + {"session_id": "123", "fatebook_tracker": None, "googall_tracker": None} + ) + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "parameters": [ + { + "name": "session_id", + "in": "cookie", + "required": True, + "schema": {"type": "string", "title": "Session Id"}, + }, + { + "name": "fatebook_tracker", + "in": "cookie", + "required": False, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Fatebook Tracker", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "Fatebook Tracker", + } + ), + }, + { + "name": "googall_tracker", + "in": "cookie", + "required": False, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Googall Tracker", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "Googall Tracker", + } + ), + }, + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } + ) diff --git a/tests/test_tutorial/test_cookie_param_models/test_tutorial002.py b/tests/test_tutorial/test_cookie_param_models/test_tutorial002.py new file mode 100644 index 000000000..30adadc8a --- /dev/null +++ b/tests/test_tutorial/test_cookie_param_models/test_tutorial002.py @@ -0,0 +1,233 @@ +import importlib + +import pytest +from dirty_equals import IsDict +from fastapi.testclient import TestClient +from inline_snapshot import snapshot + +from tests.utils import needs_py39, needs_py310, needs_pydanticv1, needs_pydanticv2 + + +@pytest.fixture( + name="client", + params=[ + pytest.param("tutorial002", marks=needs_pydanticv2), + pytest.param("tutorial002_py310", marks=[needs_py310, needs_pydanticv2]), + pytest.param("tutorial002_an", marks=needs_pydanticv2), + pytest.param("tutorial002_an_py39", marks=[needs_py39, needs_pydanticv2]), + pytest.param("tutorial002_an_py310", marks=[needs_py310, needs_pydanticv2]), + pytest.param("tutorial002_pv1", marks=[needs_pydanticv1, needs_pydanticv1]), + pytest.param("tutorial002_pv1_py310", marks=[needs_py310, needs_pydanticv1]), + pytest.param("tutorial002_pv1_an", marks=[needs_pydanticv1]), + pytest.param("tutorial002_pv1_an_py39", marks=[needs_py39, needs_pydanticv1]), + pytest.param("tutorial002_pv1_an_py310", marks=[needs_py310, needs_pydanticv1]), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.cookie_param_models.{request.param}") + + client = TestClient(mod.app) + return client + + +def test_cookie_param_model(client: TestClient): + with client as c: + c.cookies.set("session_id", "123") + c.cookies.set("fatebook_tracker", "456") + c.cookies.set("googall_tracker", "789") + response = c.get("/items/") + assert response.status_code == 200 + assert response.json() == { + "session_id": "123", + "fatebook_tracker": "456", + "googall_tracker": "789", + } + + +def test_cookie_param_model_defaults(client: TestClient): + with client as c: + c.cookies.set("session_id", "123") + response = c.get("/items/") + assert response.status_code == 200 + assert response.json() == { + "session_id": "123", + "fatebook_tracker": None, + "googall_tracker": None, + } + + +def test_cookie_param_model_invalid(client: TestClient): + response = client.get("/items/") + assert response.status_code == 422 + assert response.json() == snapshot( + IsDict( + { + "detail": [ + { + "type": "missing", + "loc": ["cookie", "session_id"], + "msg": "Field required", + "input": {}, + } + ] + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "type": "value_error.missing", + "loc": ["cookie", "session_id"], + "msg": "field required", + } + ] + } + ) + ) + + +def test_cookie_param_model_extra(client: TestClient): + with client as c: + c.cookies.set("session_id", "123") + c.cookies.set("extra", "track-me-here-too") + response = c.get("/items/") + assert response.status_code == 422 + assert response.json() == snapshot( + IsDict( + { + "detail": [ + { + "type": "extra_forbidden", + "loc": ["cookie", "extra"], + "msg": "Extra inputs are not permitted", + "input": "track-me-here-too", + } + ] + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "type": "value_error.extra", + "loc": ["cookie", "extra"], + "msg": "extra fields not permitted", + } + ] + } + ) + ) + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "parameters": [ + { + "name": "session_id", + "in": "cookie", + "required": True, + "schema": {"type": "string", "title": "Session Id"}, + }, + { + "name": "fatebook_tracker", + "in": "cookie", + "required": False, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Fatebook Tracker", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "Fatebook Tracker", + } + ), + }, + { + "name": "googall_tracker", + "in": "cookie", + "required": False, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Googall Tracker", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "Googall Tracker", + } + ), + }, + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } + ) diff --git a/tests/test_tutorial/test_cookie_params/test_tutorial001.py b/tests/test_tutorial/test_cookie_params/test_tutorial001.py index 7d0e669ab..90e8dfd37 100644 --- a/tests/test_tutorial/test_cookie_params/test_tutorial001.py +++ b/tests/test_tutorial/test_cookie_params/test_tutorial001.py @@ -1,8 +1,27 @@ +import importlib +from types import ModuleType + import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from docs_src.cookie_params.tutorial001 import app +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="mod", + params=[ + "tutorial001", + pytest.param("tutorial001_py310", marks=needs_py310), + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + pytest.param("tutorial001_an_py310", marks=needs_py310), + ], +) +def get_mod(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.cookie_params.{request.param}") + + return mod @pytest.mark.parametrize( @@ -19,15 +38,15 @@ from docs_src.cookie_params.tutorial001 import app ("/items", {"session": "cookiesession"}, 200, {"ads_id": None}), ], ) -def test(path, cookies, expected_status, expected_response): - client = TestClient(app, cookies=cookies) +def test(path, cookies, expected_status, expected_response, mod: ModuleType): + client = TestClient(mod.app, cookies=cookies) response = client.get(path) assert response.status_code == expected_status assert response.json() == expected_response -def test_openapi_schema(): - client = TestClient(app) +def test_openapi_schema(mod: ModuleType): + client = TestClient(mod.app) response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { diff --git a/tests/test_tutorial/test_cookie_params/test_tutorial001_an.py b/tests/test_tutorial/test_cookie_params/test_tutorial001_an.py deleted file mode 100644 index 2505876c8..000000000 --- a/tests/test_tutorial/test_cookie_params/test_tutorial001_an.py +++ /dev/null @@ -1,108 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from docs_src.cookie_params.tutorial001_an import app - - -@pytest.mark.parametrize( - "path,cookies,expected_status,expected_response", - [ - ("/items", None, 200, {"ads_id": None}), - ("/items", {"ads_id": "ads_track"}, 200, {"ads_id": "ads_track"}), - ( - "/items", - {"ads_id": "ads_track", "session": "cookiesession"}, - 200, - {"ads_id": "ads_track"}, - ), - ("/items", {"session": "cookiesession"}, 200, {"ads_id": None}), - ], -) -def test(path, cookies, expected_status, expected_response): - client = TestClient(app, cookies=cookies) - response = client.get(path) - assert response.status_code == expected_status - assert response.json() == expected_response - - -def test_openapi_schema(): - client = TestClient(app) - response = client.get("/openapi.json") - assert response.status_code == 200 - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Ads Id", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Ads Id", "type": "string"} - ), - "name": "ads_id", - "in": "cookie", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_cookie_params/test_tutorial001_an_py310.py b/tests/test_tutorial/test_cookie_params/test_tutorial001_an_py310.py deleted file mode 100644 index 108f78b9c..000000000 --- a/tests/test_tutorial/test_cookie_params/test_tutorial001_an_py310.py +++ /dev/null @@ -1,114 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@needs_py310 -@pytest.mark.parametrize( - "path,cookies,expected_status,expected_response", - [ - ("/items", None, 200, {"ads_id": None}), - ("/items", {"ads_id": "ads_track"}, 200, {"ads_id": "ads_track"}), - ( - "/items", - {"ads_id": "ads_track", "session": "cookiesession"}, - 200, - {"ads_id": "ads_track"}, - ), - ("/items", {"session": "cookiesession"}, 200, {"ads_id": None}), - ], -) -def test(path, cookies, expected_status, expected_response): - from docs_src.cookie_params.tutorial001_an_py310 import app - - client = TestClient(app, cookies=cookies) - response = client.get(path) - assert response.status_code == expected_status - assert response.json() == expected_response - - -@needs_py310 -def test_openapi_schema(): - from docs_src.cookie_params.tutorial001_an_py310 import app - - client = TestClient(app) - response = client.get("/openapi.json") - assert response.status_code == 200 - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Ads Id", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Ads Id", "type": "string"} - ), - "name": "ads_id", - "in": "cookie", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_cookie_params/test_tutorial001_an_py39.py b/tests/test_tutorial/test_cookie_params/test_tutorial001_an_py39.py deleted file mode 100644 index 8126a1052..000000000 --- a/tests/test_tutorial/test_cookie_params/test_tutorial001_an_py39.py +++ /dev/null @@ -1,114 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@needs_py39 -@pytest.mark.parametrize( - "path,cookies,expected_status,expected_response", - [ - ("/items", None, 200, {"ads_id": None}), - ("/items", {"ads_id": "ads_track"}, 200, {"ads_id": "ads_track"}), - ( - "/items", - {"ads_id": "ads_track", "session": "cookiesession"}, - 200, - {"ads_id": "ads_track"}, - ), - ("/items", {"session": "cookiesession"}, 200, {"ads_id": None}), - ], -) -def test(path, cookies, expected_status, expected_response): - from docs_src.cookie_params.tutorial001_an_py39 import app - - client = TestClient(app, cookies=cookies) - response = client.get(path) - assert response.status_code == expected_status - assert response.json() == expected_response - - -@needs_py39 -def test_openapi_schema(): - from docs_src.cookie_params.tutorial001_an_py39 import app - - client = TestClient(app) - response = client.get("/openapi.json") - assert response.status_code == 200 - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Ads Id", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Ads Id", "type": "string"} - ), - "name": "ads_id", - "in": "cookie", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_cookie_params/test_tutorial001_py310.py b/tests/test_tutorial/test_cookie_params/test_tutorial001_py310.py deleted file mode 100644 index 6711fa581..000000000 --- a/tests/test_tutorial/test_cookie_params/test_tutorial001_py310.py +++ /dev/null @@ -1,114 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@needs_py310 -@pytest.mark.parametrize( - "path,cookies,expected_status,expected_response", - [ - ("/items", None, 200, {"ads_id": None}), - ("/items", {"ads_id": "ads_track"}, 200, {"ads_id": "ads_track"}), - ( - "/items", - {"ads_id": "ads_track", "session": "cookiesession"}, - 200, - {"ads_id": "ads_track"}, - ), - ("/items", {"session": "cookiesession"}, 200, {"ads_id": None}), - ], -) -def test(path, cookies, expected_status, expected_response): - from docs_src.cookie_params.tutorial001_py310 import app - - client = TestClient(app, cookies=cookies) - response = client.get(path) - assert response.status_code == expected_status - assert response.json() == expected_response - - -@needs_py310 -def test_openapi_schema(): - from docs_src.cookie_params.tutorial001_py310 import app - - client = TestClient(app) - response = client.get("/openapi.json") - assert response.status_code == 200 - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Ads Id", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Ads Id", "type": "string"} - ), - "name": "ads_id", - "in": "cookie", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py b/tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py index 34a18b12c..aff070d74 100644 --- a/tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py +++ b/tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py @@ -20,10 +20,8 @@ def client(): def test_swagger_ui_html(client: TestClient): response = client.get("/docs") assert response.status_code == 200, response.text - assert ( - "https://unpkg.com/swagger-ui-dist@5.9.0/swagger-ui-bundle.js" in response.text - ) - assert "https://unpkg.com/swagger-ui-dist@5.9.0/swagger-ui.css" in response.text + assert "https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js" in response.text + assert "https://unpkg.com/swagger-ui-dist@5/swagger-ui.css" in response.text def test_swagger_ui_oauth2_redirect_html(client: TestClient): diff --git a/tests/test_tutorial/test_custom_request_and_route/test_tutorial002.py b/tests/test_tutorial/test_custom_request_and_route/test_tutorial002.py index ad142ec88..6f7355aaa 100644 --- a/tests/test_tutorial/test_custom_request_and_route/test_tutorial002.py +++ b/tests/test_tutorial/test_custom_request_and_route/test_tutorial002.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from docs_src.custom_request_and_route.tutorial002 import app @@ -23,7 +22,6 @@ def test_exception_handler_body_access(): "loc": ["body"], "msg": "Input should be a valid list", "input": {"numbers": [1, 2, 3]}, - "url": match_pydantic_error_url("list_type"), } ], "body": '{"numbers": [1, 2, 3]}', diff --git a/tests/test_tutorial/test_custom_response/test_tutorial006c.py b/tests/test_tutorial/test_custom_response/test_tutorial006c.py index 51aa1833d..2675f2a93 100644 --- a/tests/test_tutorial/test_custom_response/test_tutorial006c.py +++ b/tests/test_tutorial/test_custom_response/test_tutorial006c.py @@ -8,7 +8,7 @@ client = TestClient(app) def test_redirect_status_code(): response = client.get("/pydantic", follow_redirects=False) assert response.status_code == 302 - assert response.headers["location"] == "https://pydantic-docs.helpmanual.io/" + assert response.headers["location"] == "https://docs.pydantic.dev/" def test_openapi_schema(): diff --git a/tests/test_tutorial/test_dataclasses/test_tutorial001.py b/tests/test_tutorial/test_dataclasses/test_tutorial001.py index 9f1200f37..762654d29 100644 --- a/tests/test_tutorial/test_dataclasses/test_tutorial001.py +++ b/tests/test_tutorial/test_dataclasses/test_tutorial001.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from docs_src.dataclasses.tutorial001 import app @@ -29,7 +28,6 @@ def test_post_invalid_item(): "loc": ["body", "price"], "msg": "Input should be a valid number, unable to parse string as a number", "input": "invalid price", - "url": match_pydantic_error_url("float_parsing"), } ] } diff --git a/tests/test_tutorial/test_dataclasses/test_tutorial002.py b/tests/test_tutorial/test_dataclasses/test_tutorial002.py index 4146f4cd6..e6d303cfc 100644 --- a/tests/test_tutorial/test_dataclasses/test_tutorial002.py +++ b/tests/test_tutorial/test_dataclasses/test_tutorial002.py @@ -12,7 +12,7 @@ def test_get_item(): assert response.json() == { "name": "Island In The Moon", "price": 12.99, - "description": "A place to be be playin' and havin' fun", + "description": "A place to be playin' and havin' fun", "tags": ["breater"], "tax": None, } diff --git a/tests/test_tutorial/test_dataclasses/test_tutorial003.py b/tests/test_tutorial/test_dataclasses/test_tutorial003.py index dd0e36735..e1fa45201 100644 --- a/tests/test_tutorial/test_dataclasses/test_tutorial003.py +++ b/tests/test_tutorial/test_dataclasses/test_tutorial003.py @@ -31,7 +31,7 @@ def test_get_authors(): "items": [ { "name": "Island In The Moon", - "description": "A place to be be playin' and havin' fun", + "description": "A place to be playin' and havin' fun", }, {"name": "Holy Buddies", "description": None}, ], diff --git a/tests/test_tutorial/test_dependencies/test_tutorial001.py b/tests/test_tutorial/test_dependencies/test_tutorial001.py index d1324a641..ed9944912 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial001.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial001.py @@ -1,10 +1,27 @@ +import importlib + import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from docs_src.dependencies.tutorial001 import app +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py310", marks=needs_py310), + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + pytest.param("tutorial001_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.dependencies.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client @pytest.mark.parametrize( @@ -17,13 +34,13 @@ client = TestClient(app) ("/users", 200, {"q": None, "skip": 0, "limit": 100}), ], ) -def test_get(path, expected_status, expected_response): +def test_get(path, expected_status, expected_response, client: TestClient): response = client.get(path) assert response.status_code == expected_status assert response.json() == expected_response -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_dependencies/test_tutorial001_an.py b/tests/test_tutorial/test_dependencies/test_tutorial001_an.py deleted file mode 100644 index 79c2a1e10..000000000 --- a/tests/test_tutorial/test_dependencies/test_tutorial001_an.py +++ /dev/null @@ -1,183 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from docs_src.dependencies.tutorial001_an import app - -client = TestClient(app) - - -@pytest.mark.parametrize( - "path,expected_status,expected_response", - [ - ("/items", 200, {"q": None, "skip": 0, "limit": 100}), - ("/items?q=foo", 200, {"q": "foo", "skip": 0, "limit": 100}), - ("/items?q=foo&skip=5", 200, {"q": "foo", "skip": 5, "limit": 100}), - ("/items?q=foo&skip=5&limit=30", 200, {"q": "foo", "skip": 5, "limit": 30}), - ("/users", 200, {"q": None, "skip": 0, "limit": 100}), - ], -) -def test_get(path, expected_status, expected_response): - response = client.get(path) - assert response.status_code == expected_status - assert response.json() == expected_response - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Q", "type": "string"} - ), - "name": "q", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - "/users/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Q", "type": "string"} - ), - "name": "q", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_dependencies/test_tutorial001_an_py310.py b/tests/test_tutorial/test_dependencies/test_tutorial001_an_py310.py deleted file mode 100644 index 7db55a1c5..000000000 --- a/tests/test_tutorial/test_dependencies/test_tutorial001_an_py310.py +++ /dev/null @@ -1,191 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.dependencies.tutorial001_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -@pytest.mark.parametrize( - "path,expected_status,expected_response", - [ - ("/items", 200, {"q": None, "skip": 0, "limit": 100}), - ("/items?q=foo", 200, {"q": "foo", "skip": 0, "limit": 100}), - ("/items?q=foo&skip=5", 200, {"q": "foo", "skip": 5, "limit": 100}), - ("/items?q=foo&skip=5&limit=30", 200, {"q": "foo", "skip": 5, "limit": 30}), - ("/users", 200, {"q": None, "skip": 0, "limit": 100}), - ], -) -def test_get(path, expected_status, expected_response, client: TestClient): - response = client.get(path) - assert response.status_code == expected_status - assert response.json() == expected_response - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Q", "type": "string"} - ), - "name": "q", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - "/users/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Q", "type": "string"} - ), - "name": "q", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_dependencies/test_tutorial001_an_py39.py b/tests/test_tutorial/test_dependencies/test_tutorial001_an_py39.py deleted file mode 100644 index 68c2dedb1..000000000 --- a/tests/test_tutorial/test_dependencies/test_tutorial001_an_py39.py +++ /dev/null @@ -1,191 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.dependencies.tutorial001_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -@pytest.mark.parametrize( - "path,expected_status,expected_response", - [ - ("/items", 200, {"q": None, "skip": 0, "limit": 100}), - ("/items?q=foo", 200, {"q": "foo", "skip": 0, "limit": 100}), - ("/items?q=foo&skip=5", 200, {"q": "foo", "skip": 5, "limit": 100}), - ("/items?q=foo&skip=5&limit=30", 200, {"q": "foo", "skip": 5, "limit": 30}), - ("/users", 200, {"q": None, "skip": 0, "limit": 100}), - ], -) -def test_get(path, expected_status, expected_response, client: TestClient): - response = client.get(path) - assert response.status_code == expected_status - assert response.json() == expected_response - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Q", "type": "string"} - ), - "name": "q", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - "/users/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Q", "type": "string"} - ), - "name": "q", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_dependencies/test_tutorial001_py310.py b/tests/test_tutorial/test_dependencies/test_tutorial001_py310.py deleted file mode 100644 index 381eecb63..000000000 --- a/tests/test_tutorial/test_dependencies/test_tutorial001_py310.py +++ /dev/null @@ -1,191 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.dependencies.tutorial001_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -@pytest.mark.parametrize( - "path,expected_status,expected_response", - [ - ("/items", 200, {"q": None, "skip": 0, "limit": 100}), - ("/items?q=foo", 200, {"q": "foo", "skip": 0, "limit": 100}), - ("/items?q=foo&skip=5", 200, {"q": "foo", "skip": 5, "limit": 100}), - ("/items?q=foo&skip=5&limit=30", 200, {"q": "foo", "skip": 5, "limit": 30}), - ("/users", 200, {"q": None, "skip": 0, "limit": 100}), - ], -) -def test_get(path, expected_status, expected_response, client: TestClient): - response = client.get(path) - assert response.status_code == expected_status - assert response.json() == expected_response - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Q", "type": "string"} - ), - "name": "q", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - "/users/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Q", "type": "string"} - ), - "name": "q", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_dependencies/test_tutorial004.py b/tests/test_tutorial/test_dependencies/test_tutorial004.py index 5c5d34cfc..8221c83d4 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial004.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial004.py @@ -1,10 +1,27 @@ +import importlib + import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from docs_src.dependencies.tutorial004 import app +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial004", + pytest.param("tutorial004_py310", marks=needs_py310), + "tutorial004_an", + pytest.param("tutorial004_an_py39", marks=needs_py39), + pytest.param("tutorial004_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.dependencies.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client @pytest.mark.parametrize( @@ -55,13 +72,13 @@ client = TestClient(app) ), ], ) -def test_get(path, expected_status, expected_response): +def test_get(path, expected_status, expected_response, client: TestClient): response = client.get(path) assert response.status_code == expected_status assert response.json() == expected_response -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_dependencies/test_tutorial004_an.py b/tests/test_tutorial/test_dependencies/test_tutorial004_an.py deleted file mode 100644 index c5c1a1fb8..000000000 --- a/tests/test_tutorial/test_dependencies/test_tutorial004_an.py +++ /dev/null @@ -1,162 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from docs_src.dependencies.tutorial004_an import app - -client = TestClient(app) - - -@pytest.mark.parametrize( - "path,expected_status,expected_response", - [ - ( - "/items", - 200, - { - "items": [ - {"item_name": "Foo"}, - {"item_name": "Bar"}, - {"item_name": "Baz"}, - ] - }, - ), - ( - "/items?q=foo", - 200, - { - "items": [ - {"item_name": "Foo"}, - {"item_name": "Bar"}, - {"item_name": "Baz"}, - ], - "q": "foo", - }, - ), - ( - "/items?q=foo&skip=1", - 200, - {"items": [{"item_name": "Bar"}, {"item_name": "Baz"}], "q": "foo"}, - ), - ( - "/items?q=bar&limit=2", - 200, - {"items": [{"item_name": "Foo"}, {"item_name": "Bar"}], "q": "bar"}, - ), - ( - "/items?q=bar&skip=1&limit=1", - 200, - {"items": [{"item_name": "Bar"}], "q": "bar"}, - ), - ( - "/items?limit=1&q=bar&skip=1", - 200, - {"items": [{"item_name": "Bar"}], "q": "bar"}, - ), - ], -) -def test_get(path, expected_status, expected_response): - response = client.get(path) - assert response.status_code == expected_status - assert response.json() == expected_response - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Q", "type": "string"} - ), - "name": "q", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_dependencies/test_tutorial004_an_py310.py b/tests/test_tutorial/test_dependencies/test_tutorial004_an_py310.py deleted file mode 100644 index 6fd093ddb..000000000 --- a/tests/test_tutorial/test_dependencies/test_tutorial004_an_py310.py +++ /dev/null @@ -1,170 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.dependencies.tutorial004_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -@pytest.mark.parametrize( - "path,expected_status,expected_response", - [ - ( - "/items", - 200, - { - "items": [ - {"item_name": "Foo"}, - {"item_name": "Bar"}, - {"item_name": "Baz"}, - ] - }, - ), - ( - "/items?q=foo", - 200, - { - "items": [ - {"item_name": "Foo"}, - {"item_name": "Bar"}, - {"item_name": "Baz"}, - ], - "q": "foo", - }, - ), - ( - "/items?q=foo&skip=1", - 200, - {"items": [{"item_name": "Bar"}, {"item_name": "Baz"}], "q": "foo"}, - ), - ( - "/items?q=bar&limit=2", - 200, - {"items": [{"item_name": "Foo"}, {"item_name": "Bar"}], "q": "bar"}, - ), - ( - "/items?q=bar&skip=1&limit=1", - 200, - {"items": [{"item_name": "Bar"}], "q": "bar"}, - ), - ( - "/items?limit=1&q=bar&skip=1", - 200, - {"items": [{"item_name": "Bar"}], "q": "bar"}, - ), - ], -) -def test_get(path, expected_status, expected_response, client: TestClient): - response = client.get(path) - assert response.status_code == expected_status - assert response.json() == expected_response - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Q", "type": "string"} - ), - "name": "q", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_dependencies/test_tutorial004_an_py39.py b/tests/test_tutorial/test_dependencies/test_tutorial004_an_py39.py deleted file mode 100644 index fbbe84cc9..000000000 --- a/tests/test_tutorial/test_dependencies/test_tutorial004_an_py39.py +++ /dev/null @@ -1,170 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.dependencies.tutorial004_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -@pytest.mark.parametrize( - "path,expected_status,expected_response", - [ - ( - "/items", - 200, - { - "items": [ - {"item_name": "Foo"}, - {"item_name": "Bar"}, - {"item_name": "Baz"}, - ] - }, - ), - ( - "/items?q=foo", - 200, - { - "items": [ - {"item_name": "Foo"}, - {"item_name": "Bar"}, - {"item_name": "Baz"}, - ], - "q": "foo", - }, - ), - ( - "/items?q=foo&skip=1", - 200, - {"items": [{"item_name": "Bar"}, {"item_name": "Baz"}], "q": "foo"}, - ), - ( - "/items?q=bar&limit=2", - 200, - {"items": [{"item_name": "Foo"}, {"item_name": "Bar"}], "q": "bar"}, - ), - ( - "/items?q=bar&skip=1&limit=1", - 200, - {"items": [{"item_name": "Bar"}], "q": "bar"}, - ), - ( - "/items?limit=1&q=bar&skip=1", - 200, - {"items": [{"item_name": "Bar"}], "q": "bar"}, - ), - ], -) -def test_get(path, expected_status, expected_response, client: TestClient): - response = client.get(path) - assert response.status_code == expected_status - assert response.json() == expected_response - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Q", "type": "string"} - ), - "name": "q", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_dependencies/test_tutorial004_py310.py b/tests/test_tutorial/test_dependencies/test_tutorial004_py310.py deleted file mode 100644 index 845b098e7..000000000 --- a/tests/test_tutorial/test_dependencies/test_tutorial004_py310.py +++ /dev/null @@ -1,170 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.dependencies.tutorial004_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -@pytest.mark.parametrize( - "path,expected_status,expected_response", - [ - ( - "/items", - 200, - { - "items": [ - {"item_name": "Foo"}, - {"item_name": "Bar"}, - {"item_name": "Baz"}, - ] - }, - ), - ( - "/items?q=foo", - 200, - { - "items": [ - {"item_name": "Foo"}, - {"item_name": "Bar"}, - {"item_name": "Baz"}, - ], - "q": "foo", - }, - ), - ( - "/items?q=foo&skip=1", - 200, - {"items": [{"item_name": "Bar"}, {"item_name": "Baz"}], "q": "foo"}, - ), - ( - "/items?q=bar&limit=2", - 200, - {"items": [{"item_name": "Foo"}, {"item_name": "Bar"}], "q": "bar"}, - ), - ( - "/items?q=bar&skip=1&limit=1", - 200, - {"items": [{"item_name": "Bar"}], "q": "bar"}, - ), - ( - "/items?limit=1&q=bar&skip=1", - 200, - {"items": [{"item_name": "Bar"}], "q": "bar"}, - ), - ], -) -def test_get(path, expected_status, expected_response, client: TestClient): - response = client.get(path) - assert response.status_code == expected_status - assert response.json() == expected_response - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Q", "type": "string"} - ), - "name": "q", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_dependencies/test_tutorial006.py b/tests/test_tutorial/test_dependencies/test_tutorial006.py index 704e389a5..4530762f7 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial006.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial006.py @@ -1,13 +1,28 @@ +import importlib + +import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url -from docs_src.dependencies.tutorial006 import app +from ...utils import needs_py39 + + +@pytest.fixture( + name="client", + params=[ + "tutorial006", + "tutorial006_an", + pytest.param("tutorial006_an_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.dependencies.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_get_no_headers(): +def test_get_no_headers(client: TestClient): response = client.get("/items/") assert response.status_code == 422, response.text assert response.json() == IsDict( @@ -18,14 +33,12 @@ def test_get_no_headers(): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["header", "x-key"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -48,13 +61,13 @@ def test_get_no_headers(): ) -def test_get_invalid_one_header(): +def test_get_invalid_one_header(client: TestClient): response = client.get("/items/", headers={"X-Token": "invalid"}) assert response.status_code == 400, response.text assert response.json() == {"detail": "X-Token header invalid"} -def test_get_invalid_second_header(): +def test_get_invalid_second_header(client: TestClient): response = client.get( "/items/", headers={"X-Token": "fake-super-secret-token", "X-Key": "invalid"} ) @@ -62,7 +75,7 @@ def test_get_invalid_second_header(): assert response.json() == {"detail": "X-Key header invalid"} -def test_get_valid_headers(): +def test_get_valid_headers(client: TestClient): response = client.get( "/items/", headers={ @@ -74,7 +87,7 @@ def test_get_valid_headers(): assert response.json() == [{"item": "Foo"}, {"item": "Bar"}] -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_dependencies/test_tutorial006_an.py b/tests/test_tutorial/test_dependencies/test_tutorial006_an.py deleted file mode 100644 index 5034fceba..000000000 --- a/tests/test_tutorial/test_dependencies/test_tutorial006_an.py +++ /dev/null @@ -1,152 +0,0 @@ -from dirty_equals import IsDict -from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url - -from docs_src.dependencies.tutorial006_an import app - -client = TestClient(app) - - -def test_get_no_headers(): - response = client.get("/items/") - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["header", "x-token"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - { - "type": "missing", - "loc": ["header", "x-key"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["header", "x-key"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_get_invalid_one_header(): - response = client.get("/items/", headers={"X-Token": "invalid"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "X-Token header invalid"} - - -def test_get_invalid_second_header(): - response = client.get( - "/items/", headers={"X-Token": "fake-super-secret-token", "X-Key": "invalid"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "X-Key header invalid"} - - -def test_get_valid_headers(): - response = client.get( - "/items/", - headers={ - "X-Token": "fake-super-secret-token", - "X-Key": "fake-super-secret-key", - }, - ) - assert response.status_code == 200, response.text - assert response.json() == [{"item": "Foo"}, {"item": "Bar"}] - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": True, - "schema": {"title": "X-Token", "type": "string"}, - "name": "x-token", - "in": "header", - }, - { - "required": True, - "schema": {"title": "X-Key", "type": "string"}, - "name": "x-key", - "in": "header", - }, - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_dependencies/test_tutorial006_an_py39.py b/tests/test_tutorial/test_dependencies/test_tutorial006_an_py39.py deleted file mode 100644 index 3fc22dd3c..000000000 --- a/tests/test_tutorial/test_dependencies/test_tutorial006_an_py39.py +++ /dev/null @@ -1,164 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.dependencies.tutorial006_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_get_no_headers(client: TestClient): - response = client.get("/items/") - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["header", "x-token"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - { - "type": "missing", - "loc": ["header", "x-key"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["header", "x-key"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_get_invalid_one_header(client: TestClient): - response = client.get("/items/", headers={"X-Token": "invalid"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "X-Token header invalid"} - - -@needs_py39 -def test_get_invalid_second_header(client: TestClient): - response = client.get( - "/items/", headers={"X-Token": "fake-super-secret-token", "X-Key": "invalid"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "X-Key header invalid"} - - -@needs_py39 -def test_get_valid_headers(client: TestClient): - response = client.get( - "/items/", - headers={ - "X-Token": "fake-super-secret-token", - "X-Key": "fake-super-secret-key", - }, - ) - assert response.status_code == 200, response.text - assert response.json() == [{"item": "Foo"}, {"item": "Bar"}] - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": True, - "schema": {"title": "X-Token", "type": "string"}, - "name": "x-token", - "in": "header", - }, - { - "required": True, - "schema": {"title": "X-Key", "type": "string"}, - "name": "x-key", - "in": "header", - }, - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008b.py b/tests/test_tutorial/test_dependencies/test_tutorial008b.py index 86acba9e4..4d7092265 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial008b.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial008b.py @@ -1,23 +1,39 @@ +import importlib + +import pytest from fastapi.testclient import TestClient -from docs_src.dependencies.tutorial008b import app +from ...utils import needs_py39 + + +@pytest.fixture( + name="client", + params=[ + "tutorial008b", + "tutorial008b_an", + pytest.param("tutorial008b_an_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.dependencies.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_get_no_item(): +def test_get_no_item(client: TestClient): response = client.get("/items/foo") assert response.status_code == 404, response.text assert response.json() == {"detail": "Item not found"} -def test_owner_error(): +def test_owner_error(client: TestClient): response = client.get("/items/plumbus") assert response.status_code == 400, response.text assert response.json() == {"detail": "Owner error: Rick"} -def test_get_item(): +def test_get_item(client: TestClient): response = client.get("/items/portal-gun") assert response.status_code == 200, response.text assert response.json() == {"description": "Gun to create portals", "owner": "Rick"} diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008b_an.py b/tests/test_tutorial/test_dependencies/test_tutorial008b_an.py deleted file mode 100644 index 7f51fc52a..000000000 --- a/tests/test_tutorial/test_dependencies/test_tutorial008b_an.py +++ /dev/null @@ -1,23 +0,0 @@ -from fastapi.testclient import TestClient - -from docs_src.dependencies.tutorial008b_an import app - -client = TestClient(app) - - -def test_get_no_item(): - response = client.get("/items/foo") - assert response.status_code == 404, response.text - assert response.json() == {"detail": "Item not found"} - - -def test_owner_error(): - response = client.get("/items/plumbus") - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Owner error: Rick"} - - -def test_get_item(): - response = client.get("/items/portal-gun") - assert response.status_code == 200, response.text - assert response.json() == {"description": "Gun to create portals", "owner": "Rick"} diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008b_an_py39.py b/tests/test_tutorial/test_dependencies/test_tutorial008b_an_py39.py deleted file mode 100644 index 7f51fc52a..000000000 --- a/tests/test_tutorial/test_dependencies/test_tutorial008b_an_py39.py +++ /dev/null @@ -1,23 +0,0 @@ -from fastapi.testclient import TestClient - -from docs_src.dependencies.tutorial008b_an import app - -client = TestClient(app) - - -def test_get_no_item(): - response = client.get("/items/foo") - assert response.status_code == 404, response.text - assert response.json() == {"detail": "Item not found"} - - -def test_owner_error(): - response = client.get("/items/plumbus") - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Owner error: Rick"} - - -def test_get_item(): - response = client.get("/items/portal-gun") - assert response.status_code == 200, response.text - assert response.json() == {"description": "Gun to create portals", "owner": "Rick"} diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008c.py b/tests/test_tutorial/test_dependencies/test_tutorial008c.py new file mode 100644 index 000000000..11e96bf46 --- /dev/null +++ b/tests/test_tutorial/test_dependencies/test_tutorial008c.py @@ -0,0 +1,50 @@ +import importlib +from types import ModuleType + +import pytest +from fastapi.exceptions import FastAPIError +from fastapi.testclient import TestClient + +from ...utils import needs_py39 + + +@pytest.fixture( + name="mod", + params=[ + "tutorial008c", + "tutorial008c_an", + pytest.param("tutorial008c_an_py39", marks=needs_py39), + ], +) +def get_mod(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.dependencies.{request.param}") + + return mod + + +def test_get_no_item(mod: ModuleType): + client = TestClient(mod.app) + response = client.get("/items/foo") + assert response.status_code == 404, response.text + assert response.json() == {"detail": "Item not found, there's only a plumbus here"} + + +def test_get(mod: ModuleType): + client = TestClient(mod.app) + response = client.get("/items/plumbus") + assert response.status_code == 200, response.text + assert response.json() == "plumbus" + + +def test_fastapi_error(mod: ModuleType): + client = TestClient(mod.app) + with pytest.raises(FastAPIError) as exc_info: + client.get("/items/portal-gun") + assert "No response object was returned" in exc_info.value.args[0] + + +def test_internal_server_error(mod: ModuleType): + client = TestClient(mod.app, raise_server_exceptions=False) + response = client.get("/items/portal-gun") + assert response.status_code == 500, response.text + assert response.text == "Internal Server Error" diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008d.py b/tests/test_tutorial/test_dependencies/test_tutorial008d.py new file mode 100644 index 000000000..bc99bb383 --- /dev/null +++ b/tests/test_tutorial/test_dependencies/test_tutorial008d.py @@ -0,0 +1,51 @@ +import importlib +from types import ModuleType + +import pytest +from fastapi.testclient import TestClient + +from ...utils import needs_py39 + + +@pytest.fixture( + name="mod", + params=[ + "tutorial008d", + "tutorial008d_an", + pytest.param("tutorial008d_an_py39", marks=needs_py39), + ], +) +def get_mod(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.dependencies.{request.param}") + + return mod + + +def test_get_no_item(mod: ModuleType): + client = TestClient(mod.app) + response = client.get("/items/foo") + assert response.status_code == 404, response.text + assert response.json() == {"detail": "Item not found, there's only a plumbus here"} + + +def test_get(mod: ModuleType): + client = TestClient(mod.app) + response = client.get("/items/plumbus") + assert response.status_code == 200, response.text + assert response.json() == "plumbus" + + +def test_internal_error(mod: ModuleType): + client = TestClient(mod.app) + with pytest.raises(mod.InternalError) as exc_info: + client.get("/items/portal-gun") + assert ( + exc_info.value.args[0] == "The portal gun is too dangerous to be owned by Rick" + ) + + +def test_internal_server_error(mod: ModuleType): + client = TestClient(mod.app, raise_server_exceptions=False) + response = client.get("/items/portal-gun") + assert response.status_code == 500, response.text + assert response.text == "Internal Server Error" diff --git a/tests/test_tutorial/test_dependencies/test_tutorial012.py b/tests/test_tutorial/test_dependencies/test_tutorial012.py index 753e62e43..0af17e9bc 100644 --- a/tests/test_tutorial/test_dependencies/test_tutorial012.py +++ b/tests/test_tutorial/test_dependencies/test_tutorial012.py @@ -1,13 +1,28 @@ +import importlib + +import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url -from docs_src.dependencies.tutorial012 import app +from ...utils import needs_py39 + + +@pytest.fixture( + name="client", + params=[ + "tutorial012", + "tutorial012_an", + pytest.param("tutorial012_an_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.dependencies.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_get_no_headers_items(): +def test_get_no_headers_items(client: TestClient): response = client.get("/items/") assert response.status_code == 422, response.text assert response.json() == IsDict( @@ -18,14 +33,12 @@ def test_get_no_headers_items(): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["header", "x-key"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -48,7 +61,7 @@ def test_get_no_headers_items(): ) -def test_get_no_headers_users(): +def test_get_no_headers_users(client: TestClient): response = client.get("/users/") assert response.status_code == 422, response.text assert response.json() == IsDict( @@ -59,14 +72,12 @@ def test_get_no_headers_users(): "loc": ["header", "x-token"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "missing", "loc": ["header", "x-key"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, ] } @@ -89,19 +100,19 @@ def test_get_no_headers_users(): ) -def test_get_invalid_one_header_items(): +def test_get_invalid_one_header_items(client: TestClient): response = client.get("/items/", headers={"X-Token": "invalid"}) assert response.status_code == 400, response.text assert response.json() == {"detail": "X-Token header invalid"} -def test_get_invalid_one_users(): +def test_get_invalid_one_users(client: TestClient): response = client.get("/users/", headers={"X-Token": "invalid"}) assert response.status_code == 400, response.text assert response.json() == {"detail": "X-Token header invalid"} -def test_get_invalid_second_header_items(): +def test_get_invalid_second_header_items(client: TestClient): response = client.get( "/items/", headers={"X-Token": "fake-super-secret-token", "X-Key": "invalid"} ) @@ -109,7 +120,7 @@ def test_get_invalid_second_header_items(): assert response.json() == {"detail": "X-Key header invalid"} -def test_get_invalid_second_header_users(): +def test_get_invalid_second_header_users(client: TestClient): response = client.get( "/users/", headers={"X-Token": "fake-super-secret-token", "X-Key": "invalid"} ) @@ -117,7 +128,7 @@ def test_get_invalid_second_header_users(): assert response.json() == {"detail": "X-Key header invalid"} -def test_get_valid_headers_items(): +def test_get_valid_headers_items(client: TestClient): response = client.get( "/items/", headers={ @@ -129,7 +140,7 @@ def test_get_valid_headers_items(): assert response.json() == [{"item": "Portal Gun"}, {"item": "Plumbus"}] -def test_get_valid_headers_users(): +def test_get_valid_headers_users(client: TestClient): response = client.get( "/users/", headers={ @@ -141,7 +152,7 @@ def test_get_valid_headers_users(): assert response.json() == [{"username": "Rick"}, {"username": "Morty"}] -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_dependencies/test_tutorial012_an.py b/tests/test_tutorial/test_dependencies/test_tutorial012_an.py deleted file mode 100644 index 4157d4612..000000000 --- a/tests/test_tutorial/test_dependencies/test_tutorial012_an.py +++ /dev/null @@ -1,255 +0,0 @@ -from dirty_equals import IsDict -from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url - -from docs_src.dependencies.tutorial012_an import app - -client = TestClient(app) - - -def test_get_no_headers_items(): - response = client.get("/items/") - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["header", "x-token"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - { - "type": "missing", - "loc": ["header", "x-key"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["header", "x-key"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_get_no_headers_users(): - response = client.get("/users/") - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["header", "x-token"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - { - "type": "missing", - "loc": ["header", "x-key"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["header", "x-key"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_get_invalid_one_header_items(): - response = client.get("/items/", headers={"X-Token": "invalid"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "X-Token header invalid"} - - -def test_get_invalid_one_users(): - response = client.get("/users/", headers={"X-Token": "invalid"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "X-Token header invalid"} - - -def test_get_invalid_second_header_items(): - response = client.get( - "/items/", headers={"X-Token": "fake-super-secret-token", "X-Key": "invalid"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "X-Key header invalid"} - - -def test_get_invalid_second_header_users(): - response = client.get( - "/users/", headers={"X-Token": "fake-super-secret-token", "X-Key": "invalid"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "X-Key header invalid"} - - -def test_get_valid_headers_items(): - response = client.get( - "/items/", - headers={ - "X-Token": "fake-super-secret-token", - "X-Key": "fake-super-secret-key", - }, - ) - assert response.status_code == 200, response.text - assert response.json() == [{"item": "Portal Gun"}, {"item": "Plumbus"}] - - -def test_get_valid_headers_users(): - response = client.get( - "/users/", - headers={ - "X-Token": "fake-super-secret-token", - "X-Key": "fake-super-secret-key", - }, - ) - assert response.status_code == 200, response.text - assert response.json() == [{"username": "Rick"}, {"username": "Morty"}] - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": True, - "schema": {"title": "X-Token", "type": "string"}, - "name": "x-token", - "in": "header", - }, - { - "required": True, - "schema": {"title": "X-Key", "type": "string"}, - "name": "x-key", - "in": "header", - }, - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/users/": { - "get": { - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": True, - "schema": {"title": "X-Token", "type": "string"}, - "name": "x-token", - "in": "header", - }, - { - "required": True, - "schema": {"title": "X-Key", "type": "string"}, - "name": "x-key", - "in": "header", - }, - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_dependencies/test_tutorial012_an_py39.py b/tests/test_tutorial/test_dependencies/test_tutorial012_an_py39.py deleted file mode 100644 index 9e46758cb..000000000 --- a/tests/test_tutorial/test_dependencies/test_tutorial012_an_py39.py +++ /dev/null @@ -1,271 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.dependencies.tutorial012_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_get_no_headers_items(client: TestClient): - response = client.get("/items/") - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["header", "x-token"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - { - "type": "missing", - "loc": ["header", "x-key"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["header", "x-key"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_get_no_headers_users(client: TestClient): - response = client.get("/users/") - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["header", "x-token"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - { - "type": "missing", - "loc": ["header", "x-key"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["header", "x-token"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["header", "x-key"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_get_invalid_one_header_items(client: TestClient): - response = client.get("/items/", headers={"X-Token": "invalid"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "X-Token header invalid"} - - -@needs_py39 -def test_get_invalid_one_users(client: TestClient): - response = client.get("/users/", headers={"X-Token": "invalid"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "X-Token header invalid"} - - -@needs_py39 -def test_get_invalid_second_header_items(client: TestClient): - response = client.get( - "/items/", headers={"X-Token": "fake-super-secret-token", "X-Key": "invalid"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "X-Key header invalid"} - - -@needs_py39 -def test_get_invalid_second_header_users(client: TestClient): - response = client.get( - "/users/", headers={"X-Token": "fake-super-secret-token", "X-Key": "invalid"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "X-Key header invalid"} - - -@needs_py39 -def test_get_valid_headers_items(client: TestClient): - response = client.get( - "/items/", - headers={ - "X-Token": "fake-super-secret-token", - "X-Key": "fake-super-secret-key", - }, - ) - assert response.status_code == 200, response.text - assert response.json() == [{"item": "Portal Gun"}, {"item": "Plumbus"}] - - -@needs_py39 -def test_get_valid_headers_users(client: TestClient): - response = client.get( - "/users/", - headers={ - "X-Token": "fake-super-secret-token", - "X-Key": "fake-super-secret-key", - }, - ) - assert response.status_code == 200, response.text - assert response.json() == [{"username": "Rick"}, {"username": "Morty"}] - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": True, - "schema": {"title": "X-Token", "type": "string"}, - "name": "x-token", - "in": "header", - }, - { - "required": True, - "schema": {"title": "X-Key", "type": "string"}, - "name": "x-key", - "in": "header", - }, - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/users/": { - "get": { - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": True, - "schema": {"title": "X-Token", "type": "string"}, - "name": "x-token", - "in": "header", - }, - { - "required": True, - "schema": {"title": "X-Key", "type": "string"}, - "name": "x-key", - "in": "header", - }, - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_extra_data_types/test_tutorial001.py b/tests/test_tutorial/test_extra_data_types/test_tutorial001.py index 7710446ce..b816c9cab 100644 --- a/tests/test_tutorial/test_extra_data_types/test_tutorial001.py +++ b/tests/test_tutorial/test_extra_data_types/test_tutorial001.py @@ -1,12 +1,30 @@ +import importlib + +import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from docs_src.extra_data_types.tutorial001 import app +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py310", marks=needs_py310), + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + pytest.param("tutorial001_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.extra_data_types.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_extra_types(): +def test_extra_types(client: TestClient): item_id = "ff97dd87-a4a5-4a12-b412-cde99f33e00e" data = { "start_datetime": "2018-12-22T14:00:00+00:00", @@ -27,7 +45,7 @@ def test_extra_types(): assert response.json() == expected_response -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { @@ -67,6 +85,7 @@ def test_openapi_schema(): } ], "requestBody": { + "required": True, "content": { "application/json": { "schema": IsDict( @@ -86,7 +105,7 @@ def test_openapi_schema(): } ) } - } + }, }, } } @@ -97,40 +116,16 @@ def test_openapi_schema(): "title": "Body_read_items_items__item_id__put", "type": "object", "properties": { - "start_datetime": IsDict( - { - "title": "Start Datetime", - "anyOf": [ - {"type": "string", "format": "date-time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Start Datetime", - "type": "string", - "format": "date-time", - } - ), - "end_datetime": IsDict( - { - "title": "End Datetime", - "anyOf": [ - {"type": "string", "format": "date-time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "End Datetime", - "type": "string", - "format": "date-time", - } - ), + "start_datetime": { + "title": "Start Datetime", + "type": "string", + "format": "date-time", + }, + "end_datetime": { + "title": "End Datetime", + "type": "string", + "format": "date-time", + }, "repeat_at": IsDict( { "title": "Repeat At", @@ -151,10 +146,8 @@ def test_openapi_schema(): "process_after": IsDict( { "title": "Process After", - "anyOf": [ - {"type": "string", "format": "duration"}, - {"type": "null"}, - ], + "type": "string", + "format": "duration", } ) | IsDict( @@ -166,6 +159,7 @@ def test_openapi_schema(): } ), }, + "required": ["start_datetime", "end_datetime", "process_after"], }, "ValidationError": { "title": "ValidationError", diff --git a/tests/test_tutorial/test_extra_data_types/test_tutorial001_an.py b/tests/test_tutorial/test_extra_data_types/test_tutorial001_an.py deleted file mode 100644 index 9951b3b51..000000000 --- a/tests/test_tutorial/test_extra_data_types/test_tutorial001_an.py +++ /dev/null @@ -1,199 +0,0 @@ -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from docs_src.extra_data_types.tutorial001_an import app - -client = TestClient(app) - - -def test_extra_types(): - item_id = "ff97dd87-a4a5-4a12-b412-cde99f33e00e" - data = { - "start_datetime": "2018-12-22T14:00:00+00:00", - "end_datetime": "2018-12-24T15:00:00+00:00", - "repeat_at": "15:30:00", - "process_after": 300, - } - expected_response = data.copy() - expected_response.update( - { - "start_process": "2018-12-22T14:05:00+00:00", - "duration": 176_100, - "item_id": item_id, - } - ) - response = client.put(f"/items/{item_id}", json=data) - assert response.status_code == 200, response.text - assert response.json() == expected_response - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": { - "title": "Item Id", - "type": "string", - "format": "uuid", - }, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict( - { - "allOf": [ - { - "$ref": "#/components/schemas/Body_read_items_items__item_id__put" - } - ], - "title": "Body", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "$ref": "#/components/schemas/Body_read_items_items__item_id__put" - } - ) - } - } - }, - } - } - }, - "components": { - "schemas": { - "Body_read_items_items__item_id__put": { - "title": "Body_read_items_items__item_id__put", - "type": "object", - "properties": { - "start_datetime": IsDict( - { - "title": "Start Datetime", - "anyOf": [ - {"type": "string", "format": "date-time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Start Datetime", - "type": "string", - "format": "date-time", - } - ), - "end_datetime": IsDict( - { - "title": "End Datetime", - "anyOf": [ - {"type": "string", "format": "date-time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "End Datetime", - "type": "string", - "format": "date-time", - } - ), - "repeat_at": IsDict( - { - "title": "Repeat At", - "anyOf": [ - {"type": "string", "format": "time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Repeat At", - "type": "string", - "format": "time", - } - ), - "process_after": IsDict( - { - "title": "Process After", - "anyOf": [ - {"type": "string", "format": "duration"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Process After", - "type": "number", - "format": "time-delta", - } - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py310.py b/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py310.py deleted file mode 100644 index 7c482b8cb..000000000 --- a/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py310.py +++ /dev/null @@ -1,208 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.extra_data_types.tutorial001_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_extra_types(client: TestClient): - item_id = "ff97dd87-a4a5-4a12-b412-cde99f33e00e" - data = { - "start_datetime": "2018-12-22T14:00:00+00:00", - "end_datetime": "2018-12-24T15:00:00+00:00", - "repeat_at": "15:30:00", - "process_after": 300, - } - expected_response = data.copy() - expected_response.update( - { - "start_process": "2018-12-22T14:05:00+00:00", - "duration": 176_100, - "item_id": item_id, - } - ) - response = client.put(f"/items/{item_id}", json=data) - assert response.status_code == 200, response.text - assert response.json() == expected_response - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": { - "title": "Item Id", - "type": "string", - "format": "uuid", - }, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict( - { - "allOf": [ - { - "$ref": "#/components/schemas/Body_read_items_items__item_id__put" - } - ], - "title": "Body", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "$ref": "#/components/schemas/Body_read_items_items__item_id__put" - } - ) - } - } - }, - } - } - }, - "components": { - "schemas": { - "Body_read_items_items__item_id__put": { - "title": "Body_read_items_items__item_id__put", - "type": "object", - "properties": { - "start_datetime": IsDict( - { - "title": "Start Datetime", - "anyOf": [ - {"type": "string", "format": "date-time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Start Datetime", - "type": "string", - "format": "date-time", - } - ), - "end_datetime": IsDict( - { - "title": "End Datetime", - "anyOf": [ - {"type": "string", "format": "date-time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "End Datetime", - "type": "string", - "format": "date-time", - } - ), - "repeat_at": IsDict( - { - "title": "Repeat At", - "anyOf": [ - {"type": "string", "format": "time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Repeat At", - "type": "string", - "format": "time", - } - ), - "process_after": IsDict( - { - "title": "Process After", - "anyOf": [ - {"type": "string", "format": "duration"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Process After", - "type": "number", - "format": "time-delta", - } - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py39.py b/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py39.py deleted file mode 100644 index 87473867b..000000000 --- a/tests/test_tutorial/test_extra_data_types/test_tutorial001_an_py39.py +++ /dev/null @@ -1,208 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.extra_data_types.tutorial001_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_extra_types(client: TestClient): - item_id = "ff97dd87-a4a5-4a12-b412-cde99f33e00e" - data = { - "start_datetime": "2018-12-22T14:00:00+00:00", - "end_datetime": "2018-12-24T15:00:00+00:00", - "repeat_at": "15:30:00", - "process_after": 300, - } - expected_response = data.copy() - expected_response.update( - { - "start_process": "2018-12-22T14:05:00+00:00", - "duration": 176_100, - "item_id": item_id, - } - ) - response = client.put(f"/items/{item_id}", json=data) - assert response.status_code == 200, response.text - assert response.json() == expected_response - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": { - "title": "Item Id", - "type": "string", - "format": "uuid", - }, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict( - { - "allOf": [ - { - "$ref": "#/components/schemas/Body_read_items_items__item_id__put" - } - ], - "title": "Body", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "$ref": "#/components/schemas/Body_read_items_items__item_id__put" - } - ) - } - } - }, - } - } - }, - "components": { - "schemas": { - "Body_read_items_items__item_id__put": { - "title": "Body_read_items_items__item_id__put", - "type": "object", - "properties": { - "start_datetime": IsDict( - { - "title": "Start Datetime", - "anyOf": [ - {"type": "string", "format": "date-time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Start Datetime", - "type": "string", - "format": "date-time", - } - ), - "end_datetime": IsDict( - { - "title": "End Datetime", - "anyOf": [ - {"type": "string", "format": "date-time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "End Datetime", - "type": "string", - "format": "date-time", - } - ), - "repeat_at": IsDict( - { - "title": "Repeat At", - "anyOf": [ - {"type": "string", "format": "time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Repeat At", - "type": "string", - "format": "time", - } - ), - "process_after": IsDict( - { - "title": "Process After", - "anyOf": [ - {"type": "string", "format": "duration"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Process After", - "type": "number", - "format": "time-delta", - } - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_extra_data_types/test_tutorial001_py310.py b/tests/test_tutorial/test_extra_data_types/test_tutorial001_py310.py deleted file mode 100644 index 0b71d9177..000000000 --- a/tests/test_tutorial/test_extra_data_types/test_tutorial001_py310.py +++ /dev/null @@ -1,208 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.extra_data_types.tutorial001_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_extra_types(client: TestClient): - item_id = "ff97dd87-a4a5-4a12-b412-cde99f33e00e" - data = { - "start_datetime": "2018-12-22T14:00:00+00:00", - "end_datetime": "2018-12-24T15:00:00+00:00", - "repeat_at": "15:30:00", - "process_after": 300, - } - expected_response = data.copy() - expected_response.update( - { - "start_process": "2018-12-22T14:05:00+00:00", - "duration": 176_100, - "item_id": item_id, - } - ) - response = client.put(f"/items/{item_id}", json=data) - assert response.status_code == 200, response.text - assert response.json() == expected_response - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": { - "title": "Item Id", - "type": "string", - "format": "uuid", - }, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict( - { - "allOf": [ - { - "$ref": "#/components/schemas/Body_read_items_items__item_id__put" - } - ], - "title": "Body", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "$ref": "#/components/schemas/Body_read_items_items__item_id__put" - } - ) - } - } - }, - } - } - }, - "components": { - "schemas": { - "Body_read_items_items__item_id__put": { - "title": "Body_read_items_items__item_id__put", - "type": "object", - "properties": { - "start_datetime": IsDict( - { - "title": "Start Datetime", - "anyOf": [ - {"type": "string", "format": "date-time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Start Datetime", - "type": "string", - "format": "date-time", - } - ), - "end_datetime": IsDict( - { - "title": "End Datetime", - "anyOf": [ - {"type": "string", "format": "date-time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "End Datetime", - "type": "string", - "format": "date-time", - } - ), - "repeat_at": IsDict( - { - "title": "Repeat At", - "anyOf": [ - {"type": "string", "format": "time"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Repeat At", - "type": "string", - "format": "time", - } - ), - "process_after": IsDict( - { - "title": "Process After", - "anyOf": [ - {"type": "string", "format": "duration"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Process After", - "type": "number", - "format": "time-delta", - } - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_extra_models/test_tutorial003.py b/tests/test_tutorial/test_extra_models/test_tutorial003.py index 0ccb99948..73aa29903 100644 --- a/tests/test_tutorial/test_extra_models/test_tutorial003.py +++ b/tests/test_tutorial/test_extra_models/test_tutorial003.py @@ -1,12 +1,27 @@ +import importlib + +import pytest from dirty_equals import IsOneOf from fastapi.testclient import TestClient -from docs_src.extra_models.tutorial003 import app +from ...utils import needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial003", + pytest.param("tutorial003_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.extra_models.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_get_car(): +def test_get_car(client: TestClient): response = client.get("/items/item1") assert response.status_code == 200, response.text assert response.json() == { @@ -15,7 +30,7 @@ def test_get_car(): } -def test_get_plane(): +def test_get_plane(client: TestClient): response = client.get("/items/item2") assert response.status_code == 200, response.text assert response.json() == { @@ -25,7 +40,7 @@ def test_get_plane(): } -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_extra_models/test_tutorial003_py310.py b/tests/test_tutorial/test_extra_models/test_tutorial003_py310.py deleted file mode 100644 index b2fe65fd9..000000000 --- a/tests/test_tutorial/test_extra_models/test_tutorial003_py310.py +++ /dev/null @@ -1,144 +0,0 @@ -import pytest -from dirty_equals import IsOneOf -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.extra_models.tutorial003_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_get_car(client: TestClient): - response = client.get("/items/item1") - assert response.status_code == 200, response.text - assert response.json() == { - "description": "All my friends drive a low rider", - "type": "car", - } - - -@needs_py310 -def test_get_plane(client: TestClient): - response = client.get("/items/item2") - assert response.status_code == 200, response.text - assert response.json() == { - "description": "Music is my aeroplane, it's my aeroplane", - "type": "plane", - "size": 5, - } - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Item Items Item Id Get", - "anyOf": [ - {"$ref": "#/components/schemas/PlaneItem"}, - {"$ref": "#/components/schemas/CarItem"}, - ], - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Item", - "operationId": "read_item_items__item_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - } - ], - } - } - }, - "components": { - "schemas": { - "PlaneItem": { - "title": "PlaneItem", - "required": IsOneOf( - ["description", "type", "size"], - # TODO: remove when deprecating Pydantic v1 - ["description", "size"], - ), - "type": "object", - "properties": { - "description": {"title": "Description", "type": "string"}, - "type": {"title": "Type", "type": "string", "default": "plane"}, - "size": {"title": "Size", "type": "integer"}, - }, - }, - "CarItem": { - "title": "CarItem", - "required": IsOneOf( - ["description", "type"], - # TODO: remove when deprecating Pydantic v1 - ["description"], - ), - "type": "object", - "properties": { - "description": {"title": "Description", "type": "string"}, - "type": {"title": "Type", "type": "string", "default": "car"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_extra_models/test_tutorial004.py b/tests/test_tutorial/test_extra_models/test_tutorial004.py index 71f6a8c70..7628db30c 100644 --- a/tests/test_tutorial/test_extra_models/test_tutorial004.py +++ b/tests/test_tutorial/test_extra_models/test_tutorial004.py @@ -1,11 +1,26 @@ +import importlib + +import pytest from fastapi.testclient import TestClient -from docs_src.extra_models.tutorial004 import app +from ...utils import needs_py39 + + +@pytest.fixture( + name="client", + params=[ + "tutorial004", + pytest.param("tutorial004_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.extra_models.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_get_items(): +def test_get_items(client: TestClient): response = client.get("/items/") assert response.status_code == 200, response.text assert response.json() == [ @@ -14,7 +29,7 @@ def test_get_items(): ] -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_extra_models/test_tutorial004_py39.py b/tests/test_tutorial/test_extra_models/test_tutorial004_py39.py deleted file mode 100644 index 5475b92e1..000000000 --- a/tests/test_tutorial/test_extra_models/test_tutorial004_py39.py +++ /dev/null @@ -1,67 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.extra_models.tutorial004_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_get_items(client: TestClient): - response = client.get("/items/") - assert response.status_code == 200, response.text - assert response.json() == [ - {"name": "Foo", "description": "There comes my hero"}, - {"name": "Red", "description": "It's my aeroplane"}, - ] - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Items Items Get", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - } - } - }, - } - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "description"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": {"title": "Description", "type": "string"}, - }, - } - } - }, - } diff --git a/tests/test_tutorial/test_extra_models/test_tutorial005.py b/tests/test_tutorial/test_extra_models/test_tutorial005.py index b0861c37f..553e44238 100644 --- a/tests/test_tutorial/test_extra_models/test_tutorial005.py +++ b/tests/test_tutorial/test_extra_models/test_tutorial005.py @@ -1,17 +1,32 @@ +import importlib + +import pytest from fastapi.testclient import TestClient -from docs_src.extra_models.tutorial005 import app +from ...utils import needs_py39 + + +@pytest.fixture( + name="client", + params=[ + "tutorial005", + pytest.param("tutorial005_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.extra_models.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_get_items(): +def test_get_items(client: TestClient): response = client.get("/keyword-weights/") assert response.status_code == 200, response.text assert response.json() == {"foo": 2.3, "bar": 3.4} -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_extra_models/test_tutorial005_py39.py b/tests/test_tutorial/test_extra_models/test_tutorial005_py39.py deleted file mode 100644 index 7278e93c3..000000000 --- a/tests/test_tutorial/test_extra_models/test_tutorial005_py39.py +++ /dev/null @@ -1,51 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.extra_models.tutorial005_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_get_items(client: TestClient): - response = client.get("/keyword-weights/") - assert response.status_code == 200, response.text - assert response.json() == {"foo": 2.3, "bar": 3.4} - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/keyword-weights/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Keyword Weights Keyword Weights Get", - "type": "object", - "additionalProperties": {"type": "number"}, - } - } - }, - } - }, - "summary": "Read Keyword Weights", - "operationId": "read_keyword_weights_keyword_weights__get", - } - } - }, - } diff --git a/tests/test_tutorial/test_handling_errors/test_tutorial005.py b/tests/test_tutorial/test_handling_errors/test_tutorial005.py index 494c317ca..581b2e4c7 100644 --- a/tests/test_tutorial/test_handling_errors/test_tutorial005.py +++ b/tests/test_tutorial/test_handling_errors/test_tutorial005.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from docs_src.handling_errors.tutorial005 import app @@ -18,7 +17,6 @@ def test_post_validation_error(): "loc": ["body", "size"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "XL", - "url": match_pydantic_error_url("int_parsing"), } ], "body": {"title": "towel", "size": "XL"}, diff --git a/tests/test_tutorial/test_handling_errors/test_tutorial006.py b/tests/test_tutorial/test_handling_errors/test_tutorial006.py index cc2b496a8..7d2f553aa 100644 --- a/tests/test_tutorial/test_handling_errors/test_tutorial006.py +++ b/tests/test_tutorial/test_handling_errors/test_tutorial006.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from docs_src.handling_errors.tutorial006 import app @@ -18,7 +17,6 @@ def test_get_validation_error(): "loc": ["path", "item_id"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "foo", - "url": match_pydantic_error_url("int_parsing"), } ] } diff --git a/docs_src/sql_databases/sql_app/tests/__init__.py b/tests/test_tutorial/test_header_param_models/__init__.py similarity index 100% rename from docs_src/sql_databases/sql_app/tests/__init__.py rename to tests/test_tutorial/test_header_param_models/__init__.py diff --git a/tests/test_tutorial/test_header_param_models/test_tutorial001.py b/tests/test_tutorial/test_header_param_models/test_tutorial001.py new file mode 100644 index 000000000..06b2404cf --- /dev/null +++ b/tests/test_tutorial/test_header_param_models/test_tutorial001.py @@ -0,0 +1,238 @@ +import importlib + +import pytest +from dirty_equals import IsDict +from fastapi.testclient import TestClient +from inline_snapshot import snapshot + +from tests.utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py39", marks=needs_py39), + pytest.param("tutorial001_py310", marks=needs_py310), + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + pytest.param("tutorial001_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.header_param_models.{request.param}") + + client = TestClient(mod.app) + return client + + +def test_header_param_model(client: TestClient): + response = client.get( + "/items/", + headers=[ + ("save-data", "true"), + ("if-modified-since", "yesterday"), + ("traceparent", "123"), + ("x-tag", "one"), + ("x-tag", "two"), + ], + ) + assert response.status_code == 200 + assert response.json() == { + "host": "testserver", + "save_data": True, + "if_modified_since": "yesterday", + "traceparent": "123", + "x_tag": ["one", "two"], + } + + +def test_header_param_model_defaults(client: TestClient): + response = client.get("/items/", headers=[("save-data", "true")]) + assert response.status_code == 200 + assert response.json() == { + "host": "testserver", + "save_data": True, + "if_modified_since": None, + "traceparent": None, + "x_tag": [], + } + + +def test_header_param_model_invalid(client: TestClient): + response = client.get("/items/") + assert response.status_code == 422 + assert response.json() == snapshot( + { + "detail": [ + IsDict( + { + "type": "missing", + "loc": ["header", "save_data"], + "msg": "Field required", + "input": { + "x_tag": [], + "host": "testserver", + "accept": "*/*", + "accept-encoding": "gzip, deflate", + "connection": "keep-alive", + "user-agent": "testclient", + }, + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "value_error.missing", + "loc": ["header", "save_data"], + "msg": "field required", + } + ) + ] + } + ) + + +def test_header_param_model_extra(client: TestClient): + response = client.get( + "/items/", headers=[("save-data", "true"), ("tool", "plumbus")] + ) + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "host": "testserver", + "save_data": True, + "if_modified_since": None, + "traceparent": None, + "x_tag": [], + } + ) + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "parameters": [ + { + "name": "host", + "in": "header", + "required": True, + "schema": {"type": "string", "title": "Host"}, + }, + { + "name": "save_data", + "in": "header", + "required": True, + "schema": {"type": "boolean", "title": "Save Data"}, + }, + { + "name": "if_modified_since", + "in": "header", + "required": False, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "If Modified Since", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "If Modified Since", + } + ), + }, + { + "name": "traceparent", + "in": "header", + "required": False, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Traceparent", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "Traceparent", + } + ), + }, + { + "name": "x_tag", + "in": "header", + "required": False, + "schema": { + "type": "array", + "items": {"type": "string"}, + "default": [], + "title": "X Tag", + }, + }, + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } + ) diff --git a/tests/test_tutorial/test_header_param_models/test_tutorial002.py b/tests/test_tutorial/test_header_param_models/test_tutorial002.py new file mode 100644 index 000000000..e07655a0c --- /dev/null +++ b/tests/test_tutorial/test_header_param_models/test_tutorial002.py @@ -0,0 +1,249 @@ +import importlib + +import pytest +from dirty_equals import IsDict +from fastapi.testclient import TestClient +from inline_snapshot import snapshot + +from tests.utils import needs_py39, needs_py310, needs_pydanticv1, needs_pydanticv2 + + +@pytest.fixture( + name="client", + params=[ + pytest.param("tutorial002", marks=needs_pydanticv2), + pytest.param("tutorial002_py310", marks=[needs_py310, needs_pydanticv2]), + pytest.param("tutorial002_an", marks=needs_pydanticv2), + pytest.param("tutorial002_an_py39", marks=[needs_py39, needs_pydanticv2]), + pytest.param("tutorial002_an_py310", marks=[needs_py310, needs_pydanticv2]), + pytest.param("tutorial002_pv1", marks=[needs_pydanticv1, needs_pydanticv1]), + pytest.param("tutorial002_pv1_py310", marks=[needs_py310, needs_pydanticv1]), + pytest.param("tutorial002_pv1_an", marks=[needs_pydanticv1]), + pytest.param("tutorial002_pv1_an_py39", marks=[needs_py39, needs_pydanticv1]), + pytest.param("tutorial002_pv1_an_py310", marks=[needs_py310, needs_pydanticv1]), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.header_param_models.{request.param}") + + client = TestClient(mod.app) + client.headers.clear() + return client + + +def test_header_param_model(client: TestClient): + response = client.get( + "/items/", + headers=[ + ("save-data", "true"), + ("if-modified-since", "yesterday"), + ("traceparent", "123"), + ("x-tag", "one"), + ("x-tag", "two"), + ], + ) + assert response.status_code == 200, response.text + assert response.json() == { + "host": "testserver", + "save_data": True, + "if_modified_since": "yesterday", + "traceparent": "123", + "x_tag": ["one", "two"], + } + + +def test_header_param_model_defaults(client: TestClient): + response = client.get("/items/", headers=[("save-data", "true")]) + assert response.status_code == 200 + assert response.json() == { + "host": "testserver", + "save_data": True, + "if_modified_since": None, + "traceparent": None, + "x_tag": [], + } + + +def test_header_param_model_invalid(client: TestClient): + response = client.get("/items/") + assert response.status_code == 422 + assert response.json() == snapshot( + { + "detail": [ + IsDict( + { + "type": "missing", + "loc": ["header", "save_data"], + "msg": "Field required", + "input": {"x_tag": [], "host": "testserver"}, + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "value_error.missing", + "loc": ["header", "save_data"], + "msg": "field required", + } + ) + ] + } + ) + + +def test_header_param_model_extra(client: TestClient): + response = client.get( + "/items/", headers=[("save-data", "true"), ("tool", "plumbus")] + ) + assert response.status_code == 422, response.text + assert response.json() == snapshot( + { + "detail": [ + IsDict( + { + "type": "extra_forbidden", + "loc": ["header", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "value_error.extra", + "loc": ["header", "tool"], + "msg": "extra fields not permitted", + } + ) + ] + } + ) + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "parameters": [ + { + "name": "host", + "in": "header", + "required": True, + "schema": {"type": "string", "title": "Host"}, + }, + { + "name": "save_data", + "in": "header", + "required": True, + "schema": {"type": "boolean", "title": "Save Data"}, + }, + { + "name": "if_modified_since", + "in": "header", + "required": False, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "If Modified Since", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "If Modified Since", + } + ), + }, + { + "name": "traceparent", + "in": "header", + "required": False, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Traceparent", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "Traceparent", + } + ), + }, + { + "name": "x_tag", + "in": "header", + "required": False, + "schema": { + "type": "array", + "items": {"type": "string"}, + "default": [], + "title": "X Tag", + }, + }, + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } + ) diff --git a/tests/test_tutorial/test_header_params/test_tutorial001.py b/tests/test_tutorial/test_header_params/test_tutorial001.py index 746fc0502..d6f7fe618 100644 --- a/tests/test_tutorial/test_header_params/test_tutorial001.py +++ b/tests/test_tutorial/test_header_params/test_tutorial001.py @@ -1,10 +1,26 @@ +import importlib + import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from docs_src.header_params.tutorial001 import app +from ...utils import needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py310", marks=needs_py310), + "tutorial001_an", + pytest.param("tutorial001_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.header_params.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client @pytest.mark.parametrize( @@ -15,13 +31,13 @@ client = TestClient(app) ("/items", {"User-Agent": "FastAPI test"}, 200, {"User-Agent": "FastAPI test"}), ], ) -def test(path, headers, expected_status, expected_response): +def test(path, headers, expected_status, expected_response, client: TestClient): response = client.get(path, headers=headers) assert response.status_code == expected_status assert response.json() == expected_response -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { diff --git a/tests/test_tutorial/test_header_params/test_tutorial001_an.py b/tests/test_tutorial/test_header_params/test_tutorial001_an.py deleted file mode 100644 index a715228aa..000000000 --- a/tests/test_tutorial/test_header_params/test_tutorial001_an.py +++ /dev/null @@ -1,102 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from docs_src.header_params.tutorial001_an import app - -client = TestClient(app) - - -@pytest.mark.parametrize( - "path,headers,expected_status,expected_response", - [ - ("/items", None, 200, {"User-Agent": "testclient"}), - ("/items", {"X-Header": "notvalid"}, 200, {"User-Agent": "testclient"}), - ("/items", {"User-Agent": "FastAPI test"}, 200, {"User-Agent": "FastAPI test"}), - ], -) -def test(path, headers, expected_status, expected_response): - response = client.get(path, headers=headers) - assert response.status_code == expected_status - assert response.json() == expected_response - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200 - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "User-Agent", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "User-Agent", "type": "string"} - ), - "name": "user-agent", - "in": "header", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_header_params/test_tutorial001_an_py310.py b/tests/test_tutorial/test_header_params/test_tutorial001_an_py310.py deleted file mode 100644 index caf85bc6c..000000000 --- a/tests/test_tutorial/test_header_params/test_tutorial001_an_py310.py +++ /dev/null @@ -1,110 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.header_params.tutorial001_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -@pytest.mark.parametrize( - "path,headers,expected_status,expected_response", - [ - ("/items", None, 200, {"User-Agent": "testclient"}), - ("/items", {"X-Header": "notvalid"}, 200, {"User-Agent": "testclient"}), - ("/items", {"User-Agent": "FastAPI test"}, 200, {"User-Agent": "FastAPI test"}), - ], -) -def test(path, headers, expected_status, expected_response, client: TestClient): - response = client.get(path, headers=headers) - assert response.status_code == expected_status - assert response.json() == expected_response - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200 - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "User-Agent", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "User-Agent", "type": "string"} - ), - "name": "user-agent", - "in": "header", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_header_params/test_tutorial001_py310.py b/tests/test_tutorial/test_header_params/test_tutorial001_py310.py deleted file mode 100644 index 57e0a296a..000000000 --- a/tests/test_tutorial/test_header_params/test_tutorial001_py310.py +++ /dev/null @@ -1,110 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.header_params.tutorial001_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -@pytest.mark.parametrize( - "path,headers,expected_status,expected_response", - [ - ("/items", None, 200, {"User-Agent": "testclient"}), - ("/items", {"X-Header": "notvalid"}, 200, {"User-Agent": "testclient"}), - ("/items", {"User-Agent": "FastAPI test"}, 200, {"User-Agent": "FastAPI test"}), - ], -) -def test(path, headers, expected_status, expected_response, client: TestClient): - response = client.get(path, headers=headers) - assert response.status_code == expected_status - assert response.json() == expected_response - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200 - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "User-Agent", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "User-Agent", "type": "string"} - ), - "name": "user-agent", - "in": "header", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_header_params/test_tutorial002.py b/tests/test_tutorial/test_header_params/test_tutorial002.py index 78bac838c..7158f8651 100644 --- a/tests/test_tutorial/test_header_params/test_tutorial002.py +++ b/tests/test_tutorial/test_header_params/test_tutorial002.py @@ -1,10 +1,27 @@ +import importlib + import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from docs_src.header_params.tutorial002 import app +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial002", + pytest.param("tutorial002_py310", marks=needs_py310), + "tutorial002_an", + pytest.param("tutorial002_an_py39", marks=needs_py39), + pytest.param("tutorial002_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.header_params.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client @pytest.mark.parametrize( @@ -26,13 +43,13 @@ client = TestClient(app) ), ], ) -def test(path, headers, expected_status, expected_response): +def test(path, headers, expected_status, expected_response, client: TestClient): response = client.get(path, headers=headers) assert response.status_code == expected_status assert response.json() == expected_response -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { diff --git a/tests/test_tutorial/test_header_params/test_tutorial002_an.py b/tests/test_tutorial/test_header_params/test_tutorial002_an.py deleted file mode 100644 index ffda8158f..000000000 --- a/tests/test_tutorial/test_header_params/test_tutorial002_an.py +++ /dev/null @@ -1,113 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from docs_src.header_params.tutorial002_an import app - -client = TestClient(app) - - -@pytest.mark.parametrize( - "path,headers,expected_status,expected_response", - [ - ("/items", None, 200, {"strange_header": None}), - ("/items", {"X-Header": "notvalid"}, 200, {"strange_header": None}), - ( - "/items", - {"strange_header": "FastAPI test"}, - 200, - {"strange_header": "FastAPI test"}, - ), - ( - "/items", - {"strange-header": "Not really underscore"}, - 200, - {"strange_header": None}, - ), - ], -) -def test(path, headers, expected_status, expected_response): - response = client.get(path, headers=headers) - assert response.status_code == expected_status - assert response.json() == expected_response - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200 - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Strange Header", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Strange Header", "type": "string"} - ), - "name": "strange_header", - "in": "header", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_header_params/test_tutorial002_an_py310.py b/tests/test_tutorial/test_header_params/test_tutorial002_an_py310.py deleted file mode 100644 index 6f332f3ba..000000000 --- a/tests/test_tutorial/test_header_params/test_tutorial002_an_py310.py +++ /dev/null @@ -1,121 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.header_params.tutorial002_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -@pytest.mark.parametrize( - "path,headers,expected_status,expected_response", - [ - ("/items", None, 200, {"strange_header": None}), - ("/items", {"X-Header": "notvalid"}, 200, {"strange_header": None}), - ( - "/items", - {"strange_header": "FastAPI test"}, - 200, - {"strange_header": "FastAPI test"}, - ), - ( - "/items", - {"strange-header": "Not really underscore"}, - 200, - {"strange_header": None}, - ), - ], -) -def test(path, headers, expected_status, expected_response, client: TestClient): - response = client.get(path, headers=headers) - assert response.status_code == expected_status - assert response.json() == expected_response - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200 - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Strange Header", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Strange Header", "type": "string"} - ), - "name": "strange_header", - "in": "header", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_header_params/test_tutorial002_an_py39.py b/tests/test_tutorial/test_header_params/test_tutorial002_an_py39.py deleted file mode 100644 index 8202bc671..000000000 --- a/tests/test_tutorial/test_header_params/test_tutorial002_an_py39.py +++ /dev/null @@ -1,124 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.header_params.tutorial002_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -@pytest.mark.parametrize( - "path,headers,expected_status,expected_response", - [ - ("/items", None, 200, {"strange_header": None}), - ("/items", {"X-Header": "notvalid"}, 200, {"strange_header": None}), - ( - "/items", - {"strange_header": "FastAPI test"}, - 200, - {"strange_header": "FastAPI test"}, - ), - ( - "/items", - {"strange-header": "Not really underscore"}, - 200, - {"strange_header": None}, - ), - ], -) -def test(path, headers, expected_status, expected_response, client: TestClient): - response = client.get(path, headers=headers) - assert response.status_code == expected_status - assert response.json() == expected_response - - -@needs_py39 -def test_openapi_schema(): - from docs_src.header_params.tutorial002_an_py39 import app - - client = TestClient(app) - response = client.get("/openapi.json") - assert response.status_code == 200 - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Strange Header", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Strange Header", "type": "string"} - ), - "name": "strange_header", - "in": "header", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_header_params/test_tutorial002_py310.py b/tests/test_tutorial/test_header_params/test_tutorial002_py310.py deleted file mode 100644 index c113ed23e..000000000 --- a/tests/test_tutorial/test_header_params/test_tutorial002_py310.py +++ /dev/null @@ -1,124 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.header_params.tutorial002_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -@pytest.mark.parametrize( - "path,headers,expected_status,expected_response", - [ - ("/items", None, 200, {"strange_header": None}), - ("/items", {"X-Header": "notvalid"}, 200, {"strange_header": None}), - ( - "/items", - {"strange_header": "FastAPI test"}, - 200, - {"strange_header": "FastAPI test"}, - ), - ( - "/items", - {"strange-header": "Not really underscore"}, - 200, - {"strange_header": None}, - ), - ], -) -def test(path, headers, expected_status, expected_response, client: TestClient): - response = client.get(path, headers=headers) - assert response.status_code == expected_status - assert response.json() == expected_response - - -@needs_py310 -def test_openapi_schema(): - from docs_src.header_params.tutorial002_py310 import app - - client = TestClient(app) - response = client.get("/openapi.json") - assert response.status_code == 200 - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Strange Header", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Strange Header", "type": "string"} - ), - "name": "strange_header", - "in": "header", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_header_params/test_tutorial003.py b/tests/test_tutorial/test_header_params/test_tutorial003.py index 6f7de8ed4..0b58227f6 100644 --- a/tests/test_tutorial/test_header_params/test_tutorial003.py +++ b/tests/test_tutorial/test_header_params/test_tutorial003.py @@ -1,10 +1,27 @@ +import importlib + import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from docs_src.header_params.tutorial003 import app +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial003", + pytest.param("tutorial003_py310", marks=needs_py310), + "tutorial003_an", + pytest.param("tutorial003_an_py39", marks=needs_py39), + pytest.param("tutorial003_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.header_params.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client @pytest.mark.parametrize( @@ -12,21 +29,17 @@ client = TestClient(app) [ ("/items", None, 200, {"X-Token values": None}), ("/items", {"x-token": "foo"}, 200, {"X-Token values": ["foo"]}), - ( - "/items", - [("x-token", "foo"), ("x-token", "bar")], - 200, - {"X-Token values": ["foo", "bar"]}, - ), + # TODO: fix this, is it a bug? + # ("/items", [("x-token", "foo"), ("x-token", "bar")], 200, {"X-Token values": ["foo", "bar"]}), ], ) -def test(path, headers, expected_status, expected_response): +def test(path, headers, expected_status, expected_response, client: TestClient): response = client.get(path, headers=headers) assert response.status_code == expected_status assert response.json() == expected_response -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200 assert response.json() == { diff --git a/tests/test_tutorial/test_header_params/test_tutorial003_an.py b/tests/test_tutorial/test_header_params/test_tutorial003_an.py deleted file mode 100644 index 742ed41f4..000000000 --- a/tests/test_tutorial/test_header_params/test_tutorial003_an.py +++ /dev/null @@ -1,110 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from docs_src.header_params.tutorial003_an import app - -client = TestClient(app) - - -@pytest.mark.parametrize( - "path,headers,expected_status,expected_response", - [ - ("/items", None, 200, {"X-Token values": None}), - ("/items", {"x-token": "foo"}, 200, {"X-Token values": ["foo"]}), - # TODO: fix this, is it a bug? - # ("/items", [("x-token", "foo"), ("x-token", "bar")], 200, {"X-Token values": ["foo", "bar"]}), - ], -) -def test(path, headers, expected_status, expected_response): - response = client.get(path, headers=headers) - assert response.status_code == expected_status - assert response.json() == expected_response - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200 - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "title": "X-Token", - "anyOf": [ - {"type": "array", "items": {"type": "string"}}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "X-Token", - "type": "array", - "items": {"type": "string"}, - } - ), - "name": "x-token", - "in": "header", - } - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_header_params/test_tutorial003_an_py310.py b/tests/test_tutorial/test_header_params/test_tutorial003_an_py310.py deleted file mode 100644 index fdac4a416..000000000 --- a/tests/test_tutorial/test_header_params/test_tutorial003_an_py310.py +++ /dev/null @@ -1,118 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.header_params.tutorial003_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -@pytest.mark.parametrize( - "path,headers,expected_status,expected_response", - [ - ("/items", None, 200, {"X-Token values": None}), - ("/items", {"x-token": "foo"}, 200, {"X-Token values": ["foo"]}), - # TODO: fix this, is it a bug? - # ("/items", [("x-token", "foo"), ("x-token", "bar")], 200, {"X-Token values": ["foo", "bar"]}), - ], -) -def test(path, headers, expected_status, expected_response, client: TestClient): - response = client.get(path, headers=headers) - assert response.status_code == expected_status - assert response.json() == expected_response - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200 - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "title": "X-Token", - "anyOf": [ - {"type": "array", "items": {"type": "string"}}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "X-Token", - "type": "array", - "items": {"type": "string"}, - } - ), - "name": "x-token", - "in": "header", - } - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_header_params/test_tutorial003_an_py39.py b/tests/test_tutorial/test_header_params/test_tutorial003_an_py39.py deleted file mode 100644 index c50543cc8..000000000 --- a/tests/test_tutorial/test_header_params/test_tutorial003_an_py39.py +++ /dev/null @@ -1,118 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.header_params.tutorial003_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -@pytest.mark.parametrize( - "path,headers,expected_status,expected_response", - [ - ("/items", None, 200, {"X-Token values": None}), - ("/items", {"x-token": "foo"}, 200, {"X-Token values": ["foo"]}), - # TODO: fix this, is it a bug? - # ("/items", [("x-token", "foo"), ("x-token", "bar")], 200, {"X-Token values": ["foo", "bar"]}), - ], -) -def test(path, headers, expected_status, expected_response, client: TestClient): - response = client.get(path, headers=headers) - assert response.status_code == expected_status - assert response.json() == expected_response - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200 - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "title": "X-Token", - "anyOf": [ - {"type": "array", "items": {"type": "string"}}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "X-Token", - "type": "array", - "items": {"type": "string"}, - } - ), - "name": "x-token", - "in": "header", - } - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_header_params/test_tutorial003_py310.py b/tests/test_tutorial/test_header_params/test_tutorial003_py310.py deleted file mode 100644 index 3afb355e9..000000000 --- a/tests/test_tutorial/test_header_params/test_tutorial003_py310.py +++ /dev/null @@ -1,118 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.header_params.tutorial003_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -@pytest.mark.parametrize( - "path,headers,expected_status,expected_response", - [ - ("/items", None, 200, {"X-Token values": None}), - ("/items", {"x-token": "foo"}, 200, {"X-Token values": ["foo"]}), - # TODO: fix this, is it a bug? - # ("/items", [("x-token", "foo"), ("x-token", "bar")], 200, {"X-Token values": ["foo", "bar"]}), - ], -) -def test(path, headers, expected_status, expected_response, client: TestClient): - response = client.get(path, headers=headers) - assert response.status_code == expected_status - assert response.json() == expected_response - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200 - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "title": "X-Token", - "anyOf": [ - {"type": "array", "items": {"type": "string"}}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "X-Token", - "type": "array", - "items": {"type": "string"}, - } - ), - "name": "x-token", - "in": "header", - } - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial007.py b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial007.py index 2d2802269..8240b60a6 100644 --- a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial007.py +++ b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial007.py @@ -1,6 +1,5 @@ import pytest from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from ...utils import needs_pydanticv2 @@ -64,7 +63,6 @@ def test_post_invalid(client: TestClient): "loc": ["tags", 3], "msg": "Input should be a valid string", "input": {"sneaky": "object"}, - "url": match_pydantic_error_url("string_type"), } ] } diff --git a/tests/test_tutorial/test_path_operation_configurations/test_tutorial005.py b/tests/test_tutorial/test_path_operation_configurations/test_tutorial005.py index d3792e701..0742f5d0e 100644 --- a/tests/test_tutorial/test_path_operation_configurations/test_tutorial005.py +++ b/tests/test_tutorial/test_path_operation_configurations/test_tutorial005.py @@ -1,13 +1,29 @@ +import importlib + +import pytest from fastapi.testclient import TestClient -from docs_src.path_operation_configuration.tutorial005 import app +from ...utils import needs_py39, needs_py310, needs_pydanticv1, needs_pydanticv2 + -from ...utils import needs_pydanticv1, needs_pydanticv2 +@pytest.fixture( + name="client", + params=[ + "tutorial005", + pytest.param("tutorial005_py39", marks=needs_py39), + pytest.param("tutorial005_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module( + f"docs_src.path_operation_configuration.{request.param}" + ) -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_query_params_str_validations(): +def test_query_params_str_validations(client: TestClient): response = client.post("/items/", json={"name": "Foo", "price": 42}) assert response.status_code == 200, response.text assert response.json() == { @@ -20,7 +36,7 @@ def test_query_params_str_validations(): @needs_pydanticv2 -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { @@ -123,7 +139,7 @@ def test_openapi_schema(): # TODO: remove when deprecating Pydantic v1 @needs_pydanticv1 -def test_openapi_schema_pv1(): +def test_openapi_schema_pv1(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_path_operation_configurations/test_tutorial005_py310.py b/tests/test_tutorial/test_path_operation_configurations/test_tutorial005_py310.py deleted file mode 100644 index a68deb3df..000000000 --- a/tests/test_tutorial/test_path_operation_configurations/test_tutorial005_py310.py +++ /dev/null @@ -1,226 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py310, needs_pydanticv1, needs_pydanticv2 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.path_operation_configuration.tutorial005_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_query_params_str_validations(client: TestClient): - response = client.post("/items/", json={"name": "Foo", "price": 42}) - assert response.status_code == 200, response.text - assert response.json() == { - "name": "Foo", - "price": 42, - "description": None, - "tax": None, - "tags": [], - } - - -@needs_py310 -@needs_pydanticv2 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "post": { - "responses": { - "200": { - "description": "The created item", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create an item", - "description": "Create an item with all the information:\n\n- **name**: each item must have a name\n- **description**: a long description\n- **price**: required\n- **tax**: if the item doesn't have tax, you can omit this\n- **tags**: a set of unique tag strings for this item", - "operationId": "create_item_items__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - }, - "price": {"title": "Price", "type": "number"}, - "tax": { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - }, - "tags": { - "title": "Tags", - "uniqueItems": True, - "type": "array", - "items": {"type": "string"}, - "default": [], - }, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } - - -# TODO: remove when deprecating Pydantic v1 -@needs_py310 -@needs_pydanticv1 -def test_openapi_schema_pv1(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "post": { - "responses": { - "200": { - "description": "The created item", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create an item", - "description": "Create an item with all the information:\n\n- **name**: each item must have a name\n- **description**: a long description\n- **price**: required\n- **tax**: if the item doesn't have tax, you can omit this\n- **tags**: a set of unique tag strings for this item", - "operationId": "create_item_items__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": {"title": "Description", "type": "string"}, - "price": {"title": "Price", "type": "number"}, - "tax": {"title": "Tax", "type": "number"}, - "tags": { - "title": "Tags", - "uniqueItems": True, - "type": "array", - "items": {"type": "string"}, - "default": [], - }, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_path_operation_configurations/test_tutorial005_py39.py b/tests/test_tutorial/test_path_operation_configurations/test_tutorial005_py39.py deleted file mode 100644 index e17f2592d..000000000 --- a/tests/test_tutorial/test_path_operation_configurations/test_tutorial005_py39.py +++ /dev/null @@ -1,226 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39, needs_pydanticv1, needs_pydanticv2 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.path_operation_configuration.tutorial005_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_query_params_str_validations(client: TestClient): - response = client.post("/items/", json={"name": "Foo", "price": 42}) - assert response.status_code == 200, response.text - assert response.json() == { - "name": "Foo", - "price": 42, - "description": None, - "tax": None, - "tags": [], - } - - -@needs_py39 -@needs_pydanticv2 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "post": { - "responses": { - "200": { - "description": "The created item", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create an item", - "description": "Create an item with all the information:\n\n- **name**: each item must have a name\n- **description**: a long description\n- **price**: required\n- **tax**: if the item doesn't have tax, you can omit this\n- **tags**: a set of unique tag strings for this item", - "operationId": "create_item_items__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - }, - "price": {"title": "Price", "type": "number"}, - "tax": { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - }, - "tags": { - "title": "Tags", - "uniqueItems": True, - "type": "array", - "items": {"type": "string"}, - "default": [], - }, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } - - -# TODO: remove when deprecating Pydantic v1 -@needs_py39 -@needs_pydanticv1 -def test_openapi_schema_pv1(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "post": { - "responses": { - "200": { - "description": "The created item", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create an item", - "description": "Create an item with all the information:\n\n- **name**: each item must have a name\n- **description**: a long description\n- **price**: required\n- **tax**: if the item doesn't have tax, you can omit this\n- **tags**: a set of unique tag strings for this item", - "operationId": "create_item_items__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": {"title": "Description", "type": "string"}, - "price": {"title": "Price", "type": "number"}, - "tax": {"title": "Tax", "type": "number"}, - "tags": { - "title": "Tags", - "uniqueItems": True, - "type": "array", - "items": {"type": "string"}, - "default": [], - }, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/docs_src/sql_databases/sql_app_py310/__init__.py b/tests/test_tutorial/test_query_param_models/__init__.py similarity index 100% rename from docs_src/sql_databases/sql_app_py310/__init__.py rename to tests/test_tutorial/test_query_param_models/__init__.py diff --git a/tests/test_tutorial/test_query_param_models/test_tutorial001.py b/tests/test_tutorial/test_query_param_models/test_tutorial001.py new file mode 100644 index 000000000..5b7bc7b42 --- /dev/null +++ b/tests/test_tutorial/test_query_param_models/test_tutorial001.py @@ -0,0 +1,260 @@ +import importlib + +import pytest +from dirty_equals import IsDict +from fastapi.testclient import TestClient +from inline_snapshot import snapshot + +from tests.utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py39", marks=needs_py39), + pytest.param("tutorial001_py310", marks=needs_py310), + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + pytest.param("tutorial001_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.query_param_models.{request.param}") + + client = TestClient(mod.app) + return client + + +def test_query_param_model(client: TestClient): + response = client.get( + "/items/", + params={ + "limit": 10, + "offset": 5, + "order_by": "updated_at", + "tags": ["tag1", "tag2"], + }, + ) + assert response.status_code == 200 + assert response.json() == { + "limit": 10, + "offset": 5, + "order_by": "updated_at", + "tags": ["tag1", "tag2"], + } + + +def test_query_param_model_defaults(client: TestClient): + response = client.get("/items/") + assert response.status_code == 200 + assert response.json() == { + "limit": 100, + "offset": 0, + "order_by": "created_at", + "tags": [], + } + + +def test_query_param_model_invalid(client: TestClient): + response = client.get( + "/items/", + params={ + "limit": 150, + "offset": -1, + "order_by": "invalid", + }, + ) + assert response.status_code == 422 + assert response.json() == snapshot( + IsDict( + { + "detail": [ + { + "type": "less_than_equal", + "loc": ["query", "limit"], + "msg": "Input should be less than or equal to 100", + "input": "150", + "ctx": {"le": 100}, + }, + { + "type": "greater_than_equal", + "loc": ["query", "offset"], + "msg": "Input should be greater than or equal to 0", + "input": "-1", + "ctx": {"ge": 0}, + }, + { + "type": "literal_error", + "loc": ["query", "order_by"], + "msg": "Input should be 'created_at' or 'updated_at'", + "input": "invalid", + "ctx": {"expected": "'created_at' or 'updated_at'"}, + }, + ] + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "type": "value_error.number.not_le", + "loc": ["query", "limit"], + "msg": "ensure this value is less than or equal to 100", + "ctx": {"limit_value": 100}, + }, + { + "type": "value_error.number.not_ge", + "loc": ["query", "offset"], + "msg": "ensure this value is greater than or equal to 0", + "ctx": {"limit_value": 0}, + }, + { + "type": "value_error.const", + "loc": ["query", "order_by"], + "msg": "unexpected value; permitted: 'created_at', 'updated_at'", + "ctx": { + "given": "invalid", + "permitted": ["created_at", "updated_at"], + }, + }, + ] + } + ) + ) + + +def test_query_param_model_extra(client: TestClient): + response = client.get( + "/items/", + params={ + "limit": 10, + "offset": 5, + "order_by": "updated_at", + "tags": ["tag1", "tag2"], + "tool": "plumbus", + }, + ) + assert response.status_code == 200 + assert response.json() == { + "limit": 10, + "offset": 5, + "order_by": "updated_at", + "tags": ["tag1", "tag2"], + } + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "parameters": [ + { + "name": "limit", + "in": "query", + "required": False, + "schema": { + "type": "integer", + "maximum": 100, + "exclusiveMinimum": 0, + "default": 100, + "title": "Limit", + }, + }, + { + "name": "offset", + "in": "query", + "required": False, + "schema": { + "type": "integer", + "minimum": 0, + "default": 0, + "title": "Offset", + }, + }, + { + "name": "order_by", + "in": "query", + "required": False, + "schema": { + "enum": ["created_at", "updated_at"], + "type": "string", + "default": "created_at", + "title": "Order By", + }, + }, + { + "name": "tags", + "in": "query", + "required": False, + "schema": { + "type": "array", + "items": {"type": "string"}, + "default": [], + "title": "Tags", + }, + }, + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } + ) diff --git a/tests/test_tutorial/test_query_param_models/test_tutorial002.py b/tests/test_tutorial/test_query_param_models/test_tutorial002.py new file mode 100644 index 000000000..4432c9d8a --- /dev/null +++ b/tests/test_tutorial/test_query_param_models/test_tutorial002.py @@ -0,0 +1,282 @@ +import importlib + +import pytest +from dirty_equals import IsDict +from fastapi.testclient import TestClient +from inline_snapshot import snapshot + +from tests.utils import needs_py39, needs_py310, needs_pydanticv1, needs_pydanticv2 + + +@pytest.fixture( + name="client", + params=[ + pytest.param("tutorial002", marks=needs_pydanticv2), + pytest.param("tutorial002_py39", marks=[needs_py39, needs_pydanticv2]), + pytest.param("tutorial002_py310", marks=[needs_py310, needs_pydanticv2]), + pytest.param("tutorial002_an", marks=needs_pydanticv2), + pytest.param("tutorial002_an_py39", marks=[needs_py39, needs_pydanticv2]), + pytest.param("tutorial002_an_py310", marks=[needs_py310, needs_pydanticv2]), + pytest.param("tutorial002_pv1", marks=[needs_pydanticv1, needs_pydanticv1]), + pytest.param("tutorial002_pv1_py39", marks=[needs_py39, needs_pydanticv1]), + pytest.param("tutorial002_pv1_py310", marks=[needs_py310, needs_pydanticv1]), + pytest.param("tutorial002_pv1_an", marks=[needs_pydanticv1]), + pytest.param("tutorial002_pv1_an_py39", marks=[needs_py39, needs_pydanticv1]), + pytest.param("tutorial002_pv1_an_py310", marks=[needs_py310, needs_pydanticv1]), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.query_param_models.{request.param}") + + client = TestClient(mod.app) + return client + + +def test_query_param_model(client: TestClient): + response = client.get( + "/items/", + params={ + "limit": 10, + "offset": 5, + "order_by": "updated_at", + "tags": ["tag1", "tag2"], + }, + ) + assert response.status_code == 200 + assert response.json() == { + "limit": 10, + "offset": 5, + "order_by": "updated_at", + "tags": ["tag1", "tag2"], + } + + +def test_query_param_model_defaults(client: TestClient): + response = client.get("/items/") + assert response.status_code == 200 + assert response.json() == { + "limit": 100, + "offset": 0, + "order_by": "created_at", + "tags": [], + } + + +def test_query_param_model_invalid(client: TestClient): + response = client.get( + "/items/", + params={ + "limit": 150, + "offset": -1, + "order_by": "invalid", + }, + ) + assert response.status_code == 422 + assert response.json() == snapshot( + IsDict( + { + "detail": [ + { + "type": "less_than_equal", + "loc": ["query", "limit"], + "msg": "Input should be less than or equal to 100", + "input": "150", + "ctx": {"le": 100}, + }, + { + "type": "greater_than_equal", + "loc": ["query", "offset"], + "msg": "Input should be greater than or equal to 0", + "input": "-1", + "ctx": {"ge": 0}, + }, + { + "type": "literal_error", + "loc": ["query", "order_by"], + "msg": "Input should be 'created_at' or 'updated_at'", + "input": "invalid", + "ctx": {"expected": "'created_at' or 'updated_at'"}, + }, + ] + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "detail": [ + { + "type": "value_error.number.not_le", + "loc": ["query", "limit"], + "msg": "ensure this value is less than or equal to 100", + "ctx": {"limit_value": 100}, + }, + { + "type": "value_error.number.not_ge", + "loc": ["query", "offset"], + "msg": "ensure this value is greater than or equal to 0", + "ctx": {"limit_value": 0}, + }, + { + "type": "value_error.const", + "loc": ["query", "order_by"], + "msg": "unexpected value; permitted: 'created_at', 'updated_at'", + "ctx": { + "given": "invalid", + "permitted": ["created_at", "updated_at"], + }, + }, + ] + } + ) + ) + + +def test_query_param_model_extra(client: TestClient): + response = client.get( + "/items/", + params={ + "limit": 10, + "offset": 5, + "order_by": "updated_at", + "tags": ["tag1", "tag2"], + "tool": "plumbus", + }, + ) + assert response.status_code == 422 + assert response.json() == snapshot( + { + "detail": [ + IsDict( + { + "type": "extra_forbidden", + "loc": ["query", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "value_error.extra", + "loc": ["query", "tool"], + "msg": "extra fields not permitted", + } + ) + ] + } + ) + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "parameters": [ + { + "name": "limit", + "in": "query", + "required": False, + "schema": { + "type": "integer", + "maximum": 100, + "exclusiveMinimum": 0, + "default": 100, + "title": "Limit", + }, + }, + { + "name": "offset", + "in": "query", + "required": False, + "schema": { + "type": "integer", + "minimum": 0, + "default": 0, + "title": "Offset", + }, + }, + { + "name": "order_by", + "in": "query", + "required": False, + "schema": { + "enum": ["created_at", "updated_at"], + "type": "string", + "default": "created_at", + "title": "Order By", + }, + }, + { + "name": "tags", + "in": "query", + "required": False, + "schema": { + "type": "array", + "items": {"type": "string"}, + "default": [], + "title": "Tags", + }, + }, + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } + ) diff --git a/tests/test_tutorial/test_query_params/test_tutorial005.py b/tests/test_tutorial/test_query_params/test_tutorial005.py index 921586357..05ae85b45 100644 --- a/tests/test_tutorial/test_query_params/test_tutorial005.py +++ b/tests/test_tutorial/test_query_params/test_tutorial005.py @@ -1,6 +1,5 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url from docs_src.query_params.tutorial005 import app @@ -24,7 +23,6 @@ def test_foo_no_needy(): "loc": ["query", "needy"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } diff --git a/tests/test_tutorial/test_query_params/test_tutorial006.py b/tests/test_tutorial/test_query_params/test_tutorial006.py index e07803d6c..a0b5ef494 100644 --- a/tests/test_tutorial/test_query_params/test_tutorial006.py +++ b/tests/test_tutorial/test_query_params/test_tutorial006.py @@ -1,14 +1,23 @@ +import importlib + import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url + +from ...utils import needs_py310 -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params.tutorial006 import app +@pytest.fixture( + name="client", + params=[ + "tutorial006", + pytest.param("tutorial006_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.query_params.{request.param}") - c = TestClient(app) + c = TestClient(mod.app) return c @@ -34,21 +43,18 @@ def test_foo_no_needy(client: TestClient): "loc": ["query", "needy"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), }, { "type": "int_parsing", "loc": ["query", "skip"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "a", - "url": match_pydantic_error_url("int_parsing"), }, { "type": "int_parsing", "loc": ["query", "limit"], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "b", - "url": match_pydantic_error_url("int_parsing"), }, ] } diff --git a/tests/test_tutorial/test_query_params/test_tutorial006_py310.py b/tests/test_tutorial/test_query_params/test_tutorial006_py310.py deleted file mode 100644 index 6c4c0b4dc..000000000 --- a/tests/test_tutorial/test_query_params/test_tutorial006_py310.py +++ /dev/null @@ -1,184 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params.tutorial006_py310 import app - - c = TestClient(app) - return c - - -@needs_py310 -def test_foo_needy_very(client: TestClient): - response = client.get("/items/foo?needy=very") - assert response.status_code == 200 - assert response.json() == { - "item_id": "foo", - "needy": "very", - "skip": 0, - "limit": None, - } - - -@needs_py310 -def test_foo_no_needy(client: TestClient): - response = client.get("/items/foo?skip=a&limit=b") - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["query", "needy"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - { - "type": "int_parsing", - "loc": ["query", "skip"], - "msg": "Input should be a valid integer, unable to parse string as an integer", - "input": "a", - "url": match_pydantic_error_url("int_parsing"), - }, - { - "type": "int_parsing", - "loc": ["query", "limit"], - "msg": "Input should be a valid integer, unable to parse string as an integer", - "input": "b", - "url": match_pydantic_error_url("int_parsing"), - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["query", "needy"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["query", "skip"], - "msg": "value is not a valid integer", - "type": "type_error.integer", - }, - { - "loc": ["query", "limit"], - "msg": "value is not a valid integer", - "type": "type_error.integer", - }, - ] - } - ) - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200 - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read User Item", - "operationId": "read_user_item_items__item_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - }, - { - "required": True, - "schema": {"title": "Needy", "type": "string"}, - "name": "needy", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "integer"}, {"type": "null"}], - "title": "Limit", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Limit", "type": "integer"} - ), - "name": "limit", - "in": "query", - }, - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py index 287c2e8f8..e08e16963 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py @@ -1,14 +1,29 @@ +import importlib + import pytest from dirty_equals import IsDict +from fastapi._compat import PYDANTIC_VERSION_MINOR_TUPLE from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url + +from ...utils import needs_py39, needs_py310 -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial010 import app +@pytest.fixture( + name="client", + params=[ + "tutorial010", + pytest.param("tutorial010_py310", marks=needs_py310), + "tutorial010_an", + pytest.param("tutorial010_an_py39", marks=needs_py39), + pytest.param("tutorial010_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module( + f"docs_src.query_params_str_validations.{request.param}" + ) - client = TestClient(app) + client = TestClient(mod.app) return client @@ -45,7 +60,6 @@ def test_query_params_str_validations_item_query_nonregexquery(client: TestClien "msg": "String should match pattern '^fixedquery$'", "input": "nonregexquery", "ctx": {"pattern": "^fixedquery$"}, - "url": match_pydantic_error_url("string_pattern_mismatch"), } ] } @@ -109,6 +123,12 @@ def test_openapi_schema(client: TestClient): ], "title": "Query string", "description": "Query string for the items to search in the database that have a good match", + # See https://github.com/pydantic/pydantic/blob/80353c29a824c55dea4667b328ba8f329879ac9f/tests/test_fastapi.sh#L25-L34. + **( + {"deprecated": True} + if PYDANTIC_VERSION_MINOR_TUPLE >= (2, 10) + else {} + ), } ) | IsDict( diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an.py deleted file mode 100644 index 5b0515070..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an.py +++ /dev/null @@ -1,163 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial010_an import app - - client = TestClient(app) - return client - - -def test_query_params_str_validations_no_query(client: TestClient): - response = client.get("/items/") - assert response.status_code == 200 - assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - - -def test_query_params_str_validations_item_query_fixedquery(client: TestClient): - response = client.get("/items/", params={"item-query": "fixedquery"}) - assert response.status_code == 200 - assert response.json() == { - "items": [{"item_id": "Foo"}, {"item_id": "Bar"}], - "q": "fixedquery", - } - - -def test_query_params_str_validations_q_fixedquery(client: TestClient): - response = client.get("/items/", params={"q": "fixedquery"}) - assert response.status_code == 200 - assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - - -def test_query_params_str_validations_item_query_nonregexquery(client: TestClient): - response = client.get("/items/", params={"item-query": "nonregexquery"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "string_pattern_mismatch", - "loc": ["query", "item-query"], - "msg": "String should match pattern '^fixedquery$'", - "input": "nonregexquery", - "ctx": {"pattern": "^fixedquery$"}, - "url": match_pydantic_error_url("string_pattern_mismatch"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "ctx": {"pattern": "^fixedquery$"}, - "loc": ["query", "item-query"], - "msg": 'string does not match regex "^fixedquery$"', - "type": "value_error.str.regex", - } - ] - } - ) - - -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "description": "Query string for the items to search in the database that have a good match", - "required": False, - "deprecated": True, - "schema": IsDict( - { - "anyOf": [ - { - "type": "string", - "minLength": 3, - "maxLength": 50, - "pattern": "^fixedquery$", - }, - {"type": "null"}, - ], - "title": "Query string", - "description": "Query string for the items to search in the database that have a good match", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Query string", - "maxLength": 50, - "minLength": 3, - "pattern": "^fixedquery$", - "type": "string", - "description": "Query string for the items to search in the database that have a good match", - } - ), - "name": "item-query", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py310.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py310.py deleted file mode 100644 index d22b1ce20..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py310.py +++ /dev/null @@ -1,170 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial010_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_query_params_str_validations_no_query(client: TestClient): - response = client.get("/items/") - assert response.status_code == 200 - assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - - -@needs_py310 -def test_query_params_str_validations_item_query_fixedquery(client: TestClient): - response = client.get("/items/", params={"item-query": "fixedquery"}) - assert response.status_code == 200 - assert response.json() == { - "items": [{"item_id": "Foo"}, {"item_id": "Bar"}], - "q": "fixedquery", - } - - -@needs_py310 -def test_query_params_str_validations_q_fixedquery(client: TestClient): - response = client.get("/items/", params={"q": "fixedquery"}) - assert response.status_code == 200 - assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - - -@needs_py310 -def test_query_params_str_validations_item_query_nonregexquery(client: TestClient): - response = client.get("/items/", params={"item-query": "nonregexquery"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "string_pattern_mismatch", - "loc": ["query", "item-query"], - "msg": "String should match pattern '^fixedquery$'", - "input": "nonregexquery", - "ctx": {"pattern": "^fixedquery$"}, - "url": match_pydantic_error_url("string_pattern_mismatch"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "ctx": {"pattern": "^fixedquery$"}, - "loc": ["query", "item-query"], - "msg": 'string does not match regex "^fixedquery$"', - "type": "value_error.str.regex", - } - ] - } - ) - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "description": "Query string for the items to search in the database that have a good match", - "required": False, - "deprecated": True, - "schema": IsDict( - { - "anyOf": [ - { - "type": "string", - "minLength": 3, - "maxLength": 50, - "pattern": "^fixedquery$", - }, - {"type": "null"}, - ], - "title": "Query string", - "description": "Query string for the items to search in the database that have a good match", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Query string", - "maxLength": 50, - "minLength": 3, - "pattern": "^fixedquery$", - "type": "string", - "description": "Query string for the items to search in the database that have a good match", - } - ), - "name": "item-query", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py39.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py39.py deleted file mode 100644 index 3e7d5d3ad..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py39.py +++ /dev/null @@ -1,170 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial010_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_query_params_str_validations_no_query(client: TestClient): - response = client.get("/items/") - assert response.status_code == 200 - assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - - -@needs_py39 -def test_query_params_str_validations_item_query_fixedquery(client: TestClient): - response = client.get("/items/", params={"item-query": "fixedquery"}) - assert response.status_code == 200 - assert response.json() == { - "items": [{"item_id": "Foo"}, {"item_id": "Bar"}], - "q": "fixedquery", - } - - -@needs_py39 -def test_query_params_str_validations_q_fixedquery(client: TestClient): - response = client.get("/items/", params={"q": "fixedquery"}) - assert response.status_code == 200 - assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - - -@needs_py39 -def test_query_params_str_validations_item_query_nonregexquery(client: TestClient): - response = client.get("/items/", params={"item-query": "nonregexquery"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "string_pattern_mismatch", - "loc": ["query", "item-query"], - "msg": "String should match pattern '^fixedquery$'", - "input": "nonregexquery", - "ctx": {"pattern": "^fixedquery$"}, - "url": match_pydantic_error_url("string_pattern_mismatch"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "ctx": {"pattern": "^fixedquery$"}, - "loc": ["query", "item-query"], - "msg": 'string does not match regex "^fixedquery$"', - "type": "value_error.str.regex", - } - ] - } - ) - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "description": "Query string for the items to search in the database that have a good match", - "required": False, - "deprecated": True, - "schema": IsDict( - { - "anyOf": [ - { - "type": "string", - "minLength": 3, - "maxLength": 50, - "pattern": "^fixedquery$", - }, - {"type": "null"}, - ], - "title": "Query string", - "description": "Query string for the items to search in the database that have a good match", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Query string", - "maxLength": 50, - "minLength": 3, - "pattern": "^fixedquery$", - "type": "string", - "description": "Query string for the items to search in the database that have a good match", - } - ), - "name": "item-query", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_py310.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_py310.py deleted file mode 100644 index 1c3a09d39..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_py310.py +++ /dev/null @@ -1,170 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial010_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_query_params_str_validations_no_query(client: TestClient): - response = client.get("/items/") - assert response.status_code == 200 - assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - - -@needs_py310 -def test_query_params_str_validations_item_query_fixedquery(client: TestClient): - response = client.get("/items/", params={"item-query": "fixedquery"}) - assert response.status_code == 200 - assert response.json() == { - "items": [{"item_id": "Foo"}, {"item_id": "Bar"}], - "q": "fixedquery", - } - - -@needs_py310 -def test_query_params_str_validations_q_fixedquery(client: TestClient): - response = client.get("/items/", params={"q": "fixedquery"}) - assert response.status_code == 200 - assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - - -@needs_py310 -def test_query_params_str_validations_item_query_nonregexquery(client: TestClient): - response = client.get("/items/", params={"item-query": "nonregexquery"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "string_pattern_mismatch", - "loc": ["query", "item-query"], - "msg": "String should match pattern '^fixedquery$'", - "input": "nonregexquery", - "ctx": {"pattern": "^fixedquery$"}, - "url": match_pydantic_error_url("string_pattern_mismatch"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "ctx": {"pattern": "^fixedquery$"}, - "loc": ["query", "item-query"], - "msg": 'string does not match regex "^fixedquery$"', - "type": "value_error.str.regex", - } - ] - } - ) - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "description": "Query string for the items to search in the database that have a good match", - "required": False, - "deprecated": True, - "schema": IsDict( - { - "anyOf": [ - { - "type": "string", - "minLength": 3, - "maxLength": 50, - "pattern": "^fixedquery$", - }, - {"type": "null"}, - ], - "title": "Query string", - "description": "Query string for the items to search in the database that have a good match", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Query string", - "maxLength": 50, - "minLength": 3, - "pattern": "^fixedquery$", - "type": "string", - "description": "Query string for the items to search in the database that have a good match", - } - ), - "name": "item-query", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011.py index 5ba39b05d..f4da25752 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011.py @@ -1,26 +1,47 @@ +import importlib + +import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from docs_src.query_params_str_validations.tutorial011 import app +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial011", + pytest.param("tutorial011_py39", marks=needs_py310), + pytest.param("tutorial011_py310", marks=needs_py310), + "tutorial011_an", + pytest.param("tutorial011_an_py39", marks=needs_py39), + pytest.param("tutorial011_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module( + f"docs_src.query_params_str_validations.{request.param}" + ) -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_multi_query_values(): +def test_multi_query_values(client: TestClient): url = "/items/?q=foo&q=bar" response = client.get(url) assert response.status_code == 200, response.text assert response.json() == {"q": ["foo", "bar"]} -def test_query_no_values(): +def test_query_no_values(client: TestClient): url = "/items/" response = client.get(url) assert response.status_code == 200, response.text assert response.json() == {"q": None} -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an.py deleted file mode 100644 index 3942ea77a..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an.py +++ /dev/null @@ -1,108 +0,0 @@ -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from docs_src.query_params_str_validations.tutorial011_an import app - -client = TestClient(app) - - -def test_multi_query_values(): - url = "/items/?q=foo&q=bar" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["foo", "bar"]} - - -def test_query_no_values(): - url = "/items/" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": None} - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [ - {"type": "array", "items": {"type": "string"}}, - {"type": "null"}, - ], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Q", - "type": "array", - "items": {"type": "string"}, - } - ), - "name": "q", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an_py310.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an_py310.py deleted file mode 100644 index f2ec38c95..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an_py310.py +++ /dev/null @@ -1,118 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial011_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_multi_query_values(client: TestClient): - url = "/items/?q=foo&q=bar" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["foo", "bar"]} - - -@needs_py310 -def test_query_no_values(client: TestClient): - url = "/items/" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": None} - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [ - {"type": "array", "items": {"type": "string"}}, - {"type": "null"}, - ], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Q", - "type": "array", - "items": {"type": "string"}, - } - ), - "name": "q", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an_py39.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an_py39.py deleted file mode 100644 index cd7b15679..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an_py39.py +++ /dev/null @@ -1,118 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial011_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_multi_query_values(client: TestClient): - url = "/items/?q=foo&q=bar" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["foo", "bar"]} - - -@needs_py39 -def test_query_no_values(client: TestClient): - url = "/items/" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": None} - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [ - {"type": "array", "items": {"type": "string"}}, - {"type": "null"}, - ], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Q", - "type": "array", - "items": {"type": "string"}, - } - ), - "name": "q", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_py310.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_py310.py deleted file mode 100644 index bdc729516..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_py310.py +++ /dev/null @@ -1,118 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial011_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_multi_query_values(client: TestClient): - url = "/items/?q=foo&q=bar" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["foo", "bar"]} - - -@needs_py310 -def test_query_no_values(client: TestClient): - url = "/items/" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": None} - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [ - {"type": "array", "items": {"type": "string"}}, - {"type": "null"}, - ], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Q", - "type": "array", - "items": {"type": "string"}, - } - ), - "name": "q", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_py39.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_py39.py deleted file mode 100644 index 26ac56b2f..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_py39.py +++ /dev/null @@ -1,118 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial011_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_multi_query_values(client: TestClient): - url = "/items/?q=foo&q=bar" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["foo", "bar"]} - - -@needs_py39 -def test_query_no_values(client: TestClient): - url = "/items/" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": None} - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [ - {"type": "array", "items": {"type": "string"}}, - {"type": "null"}, - ], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Q", - "type": "array", - "items": {"type": "string"}, - } - ), - "name": "q", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial012.py index 1436db384..549a90519 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial012.py @@ -1,25 +1,44 @@ +import importlib + +import pytest from fastapi.testclient import TestClient -from docs_src.query_params_str_validations.tutorial012 import app +from ...utils import needs_py39 + + +@pytest.fixture( + name="client", + params=[ + "tutorial012", + pytest.param("tutorial012_py39", marks=needs_py39), + "tutorial012_an", + pytest.param("tutorial012_an_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module( + f"docs_src.query_params_str_validations.{request.param}" + ) -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_default_query_values(): +def test_default_query_values(client: TestClient): url = "/items/" response = client.get(url) assert response.status_code == 200, response.text assert response.json() == {"q": ["foo", "bar"]} -def test_multi_query_values(): +def test_multi_query_values(client: TestClient): url = "/items/?q=baz&q=foobar" response = client.get(url) assert response.status_code == 200, response.text assert response.json() == {"q": ["baz", "foobar"]} -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_an.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_an.py deleted file mode 100644 index 270763f1d..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_an.py +++ /dev/null @@ -1,96 +0,0 @@ -from fastapi.testclient import TestClient - -from docs_src.query_params_str_validations.tutorial012_an import app - -client = TestClient(app) - - -def test_default_query_values(): - url = "/items/" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["foo", "bar"]} - - -def test_multi_query_values(): - url = "/items/?q=baz&q=foobar" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["baz", "foobar"]} - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Q", - "type": "array", - "items": {"type": "string"}, - "default": ["foo", "bar"], - }, - "name": "q", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_an_py39.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_an_py39.py deleted file mode 100644 index 548391683..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_an_py39.py +++ /dev/null @@ -1,106 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial012_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_default_query_values(client: TestClient): - url = "/items/" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["foo", "bar"]} - - -@needs_py39 -def test_multi_query_values(client: TestClient): - url = "/items/?q=baz&q=foobar" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["baz", "foobar"]} - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Q", - "type": "array", - "items": {"type": "string"}, - "default": ["foo", "bar"], - }, - "name": "q", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_py39.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_py39.py deleted file mode 100644 index e7d745154..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_py39.py +++ /dev/null @@ -1,106 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial012_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_default_query_values(client: TestClient): - url = "/items/" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["foo", "bar"]} - - -@needs_py39 -def test_multi_query_values(client: TestClient): - url = "/items/?q=baz&q=foobar" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["baz", "foobar"]} - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Q", - "type": "array", - "items": {"type": "string"}, - "default": ["foo", "bar"], - }, - "name": "q", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial013.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial013.py index 1ba1fdf61..f2f5f7a85 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial013.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial013.py @@ -1,25 +1,43 @@ +import importlib + +import pytest from fastapi.testclient import TestClient -from docs_src.query_params_str_validations.tutorial013 import app +from ...utils import needs_py39 + + +@pytest.fixture( + name="client", + params=[ + "tutorial013", + "tutorial013_an", + pytest.param("tutorial013_an_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module( + f"docs_src.query_params_str_validations.{request.param}" + ) -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_multi_query_values(): +def test_multi_query_values(client: TestClient): url = "/items/?q=foo&q=bar" response = client.get(url) assert response.status_code == 200, response.text assert response.json() == {"q": ["foo", "bar"]} -def test_query_no_values(): +def test_query_no_values(client: TestClient): url = "/items/" response = client.get(url) assert response.status_code == 200, response.text assert response.json() == {"q": []} -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial013_an.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial013_an.py deleted file mode 100644 index 343261748..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial013_an.py +++ /dev/null @@ -1,96 +0,0 @@ -from fastapi.testclient import TestClient - -from docs_src.query_params_str_validations.tutorial013_an import app - -client = TestClient(app) - - -def test_multi_query_values(): - url = "/items/?q=foo&q=bar" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["foo", "bar"]} - - -def test_query_no_values(): - url = "/items/" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": []} - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Q", - "type": "array", - "items": {}, - "default": [], - }, - "name": "q", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial013_an_py39.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial013_an_py39.py deleted file mode 100644 index 537d6325b..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial013_an_py39.py +++ /dev/null @@ -1,106 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial013_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_multi_query_values(client: TestClient): - url = "/items/?q=foo&q=bar" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["foo", "bar"]} - - -@needs_py39 -def test_query_no_values(client: TestClient): - url = "/items/" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": []} - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Q", - "type": "array", - "items": {}, - "default": [], - }, - "name": "q", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial014.py index 7bce7590c..edd40bb1a 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial014.py @@ -1,23 +1,43 @@ +import importlib + +import pytest from fastapi.testclient import TestClient -from docs_src.query_params_str_validations.tutorial014 import app +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial014", + pytest.param("tutorial014_py310", marks=needs_py310), + "tutorial014_an", + pytest.param("tutorial014_an_py39", marks=needs_py39), + pytest.param("tutorial014_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module( + f"docs_src.query_params_str_validations.{request.param}" + ) -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_hidden_query(): +def test_hidden_query(client: TestClient): response = client.get("/items?hidden_query=somevalue") assert response.status_code == 200, response.text assert response.json() == {"hidden_query": "somevalue"} -def test_no_hidden_query(): +def test_no_hidden_query(client: TestClient): response = client.get("/items") assert response.status_code == 200, response.text assert response.json() == {"hidden_query": "Not found"} -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an.py deleted file mode 100644 index 2182e87b7..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an.py +++ /dev/null @@ -1,81 +0,0 @@ -from fastapi.testclient import TestClient - -from docs_src.query_params_str_validations.tutorial014_an import app - -client = TestClient(app) - - -def test_hidden_query(): - response = client.get("/items?hidden_query=somevalue") - assert response.status_code == 200, response.text - assert response.json() == {"hidden_query": "somevalue"} - - -def test_no_hidden_query(): - response = client.get("/items") - assert response.status_code == 200, response.text - assert response.json() == {"hidden_query": "Not found"} - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an_py310.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an_py310.py deleted file mode 100644 index 344004d01..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an_py310.py +++ /dev/null @@ -1,91 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial014_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_hidden_query(client: TestClient): - response = client.get("/items?hidden_query=somevalue") - assert response.status_code == 200, response.text - assert response.json() == {"hidden_query": "somevalue"} - - -@needs_py310 -def test_no_hidden_query(client: TestClient): - response = client.get("/items") - assert response.status_code == 200, response.text - assert response.json() == {"hidden_query": "Not found"} - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an_py39.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an_py39.py deleted file mode 100644 index 5d4f6df3d..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an_py39.py +++ /dev/null @@ -1,91 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial014_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_hidden_query(client: TestClient): - response = client.get("/items?hidden_query=somevalue") - assert response.status_code == 200, response.text - assert response.json() == {"hidden_query": "somevalue"} - - -@needs_py310 -def test_no_hidden_query(client: TestClient): - response = client.get("/items") - assert response.status_code == 200, response.text - assert response.json() == {"hidden_query": "Not found"} - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_py310.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_py310.py deleted file mode 100644 index dad49fb12..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_py310.py +++ /dev/null @@ -1,91 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial014_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_hidden_query(client: TestClient): - response = client.get("/items?hidden_query=somevalue") - assert response.status_code == 200, response.text - assert response.json() == {"hidden_query": "somevalue"} - - -@needs_py310 -def test_no_hidden_query(client: TestClient): - response = client.get("/items") - assert response.status_code == 200, response.text - assert response.json() == {"hidden_query": "Not found"} - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial015.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial015.py new file mode 100644 index 000000000..ae1c40286 --- /dev/null +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial015.py @@ -0,0 +1,143 @@ +import importlib + +import pytest +from dirty_equals import IsStr +from fastapi.testclient import TestClient +from inline_snapshot import snapshot + +from ...utils import needs_py39, needs_py310, needs_pydanticv2 + + +@pytest.fixture( + name="client", + params=[ + pytest.param("tutorial015_an", marks=needs_pydanticv2), + pytest.param("tutorial015_an_py310", marks=(needs_py310, needs_pydanticv2)), + pytest.param("tutorial015_an_py39", marks=(needs_py39, needs_pydanticv2)), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module( + f"docs_src.query_params_str_validations.{request.param}" + ) + + client = TestClient(mod.app) + return client + + +def test_get_random_item(client: TestClient): + response = client.get("/items") + assert response.status_code == 200, response.text + assert response.json() == {"id": IsStr(), "name": IsStr()} + + +def test_get_item(client: TestClient): + response = client.get("/items?id=isbn-9781529046137") + assert response.status_code == 200, response.text + assert response.json() == { + "id": "isbn-9781529046137", + "name": "The Hitchhiker's Guide to the Galaxy", + } + + +def test_get_item_does_not_exist(client: TestClient): + response = client.get("/items?id=isbn-nope") + assert response.status_code == 200, response.text + assert response.json() == {"id": "isbn-nope", "name": None} + + +def test_get_invalid_item(client: TestClient): + response = client.get("/items?id=wtf-yes") + assert response.status_code == 422, response.text + assert response.json() == snapshot( + { + "detail": [ + { + "type": "value_error", + "loc": ["query", "id"], + "msg": 'Value error, Invalid ID format, it must start with "isbn-" or "imdb-"', + "input": "wtf-yes", + "ctx": {"error": {}}, + } + ] + } + ) + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "parameters": [ + { + "name": "id", + "in": "query", + "required": False, + "schema": { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Id", + }, + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } + ) diff --git a/tests/test_tutorial/test_request_files/test_tutorial001.py b/tests/test_tutorial/test_request_files/test_tutorial001.py index 91cc2b636..b06919961 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial001.py +++ b/tests/test_tutorial/test_request_files/test_tutorial001.py @@ -1,24 +1,28 @@ +import importlib + +import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url -from docs_src.request_files.tutorial001 import app +from ...utils import needs_py39 -client = TestClient(app) +@pytest.fixture( + name="client", + params=[ + "tutorial001", + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.request_files.{request.param}") -file_required = { - "detail": [ - { - "loc": ["body", "file"], - "msg": "field required", - "type": "value_error.missing", - } - ] -} + client = TestClient(mod.app) + return client -def test_post_form_no_body(): +def test_post_form_no_body(client: TestClient): response = client.post("/files/") assert response.status_code == 422, response.text assert response.json() == IsDict( @@ -29,7 +33,6 @@ def test_post_form_no_body(): "loc": ["body", "file"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -47,7 +50,7 @@ def test_post_form_no_body(): ) -def test_post_body_json(): +def test_post_body_json(client: TestClient): response = client.post("/files/", json={"file": "Foo"}) assert response.status_code == 422, response.text assert response.json() == IsDict( @@ -58,7 +61,6 @@ def test_post_body_json(): "loc": ["body", "file"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -76,41 +78,38 @@ def test_post_body_json(): ) -def test_post_file(tmp_path): +def test_post_file(tmp_path, client: TestClient): path = tmp_path / "test.txt" path.write_bytes(b"") - client = TestClient(app) with path.open("rb") as file: response = client.post("/files/", files={"file": file}) assert response.status_code == 200, response.text assert response.json() == {"file_size": 14} -def test_post_large_file(tmp_path): +def test_post_large_file(tmp_path, client: TestClient): default_pydantic_max_size = 2**16 path = tmp_path / "test.txt" path.write_bytes(b"x" * (default_pydantic_max_size + 1)) - client = TestClient(app) with path.open("rb") as file: response = client.post("/files/", files={"file": file}) assert response.status_code == 200, response.text assert response.json() == {"file_size": default_pydantic_max_size + 1} -def test_post_upload_file(tmp_path): +def test_post_upload_file(tmp_path, client: TestClient): path = tmp_path / "test.txt" path.write_bytes(b"") - client = TestClient(app) with path.open("rb") as file: response = client.post("/uploadfile/", files={"file": file}) assert response.status_code == 200, response.text assert response.json() == {"filename": "test.txt"} -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_02.py b/tests/test_tutorial/test_request_files/test_tutorial001_02.py index 42f75442a..9075a1756 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial001_02.py +++ b/tests/test_tutorial/test_request_files/test_tutorial001_02.py @@ -1,46 +1,63 @@ +import importlib +from pathlib import Path + +import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from docs_src.request_files.tutorial001_02 import app +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial001_02", + pytest.param("tutorial001_02_py310", marks=needs_py310), + "tutorial001_02_an", + pytest.param("tutorial001_02_an_py39", marks=needs_py39), + pytest.param("tutorial001_02_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.request_files.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_post_form_no_body(): +def test_post_form_no_body(client: TestClient): response = client.post("/files/") assert response.status_code == 200, response.text assert response.json() == {"message": "No file sent"} -def test_post_uploadfile_no_body(): +def test_post_uploadfile_no_body(client: TestClient): response = client.post("/uploadfile/") assert response.status_code == 200, response.text assert response.json() == {"message": "No upload file sent"} -def test_post_file(tmp_path): +def test_post_file(tmp_path: Path, client: TestClient): path = tmp_path / "test.txt" path.write_bytes(b"") - client = TestClient(app) with path.open("rb") as file: response = client.post("/files/", files={"file": file}) assert response.status_code == 200, response.text assert response.json() == {"file_size": 14} -def test_post_upload_file(tmp_path): +def test_post_upload_file(tmp_path: Path, client: TestClient): path = tmp_path / "test.txt" path.write_bytes(b"") - client = TestClient(app) with path.open("rb") as file: response = client.post("/uploadfile/", files={"file": file}) assert response.status_code == 200, response.text assert response.json() == {"filename": "test.txt"} -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_02_an.py b/tests/test_tutorial/test_request_files/test_tutorial001_02_an.py deleted file mode 100644 index f63eb339c..000000000 --- a/tests/test_tutorial/test_request_files/test_tutorial001_02_an.py +++ /dev/null @@ -1,208 +0,0 @@ -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from docs_src.request_files.tutorial001_02_an import app - -client = TestClient(app) - - -def test_post_form_no_body(): - response = client.post("/files/") - assert response.status_code == 200, response.text - assert response.json() == {"message": "No file sent"} - - -def test_post_uploadfile_no_body(): - response = client.post("/uploadfile/") - assert response.status_code == 200, response.text - assert response.json() == {"message": "No upload file sent"} - - -def test_post_file(tmp_path): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file: - response = client.post("/files/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"file_size": 14} - - -def test_post_upload_file(tmp_path): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file: - response = client.post("/uploadfile/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"filename": "test.txt"} - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/files/": { - "post": { - "summary": "Create File", - "operationId": "create_file_files__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": IsDict( - { - "allOf": [ - { - "$ref": "#/components/schemas/Body_create_file_files__post" - } - ], - "title": "Body", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "$ref": "#/components/schemas/Body_create_file_files__post" - } - ) - } - } - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/uploadfile/": { - "post": { - "summary": "Create Upload File", - "operationId": "create_upload_file_uploadfile__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": IsDict( - { - "allOf": [ - { - "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" - } - ], - "title": "Body", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" - } - ) - } - } - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - }, - "components": { - "schemas": { - "Body_create_file_files__post": { - "title": "Body_create_file_files__post", - "type": "object", - "properties": { - "file": IsDict( - { - "title": "File", - "anyOf": [ - {"type": "string", "format": "binary"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "File", "type": "string", "format": "binary"} - ) - }, - }, - "Body_create_upload_file_uploadfile__post": { - "title": "Body_create_upload_file_uploadfile__post", - "type": "object", - "properties": { - "file": IsDict( - { - "title": "File", - "anyOf": [ - {"type": "string", "format": "binary"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "File", "type": "string", "format": "binary"} - ) - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_02_an_py310.py b/tests/test_tutorial/test_request_files/test_tutorial001_02_an_py310.py deleted file mode 100644 index 94b6ac67e..000000000 --- a/tests/test_tutorial/test_request_files/test_tutorial001_02_an_py310.py +++ /dev/null @@ -1,220 +0,0 @@ -from pathlib import Path - -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.request_files.tutorial001_02_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_post_form_no_body(client: TestClient): - response = client.post("/files/") - assert response.status_code == 200, response.text - assert response.json() == {"message": "No file sent"} - - -@needs_py310 -def test_post_uploadfile_no_body(client: TestClient): - response = client.post("/uploadfile/") - assert response.status_code == 200, response.text - assert response.json() == {"message": "No upload file sent"} - - -@needs_py310 -def test_post_file(tmp_path: Path, client: TestClient): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - with path.open("rb") as file: - response = client.post("/files/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"file_size": 14} - - -@needs_py310 -def test_post_upload_file(tmp_path: Path, client: TestClient): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - with path.open("rb") as file: - response = client.post("/uploadfile/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"filename": "test.txt"} - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/files/": { - "post": { - "summary": "Create File", - "operationId": "create_file_files__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": IsDict( - { - "allOf": [ - { - "$ref": "#/components/schemas/Body_create_file_files__post" - } - ], - "title": "Body", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "$ref": "#/components/schemas/Body_create_file_files__post" - } - ) - } - } - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/uploadfile/": { - "post": { - "summary": "Create Upload File", - "operationId": "create_upload_file_uploadfile__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": IsDict( - { - "allOf": [ - { - "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" - } - ], - "title": "Body", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" - } - ) - } - } - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - }, - "components": { - "schemas": { - "Body_create_file_files__post": { - "title": "Body_create_file_files__post", - "type": "object", - "properties": { - "file": IsDict( - { - "title": "File", - "anyOf": [ - {"type": "string", "format": "binary"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "File", "type": "string", "format": "binary"} - ) - }, - }, - "Body_create_upload_file_uploadfile__post": { - "title": "Body_create_upload_file_uploadfile__post", - "type": "object", - "properties": { - "file": IsDict( - { - "title": "File", - "anyOf": [ - {"type": "string", "format": "binary"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "File", "type": "string", "format": "binary"} - ) - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_02_an_py39.py b/tests/test_tutorial/test_request_files/test_tutorial001_02_an_py39.py deleted file mode 100644 index fcb39f8f1..000000000 --- a/tests/test_tutorial/test_request_files/test_tutorial001_02_an_py39.py +++ /dev/null @@ -1,220 +0,0 @@ -from pathlib import Path - -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.request_files.tutorial001_02_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_post_form_no_body(client: TestClient): - response = client.post("/files/") - assert response.status_code == 200, response.text - assert response.json() == {"message": "No file sent"} - - -@needs_py39 -def test_post_uploadfile_no_body(client: TestClient): - response = client.post("/uploadfile/") - assert response.status_code == 200, response.text - assert response.json() == {"message": "No upload file sent"} - - -@needs_py39 -def test_post_file(tmp_path: Path, client: TestClient): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - with path.open("rb") as file: - response = client.post("/files/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"file_size": 14} - - -@needs_py39 -def test_post_upload_file(tmp_path: Path, client: TestClient): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - with path.open("rb") as file: - response = client.post("/uploadfile/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"filename": "test.txt"} - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/files/": { - "post": { - "summary": "Create File", - "operationId": "create_file_files__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": IsDict( - { - "allOf": [ - { - "$ref": "#/components/schemas/Body_create_file_files__post" - } - ], - "title": "Body", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "$ref": "#/components/schemas/Body_create_file_files__post" - } - ) - } - } - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/uploadfile/": { - "post": { - "summary": "Create Upload File", - "operationId": "create_upload_file_uploadfile__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": IsDict( - { - "allOf": [ - { - "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" - } - ], - "title": "Body", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" - } - ) - } - } - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - }, - "components": { - "schemas": { - "Body_create_file_files__post": { - "title": "Body_create_file_files__post", - "type": "object", - "properties": { - "file": IsDict( - { - "title": "File", - "anyOf": [ - {"type": "string", "format": "binary"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "File", "type": "string", "format": "binary"} - ) - }, - }, - "Body_create_upload_file_uploadfile__post": { - "title": "Body_create_upload_file_uploadfile__post", - "type": "object", - "properties": { - "file": IsDict( - { - "title": "File", - "anyOf": [ - {"type": "string", "format": "binary"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "File", "type": "string", "format": "binary"} - ) - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_02_py310.py b/tests/test_tutorial/test_request_files/test_tutorial001_02_py310.py deleted file mode 100644 index a700752a3..000000000 --- a/tests/test_tutorial/test_request_files/test_tutorial001_02_py310.py +++ /dev/null @@ -1,220 +0,0 @@ -from pathlib import Path - -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.request_files.tutorial001_02_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_post_form_no_body(client: TestClient): - response = client.post("/files/") - assert response.status_code == 200, response.text - assert response.json() == {"message": "No file sent"} - - -@needs_py310 -def test_post_uploadfile_no_body(client: TestClient): - response = client.post("/uploadfile/") - assert response.status_code == 200, response.text - assert response.json() == {"message": "No upload file sent"} - - -@needs_py310 -def test_post_file(tmp_path: Path, client: TestClient): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - with path.open("rb") as file: - response = client.post("/files/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"file_size": 14} - - -@needs_py310 -def test_post_upload_file(tmp_path: Path, client: TestClient): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - with path.open("rb") as file: - response = client.post("/uploadfile/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"filename": "test.txt"} - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/files/": { - "post": { - "summary": "Create File", - "operationId": "create_file_files__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": IsDict( - { - "allOf": [ - { - "$ref": "#/components/schemas/Body_create_file_files__post" - } - ], - "title": "Body", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "$ref": "#/components/schemas/Body_create_file_files__post" - } - ) - } - } - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/uploadfile/": { - "post": { - "summary": "Create Upload File", - "operationId": "create_upload_file_uploadfile__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": IsDict( - { - "allOf": [ - { - "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" - } - ], - "title": "Body", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" - } - ) - } - } - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - }, - "components": { - "schemas": { - "Body_create_file_files__post": { - "title": "Body_create_file_files__post", - "type": "object", - "properties": { - "file": IsDict( - { - "title": "File", - "anyOf": [ - {"type": "string", "format": "binary"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "File", "type": "string", "format": "binary"} - ) - }, - }, - "Body_create_upload_file_uploadfile__post": { - "title": "Body_create_upload_file_uploadfile__post", - "type": "object", - "properties": { - "file": IsDict( - { - "title": "File", - "anyOf": [ - {"type": "string", "format": "binary"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "File", "type": "string", "format": "binary"} - ) - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_03.py b/tests/test_tutorial/test_request_files/test_tutorial001_03.py index f02170814..9fbe2166c 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial001_03.py +++ b/tests/test_tutorial/test_request_files/test_tutorial001_03.py @@ -1,33 +1,47 @@ +import importlib + +import pytest from fastapi.testclient import TestClient -from docs_src.request_files.tutorial001_03 import app +from ...utils import needs_py39 + + +@pytest.fixture( + name="client", + params=[ + "tutorial001_03", + "tutorial001_03_an", + pytest.param("tutorial001_03_an_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.request_files.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_post_file(tmp_path): +def test_post_file(tmp_path, client: TestClient): path = tmp_path / "test.txt" path.write_bytes(b"") - client = TestClient(app) with path.open("rb") as file: response = client.post("/files/", files={"file": file}) assert response.status_code == 200, response.text assert response.json() == {"file_size": 14} -def test_post_upload_file(tmp_path): +def test_post_upload_file(tmp_path, client: TestClient): path = tmp_path / "test.txt" path.write_bytes(b"") - client = TestClient(app) with path.open("rb") as file: response = client.post("/uploadfile/", files={"file": file}) assert response.status_code == 200, response.text assert response.json() == {"filename": "test.txt"} -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_03_an.py b/tests/test_tutorial/test_request_files/test_tutorial001_03_an.py deleted file mode 100644 index acfb749ce..000000000 --- a/tests/test_tutorial/test_request_files/test_tutorial001_03_an.py +++ /dev/null @@ -1,159 +0,0 @@ -from fastapi.testclient import TestClient - -from docs_src.request_files.tutorial001_03_an import app - -client = TestClient(app) - - -def test_post_file(tmp_path): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file: - response = client.post("/files/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"file_size": 14} - - -def test_post_upload_file(tmp_path): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file: - response = client.post("/uploadfile/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"filename": "test.txt"} - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/files/": { - "post": { - "summary": "Create File", - "operationId": "create_file_files__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": { - "$ref": "#/components/schemas/Body_create_file_files__post" - } - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/uploadfile/": { - "post": { - "summary": "Create Upload File", - "operationId": "create_upload_file_uploadfile__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": { - "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" - } - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - }, - "components": { - "schemas": { - "Body_create_file_files__post": { - "title": "Body_create_file_files__post", - "required": ["file"], - "type": "object", - "properties": { - "file": { - "title": "File", - "type": "string", - "description": "A file read as bytes", - "format": "binary", - } - }, - }, - "Body_create_upload_file_uploadfile__post": { - "title": "Body_create_upload_file_uploadfile__post", - "required": ["file"], - "type": "object", - "properties": { - "file": { - "title": "File", - "type": "string", - "description": "A file read as UploadFile", - "format": "binary", - } - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_03_an_py39.py b/tests/test_tutorial/test_request_files/test_tutorial001_03_an_py39.py deleted file mode 100644 index 36e5faac1..000000000 --- a/tests/test_tutorial/test_request_files/test_tutorial001_03_an_py39.py +++ /dev/null @@ -1,167 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.request_files.tutorial001_03_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_post_file(tmp_path, client: TestClient): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - with path.open("rb") as file: - response = client.post("/files/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"file_size": 14} - - -@needs_py39 -def test_post_upload_file(tmp_path, client: TestClient): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - with path.open("rb") as file: - response = client.post("/uploadfile/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"filename": "test.txt"} - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/files/": { - "post": { - "summary": "Create File", - "operationId": "create_file_files__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": { - "$ref": "#/components/schemas/Body_create_file_files__post" - } - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - "/uploadfile/": { - "post": { - "summary": "Create Upload File", - "operationId": "create_upload_file_uploadfile__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": { - "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" - } - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - }, - }, - "components": { - "schemas": { - "Body_create_file_files__post": { - "title": "Body_create_file_files__post", - "required": ["file"], - "type": "object", - "properties": { - "file": { - "title": "File", - "type": "string", - "description": "A file read as bytes", - "format": "binary", - } - }, - }, - "Body_create_upload_file_uploadfile__post": { - "title": "Body_create_upload_file_uploadfile__post", - "required": ["file"], - "type": "object", - "properties": { - "file": { - "title": "File", - "type": "string", - "description": "A file read as UploadFile", - "format": "binary", - } - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_an.py b/tests/test_tutorial/test_request_files/test_tutorial001_an.py deleted file mode 100644 index 3021eb3c3..000000000 --- a/tests/test_tutorial/test_request_files/test_tutorial001_an.py +++ /dev/null @@ -1,221 +0,0 @@ -from dirty_equals import IsDict -from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url - -from docs_src.request_files.tutorial001_an import app - -client = TestClient(app) - - -def test_post_form_no_body(): - response = client.post("/files/") - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "file"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "file"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -def test_post_body_json(): - response = client.post("/files/", json={"file": "Foo"}) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "file"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "file"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -def test_post_file(tmp_path): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file: - response = client.post("/files/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"file_size": 14} - - -def test_post_large_file(tmp_path): - default_pydantic_max_size = 2**16 - path = tmp_path / "test.txt" - path.write_bytes(b"x" * (default_pydantic_max_size + 1)) - - client = TestClient(app) - with path.open("rb") as file: - response = client.post("/files/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"file_size": default_pydantic_max_size + 1} - - -def test_post_upload_file(tmp_path): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file: - response = client.post("/uploadfile/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"filename": "test.txt"} - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/files/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create File", - "operationId": "create_file_files__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": { - "$ref": "#/components/schemas/Body_create_file_files__post" - } - } - }, - "required": True, - }, - } - }, - "/uploadfile/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Upload File", - "operationId": "create_upload_file_uploadfile__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": { - "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" - } - } - }, - "required": True, - }, - } - }, - }, - "components": { - "schemas": { - "Body_create_upload_file_uploadfile__post": { - "title": "Body_create_upload_file_uploadfile__post", - "required": ["file"], - "type": "object", - "properties": { - "file": {"title": "File", "type": "string", "format": "binary"} - }, - }, - "Body_create_file_files__post": { - "title": "Body_create_file_files__post", - "required": ["file"], - "type": "object", - "properties": { - "file": {"title": "File", "type": "string", "format": "binary"} - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_request_files/test_tutorial001_an_py39.py b/tests/test_tutorial/test_request_files/test_tutorial001_an_py39.py deleted file mode 100644 index 04f3a4693..000000000 --- a/tests/test_tutorial/test_request_files/test_tutorial001_an_py39.py +++ /dev/null @@ -1,231 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.request_files.tutorial001_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_post_form_no_body(client: TestClient): - response = client.post("/files/") - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "file"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "file"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -@needs_py39 -def test_post_body_json(client: TestClient): - response = client.post("/files/", json={"file": "Foo"}) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "file"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "file"], - "msg": "field required", - "type": "value_error.missing", - } - ] - } - ) - - -@needs_py39 -def test_post_file(tmp_path, client: TestClient): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - with path.open("rb") as file: - response = client.post("/files/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"file_size": 14} - - -@needs_py39 -def test_post_large_file(tmp_path, client: TestClient): - default_pydantic_max_size = 2**16 - path = tmp_path / "test.txt" - path.write_bytes(b"x" * (default_pydantic_max_size + 1)) - - with path.open("rb") as file: - response = client.post("/files/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"file_size": default_pydantic_max_size + 1} - - -@needs_py39 -def test_post_upload_file(tmp_path, client: TestClient): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - with path.open("rb") as file: - response = client.post("/uploadfile/", files={"file": file}) - assert response.status_code == 200, response.text - assert response.json() == {"filename": "test.txt"} - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/files/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create File", - "operationId": "create_file_files__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": { - "$ref": "#/components/schemas/Body_create_file_files__post" - } - } - }, - "required": True, - }, - } - }, - "/uploadfile/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Upload File", - "operationId": "create_upload_file_uploadfile__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": { - "$ref": "#/components/schemas/Body_create_upload_file_uploadfile__post" - } - } - }, - "required": True, - }, - } - }, - }, - "components": { - "schemas": { - "Body_create_upload_file_uploadfile__post": { - "title": "Body_create_upload_file_uploadfile__post", - "required": ["file"], - "type": "object", - "properties": { - "file": {"title": "File", "type": "string", "format": "binary"} - }, - }, - "Body_create_file_files__post": { - "title": "Body_create_file_files__post", - "required": ["file"], - "type": "object", - "properties": { - "file": {"title": "File", "type": "string", "format": "binary"} - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_request_files/test_tutorial002.py b/tests/test_tutorial/test_request_files/test_tutorial002.py index ed9680b62..446a87657 100644 --- a/tests/test_tutorial/test_request_files/test_tutorial002.py +++ b/tests/test_tutorial/test_request_files/test_tutorial002.py @@ -1,13 +1,35 @@ +import importlib + +import pytest from dirty_equals import IsDict +from fastapi import FastAPI from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url -from docs_src.request_files.tutorial002 import app +from ...utils import needs_py39 + + +@pytest.fixture( + name="app", + params=[ + "tutorial002", + "tutorial002_an", + pytest.param("tutorial002_py39", marks=needs_py39), + pytest.param("tutorial002_an_py39", marks=needs_py39), + ], +) +def get_app(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.request_files.{request.param}") -client = TestClient(app) + return mod.app + + +@pytest.fixture(name="client") +def get_client(app: FastAPI): + client = TestClient(app) + return client -def test_post_form_no_body(): +def test_post_form_no_body(client: TestClient): response = client.post("/files/") assert response.status_code == 422, response.text assert response.json() == IsDict( @@ -18,7 +40,6 @@ def test_post_form_no_body(): "loc": ["body", "files"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -36,7 +57,7 @@ def test_post_form_no_body(): ) -def test_post_body_json(): +def test_post_body_json(client: TestClient): response = client.post("/files/", json={"file": "Foo"}) assert response.status_code == 422, response.text assert response.json() == IsDict( @@ -47,7 +68,6 @@ def test_post_body_json(): "loc": ["body", "files"], "msg": "Field required", "input": None, - "url": match_pydantic_error_url("missing"), } ] } @@ -65,7 +85,7 @@ def test_post_body_json(): ) -def test_post_files(tmp_path): +def test_post_files(tmp_path, app: FastAPI): path = tmp_path / "test.txt" path.write_bytes(b"") path2 = tmp_path / "test2.txt" @@ -84,7 +104,7 @@ def test_post_files(tmp_path): assert response.json() == {"file_sizes": [14, 15]} -def test_post_upload_file(tmp_path): +def test_post_upload_file(tmp_path, app: FastAPI): path = tmp_path / "test.txt" path.write_bytes(b"") path2 = tmp_path / "test2.txt" @@ -103,14 +123,14 @@ def test_post_upload_file(tmp_path): assert response.json() == {"filenames": ["test.txt", "test2.txt"]} -def test_get_root(): +def test_get_root(app: FastAPI): client = TestClient(app) response = client.get("/") assert response.status_code == 200, response.text assert b"") - path2 = tmp_path / "test2.txt" - path2.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file, path2.open("rb") as file2: - response = client.post( - "/files/", - files=( - ("files", ("test.txt", file)), - ("files", ("test2.txt", file2)), - ), - ) - assert response.status_code == 200, response.text - assert response.json() == {"file_sizes": [14, 15]} - - -def test_post_upload_file(tmp_path): - path = tmp_path / "test.txt" - path.write_bytes(b"") - path2 = tmp_path / "test2.txt" - path2.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file, path2.open("rb") as file2: - response = client.post( - "/uploadfiles/", - files=( - ("files", ("test.txt", file)), - ("files", ("test2.txt", file2)), - ), - ) - assert response.status_code == 200, response.text - assert response.json() == {"filenames": ["test.txt", "test2.txt"]} - - -def test_get_root(): - client = TestClient(app) - response = client.get("/") - assert response.status_code == 200, response.text - assert b"") - path2 = tmp_path / "test2.txt" - path2.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file, path2.open("rb") as file2: - response = client.post( - "/files/", - files=( - ("files", ("test.txt", file)), - ("files", ("test2.txt", file2)), - ), - ) - assert response.status_code == 200, response.text - assert response.json() == {"file_sizes": [14, 15]} - - -@needs_py39 -def test_post_upload_file(tmp_path, app: FastAPI): - path = tmp_path / "test.txt" - path.write_bytes(b"") - path2 = tmp_path / "test2.txt" - path2.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file, path2.open("rb") as file2: - response = client.post( - "/uploadfiles/", - files=( - ("files", ("test.txt", file)), - ("files", ("test2.txt", file2)), - ), - ) - assert response.status_code == 200, response.text - assert response.json() == {"filenames": ["test.txt", "test2.txt"]} - - -@needs_py39 -def test_get_root(app: FastAPI): - client = TestClient(app) - response = client.get("/") - assert response.status_code == 200, response.text - assert b"") - path2 = tmp_path / "test2.txt" - path2.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file, path2.open("rb") as file2: - response = client.post( - "/files/", - files=( - ("files", ("test.txt", file)), - ("files", ("test2.txt", file2)), - ), - ) - assert response.status_code == 200, response.text - assert response.json() == {"file_sizes": [14, 15]} - - -@needs_py39 -def test_post_upload_file(tmp_path, app: FastAPI): - path = tmp_path / "test.txt" - path.write_bytes(b"") - path2 = tmp_path / "test2.txt" - path2.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file, path2.open("rb") as file2: - response = client.post( - "/uploadfiles/", - files=( - ("files", ("test.txt", file)), - ("files", ("test2.txt", file2)), - ), - ) - assert response.status_code == 200, response.text - assert response.json() == {"filenames": ["test.txt", "test2.txt"]} - - -@needs_py39 -def test_get_root(app: FastAPI): - client = TestClient(app) - response = client.get("/") - assert response.status_code == 200, response.text - assert b"") path2 = tmp_path / "test2.txt" @@ -24,7 +47,7 @@ def test_post_files(tmp_path): assert response.json() == {"file_sizes": [14, 15]} -def test_post_upload_file(tmp_path): +def test_post_upload_file(tmp_path, app: FastAPI): path = tmp_path / "test.txt" path.write_bytes(b"") path2 = tmp_path / "test2.txt" @@ -43,14 +66,14 @@ def test_post_upload_file(tmp_path): assert response.json() == {"filenames": ["test.txt", "test2.txt"]} -def test_get_root(): +def test_get_root(app: FastAPI): client = TestClient(app) response = client.get("/") assert response.status_code == 200, response.text assert b"") - path2 = tmp_path / "test2.txt" - path2.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file, path2.open("rb") as file2: - response = client.post( - "/files/", - files=( - ("files", ("test.txt", file)), - ("files", ("test2.txt", file2)), - ), - ) - assert response.status_code == 200, response.text - assert response.json() == {"file_sizes": [14, 15]} - - -def test_post_upload_file(tmp_path): - path = tmp_path / "test.txt" - path.write_bytes(b"") - path2 = tmp_path / "test2.txt" - path2.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file, path2.open("rb") as file2: - response = client.post( - "/uploadfiles/", - files=( - ("files", ("test.txt", file)), - ("files", ("test2.txt", file2)), - ), - ) - assert response.status_code == 200, response.text - assert response.json() == {"filenames": ["test.txt", "test2.txt"]} - - -def test_get_root(): - client = TestClient(app) - response = client.get("/") - assert response.status_code == 200, response.text - assert b"") - path2 = tmp_path / "test2.txt" - path2.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file, path2.open("rb") as file2: - response = client.post( - "/files/", - files=( - ("files", ("test.txt", file)), - ("files", ("test2.txt", file2)), - ), - ) - assert response.status_code == 200, response.text - assert response.json() == {"file_sizes": [14, 15]} - - -@needs_py39 -def test_post_upload_file(tmp_path, app: FastAPI): - path = tmp_path / "test.txt" - path.write_bytes(b"") - path2 = tmp_path / "test2.txt" - path2.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file, path2.open("rb") as file2: - response = client.post( - "/uploadfiles/", - files=( - ("files", ("test.txt", file)), - ("files", ("test2.txt", file2)), - ), - ) - assert response.status_code == 200, response.text - assert response.json() == {"filenames": ["test.txt", "test2.txt"]} - - -@needs_py39 -def test_get_root(app: FastAPI): - client = TestClient(app) - response = client.get("/") - assert response.status_code == 200, response.text - assert b"") - path2 = tmp_path / "test2.txt" - path2.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file, path2.open("rb") as file2: - response = client.post( - "/files/", - files=( - ("files", ("test.txt", file)), - ("files", ("test2.txt", file2)), - ), - ) - assert response.status_code == 200, response.text - assert response.json() == {"file_sizes": [14, 15]} - - -@needs_py39 -def test_post_upload_file(tmp_path, app: FastAPI): - path = tmp_path / "test.txt" - path.write_bytes(b"") - path2 = tmp_path / "test2.txt" - path2.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file, path2.open("rb") as file2: - response = client.post( - "/uploadfiles/", - files=( - ("files", ("test.txt", file)), - ("files", ("test2.txt", file2)), - ), - ) - assert response.status_code == 200, response.text - assert response.json() == {"filenames": ["test.txt", "test2.txt"]} - - -@needs_py39 -def test_get_root(app: FastAPI): - client = TestClient(app) - response = client.get("/") - assert response.status_code == 200, response.text - assert b"") - - client = TestClient(app) - with path.open("rb") as file: - response = client.post("/files/", files={"file": file}) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "fileb"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - { - "type": "missing", - "loc": ["body", "token"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "fileb"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -def test_post_files_and_token(tmp_path, app: FastAPI): - patha = tmp_path / "test.txt" - pathb = tmp_path / "testb.txt" - patha.write_text("") - pathb.write_text("") - - client = TestClient(app) - with patha.open("rb") as filea, pathb.open("rb") as fileb: - response = client.post( - "/files/", - data={"token": "foo"}, - files={"file": filea, "fileb": ("testb.txt", fileb, "text/plain")}, - ) - assert response.status_code == 200, response.text - assert response.json() == { - "file_size": 14, - "token": "foo", - "fileb_content_type": "text/plain", - } - - -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/files/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create File", - "operationId": "create_file_files__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": { - "$ref": "#/components/schemas/Body_create_file_files__post" - } - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "Body_create_file_files__post": { - "title": "Body_create_file_files__post", - "required": ["file", "fileb", "token"], - "type": "object", - "properties": { - "file": {"title": "File", "type": "string", "format": "binary"}, - "fileb": { - "title": "Fileb", - "type": "string", - "format": "binary", - }, - "token": {"title": "Token", "type": "string"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an_py39.py b/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an_py39.py deleted file mode 100644 index 3d007e90b..000000000 --- a/tests/test_tutorial/test_request_forms_and_files/test_tutorial001_an_py39.py +++ /dev/null @@ -1,328 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi import FastAPI -from fastapi.testclient import TestClient -from fastapi.utils import match_pydantic_error_url - -from ...utils import needs_py39 - - -@pytest.fixture(name="app") -def get_app(): - from docs_src.request_forms_and_files.tutorial001_an_py39 import app - - return app - - -@pytest.fixture(name="client") -def get_client(app: FastAPI): - client = TestClient(app) - return client - - -@needs_py39 -def test_post_form_no_body(client: TestClient): - response = client.post("/files/") - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "file"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - { - "type": "missing", - "loc": ["body", "fileb"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - { - "type": "missing", - "loc": ["body", "token"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "file"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "fileb"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_post_form_no_file(client: TestClient): - response = client.post("/files/", data={"token": "foo"}) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "file"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - { - "type": "missing", - "loc": ["body", "fileb"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "file"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "fileb"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_post_body_json(client: TestClient): - response = client.post("/files/", json={"file": "Foo", "token": "Bar"}) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "file"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - { - "type": "missing", - "loc": ["body", "fileb"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - { - "type": "missing", - "loc": ["body", "token"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "file"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "fileb"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_post_file_no_token(tmp_path, app: FastAPI): - path = tmp_path / "test.txt" - path.write_bytes(b"") - - client = TestClient(app) - with path.open("rb") as file: - response = client.post("/files/", files={"file": file}) - assert response.status_code == 422, response.text - assert response.json() == IsDict( - { - "detail": [ - { - "type": "missing", - "loc": ["body", "fileb"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - { - "type": "missing", - "loc": ["body", "token"], - "msg": "Field required", - "input": None, - "url": match_pydantic_error_url("missing"), - }, - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "loc": ["body", "fileb"], - "msg": "field required", - "type": "value_error.missing", - }, - { - "loc": ["body", "token"], - "msg": "field required", - "type": "value_error.missing", - }, - ] - } - ) - - -@needs_py39 -def test_post_files_and_token(tmp_path, app: FastAPI): - patha = tmp_path / "test.txt" - pathb = tmp_path / "testb.txt" - patha.write_text("") - pathb.write_text("") - - client = TestClient(app) - with patha.open("rb") as filea, pathb.open("rb") as fileb: - response = client.post( - "/files/", - data={"token": "foo"}, - files={"file": filea, "fileb": ("testb.txt", fileb, "text/plain")}, - ) - assert response.status_code == 200, response.text - assert response.json() == { - "file_size": 14, - "token": "foo", - "fileb_content_type": "text/plain", - } - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/files/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create File", - "operationId": "create_file_files__post", - "requestBody": { - "content": { - "multipart/form-data": { - "schema": { - "$ref": "#/components/schemas/Body_create_file_files__post" - } - } - }, - "required": True, - }, - } - } - }, - "components": { - "schemas": { - "Body_create_file_files__post": { - "title": "Body_create_file_files__post", - "required": ["file", "fileb", "token"], - "type": "object", - "properties": { - "file": {"title": "File", "type": "string", "format": "binary"}, - "fileb": { - "title": "Fileb", - "type": "string", - "format": "binary", - }, - "token": {"title": "Token", "type": "string"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_response_model/test_tutorial003_01.py b/tests/test_tutorial/test_response_model/test_tutorial003_01.py index 3a6a0b20d..3975856b6 100644 --- a/tests/test_tutorial/test_response_model/test_tutorial003_01.py +++ b/tests/test_tutorial/test_response_model/test_tutorial003_01.py @@ -1,12 +1,27 @@ +import importlib + +import pytest from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient -from docs_src.response_model.tutorial003_01 import app +from ...utils import needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial003_01", + pytest.param("tutorial003_01_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.response_model.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_post_user(): +def test_post_user(client: TestClient): response = client.post( "/user/", json={ @@ -24,7 +39,7 @@ def test_post_user(): } -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_response_model/test_tutorial003_01_py310.py b/tests/test_tutorial/test_response_model/test_tutorial003_01_py310.py deleted file mode 100644 index 6985b9de6..000000000 --- a/tests/test_tutorial/test_response_model/test_tutorial003_01_py310.py +++ /dev/null @@ -1,160 +0,0 @@ -import pytest -from dirty_equals import IsDict, IsOneOf -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.response_model.tutorial003_01_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_post_user(client: TestClient): - response = client.post( - "/user/", - json={ - "username": "foo", - "password": "fighter", - "email": "foo@example.com", - "full_name": "Grave Dohl", - }, - ) - assert response.status_code == 200, response.text - assert response.json() == { - "username": "foo", - "email": "foo@example.com", - "full_name": "Grave Dohl", - } - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/user/": { - "post": { - "summary": "Create User", - "operationId": "create_user_user__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/UserIn"} - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/BaseUser"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "BaseUser": { - "title": "BaseUser", - "required": IsOneOf( - ["username", "email", "full_name"], - # TODO: remove when deprecating Pydantic v1 - ["username", "email"], - ), - "type": "object", - "properties": { - "username": {"title": "Username", "type": "string"}, - "email": { - "title": "Email", - "type": "string", - "format": "email", - }, - "full_name": IsDict( - { - "title": "Full Name", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Full Name", "type": "string"} - ), - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "UserIn": { - "title": "UserIn", - "required": ["username", "email", "password"], - "type": "object", - "properties": { - "username": {"title": "Username", "type": "string"}, - "email": { - "title": "Email", - "type": "string", - "format": "email", - }, - "full_name": IsDict( - { - "title": "Full Name", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Full Name", "type": "string"} - ), - "password": {"title": "Password", "type": "string"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_response_model/test_tutorial003_05.py b/tests/test_tutorial/test_response_model/test_tutorial003_05.py index c7a39cc74..9500852e1 100644 --- a/tests/test_tutorial/test_response_model/test_tutorial003_05.py +++ b/tests/test_tutorial/test_response_model/test_tutorial003_05.py @@ -1,23 +1,38 @@ +import importlib + +import pytest from fastapi.testclient import TestClient -from docs_src.response_model.tutorial003_05 import app +from ...utils import needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial003_05", + pytest.param("tutorial003_05_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.response_model.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_get_portal(): +def test_get_portal(client: TestClient): response = client.get("/portal") assert response.status_code == 200, response.text assert response.json() == {"message": "Here's your interdimensional portal."} -def test_get_redirect(): +def test_get_redirect(client: TestClient): response = client.get("/portal", params={"teleport": True}, follow_redirects=False) assert response.status_code == 307, response.text assert response.headers["location"] == "https://www.youtube.com/watch?v=dQw4w9WgXcQ" -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_response_model/test_tutorial003_05_py310.py b/tests/test_tutorial/test_response_model/test_tutorial003_05_py310.py deleted file mode 100644 index f80d62572..000000000 --- a/tests/test_tutorial/test_response_model/test_tutorial003_05_py310.py +++ /dev/null @@ -1,103 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.response_model.tutorial003_05_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_get_portal(client: TestClient): - response = client.get("/portal") - assert response.status_code == 200, response.text - assert response.json() == {"message": "Here's your interdimensional portal."} - - -@needs_py310 -def test_get_redirect(client: TestClient): - response = client.get("/portal", params={"teleport": True}, follow_redirects=False) - assert response.status_code == 307, response.text - assert response.headers["location"] == "https://www.youtube.com/watch?v=dQw4w9WgXcQ" - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/portal": { - "get": { - "summary": "Get Portal", - "operationId": "get_portal_portal_get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Teleport", - "type": "boolean", - "default": False, - }, - "name": "teleport", - "in": "query", - } - ], - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_response_model/test_tutorial004.py b/tests/test_tutorial/test_response_model/test_tutorial004.py index e9bde18dd..449a52b81 100644 --- a/tests/test_tutorial/test_response_model/test_tutorial004.py +++ b/tests/test_tutorial/test_response_model/test_tutorial004.py @@ -1,10 +1,25 @@ +import importlib + import pytest from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient -from docs_src.response_model.tutorial004 import app +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial004", + pytest.param("tutorial004_py39", marks=needs_py39), + pytest.param("tutorial004_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.response_model.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client @pytest.mark.parametrize( @@ -27,13 +42,13 @@ client = TestClient(app) ), ], ) -def test_get(url, data): +def test_get(url, data, client: TestClient): response = client.get(url) assert response.status_code == 200, response.text assert response.json() == data -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_response_model/test_tutorial004_py310.py b/tests/test_tutorial/test_response_model/test_tutorial004_py310.py deleted file mode 100644 index 6f8a3cbea..000000000 --- a/tests/test_tutorial/test_response_model/test_tutorial004_py310.py +++ /dev/null @@ -1,147 +0,0 @@ -import pytest -from dirty_equals import IsDict, IsOneOf -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.response_model.tutorial004_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -@pytest.mark.parametrize( - "url,data", - [ - ("/items/foo", {"name": "Foo", "price": 50.2}), - ( - "/items/bar", - {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2}, - ), - ( - "/items/baz", - { - "name": "Baz", - "description": None, - "price": 50.2, - "tax": 10.5, - "tags": [], - }, - ), - ], -) -def test_get(url, data, client: TestClient): - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == data - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Item", - "operationId": "read_item_items__item_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - } - ], - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": IsOneOf( - ["name", "description", "price", "tax", "tags"], - # TODO: remove when deprecating Pydantic v1 - ["name", "price"], - ), - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "price": {"title": "Price", "type": "number"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "tax": {"title": "Tax", "type": "number", "default": 10.5}, - "tags": { - "title": "Tags", - "type": "array", - "items": {"type": "string"}, - "default": [], - }, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_response_model/test_tutorial004_py39.py b/tests/test_tutorial/test_response_model/test_tutorial004_py39.py deleted file mode 100644 index cfaa1eba2..000000000 --- a/tests/test_tutorial/test_response_model/test_tutorial004_py39.py +++ /dev/null @@ -1,147 +0,0 @@ -import pytest -from dirty_equals import IsDict, IsOneOf -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.response_model.tutorial004_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -@pytest.mark.parametrize( - "url,data", - [ - ("/items/foo", {"name": "Foo", "price": 50.2}), - ( - "/items/bar", - {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2}, - ), - ( - "/items/baz", - { - "name": "Baz", - "description": None, - "price": 50.2, - "tax": 10.5, - "tags": [], - }, - ), - ], -) -def test_get(url, data, client: TestClient): - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == data - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Item", - "operationId": "read_item_items__item_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - } - ], - } - } - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": IsOneOf( - ["name", "description", "price", "tax", "tags"], - # TODO: remove when deprecating Pydantic v1 - ["name", "price"], - ), - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "price": {"title": "Price", "type": "number"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "tax": {"title": "Tax", "type": "number", "default": 10.5}, - "tags": { - "title": "Tags", - "type": "array", - "items": {"type": "string"}, - "default": [], - }, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_response_model/test_tutorial005.py b/tests/test_tutorial/test_response_model/test_tutorial005.py index b20864c07..a633a3fdd 100644 --- a/tests/test_tutorial/test_response_model/test_tutorial005.py +++ b/tests/test_tutorial/test_response_model/test_tutorial005.py @@ -1,18 +1,33 @@ +import importlib + +import pytest from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient -from docs_src.response_model.tutorial005 import app +from ...utils import needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial005", + pytest.param("tutorial005_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.response_model.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_read_item_name(): +def test_read_item_name(client: TestClient): response = client.get("/items/bar/name") assert response.status_code == 200, response.text assert response.json() == {"name": "Bar", "description": "The Bar fighters"} -def test_read_item_public_data(): +def test_read_item_public_data(client: TestClient): response = client.get("/items/bar/public") assert response.status_code == 200, response.text assert response.json() == { @@ -22,7 +37,7 @@ def test_read_item_public_data(): } -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_response_model/test_tutorial005_py310.py b/tests/test_tutorial/test_response_model/test_tutorial005_py310.py deleted file mode 100644 index de552c8f2..000000000 --- a/tests/test_tutorial/test_response_model/test_tutorial005_py310.py +++ /dev/null @@ -1,166 +0,0 @@ -import pytest -from dirty_equals import IsDict, IsOneOf -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.response_model.tutorial005_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_read_item_name(client: TestClient): - response = client.get("/items/bar/name") - assert response.status_code == 200, response.text - assert response.json() == {"name": "Bar", "description": "The Bar fighters"} - - -@needs_py310 -def test_read_item_public_data(client: TestClient): - response = client.get("/items/bar/public") - assert response.status_code == 200, response.text - assert response.json() == { - "name": "Bar", - "description": "The Bar fighters", - "price": 62, - } - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}/name": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Item Name", - "operationId": "read_item_name_items__item_id__name_get", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - } - ], - } - }, - "/items/{item_id}/public": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Item Public Data", - "operationId": "read_item_public_data_items__item_id__public_get", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - } - ], - } - }, - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": IsOneOf( - ["name", "description", "price", "tax"], - # TODO: remove when deprecating Pydantic v1 - ["name", "price"], - ), - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "price": {"title": "Price", "type": "number"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "tax": {"title": "Tax", "type": "number", "default": 10.5}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_response_model/test_tutorial006.py b/tests/test_tutorial/test_response_model/test_tutorial006.py index 1e47e2ead..863522d1b 100644 --- a/tests/test_tutorial/test_response_model/test_tutorial006.py +++ b/tests/test_tutorial/test_response_model/test_tutorial006.py @@ -1,18 +1,33 @@ +import importlib + +import pytest from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient -from docs_src.response_model.tutorial006 import app +from ...utils import needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial006", + pytest.param("tutorial006_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.response_model.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_read_item_name(): +def test_read_item_name(client: TestClient): response = client.get("/items/bar/name") assert response.status_code == 200, response.text assert response.json() == {"name": "Bar", "description": "The Bar fighters"} -def test_read_item_public_data(): +def test_read_item_public_data(client: TestClient): response = client.get("/items/bar/public") assert response.status_code == 200, response.text assert response.json() == { @@ -22,7 +37,7 @@ def test_read_item_public_data(): } -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_response_model/test_tutorial006_py310.py b/tests/test_tutorial/test_response_model/test_tutorial006_py310.py deleted file mode 100644 index 40058b12d..000000000 --- a/tests/test_tutorial/test_response_model/test_tutorial006_py310.py +++ /dev/null @@ -1,166 +0,0 @@ -import pytest -from dirty_equals import IsDict, IsOneOf -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.response_model.tutorial006_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_read_item_name(client: TestClient): - response = client.get("/items/bar/name") - assert response.status_code == 200, response.text - assert response.json() == {"name": "Bar", "description": "The Bar fighters"} - - -@needs_py310 -def test_read_item_public_data(client: TestClient): - response = client.get("/items/bar/public") - assert response.status_code == 200, response.text - assert response.json() == { - "name": "Bar", - "description": "The Bar fighters", - "price": 62, - } - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}/name": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Item Name", - "operationId": "read_item_name_items__item_id__name_get", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - } - ], - } - }, - "/items/{item_id}/public": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Item Public Data", - "operationId": "read_item_public_data_items__item_id__public_get", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "string"}, - "name": "item_id", - "in": "path", - } - ], - } - }, - }, - "components": { - "schemas": { - "Item": { - "title": "Item", - "required": IsOneOf( - ["name", "description", "price", "tax"], - # TODO: remove when deprecating Pydantic v1 - ["name", "price"], - ), - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "price": {"title": "Price", "type": "number"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "tax": {"title": "Tax", "type": "number", "default": 10.5}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial001.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial001.py index 98b187355..c21cbb4bc 100644 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial001.py +++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial001.py @@ -1,14 +1,22 @@ +import importlib + import pytest from fastapi.testclient import TestClient -from ...utils import needs_pydanticv2 +from ...utils import needs_py310, needs_pydanticv2 -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial001 import app +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.schema_extra_example.{request.param}") - client = TestClient(app) + client = TestClient(mod.app) return client diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial001_pv1.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial001_pv1.py index 3520ef61d..b79f42e64 100644 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial001_pv1.py +++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial001_pv1.py @@ -1,14 +1,22 @@ +import importlib + import pytest from fastapi.testclient import TestClient -from ...utils import needs_pydanticv1 +from ...utils import needs_py310, needs_pydanticv1 -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial001_pv1 import app +@pytest.fixture( + name="client", + params=[ + "tutorial001_pv1", + pytest.param("tutorial001_pv1_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.schema_extra_example.{request.param}") - client = TestClient(app) + client = TestClient(mod.app) return client diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial001_py310.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial001_py310.py deleted file mode 100644 index e63e33cda..000000000 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial001_py310.py +++ /dev/null @@ -1,135 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py310, needs_pydanticv2 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial001_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -@needs_pydanticv2 -def test_post_body_example(client: TestClient): - response = client.put( - "/items/5", - json={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - ) - assert response.status_code == 200 - - -@needs_py310 -@needs_pydanticv2 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - # insert_assert(response.json()) - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "name": "item_id", - "in": "path", - "required": True, - "schema": {"type": "integer", "title": "Item Id"}, - } - ], - "requestBody": { - "required": True, - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "properties": { - "detail": { - "items": {"$ref": "#/components/schemas/ValidationError"}, - "type": "array", - "title": "Detail", - } - }, - "type": "object", - "title": "HTTPValidationError", - }, - "Item": { - "properties": { - "name": {"type": "string", "title": "Name"}, - "description": { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Description", - }, - "price": {"type": "number", "title": "Price"}, - "tax": { - "anyOf": [{"type": "number"}, {"type": "null"}], - "title": "Tax", - }, - }, - "type": "object", - "required": ["name", "price"], - "title": "Item", - "examples": [ - { - "description": "A very nice Item", - "name": "Foo", - "price": 35.4, - "tax": 3.2, - } - ], - }, - "ValidationError": { - "properties": { - "loc": { - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - "type": "array", - "title": "Location", - }, - "msg": {"type": "string", "title": "Message"}, - "type": {"type": "string", "title": "Error Type"}, - }, - "type": "object", - "required": ["loc", "msg", "type"], - "title": "ValidationError", - }, - } - }, - } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial001_py310_pv1.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial001_py310_pv1.py deleted file mode 100644 index e036d6b68..000000000 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial001_py310_pv1.py +++ /dev/null @@ -1,129 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py310, needs_pydanticv1 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial001_py310_pv1 import app - - client = TestClient(app) - return client - - -@needs_py310 -@needs_pydanticv1 -def test_post_body_example(client: TestClient): - response = client.put( - "/items/5", - json={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - ) - assert response.status_code == 200 - - -@needs_py310 -@needs_pydanticv1 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - # insert_assert(response.json()) - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"type": "integer", "title": "Item Id"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "properties": { - "detail": { - "items": {"$ref": "#/components/schemas/ValidationError"}, - "type": "array", - "title": "Detail", - } - }, - "type": "object", - "title": "HTTPValidationError", - }, - "Item": { - "properties": { - "name": {"type": "string", "title": "Name"}, - "description": {"type": "string", "title": "Description"}, - "price": {"type": "number", "title": "Price"}, - "tax": {"type": "number", "title": "Tax"}, - }, - "type": "object", - "required": ["name", "price"], - "title": "Item", - "examples": [ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - } - ], - }, - "ValidationError": { - "properties": { - "loc": { - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - "type": "array", - "title": "Location", - }, - "msg": {"type": "string", "title": "Message"}, - "type": {"type": "string", "title": "Error Type"}, - }, - "type": "object", - "required": ["loc", "msg", "type"], - "title": "ValidationError", - }, - } - }, - } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial004.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial004.py index eac0d1e29..61aefd12a 100644 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial004.py +++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial004.py @@ -1,13 +1,30 @@ +import importlib + +import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from docs_src.schema_extra_example.tutorial004 import app +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial004", + pytest.param("tutorial004_py310", marks=needs_py310), + "tutorial004_an", + pytest.param("tutorial004_an_py39", marks=needs_py39), + pytest.param("tutorial004_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.schema_extra_example.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -# Test required and embedded body parameters with no bodies sent -def test_post_body_example(): +def test_post_body_example(client: TestClient): response = client.put( "/items/5", json={ @@ -20,7 +37,7 @@ def test_post_body_example(): assert response.status_code == 200 -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an.py deleted file mode 100644 index a9cecd098..000000000 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an.py +++ /dev/null @@ -1,168 +0,0 @@ -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from docs_src.schema_extra_example.tutorial004_an import app - -client = TestClient(app) - - -# Test required and embedded body parameters with no bodies sent -def test_post_body_example(): - response = client.put( - "/items/5", - json={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - ) - assert response.status_code == 200 - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict( - { - "$ref": "#/components/schemas/Item", - "examples": [ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - {"name": "Bar", "price": "35.4"}, - { - "name": "Baz", - "price": "thirty five point four", - }, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "allOf": [ - {"$ref": "#/components/schemas/Item"} - ], - "title": "Item", - "examples": [ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - {"name": "Bar", "price": "35.4"}, - { - "name": "Baz", - "price": "thirty five point four", - }, - ], - } - ) - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an_py310.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an_py310.py deleted file mode 100644 index b6a735599..000000000 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an_py310.py +++ /dev/null @@ -1,177 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial004_an_py310 import app - - client = TestClient(app) - return client - - -# Test required and embedded body parameters with no bodies sent -@needs_py310 -def test_post_body_example(client: TestClient): - response = client.put( - "/items/5", - json={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - ) - assert response.status_code == 200 - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict( - { - "$ref": "#/components/schemas/Item", - "examples": [ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - {"name": "Bar", "price": "35.4"}, - { - "name": "Baz", - "price": "thirty five point four", - }, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "allOf": [ - {"$ref": "#/components/schemas/Item"} - ], - "title": "Item", - "examples": [ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - {"name": "Bar", "price": "35.4"}, - { - "name": "Baz", - "price": "thirty five point four", - }, - ], - } - ) - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an_py39.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an_py39.py deleted file mode 100644 index 2493194a0..000000000 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial004_an_py39.py +++ /dev/null @@ -1,177 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial004_an_py39 import app - - client = TestClient(app) - return client - - -# Test required and embedded body parameters with no bodies sent -@needs_py39 -def test_post_body_example(client: TestClient): - response = client.put( - "/items/5", - json={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - ) - assert response.status_code == 200 - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict( - { - "$ref": "#/components/schemas/Item", - "examples": [ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - {"name": "Bar", "price": "35.4"}, - { - "name": "Baz", - "price": "thirty five point four", - }, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "allOf": [ - {"$ref": "#/components/schemas/Item"} - ], - "title": "Item", - "examples": [ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - {"name": "Bar", "price": "35.4"}, - { - "name": "Baz", - "price": "thirty five point four", - }, - ], - } - ) - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial004_py310.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial004_py310.py deleted file mode 100644 index 15f54bd5a..000000000 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial004_py310.py +++ /dev/null @@ -1,177 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial004_py310 import app - - client = TestClient(app) - return client - - -# Test required and embedded body parameters with no bodies sent -@needs_py310 -def test_post_body_example(client: TestClient): - response = client.put( - "/items/5", - json={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - ) - assert response.status_code == 200 - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict( - { - "$ref": "#/components/schemas/Item", - "examples": [ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - {"name": "Bar", "price": "35.4"}, - { - "name": "Baz", - "price": "thirty five point four", - }, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "allOf": [ - {"$ref": "#/components/schemas/Item"} - ], - "title": "Item", - "examples": [ - { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - {"name": "Bar", "price": "35.4"}, - { - "name": "Baz", - "price": "thirty five point four", - }, - ], - } - ) - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial005.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial005.py index 94a40ed5a..12859227b 100644 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial005.py +++ b/tests/test_tutorial/test_schema_extra_example/test_tutorial005.py @@ -1,13 +1,26 @@ +import importlib + import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient +from ...utils import needs_py39, needs_py310 + -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial005 import app +@pytest.fixture( + name="client", + params=[ + "tutorial005", + pytest.param("tutorial005_py310", marks=needs_py310), + "tutorial005_an", + pytest.param("tutorial005_an_py39", marks=needs_py39), + pytest.param("tutorial005_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.schema_extra_example.{request.param}") - client = TestClient(app) + client = TestClient(mod.app) return client diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an.py deleted file mode 100644 index da92f98f6..000000000 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an.py +++ /dev/null @@ -1,166 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial005_an import app - - client = TestClient(app) - return client - - -def test_post_body_example(client: TestClient): - response = client.put( - "/items/5", - json={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - ) - assert response.status_code == 200 - - -def test_openapi_schema(client: TestClient) -> None: - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict({"$ref": "#/components/schemas/Item"}) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "allOf": [ - {"$ref": "#/components/schemas/Item"} - ], - "title": "Item", - } - ), - "examples": { - "normal": { - "summary": "A normal example", - "description": "A **normal** item works correctly.", - "value": { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - }, - "converted": { - "summary": "An example with converted data", - "description": "FastAPI can convert price `strings` to actual `numbers` automatically", - "value": {"name": "Bar", "price": "35.4"}, - }, - "invalid": { - "summary": "Invalid data is rejected with an error", - "value": { - "name": "Baz", - "price": "thirty five point four", - }, - }, - }, - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an_py310.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an_py310.py deleted file mode 100644 index 9109cb14e..000000000 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an_py310.py +++ /dev/null @@ -1,170 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial005_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_post_body_example(client: TestClient): - response = client.put( - "/items/5", - json={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - ) - assert response.status_code == 200 - - -@needs_py310 -def test_openapi_schema(client: TestClient) -> None: - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict({"$ref": "#/components/schemas/Item"}) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "allOf": [ - {"$ref": "#/components/schemas/Item"} - ], - "title": "Item", - } - ), - "examples": { - "normal": { - "summary": "A normal example", - "description": "A **normal** item works correctly.", - "value": { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - }, - "converted": { - "summary": "An example with converted data", - "description": "FastAPI can convert price `strings` to actual `numbers` automatically", - "value": {"name": "Bar", "price": "35.4"}, - }, - "invalid": { - "summary": "Invalid data is rejected with an error", - "value": { - "name": "Baz", - "price": "thirty five point four", - }, - }, - }, - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an_py39.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an_py39.py deleted file mode 100644 index fd4ec0575..000000000 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial005_an_py39.py +++ /dev/null @@ -1,170 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial005_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_post_body_example(client: TestClient): - response = client.put( - "/items/5", - json={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - ) - assert response.status_code == 200 - - -@needs_py39 -def test_openapi_schema(client: TestClient) -> None: - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict({"$ref": "#/components/schemas/Item"}) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "allOf": [ - {"$ref": "#/components/schemas/Item"} - ], - "title": "Item", - } - ), - "examples": { - "normal": { - "summary": "A normal example", - "description": "A **normal** item works correctly.", - "value": { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - }, - "converted": { - "summary": "An example with converted data", - "description": "FastAPI can convert price `strings` to actual `numbers` automatically", - "value": {"name": "Bar", "price": "35.4"}, - }, - "invalid": { - "summary": "Invalid data is rejected with an error", - "value": { - "name": "Baz", - "price": "thirty five point four", - }, - }, - }, - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_schema_extra_example/test_tutorial005_py310.py b/tests/test_tutorial/test_schema_extra_example/test_tutorial005_py310.py deleted file mode 100644 index 05df53422..000000000 --- a/tests/test_tutorial/test_schema_extra_example/test_tutorial005_py310.py +++ /dev/null @@ -1,170 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.schema_extra_example.tutorial005_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_post_body_example(client: TestClient): - response = client.put( - "/items/5", - json={ - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - ) - assert response.status_code == 200 - - -@needs_py310 -def test_openapi_schema(client: TestClient) -> None: - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/{item_id}": { - "put": { - "summary": "Update Item", - "operationId": "update_item_items__item_id__put", - "parameters": [ - { - "required": True, - "schema": {"title": "Item Id", "type": "integer"}, - "name": "item_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": IsDict({"$ref": "#/components/schemas/Item"}) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "allOf": [ - {"$ref": "#/components/schemas/Item"} - ], - "title": "Item", - } - ), - "examples": { - "normal": { - "summary": "A normal example", - "description": "A **normal** item works correctly.", - "value": { - "name": "Foo", - "description": "A very nice Item", - "price": 35.4, - "tax": 3.2, - }, - }, - "converted": { - "summary": "An example with converted data", - "description": "FastAPI can convert price `strings` to actual `numbers` automatically", - "value": {"name": "Bar", "price": "35.4"}, - }, - "invalid": { - "summary": "Invalid data is rejected with an error", - "value": { - "name": "Baz", - "price": "thirty five point four", - }, - }, - }, - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "Item": { - "title": "Item", - "required": ["name", "price"], - "type": "object", - "properties": { - "name": {"title": "Name", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - "price": {"title": "Price", "type": "number"}, - "tax": IsDict( - { - "title": "Tax", - "anyOf": [{"type": "number"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Tax", "type": "number"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial001.py b/tests/test_tutorial/test_security/test_tutorial001.py index 417bed8f7..f572d6e3e 100644 --- a/tests/test_tutorial/test_security/test_tutorial001.py +++ b/tests/test_tutorial/test_security/test_tutorial001.py @@ -1,31 +1,47 @@ +import importlib + +import pytest from fastapi.testclient import TestClient -from docs_src.security.tutorial001 import app +from ...utils import needs_py39 + + +@pytest.fixture( + name="client", + params=[ + "tutorial001", + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.security.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_no_token(): +def test_no_token(client: TestClient): response = client.get("/items") assert response.status_code == 401, response.text assert response.json() == {"detail": "Not authenticated"} assert response.headers["WWW-Authenticate"] == "Bearer" -def test_token(): +def test_token(client: TestClient): response = client.get("/items", headers={"Authorization": "Bearer testtoken"}) assert response.status_code == 200, response.text assert response.json() == {"token": "testtoken"} -def test_incorrect_token(): +def test_incorrect_token(client: TestClient): response = client.get("/items", headers={"Authorization": "Notexistent testtoken"}) assert response.status_code == 401, response.text assert response.json() == {"detail": "Not authenticated"} assert response.headers["WWW-Authenticate"] == "Bearer" -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_security/test_tutorial001_an.py b/tests/test_tutorial/test_security/test_tutorial001_an.py deleted file mode 100644 index 59460da7f..000000000 --- a/tests/test_tutorial/test_security/test_tutorial001_an.py +++ /dev/null @@ -1,57 +0,0 @@ -from fastapi.testclient import TestClient - -from docs_src.security.tutorial001_an import app - -client = TestClient(app) - - -def test_no_token(): - response = client.get("/items") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -def test_token(): - response = client.get("/items", headers={"Authorization": "Bearer testtoken"}) - assert response.status_code == 200, response.text - assert response.json() == {"token": "testtoken"} - - -def test_incorrect_token(): - response = client.get("/items", headers={"Authorization": "Notexistent testtoken"}) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "security": [{"OAuth2PasswordBearer": []}], - } - } - }, - "components": { - "securitySchemes": { - "OAuth2PasswordBearer": { - "type": "oauth2", - "flows": {"password": {"scopes": {}, "tokenUrl": "token"}}, - } - } - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial001_an_py39.py b/tests/test_tutorial/test_security/test_tutorial001_an_py39.py deleted file mode 100644 index d8e712773..000000000 --- a/tests/test_tutorial/test_security/test_tutorial001_an_py39.py +++ /dev/null @@ -1,68 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.security.tutorial001_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_no_token(client: TestClient): - response = client.get("/items") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py39 -def test_token(client: TestClient): - response = client.get("/items", headers={"Authorization": "Bearer testtoken"}) - assert response.status_code == 200, response.text - assert response.json() == {"token": "testtoken"} - - -@needs_py39 -def test_incorrect_token(client: TestClient): - response = client.get("/items", headers={"Authorization": "Notexistent testtoken"}) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "security": [{"OAuth2PasswordBearer": []}], - } - } - }, - "components": { - "securitySchemes": { - "OAuth2PasswordBearer": { - "type": "oauth2", - "flows": {"password": {"scopes": {}, "tokenUrl": "token"}}, - } - } - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial003.py b/tests/test_tutorial/test_security/test_tutorial003.py index 18d4680f6..37fc2618f 100644 --- a/tests/test_tutorial/test_security/test_tutorial003.py +++ b/tests/test_tutorial/test_security/test_tutorial003.py @@ -1,18 +1,36 @@ +import importlib + +import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from docs_src.security.tutorial003 import app +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial003", + pytest.param("tutorial003_py310", marks=needs_py310), + "tutorial003_an", + pytest.param("tutorial003_an_py39", marks=needs_py39), + pytest.param("tutorial003_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.security.{request.param}") -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_login(): +def test_login(client: TestClient): response = client.post("/token", data={"username": "johndoe", "password": "secret"}) assert response.status_code == 200, response.text assert response.json() == {"access_token": "johndoe", "token_type": "bearer"} -def test_login_incorrect_password(): +def test_login_incorrect_password(client: TestClient): response = client.post( "/token", data={"username": "johndoe", "password": "incorrect"} ) @@ -20,20 +38,20 @@ def test_login_incorrect_password(): assert response.json() == {"detail": "Incorrect username or password"} -def test_login_incorrect_username(): +def test_login_incorrect_username(client: TestClient): response = client.post("/token", data={"username": "foo", "password": "secret"}) assert response.status_code == 400, response.text assert response.json() == {"detail": "Incorrect username or password"} -def test_no_token(): +def test_no_token(client: TestClient): response = client.get("/users/me") assert response.status_code == 401, response.text assert response.json() == {"detail": "Not authenticated"} assert response.headers["WWW-Authenticate"] == "Bearer" -def test_token(): +def test_token(client: TestClient): response = client.get("/users/me", headers={"Authorization": "Bearer johndoe"}) assert response.status_code == 200, response.text assert response.json() == { @@ -45,14 +63,14 @@ def test_token(): } -def test_incorrect_token(): +def test_incorrect_token(client: TestClient): response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"}) assert response.status_code == 401, response.text assert response.json() == {"detail": "Invalid authentication credentials"} assert response.headers["WWW-Authenticate"] == "Bearer" -def test_incorrect_token_type(): +def test_incorrect_token_type(client: TestClient): response = client.get( "/users/me", headers={"Authorization": "Notexistent testtoken"} ) @@ -61,13 +79,13 @@ def test_incorrect_token_type(): assert response.headers["WWW-Authenticate"] == "Bearer" -def test_inactive_user(): +def test_inactive_user(client: TestClient): response = client.get("/users/me", headers={"Authorization": "Bearer alice"}) assert response.status_code == 400, response.text assert response.json() == {"detail": "Inactive user"} -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { @@ -131,7 +149,7 @@ def test_openapi_schema(): { "title": "Grant Type", "anyOf": [ - {"pattern": "password", "type": "string"}, + {"pattern": "^password$", "type": "string"}, {"type": "null"}, ], } @@ -140,7 +158,7 @@ def test_openapi_schema(): # TODO: remove when deprecating Pydantic v1 { "title": "Grant Type", - "pattern": "password", + "pattern": "^password$", "type": "string", } ), diff --git a/tests/test_tutorial/test_security/test_tutorial003_an.py b/tests/test_tutorial/test_security/test_tutorial003_an.py deleted file mode 100644 index a8f64d0c6..000000000 --- a/tests/test_tutorial/test_security/test_tutorial003_an.py +++ /dev/null @@ -1,207 +0,0 @@ -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from docs_src.security.tutorial003_an import app - -client = TestClient(app) - - -def test_login(): - response = client.post("/token", data={"username": "johndoe", "password": "secret"}) - assert response.status_code == 200, response.text - assert response.json() == {"access_token": "johndoe", "token_type": "bearer"} - - -def test_login_incorrect_password(): - response = client.post( - "/token", data={"username": "johndoe", "password": "incorrect"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -def test_login_incorrect_username(): - response = client.post("/token", data={"username": "foo", "password": "secret"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -def test_no_token(): - response = client.get("/users/me") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -def test_token(): - response = client.get("/users/me", headers={"Authorization": "Bearer johndoe"}) - assert response.status_code == 200, response.text - assert response.json() == { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "hashed_password": "fakehashedsecret", - "disabled": False, - } - - -def test_incorrect_token(): - response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"}) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Invalid authentication credentials"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -def test_incorrect_token_type(): - response = client.get( - "/users/me", headers={"Authorization": "Notexistent testtoken"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -def test_inactive_user(): - response = client.get("/users/me", headers={"Authorization": "Bearer alice"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Inactive user"} - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/token": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Login", - "operationId": "login_token_post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": { - "$ref": "#/components/schemas/Body_login_token_post" - } - } - }, - "required": True, - }, - } - }, - "/users/me": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Users Me", - "operationId": "read_users_me_users_me_get", - "security": [{"OAuth2PasswordBearer": []}], - } - }, - }, - "components": { - "schemas": { - "Body_login_token_post": { - "title": "Body_login_token_post", - "required": ["username", "password"], - "type": "object", - "properties": { - "grant_type": IsDict( - { - "title": "Grant Type", - "anyOf": [ - {"pattern": "password", "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Grant Type", - "pattern": "password", - "type": "string", - } - ), - "username": {"title": "Username", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - "scope": {"title": "Scope", "type": "string", "default": ""}, - "client_id": IsDict( - { - "title": "Client Id", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Id", "type": "string"} - ), - "client_secret": IsDict( - { - "title": "Client Secret", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Secret", "type": "string"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - }, - "securitySchemes": { - "OAuth2PasswordBearer": { - "type": "oauth2", - "flows": {"password": {"scopes": {}, "tokenUrl": "token"}}, - } - }, - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial003_an_py310.py b/tests/test_tutorial/test_security/test_tutorial003_an_py310.py deleted file mode 100644 index 7cbbcee2f..000000000 --- a/tests/test_tutorial/test_security/test_tutorial003_an_py310.py +++ /dev/null @@ -1,223 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.security.tutorial003_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_login(client: TestClient): - response = client.post("/token", data={"username": "johndoe", "password": "secret"}) - assert response.status_code == 200, response.text - assert response.json() == {"access_token": "johndoe", "token_type": "bearer"} - - -@needs_py310 -def test_login_incorrect_password(client: TestClient): - response = client.post( - "/token", data={"username": "johndoe", "password": "incorrect"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py310 -def test_login_incorrect_username(client: TestClient): - response = client.post("/token", data={"username": "foo", "password": "secret"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py310 -def test_no_token(client: TestClient): - response = client.get("/users/me") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_token(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer johndoe"}) - assert response.status_code == 200, response.text - assert response.json() == { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "hashed_password": "fakehashedsecret", - "disabled": False, - } - - -@needs_py310 -def test_incorrect_token(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"}) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Invalid authentication credentials"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_incorrect_token_type(client: TestClient): - response = client.get( - "/users/me", headers={"Authorization": "Notexistent testtoken"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_inactive_user(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer alice"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Inactive user"} - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/token": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Login", - "operationId": "login_token_post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": { - "$ref": "#/components/schemas/Body_login_token_post" - } - } - }, - "required": True, - }, - } - }, - "/users/me": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Users Me", - "operationId": "read_users_me_users_me_get", - "security": [{"OAuth2PasswordBearer": []}], - } - }, - }, - "components": { - "schemas": { - "Body_login_token_post": { - "title": "Body_login_token_post", - "required": ["username", "password"], - "type": "object", - "properties": { - "grant_type": IsDict( - { - "title": "Grant Type", - "anyOf": [ - {"pattern": "password", "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Grant Type", - "pattern": "password", - "type": "string", - } - ), - "username": {"title": "Username", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - "scope": {"title": "Scope", "type": "string", "default": ""}, - "client_id": IsDict( - { - "title": "Client Id", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Id", "type": "string"} - ), - "client_secret": IsDict( - { - "title": "Client Secret", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Secret", "type": "string"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - }, - "securitySchemes": { - "OAuth2PasswordBearer": { - "type": "oauth2", - "flows": {"password": {"scopes": {}, "tokenUrl": "token"}}, - } - }, - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial003_an_py39.py b/tests/test_tutorial/test_security/test_tutorial003_an_py39.py deleted file mode 100644 index 7b21fbcc9..000000000 --- a/tests/test_tutorial/test_security/test_tutorial003_an_py39.py +++ /dev/null @@ -1,223 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.security.tutorial003_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_login(client: TestClient): - response = client.post("/token", data={"username": "johndoe", "password": "secret"}) - assert response.status_code == 200, response.text - assert response.json() == {"access_token": "johndoe", "token_type": "bearer"} - - -@needs_py39 -def test_login_incorrect_password(client: TestClient): - response = client.post( - "/token", data={"username": "johndoe", "password": "incorrect"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py39 -def test_login_incorrect_username(client: TestClient): - response = client.post("/token", data={"username": "foo", "password": "secret"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py39 -def test_no_token(client: TestClient): - response = client.get("/users/me") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py39 -def test_token(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer johndoe"}) - assert response.status_code == 200, response.text - assert response.json() == { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "hashed_password": "fakehashedsecret", - "disabled": False, - } - - -@needs_py39 -def test_incorrect_token(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"}) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Invalid authentication credentials"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py39 -def test_incorrect_token_type(client: TestClient): - response = client.get( - "/users/me", headers={"Authorization": "Notexistent testtoken"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py39 -def test_inactive_user(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer alice"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Inactive user"} - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/token": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Login", - "operationId": "login_token_post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": { - "$ref": "#/components/schemas/Body_login_token_post" - } - } - }, - "required": True, - }, - } - }, - "/users/me": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Users Me", - "operationId": "read_users_me_users_me_get", - "security": [{"OAuth2PasswordBearer": []}], - } - }, - }, - "components": { - "schemas": { - "Body_login_token_post": { - "title": "Body_login_token_post", - "required": ["username", "password"], - "type": "object", - "properties": { - "grant_type": IsDict( - { - "title": "Grant Type", - "anyOf": [ - {"pattern": "password", "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Grant Type", - "pattern": "password", - "type": "string", - } - ), - "username": {"title": "Username", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - "scope": {"title": "Scope", "type": "string", "default": ""}, - "client_id": IsDict( - { - "title": "Client Id", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Id", "type": "string"} - ), - "client_secret": IsDict( - { - "title": "Client Secret", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Secret", "type": "string"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - }, - "securitySchemes": { - "OAuth2PasswordBearer": { - "type": "oauth2", - "flows": {"password": {"scopes": {}, "tokenUrl": "token"}}, - } - }, - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial003_py310.py b/tests/test_tutorial/test_security/test_tutorial003_py310.py deleted file mode 100644 index 512504534..000000000 --- a/tests/test_tutorial/test_security/test_tutorial003_py310.py +++ /dev/null @@ -1,223 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.security.tutorial003_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_login(client: TestClient): - response = client.post("/token", data={"username": "johndoe", "password": "secret"}) - assert response.status_code == 200, response.text - assert response.json() == {"access_token": "johndoe", "token_type": "bearer"} - - -@needs_py310 -def test_login_incorrect_password(client: TestClient): - response = client.post( - "/token", data={"username": "johndoe", "password": "incorrect"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py310 -def test_login_incorrect_username(client: TestClient): - response = client.post("/token", data={"username": "foo", "password": "secret"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py310 -def test_no_token(client: TestClient): - response = client.get("/users/me") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_token(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer johndoe"}) - assert response.status_code == 200, response.text - assert response.json() == { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "hashed_password": "fakehashedsecret", - "disabled": False, - } - - -@needs_py310 -def test_incorrect_token(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"}) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Invalid authentication credentials"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_incorrect_token_type(client: TestClient): - response = client.get( - "/users/me", headers={"Authorization": "Notexistent testtoken"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_inactive_user(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer alice"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Inactive user"} - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/token": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Login", - "operationId": "login_token_post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": { - "$ref": "#/components/schemas/Body_login_token_post" - } - } - }, - "required": True, - }, - } - }, - "/users/me": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Users Me", - "operationId": "read_users_me_users_me_get", - "security": [{"OAuth2PasswordBearer": []}], - } - }, - }, - "components": { - "schemas": { - "Body_login_token_post": { - "title": "Body_login_token_post", - "required": ["username", "password"], - "type": "object", - "properties": { - "grant_type": IsDict( - { - "title": "Grant Type", - "anyOf": [ - {"pattern": "password", "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Grant Type", - "pattern": "password", - "type": "string", - } - ), - "username": {"title": "Username", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - "scope": {"title": "Scope", "type": "string", "default": ""}, - "client_id": IsDict( - { - "title": "Client Id", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Id", "type": "string"} - ), - "client_secret": IsDict( - { - "title": "Client Secret", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Secret", "type": "string"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - }, - "securitySchemes": { - "OAuth2PasswordBearer": { - "type": "oauth2", - "flows": {"password": {"scopes": {}, "tokenUrl": "token"}}, - } - }, - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial005.py b/tests/test_tutorial/test_security/test_tutorial005.py index c669c306d..88c3d7815 100644 --- a/tests/test_tutorial/test_security/test_tutorial005.py +++ b/tests/test_tutorial/test_security/test_tutorial005.py @@ -1,18 +1,33 @@ +import importlib +from types import ModuleType + +import pytest from dirty_equals import IsDict, IsOneOf from fastapi.testclient import TestClient -from docs_src.security.tutorial005 import ( - app, - create_access_token, - fake_users_db, - get_password_hash, - verify_password, +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="mod", + params=[ + "tutorial005", + pytest.param("tutorial005_py310", marks=needs_py310), + "tutorial005_an", + pytest.param("tutorial005_py39", marks=needs_py39), + pytest.param("tutorial005_an_py39", marks=needs_py39), + pytest.param("tutorial005_an_py310", marks=needs_py310), + ], ) +def get_mod(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.security.{request.param}") -client = TestClient(app) + return mod -def get_access_token(username="johndoe", password="secret", scope=None): +def get_access_token( + *, username="johndoe", password="secret", scope=None, client: TestClient +): data = {"username": username, "password": password} if scope: data["scope"] = scope @@ -22,7 +37,8 @@ def get_access_token(username="johndoe", password="secret", scope=None): return access_token -def test_login(): +def test_login(mod: ModuleType): + client = TestClient(mod.app) response = client.post("/token", data={"username": "johndoe", "password": "secret"}) assert response.status_code == 200, response.text content = response.json() @@ -30,7 +46,8 @@ def test_login(): assert content["token_type"] == "bearer" -def test_login_incorrect_password(): +def test_login_incorrect_password(mod: ModuleType): + client = TestClient(mod.app) response = client.post( "/token", data={"username": "johndoe", "password": "incorrect"} ) @@ -38,21 +55,24 @@ def test_login_incorrect_password(): assert response.json() == {"detail": "Incorrect username or password"} -def test_login_incorrect_username(): +def test_login_incorrect_username(mod: ModuleType): + client = TestClient(mod.app) response = client.post("/token", data={"username": "foo", "password": "secret"}) assert response.status_code == 400, response.text assert response.json() == {"detail": "Incorrect username or password"} -def test_no_token(): +def test_no_token(mod: ModuleType): + client = TestClient(mod.app) response = client.get("/users/me") assert response.status_code == 401, response.text assert response.json() == {"detail": "Not authenticated"} assert response.headers["WWW-Authenticate"] == "Bearer" -def test_token(): - access_token = get_access_token(scope="me") +def test_token(mod: ModuleType): + client = TestClient(mod.app) + access_token = get_access_token(scope="me", client=client) response = client.get( "/users/me", headers={"Authorization": f"Bearer {access_token}"} ) @@ -65,14 +85,16 @@ def test_token(): } -def test_incorrect_token(): +def test_incorrect_token(mod: ModuleType): + client = TestClient(mod.app) response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"}) assert response.status_code == 401, response.text assert response.json() == {"detail": "Could not validate credentials"} assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' -def test_incorrect_token_type(): +def test_incorrect_token_type(mod: ModuleType): + client = TestClient(mod.app) response = client.get( "/users/me", headers={"Authorization": "Notexistent testtoken"} ) @@ -81,20 +103,24 @@ def test_incorrect_token_type(): assert response.headers["WWW-Authenticate"] == "Bearer" -def test_verify_password(): - assert verify_password("secret", fake_users_db["johndoe"]["hashed_password"]) +def test_verify_password(mod: ModuleType): + assert mod.verify_password( + "secret", mod.fake_users_db["johndoe"]["hashed_password"] + ) -def test_get_password_hash(): - assert get_password_hash("secretalice") +def test_get_password_hash(mod: ModuleType): + assert mod.get_password_hash("secretalice") -def test_create_access_token(): - access_token = create_access_token(data={"data": "foo"}) +def test_create_access_token(mod: ModuleType): + access_token = mod.create_access_token(data={"data": "foo"}) assert access_token -def test_token_no_sub(): +def test_token_no_sub(mod: ModuleType): + client = TestClient(mod.app) + response = client.get( "/users/me", headers={ @@ -106,7 +132,9 @@ def test_token_no_sub(): assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' -def test_token_no_username(): +def test_token_no_username(mod: ModuleType): + client = TestClient(mod.app) + response = client.get( "/users/me", headers={ @@ -118,8 +146,10 @@ def test_token_no_username(): assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' -def test_token_no_scope(): - access_token = get_access_token() +def test_token_no_scope(mod: ModuleType): + client = TestClient(mod.app) + + access_token = get_access_token(client=client) response = client.get( "/users/me", headers={"Authorization": f"Bearer {access_token}"} ) @@ -128,7 +158,9 @@ def test_token_no_scope(): assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' -def test_token_inexistent_user(): +def test_token_nonexistent_user(mod: ModuleType): + client = TestClient(mod.app) + response = client.get( "/users/me", headers={ @@ -140,9 +172,11 @@ def test_token_inexistent_user(): assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' -def test_token_inactive_user(): +def test_token_inactive_user(mod: ModuleType): + client = TestClient(mod.app) + access_token = get_access_token( - username="alice", password="secretalice", scope="me" + username="alice", password="secretalice", scope="me", client=client ) response = client.get( "/users/me", headers={"Authorization": f"Bearer {access_token}"} @@ -151,8 +185,9 @@ def test_token_inactive_user(): assert response.json() == {"detail": "Inactive user"} -def test_read_items(): - access_token = get_access_token(scope="me items") +def test_read_items(mod: ModuleType): + client = TestClient(mod.app) + access_token = get_access_token(scope="me items", client=client) response = client.get( "/users/me/items/", headers={"Authorization": f"Bearer {access_token}"} ) @@ -160,8 +195,9 @@ def test_read_items(): assert response.json() == [{"item_id": "Foo", "owner": "johndoe"}] -def test_read_system_status(): - access_token = get_access_token() +def test_read_system_status(mod: ModuleType): + client = TestClient(mod.app) + access_token = get_access_token(client=client) response = client.get( "/status/", headers={"Authorization": f"Bearer {access_token}"} ) @@ -169,14 +205,16 @@ def test_read_system_status(): assert response.json() == {"status": "ok"} -def test_read_system_status_no_token(): +def test_read_system_status_no_token(mod: ModuleType): + client = TestClient(mod.app) response = client.get("/status/") assert response.status_code == 401, response.text assert response.json() == {"detail": "Not authenticated"} assert response.headers["WWW-Authenticate"] == "Bearer" -def test_openapi_schema(): +def test_openapi_schema(mod: ModuleType): + client = TestClient(mod.app) response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { @@ -325,7 +363,7 @@ def test_openapi_schema(): { "title": "Grant Type", "anyOf": [ - {"pattern": "password", "type": "string"}, + {"pattern": "^password$", "type": "string"}, {"type": "null"}, ], } @@ -334,7 +372,7 @@ def test_openapi_schema(): # TODO: remove when deprecating Pydantic v1 { "title": "Grant Type", - "pattern": "password", + "pattern": "^password$", "type": "string", } ), diff --git a/tests/test_tutorial/test_security/test_tutorial005_an.py b/tests/test_tutorial/test_security/test_tutorial005_an.py deleted file mode 100644 index aaab04f78..000000000 --- a/tests/test_tutorial/test_security/test_tutorial005_an.py +++ /dev/null @@ -1,409 +0,0 @@ -from dirty_equals import IsDict, IsOneOf -from fastapi.testclient import TestClient - -from docs_src.security.tutorial005_an import ( - app, - create_access_token, - fake_users_db, - get_password_hash, - verify_password, -) - -client = TestClient(app) - - -def get_access_token(username="johndoe", password="secret", scope=None): - data = {"username": username, "password": password} - if scope: - data["scope"] = scope - response = client.post("/token", data=data) - content = response.json() - access_token = content.get("access_token") - return access_token - - -def test_login(): - response = client.post("/token", data={"username": "johndoe", "password": "secret"}) - assert response.status_code == 200, response.text - content = response.json() - assert "access_token" in content - assert content["token_type"] == "bearer" - - -def test_login_incorrect_password(): - response = client.post( - "/token", data={"username": "johndoe", "password": "incorrect"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -def test_login_incorrect_username(): - response = client.post("/token", data={"username": "foo", "password": "secret"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -def test_no_token(): - response = client.get("/users/me") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -def test_token(): - access_token = get_access_token(scope="me") - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "disabled": False, - } - - -def test_incorrect_token(): - response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"}) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -def test_incorrect_token_type(): - response = client.get( - "/users/me", headers={"Authorization": "Notexistent testtoken"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -def test_verify_password(): - assert verify_password("secret", fake_users_db["johndoe"]["hashed_password"]) - - -def test_get_password_hash(): - assert get_password_hash("secretalice") - - -def test_create_access_token(): - access_token = create_access_token(data={"data": "foo"}) - assert access_token - - -def test_token_no_sub(): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoiZm9vIn0.9ynBhuYb4e6aW3oJr_K_TBgwcMTDpRToQIE25L57rOE" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -def test_token_no_username(): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJmb28ifQ.NnExK_dlNAYyzACrXtXDrcWOgGY2JuPbI4eDaHdfK5Y" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -def test_token_no_scope(): - access_token = get_access_token() - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not enough permissions"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -def test_token_inexistent_user(): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VybmFtZTpib2IifQ.HcfCW67Uda-0gz54ZWTqmtgJnZeNem0Q757eTa9EZuw" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -def test_token_inactive_user(): - access_token = get_access_token( - username="alice", password="secretalice", scope="me" - ) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Inactive user"} - - -def test_read_items(): - access_token = get_access_token(scope="me items") - response = client.get( - "/users/me/items/", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == [{"item_id": "Foo", "owner": "johndoe"}] - - -def test_read_system_status(): - access_token = get_access_token() - response = client.get( - "/status/", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == {"status": "ok"} - - -def test_read_system_status_no_token(): - response = client.get("/status/") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/token": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Token"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Login For Access Token", - "operationId": "login_for_access_token_token_post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": { - "$ref": "#/components/schemas/Body_login_for_access_token_token_post" - } - } - }, - "required": True, - }, - } - }, - "/users/me/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - } - }, - "summary": "Read Users Me", - "operationId": "read_users_me_users_me__get", - "security": [{"OAuth2PasswordBearer": ["me"]}], - } - }, - "/users/me/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Own Items", - "operationId": "read_own_items_users_me_items__get", - "security": [{"OAuth2PasswordBearer": ["items", "me"]}], - } - }, - "/status/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read System Status", - "operationId": "read_system_status_status__get", - "security": [{"OAuth2PasswordBearer": []}], - } - }, - }, - "components": { - "schemas": { - "User": { - "title": "User", - "required": IsOneOf( - ["username", "email", "full_name", "disabled"], - # TODO: remove when deprecating Pydantic v1 - ["username"], - ), - "type": "object", - "properties": { - "username": {"title": "Username", "type": "string"}, - "email": IsDict( - { - "title": "Email", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Email", "type": "string"} - ), - "full_name": IsDict( - { - "title": "Full Name", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Full Name", "type": "string"} - ), - "disabled": IsDict( - { - "title": "Disabled", - "anyOf": [{"type": "boolean"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Disabled", "type": "boolean"} - ), - }, - }, - "Token": { - "title": "Token", - "required": ["access_token", "token_type"], - "type": "object", - "properties": { - "access_token": {"title": "Access Token", "type": "string"}, - "token_type": {"title": "Token Type", "type": "string"}, - }, - }, - "Body_login_for_access_token_token_post": { - "title": "Body_login_for_access_token_token_post", - "required": ["username", "password"], - "type": "object", - "properties": { - "grant_type": IsDict( - { - "title": "Grant Type", - "anyOf": [ - {"pattern": "password", "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Grant Type", - "pattern": "password", - "type": "string", - } - ), - "username": {"title": "Username", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - "scope": {"title": "Scope", "type": "string", "default": ""}, - "client_id": IsDict( - { - "title": "Client Id", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Id", "type": "string"} - ), - "client_secret": IsDict( - { - "title": "Client Secret", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Secret", "type": "string"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - }, - "securitySchemes": { - "OAuth2PasswordBearer": { - "type": "oauth2", - "flows": { - "password": { - "scopes": { - "me": "Read information about the current user.", - "items": "Read items.", - }, - "tokenUrl": "token", - } - }, - } - }, - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial005_an_py310.py b/tests/test_tutorial/test_security/test_tutorial005_an_py310.py deleted file mode 100644 index 243d0773c..000000000 --- a/tests/test_tutorial/test_security/test_tutorial005_an_py310.py +++ /dev/null @@ -1,437 +0,0 @@ -import pytest -from dirty_equals import IsDict, IsOneOf -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.security.tutorial005_an_py310 import app - - client = TestClient(app) - return client - - -def get_access_token( - *, username="johndoe", password="secret", scope=None, client: TestClient -): - data = {"username": username, "password": password} - if scope: - data["scope"] = scope - response = client.post("/token", data=data) - content = response.json() - access_token = content.get("access_token") - return access_token - - -@needs_py310 -def test_login(client: TestClient): - response = client.post("/token", data={"username": "johndoe", "password": "secret"}) - assert response.status_code == 200, response.text - content = response.json() - assert "access_token" in content - assert content["token_type"] == "bearer" - - -@needs_py310 -def test_login_incorrect_password(client: TestClient): - response = client.post( - "/token", data={"username": "johndoe", "password": "incorrect"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py310 -def test_login_incorrect_username(client: TestClient): - response = client.post("/token", data={"username": "foo", "password": "secret"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py310 -def test_no_token(client: TestClient): - response = client.get("/users/me") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_token(client: TestClient): - access_token = get_access_token(scope="me", client=client) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "disabled": False, - } - - -@needs_py310 -def test_incorrect_token(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"}) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py310 -def test_incorrect_token_type(client: TestClient): - response = client.get( - "/users/me", headers={"Authorization": "Notexistent testtoken"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_verify_password(): - from docs_src.security.tutorial005_an_py310 import fake_users_db, verify_password - - assert verify_password("secret", fake_users_db["johndoe"]["hashed_password"]) - - -@needs_py310 -def test_get_password_hash(): - from docs_src.security.tutorial005_an_py310 import get_password_hash - - assert get_password_hash("secretalice") - - -@needs_py310 -def test_create_access_token(): - from docs_src.security.tutorial005_an_py310 import create_access_token - - access_token = create_access_token(data={"data": "foo"}) - assert access_token - - -@needs_py310 -def test_token_no_sub(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoiZm9vIn0.9ynBhuYb4e6aW3oJr_K_TBgwcMTDpRToQIE25L57rOE" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py310 -def test_token_no_username(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJmb28ifQ.NnExK_dlNAYyzACrXtXDrcWOgGY2JuPbI4eDaHdfK5Y" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py310 -def test_token_no_scope(client: TestClient): - access_token = get_access_token(client=client) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not enough permissions"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py310 -def test_token_inexistent_user(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VybmFtZTpib2IifQ.HcfCW67Uda-0gz54ZWTqmtgJnZeNem0Q757eTa9EZuw" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py310 -def test_token_inactive_user(client: TestClient): - access_token = get_access_token( - username="alice", password="secretalice", scope="me", client=client - ) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Inactive user"} - - -@needs_py310 -def test_read_items(client: TestClient): - access_token = get_access_token(scope="me items", client=client) - response = client.get( - "/users/me/items/", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == [{"item_id": "Foo", "owner": "johndoe"}] - - -@needs_py310 -def test_read_system_status(client: TestClient): - access_token = get_access_token(client=client) - response = client.get( - "/status/", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == {"status": "ok"} - - -@needs_py310 -def test_read_system_status_no_token(client: TestClient): - response = client.get("/status/") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/token": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Token"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Login For Access Token", - "operationId": "login_for_access_token_token_post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": { - "$ref": "#/components/schemas/Body_login_for_access_token_token_post" - } - } - }, - "required": True, - }, - } - }, - "/users/me/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - } - }, - "summary": "Read Users Me", - "operationId": "read_users_me_users_me__get", - "security": [{"OAuth2PasswordBearer": ["me"]}], - } - }, - "/users/me/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Own Items", - "operationId": "read_own_items_users_me_items__get", - "security": [{"OAuth2PasswordBearer": ["items", "me"]}], - } - }, - "/status/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read System Status", - "operationId": "read_system_status_status__get", - "security": [{"OAuth2PasswordBearer": []}], - } - }, - }, - "components": { - "schemas": { - "User": { - "title": "User", - "required": IsOneOf( - ["username", "email", "full_name", "disabled"], - # TODO: remove when deprecating Pydantic v1 - ["username"], - ), - "type": "object", - "properties": { - "username": {"title": "Username", "type": "string"}, - "email": IsDict( - { - "title": "Email", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Email", "type": "string"} - ), - "full_name": IsDict( - { - "title": "Full Name", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Full Name", "type": "string"} - ), - "disabled": IsDict( - { - "title": "Disabled", - "anyOf": [{"type": "boolean"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Disabled", "type": "boolean"} - ), - }, - }, - "Token": { - "title": "Token", - "required": ["access_token", "token_type"], - "type": "object", - "properties": { - "access_token": {"title": "Access Token", "type": "string"}, - "token_type": {"title": "Token Type", "type": "string"}, - }, - }, - "Body_login_for_access_token_token_post": { - "title": "Body_login_for_access_token_token_post", - "required": ["username", "password"], - "type": "object", - "properties": { - "grant_type": IsDict( - { - "title": "Grant Type", - "anyOf": [ - {"pattern": "password", "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Grant Type", - "pattern": "password", - "type": "string", - } - ), - "username": {"title": "Username", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - "scope": {"title": "Scope", "type": "string", "default": ""}, - "client_id": IsDict( - { - "title": "Client Id", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Id", "type": "string"} - ), - "client_secret": IsDict( - { - "title": "Client Secret", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Secret", "type": "string"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - }, - "securitySchemes": { - "OAuth2PasswordBearer": { - "type": "oauth2", - "flows": { - "password": { - "scopes": { - "me": "Read information about the current user.", - "items": "Read items.", - }, - "tokenUrl": "token", - } - }, - } - }, - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial005_an_py39.py b/tests/test_tutorial/test_security/test_tutorial005_an_py39.py deleted file mode 100644 index 17a3f9aa2..000000000 --- a/tests/test_tutorial/test_security/test_tutorial005_an_py39.py +++ /dev/null @@ -1,437 +0,0 @@ -import pytest -from dirty_equals import IsDict, IsOneOf -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.security.tutorial005_an_py39 import app - - client = TestClient(app) - return client - - -def get_access_token( - *, username="johndoe", password="secret", scope=None, client: TestClient -): - data = {"username": username, "password": password} - if scope: - data["scope"] = scope - response = client.post("/token", data=data) - content = response.json() - access_token = content.get("access_token") - return access_token - - -@needs_py39 -def test_login(client: TestClient): - response = client.post("/token", data={"username": "johndoe", "password": "secret"}) - assert response.status_code == 200, response.text - content = response.json() - assert "access_token" in content - assert content["token_type"] == "bearer" - - -@needs_py39 -def test_login_incorrect_password(client: TestClient): - response = client.post( - "/token", data={"username": "johndoe", "password": "incorrect"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py39 -def test_login_incorrect_username(client: TestClient): - response = client.post("/token", data={"username": "foo", "password": "secret"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py39 -def test_no_token(client: TestClient): - response = client.get("/users/me") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py39 -def test_token(client: TestClient): - access_token = get_access_token(scope="me", client=client) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "disabled": False, - } - - -@needs_py39 -def test_incorrect_token(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"}) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py39 -def test_incorrect_token_type(client: TestClient): - response = client.get( - "/users/me", headers={"Authorization": "Notexistent testtoken"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py39 -def test_verify_password(): - from docs_src.security.tutorial005_an_py39 import fake_users_db, verify_password - - assert verify_password("secret", fake_users_db["johndoe"]["hashed_password"]) - - -@needs_py39 -def test_get_password_hash(): - from docs_src.security.tutorial005_an_py39 import get_password_hash - - assert get_password_hash("secretalice") - - -@needs_py39 -def test_create_access_token(): - from docs_src.security.tutorial005_an_py39 import create_access_token - - access_token = create_access_token(data={"data": "foo"}) - assert access_token - - -@needs_py39 -def test_token_no_sub(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoiZm9vIn0.9ynBhuYb4e6aW3oJr_K_TBgwcMTDpRToQIE25L57rOE" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py39 -def test_token_no_username(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJmb28ifQ.NnExK_dlNAYyzACrXtXDrcWOgGY2JuPbI4eDaHdfK5Y" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py39 -def test_token_no_scope(client: TestClient): - access_token = get_access_token(client=client) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not enough permissions"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py39 -def test_token_inexistent_user(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VybmFtZTpib2IifQ.HcfCW67Uda-0gz54ZWTqmtgJnZeNem0Q757eTa9EZuw" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py39 -def test_token_inactive_user(client: TestClient): - access_token = get_access_token( - username="alice", password="secretalice", scope="me", client=client - ) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Inactive user"} - - -@needs_py39 -def test_read_items(client: TestClient): - access_token = get_access_token(scope="me items", client=client) - response = client.get( - "/users/me/items/", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == [{"item_id": "Foo", "owner": "johndoe"}] - - -@needs_py39 -def test_read_system_status(client: TestClient): - access_token = get_access_token(client=client) - response = client.get( - "/status/", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == {"status": "ok"} - - -@needs_py39 -def test_read_system_status_no_token(client: TestClient): - response = client.get("/status/") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/token": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Token"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Login For Access Token", - "operationId": "login_for_access_token_token_post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": { - "$ref": "#/components/schemas/Body_login_for_access_token_token_post" - } - } - }, - "required": True, - }, - } - }, - "/users/me/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - } - }, - "summary": "Read Users Me", - "operationId": "read_users_me_users_me__get", - "security": [{"OAuth2PasswordBearer": ["me"]}], - } - }, - "/users/me/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Own Items", - "operationId": "read_own_items_users_me_items__get", - "security": [{"OAuth2PasswordBearer": ["items", "me"]}], - } - }, - "/status/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read System Status", - "operationId": "read_system_status_status__get", - "security": [{"OAuth2PasswordBearer": []}], - } - }, - }, - "components": { - "schemas": { - "User": { - "title": "User", - "required": IsOneOf( - ["username", "email", "full_name", "disabled"], - # TODO: remove when deprecating Pydantic v1 - ["username"], - ), - "type": "object", - "properties": { - "username": {"title": "Username", "type": "string"}, - "email": IsDict( - { - "title": "Email", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Email", "type": "string"} - ), - "full_name": IsDict( - { - "title": "Full Name", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Full Name", "type": "string"} - ), - "disabled": IsDict( - { - "title": "Disabled", - "anyOf": [{"type": "boolean"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Disabled", "type": "boolean"} - ), - }, - }, - "Token": { - "title": "Token", - "required": ["access_token", "token_type"], - "type": "object", - "properties": { - "access_token": {"title": "Access Token", "type": "string"}, - "token_type": {"title": "Token Type", "type": "string"}, - }, - }, - "Body_login_for_access_token_token_post": { - "title": "Body_login_for_access_token_token_post", - "required": ["username", "password"], - "type": "object", - "properties": { - "grant_type": IsDict( - { - "title": "Grant Type", - "anyOf": [ - {"pattern": "password", "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Grant Type", - "pattern": "password", - "type": "string", - } - ), - "username": {"title": "Username", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - "scope": {"title": "Scope", "type": "string", "default": ""}, - "client_id": IsDict( - { - "title": "Client Id", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Id", "type": "string"} - ), - "client_secret": IsDict( - { - "title": "Client Secret", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Secret", "type": "string"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - }, - "securitySchemes": { - "OAuth2PasswordBearer": { - "type": "oauth2", - "flows": { - "password": { - "scopes": { - "me": "Read information about the current user.", - "items": "Read items.", - }, - "tokenUrl": "token", - } - }, - } - }, - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial005_py310.py b/tests/test_tutorial/test_security/test_tutorial005_py310.py deleted file mode 100644 index 06455cd63..000000000 --- a/tests/test_tutorial/test_security/test_tutorial005_py310.py +++ /dev/null @@ -1,437 +0,0 @@ -import pytest -from dirty_equals import IsDict, IsOneOf -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.security.tutorial005_py310 import app - - client = TestClient(app) - return client - - -def get_access_token( - *, username="johndoe", password="secret", scope=None, client: TestClient -): - data = {"username": username, "password": password} - if scope: - data["scope"] = scope - response = client.post("/token", data=data) - content = response.json() - access_token = content.get("access_token") - return access_token - - -@needs_py310 -def test_login(client: TestClient): - response = client.post("/token", data={"username": "johndoe", "password": "secret"}) - assert response.status_code == 200, response.text - content = response.json() - assert "access_token" in content - assert content["token_type"] == "bearer" - - -@needs_py310 -def test_login_incorrect_password(client: TestClient): - response = client.post( - "/token", data={"username": "johndoe", "password": "incorrect"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py310 -def test_login_incorrect_username(client: TestClient): - response = client.post("/token", data={"username": "foo", "password": "secret"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py310 -def test_no_token(client: TestClient): - response = client.get("/users/me") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_token(client: TestClient): - access_token = get_access_token(scope="me", client=client) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "disabled": False, - } - - -@needs_py310 -def test_incorrect_token(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"}) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py310 -def test_incorrect_token_type(client: TestClient): - response = client.get( - "/users/me", headers={"Authorization": "Notexistent testtoken"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_verify_password(): - from docs_src.security.tutorial005_py310 import fake_users_db, verify_password - - assert verify_password("secret", fake_users_db["johndoe"]["hashed_password"]) - - -@needs_py310 -def test_get_password_hash(): - from docs_src.security.tutorial005_py310 import get_password_hash - - assert get_password_hash("secretalice") - - -@needs_py310 -def test_create_access_token(): - from docs_src.security.tutorial005_py310 import create_access_token - - access_token = create_access_token(data={"data": "foo"}) - assert access_token - - -@needs_py310 -def test_token_no_sub(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoiZm9vIn0.9ynBhuYb4e6aW3oJr_K_TBgwcMTDpRToQIE25L57rOE" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py310 -def test_token_no_username(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJmb28ifQ.NnExK_dlNAYyzACrXtXDrcWOgGY2JuPbI4eDaHdfK5Y" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py310 -def test_token_no_scope(client: TestClient): - access_token = get_access_token(client=client) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not enough permissions"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py310 -def test_token_inexistent_user(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VybmFtZTpib2IifQ.HcfCW67Uda-0gz54ZWTqmtgJnZeNem0Q757eTa9EZuw" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py310 -def test_token_inactive_user(client: TestClient): - access_token = get_access_token( - username="alice", password="secretalice", scope="me", client=client - ) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Inactive user"} - - -@needs_py310 -def test_read_items(client: TestClient): - access_token = get_access_token(scope="me items", client=client) - response = client.get( - "/users/me/items/", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == [{"item_id": "Foo", "owner": "johndoe"}] - - -@needs_py310 -def test_read_system_status(client: TestClient): - access_token = get_access_token(client=client) - response = client.get( - "/status/", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == {"status": "ok"} - - -@needs_py310 -def test_read_system_status_no_token(client: TestClient): - response = client.get("/status/") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/token": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Token"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Login For Access Token", - "operationId": "login_for_access_token_token_post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": { - "$ref": "#/components/schemas/Body_login_for_access_token_token_post" - } - } - }, - "required": True, - }, - } - }, - "/users/me/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - } - }, - "summary": "Read Users Me", - "operationId": "read_users_me_users_me__get", - "security": [{"OAuth2PasswordBearer": ["me"]}], - } - }, - "/users/me/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Own Items", - "operationId": "read_own_items_users_me_items__get", - "security": [{"OAuth2PasswordBearer": ["items", "me"]}], - } - }, - "/status/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read System Status", - "operationId": "read_system_status_status__get", - "security": [{"OAuth2PasswordBearer": []}], - } - }, - }, - "components": { - "schemas": { - "User": { - "title": "User", - "required": IsOneOf( - ["username", "email", "full_name", "disabled"], - # TODO: remove when deprecating Pydantic v1 - ["username"], - ), - "type": "object", - "properties": { - "username": {"title": "Username", "type": "string"}, - "email": IsDict( - { - "title": "Email", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Email", "type": "string"} - ), - "full_name": IsDict( - { - "title": "Full Name", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Full Name", "type": "string"} - ), - "disabled": IsDict( - { - "title": "Disabled", - "anyOf": [{"type": "boolean"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Disabled", "type": "boolean"} - ), - }, - }, - "Token": { - "title": "Token", - "required": ["access_token", "token_type"], - "type": "object", - "properties": { - "access_token": {"title": "Access Token", "type": "string"}, - "token_type": {"title": "Token Type", "type": "string"}, - }, - }, - "Body_login_for_access_token_token_post": { - "title": "Body_login_for_access_token_token_post", - "required": ["username", "password"], - "type": "object", - "properties": { - "grant_type": IsDict( - { - "title": "Grant Type", - "anyOf": [ - {"pattern": "password", "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Grant Type", - "pattern": "password", - "type": "string", - } - ), - "username": {"title": "Username", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - "scope": {"title": "Scope", "type": "string", "default": ""}, - "client_id": IsDict( - { - "title": "Client Id", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Id", "type": "string"} - ), - "client_secret": IsDict( - { - "title": "Client Secret", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Secret", "type": "string"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - }, - "securitySchemes": { - "OAuth2PasswordBearer": { - "type": "oauth2", - "flows": { - "password": { - "scopes": { - "me": "Read information about the current user.", - "items": "Read items.", - }, - "tokenUrl": "token", - } - }, - } - }, - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial005_py39.py b/tests/test_tutorial/test_security/test_tutorial005_py39.py deleted file mode 100644 index 9455bfb4e..000000000 --- a/tests/test_tutorial/test_security/test_tutorial005_py39.py +++ /dev/null @@ -1,437 +0,0 @@ -import pytest -from dirty_equals import IsDict, IsOneOf -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.security.tutorial005_py39 import app - - client = TestClient(app) - return client - - -def get_access_token( - *, username="johndoe", password="secret", scope=None, client: TestClient -): - data = {"username": username, "password": password} - if scope: - data["scope"] = scope - response = client.post("/token", data=data) - content = response.json() - access_token = content.get("access_token") - return access_token - - -@needs_py39 -def test_login(client: TestClient): - response = client.post("/token", data={"username": "johndoe", "password": "secret"}) - assert response.status_code == 200, response.text - content = response.json() - assert "access_token" in content - assert content["token_type"] == "bearer" - - -@needs_py39 -def test_login_incorrect_password(client: TestClient): - response = client.post( - "/token", data={"username": "johndoe", "password": "incorrect"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py39 -def test_login_incorrect_username(client: TestClient): - response = client.post("/token", data={"username": "foo", "password": "secret"}) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Incorrect username or password"} - - -@needs_py39 -def test_no_token(client: TestClient): - response = client.get("/users/me") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py39 -def test_token(client: TestClient): - access_token = get_access_token(scope="me", client=client) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == { - "username": "johndoe", - "full_name": "John Doe", - "email": "johndoe@example.com", - "disabled": False, - } - - -@needs_py39 -def test_incorrect_token(client: TestClient): - response = client.get("/users/me", headers={"Authorization": "Bearer nonexistent"}) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py39 -def test_incorrect_token_type(client: TestClient): - response = client.get( - "/users/me", headers={"Authorization": "Notexistent testtoken"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py39 -def test_verify_password(): - from docs_src.security.tutorial005_py39 import fake_users_db, verify_password - - assert verify_password("secret", fake_users_db["johndoe"]["hashed_password"]) - - -@needs_py39 -def test_get_password_hash(): - from docs_src.security.tutorial005_py39 import get_password_hash - - assert get_password_hash("secretalice") - - -@needs_py39 -def test_create_access_token(): - from docs_src.security.tutorial005_py39 import create_access_token - - access_token = create_access_token(data={"data": "foo"}) - assert access_token - - -@needs_py39 -def test_token_no_sub(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjoiZm9vIn0.9ynBhuYb4e6aW3oJr_K_TBgwcMTDpRToQIE25L57rOE" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py39 -def test_token_no_username(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJmb28ifQ.NnExK_dlNAYyzACrXtXDrcWOgGY2JuPbI4eDaHdfK5Y" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py39 -def test_token_no_scope(client: TestClient): - access_token = get_access_token(client=client) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not enough permissions"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py39 -def test_token_inexistent_user(client: TestClient): - response = client.get( - "/users/me", - headers={ - "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VybmFtZTpib2IifQ.HcfCW67Uda-0gz54ZWTqmtgJnZeNem0Q757eTa9EZuw" - }, - ) - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Could not validate credentials"} - assert response.headers["WWW-Authenticate"] == 'Bearer scope="me"' - - -@needs_py39 -def test_token_inactive_user(client: TestClient): - access_token = get_access_token( - username="alice", password="secretalice", scope="me", client=client - ) - response = client.get( - "/users/me", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 400, response.text - assert response.json() == {"detail": "Inactive user"} - - -@needs_py39 -def test_read_items(client: TestClient): - access_token = get_access_token(scope="me items", client=client) - response = client.get( - "/users/me/items/", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == [{"item_id": "Foo", "owner": "johndoe"}] - - -@needs_py39 -def test_read_system_status(client: TestClient): - access_token = get_access_token(client=client) - response = client.get( - "/status/", headers={"Authorization": f"Bearer {access_token}"} - ) - assert response.status_code == 200, response.text - assert response.json() == {"status": "ok"} - - -@needs_py39 -def test_read_system_status_no_token(client: TestClient): - response = client.get("/status/") - assert response.status_code == 401, response.text - assert response.json() == {"detail": "Not authenticated"} - assert response.headers["WWW-Authenticate"] == "Bearer" - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/token": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Token"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Login For Access Token", - "operationId": "login_for_access_token_token_post", - "requestBody": { - "content": { - "application/x-www-form-urlencoded": { - "schema": { - "$ref": "#/components/schemas/Body_login_for_access_token_token_post" - } - } - }, - "required": True, - }, - } - }, - "/users/me/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - } - }, - "summary": "Read Users Me", - "operationId": "read_users_me_users_me__get", - "security": [{"OAuth2PasswordBearer": ["me"]}], - } - }, - "/users/me/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Own Items", - "operationId": "read_own_items_users_me_items__get", - "security": [{"OAuth2PasswordBearer": ["items", "me"]}], - } - }, - "/status/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read System Status", - "operationId": "read_system_status_status__get", - "security": [{"OAuth2PasswordBearer": []}], - } - }, - }, - "components": { - "schemas": { - "User": { - "title": "User", - "required": IsOneOf( - ["username", "email", "full_name", "disabled"], - # TODO: remove when deprecating Pydantic v1 - ["username"], - ), - "type": "object", - "properties": { - "username": {"title": "Username", "type": "string"}, - "email": IsDict( - { - "title": "Email", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Email", "type": "string"} - ), - "full_name": IsDict( - { - "title": "Full Name", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Full Name", "type": "string"} - ), - "disabled": IsDict( - { - "title": "Disabled", - "anyOf": [{"type": "boolean"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Disabled", "type": "boolean"} - ), - }, - }, - "Token": { - "title": "Token", - "required": ["access_token", "token_type"], - "type": "object", - "properties": { - "access_token": {"title": "Access Token", "type": "string"}, - "token_type": {"title": "Token Type", "type": "string"}, - }, - }, - "Body_login_for_access_token_token_post": { - "title": "Body_login_for_access_token_token_post", - "required": ["username", "password"], - "type": "object", - "properties": { - "grant_type": IsDict( - { - "title": "Grant Type", - "anyOf": [ - {"pattern": "password", "type": "string"}, - {"type": "null"}, - ], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Grant Type", - "pattern": "password", - "type": "string", - } - ), - "username": {"title": "Username", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - "scope": {"title": "Scope", "type": "string", "default": ""}, - "client_id": IsDict( - { - "title": "Client Id", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Id", "type": "string"} - ), - "client_secret": IsDict( - { - "title": "Client Secret", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Client Secret", "type": "string"} - ), - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - }, - "securitySchemes": { - "OAuth2PasswordBearer": { - "type": "oauth2", - "flows": { - "password": { - "scopes": { - "me": "Read information about the current user.", - "items": "Read items.", - }, - "tokenUrl": "token", - } - }, - } - }, - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial006.py b/tests/test_tutorial/test_security/test_tutorial006.py index dc459b6fd..40b413806 100644 --- a/tests/test_tutorial/test_security/test_tutorial006.py +++ b/tests/test_tutorial/test_security/test_tutorial006.py @@ -1,26 +1,41 @@ +import importlib from base64 import b64encode +import pytest from fastapi.testclient import TestClient -from docs_src.security.tutorial006 import app +from ...utils import needs_py39 -client = TestClient(app) +@pytest.fixture( + name="client", + params=[ + "tutorial006", + "tutorial006_an", + pytest.param("tutorial006_an_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.security.{request.param}") -def test_security_http_basic(): + client = TestClient(mod.app) + return client + + +def test_security_http_basic(client: TestClient): response = client.get("/users/me", auth=("john", "secret")) assert response.status_code == 200, response.text assert response.json() == {"username": "john", "password": "secret"} -def test_security_http_basic_no_credentials(): +def test_security_http_basic_no_credentials(client: TestClient): response = client.get("/users/me") assert response.json() == {"detail": "Not authenticated"} assert response.status_code == 401, response.text assert response.headers["WWW-Authenticate"] == "Basic" -def test_security_http_basic_invalid_credentials(): +def test_security_http_basic_invalid_credentials(client: TestClient): response = client.get( "/users/me", headers={"Authorization": "Basic notabase64token"} ) @@ -29,7 +44,7 @@ def test_security_http_basic_invalid_credentials(): assert response.json() == {"detail": "Invalid authentication credentials"} -def test_security_http_basic_non_basic_credentials(): +def test_security_http_basic_non_basic_credentials(client: TestClient): payload = b64encode(b"johnsecret").decode("ascii") auth_header = f"Basic {payload}" response = client.get("/users/me", headers={"Authorization": auth_header}) @@ -38,7 +53,7 @@ def test_security_http_basic_non_basic_credentials(): assert response.json() == {"detail": "Invalid authentication credentials"} -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_security/test_tutorial006_an.py b/tests/test_tutorial/test_security/test_tutorial006_an.py deleted file mode 100644 index 52ddd938f..000000000 --- a/tests/test_tutorial/test_security/test_tutorial006_an.py +++ /dev/null @@ -1,65 +0,0 @@ -from base64 import b64encode - -from fastapi.testclient import TestClient - -from docs_src.security.tutorial006_an import app - -client = TestClient(app) - - -def test_security_http_basic(): - response = client.get("/users/me", auth=("john", "secret")) - assert response.status_code == 200, response.text - assert response.json() == {"username": "john", "password": "secret"} - - -def test_security_http_basic_no_credentials(): - response = client.get("/users/me") - assert response.json() == {"detail": "Not authenticated"} - assert response.status_code == 401, response.text - assert response.headers["WWW-Authenticate"] == "Basic" - - -def test_security_http_basic_invalid_credentials(): - response = client.get( - "/users/me", headers={"Authorization": "Basic notabase64token"} - ) - assert response.status_code == 401, response.text - assert response.headers["WWW-Authenticate"] == "Basic" - assert response.json() == {"detail": "Invalid authentication credentials"} - - -def test_security_http_basic_non_basic_credentials(): - payload = b64encode(b"johnsecret").decode("ascii") - auth_header = f"Basic {payload}" - response = client.get("/users/me", headers={"Authorization": auth_header}) - assert response.status_code == 401, response.text - assert response.headers["WWW-Authenticate"] == "Basic" - assert response.json() == {"detail": "Invalid authentication credentials"} - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/me": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Current User", - "operationId": "read_current_user_users_me_get", - "security": [{"HTTPBasic": []}], - } - } - }, - "components": { - "securitySchemes": {"HTTPBasic": {"type": "http", "scheme": "basic"}} - }, - } diff --git a/tests/test_tutorial/test_security/test_tutorial006_an_py39.py b/tests/test_tutorial/test_security/test_tutorial006_an_py39.py deleted file mode 100644 index 52b22e573..000000000 --- a/tests/test_tutorial/test_security/test_tutorial006_an_py39.py +++ /dev/null @@ -1,77 +0,0 @@ -from base64 import b64encode - -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.security.tutorial006_an import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_security_http_basic(client: TestClient): - response = client.get("/users/me", auth=("john", "secret")) - assert response.status_code == 200, response.text - assert response.json() == {"username": "john", "password": "secret"} - - -@needs_py39 -def test_security_http_basic_no_credentials(client: TestClient): - response = client.get("/users/me") - assert response.json() == {"detail": "Not authenticated"} - assert response.status_code == 401, response.text - assert response.headers["WWW-Authenticate"] == "Basic" - - -@needs_py39 -def test_security_http_basic_invalid_credentials(client: TestClient): - response = client.get( - "/users/me", headers={"Authorization": "Basic notabase64token"} - ) - assert response.status_code == 401, response.text - assert response.headers["WWW-Authenticate"] == "Basic" - assert response.json() == {"detail": "Invalid authentication credentials"} - - -@needs_py39 -def test_security_http_basic_non_basic_credentials(client: TestClient): - payload = b64encode(b"johnsecret").decode("ascii") - auth_header = f"Basic {payload}" - response = client.get("/users/me", headers={"Authorization": auth_header}) - assert response.status_code == 401, response.text - assert response.headers["WWW-Authenticate"] == "Basic" - assert response.json() == {"detail": "Invalid authentication credentials"} - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/me": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - } - }, - "summary": "Read Current User", - "operationId": "read_current_user_users_me_get", - "security": [{"HTTPBasic": []}], - } - } - }, - "components": { - "securitySchemes": {"HTTPBasic": {"type": "http", "scheme": "basic"}} - }, - } diff --git a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001.py b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001.py index cdfae9f8c..059fb889b 100644 --- a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001.py +++ b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001.py @@ -1,14 +1,23 @@ +import importlib + import pytest from fastapi.testclient import TestClient -from ...utils import needs_pydanticv2 +from ...utils import needs_py39, needs_py310, needs_pydanticv2 -@pytest.fixture(name="client") -def get_client() -> TestClient: - from docs_src.separate_openapi_schemas.tutorial001 import app +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py310", marks=needs_py310), + pytest.param("tutorial001_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest) -> TestClient: + mod = importlib.import_module(f"docs_src.separate_openapi_schemas.{request.param}") - client = TestClient(app) + client = TestClient(mod.app) return client diff --git a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001_py310.py b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001_py310.py deleted file mode 100644 index 3b22146f6..000000000 --- a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001_py310.py +++ /dev/null @@ -1,136 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py310, needs_pydanticv2 - - -@pytest.fixture(name="client") -def get_client() -> TestClient: - from docs_src.separate_openapi_schemas.tutorial001_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_create_item(client: TestClient) -> None: - response = client.post("/items/", json={"name": "Foo"}) - assert response.status_code == 200, response.text - assert response.json() == {"name": "Foo", "description": None} - - -@needs_py310 -def test_read_items(client: TestClient) -> None: - response = client.get("/items/") - assert response.status_code == 200, response.text - assert response.json() == [ - { - "name": "Portal Gun", - "description": "Device to travel through the multi-rick-verse", - }, - {"name": "Plumbus", "description": None}, - ] - - -@needs_py310 -@needs_pydanticv2 -def test_openapi_schema(client: TestClient) -> None: - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "items": {"$ref": "#/components/schemas/Item"}, - "type": "array", - "title": "Response Read Items Items Get", - } - } - }, - } - }, - }, - "post": { - "summary": "Create Item", - "operationId": "create_item_items__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - }, - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "properties": { - "detail": { - "items": {"$ref": "#/components/schemas/ValidationError"}, - "type": "array", - "title": "Detail", - } - }, - "type": "object", - "title": "HTTPValidationError", - }, - "Item": { - "properties": { - "name": {"type": "string", "title": "Name"}, - "description": { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Description", - }, - }, - "type": "object", - "required": ["name"], - "title": "Item", - }, - "ValidationError": { - "properties": { - "loc": { - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - "type": "array", - "title": "Location", - }, - "msg": {"type": "string", "title": "Message"}, - "type": {"type": "string", "title": "Error Type"}, - }, - "type": "object", - "required": ["loc", "msg", "type"], - "title": "ValidationError", - }, - } - }, - } diff --git a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001_py39.py b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001_py39.py deleted file mode 100644 index 991abe811..000000000 --- a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001_py39.py +++ /dev/null @@ -1,136 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39, needs_pydanticv2 - - -@pytest.fixture(name="client") -def get_client() -> TestClient: - from docs_src.separate_openapi_schemas.tutorial001_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_create_item(client: TestClient) -> None: - response = client.post("/items/", json={"name": "Foo"}) - assert response.status_code == 200, response.text - assert response.json() == {"name": "Foo", "description": None} - - -@needs_py39 -def test_read_items(client: TestClient) -> None: - response = client.get("/items/") - assert response.status_code == 200, response.text - assert response.json() == [ - { - "name": "Portal Gun", - "description": "Device to travel through the multi-rick-verse", - }, - {"name": "Plumbus", "description": None}, - ] - - -@needs_py39 -@needs_pydanticv2 -def test_openapi_schema(client: TestClient) -> None: - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "items": {"$ref": "#/components/schemas/Item"}, - "type": "array", - "title": "Response Read Items Items Get", - } - } - }, - } - }, - }, - "post": { - "summary": "Create Item", - "operationId": "create_item_items__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - }, - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "properties": { - "detail": { - "items": {"$ref": "#/components/schemas/ValidationError"}, - "type": "array", - "title": "Detail", - } - }, - "type": "object", - "title": "HTTPValidationError", - }, - "Item": { - "properties": { - "name": {"type": "string", "title": "Name"}, - "description": { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Description", - }, - }, - "type": "object", - "required": ["name"], - "title": "Item", - }, - "ValidationError": { - "properties": { - "loc": { - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - "type": "array", - "title": "Location", - }, - "msg": {"type": "string", "title": "Message"}, - "type": {"type": "string", "title": "Error Type"}, - }, - "type": "object", - "required": ["loc", "msg", "type"], - "title": "ValidationError", - }, - } - }, - } diff --git a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002.py b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002.py index d2cf7945b..cc9afeab7 100644 --- a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002.py +++ b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002.py @@ -1,14 +1,23 @@ +import importlib + import pytest from fastapi.testclient import TestClient -from ...utils import needs_pydanticv2 +from ...utils import needs_py39, needs_py310, needs_pydanticv2 -@pytest.fixture(name="client") -def get_client() -> TestClient: - from docs_src.separate_openapi_schemas.tutorial002 import app +@pytest.fixture( + name="client", + params=[ + "tutorial002", + pytest.param("tutorial002_py310", marks=needs_py310), + pytest.param("tutorial002_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest) -> TestClient: + mod = importlib.import_module(f"docs_src.separate_openapi_schemas.{request.param}") - client = TestClient(app) + client = TestClient(mod.app) return client diff --git a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002_py310.py b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002_py310.py deleted file mode 100644 index 89c9ce977..000000000 --- a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002_py310.py +++ /dev/null @@ -1,136 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py310, needs_pydanticv2 - - -@pytest.fixture(name="client") -def get_client() -> TestClient: - from docs_src.separate_openapi_schemas.tutorial002_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_create_item(client: TestClient) -> None: - response = client.post("/items/", json={"name": "Foo"}) - assert response.status_code == 200, response.text - assert response.json() == {"name": "Foo", "description": None} - - -@needs_py310 -def test_read_items(client: TestClient) -> None: - response = client.get("/items/") - assert response.status_code == 200, response.text - assert response.json() == [ - { - "name": "Portal Gun", - "description": "Device to travel through the multi-rick-verse", - }, - {"name": "Plumbus", "description": None}, - ] - - -@needs_py310 -@needs_pydanticv2 -def test_openapi_schema(client: TestClient) -> None: - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "items": {"$ref": "#/components/schemas/Item"}, - "type": "array", - "title": "Response Read Items Items Get", - } - } - }, - } - }, - }, - "post": { - "summary": "Create Item", - "operationId": "create_item_items__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - }, - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "properties": { - "detail": { - "items": {"$ref": "#/components/schemas/ValidationError"}, - "type": "array", - "title": "Detail", - } - }, - "type": "object", - "title": "HTTPValidationError", - }, - "Item": { - "properties": { - "name": {"type": "string", "title": "Name"}, - "description": { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Description", - }, - }, - "type": "object", - "required": ["name"], - "title": "Item", - }, - "ValidationError": { - "properties": { - "loc": { - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - "type": "array", - "title": "Location", - }, - "msg": {"type": "string", "title": "Message"}, - "type": {"type": "string", "title": "Error Type"}, - }, - "type": "object", - "required": ["loc", "msg", "type"], - "title": "ValidationError", - }, - } - }, - } diff --git a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002_py39.py b/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002_py39.py deleted file mode 100644 index 6ac3d8f79..000000000 --- a/tests/test_tutorial/test_separate_openapi_schemas/test_tutorial002_py39.py +++ /dev/null @@ -1,136 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39, needs_pydanticv2 - - -@pytest.fixture(name="client") -def get_client() -> TestClient: - from docs_src.separate_openapi_schemas.tutorial002_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_create_item(client: TestClient) -> None: - response = client.post("/items/", json={"name": "Foo"}) - assert response.status_code == 200, response.text - assert response.json() == {"name": "Foo", "description": None} - - -@needs_py39 -def test_read_items(client: TestClient) -> None: - response = client.get("/items/") - assert response.status_code == 200, response.text - assert response.json() == [ - { - "name": "Portal Gun", - "description": "Device to travel through the multi-rick-verse", - }, - {"name": "Plumbus", "description": None}, - ] - - -@needs_py39 -@needs_pydanticv2 -def test_openapi_schema(client: TestClient) -> None: - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "items": {"$ref": "#/components/schemas/Item"}, - "type": "array", - "title": "Response Read Items Items Get", - } - } - }, - } - }, - }, - "post": { - "summary": "Create Item", - "operationId": "create_item_items__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - "required": True, - }, - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - }, - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "properties": { - "detail": { - "items": {"$ref": "#/components/schemas/ValidationError"}, - "type": "array", - "title": "Detail", - } - }, - "type": "object", - "title": "HTTPValidationError", - }, - "Item": { - "properties": { - "name": {"type": "string", "title": "Name"}, - "description": { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Description", - }, - }, - "type": "object", - "required": ["name"], - "title": "Item", - }, - "ValidationError": { - "properties": { - "loc": { - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - "type": "array", - "title": "Location", - }, - "msg": {"type": "string", "title": "Message"}, - "type": {"type": "string", "title": "Error Type"}, - }, - "type": "object", - "required": ["loc", "msg", "type"], - "title": "ValidationError", - }, - } - }, - } diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases.py b/tests/test_tutorial/test_sql_databases/test_sql_databases.py deleted file mode 100644 index 03e747433..000000000 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases.py +++ /dev/null @@ -1,419 +0,0 @@ -import importlib -import os -from pathlib import Path - -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_pydanticv1 - - -@pytest.fixture(scope="module") -def client(tmp_path_factory: pytest.TempPathFactory): - tmp_path = tmp_path_factory.mktemp("data") - cwd = os.getcwd() - os.chdir(tmp_path) - test_db = Path("./sql_app.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app import main - - # Ensure import side effects are re-executed - importlib.reload(main) - with TestClient(main.app) as c: - yield c - if test_db.is_file(): # pragma: nocover - test_db.unlink() - os.chdir(cwd) - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_create_user(client): - test_user = {"email": "johndoe@example.com", "password": "secret"} - response = client.post("/users/", json=test_user) - assert response.status_code == 200, response.text - data = response.json() - assert test_user["email"] == data["email"] - assert "id" in data - response = client.post("/users/", json=test_user) - assert response.status_code == 400, response.text - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_user(client): - response = client.get("/users/1") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data - assert "id" in data - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_inexistent_user(client): - response = client.get("/users/999") - assert response.status_code == 404, response.text - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_users(client): - response = client.get("/users/") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data[0] - assert "id" in data[0] - - -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_create_item(client): - item = {"title": "Foo", "description": "Something that fights"} - response = client.post("/users/1/items/", json=item) - assert response.status_code == 200, response.text - item_data = response.json() - assert item["title"] == item_data["title"] - assert item["description"] == item_data["description"] - assert "id" in item_data - assert "owner_id" in item_data - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - - -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_read_items(client): - response = client.get("/items/") - assert response.status_code == 200, response.text - data = response.json() - assert data - first_item = data[0] - assert "title" in first_item - assert "description" in first_item - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Users Users Get", - "type": "array", - "items": {"$ref": "#/components/schemas/User"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - }, - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create User", - "operationId": "create_user_users__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/UserCreate"} - } - }, - "required": True, - }, - }, - }, - "/users/{user_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read User", - "operationId": "read_user_users__user_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - } - }, - "/users/{user_id}/items/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Item For User", - "operationId": "create_item_for_user_users__user_id__items__post", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/ItemCreate"} - } - }, - "required": True, - }, - } - }, - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Items Items Get", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - }, - "components": { - "schemas": { - "ItemCreate": { - "title": "ItemCreate", - "required": ["title"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - }, - }, - "Item": { - "title": "Item", - "required": ["title", "id", "owner_id"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"}, - ), - "id": {"title": "Id", "type": "integer"}, - "owner_id": {"title": "Owner Id", "type": "integer"}, - }, - }, - "User": { - "title": "User", - "required": ["email", "id", "is_active"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "id": {"title": "Id", "type": "integer"}, - "is_active": {"title": "Is Active", "type": "boolean"}, - "items": { - "title": "Items", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - "default": [], - }, - }, - }, - "UserCreate": { - "title": "UserCreate", - "required": ["email", "password"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware.py deleted file mode 100644 index a503ef2a6..000000000 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware.py +++ /dev/null @@ -1,421 +0,0 @@ -import importlib -from pathlib import Path - -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_pydanticv1 - - -@pytest.fixture(scope="module") -def client(): - test_db = Path("./sql_app.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app import alt_main - - # Ensure import side effects are re-executed - importlib.reload(alt_main) - - with TestClient(alt_main.app) as c: - yield c - if test_db.is_file(): # pragma: nocover - test_db.unlink() - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_create_user(client): - test_user = {"email": "johndoe@example.com", "password": "secret"} - response = client.post("/users/", json=test_user) - assert response.status_code == 200, response.text - data = response.json() - assert test_user["email"] == data["email"] - assert "id" in data - response = client.post("/users/", json=test_user) - assert response.status_code == 400, response.text - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_user(client): - response = client.get("/users/1") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data - assert "id" in data - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_inexistent_user(client): - response = client.get("/users/999") - assert response.status_code == 404, response.text - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_users(client): - response = client.get("/users/") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data[0] - assert "id" in data[0] - - -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_create_item(client): - item = {"title": "Foo", "description": "Something that fights"} - response = client.post("/users/1/items/", json=item) - assert response.status_code == 200, response.text - item_data = response.json() - assert item["title"] == item_data["title"] - assert item["description"] == item_data["description"] - assert "id" in item_data - assert "owner_id" in item_data - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - - -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_read_items(client): - response = client.get("/items/") - assert response.status_code == 200, response.text - data = response.json() - assert data - first_item = data[0] - assert "title" in first_item - assert "description" in first_item - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Users Users Get", - "type": "array", - "items": {"$ref": "#/components/schemas/User"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - }, - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create User", - "operationId": "create_user_users__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/UserCreate"} - } - }, - "required": True, - }, - }, - }, - "/users/{user_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read User", - "operationId": "read_user_users__user_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - } - }, - "/users/{user_id}/items/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Item For User", - "operationId": "create_item_for_user_users__user_id__items__post", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/ItemCreate"} - } - }, - "required": True, - }, - } - }, - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Items Items Get", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - }, - "components": { - "schemas": { - "ItemCreate": { - "title": "ItemCreate", - "required": ["title"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - }, - }, - "Item": { - "title": "Item", - "required": ["title", "id", "owner_id"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"}, - ), - "id": {"title": "Id", "type": "integer"}, - "owner_id": {"title": "Owner Id", "type": "integer"}, - }, - }, - "User": { - "title": "User", - "required": ["email", "id", "is_active"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "id": {"title": "Id", "type": "integer"}, - "is_active": {"title": "Is Active", "type": "boolean"}, - "items": { - "title": "Items", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - "default": [], - }, - }, - }, - "UserCreate": { - "title": "UserCreate", - "required": ["email", "password"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py310.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py310.py deleted file mode 100644 index d54cc6552..000000000 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py310.py +++ /dev/null @@ -1,433 +0,0 @@ -import importlib -import os -from pathlib import Path - -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310, needs_pydanticv1 - - -@pytest.fixture(scope="module") -def client(tmp_path_factory: pytest.TempPathFactory): - tmp_path = tmp_path_factory.mktemp("data") - cwd = os.getcwd() - os.chdir(tmp_path) - test_db = Path("./sql_app.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app_py310 import alt_main - - # Ensure import side effects are re-executed - importlib.reload(alt_main) - - with TestClient(alt_main.app) as c: - yield c - if test_db.is_file(): # pragma: nocover - test_db.unlink() - os.chdir(cwd) - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_create_user(client): - test_user = {"email": "johndoe@example.com", "password": "secret"} - response = client.post("/users/", json=test_user) - assert response.status_code == 200, response.text - data = response.json() - assert test_user["email"] == data["email"] - assert "id" in data - response = client.post("/users/", json=test_user) - assert response.status_code == 400, response.text - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_user(client): - response = client.get("/users/1") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data - assert "id" in data - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_inexistent_user(client): - response = client.get("/users/999") - assert response.status_code == 404, response.text - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_users(client): - response = client.get("/users/") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data[0] - assert "id" in data[0] - - -@needs_py310 -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_create_item(client): - item = {"title": "Foo", "description": "Something that fights"} - response = client.post("/users/1/items/", json=item) - assert response.status_code == 200, response.text - item_data = response.json() - assert item["title"] == item_data["title"] - assert item["description"] == item_data["description"] - assert "id" in item_data - assert "owner_id" in item_data - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - - -@needs_py310 -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_read_items(client): - response = client.get("/items/") - assert response.status_code == 200, response.text - data = response.json() - assert data - first_item = data[0] - assert "title" in first_item - assert "description" in first_item - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Users Users Get", - "type": "array", - "items": {"$ref": "#/components/schemas/User"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - }, - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create User", - "operationId": "create_user_users__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/UserCreate"} - } - }, - "required": True, - }, - }, - }, - "/users/{user_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read User", - "operationId": "read_user_users__user_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - } - }, - "/users/{user_id}/items/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Item For User", - "operationId": "create_item_for_user_users__user_id__items__post", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/ItemCreate"} - } - }, - "required": True, - }, - } - }, - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Items Items Get", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - }, - "components": { - "schemas": { - "ItemCreate": { - "title": "ItemCreate", - "required": ["title"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - }, - }, - "Item": { - "title": "Item", - "required": ["title", "id", "owner_id"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"}, - ), - "id": {"title": "Id", "type": "integer"}, - "owner_id": {"title": "Owner Id", "type": "integer"}, - }, - }, - "User": { - "title": "User", - "required": ["email", "id", "is_active"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "id": {"title": "Id", "type": "integer"}, - "is_active": {"title": "Is Active", "type": "boolean"}, - "items": { - "title": "Items", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - "default": [], - }, - }, - }, - "UserCreate": { - "title": "UserCreate", - "required": ["email", "password"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py39.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py39.py deleted file mode 100644 index 4e43995e6..000000000 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases_middleware_py39.py +++ /dev/null @@ -1,433 +0,0 @@ -import importlib -import os -from pathlib import Path - -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39, needs_pydanticv1 - - -@pytest.fixture(scope="module") -def client(tmp_path_factory: pytest.TempPathFactory): - tmp_path = tmp_path_factory.mktemp("data") - cwd = os.getcwd() - os.chdir(tmp_path) - test_db = Path("./sql_app.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app_py39 import alt_main - - # Ensure import side effects are re-executed - importlib.reload(alt_main) - - with TestClient(alt_main.app) as c: - yield c - if test_db.is_file(): # pragma: nocover - test_db.unlink() - os.chdir(cwd) - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_create_user(client): - test_user = {"email": "johndoe@example.com", "password": "secret"} - response = client.post("/users/", json=test_user) - assert response.status_code == 200, response.text - data = response.json() - assert test_user["email"] == data["email"] - assert "id" in data - response = client.post("/users/", json=test_user) - assert response.status_code == 400, response.text - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_user(client): - response = client.get("/users/1") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data - assert "id" in data - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_inexistent_user(client): - response = client.get("/users/999") - assert response.status_code == 404, response.text - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_users(client): - response = client.get("/users/") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data[0] - assert "id" in data[0] - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_create_item(client): - item = {"title": "Foo", "description": "Something that fights"} - response = client.post("/users/1/items/", json=item) - assert response.status_code == 200, response.text - item_data = response.json() - assert item["title"] == item_data["title"] - assert item["description"] == item_data["description"] - assert "id" in item_data - assert "owner_id" in item_data - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_read_items(client): - response = client.get("/items/") - assert response.status_code == 200, response.text - data = response.json() - assert data - first_item = data[0] - assert "title" in first_item - assert "description" in first_item - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Users Users Get", - "type": "array", - "items": {"$ref": "#/components/schemas/User"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - }, - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create User", - "operationId": "create_user_users__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/UserCreate"} - } - }, - "required": True, - }, - }, - }, - "/users/{user_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read User", - "operationId": "read_user_users__user_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - } - }, - "/users/{user_id}/items/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Item For User", - "operationId": "create_item_for_user_users__user_id__items__post", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/ItemCreate"} - } - }, - "required": True, - }, - } - }, - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Items Items Get", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - }, - "components": { - "schemas": { - "ItemCreate": { - "title": "ItemCreate", - "required": ["title"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - }, - }, - "Item": { - "title": "Item", - "required": ["title", "id", "owner_id"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"}, - ), - "id": {"title": "Id", "type": "integer"}, - "owner_id": {"title": "Owner Id", "type": "integer"}, - }, - }, - "User": { - "title": "User", - "required": ["email", "id", "is_active"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "id": {"title": "Id", "type": "integer"}, - "is_active": {"title": "Is Active", "type": "boolean"}, - "items": { - "title": "Items", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - "default": [], - }, - }, - }, - "UserCreate": { - "title": "UserCreate", - "required": ["email", "password"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_py310.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_py310.py deleted file mode 100644 index b89b8b031..000000000 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases_py310.py +++ /dev/null @@ -1,432 +0,0 @@ -import importlib -import os -from pathlib import Path - -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310, needs_pydanticv1 - - -@pytest.fixture(scope="module", name="client") -def get_client(tmp_path_factory: pytest.TempPathFactory): - tmp_path = tmp_path_factory.mktemp("data") - cwd = os.getcwd() - os.chdir(tmp_path) - test_db = Path("./sql_app.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app_py310 import main - - # Ensure import side effects are re-executed - importlib.reload(main) - with TestClient(main.app) as c: - yield c - if test_db.is_file(): # pragma: nocover - test_db.unlink() - os.chdir(cwd) - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_create_user(client): - test_user = {"email": "johndoe@example.com", "password": "secret"} - response = client.post("/users/", json=test_user) - assert response.status_code == 200, response.text - data = response.json() - assert test_user["email"] == data["email"] - assert "id" in data - response = client.post("/users/", json=test_user) - assert response.status_code == 400, response.text - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_user(client): - response = client.get("/users/1") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data - assert "id" in data - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_inexistent_user(client): - response = client.get("/users/999") - assert response.status_code == 404, response.text - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_users(client): - response = client.get("/users/") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data[0] - assert "id" in data[0] - - -@needs_py310 -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_create_item(client): - item = {"title": "Foo", "description": "Something that fights"} - response = client.post("/users/1/items/", json=item) - assert response.status_code == 200, response.text - item_data = response.json() - assert item["title"] == item_data["title"] - assert item["description"] == item_data["description"] - assert "id" in item_data - assert "owner_id" in item_data - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - - -@needs_py310 -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_read_items(client): - response = client.get("/items/") - assert response.status_code == 200, response.text - data = response.json() - assert data - first_item = data[0] - assert "title" in first_item - assert "description" in first_item - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Users Users Get", - "type": "array", - "items": {"$ref": "#/components/schemas/User"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - }, - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create User", - "operationId": "create_user_users__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/UserCreate"} - } - }, - "required": True, - }, - }, - }, - "/users/{user_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read User", - "operationId": "read_user_users__user_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - } - }, - "/users/{user_id}/items/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Item For User", - "operationId": "create_item_for_user_users__user_id__items__post", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/ItemCreate"} - } - }, - "required": True, - }, - } - }, - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Items Items Get", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - }, - "components": { - "schemas": { - "ItemCreate": { - "title": "ItemCreate", - "required": ["title"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - }, - }, - "Item": { - "title": "Item", - "required": ["title", "id", "owner_id"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"}, - ), - "id": {"title": "Id", "type": "integer"}, - "owner_id": {"title": "Owner Id", "type": "integer"}, - }, - }, - "User": { - "title": "User", - "required": ["email", "id", "is_active"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "id": {"title": "Id", "type": "integer"}, - "is_active": {"title": "Is Active", "type": "boolean"}, - "items": { - "title": "Items", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - "default": [], - }, - }, - }, - "UserCreate": { - "title": "UserCreate", - "required": ["email", "password"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_sql_databases/test_sql_databases_py39.py b/tests/test_tutorial/test_sql_databases/test_sql_databases_py39.py deleted file mode 100644 index 13351bc81..000000000 --- a/tests/test_tutorial/test_sql_databases/test_sql_databases_py39.py +++ /dev/null @@ -1,432 +0,0 @@ -import importlib -import os -from pathlib import Path - -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39, needs_pydanticv1 - - -@pytest.fixture(scope="module", name="client") -def get_client(tmp_path_factory: pytest.TempPathFactory): - tmp_path = tmp_path_factory.mktemp("data") - cwd = os.getcwd() - os.chdir(tmp_path) - test_db = Path("./sql_app.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app_py39 import main - - # Ensure import side effects are re-executed - importlib.reload(main) - with TestClient(main.app) as c: - yield c - if test_db.is_file(): # pragma: nocover - test_db.unlink() - os.chdir(cwd) - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_create_user(client): - test_user = {"email": "johndoe@example.com", "password": "secret"} - response = client.post("/users/", json=test_user) - assert response.status_code == 200, response.text - data = response.json() - assert test_user["email"] == data["email"] - assert "id" in data - response = client.post("/users/", json=test_user) - assert response.status_code == 400, response.text - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_user(client): - response = client.get("/users/1") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data - assert "id" in data - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_inexistent_user(client): - response = client.get("/users/999") - assert response.status_code == 404, response.text - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_get_users(client): - response = client.get("/users/") - assert response.status_code == 200, response.text - data = response.json() - assert "email" in data[0] - assert "id" in data[0] - - -@needs_py39 -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_create_item(client): - item = {"title": "Foo", "description": "Something that fights"} - response = client.post("/users/1/items/", json=item) - assert response.status_code == 200, response.text - item_data = response.json() - assert item["title"] == item_data["title"] - assert item["description"] == item_data["description"] - assert "id" in item_data - assert "owner_id" in item_data - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - response = client.get("/users/1") - assert response.status_code == 200, response.text - user_data = response.json() - item_to_check = [it for it in user_data["items"] if it["id"] == item_data["id"]][0] - assert item_to_check["title"] == item["title"] - assert item_to_check["description"] == item["description"] - - -@needs_py39 -# TODO: pv2 add Pydantic v2 version -@needs_pydanticv1 -def test_read_items(client): - response = client.get("/items/") - assert response.status_code == 200, response.text - data = response.json() - assert data - first_item = data[0] - assert "title" in first_item - assert "description" in first_item - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/users/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Users Users Get", - "type": "array", - "items": {"$ref": "#/components/schemas/User"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Users", - "operationId": "read_users_users__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - }, - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create User", - "operationId": "create_user_users__post", - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/UserCreate"} - } - }, - "required": True, - }, - }, - }, - "/users/{user_id}": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/User"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read User", - "operationId": "read_user_users__user_id__get", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - } - }, - "/users/{user_id}/items/": { - "post": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/Item"} - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Create Item For User", - "operationId": "create_item_for_user_users__user_id__items__post", - "parameters": [ - { - "required": True, - "schema": {"title": "User Id", "type": "integer"}, - "name": "user_id", - "in": "path", - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": {"$ref": "#/components/schemas/ItemCreate"} - } - }, - "required": True, - }, - } - }, - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": { - "application/json": { - "schema": { - "title": "Response Read Items Items Get", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - } - } - }, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Skip", - "type": "integer", - "default": 0, - }, - "name": "skip", - "in": "query", - }, - { - "required": False, - "schema": { - "title": "Limit", - "type": "integer", - "default": 100, - }, - "name": "limit", - "in": "query", - }, - ], - } - }, - }, - "components": { - "schemas": { - "ItemCreate": { - "title": "ItemCreate", - "required": ["title"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"} - ), - }, - }, - "Item": { - "title": "Item", - "required": ["title", "id", "owner_id"], - "type": "object", - "properties": { - "title": {"title": "Title", "type": "string"}, - "description": IsDict( - { - "title": "Description", - "anyOf": [{"type": "string"}, {"type": "null"}], - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - {"title": "Description", "type": "string"}, - ), - "id": {"title": "Id", "type": "integer"}, - "owner_id": {"title": "Owner Id", "type": "integer"}, - }, - }, - "User": { - "title": "User", - "required": ["email", "id", "is_active"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "id": {"title": "Id", "type": "integer"}, - "is_active": {"title": "Is Active", "type": "boolean"}, - "items": { - "title": "Items", - "type": "array", - "items": {"$ref": "#/components/schemas/Item"}, - "default": [], - }, - }, - }, - "UserCreate": { - "title": "UserCreate", - "required": ["email", "password"], - "type": "object", - "properties": { - "email": {"title": "Email", "type": "string"}, - "password": {"title": "Password", "type": "string"}, - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_sql_databases/test_testing_databases.py b/tests/test_tutorial/test_sql_databases/test_testing_databases.py deleted file mode 100644 index ce6ce230c..000000000 --- a/tests/test_tutorial/test_sql_databases/test_testing_databases.py +++ /dev/null @@ -1,27 +0,0 @@ -import importlib -import os -from pathlib import Path - -import pytest - -from ...utils import needs_pydanticv1 - - -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_testing_dbs(tmp_path_factory: pytest.TempPathFactory): - tmp_path = tmp_path_factory.mktemp("data") - cwd = os.getcwd() - os.chdir(tmp_path) - test_db = Path("./test.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app.tests import test_sql_app - - # Ensure import side effects are re-executed - importlib.reload(test_sql_app) - test_sql_app.test_create_user() - if test_db.is_file(): # pragma: nocover - test_db.unlink() - os.chdir(cwd) diff --git a/tests/test_tutorial/test_sql_databases/test_testing_databases_py310.py b/tests/test_tutorial/test_sql_databases/test_testing_databases_py310.py deleted file mode 100644 index 545d63c2a..000000000 --- a/tests/test_tutorial/test_sql_databases/test_testing_databases_py310.py +++ /dev/null @@ -1,28 +0,0 @@ -import importlib -import os -from pathlib import Path - -import pytest - -from ...utils import needs_py310, needs_pydanticv1 - - -@needs_py310 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_testing_dbs_py39(tmp_path_factory: pytest.TempPathFactory): - tmp_path = tmp_path_factory.mktemp("data") - cwd = os.getcwd() - os.chdir(tmp_path) - test_db = Path("./test.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app_py310.tests import test_sql_app - - # Ensure import side effects are re-executed - importlib.reload(test_sql_app) - test_sql_app.test_create_user() - if test_db.is_file(): # pragma: nocover - test_db.unlink() - os.chdir(cwd) diff --git a/tests/test_tutorial/test_sql_databases/test_testing_databases_py39.py b/tests/test_tutorial/test_sql_databases/test_testing_databases_py39.py deleted file mode 100644 index 99bfd3fa8..000000000 --- a/tests/test_tutorial/test_sql_databases/test_testing_databases_py39.py +++ /dev/null @@ -1,28 +0,0 @@ -import importlib -import os -from pathlib import Path - -import pytest - -from ...utils import needs_py39, needs_pydanticv1 - - -@needs_py39 -# TODO: pv2 add version with Pydantic v2 -@needs_pydanticv1 -def test_testing_dbs_py39(tmp_path_factory: pytest.TempPathFactory): - tmp_path = tmp_path_factory.mktemp("data") - cwd = os.getcwd() - os.chdir(tmp_path) - test_db = Path("./test.db") - if test_db.is_file(): # pragma: nocover - test_db.unlink() - # Import while creating the client to create the DB after starting the test session - from docs_src.sql_databases.sql_app_py39.tests import test_sql_app - - # Ensure import side effects are re-executed - importlib.reload(test_sql_app) - test_sql_app.test_create_user() - if test_db.is_file(): # pragma: nocover - test_db.unlink() - os.chdir(cwd) diff --git a/tests/test_tutorial/test_sql_databases/test_tutorial001.py b/tests/test_tutorial/test_sql_databases/test_tutorial001.py new file mode 100644 index 000000000..cc7e590df --- /dev/null +++ b/tests/test_tutorial/test_sql_databases/test_tutorial001.py @@ -0,0 +1,373 @@ +import importlib +import warnings + +import pytest +from dirty_equals import IsDict, IsInt +from fastapi.testclient import TestClient +from inline_snapshot import snapshot +from sqlalchemy import StaticPool +from sqlmodel import SQLModel, create_engine +from sqlmodel.main import default_registry + +from tests.utils import needs_py39, needs_py310 + + +def clear_sqlmodel(): + # Clear the tables in the metadata for the default base model + SQLModel.metadata.clear() + # Clear the Models associated with the registry, to avoid warnings + default_registry.dispose() + + +@pytest.fixture( + name="client", + params=[ + "tutorial001", + pytest.param("tutorial001_py39", marks=needs_py39), + pytest.param("tutorial001_py310", marks=needs_py310), + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + pytest.param("tutorial001_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + clear_sqlmodel() + # TODO: remove when updating SQL tutorial to use new lifespan API + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + mod = importlib.import_module(f"docs_src.sql_databases.{request.param}") + clear_sqlmodel() + importlib.reload(mod) + mod.sqlite_url = "sqlite://" + mod.engine = create_engine( + mod.sqlite_url, connect_args={"check_same_thread": False}, poolclass=StaticPool + ) + + with TestClient(mod.app) as c: + yield c + + +def test_crud_app(client: TestClient): + # TODO: this warns that SQLModel.from_orm is deprecated in Pydantic v1, refactor + # this if using obj.model_validate becomes independent of Pydantic v2 + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + # No heroes before creating + response = client.get("heroes/") + assert response.status_code == 200, response.text + assert response.json() == [] + + # Create a hero + response = client.post( + "/heroes/", + json={ + "id": 999, + "name": "Dead Pond", + "age": 30, + "secret_name": "Dive Wilson", + }, + ) + assert response.status_code == 200, response.text + assert response.json() == snapshot( + {"age": 30, "secret_name": "Dive Wilson", "id": 999, "name": "Dead Pond"} + ) + + # Read a hero + hero_id = response.json()["id"] + response = client.get(f"/heroes/{hero_id}") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + {"name": "Dead Pond", "age": 30, "id": 999, "secret_name": "Dive Wilson"} + ) + + # Read all heroes + # Create more heroes first + response = client.post( + "/heroes/", + json={"name": "Spider-Boy", "age": 18, "secret_name": "Pedro Parqueador"}, + ) + assert response.status_code == 200, response.text + response = client.post( + "/heroes/", json={"name": "Rusty-Man", "secret_name": "Tommy Sharp"} + ) + assert response.status_code == 200, response.text + + response = client.get("/heroes/") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + [ + { + "name": "Dead Pond", + "age": 30, + "id": IsInt(), + "secret_name": "Dive Wilson", + }, + { + "name": "Spider-Boy", + "age": 18, + "id": IsInt(), + "secret_name": "Pedro Parqueador", + }, + { + "name": "Rusty-Man", + "age": None, + "id": IsInt(), + "secret_name": "Tommy Sharp", + }, + ] + ) + + response = client.get("/heroes/?offset=1&limit=1") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + [ + { + "name": "Spider-Boy", + "age": 18, + "id": IsInt(), + "secret_name": "Pedro Parqueador", + } + ] + ) + + # Delete a hero + response = client.delete(f"/heroes/{hero_id}") + assert response.status_code == 200, response.text + assert response.json() == snapshot({"ok": True}) + + response = client.get(f"/heroes/{hero_id}") + assert response.status_code == 404, response.text + + response = client.delete(f"/heroes/{hero_id}") + assert response.status_code == 404, response.text + assert response.json() == snapshot({"detail": "Hero not found"}) + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/heroes/": { + "post": { + "summary": "Create Hero", + "operationId": "create_hero_heroes__post", + "requestBody": { + "required": True, + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Hero"} + } + }, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Hero"} + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + "get": { + "summary": "Read Heroes", + "operationId": "read_heroes_heroes__get", + "parameters": [ + { + "name": "offset", + "in": "query", + "required": False, + "schema": { + "type": "integer", + "default": 0, + "title": "Offset", + }, + }, + { + "name": "limit", + "in": "query", + "required": False, + "schema": { + "type": "integer", + "maximum": 100, + "default": 100, + "title": "Limit", + }, + }, + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Hero" + }, + "title": "Response Read Heroes Heroes Get", + } + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + }, + "/heroes/{hero_id}": { + "get": { + "summary": "Read Hero", + "operationId": "read_hero_heroes__hero_id__get", + "parameters": [ + { + "name": "hero_id", + "in": "path", + "required": True, + "schema": {"type": "integer", "title": "Hero Id"}, + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {"$ref": "#/components/schemas/Hero"} + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + "delete": { + "summary": "Delete Hero", + "operationId": "delete_hero_heroes__hero_id__delete", + "parameters": [ + { + "name": "hero_id", + "in": "path", + "required": True, + "schema": {"type": "integer", "title": "Hero Id"}, + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + }, + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "Hero": { + "properties": { + "id": IsDict( + { + "anyOf": [{"type": "integer"}, {"type": "null"}], + "title": "Id", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "integer", + "title": "Id", + } + ), + "name": {"type": "string", "title": "Name"}, + "age": IsDict( + { + "anyOf": [{"type": "integer"}, {"type": "null"}], + "title": "Age", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "integer", + "title": "Age", + } + ), + "secret_name": {"type": "string", "title": "Secret Name"}, + }, + "type": "object", + "required": ["name", "secret_name"], + "title": "Hero", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } + ) diff --git a/tests/test_tutorial/test_sql_databases/test_tutorial002.py b/tests/test_tutorial/test_sql_databases/test_tutorial002.py new file mode 100644 index 000000000..68c1966f5 --- /dev/null +++ b/tests/test_tutorial/test_sql_databases/test_tutorial002.py @@ -0,0 +1,481 @@ +import importlib +import warnings + +import pytest +from dirty_equals import IsDict, IsInt +from fastapi.testclient import TestClient +from inline_snapshot import snapshot +from sqlalchemy import StaticPool +from sqlmodel import SQLModel, create_engine +from sqlmodel.main import default_registry + +from tests.utils import needs_py39, needs_py310 + + +def clear_sqlmodel(): + # Clear the tables in the metadata for the default base model + SQLModel.metadata.clear() + # Clear the Models associated with the registry, to avoid warnings + default_registry.dispose() + + +@pytest.fixture( + name="client", + params=[ + "tutorial002", + pytest.param("tutorial002_py39", marks=needs_py39), + pytest.param("tutorial002_py310", marks=needs_py310), + "tutorial002_an", + pytest.param("tutorial002_an_py39", marks=needs_py39), + pytest.param("tutorial002_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + clear_sqlmodel() + # TODO: remove when updating SQL tutorial to use new lifespan API + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + mod = importlib.import_module(f"docs_src.sql_databases.{request.param}") + clear_sqlmodel() + importlib.reload(mod) + mod.sqlite_url = "sqlite://" + mod.engine = create_engine( + mod.sqlite_url, connect_args={"check_same_thread": False}, poolclass=StaticPool + ) + + with TestClient(mod.app) as c: + yield c + + +def test_crud_app(client: TestClient): + # TODO: this warns that SQLModel.from_orm is deprecated in Pydantic v1, refactor + # this if using obj.model_validate becomes independent of Pydantic v2 + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + # No heroes before creating + response = client.get("heroes/") + assert response.status_code == 200, response.text + assert response.json() == [] + + # Create a hero + response = client.post( + "/heroes/", + json={ + "id": 9000, + "name": "Dead Pond", + "age": 30, + "secret_name": "Dive Wilson", + }, + ) + assert response.status_code == 200, response.text + assert response.json() == snapshot( + {"age": 30, "id": IsInt(), "name": "Dead Pond"} + ) + assert ( + response.json()["id"] != 9000 + ), "The ID should be generated by the database" + + # Read a hero + hero_id = response.json()["id"] + response = client.get(f"/heroes/{hero_id}") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + {"name": "Dead Pond", "age": 30, "id": IsInt()} + ) + + # Read all heroes + # Create more heroes first + response = client.post( + "/heroes/", + json={"name": "Spider-Boy", "age": 18, "secret_name": "Pedro Parqueador"}, + ) + assert response.status_code == 200, response.text + response = client.post( + "/heroes/", json={"name": "Rusty-Man", "secret_name": "Tommy Sharp"} + ) + assert response.status_code == 200, response.text + + response = client.get("/heroes/") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + [ + {"name": "Dead Pond", "age": 30, "id": IsInt()}, + {"name": "Spider-Boy", "age": 18, "id": IsInt()}, + {"name": "Rusty-Man", "age": None, "id": IsInt()}, + ] + ) + + response = client.get("/heroes/?offset=1&limit=1") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + [{"name": "Spider-Boy", "age": 18, "id": IsInt()}] + ) + + # Update a hero + response = client.patch( + f"/heroes/{hero_id}", json={"name": "Dog Pond", "age": None} + ) + assert response.status_code == 200, response.text + assert response.json() == snapshot( + {"name": "Dog Pond", "age": None, "id": hero_id} + ) + + # Get updated hero + response = client.get(f"/heroes/{hero_id}") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + {"name": "Dog Pond", "age": None, "id": hero_id} + ) + + # Delete a hero + response = client.delete(f"/heroes/{hero_id}") + assert response.status_code == 200, response.text + assert response.json() == snapshot({"ok": True}) + + # The hero is no longer found + response = client.get(f"/heroes/{hero_id}") + assert response.status_code == 404, response.text + + # Delete a hero that does not exist + response = client.delete(f"/heroes/{hero_id}") + assert response.status_code == 404, response.text + assert response.json() == snapshot({"detail": "Hero not found"}) + + # Update a hero that does not exist + response = client.patch(f"/heroes/{hero_id}", json={"name": "Dog Pond"}) + assert response.status_code == 404, response.text + assert response.json() == snapshot({"detail": "Hero not found"}) + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/heroes/": { + "post": { + "summary": "Create Hero", + "operationId": "create_hero_heroes__post", + "requestBody": { + "required": True, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HeroCreate" + } + } + }, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HeroPublic" + } + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + "get": { + "summary": "Read Heroes", + "operationId": "read_heroes_heroes__get", + "parameters": [ + { + "name": "offset", + "in": "query", + "required": False, + "schema": { + "type": "integer", + "default": 0, + "title": "Offset", + }, + }, + { + "name": "limit", + "in": "query", + "required": False, + "schema": { + "type": "integer", + "maximum": 100, + "default": 100, + "title": "Limit", + }, + }, + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/HeroPublic" + }, + "title": "Response Read Heroes Heroes Get", + } + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + }, + "/heroes/{hero_id}": { + "get": { + "summary": "Read Hero", + "operationId": "read_hero_heroes__hero_id__get", + "parameters": [ + { + "name": "hero_id", + "in": "path", + "required": True, + "schema": {"type": "integer", "title": "Hero Id"}, + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HeroPublic" + } + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + "patch": { + "summary": "Update Hero", + "operationId": "update_hero_heroes__hero_id__patch", + "parameters": [ + { + "name": "hero_id", + "in": "path", + "required": True, + "schema": {"type": "integer", "title": "Hero Id"}, + } + ], + "requestBody": { + "required": True, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HeroUpdate" + } + } + }, + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HeroPublic" + } + } + }, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + "delete": { + "summary": "Delete Hero", + "operationId": "delete_hero_heroes__hero_id__delete", + "parameters": [ + { + "name": "hero_id", + "in": "path", + "required": True, + "schema": {"type": "integer", "title": "Hero Id"}, + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + }, + }, + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "HeroCreate": { + "properties": { + "name": {"type": "string", "title": "Name"}, + "age": IsDict( + { + "anyOf": [{"type": "integer"}, {"type": "null"}], + "title": "Age", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "integer", + "title": "Age", + } + ), + "secret_name": {"type": "string", "title": "Secret Name"}, + }, + "type": "object", + "required": ["name", "secret_name"], + "title": "HeroCreate", + }, + "HeroPublic": { + "properties": { + "name": {"type": "string", "title": "Name"}, + "age": IsDict( + { + "anyOf": [{"type": "integer"}, {"type": "null"}], + "title": "Age", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "integer", + "title": "Age", + } + ), + "id": {"type": "integer", "title": "Id"}, + }, + "type": "object", + "required": ["name", "id"], + "title": "HeroPublic", + }, + "HeroUpdate": { + "properties": { + "name": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Name", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "Name", + } + ), + "age": IsDict( + { + "anyOf": [{"type": "integer"}, {"type": "null"}], + "title": "Age", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "integer", + "title": "Age", + } + ), + "secret_name": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Secret Name", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "Secret Name", + } + ), + }, + "type": "object", + "title": "HeroUpdate", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } + ) diff --git a/tests/test_tutorial/test_testing/test_main_b.py b/tests/test_tutorial/test_testing/test_main_b.py index fc1a832f9..aa7f969c6 100644 --- a/tests/test_tutorial/test_testing/test_main_b.py +++ b/tests/test_tutorial/test_testing/test_main_b.py @@ -1,10 +1,31 @@ -from docs_src.app_testing.app_b import test_main +import importlib +from types import ModuleType +import pytest -def test_app(): +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="test_module", + params=[ + "app_b.test_main", + pytest.param("app_b_py310.test_main", marks=needs_py310), + "app_b_an.test_main", + pytest.param("app_b_an_py39.test_main", marks=needs_py39), + pytest.param("app_b_an_py310.test_main", marks=needs_py310), + ], +) +def get_test_module(request: pytest.FixtureRequest) -> ModuleType: + mod: ModuleType = importlib.import_module(f"docs_src.app_testing.{request.param}") + return mod + + +def test_app(test_module: ModuleType): + test_main = test_module test_main.test_create_existing_item() test_main.test_create_item() test_main.test_create_item_bad_token() - test_main.test_read_inexistent_item() + test_main.test_read_nonexistent_item() test_main.test_read_item() test_main.test_read_item_bad_token() diff --git a/tests/test_tutorial/test_testing/test_main_b_an.py b/tests/test_tutorial/test_testing/test_main_b_an.py deleted file mode 100644 index b64c5f710..000000000 --- a/tests/test_tutorial/test_testing/test_main_b_an.py +++ /dev/null @@ -1,10 +0,0 @@ -from docs_src.app_testing.app_b_an import test_main - - -def test_app(): - test_main.test_create_existing_item() - test_main.test_create_item() - test_main.test_create_item_bad_token() - test_main.test_read_inexistent_item() - test_main.test_read_item() - test_main.test_read_item_bad_token() diff --git a/tests/test_tutorial/test_testing/test_main_b_an_py310.py b/tests/test_tutorial/test_testing/test_main_b_an_py310.py deleted file mode 100644 index 194700b6d..000000000 --- a/tests/test_tutorial/test_testing/test_main_b_an_py310.py +++ /dev/null @@ -1,13 +0,0 @@ -from ...utils import needs_py310 - - -@needs_py310 -def test_app(): - from docs_src.app_testing.app_b_an_py310 import test_main - - test_main.test_create_existing_item() - test_main.test_create_item() - test_main.test_create_item_bad_token() - test_main.test_read_inexistent_item() - test_main.test_read_item() - test_main.test_read_item_bad_token() diff --git a/tests/test_tutorial/test_testing/test_main_b_an_py39.py b/tests/test_tutorial/test_testing/test_main_b_an_py39.py deleted file mode 100644 index 2f8a13623..000000000 --- a/tests/test_tutorial/test_testing/test_main_b_an_py39.py +++ /dev/null @@ -1,13 +0,0 @@ -from ...utils import needs_py39 - - -@needs_py39 -def test_app(): - from docs_src.app_testing.app_b_an_py39 import test_main - - test_main.test_create_existing_item() - test_main.test_create_item() - test_main.test_create_item_bad_token() - test_main.test_read_inexistent_item() - test_main.test_read_item() - test_main.test_read_item_bad_token() diff --git a/tests/test_tutorial/test_testing/test_main_b_py310.py b/tests/test_tutorial/test_testing/test_main_b_py310.py deleted file mode 100644 index a504ed234..000000000 --- a/tests/test_tutorial/test_testing/test_main_b_py310.py +++ /dev/null @@ -1,13 +0,0 @@ -from ...utils import needs_py310 - - -@needs_py310 -def test_app(): - from docs_src.app_testing.app_b_py310 import test_main - - test_main.test_create_existing_item() - test_main.test_create_item() - test_main.test_create_item_bad_token() - test_main.test_read_inexistent_item() - test_main.test_read_item() - test_main.test_read_item_bad_token() diff --git a/tests/test_tutorial/test_testing_dependencies/test_tutorial001.py b/tests/test_tutorial/test_testing_dependencies/test_tutorial001.py index af26307f5..00ee6ab1e 100644 --- a/tests/test_tutorial/test_testing_dependencies/test_tutorial001.py +++ b/tests/test_tutorial/test_testing_dependencies/test_tutorial001.py @@ -1,25 +1,48 @@ -from docs_src.dependency_testing.tutorial001 import ( - app, - client, - test_override_in_items, - test_override_in_items_with_params, - test_override_in_items_with_q, +import importlib +from types import ModuleType + +import pytest + +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="test_module", + params=[ + "tutorial001", + pytest.param("tutorial001_py310", marks=needs_py310), + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + pytest.param("tutorial001_an_py310", marks=needs_py310), + ], ) +def get_test_module(request: pytest.FixtureRequest) -> ModuleType: + mod: ModuleType = importlib.import_module( + f"docs_src.dependency_testing.{request.param}" + ) + return mod -def test_override_in_items_run(): +def test_override_in_items_run(test_module: ModuleType): + test_override_in_items = test_module.test_override_in_items + test_override_in_items() -def test_override_in_items_with_q_run(): +def test_override_in_items_with_q_run(test_module: ModuleType): + test_override_in_items_with_q = test_module.test_override_in_items_with_q + test_override_in_items_with_q() -def test_override_in_items_with_params_run(): +def test_override_in_items_with_params_run(test_module: ModuleType): + test_override_in_items_with_params = test_module.test_override_in_items_with_params + test_override_in_items_with_params() -def test_override_in_users(): +def test_override_in_users(test_module: ModuleType): + client = test_module.client response = client.get("/users/") assert response.status_code == 200, response.text assert response.json() == { @@ -28,7 +51,8 @@ def test_override_in_users(): } -def test_override_in_users_with_q(): +def test_override_in_users_with_q(test_module: ModuleType): + client = test_module.client response = client.get("/users/?q=foo") assert response.status_code == 200, response.text assert response.json() == { @@ -37,7 +61,8 @@ def test_override_in_users_with_q(): } -def test_override_in_users_with_params(): +def test_override_in_users_with_params(test_module: ModuleType): + client = test_module.client response = client.get("/users/?q=foo&skip=100&limit=200") assert response.status_code == 200, response.text assert response.json() == { @@ -46,7 +71,9 @@ def test_override_in_users_with_params(): } -def test_normal_app(): +def test_normal_app(test_module: ModuleType): + app = test_module.app + client = test_module.client app.dependency_overrides = None response = client.get("/items/?q=foo&skip=100&limit=200") assert response.status_code == 200, response.text diff --git a/tests/test_tutorial/test_testing_dependencies/test_tutorial001_an.py b/tests/test_tutorial/test_testing_dependencies/test_tutorial001_an.py deleted file mode 100644 index fc1f9149a..000000000 --- a/tests/test_tutorial/test_testing_dependencies/test_tutorial001_an.py +++ /dev/null @@ -1,56 +0,0 @@ -from docs_src.dependency_testing.tutorial001_an import ( - app, - client, - test_override_in_items, - test_override_in_items_with_params, - test_override_in_items_with_q, -) - - -def test_override_in_items_run(): - test_override_in_items() - - -def test_override_in_items_with_q_run(): - test_override_in_items_with_q() - - -def test_override_in_items_with_params_run(): - test_override_in_items_with_params() - - -def test_override_in_users(): - response = client.get("/users/") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": None, "skip": 5, "limit": 10}, - } - - -def test_override_in_users_with_q(): - response = client.get("/users/?q=foo") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": "foo", "skip": 5, "limit": 10}, - } - - -def test_override_in_users_with_params(): - response = client.get("/users/?q=foo&skip=100&limit=200") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": "foo", "skip": 5, "limit": 10}, - } - - -def test_normal_app(): - app.dependency_overrides = None - response = client.get("/items/?q=foo&skip=100&limit=200") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Items!", - "params": {"q": "foo", "skip": 100, "limit": 200}, - } diff --git a/tests/test_tutorial/test_testing_dependencies/test_tutorial001_an_py310.py b/tests/test_tutorial/test_testing_dependencies/test_tutorial001_an_py310.py deleted file mode 100644 index a3d27f47f..000000000 --- a/tests/test_tutorial/test_testing_dependencies/test_tutorial001_an_py310.py +++ /dev/null @@ -1,75 +0,0 @@ -from ...utils import needs_py310 - - -@needs_py310 -def test_override_in_items_run(): - from docs_src.dependency_testing.tutorial001_an_py310 import test_override_in_items - - test_override_in_items() - - -@needs_py310 -def test_override_in_items_with_q_run(): - from docs_src.dependency_testing.tutorial001_an_py310 import ( - test_override_in_items_with_q, - ) - - test_override_in_items_with_q() - - -@needs_py310 -def test_override_in_items_with_params_run(): - from docs_src.dependency_testing.tutorial001_an_py310 import ( - test_override_in_items_with_params, - ) - - test_override_in_items_with_params() - - -@needs_py310 -def test_override_in_users(): - from docs_src.dependency_testing.tutorial001_an_py310 import client - - response = client.get("/users/") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": None, "skip": 5, "limit": 10}, - } - - -@needs_py310 -def test_override_in_users_with_q(): - from docs_src.dependency_testing.tutorial001_an_py310 import client - - response = client.get("/users/?q=foo") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": "foo", "skip": 5, "limit": 10}, - } - - -@needs_py310 -def test_override_in_users_with_params(): - from docs_src.dependency_testing.tutorial001_an_py310 import client - - response = client.get("/users/?q=foo&skip=100&limit=200") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": "foo", "skip": 5, "limit": 10}, - } - - -@needs_py310 -def test_normal_app(): - from docs_src.dependency_testing.tutorial001_an_py310 import app, client - - app.dependency_overrides = None - response = client.get("/items/?q=foo&skip=100&limit=200") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Items!", - "params": {"q": "foo", "skip": 100, "limit": 200}, - } diff --git a/tests/test_tutorial/test_testing_dependencies/test_tutorial001_an_py39.py b/tests/test_tutorial/test_testing_dependencies/test_tutorial001_an_py39.py deleted file mode 100644 index f03ed5e07..000000000 --- a/tests/test_tutorial/test_testing_dependencies/test_tutorial001_an_py39.py +++ /dev/null @@ -1,75 +0,0 @@ -from ...utils import needs_py39 - - -@needs_py39 -def test_override_in_items_run(): - from docs_src.dependency_testing.tutorial001_an_py39 import test_override_in_items - - test_override_in_items() - - -@needs_py39 -def test_override_in_items_with_q_run(): - from docs_src.dependency_testing.tutorial001_an_py39 import ( - test_override_in_items_with_q, - ) - - test_override_in_items_with_q() - - -@needs_py39 -def test_override_in_items_with_params_run(): - from docs_src.dependency_testing.tutorial001_an_py39 import ( - test_override_in_items_with_params, - ) - - test_override_in_items_with_params() - - -@needs_py39 -def test_override_in_users(): - from docs_src.dependency_testing.tutorial001_an_py39 import client - - response = client.get("/users/") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": None, "skip": 5, "limit": 10}, - } - - -@needs_py39 -def test_override_in_users_with_q(): - from docs_src.dependency_testing.tutorial001_an_py39 import client - - response = client.get("/users/?q=foo") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": "foo", "skip": 5, "limit": 10}, - } - - -@needs_py39 -def test_override_in_users_with_params(): - from docs_src.dependency_testing.tutorial001_an_py39 import client - - response = client.get("/users/?q=foo&skip=100&limit=200") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": "foo", "skip": 5, "limit": 10}, - } - - -@needs_py39 -def test_normal_app(): - from docs_src.dependency_testing.tutorial001_an_py39 import app, client - - app.dependency_overrides = None - response = client.get("/items/?q=foo&skip=100&limit=200") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Items!", - "params": {"q": "foo", "skip": 100, "limit": 200}, - } diff --git a/tests/test_tutorial/test_testing_dependencies/test_tutorial001_py310.py b/tests/test_tutorial/test_testing_dependencies/test_tutorial001_py310.py deleted file mode 100644 index 776b916ff..000000000 --- a/tests/test_tutorial/test_testing_dependencies/test_tutorial001_py310.py +++ /dev/null @@ -1,75 +0,0 @@ -from ...utils import needs_py310 - - -@needs_py310 -def test_override_in_items_run(): - from docs_src.dependency_testing.tutorial001_py310 import test_override_in_items - - test_override_in_items() - - -@needs_py310 -def test_override_in_items_with_q_run(): - from docs_src.dependency_testing.tutorial001_py310 import ( - test_override_in_items_with_q, - ) - - test_override_in_items_with_q() - - -@needs_py310 -def test_override_in_items_with_params_run(): - from docs_src.dependency_testing.tutorial001_py310 import ( - test_override_in_items_with_params, - ) - - test_override_in_items_with_params() - - -@needs_py310 -def test_override_in_users(): - from docs_src.dependency_testing.tutorial001_py310 import client - - response = client.get("/users/") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": None, "skip": 5, "limit": 10}, - } - - -@needs_py310 -def test_override_in_users_with_q(): - from docs_src.dependency_testing.tutorial001_py310 import client - - response = client.get("/users/?q=foo") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": "foo", "skip": 5, "limit": 10}, - } - - -@needs_py310 -def test_override_in_users_with_params(): - from docs_src.dependency_testing.tutorial001_py310 import client - - response = client.get("/users/?q=foo&skip=100&limit=200") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": "foo", "skip": 5, "limit": 10}, - } - - -@needs_py310 -def test_normal_app(): - from docs_src.dependency_testing.tutorial001_py310 import app, client - - app.dependency_overrides = None - response = client.get("/items/?q=foo&skip=100&limit=200") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Items!", - "params": {"q": "foo", "skip": 100, "limit": 200}, - } diff --git a/tests/test_tutorial/test_websockets/test_tutorial002.py b/tests/test_tutorial/test_websockets/test_tutorial002.py index bb5ccbf8e..51aa5752a 100644 --- a/tests/test_tutorial/test_websockets/test_tutorial002.py +++ b/tests/test_tutorial/test_websockets/test_tutorial002.py @@ -1,18 +1,37 @@ +import importlib + import pytest +from fastapi import FastAPI from fastapi.testclient import TestClient from fastapi.websockets import WebSocketDisconnect -from docs_src.websockets.tutorial002 import app +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="app", + params=[ + "tutorial002", + pytest.param("tutorial002_py310", marks=needs_py310), + "tutorial002_an", + pytest.param("tutorial002_an_py39", marks=needs_py39), + pytest.param("tutorial002_an_py310", marks=needs_py310), + ], +) +def get_app(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.websockets.{request.param}") + + return mod.app -def test_main(): +def test_main(app: FastAPI): client = TestClient(app) response = client.get("/") assert response.status_code == 200, response.text assert b"" in response.content -def test_websocket_with_cookie(): +def test_websocket_with_cookie(app: FastAPI): client = TestClient(app, cookies={"session": "fakesession"}) with pytest.raises(WebSocketDisconnect): with client.websocket_connect("/items/foo/ws") as websocket: @@ -30,7 +49,7 @@ def test_websocket_with_cookie(): assert data == f"Message text was: {message}, for item ID: foo" -def test_websocket_with_header(): +def test_websocket_with_header(app: FastAPI): client = TestClient(app) with pytest.raises(WebSocketDisconnect): with client.websocket_connect("/items/bar/ws?token=some-token") as websocket: @@ -48,7 +67,7 @@ def test_websocket_with_header(): assert data == f"Message text was: {message}, for item ID: bar" -def test_websocket_with_header_and_query(): +def test_websocket_with_header_and_query(app: FastAPI): client = TestClient(app) with pytest.raises(WebSocketDisconnect): with client.websocket_connect("/items/2/ws?q=3&token=some-token") as websocket: @@ -70,7 +89,7 @@ def test_websocket_with_header_and_query(): assert data == f"Message text was: {message}, for item ID: 2" -def test_websocket_no_credentials(): +def test_websocket_no_credentials(app: FastAPI): client = TestClient(app) with pytest.raises(WebSocketDisconnect): with client.websocket_connect("/items/foo/ws"): @@ -79,7 +98,7 @@ def test_websocket_no_credentials(): ) # pragma: no cover -def test_websocket_invalid_data(): +def test_websocket_invalid_data(app: FastAPI): client = TestClient(app) with pytest.raises(WebSocketDisconnect): with client.websocket_connect("/items/foo/ws?q=bar&token=some-token"): diff --git a/tests/test_tutorial/test_websockets/test_tutorial002_an.py b/tests/test_tutorial/test_websockets/test_tutorial002_an.py deleted file mode 100644 index ec78d70d3..000000000 --- a/tests/test_tutorial/test_websockets/test_tutorial002_an.py +++ /dev/null @@ -1,88 +0,0 @@ -import pytest -from fastapi.testclient import TestClient -from fastapi.websockets import WebSocketDisconnect - -from docs_src.websockets.tutorial002_an import app - - -def test_main(): - client = TestClient(app) - response = client.get("/") - assert response.status_code == 200, response.text - assert b"" in response.content - - -def test_websocket_with_cookie(): - client = TestClient(app, cookies={"session": "fakesession"}) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: fakesession" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: foo" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: fakesession" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: foo" - - -def test_websocket_with_header(): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/bar/ws?token=some-token") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: bar" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: bar" - - -def test_websocket_with_header_and_query(): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/2/ws?q=3&token=some-token") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == "Query parameter q is: 3" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: 2" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == "Query parameter q is: 3" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: 2" - - -def test_websocket_no_credentials(): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws"): - pytest.fail( - "did not raise WebSocketDisconnect on __enter__" - ) # pragma: no cover - - -def test_websocket_invalid_data(): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws?q=bar&token=some-token"): - pytest.fail( - "did not raise WebSocketDisconnect on __enter__" - ) # pragma: no cover diff --git a/tests/test_tutorial/test_websockets/test_tutorial002_an_py310.py b/tests/test_tutorial/test_websockets/test_tutorial002_an_py310.py deleted file mode 100644 index 23b4bcb78..000000000 --- a/tests/test_tutorial/test_websockets/test_tutorial002_an_py310.py +++ /dev/null @@ -1,102 +0,0 @@ -import pytest -from fastapi import FastAPI -from fastapi.testclient import TestClient -from fastapi.websockets import WebSocketDisconnect - -from ...utils import needs_py310 - - -@pytest.fixture(name="app") -def get_app(): - from docs_src.websockets.tutorial002_an_py310 import app - - return app - - -@needs_py310 -def test_main(app: FastAPI): - client = TestClient(app) - response = client.get("/") - assert response.status_code == 200, response.text - assert b"" in response.content - - -@needs_py310 -def test_websocket_with_cookie(app: FastAPI): - client = TestClient(app, cookies={"session": "fakesession"}) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: fakesession" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: foo" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: fakesession" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: foo" - - -@needs_py310 -def test_websocket_with_header(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/bar/ws?token=some-token") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: bar" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: bar" - - -@needs_py310 -def test_websocket_with_header_and_query(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/2/ws?q=3&token=some-token") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == "Query parameter q is: 3" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: 2" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == "Query parameter q is: 3" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: 2" - - -@needs_py310 -def test_websocket_no_credentials(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws"): - pytest.fail( - "did not raise WebSocketDisconnect on __enter__" - ) # pragma: no cover - - -@needs_py310 -def test_websocket_invalid_data(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws?q=bar&token=some-token"): - pytest.fail( - "did not raise WebSocketDisconnect on __enter__" - ) # pragma: no cover diff --git a/tests/test_tutorial/test_websockets/test_tutorial002_an_py39.py b/tests/test_tutorial/test_websockets/test_tutorial002_an_py39.py deleted file mode 100644 index 2d77f05b3..000000000 --- a/tests/test_tutorial/test_websockets/test_tutorial002_an_py39.py +++ /dev/null @@ -1,102 +0,0 @@ -import pytest -from fastapi import FastAPI -from fastapi.testclient import TestClient -from fastapi.websockets import WebSocketDisconnect - -from ...utils import needs_py39 - - -@pytest.fixture(name="app") -def get_app(): - from docs_src.websockets.tutorial002_an_py39 import app - - return app - - -@needs_py39 -def test_main(app: FastAPI): - client = TestClient(app) - response = client.get("/") - assert response.status_code == 200, response.text - assert b"" in response.content - - -@needs_py39 -def test_websocket_with_cookie(app: FastAPI): - client = TestClient(app, cookies={"session": "fakesession"}) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: fakesession" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: foo" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: fakesession" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: foo" - - -@needs_py39 -def test_websocket_with_header(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/bar/ws?token=some-token") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: bar" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: bar" - - -@needs_py39 -def test_websocket_with_header_and_query(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/2/ws?q=3&token=some-token") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == "Query parameter q is: 3" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: 2" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == "Query parameter q is: 3" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: 2" - - -@needs_py39 -def test_websocket_no_credentials(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws"): - pytest.fail( - "did not raise WebSocketDisconnect on __enter__" - ) # pragma: no cover - - -@needs_py39 -def test_websocket_invalid_data(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws?q=bar&token=some-token"): - pytest.fail( - "did not raise WebSocketDisconnect on __enter__" - ) # pragma: no cover diff --git a/tests/test_tutorial/test_websockets/test_tutorial002_py310.py b/tests/test_tutorial/test_websockets/test_tutorial002_py310.py deleted file mode 100644 index 03bc27bdf..000000000 --- a/tests/test_tutorial/test_websockets/test_tutorial002_py310.py +++ /dev/null @@ -1,102 +0,0 @@ -import pytest -from fastapi import FastAPI -from fastapi.testclient import TestClient -from fastapi.websockets import WebSocketDisconnect - -from ...utils import needs_py310 - - -@pytest.fixture(name="app") -def get_app(): - from docs_src.websockets.tutorial002_py310 import app - - return app - - -@needs_py310 -def test_main(app: FastAPI): - client = TestClient(app) - response = client.get("/") - assert response.status_code == 200, response.text - assert b"" in response.content - - -@needs_py310 -def test_websocket_with_cookie(app: FastAPI): - client = TestClient(app, cookies={"session": "fakesession"}) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: fakesession" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: foo" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: fakesession" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: foo" - - -@needs_py310 -def test_websocket_with_header(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/bar/ws?token=some-token") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: bar" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: bar" - - -@needs_py310 -def test_websocket_with_header_and_query(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/2/ws?q=3&token=some-token") as websocket: - message = "Message one" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == "Query parameter q is: 3" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: 2" - message = "Message two" - websocket.send_text(message) - data = websocket.receive_text() - assert data == "Session cookie or query token value is: some-token" - data = websocket.receive_text() - assert data == "Query parameter q is: 3" - data = websocket.receive_text() - assert data == f"Message text was: {message}, for item ID: 2" - - -@needs_py310 -def test_websocket_no_credentials(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws"): - pytest.fail( - "did not raise WebSocketDisconnect on __enter__" - ) # pragma: no cover - - -@needs_py310 -def test_websocket_invalid_data(app: FastAPI): - client = TestClient(app) - with pytest.raises(WebSocketDisconnect): - with client.websocket_connect("/items/foo/ws?q=bar&token=some-token"): - pytest.fail( - "did not raise WebSocketDisconnect on __enter__" - ) # pragma: no cover