{"prefix": "\"\"\"Check release-notes.md and add today's date to the latest release header if missing.\"\"\"\n\nimport re\nimport sys\nfrom datetime import date\n\nRELEASE_NOTES_FILE = \"docs/en/docs/release-notes.md\"\nRELEASE_HEADER_PATTERN = re.compile(r\"^## (\\d+\\.\\d+\\.\\d+)\\s*(\\(.*\\))?\\s*$\")\n\n\ndef main() -> None:\n with open(RELEASE_NOTES_FILE) as f:\n lines = f.readlines()\n\n for i, line in enumerate(lines):\n match = RELEASE_HEADER_PATTERN.match(line)\n if not match:\n continue\n\n version = ", "suffix": "es[i] = f\"## {version} ({today})\\n\"\n print(f\"Added date: {version} ({today})\")\n\n with open(RELEASE_NOTES_FILE, \"w\") as f:\n f.writelines(lines)\n sys.exit(0)\n\n print(\"No release header found\")\n sys.exit(1)\n\n\nif __name__ ", "middle": "match.group(1)\n date_part = match.group(2)\n\n if date_part:\n print(f\"Latest release {version} already has a date: {date_part}\")\n sys.exit(0)\n\n today = date.today().isoformat()\n lin", "meta": {"filepath": "scripts/add_latest_release_date.py", "language": "python", "file_size": 1023, "cut_index": 512, "middle_length": 229}} {"prefix": "ort BaseModel, SecretStr\nfrom pydantic_settings import BaseSettings\n\n\nclass Settings(BaseSettings):\n github_repository: str\n github_token: SecretStr\n deploy_url: str | None = None\n commit_sha: str\n run_id: int\n state: Literal[\"pending\", \"success\", \"error\"] = \"pending\"\n\n\nclass LinkData(BaseModel):\n previous_link: str\n preview_link: str\n en_link: str | None = None\n\n\ndef main() -> None:\n logging.basicConfig(level=logging.INFO)\n settings = Settings()\n\n logging.info(f\"Using co", "suffix": ".sha == settings.commit_sha), None\n )\n if not use_pr:\n logging.error(f\"No PR found for hash: {settings.commit_sha}\")\n return\n commits = list(use_pr.get_commits())\n current_commit = [c for c in commits if c.sha == settings.commit_s", "middle": "nfig: {settings.model_dump_json()}\")\n g = Github(auth=Auth.Token(settings.github_token.get_secret_value()))\n repo = g.get_repo(settings.github_repository)\n use_pr = next(\n (pr for pr in repo.get_pulls() if pr.head", "meta": {"filepath": "scripts/deploy_docs_status.py", "language": "python", "file_size": 4552, "cut_index": 614, "middle_length": 229}} {"prefix": "ment.md\",\n \"contributing.md\",\n \"translations.md\",\n)\n\ndocs_path = Path(\"docs\")\nen_docs_path = Path(\"docs/en\")\nen_config_path: Path = en_docs_path / mkdocs_name\nsite_path = Path(\"site\").absolute()\nzensical_src_path = Path(\"site_zensical_src\").absolute()\n\nheader_pattern = re.compile(r\"^(#{1,6}) (.+?)(?:\\s*\\{\\s*(#.*)\\s*\\})?\\s*$\")\nheader_with_permalink_pattern = re.compile(r\"^(#{1,6}) (.+?)(\\s*\\{\\s*#.*\\s*\\})\\s*$\")\ncode_block3_pattern = re.compile(r\"^\\s*```\")\ncode_block4_pattern = re.compile(r\"^\\s*````\")\n\n\n", "suffix": "md_link_pattern.sub(r\"\\1\", text)\n\n\nclass VisibleTextExtractor(HTMLParser):\n \"\"\"Extract visible text from a string with HTML tags.\"\"\"\n\n def __init__(self):\n super().__init__()\n self.text_parts = []\n\n def handle_data(self, data):\n ", "middle": "# Pattern to match markdown links: [text](url) → text\nmd_link_pattern = re.compile(r\"\\[([^\\]]+)\\]\\([^)]+\\)\")\n\n\ndef strip_markdown_links(text: str) -> str:\n \"\"\"Replace markdown links with just their visible text.\"\"\"\n return ", "meta": {"filepath": "scripts/docs.py", "language": "python", "file_size": 30330, "cut_index": 1331, "middle_length": 229}} {"prefix": " BaseModel, SecretStr\nfrom pydantic_settings import BaseSettings\n\ngithub_graphql_url = \"https://api.github.com/graphql\"\n\n\nsponsors_query = \"\"\"\nquery Q($after: String) {\n user(login: \"tiangolo\") {\n sponsorshipsAsMaintainer(first: 100, after: $after) {\n edges {\n cursor\n node {\n sponsorEntity {\n ... on Organization {\n login\n avatarUrl\n url\n }\n ... on User {\n login\n avatarUrl\n ", "suffix": "tr\n\n\nclass Tier(BaseModel):\n name: str\n monthlyPriceInDollars: float\n\n\nclass SponsorshipAsMaintainerNode(BaseModel):\n sponsorEntity: SponsorEntity\n tier: Tier\n\n\nclass SponsorshipAsMaintainerEdge(BaseModel):\n cursor: str\n node: Sponsorship", "middle": " url\n }\n }\n tier {\n name\n monthlyPriceInDollars\n }\n }\n }\n }\n }\n}\n\"\"\"\n\n\nclass SponsorEntity(BaseModel):\n login: str\n avatarUrl: str\n url: s", "meta": {"filepath": "scripts/sponsors.py", "language": "python", "file_size": 6247, "cut_index": 716, "middle_length": 229}} {"prefix": "ocess\nimport time\n\nimport httpx\nfrom playwright.sync_api import Playwright, sync_playwright\n\n\n# Run playwright codegen to generate the code below, copy paste the sections in run()\ndef run(playwright: Playwright) -> None:\n browser = playwright.chromium.launch(headless=False)\n # Update the viewport manually\n context = browser.new_context(viewport={\"width\": 960, \"height\": 1080})\n browser = playwright.chromium.launch(headless=False)\n context = browser.new_context()\n page = context.new_page()\n ", "suffix": " # Manually add the screenshot\n page.screenshot(path=\"docs/en/docs/img/tutorial/query-param-models/image01.png\")\n\n # ---------------------\n context.close()\n browser.close()\n\n\nprocess = subprocess.Popen(\n [\"fastapi\", \"run\", \"docs_src/query_p", "middle": " page.goto(\"http://localhost:8000/docs\")\n page.get_by_role(\"button\", name=\"GET /items/ Read Items\").click()\n page.get_by_role(\"button\", name=\"Try it out\").click()\n page.get_by_role(\"heading\", name=\"Servers\").click()\n ", "meta": {"filepath": "scripts/playwright/query_param_models/image01.py", "language": "python", "file_size": 1322, "cut_index": 524, "middle_length": 229}} {"prefix": "aywright\n\n\n# Run playwright codegen to generate the code below, copy paste the sections in run()\ndef run(playwright: Playwright) -> None:\n browser = playwright.chromium.launch(headless=False)\n # Update the viewport manually\n context = browser.new_context(viewport={\"width\": 960, \"height\": 1080})\n page = context.new_page()\n page.goto(\"http://localhost:8000/docs\")\n page.get_by_role(\"button\", name=\"Item\", exact=True).click()\n page.set_viewport_size({\"width\": 960, \"height\": 700})\n # Manua", "suffix": "path=\"docs/en/docs/img/tutorial/separate-openapi-schemas/image05.png\"\n )\n\n # ---------------------\n context.close()\n browser.close()\n\n\nprocess = subprocess.Popen(\n [\"uvicorn\", \"docs_src.separate_openapi_schemas.tutorial002:app\"]\n)\ntry:\n w", "middle": "lly add the screenshot\n page.screenshot(\n ", "meta": {"filepath": "scripts/playwright/separate_openapi_schemas/image05.py", "language": "python", "file_size": 984, "cut_index": 582, "middle_length": 52}} {"prefix": "\nimport pytest\nfrom typer.testing import CliRunner\n\nfrom scripts.translation_fixer import cli\n\ndata_path = Path(\n \"scripts/tests/test_translation_fixer/test_header_permalinks/data\"\n).absolute()\n\n\n@pytest.mark.parametrize(\n \"copy_test_files\",\n [(f\"{data_path}/en_doc.md\", f\"{data_path}/translated_doc_level_mismatch_1.md\")],\n indirect=True,\n)\ndef test_level_mismatch_1(runner: CliRunner, root_dir: Path, copy_test_files):\n result = runner.invoke(\n cli,\n [\"fix-pages\", \"docs/lang/docs/", "suffix": ").read_text(\"utf-8\")\n\n assert fixed_content == expected_content # Translated doc remains unchanged\n assert \"Error processing docs/lang/docs/doc.md\" in result.output\n assert (\n \"Header levels do not match between document and original docum", "middle": "doc.md\"],\n )\n assert result.exit_code == 1\n\n fixed_content = (root_dir / \"docs\" / \"lang\" / \"docs\" / \"doc.md\").read_text(\"utf-8\")\n expected_content = Path(\n f\"{data_path}/translated_doc_level_mismatch_1.md\"\n ", "meta": {"filepath": "scripts/tests/test_translation_fixer/test_header_permalinks/test_header_level_mismatch.py", "language": "python", "file_size": 1999, "cut_index": 537, "middle_length": 229}} {"prefix": "\nimport pytest\nfrom typer.testing import CliRunner\n\nfrom scripts.translation_fixer import cli\n\ndata_path = Path(\n \"scripts/tests/test_translation_fixer/test_markdown_links/data\"\n).absolute()\n\n\n@pytest.mark.parametrize(\n \"copy_test_files\",\n [(f\"{data_path}/en_doc.md\", f\"{data_path}/translated_doc_number_gt.md\")],\n indirect=True,\n)\ndef test_gt(runner: CliRunner, root_dir: Path, copy_test_files):\n result = runner.invoke(\n cli,\n [\"fix-pages\", \"docs/lang/docs/doc.md\"],\n )\n asse", "suffix": " )\n\n assert fixed_content == expected_content # Translated doc remains unchanged\n assert \"Error processing docs/lang/docs/doc.md\" in result.output\n assert (\n \"Number of markdown links does not match the number \"\n \"in the original ", "middle": "rt result.exit_code == 1, result.output\n\n fixed_content = (root_dir / \"docs\" / \"lang\" / \"docs\" / \"doc.md\").read_text(\"utf-8\")\n expected_content = Path(f\"{data_path}/translated_doc_number_gt.md\").read_text(\n \"utf-8\"\n ", "meta": {"filepath": "scripts/tests/test_translation_fixer/test_markdown_links/test_mkd_links_number_mismatch.py", "language": "python", "file_size": 1911, "cut_index": 537, "middle_length": 229}} {"prefix": "wordRequestForm,\n SecurityScopes,\n)\nfrom jwt.exceptions import InvalidTokenError\nfrom pwdlib import PasswordHash\nfrom pydantic import BaseModel, ValidationError\n\n# to get a string like this run:\n# openssl rand -hex 32\nSECRET_KEY = \"09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7\"\nALGORITHM = \"HS256\"\nACCESS_TOKEN_EXPIRE_MINUTES = 30\n\n\nfake_users_db = {\n \"johndoe\": {\n \"username\": \"johndoe\",\n \"full_name\": \"John Doe\",\n \"email\": \"johndoe@example.com\",\n \"hashed_p", "suffix": " \"email\": \"alicechains@example.com\",\n \"hashed_password\": \"$argon2id$v=19$m=65536,t=3,p=4$g2/AV1zwopqUntPKJavBFw$BwpRGDCyUHLvHICnwijyX8ROGoiUPwNKZ7915MeYfCE\",\n \"disabled\": True,\n },\n}\n\n\nclass Token(BaseModel):\n access_token: str\n ", "middle": "assword\": \"$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w$CYaIb8sB+wtD+Vu/P4uod1+Qof8h+1g7bbDlBID48Rc\",\n \"disabled\": False,\n },\n \"alice\": {\n \"username\": \"alice\",\n \"full_name\": \"Alice Chains\",\n ", "meta": {"filepath": "docs_src/security/tutorial005_py310.py", "language": "python", "file_size": 5418, "cut_index": 716, "middle_length": 229}} {"prefix": " import Body, FastAPI\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\n\nclass Item(BaseModel):\n name: str\n description: str | None = None\n price: float\n tax: float | None = None\n\n\n@app.put(\"/items/{item_id}\")\nasync def update_item(\n *,\n item_id: int,\n item: Item = Body(\n openapi_examples={\n \"normal\": {\n \"summary\": \"A normal example\",\n \"description\": \"A **normal** item works correctly.\",\n \"value\": {\n \"name\"", "suffix": "e with converted data\",\n \"description\": \"FastAPI can convert price `strings` to actual `numbers` automatically\",\n \"value\": {\n \"name\": \"Bar\",\n \"price\": \"35.4\",\n },\n ", "middle": ": \"Foo\",\n \"description\": \"A very nice Item\",\n \"price\": 35.4,\n \"tax\": 3.2,\n },\n },\n \"converted\": {\n \"summary\": \"An exampl", "meta": {"filepath": "docs_src/schema_extra_example/tutorial005_py310.py", "language": "python", "file_size": 1348, "cut_index": 524, "middle_length": 229}} {"prefix": "m collections.abc import AsyncIterable, Iterable\n\nfrom fastapi import FastAPI\nfrom fastapi.sse import EventSourceResponse\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\n\nclass Item(BaseModel):\n name: str\n description: str | None\n\n\nitems = [\n Item(name=\"Plumbus\", description=\"A multi-purpose household device.\"),\n Item(name=\"Portal Gun\", description=\"A portal opening device.\"),\n Item(name=\"Meeseeks Box\", description=\"A box that summons a Meeseeks.\"),\n]\n\n\n@app.get(\"/items/stream\", response_cla", "suffix": " for item in items:\n yield item\n\n\n@app.get(\"/items/stream-no-annotation\", response_class=EventSourceResponse)\nasync def sse_items_no_annotation():\n for item in items:\n yield item\n\n\n@app.get(\"/items/stream-no-async-no-annotation\", respon", "middle": "ss=EventSourceResponse)\nasync def sse_items() -> AsyncIterable[Item]:\n for item in items:\n yield item\n\n\n@app.get(\"/items/stream-no-async\", response_class=EventSourceResponse)\ndef sse_items_no_async() -> Iterable[Item]:\n", "meta": {"filepath": "docs_src/server_sent_events/tutorial001_py310.py", "language": "python", "file_size": 1112, "cut_index": 515, "middle_length": 229}} {"prefix": "pi import FastAPI\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\n\nclass Item(BaseModel):\n name: str\n description: str | None = None\n price: float\n tax: float = 10.5\n\n\nitems = {\n \"foo\": {\"name\": \"Foo\", \"price\": 50.2},\n \"bar\": {\"name\": \"Bar\", \"description\": \"The Bar fighters\", \"price\": 62, \"tax\": 20.2},\n \"baz\": {\n \"name\": \"Baz\",\n \"description\": \"There goes my baz\",\n \"price\": 50.2,\n \"tax\": 10.5,\n },\n}\n\n\n@app.get(\n \"/items/{item_id}/name\",\n response_mo", "suffix": "response_model_include={\"name\", \"description\"},\n)\nasync def read_item_name(item_id: str):\n return items[item_id]\n\n\n@app.get(\"/items/{item_id}/public\", response_model=Item, response_model_exclude={\"tax\"})\nasync def read_item_public_data(item_id: str):\n ", "middle": "del=Item,\n ", "meta": {"filepath": "docs_src/response_model/tutorial005_py310.py", "language": "python", "file_size": 816, "cut_index": 522, "middle_length": 14}} {"prefix": "ithub\nfrom pydantic import BaseModel, SecretStr\nfrom pydantic_settings import BaseSettings\n\ngithub_graphql_url = \"https://api.github.com/graphql\"\n\n\nprs_query = \"\"\"\nquery Q($after: String) {\n repository(name: \"fastapi\", owner: \"fastapi\") {\n pullRequests(first: 100, after: $after) {\n edges {\n cursor\n node {\n number\n labels(first: 100) {\n nodes {\n name\n }\n }\n author {\n login\n avatarUrl\n ", "suffix": "arUrl\n url\n }\n state\n }\n }\n }\n }\n }\n }\n}\n\"\"\"\n\n\nclass Author(BaseModel):\n login: str\n avatarUrl: str\n url: str\n\n\nclass LabelNode(BaseModel):\n name: str\n\n\nclass Labels(B", "middle": " url\n }\n title\n createdAt\n lastEditedAt\n updatedAt\n state\n reviews(first:100) {\n nodes {\n author {\n login\n avat", "meta": {"filepath": "scripts/contributors.py", "language": "python", "file_size": 8807, "cut_index": 716, "middle_length": 229}} {"prefix": " = re.compile(r\"]*)>(.*?)\")\nHTML_LINK_OPEN_TAG_RE = re.compile(r\"]*)>\")\nHTML_ATTR_RE = re.compile(r'(\\w+)\\s*=\\s*([\\'\"])(.*?)\\2')\n\nCODE_BLOCK_LANG_RE = re.compile(r\"^`{3,4}([\\w-]*)\", re.MULTILINE)\n\nSLASHES_COMMENT_RE = re.compile(\n r\"^(?P.*?)(?P(?:(?<= )// .*)|(?:^// .*))?$\"\n)\n\nHASH_COMMENT_RE = re.compile(r\"^(?P.*?)(?P(?:(?<= )# .*)|(?:^# .*))?$\")\n\n\nclass CodeIncludeInfo(TypedDict):\n line_no: int\n line: str\n\n\nclass HeaderPermalinkInfo(TypedDict):\n ", "suffix": "nkAttribute(TypedDict):\n name: str\n quote: str\n value: str\n\n\nclass HtmlLinkInfo(TypedDict):\n line_no: int\n full_tag: str\n attributes: list[HTMLLinkAttribute]\n text: str\n\n\nclass MultilineCodeBlockInfo(TypedDict):\n lang: str\n start", "middle": " line_no: int\n hashes: str\n title: str\n permalink: str\n\n\nclass MarkdownLinkInfo(TypedDict):\n line_no: int\n url: str\n text: str\n title: str | None\n attributes: str | None\n full_match: str\n\n\nclass HTMLLi", "meta": {"filepath": "scripts/doc_parsing_utils.py", "language": "python", "file_size": 24109, "cut_index": 1331, "middle_length": 229}} {"prefix": "hub import Github\nfrom github.PullRequestReview import PullRequestReview\nfrom pydantic import BaseModel, SecretStr\nfrom pydantic_settings import BaseSettings\n\n\nclass LabelSettings(BaseModel):\n await_label: str | None = None\n number: int\n\n\ndefault_config = {\"approved-2\": LabelSettings(await_label=\"awaiting-review\", number=2)}\n\n\nclass Settings(BaseSettings):\n github_repository: str\n token: SecretStr\n debug: bool | None = False\n config: dict[str, LabelSettings] | Literal[\"\"] = default_config\n", "suffix": "secret_value())\nrepo = g.get_repo(settings.github_repository)\nfor pr in repo.get_pulls(state=\"open\"):\n logging.info(f\"Checking PR: #{pr.number}\")\n pr_labels = list(pr.get_labels())\n pr_label_by_name = {label.name: label for label in pr_labels}\n ", "middle": "\n\nsettings = Settings()\nif settings.debug:\n logging.basicConfig(level=logging.DEBUG)\nelse:\n logging.basicConfig(level=logging.INFO)\nlogging.debug(f\"Using config: {settings.model_dump_json()}\")\ng = Github(settings.token.get_", "meta": {"filepath": "scripts/label_approved.py", "language": "python", "file_size": 2245, "cut_index": 563, "middle_length": 229}} {"prefix": "ttings\n\ngithub_graphql_url = \"https://api.github.com/graphql\"\nquestions_category_id = \"DIC_kwDOCZduT84B6E2a\"\n\n\nPOINTS_PER_MINUTE_LIMIT = 84 # 5000 points per hour\n\nMINIMIZED_COMMENTS_REASONS_TO_EXCLUDE = {\"abuse\", \"off-topic\", \"duplicate\", \"spam\"}\n\n\nclass RateLimiter:\n def __init__(self) -> None:\n self.last_query_cost: int = 1\n self.remaining_points: int = 5000\n self.reset_at: datetime = datetime.fromtimestamp(0, timezone.utc)\n self.last_request_start_time: datetime = datetim", "suffix": "ime = 0.0\n if self.remaining_points <= self.last_query_cost:\n primary_limit_wait_time = (self.reset_at - now).total_seconds() + 2\n logging.warning(\n f\"Approaching GitHub API rate limit, remaining points: {self.re", "middle": "e.fromtimestamp(0, timezone.utc)\n self.speed_multiplier: float = 1.0\n\n def __enter__(self) -> \"RateLimiter\":\n now = datetime.now(tz=timezone.utc)\n\n # Handle primary rate limits\n primary_limit_wait_t", "meta": {"filepath": "scripts/people.py", "language": "python", "file_size": 15382, "cut_index": 921, "middle_length": 229}} {"prefix": "ory_id = \"DIC_kwDOCZduT84CT5P9\"\n\nall_discussions_query = \"\"\"\nquery Q($category_id: ID) {\n repository(name: \"fastapi\", owner: \"fastapi\") {\n discussions(categoryId: $category_id, first: 100) {\n nodes {\n title\n id\n number\n labels(first: 10) {\n edges {\n node {\n id\n name\n }\n }\n }\n }\n }\n }\n}\n\"\"\"\n\ntranslation_discussion_query = \"\"\"\nquery Q($after: String, $discussion_number: Int!) {\n repository(n", "suffix": " }\n }\n }\n }\n }\n}\n\"\"\"\n\nadd_comment_mutation = \"\"\"\nmutation Q($discussion_id: ID!, $body: String!) {\n addDiscussionComment(input: {discussionId: $discussion_id, body: $body}) {\n comment {\n id\n url\n body\n }\n }\n}\n\"\"\"\n\n", "middle": "ame: \"fastapi\", owner: \"fastapi\") {\n discussion(number: $discussion_number) {\n comments(first: 100, after: $after) {\n edges {\n cursor\n node {\n id\n url\n body\n ", "meta": {"filepath": "scripts/notify_translations.py", "language": "python", "file_size": 12930, "cut_index": 921, "middle_length": 229}} {"prefix": "m pathlib import Path\n\nimport yaml\nfrom github import Github\nfrom pydantic import BaseModel, SecretStr\nfrom pydantic_settings import BaseSettings\n\n\nclass Settings(BaseSettings):\n github_repository: str\n github_token: SecretStr\n\n\nclass Repo(BaseModel):\n name: str\n html_url: str\n stars: int\n owner_login: str\n owner_html_url: str\n\n\ndef main() -> None:\n logging.basicConfig(level=logging.INFO)\n settings = Settings()\n\n logging.info(f\"Using config: {settings.model_dump_json()}\")\n g", "suffix": "[]\n for repo in repos_list[:100]:\n if repo.full_name == settings.github_repository:\n continue\n final_repos.append(\n Repo(\n name=repo.name,\n html_url=repo.html_url,\n stars=r", "middle": " = Github(settings.github_token.get_secret_value(), per_page=100)\n r = g.get_repo(settings.github_repository)\n repos = g.search_repositories(query=\"topic:fastapi\")\n repos_list = list(repos)\n final_repos: list[Repo] = ", "meta": {"filepath": "scripts/topic_repos.py", "language": "python", "file_size": 2803, "cut_index": 563, "middle_length": 229}} {"prefix": "import typer\n\nfrom scripts.doc_parsing_utils import check_translation\n\nnon_translated_sections = (\n f\"reference{os.sep}\",\n \"release-notes.md\",\n \"fastapi-people.md\",\n \"external-links.md\",\n \"newsletter.md\",\n \"management-tasks.md\",\n \"management.md\",\n \"contributing.md\",\n \"translations.md\",\n)\n\n\ncli = typer.Typer()\n\n\n@cli.callback()\ndef callback():\n pass\n\n\ndef iter_all_lang_paths(lang_path_root: Path) -> Iterable[Path]:\n \"\"\"\n Iterate on the markdown files to translate in order ", "suffix": "irst_parent = lang_path_root\n yield from first_parent.glob(\"*.md\")\n for dir_path in first_dirs:\n yield from dir_path.rglob(\"*.md\")\n first_dirs_str = tuple(str(d) for d in first_dirs)\n for path in lang_path_root.rglob(\"*.md\"):\n if ", "middle": "of priority.\n \"\"\"\n\n first_dirs = [\n lang_path_root / \"learn\",\n lang_path_root / \"tutorial\",\n lang_path_root / \"advanced\",\n lang_path_root / \"about\",\n lang_path_root / \"how-to\",\n ]\n f", "meta": {"filepath": "scripts/translation_fixer.py", "language": "python", "file_size": 3311, "cut_index": 614, "middle_length": 229}} {"prefix": "thsep}\",\n \"release-notes.md\",\n \"fastapi-people.md\",\n \"external-links.md\",\n \"newsletter.md\",\n \"management-tasks.md\",\n \"management.md\",\n \"contributing.md\",\n \"translations.md\",\n)\n\ngeneral_prompt_path = Path(__file__).absolute().parent / \"general-llm-prompt.md\"\ngeneral_prompt = general_prompt_path.read_text(encoding=\"utf-8\")\n\napp = typer.Typer()\n\n\n@lru_cache\ndef get_langs() -> dict[str, str]:\n return yaml.safe_load(Path(\"docs/language_names.yml\").read_text(encoding=\"utf-8\"))\n\n\ndef gen", "suffix": "/{lang}/docs\")\n out_path = Path(str(path).replace(str(en_docs_path), str(lang_docs_path)))\n return out_path\n\n\ndef generate_en_path(*, lang: str, path: Path) -> Path:\n en_docs_path = Path(\"docs/en/docs\")\n assert not str(path).startswith(str(en_d", "middle": "erate_lang_path(*, lang: str, path: Path) -> Path:\n en_docs_path = Path(\"docs/en/docs\")\n assert str(path).startswith(str(en_docs_path)), (\n f\"Path must be inside {en_docs_path}\"\n )\n lang_docs_path = Path(f\"docs", "meta": {"filepath": "scripts/translate.py", "language": "python", "file_size": 17252, "cut_index": 921, "middle_length": 229}} {"prefix": " subprocess\nimport time\n\nimport httpx\nfrom playwright.sync_api import Playwright, sync_playwright\n\n\n# Run playwright codegen to generate the code below, copy paste the sections in run()\ndef run(playwright: Playwright) -> None:\n browser = playwright.chromium.launch(headless=False)\n # Update the viewport manually\n context = browser.new_context(viewport={\"width\": 960, \"height\": 1080})\n browser = playwright.chromium.launch(headless=False)\n context = browser.new_context()\n page = context.new_pa", "suffix": "---------------------\n context.close()\n browser.close()\n\n\nprocess = subprocess.Popen(\n [\"fastapi\", \"run\", \"docs_src/cookie_param_models/tutorial001.py\"]\n)\ntry:\n for _ in range(3):\n try:\n response = httpx.get(\"http://localhost:", "middle": "ge()\n page.goto(\"http://localhost:8000/docs\")\n page.get_by_role(\"link\", name=\"/items/\").click()\n # Manually add the screenshot\n page.screenshot(path=\"docs/en/docs/img/tutorial/cookie-param-models/image01.png\")\n\n # ", "meta": {"filepath": "scripts/playwright/cookie_param_models/image01.py", "language": "python", "file_size": 1193, "cut_index": 518, "middle_length": 229}} {"prefix": " subprocess\nimport time\n\nimport httpx\nfrom playwright.sync_api import Playwright, sync_playwright\n\n\n# Run playwright codegen to generate the code below, copy paste the sections in run()\ndef run(playwright: Playwright) -> None:\n browser = playwright.chromium.launch(headless=False)\n # Update the viewport manually\n context = browser.new_context(viewport={\"width\": 960, \"height\": 1080})\n page = context.new_page()\n page.goto(\"http://localhost:8000/docs\")\n page.get_by_role(\"button\", name=\"POST /l", "suffix": " context.close()\n browser.close()\n\n\nprocess = subprocess.Popen(\n [\"fastapi\", \"run\", \"docs_src/request_form_models/tutorial001.py\"]\n)\ntry:\n for _ in range(3):\n try:\n response = httpx.get(\"http://localhost:8000/docs\")\n ex", "middle": "ogin/ Login\").click()\n page.get_by_role(\"button\", name=\"Try it out\").click()\n # Manually add the screenshot\n page.screenshot(path=\"docs/en/docs/img/tutorial/request-form-models/image01.png\")\n\n # ---------------------\n", "meta": {"filepath": "scripts/playwright/request_form_models/image01.py", "language": "python", "file_size": 1171, "cut_index": 518, "middle_length": 229}} {"prefix": "mport subprocess\n\nfrom playwright.sync_api import Playwright, sync_playwright\n\n\n# Run playwright codegen to generate the code below, copy paste the sections in run()\ndef run(playwright: Playwright) -> None:\n browser = playwright.chromium.launch(headless=False)\n # Update the viewport manually\n context = browser.new_context(viewport={\"width\": 960, \"height\": 1080})\n page = context.new_page()\n page.goto(\"http://localhost:8000/docs\")\n page.get_by_text(\"GET/items/Read Items\").click()\n page.ge", "suffix": ".png\"\n )\n\n # ---------------------\n context.close()\n browser.close()\n\n\nprocess = subprocess.Popen(\n [\"uvicorn\", \"docs_src.separate_openapi_schemas.tutorial001:app\"]\n)\ntry:\n with sync_playwright() as playwright:\n run(playwright)\nfin", "middle": "t_by_role(\"button\", name=\"Try it out\").click()\n page.get_by_role(\"button\", name=\"Execute\").click()\n # Manually add the screenshot\n page.screenshot(\n path=\"docs/en/docs/img/tutorial/separate-openapi-schemas/image02", "meta": {"filepath": "scripts/playwright/separate_openapi_schemas/image02.py", "language": "python", "file_size": 1028, "cut_index": 513, "middle_length": 229}} {"prefix": "mport subprocess\n\nfrom playwright.sync_api import Playwright, sync_playwright\n\n\n# Run playwright codegen to generate the code below, copy paste the sections in run()\ndef run(playwright: Playwright) -> None:\n browser = playwright.chromium.launch(headless=False)\n # Update the viewport manually\n context = browser.new_context(viewport={\"width\": 960, \"height\": 1080})\n page = context.new_page()\n page.goto(\"http://localhost:8000/docs\")\n page.get_by_text(\"GET/items/Read Items\").click()\n page.ge", "suffix": "api-schemas/image03.png\"\n )\n\n # ---------------------\n context.close()\n browser.close()\n\n\nprocess = subprocess.Popen(\n [\"uvicorn\", \"docs_src.separate_openapi_schemas.tutorial001:app\"]\n)\ntry:\n with sync_playwright() as playwright:\n ", "middle": "t_by_role(\"tab\", name=\"Schema\").click()\n page.get_by_label(\"Schema\").get_by_role(\"button\", name=\"Expand all\").click()\n # Manually add the screenshot\n page.screenshot(\n path=\"docs/en/docs/img/tutorial/separate-open", "meta": {"filepath": "scripts/playwright/separate_openapi_schemas/image03.py", "language": "python", "file_size": 1047, "cut_index": 513, "middle_length": 229}} {"prefix": "mport subprocess\n\nfrom playwright.sync_api import Playwright, sync_playwright\n\n\n# Run playwright codegen to generate the code below, copy paste the sections in run()\ndef run(playwright: Playwright) -> None:\n browser = playwright.chromium.launch(headless=False)\n # Update the viewport manually\n context = browser.new_context(viewport={\"width\": 960, \"height\": 1080})\n page = context.new_page()\n page.goto(\"http://localhost:8000/docs\")\n page.get_by_role(\"button\", name=\"Item-Input\").click()\n pa", "suffix": "s/image04.png\"\n )\n # ---------------------\n context.close()\n browser.close()\n\n\nprocess = subprocess.Popen(\n [\"uvicorn\", \"docs_src.separate_openapi_schemas.tutorial001:app\"]\n)\ntry:\n with sync_playwright() as playwright:\n run(playwri", "middle": "ge.get_by_role(\"button\", name=\"Item-Output\").click()\n page.set_viewport_size({\"width\": 960, \"height\": 820})\n # Manually add the screenshot\n page.screenshot(\n path=\"docs/en/docs/img/tutorial/separate-openapi-schema", "meta": {"filepath": "scripts/playwright/separate_openapi_schemas/image04.py", "language": "python", "file_size": 1036, "cut_index": 513, "middle_length": 229}} {"prefix": "aywright\n\n\n# Run playwright codegen to generate the code below, copy paste the sections in run()\ndef run(playwright: Playwright) -> None:\n browser = playwright.chromium.launch(headless=False)\n # Update the viewport manually\n context = browser.new_context(viewport={\"width\": 960, \"height\": 1080})\n page = context.new_page()\n page.goto(\"http://localhost:8000/docs\")\n page.get_by_text(\"POST/items/Create Item\").click()\n page.get_by_role(\"tab\", name=\"Schema\").first.click()\n # Manually add th", "suffix": "/en/docs/img/tutorial/separate-openapi-schemas/image01.png\"\n )\n\n # ---------------------\n context.close()\n browser.close()\n\n\nprocess = subprocess.Popen(\n [\"uvicorn\", \"docs_src.separate_openapi_schemas.tutorial001:app\"]\n)\ntry:\n with sync_p", "middle": "e screenshot\n page.screenshot(\n path=\"docs", "meta": {"filepath": "scripts/playwright/separate_openapi_schemas/image01.py", "language": "python", "file_size": 974, "cut_index": 582, "middle_length": 52}} {"prefix": "ort subprocess\nimport time\n\nimport httpx\nfrom playwright.sync_api import Playwright, sync_playwright\n\n\n# Run playwright codegen to generate the code below, copy paste the sections in run()\ndef run(playwright: Playwright) -> None:\n browser = playwright.chromium.launch(headless=False)\n # Update the viewport manually\n context = browser.new_context(viewport={\"width\": 960, \"height\": 1080})\n page = context.new_page()\n page.goto(\"http://localhost:8000/docs\")\n page.get_by_role(\"button\", name=\"POST", "suffix": "process.Popen(\n [\"fastapi\", \"run\", \"docs_src/json_base64_bytes/tutorial001_py310.py\"]\n)\ntry:\n for _ in range(3):\n try:\n response = httpx.get(\"http://localhost:8000/docs\")\n except httpx.ConnectError:\n time.sleep(1)\n", "middle": " /data Post Data\").click()\n # Manually add the screenshot\n page.screenshot(path=\"docs/en/docs/img/tutorial/json-base64-bytes/image01.png\")\n\n # ---------------------\n context.close()\n browser.close()\n\n\nprocess = sub", "meta": {"filepath": "scripts/playwright/json_base64_bytes/image01.py", "language": "python", "file_size": 1117, "cut_index": 515, "middle_length": 229}} {"prefix": "ort subprocess\nimport time\n\nimport httpx\nfrom playwright.sync_api import Playwright, sync_playwright\n\n\n# Run playwright codegen to generate the code below, copy paste the sections in run()\ndef run(playwright: Playwright) -> None:\n browser = playwright.chromium.launch(headless=False)\n # Update the viewport manually\n context = browser.new_context(viewport={\"width\": 960, \"height\": 1080})\n page = context.new_page()\n page.goto(\"http://localhost:8000/docs\")\n page.get_by_label(\"post /heroes/\").cl", "suffix": "api\", \"run\", \"docs_src/sql_databases/tutorial002.py\"],\n)\ntry:\n for _ in range(3):\n try:\n response = httpx.get(\"http://localhost:8000/docs\")\n except httpx.ConnectError:\n time.sleep(1)\n break\n with sync_pl", "middle": "ick()\n # Manually add the screenshot\n page.screenshot(path=\"docs/en/docs/img/tutorial/sql-databases/image02.png\")\n\n # ---------------------\n context.close()\n browser.close()\n\n\nprocess = subprocess.Popen(\n [\"fast", "meta": {"filepath": "scripts/playwright/sql_databases/image02.py", "language": "python", "file_size": 1083, "cut_index": 515, "middle_length": 229}} {"prefix": "mport sys\nfrom collections.abc import Generator\nfrom contextlib import contextmanager\nfrom pathlib import Path\n\nimport pytest\nfrom typer.testing import CliRunner\n\nskip_on_windows = pytest.mark.skipif(\n sys.platform == \"win32\", reason=\"Skipping on Windows\"\n)\n\n\nTHIS_DIR = Path(__file__).parent.resolve()\n\n\ndef pytest_collection_modifyitems(config, items: list[pytest.Item]) -> None:\n if sys.platform != \"win32\":\n return\n\n for item in items:\n item_path = Path(item.fspath).resolve()\n ", "suffix": " try:\n yield\n finally:\n os.chdir(initial_dir)\n\n\n@pytest.fixture(name=\"runner\")\ndef get_runner(tmp_path: Path):\n with changing_dir(tmp_path):\n yield CliRunner()\n\n\n@pytest.fixture(name=\"root_dir\")\ndef prepare_paths(runner):\n d", "middle": "if item_path.is_relative_to(THIS_DIR):\n item.add_marker(skip_on_windows)\n\n\n@contextmanager\ndef changing_dir(directory: str | Path) -> Generator[None, None, None]:\n initial_dir = os.getcwd()\n os.chdir(directory)\n ", "meta": {"filepath": "scripts/tests/test_translation_fixer/conftest.py", "language": "python", "file_size": 1637, "cut_index": 537, "middle_length": 229}} {"prefix": " subprocess\nimport time\n\nimport httpx\nfrom playwright.sync_api import Playwright, sync_playwright\n\n\n# Run playwright codegen to generate the code below, copy paste the sections in run()\ndef run(playwright: Playwright) -> None:\n browser = playwright.chromium.launch(headless=False)\n # Update the viewport manually\n context = browser.new_context(viewport={\"width\": 960, \"height\": 1080})\n page = context.new_page()\n page.goto(\"http://localhost:8000/docs\")\n page.get_by_role(\"button\", name=\"GET /it", "suffix": "---\n context.close()\n browser.close()\n\n\nprocess = subprocess.Popen(\n [\"fastapi\", \"run\", \"docs_src/header_param_models/tutorial001.py\"]\n)\ntry:\n for _ in range(3):\n try:\n response = httpx.get(\"http://localhost:8000/docs\")\n ", "middle": "ems/ Read Items\").click()\n page.get_by_role(\"button\", name=\"Try it out\").click()\n # Manually add the screenshot\n page.screenshot(path=\"docs/en/docs/img/tutorial/header-param-models/image01.png\")\n\n # ------------------", "meta": {"filepath": "scripts/playwright/header_param_models/image01.py", "language": "python", "file_size": 1175, "cut_index": 518, "middle_length": 229}} {"prefix": "ort subprocess\nimport time\n\nimport httpx\nfrom playwright.sync_api import Playwright, sync_playwright\n\n\n# Run playwright codegen to generate the code below, copy paste the sections in run()\ndef run(playwright: Playwright) -> None:\n browser = playwright.chromium.launch(headless=False)\n # Update the viewport manually\n context = browser.new_context(viewport={\"width\": 960, \"height\": 1080})\n page = context.new_page()\n page.goto(\"http://localhost:8000/docs\")\n page.get_by_label(\"post /heroes/\").cl", "suffix": "api\", \"run\", \"docs_src/sql_databases/tutorial001.py\"],\n)\ntry:\n for _ in range(3):\n try:\n response = httpx.get(\"http://localhost:8000/docs\")\n except httpx.ConnectError:\n time.sleep(1)\n break\n with sync_pl", "middle": "ick()\n # Manually add the screenshot\n page.screenshot(path=\"docs/en/docs/img/tutorial/sql-databases/image01.png\")\n\n # ---------------------\n context.close()\n browser.close()\n\n\nprocess = subprocess.Popen(\n [\"fast", "meta": {"filepath": "scripts/playwright/sql_databases/image01.py", "language": "python", "file_size": 1083, "cut_index": 515, "middle_length": 229}} {"prefix": "\nimport pytest\nfrom typer.testing import CliRunner\n\nfrom scripts.translation_fixer import cli\n\ndata_path = Path(\n \"scripts/tests/test_translation_fixer/test_header_permalinks/data\"\n).absolute()\n\n\n@pytest.mark.parametrize(\n \"copy_test_files\",\n [(f\"{data_path}/en_doc.md\", f\"{data_path}/translated_doc_number_gt.md\")],\n indirect=True,\n)\ndef test_gt(runner: CliRunner, root_dir: Path, copy_test_files):\n result = runner.invoke(\n cli,\n [\"fix-pages\", \"docs/lang/docs/doc.md\"],\n )\n a", "suffix": "sert fixed_content == expected_content # Translated doc remains unchanged\n assert \"Error processing docs/lang/docs/doc.md\" in result.output\n assert (\n \"Number of headers with permalinks does not match the number \"\n \"in the original doc", "middle": "ssert result.exit_code == 1\n\n fixed_content = (root_dir / \"docs\" / \"lang\" / \"docs\" / \"doc.md\").read_text(\"utf-8\")\n expected_content = Path(f\"{data_path}/translated_doc_number_gt.md\").read_text(\n \"utf-8\"\n )\n\n as", "meta": {"filepath": "scripts/tests/test_translation_fixer/test_header_permalinks/test_header_number_mismatch.py", "language": "python", "file_size": 1900, "cut_index": 537, "middle_length": 229}} {"prefix": "\nimport pytest\nfrom typer.testing import CliRunner\n\nfrom scripts.translation_fixer import cli\n\ndata_path = Path(\n \"scripts/tests/test_translation_fixer/test_code_blocks/data\"\n).absolute()\n\n\n@pytest.mark.parametrize(\n \"copy_test_files\",\n [(f\"{data_path}/en_doc.md\", f\"{data_path}/translated_doc_lines_number_gt.md\")],\n indirect=True,\n)\ndef test_gt(runner: CliRunner, root_dir: Path, copy_test_files):\n result = runner.invoke(\n cli,\n [\"fix-pages\", \"docs/lang/docs/doc.md\"],\n )\n a", "suffix": "\"utf-8\"\n )\n\n assert fixed_content == expected_content # Translated doc remains unchanged\n assert \"Error processing docs/lang/docs/doc.md\" in result.output\n assert (\n \"Code block (lines 14-18) has different number of lines than the origi", "middle": "ssert result.exit_code == 1, result.output\n\n fixed_content = (root_dir / \"docs\" / \"lang\" / \"docs\" / \"doc.md\").read_text(\"utf-8\")\n expected_content = Path(f\"{data_path}/translated_doc_lines_number_gt.md\").read_text(\n ", "meta": {"filepath": "scripts/tests/test_translation_fixer/test_code_blocks/test_code_blocks_lines_number_mismatch.py", "language": "python", "file_size": 1916, "cut_index": 537, "middle_length": 229}} {"prefix": "\nimport pytest\nfrom typer.testing import CliRunner\n\nfrom scripts.translation_fixer import cli\n\ndata_path = Path(\n \"scripts/tests/test_translation_fixer/test_code_blocks/data\"\n).absolute()\n\n\n@pytest.mark.parametrize(\n \"copy_test_files\",\n [(f\"{data_path}/en_doc.md\", f\"{data_path}/translated_doc_number_gt.md\")],\n indirect=True,\n)\ndef test_gt(runner: CliRunner, root_dir: Path, copy_test_files):\n result = runner.invoke(\n cli,\n [\"fix-pages\", \"docs/lang/docs/doc.md\"],\n )\n assert ", "suffix": ")\n\n assert fixed_content == expected_content # Translated doc remains unchanged\n assert \"Error processing docs/lang/docs/doc.md\" in result.output\n assert (\n \"Number of code blocks does not match the number \"\n \"in the original docume", "middle": "result.exit_code == 1, result.output\n\n fixed_content = (root_dir / \"docs\" / \"lang\" / \"docs\" / \"doc.md\").read_text(\"utf-8\")\n expected_content = Path(f\"{data_path}/translated_doc_number_gt.md\").read_text(\n \"utf-8\"\n ", "meta": {"filepath": "scripts/tests/test_translation_fixer/test_code_blocks/test_code_blocks_number_mismatch.py", "language": "python", "file_size": 1902, "cut_index": 537, "middle_length": 229}} {"prefix": "test\nfrom typer.testing import CliRunner\n\nfrom scripts.translation_fixer import cli\n\ndata_path = Path(\n \"scripts/tests/test_translation_fixer/test_complex_doc/data\"\n).absolute()\n\n\n@pytest.mark.parametrize(\n \"copy_test_files\",\n [(f\"{data_path}/en_doc.md\", f\"{data_path}/translated_doc.md\")],\n indirect=True,\n)\ndef test_fix(runner: CliRunner, root_dir: Path, copy_test_files):\n result = runner.invoke(\n cli,\n [\"fix-pages\", \"docs/lang/docs/doc.md\"],\n )\n assert result.exit_code ==", "suffix": "docs\" / \"lang\" / \"docs\" / \"doc.md\").read_text(\"utf-8\")\n expected_content = (data_path / \"translated_doc_expected.md\").read_text(\"utf-8\")\n assert fixed_content == expected_content\n\n assert \"Fixing multiline code blocks in\" in result.output\n asse", "middle": " 0, result.output\n\n fixed_content = (root_dir / \"", "meta": {"filepath": "scripts/tests/test_translation_fixer/test_complex_doc/test_compex_doc.py", "language": "python", "file_size": 902, "cut_index": 547, "middle_length": 52}} {"prefix": "\nimport pytest\nfrom typer.testing import CliRunner\n\nfrom scripts.translation_fixer import cli\n\ndata_path = Path(\n \"scripts/tests/test_translation_fixer/test_code_blocks/data\"\n).absolute()\n\n\n@pytest.mark.parametrize(\n \"copy_test_files\",\n [(f\"{data_path}/en_doc.md\", f\"{data_path}/translated_doc_wrong_lang_code.md\")],\n indirect=True,\n)\ndef test_wrong_lang_code_1(runner: CliRunner, root_dir: Path, copy_test_files):\n result = runner.invoke(\n cli,\n [\"fix-pages\", \"docs/lang/docs/doc.md", "suffix": "_text(\n \"utf-8\"\n )\n\n assert fixed_content == expected_content # Translated doc remains unchanged\n assert \"Error processing docs/lang/docs/doc.md\" in result.output\n assert (\n \"Code block (lines 16-19) has different language than t", "middle": "\"],\n )\n assert result.exit_code == 1, result.output\n\n fixed_content = (root_dir / \"docs\" / \"lang\" / \"docs\" / \"doc.md\").read_text(\"utf-8\")\n expected_content = Path(f\"{data_path}/translated_doc_wrong_lang_code.md\").read", "meta": {"filepath": "scripts/tests/test_translation_fixer/test_code_blocks/test_code_blocks_wrong_lang_code.py", "language": "python", "file_size": 1950, "cut_index": 537, "middle_length": 229}} {"prefix": "\nimport pytest\nfrom typer.testing import CliRunner\n\nfrom scripts.translation_fixer import cli\n\ndata_path = Path(\n \"scripts/tests/test_translation_fixer/test_code_blocks/data\"\n).absolute()\n\n\n@pytest.mark.parametrize(\n \"copy_test_files\",\n [(f\"{data_path}/en_doc.md\", f\"{data_path}/translated_doc_mermaid_translated.md\")],\n indirect=True,\n)\ndef test_translated(runner: CliRunner, root_dir: Path, copy_test_files):\n result = runner.invoke(\n cli,\n [\"fix-pages\", \"docs/lang/docs/doc.md\"],\n", "suffix": "d\"\n ).read_text(\"utf-8\")\n\n assert fixed_content == expected_content # Translated doc remains unchanged\n assert (\n \"Skipping mermaid code block replacement (lines 41-44). This should be checked manually.\"\n ) in result.output\n\n\n@pytest.ma", "middle": " )\n assert result.exit_code == 0, result.output\n\n fixed_content = (root_dir / \"docs\" / \"lang\" / \"docs\" / \"doc.md\").read_text(\"utf-8\")\n expected_content = Path(\n f\"{data_path}/translated_doc_mermaid_translated.m", "meta": {"filepath": "scripts/tests/test_translation_fixer/test_code_blocks/test_code_blocks_mermaid.py", "language": "python", "file_size": 1807, "cut_index": 537, "middle_length": 229}} {"prefix": "\nimport pytest\nfrom typer.testing import CliRunner\n\nfrom scripts.translation_fixer import cli\n\ndata_path = Path(\n \"scripts/tests/test_translation_fixer/test_code_includes/data\"\n).absolute()\n\n\n@pytest.mark.parametrize(\n \"copy_test_files\",\n [(f\"{data_path}/en_doc.md\", f\"{data_path}/translated_doc_number_gt.md\")],\n indirect=True,\n)\ndef test_gt(runner: CliRunner, root_dir: Path, copy_test_files):\n result = runner.invoke(\n cli,\n [\"fix-pages\", \"docs/lang/docs/doc.md\"],\n )\n asser", "suffix": " fixed_content == expected_content # Translated doc remains unchanged\n assert \"Error processing docs/lang/docs/doc.md\" in result.output\n assert (\n \"Number of code include placeholders does not match the number of code includes \"\n \"in t", "middle": "t result.exit_code == 1\n\n fixed_content = (root_dir / \"docs\" / \"lang\" / \"docs\" / \"doc.md\").read_text(\"utf-8\")\n expected_content = Path(f\"{data_path}/translated_doc_number_gt.md\").read_text(\n \"utf-8\"\n )\n\n assert", "meta": {"filepath": "scripts/tests/test_translation_fixer/test_code_includes/test_number_mismatch.py", "language": "python", "file_size": 1934, "cut_index": 537, "middle_length": 229}} {"prefix": "\nimport pytest\nfrom typer.testing import CliRunner\n\nfrom scripts.translation_fixer import cli\n\ndata_path = Path(\"scripts/tests/test_translation_fixer/test_html_links/data\").absolute()\n\n\n@pytest.mark.parametrize(\n \"copy_test_files\",\n [(f\"{data_path}/en_doc.md\", f\"{data_path}/translated_doc_number_gt.md\")],\n indirect=True,\n)\ndef test_gt(runner: CliRunner, root_dir: Path, copy_test_files):\n result = runner.invoke(\n cli,\n [\"fix-pages\", \"docs/lang/docs/doc.md\"],\n )\n assert result.", "suffix": "assert fixed_content == expected_content # Translated doc remains unchanged\n assert \"Error processing docs/lang/docs/doc.md\" in result.output\n assert (\n \"Number of HTML links does not match the number \"\n \"in the original document (7 vs", "middle": "exit_code == 1, result.output\n\n fixed_content = (root_dir / \"docs\" / \"lang\" / \"docs\" / \"doc.md\").read_text(\"utf-8\")\n expected_content = Path(f\"{data_path}/translated_doc_number_gt.md\").read_text(\n \"utf-8\"\n )\n\n ", "meta": {"filepath": "scripts/tests/test_translation_fixer/test_html_links/test_html_links_number_mismatch.py", "language": "python", "file_size": 1893, "cut_index": 537, "middle_length": 229}} {"prefix": "epends, FastAPI, HTTPException, status\nfrom fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm\nfrom pydantic import BaseModel\n\nfake_users_db = {\n \"johndoe\": {\n \"username\": \"johndoe\",\n \"full_name\": \"John Doe\",\n \"email\": \"johndoe@example.com\",\n \"hashed_password\": \"fakehashedsecret\",\n \"disabled\": False,\n },\n \"alice\": {\n \"username\": \"alice\",\n \"full_name\": \"Alice Wonderson\",\n \"email\": \"alice@example.com\",\n \"hashed_passwo", "suffix": "odel):\n username: str\n email: str | None = None\n full_name: str | None = None\n disabled: bool | None = None\n\n\nclass UserInDB(User):\n hashed_password: str\n\n\ndef get_user(db, username: str):\n if username in db:\n user_dict = db[userna", "middle": "rd\": \"fakehashedsecret2\",\n \"disabled\": True,\n },\n}\n\napp = FastAPI()\n\n\ndef fake_hash_password(password: str):\n return \"fakehashed\" + password\n\n\noauth2_scheme = OAuth2PasswordBearer(tokenUrl=\"token\")\n\n\nclass User(BaseM", "meta": {"filepath": "docs_src/security/tutorial003_an_py310.py", "language": "python", "file_size": 2517, "cut_index": 563, "middle_length": 229}} {"prefix": ", status\nfrom fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm\nfrom pydantic import BaseModel\n\nfake_users_db = {\n \"johndoe\": {\n \"username\": \"johndoe\",\n \"full_name\": \"John Doe\",\n \"email\": \"johndoe@example.com\",\n \"hashed_password\": \"fakehashedsecret\",\n \"disabled\": False,\n },\n \"alice\": {\n \"username\": \"alice\",\n \"full_name\": \"Alice Wonderson\",\n \"email\": \"alice@example.com\",\n \"hashed_password\": \"fakehashedsecret2\",\n ", "suffix": "mail: str | None = None\n full_name: str | None = None\n disabled: bool | None = None\n\n\nclass UserInDB(User):\n hashed_password: str\n\n\ndef get_user(db, username: str):\n if username in db:\n user_dict = db[username]\n return UserInDB(**", "middle": " \"disabled\": True,\n },\n}\n\napp = FastAPI()\n\n\ndef fake_hash_password(password: str):\n return \"fakehashed\" + password\n\n\noauth2_scheme = OAuth2PasswordBearer(tokenUrl=\"token\")\n\n\nclass User(BaseModel):\n username: str\n e", "meta": {"filepath": "docs_src/security/tutorial003_py310.py", "language": "python", "file_size": 2433, "cut_index": 563, "middle_length": 229}} {"prefix": "asswordBearer,\n OAuth2PasswordRequestForm,\n SecurityScopes,\n)\nfrom jwt.exceptions import InvalidTokenError\nfrom pwdlib import PasswordHash\nfrom pydantic import BaseModel, ValidationError\n\n# to get a string like this run:\n# openssl rand -hex 32\nSECRET_KEY = \"09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7\"\nALGORITHM = \"HS256\"\nACCESS_TOKEN_EXPIRE_MINUTES = 30\n\n\nfake_users_db = {\n \"johndoe\": {\n \"username\": \"johndoe\",\n \"full_name\": \"John Doe\",\n \"email\": \"johndoe@ex", "suffix": "ll_name\": \"Alice Chains\",\n \"email\": \"alicechains@example.com\",\n \"hashed_password\": \"$argon2id$v=19$m=65536,t=3,p=4$g2/AV1zwopqUntPKJavBFw$BwpRGDCyUHLvHICnwijyX8ROGoiUPwNKZ7915MeYfCE\",\n \"disabled\": True,\n },\n}\n\n\nclass Token(BaseModel", "middle": "ample.com\",\n \"hashed_password\": \"$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w$CYaIb8sB+wtD+Vu/P4uod1+Qof8h+1g7bbDlBID48Rc\",\n \"disabled\": False,\n },\n \"alice\": {\n \"username\": \"alice\",\n \"fu", "meta": {"filepath": "docs_src/security/tutorial005_an_py310.py", "language": "python", "file_size": 5509, "cut_index": 716, "middle_length": 229}} {"prefix": "tapi import FastAPI\nfrom fastapi.responses import JSONResponse\nfrom pydantic import BaseModel\n\n\nclass Item(BaseModel):\n id: str\n value: str\n\n\nclass Message(BaseModel):\n message: str\n\n\napp = FastAPI()\n\n\n@app.get(\n \"/items/{item_id}\",\n response_model=Item,\n responses={\n 404: {\"model\": Message, \"description\": \"The item was not found\"},\n 200: {\n \"description\": \"Item requested by ID\",\n \"content\": {\n \"application/json\": {\n \"ex", "suffix": " }\n },\n },\n },\n)\nasync def read_item(item_id: str):\n if item_id == \"foo\":\n return {\"id\": \"foo\", \"value\": \"there goes my hero\"}\n else:\n return JSONResponse(status_code=404, content={\"message\": \"Item not ", "middle": "ample\": {\"id\": \"bar\", \"value\": \"The bar tenders\"}\n ", "meta": {"filepath": "docs_src/additional_responses/tutorial003_py310.py", "language": "python", "file_size": 837, "cut_index": 520, "middle_length": 52}} {"prefix": "pi import Depends, FastAPI, HTTPException, status\nfrom fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm\nfrom jwt.exceptions import InvalidTokenError\nfrom pwdlib import PasswordHash\nfrom pydantic import BaseModel\n\n# to get a string like this run:\n# openssl rand -hex 32\nSECRET_KEY = \"09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7\"\nALGORITHM = \"HS256\"\nACCESS_TOKEN_EXPIRE_MINUTES = 30\n\n\nfake_users_db = {\n \"johndoe\": {\n \"username\": \"johndoe\",\n \"full_name\"", "suffix": "n(BaseModel):\n access_token: str\n token_type: str\n\n\nclass TokenData(BaseModel):\n username: str | None = None\n\n\nclass User(BaseModel):\n username: str\n email: str | None = None\n full_name: str | None = None\n disabled: bool | None = None\n", "middle": ": \"John Doe\",\n \"email\": \"johndoe@example.com\",\n \"hashed_password\": \"$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w$CYaIb8sB+wtD+Vu/P4uod1+Qof8h+1g7bbDlBID48Rc\",\n \"disabled\": False,\n }\n}\n\n\nclass Toke", "meta": {"filepath": "docs_src/security/tutorial004_an_py310.py", "language": "python", "file_size": 4300, "cut_index": 614, "middle_length": 229}} {"prefix": "TTPException, status\nfrom fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm\nfrom jwt.exceptions import InvalidTokenError\nfrom pwdlib import PasswordHash\nfrom pydantic import BaseModel\n\n# to get a string like this run:\n# openssl rand -hex 32\nSECRET_KEY = \"09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7\"\nALGORITHM = \"HS256\"\nACCESS_TOKEN_EXPIRE_MINUTES = 30\n\n\nfake_users_db = {\n \"johndoe\": {\n \"username\": \"johndoe\",\n \"full_name\": \"John Doe\",\n \"email\"", "suffix": "n: str\n token_type: str\n\n\nclass TokenData(BaseModel):\n username: str | None = None\n\n\nclass User(BaseModel):\n username: str\n email: str | None = None\n full_name: str | None = None\n disabled: bool | None = None\n\n\nclass UserInDB(User):\n h", "middle": ": \"johndoe@example.com\",\n \"hashed_password\": \"$argon2id$v=19$m=65536,t=3,p=4$wagCPXjifgvUFBzq4hqe3w$CYaIb8sB+wtD+Vu/P4uod1+Qof8h+1g7bbDlBID48Rc\",\n \"disabled\": False,\n }\n}\n\n\nclass Token(BaseModel):\n access_toke", "meta": {"filepath": "docs_src/security/tutorial004_py310.py", "language": "python", "file_size": 4200, "cut_index": 614, "middle_length": 229}} {"prefix": "ort secrets\n\nfrom fastapi import Depends, FastAPI, HTTPException, status\nfrom fastapi.security import HTTPBasic, HTTPBasicCredentials\n\napp = FastAPI()\n\nsecurity = HTTPBasic()\n\n\ndef get_current_username(credentials: HTTPBasicCredentials = Depends(security)):\n current_username_bytes = credentials.username.encode(\"utf8\")\n correct_username_bytes = b\"stanleyjobson\"\n is_correct_username = secrets.compare_digest(\n current_username_bytes, correct_username_bytes\n )\n current_password_bytes = cre", "suffix": "ect_password):\n raise HTTPException(\n status_code=status.HTTP_401_UNAUTHORIZED,\n detail=\"Incorrect username or password\",\n headers={\"WWW-Authenticate\": \"Basic\"},\n )\n return credentials.username\n\n\n@app.get(\"", "middle": "dentials.password.encode(\"utf8\")\n correct_password_bytes = b\"swordfish\"\n is_correct_password = secrets.compare_digest(\n current_password_bytes, correct_password_bytes\n )\n if not (is_correct_username and is_corr", "meta": {"filepath": "docs_src/security/tutorial007_py310.py", "language": "python", "file_size": 1116, "cut_index": 515, "middle_length": 229}} {"prefix": "xception_handler,\n request_validation_exception_handler,\n)\nfrom fastapi.exceptions import RequestValidationError\nfrom starlette.exceptions import HTTPException as StarletteHTTPException\n\napp = FastAPI()\n\n\n@app.exception_handler(StarletteHTTPException)\nasync def custom_http_exception_handler(request, exc):\n print(f\"OMG! An HTTP error!: {repr(exc)}\")\n return await http_exception_handler(request, exc)\n\n\n@app.exception_handler(RequestValidationError)\nasync def validation_exception_handler(request, exc)", "suffix": "xc}\")\n return await request_validation_exception_handler(request, exc)\n\n\n@app.get(\"/items/{item_id}\")\nasync def read_item(item_id: int):\n if item_id == 3:\n raise HTTPException(status_code=418, detail=\"Nope! I don't like 3.\")\n return {\"item_", "middle": ":\n print(f\"OMG! The client sent invalid data!: {e", "meta": {"filepath": "docs_src/handling_errors/tutorial006_py310.py", "language": "python", "file_size": 928, "cut_index": 606, "middle_length": 52}} {"prefix": "ted\n\nfrom fastapi import Body, FastAPI\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\n\nclass Item(BaseModel):\n name: str\n description: str | None = None\n price: float\n tax: float | None = None\n\n\n@app.put(\"/items/{item_id}\")\nasync def update_item(\n *,\n item_id: int,\n item: Annotated[\n Item,\n Body(\n openapi_examples={\n \"normal\": {\n \"summary\": \"A normal example\",\n \"description\": \"A **normal** item works correct", "suffix": " },\n },\n \"converted\": {\n \"summary\": \"An example with converted data\",\n \"description\": \"FastAPI can convert price `strings` to actual `numbers` automatically\",\n \"value\": ", "middle": "ly.\",\n \"value\": {\n \"name\": \"Foo\",\n \"description\": \"A very nice Item\",\n \"price\": 35.4,\n \"tax\": 3.2,\n ", "meta": {"filepath": "docs_src/schema_extra_example/tutorial005_an_py310.py", "language": "python", "file_size": 1523, "cut_index": 537, "middle_length": 229}} {"prefix": " secrets\nfrom typing import Annotated\n\nfrom fastapi import Depends, FastAPI, HTTPException, status\nfrom fastapi.security import HTTPBasic, HTTPBasicCredentials\n\napp = FastAPI()\n\nsecurity = HTTPBasic()\n\n\ndef get_current_username(\n credentials: Annotated[HTTPBasicCredentials, Depends(security)],\n):\n current_username_bytes = credentials.username.encode(\"utf8\")\n correct_username_bytes = b\"stanleyjobson\"\n is_correct_username = secrets.compare_digest(\n current_username_bytes, correct_username_b", "suffix": " if not (is_correct_username and is_correct_password):\n raise HTTPException(\n status_code=status.HTTP_401_UNAUTHORIZED,\n detail=\"Incorrect username or password\",\n headers={\"WWW-Authenticate\": \"Basic\"},\n )\n ", "middle": "ytes\n )\n current_password_bytes = credentials.password.encode(\"utf8\")\n correct_password_bytes = b\"swordfish\"\n is_correct_password = secrets.compare_digest(\n current_password_bytes, correct_password_bytes\n )\n", "meta": {"filepath": "docs_src/security/tutorial007_an_py310.py", "language": "python", "file_size": 1172, "cut_index": 518, "middle_length": 229}} {"prefix": "rom fastapi import Body, FastAPI\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\n\nclass Item(BaseModel):\n name: str\n description: str | None = None\n price: float\n tax: float | None = None\n\n\n@app.put(\"/items/{item_id}\")\nasync def update_item(\n *,\n item_id: int,\n item: Item = Body(\n examples=[\n {\n \"name\": \"Foo\",\n \"description\": \"A very nice Item\",\n \"price\": 35.4,\n \"tax\": 3.2,\n },\n {\n ", "suffix": "e\": \"Bar\",\n \"price\": \"35.4\",\n },\n {\n \"name\": \"Baz\",\n \"price\": \"thirty five point four\",\n },\n ],\n ),\n):\n results = {\"item_id\": item_id, \"item\": item}\n return resul", "middle": " \"nam", "meta": {"filepath": "docs_src/schema_extra_example/tutorial004_py310.py", "language": "python", "file_size": 786, "cut_index": 513, "middle_length": 14}} {"prefix": "or\nfrom fastapi.responses import PlainTextResponse\nfrom starlette.exceptions import HTTPException as StarletteHTTPException\n\napp = FastAPI()\n\n\n@app.exception_handler(StarletteHTTPException)\nasync def http_exception_handler(request, exc):\n return PlainTextResponse(str(exc.detail), status_code=exc.status_code)\n\n\n@app.exception_handler(RequestValidationError)\nasync def validation_exception_handler(request, exc: RequestValidationError):\n message = \"Validation errors:\"\n for error in exc.errors():\n ", "suffix": "r['msg']}\"\n return PlainTextResponse(message, status_code=400)\n\n\n@app.get(\"/items/{item_id}\")\nasync def read_item(item_id: int):\n if item_id == 3:\n raise HTTPException(status_code=418, detail=\"Nope! I don't like 3.\")\n return {\"item_id\": ite", "middle": " message += f\"\\nField: {error['loc']}, Error: {erro", "meta": {"filepath": "docs_src/handling_errors/tutorial004_py310.py", "language": "python", "file_size": 920, "cut_index": 606, "middle_length": 52}} {"prefix": "t yaml\nfrom fastapi import FastAPI, HTTPException, Request\nfrom pydantic import BaseModel, ValidationError\n\napp = FastAPI()\n\n\nclass Item(BaseModel):\n name: str\n tags: list[str]\n\n\n@app.post(\n \"/items/\",\n openapi_extra={\n \"requestBody\": {\n \"content\": {\"application/x-yaml\": {\"schema\": Item.model_json_schema()}},\n \"required\": True,\n },\n },\n)\nasync def create_item(request: Request):\n raw_body = await request.body()\n try:\n data = yaml.safe_load(raw_b", "suffix": "t yaml.YAMLError:\n raise HTTPException(status_code=422, detail=\"Invalid YAML\")\n try:\n item = Item.model_validate(data)\n except ValidationError as e:\n raise HTTPException(status_code=422, detail=e.errors(include_url=False))\n re", "middle": "ody)\n excep", "meta": {"filepath": "docs_src/path_operation_advanced_configuration/tutorial007_py310.py", "language": "python", "file_size": 797, "cut_index": 517, "middle_length": 14}} {"prefix": "import gzip\nfrom collections.abc import Callable\nfrom typing import Annotated\n\nfrom fastapi import Body, FastAPI, Request, Response\nfrom fastapi.routing import APIRoute\n\n\nclass GzipRequest(Request):\n async def body(self) -> bytes:\n if not hasattr(self, \"_body\"):\n body = await super().body()\n if \"gzip\" in self.headers.getlist(\"Content-Encoding\"):\n body = gzip.decompress(body)\n self._body = body\n return self._body\n\n\nclass GzipRoute(APIRoute):\n ", "suffix": "st.receive)\n return await original_route_handler(request)\n\n return custom_route_handler\n\n\napp = FastAPI()\napp.router.route_class = GzipRoute\n\n\n@app.post(\"/sum\")\nasync def sum_numbers(numbers: Annotated[list[int], Body()]):\n return {\"su", "middle": " def get_route_handler(self) -> Callable:\n original_route_handler = super().get_route_handler()\n\n async def custom_route_handler(request: Request) -> Response:\n request = GzipRequest(request.scope, reque", "meta": {"filepath": "docs_src/custom_request_and_route/tutorial001_an_py310.py", "language": "python", "file_size": 1015, "cut_index": 512, "middle_length": 229}} {"prefix": "m fastapi import Body, FastAPI, HTTPException, Request, Response\nfrom fastapi.exceptions import RequestValidationError\nfrom fastapi.routing import APIRoute\n\n\nclass ValidationErrorLoggingRoute(APIRoute):\n def get_route_handler(self) -> Callable:\n original_route_handler = super().get_route_handler()\n\n async def custom_route_handler(request: Request) -> Response:\n try:\n return await original_route_handler(request)\n except RequestValidationError as exc:\n ", "suffix": " detail = {\"errors\": exc.errors(), \"body\": body.decode()}\n raise HTTPException(status_code=422, detail=detail)\n\n return custom_route_handler\n\n\napp = FastAPI()\napp.router.route_class = ValidationErrorLoggingRoute\n\n\n@app.post(\"/\")\nas", "middle": " body = await request.body()\n ", "meta": {"filepath": "docs_src/custom_request_and_route/tutorial002_an_py310.py", "language": "python", "file_size": 974, "cut_index": 582, "middle_length": 52}} {"prefix": "mport time\nfrom collections.abc import Callable\n\nfrom fastapi import APIRouter, FastAPI, Request, Response\nfrom fastapi.routing import APIRoute\n\n\nclass TimedRoute(APIRoute):\n def get_route_handler(self) -> Callable:\n original_route_handler = super().get_route_handler()\n\n async def custom_route_handler(request: Request) -> Response:\n before = time.time()\n response: Response = await original_route_handler(request)\n duration = time.time() - before\n r", "suffix": "urn response\n\n return custom_route_handler\n\n\napp = FastAPI()\nrouter = APIRouter(route_class=TimedRoute)\n\n\n@app.get(\"/\")\nasync def not_timed():\n return {\"message\": \"Not timed\"}\n\n\n@router.get(\"/timed\")\nasync def timed():\n return {\"message\": \"It'", "middle": "esponse.headers[\"X-Response-Time\"] = str(duration)\n print(f\"route duration: {duration}\")\n print(f\"route response: {response}\")\n print(f\"route response headers: {response.headers}\")\n ret", "meta": {"filepath": "docs_src/custom_request_and_route/tutorial003_py310.py", "language": "python", "file_size": 1051, "cut_index": 513, "middle_length": 229}} {"prefix": " import BaseModel\n\napp = FastAPI()\n\n\nclass Item(BaseModel):\n name: str\n description: str | None\n\n\nitems = [\n Item(name=\"Plumbus\", description=\"A multi-purpose household device.\"),\n Item(name=\"Portal Gun\", description=\"A portal opening device.\"),\n Item(name=\"Meeseeks Box\", description=\"A box that summons a Meeseeks.\"),\n]\n\n\n@app.get(\"/items/stream\")\nasync def stream_items() -> AsyncIterable[Item]:\n for item in items:\n yield item\n\n\n@app.get(\"/items/stream-no-async\")\ndef stream_items_no", "suffix": " yield item\n\n\n@app.get(\"/items/stream-no-annotation\")\nasync def stream_items_no_annotation():\n for item in items:\n yield item\n\n\n@app.get(\"/items/stream-no-async-no-annotation\")\ndef stream_items_no_async_no_annotation():\n for item in item", "middle": "_async() -> Iterable[Item]:\n for item in items:\n ", "meta": {"filepath": "docs_src/stream_json_lines/tutorial001_py310.py", "language": "python", "file_size": 936, "cut_index": 606, "middle_length": 52}} {"prefix": "t, Response\nfrom fastapi.exceptions import RequestValidationError\nfrom fastapi.routing import APIRoute\n\n\nclass ValidationErrorLoggingRoute(APIRoute):\n def get_route_handler(self) -> Callable:\n original_route_handler = super().get_route_handler()\n\n async def custom_route_handler(request: Request) -> Response:\n try:\n return await original_route_handler(request)\n except RequestValidationError as exc:\n body = await request.body()\n ", "suffix": "code()}\n raise HTTPException(status_code=422, detail=detail)\n\n return custom_route_handler\n\n\napp = FastAPI()\napp.router.route_class = ValidationErrorLoggingRoute\n\n\n@app.post(\"/\")\nasync def sum_numbers(numbers: list[int] = Body()):\n ", "middle": " detail = {\"errors\": exc.errors(), \"body\": body.de", "meta": {"filepath": "docs_src/custom_request_and_route/tutorial002_py310.py", "language": "python", "file_size": 935, "cut_index": 606, "middle_length": 52}} {"prefix": "rom fastapi import FastAPI, Request\n\napp = FastAPI()\n\n\ndef magic_data_reader(raw_body: bytes):\n return {\n \"size\": len(raw_body),\n \"content\": {\n \"name\": \"Maaaagic\",\n \"price\": 42,\n \"description\": \"Just kiddin', no magic here. ✨\",\n },\n }\n\n\n@app.post(\n \"/items/\",\n openapi_extra={\n \"requestBody\": {\n \"content\": {\n \"application/json\": {\n \"schema\": {\n \"required\": [\"name\", \"pri", "suffix": "\"description\": {\"type\": \"string\"},\n },\n }\n }\n },\n \"required\": True,\n },\n },\n)\nasync def create_item(request: Request):\n raw_body = await request.body()\n data = m", "middle": "ce\"],\n \"type\": \"object\",\n \"properties\": {\n \"name\": {\"type\": \"string\"},\n \"price\": {\"type\": \"number\"},\n ", "meta": {"filepath": "docs_src/path_operation_advanced_configuration/tutorial006_py310.py", "language": "python", "file_size": 1043, "cut_index": 513, "middle_length": 229}} {"prefix": "rom fastapi import FastAPI, File, UploadFile\nfrom fastapi.responses import HTMLResponse\n\napp = FastAPI()\n\n\n@app.post(\"/files/\")\nasync def create_files(files: list[bytes] = File()):\n return {\"file_sizes\": [len(file) for file in files]}\n\n\n@app.post(\"/uploadfiles/\")\nasync def create_upload_files(files: list[UploadFile]):\n return {\"filenames\": [file.filename for file in files]}\n\n\n@app.get(\"/\")\nasync def main():\n content = \"\"\"\n\n
\n\n\n\n
\n\n\n
\n\n \"\"\"\n return HTMLResponse(content=conten", "middle": "nput name=\"fil", "meta": {"filepath": "docs_src/request_files/tutorial002_py310.py", "language": "python", "file_size": 786, "cut_index": 513, "middle_length": 14}} {"prefix": "UploadFile\nfrom fastapi.responses import HTMLResponse\n\napp = FastAPI()\n\n\n@app.post(\"/files/\")\nasync def create_files(\n files: list[bytes] = File(description=\"Multiple files as bytes\"),\n):\n return {\"file_sizes\": [len(file) for file in files]}\n\n\n@app.post(\"/uploadfiles/\")\nasync def create_upload_files(\n files: list[UploadFile] = File(description=\"Multiple files as UploadFile\"),\n):\n return {\"filenames\": [file.filename for file in files]}\n\n\n@app.get(\"/\")\nasync def main():\n content = \"\"\"\n\n\n\n\n\n
\n\n\n
\n\n \"\"\"\n retu", "middle": "orm action=\"/files/\" enctype=\"multipart/form-data\" m", "meta": {"filepath": "docs_src/request_files/tutorial003_py310.py", "language": "python", "file_size": 888, "cut_index": 547, "middle_length": 52}} {"prefix": "Body, FastAPI, Request, Response\nfrom fastapi.routing import APIRoute\n\n\nclass GzipRequest(Request):\n async def body(self) -> bytes:\n if not hasattr(self, \"_body\"):\n body = await super().body()\n if \"gzip\" in self.headers.getlist(\"Content-Encoding\"):\n body = gzip.decompress(body)\n self._body = body\n return self._body\n\n\nclass GzipRoute(APIRoute):\n def get_route_handler(self) -> Callable:\n original_route_handler = super().get_route_handl", "suffix": ": Request) -> Response:\n request = GzipRequest(request.scope, request.receive)\n return await original_route_handler(request)\n\n return custom_route_handler\n\n\napp = FastAPI()\napp.router.route_class = GzipRoute\n\n\n@app.post(\"/sum\")", "middle": "er()\n\n async def custom_route_handler(request", "meta": {"filepath": "docs_src/custom_request_and_route/tutorial001_py310.py", "language": "python", "file_size": 976, "cut_index": 582, "middle_length": 52}} {"prefix": "ions.abc import AsyncIterable\nfrom typing import Annotated\n\nfrom fastapi import FastAPI, Header\nfrom fastapi.sse import EventSourceResponse, ServerSentEvent\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\n\nclass Item(BaseModel):\n name: str\n price: float\n\n\nitems = [\n Item(name=\"Plumbus\", price=32.99),\n Item(name=\"Portal Gun\", price=999.99),\n Item(name=\"Meeseeks Box\", price=49.99),\n]\n\n\n@app.get(\"/items/stream\", response_class=EventSourceResponse)\nasync def stream_items(\n last_event_id: Anno", "suffix": "ne, Header()] = None,\n) -> AsyncIterable[ServerSentEvent]:\n start = last_event_id + 1 if last_event_id is not None else 0\n for i, item in enumerate(items):\n if i < start:\n continue\n yield ServerSentEvent(data=item, id=str(i))", "middle": "tated[int | No", "meta": {"filepath": "docs_src/server_sent_events/tutorial004_py310.py", "language": "python", "file_size": 795, "cut_index": 524, "middle_length": 14}} {"prefix": "dFile\nfrom fastapi.responses import HTMLResponse\n\napp = FastAPI()\n\n\n@app.post(\"/files/\")\nasync def create_files(\n files: Annotated[list[bytes], File(description=\"Multiple files as bytes\")],\n):\n return {\"file_sizes\": [len(file) for file in files]}\n\n\n@app.post(\"/uploadfiles/\")\nasync def create_upload_files(\n files: Annotated[\n list[UploadFile], File(description=\"Multiple files as UploadFile\")\n ],\n):\n return {\"filenames\": [file.filename for file in files]}\n\n\n@app.get(\"/\")\nasync def main()", "suffix": "ctype=\"multipart/form-data\" method=\"post\">\n\n\n\n
\n\n\n\n\n\n\n
\n
\n\n\n
\n\n \"\"\"\n return HTMLResponse(content=content)", "middle": "ltipart/form-data\" method=\"post\">\n Hero:\n session.add(hero)\n session.commit()\n session.refresh(hero)\n return hero\n\n\n@app.get", "middle": "nnect_args)\n\n\ndef create_db_and_tables():\n SQLModel.metadata.create_all(engine)\n\n\ndef get_session():\n with Session(engine) as session:\n yield session\n\n\nSessionDep = Annotated[Session, Depends(get_session)]\n\napp = Fas", "meta": {"filepath": "docs_src/sql_databases/tutorial001_an_py310.py", "language": "python", "file_size": 1768, "cut_index": 537, "middle_length": 229}} {"prefix": "FastAPI framework, high performance, easy to learn, fast to code, ready for production\"\"\"\n\n__version__ = \"0.136.3\"\n\nfrom starlette import status as status\n\nfrom .applications import FastAPI as FastAPI\nfrom .background import BackgroundTasks as BackgroundTasks\nfrom .datastructures import UploadFile as UploadFile\nfrom .exceptions import HTTPException as HTTPException\nfrom .exceptions import WebSocketException as WebSocketException\nfrom .param_functions import Body as Body\nfrom .param_functions import Cookie a", "suffix": "from .param_functions import Query as Query\nfrom .param_functions import Security as Security\nfrom .requests import Request as Request\nfrom .responses import Response as Response\nfrom .routing import APIRouter as APIRouter\nfrom .websockets import WebSocket", "middle": "s Cookie\nfrom .param_functions import Depends as Depends\nfrom .param_functions import File as File\nfrom .param_functions import Form as Form\nfrom .param_functions import Header as Header\nfrom .param_functions import Path as Path\n", "meta": {"filepath": "fastapi/__init__.py", "language": "python", "file_size": 1081, "cut_index": 515, "middle_length": 229}} {"prefix": "vent schema matching the OpenAPI 3.2 spec\n# (Section 4.14.4 \"Special Considerations for Server-Sent Events\")\n_SSE_EVENT_SCHEMA: dict[str, Any] = {\n \"type\": \"object\",\n \"properties\": {\n \"data\": {\"type\": \"string\"},\n \"event\": {\"type\": \"string\"},\n \"id\": {\"type\": \"string\"},\n \"retry\": {\"type\": \"integer\", \"minimum\": 0},\n },\n}\n\n\nclass EventSourceResponse(StreamingResponse):\n \"\"\"Streaming response with `text/event-stream` media type.\n\n Use as `response_class=EventSourceRespo", "suffix": "`POST`.\n\n The actual encoding logic lives in the FastAPI routing layer. This class\n serves mainly as a marker and sets the correct `Content-Type`.\n \"\"\"\n\n media_type = \"text/event-stream\"\n\n\ndef _check_single_line(v: str | None, field_name: str) ", "middle": "nse` on a *path operation* that uses `yield`\n to enable Server Sent Events (SSE) responses.\n\n Works with **any HTTP method** (`GET`, `POST`, etc.), which makes it compatible\n with protocols like MCP that stream SSE over ", "meta": {"filepath": "fastapi/sse.py", "language": "python", "file_size": 6848, "cut_index": 716, "middle_length": 229}} {"prefix": "shot\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\n\nclass Items(BaseModel):\n items: dict[str, int]\n\n\n@app.post(\"/foo\")\ndef foo(items: Items):\n return items.items\n\n\nclient = TestClient(app)\n\n\ndef test_additional_properties_post():\n response = client.post(\"/foo\", json={\"items\": {\"foo\": 1, \"bar\": 2}})\n assert response.status_code == 200, response.text\n assert response.json() == {\"foo\": 1, \"bar\": 2}\n\n\ndef test_openapi_schema():\n response = client.get(\"/openapi.json\")\n assert response.sta", "suffix": " \"post\": {\n \"responses\": {\n \"200\": {\n \"description\": \"Successful Response\",\n \"content\": {\"application/json\": {\"schema\": {}}},\n ", "middle": "tus_code == 200, response.text\n assert response.json() == snapshot(\n {\n \"openapi\": \"3.1.0\",\n \"info\": {\"title\": \"FastAPI\", \"version\": \"0.1.0\"},\n \"paths\": {\n \"/foo\": {\n ", "meta": {"filepath": "tests/test_additional_properties.py", "language": "python", "file_size": 4238, "cut_index": 614, "middle_length": 229}} {"prefix": "ontextlib import asynccontextmanager\n\nfrom fastapi import FastAPI\nfrom fastapi.testclient import TestClient\n\nitems = {}\n\n\n@asynccontextmanager\nasync def lifespan(app: FastAPI):\n items[\"foo\"] = {\"name\": \"Fighters\"}\n items[\"bar\"] = {\"name\": \"Tenders\"}\n yield\n # clean up items\n items.clear()\n\n\napp = FastAPI(lifespan=lifespan)\n\n\n@app.get(\"/items/{item_id}\")\nasync def read_items(item_id: str):\n return items[item_id]\n\n\ndef test_read_items():\n # Before the lifespan starts, \"items\" is still emp", "suffix": " response = client.get(\"/items/foo\")\n assert response.status_code == 200\n assert response.json() == {\"name\": \"Fighters\"}\n\n # After the requests is done, the items are still there\n assert items == {\"foo\": {\"name\": \"Fighters", "middle": "ty\n assert items == {}\n\n with TestClient(app) as client:\n # Inside the \"with TestClient\" block, the lifespan starts and items added\n assert items == {\"foo\": {\"name\": \"Fighters\"}, \"bar\": {\"name\": \"Tenders\"}}\n\n ", "meta": {"filepath": "docs_src/app_testing/tutorial004_py310.py", "language": "python", "file_size": 1187, "cut_index": 518, "middle_length": 229}} {"prefix": "mport TestClient\n\nfrom .main import app\n\nclient = TestClient(app)\n\n\ndef test_read_item():\n response = client.get(\"/items/foo\", headers={\"X-Token\": \"coneofsilence\"})\n assert response.status_code == 200\n assert response.json() == {\n \"id\": \"foo\",\n \"title\": \"Foo\",\n \"description\": \"There goes my hero\",\n }\n\n\ndef test_read_item_bad_token():\n response = client.get(\"/items/foo\", headers={\"X-Token\": \"hailhydra\"})\n assert response.status_code == 400\n assert response.json() == ", "suffix": ": \"Item not found\"}\n\n\ndef test_create_item():\n response = client.post(\n \"/items/\",\n headers={\"X-Token\": \"coneofsilence\"},\n json={\"id\": \"foobar\", \"title\": \"Foo Bar\", \"description\": \"The Foo Barters\"},\n )\n assert response.status", "middle": "{\"detail\": \"Invalid X-Token header\"}\n\n\ndef test_read_nonexistent_item():\n response = client.get(\"/items/baz\", headers={\"X-Token\": \"coneofsilence\"})\n assert response.status_code == 404\n assert response.json() == {\"detail\"", "meta": {"filepath": "docs_src/app_testing/app_b_py310/test_main.py", "language": "python", "file_size": 1866, "cut_index": 537, "middle_length": 229}} {"prefix": "yping import Annotated\n\nfrom fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel\n\nfake_secret_token = \"coneofsilence\"\n\nfake_db = {\n \"foo\": {\"id\": \"foo\", \"title\": \"Foo\", \"description\": \"There goes my hero\"},\n \"bar\": {\"id\": \"bar\", \"title\": \"Bar\", \"description\": \"The bartenders\"},\n}\n\napp = FastAPI()\n\n\nclass Item(BaseModel):\n id: str\n title: str\n description: str | None = None\n\n\n@app.get(\"/items/{item_id}\", response_model=Item)\nasync def read_main(item_id: str, x_token: A", "suffix": " not found\")\n return fake_db[item_id]\n\n\n@app.post(\"/items/\")\nasync def create_item(item: Item, x_token: Annotated[str, Header()]) -> Item:\n if x_token != fake_secret_token:\n raise HTTPException(status_code=400, detail=\"Invalid X-Token header\")", "middle": "nnotated[str, Header()]):\n if x_token != fake_secret_token:\n raise HTTPException(status_code=400, detail=\"Invalid X-Token header\")\n if item_id not in fake_db:\n raise HTTPException(status_code=404, detail=\"Item", "meta": {"filepath": "docs_src/app_testing/app_b_an_py310/main.py", "language": "python", "file_size": 1163, "cut_index": 518, "middle_length": 229}} {"prefix": "astapi import FastAPI\nfrom fastapi.openapi.docs import (\n get_redoc_html,\n get_swagger_ui_html,\n get_swagger_ui_oauth2_redirect_html,\n)\n\napp = FastAPI(docs_url=None, redoc_url=None)\n\n\n@app.get(\"/docs\", include_in_schema=False)\nasync def custom_swagger_ui_html():\n return get_swagger_ui_html(\n openapi_url=app.openapi_url,\n title=app.title + \" - Swagger UI\",\n oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url,\n swagger_js_url=\"https://unpkg.com/swagger-ui-dist@5/swag", "suffix": "r_ui_oauth2_redirect_html()\n\n\n@app.get(\"/redoc\", include_in_schema=False)\nasync def redoc_html():\n return get_redoc_html(\n openapi_url=app.openapi_url,\n title=app.title + \" - ReDoc\",\n redoc_js_url=\"https://unpkg.com/redoc@2/bundles/", "middle": "ger-ui-bundle.js\",\n swagger_css_url=\"https://unpkg.com/swagger-ui-dist@5/swagger-ui.css\",\n )\n\n\n@app.get(app.swagger_ui_oauth2_redirect_url, include_in_schema=False)\nasync def swagger_ui_redirect():\n return get_swagge", "meta": {"filepath": "docs_src/custom_docs_ui/tutorial001_py310.py", "language": "python", "file_size": 1143, "cut_index": 518, "middle_length": 229}} {"prefix": "m fastapi import FastAPI, Header, HTTPException\nfrom pydantic import BaseModel\n\nfake_secret_token = \"coneofsilence\"\n\nfake_db = {\n \"foo\": {\"id\": \"foo\", \"title\": \"Foo\", \"description\": \"There goes my hero\"},\n \"bar\": {\"id\": \"bar\", \"title\": \"Bar\", \"description\": \"The bartenders\"},\n}\n\napp = FastAPI()\n\n\nclass Item(BaseModel):\n id: str\n title: str\n description: str | None = None\n\n\n@app.get(\"/items/{item_id}\", response_model=Item)\nasync def read_main(item_id: str, x_token: str = Header()):\n if x_to", "suffix": "id]\n\n\n@app.post(\"/items/\")\nasync def create_item(item: Item, x_token: str = Header()) -> Item:\n if x_token != fake_secret_token:\n raise HTTPException(status_code=400, detail=\"Invalid X-Token header\")\n if item.id in fake_db:\n raise HTTPE", "middle": "ken != fake_secret_token:\n raise HTTPException(status_code=400, detail=\"Invalid X-Token header\")\n if item_id not in fake_db:\n raise HTTPException(status_code=404, detail=\"Item not found\")\n return fake_db[item_", "meta": {"filepath": "docs_src/app_testing/app_b_py310/main.py", "language": "python", "file_size": 1113, "cut_index": 515, "middle_length": 229}} {"prefix": "mport TestClient\n\nfrom .main import app\n\nclient = TestClient(app)\n\n\ndef test_read_item():\n response = client.get(\"/items/foo\", headers={\"X-Token\": \"coneofsilence\"})\n assert response.status_code == 200\n assert response.json() == {\n \"id\": \"foo\",\n \"title\": \"Foo\",\n \"description\": \"There goes my hero\",\n }\n\n\ndef test_read_item_bad_token():\n response = client.get(\"/items/foo\", headers={\"X-Token\": \"hailhydra\"})\n assert response.status_code == 400\n assert response.json() == ", "suffix": ": \"Item not found\"}\n\n\ndef test_create_item():\n response = client.post(\n \"/items/\",\n headers={\"X-Token\": \"coneofsilence\"},\n json={\"id\": \"foobar\", \"title\": \"Foo Bar\", \"description\": \"The Foo Barters\"},\n )\n assert response.status", "middle": "{\"detail\": \"Invalid X-Token header\"}\n\n\ndef test_read_nonexistent_item():\n response = client.get(\"/items/baz\", headers={\"X-Token\": \"coneofsilence\"})\n assert response.status_code == 404\n assert response.json() == {\"detail\"", "meta": {"filepath": "docs_src/app_testing/app_b_an_py310/test_main.py", "language": "python", "file_size": 1866, "cut_index": 537, "middle_length": 229}} {"prefix": "fastapi import FastAPI\n\ndescription = \"\"\"\nChimichangApp API helps you do awesome stuff. 🚀\n\n## Items\n\nYou can **read items**.\n\n## Users\n\nYou will be able to:\n\n* **Create users** (_not implemented_).\n* **Read users** (_not implemented_).\n\"\"\"\n\napp = FastAPI(\n title=\"ChimichangApp\",\n description=description,\n summary=\"Deadpool's favorite app. Nuff said.\",\n version=\"0.0.1\",\n terms_of_service=\"http://example.com/terms/\",\n contact={\n \"name\": \"Deadpoolio the Amazing\",\n \"url\": \"http:/", "suffix": "le.com/contact/\",\n \"email\": \"dp@x-force.example.com\",\n },\n license_info={\n \"name\": \"Apache 2.0\",\n \"url\": \"https://www.apache.org/licenses/LICENSE-2.0.html\",\n },\n)\n\n\n@app.get(\"/items/\")\nasync def read_items():\n return [{\"nam", "middle": "/x-force.examp", "meta": {"filepath": "docs_src/metadata/tutorial001_py310.py", "language": "python", "file_size": 805, "cut_index": 517, "middle_length": 14}} {"prefix": "pi import FastAPI\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\n\nclass Item(BaseModel):\n name: str\n description: str | None = None\n price: float\n tax: float = 10.5\n\n\nitems = {\n \"foo\": {\"name\": \"Foo\", \"price\": 50.2},\n \"bar\": {\"name\": \"Bar\", \"description\": \"The Bar fighters\", \"price\": 62, \"tax\": 20.2},\n \"baz\": {\n \"name\": \"Baz\",\n \"description\": \"There goes my baz\",\n \"price\": 50.2,\n \"tax\": 10.5,\n },\n}\n\n\n@app.get(\n \"/items/{item_id}/name\",\n response_mo", "suffix": "response_model_include=[\"name\", \"description\"],\n)\nasync def read_item_name(item_id: str):\n return items[item_id]\n\n\n@app.get(\"/items/{item_id}/public\", response_model=Item, response_model_exclude=[\"tax\"])\nasync def read_item_public_data(item_id: str):\n ", "middle": "del=Item,\n ", "meta": {"filepath": "docs_src/response_model/tutorial006_py310.py", "language": "python", "file_size": 816, "cut_index": 522, "middle_length": 14}} {"prefix": "l\n\n\ndef custom_generate_unique_id(route: APIRoute):\n return f\"{route.tags[0]}-{route.name}\"\n\n\napp = FastAPI(generate_unique_id_function=custom_generate_unique_id)\n\n\nclass Item(BaseModel):\n name: str\n price: float\n\n\nclass ResponseMessage(BaseModel):\n message: str\n\n\nclass User(BaseModel):\n username: str\n email: str\n\n\n@app.post(\"/items/\", response_model=ResponseMessage, tags=[\"items\"])\nasync def create_item(item: Item):\n return {\"message\": \"Item received\"}\n\n\n@app.get(\"/items/\", response_mo", "suffix": "):\n return [\n {\"name\": \"Plumbus\", \"price\": 3},\n {\"name\": \"Portal Gun\", \"price\": 9001},\n ]\n\n\n@app.post(\"/users/\", response_model=ResponseMessage, tags=[\"users\"])\nasync def create_user(user: User):\n return {\"message\": \"User received\"}\n", "middle": "del=list[Item], tags=[\"items\"])\nasync def get_items(", "meta": {"filepath": "docs_src/generate_clients/tutorial003_py310.py", "language": "python", "file_size": 914, "cut_index": 606, "middle_length": 52}} {"prefix": "from fastapi import APIRouter, Depends, HTTPException\n\nfrom ..dependencies import get_token_header\n\nrouter = APIRouter(\n prefix=\"/items\",\n tags=[\"items\"],\n dependencies=[Depends(get_token_header)],\n responses={404: {\"description\": \"Not found\"}},\n)\n\n\nfake_items_db = {\"plumbus\": {\"name\": \"Plumbus\"}, \"gun\": {\"name\": \"Portal Gun\"}}\n\n\n@router.get(\"/\")\nasync def read_items():\n return fake_items_db\n\n\n@router.get(\"/{item_id}\")\nasync def read_item(item_id: str):\n if item_id not in fake_items_db:\n ", "suffix": " \"Operation forbidden\"}},\n)\nasync def update_item(item_id: str):\n if item_id != \"plumbus\":\n raise HTTPException(\n status_code=403, detail=\"You can only update the item: plumbus\"\n )\n return {\"item_id\": item_id, \"name\": \"The gr", "middle": " raise HTTPException(status_code=404, detail=\"Item not found\")\n return {\"name\": fake_items_db[item_id][\"name\"], \"item_id\": item_id}\n\n\n@router.put(\n \"/{item_id}\",\n tags=[\"custom\"],\n responses={403: {\"description\":", "meta": {"filepath": "docs_src/bigger_applications/app_an_py310/routers/items.py", "language": "python", "file_size": 1011, "cut_index": 512, "middle_length": 229}} {"prefix": "dantic import BaseModel, EmailStr\n\napp = FastAPI()\n\n\nclass UserIn(BaseModel):\n username: str\n password: str\n email: EmailStr\n full_name: str | None = None\n\n\nclass UserOut(BaseModel):\n username: str\n email: EmailStr\n full_name: str | None = None\n\n\nclass UserInDB(BaseModel):\n username: str\n hashed_password: str\n email: EmailStr\n full_name: str | None = None\n\n\ndef fake_password_hasher(raw_password: str):\n return \"supersecret\" + raw_password\n\n\ndef fake_save_user(user_in: User", "suffix": "_in.password)\n user_in_db = UserInDB(**user_in.model_dump(), hashed_password=hashed_password)\n print(\"User saved! ..not really\")\n return user_in_db\n\n\n@app.post(\"/user/\", response_model=UserOut)\nasync def create_user(user_in: UserIn):\n user_save", "middle": "In):\n hashed_password = fake_password_hasher(user", "meta": {"filepath": "docs_src/extra_models/tutorial001_py310.py", "language": "python", "file_size": 905, "cut_index": 547, "middle_length": 52}} {"prefix": "fastapi import FastAPI\nfrom pydantic import BaseModel, EmailStr\n\napp = FastAPI()\n\n\nclass UserBase(BaseModel):\n username: str\n email: EmailStr\n full_name: str | None = None\n\n\nclass UserIn(UserBase):\n password: str\n\n\nclass UserOut(UserBase):\n pass\n\n\nclass UserInDB(UserBase):\n hashed_password: str\n\n\ndef fake_password_hasher(raw_password: str):\n return \"supersecret\" + raw_password\n\n\ndef fake_save_user(user_in: UserIn):\n hashed_password = fake_password_hasher(user_in.password)\n user_in", "suffix": "(**user_in.model_dump(), hashed_password=hashed_password)\n print(\"User saved! ..not really\")\n return user_in_db\n\n\n@app.post(\"/user/\", response_model=UserOut)\nasync def create_user(user_in: UserIn):\n user_saved = fake_save_user(user_in)\n return ", "middle": "_db = UserInDB", "meta": {"filepath": "docs_src/extra_models/tutorial002_py310.py", "language": "python", "file_size": 798, "cut_index": 517, "middle_length": 14}} {"prefix": "FastAPI,\n Query,\n WebSocket,\n WebSocketException,\n status,\n)\nfrom fastapi.responses import HTMLResponse\n\napp = FastAPI()\n\nhtml = \"\"\"\n\n\n \n Chat\n \n \n

WebSocket Chat

\n
\n \n